@enclave-hq/wallet-sdk 1.2.3 → 1.2.4
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/README.md +51 -1
- package/dist/index.d.mts +413 -10
- package/dist/index.d.ts +413 -10
- package/dist/index.js +3492 -107
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3454 -76
- package/dist/index.mjs.map +1 -1
- package/dist/react/index.d.mts +88 -9
- package/dist/react/index.d.ts +88 -9
- package/dist/react/index.js +3341 -79
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +3315 -57
- package/dist/react/index.mjs.map +1 -1
- package/package.json +7 -2
package/dist/index.js
CHANGED
|
@@ -2,16 +2,606 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var EventEmitter = require('eventemitter3');
|
|
6
5
|
var chainUtils = require('@enclave-hq/chain-utils');
|
|
6
|
+
var EventEmitter = require('eventemitter3');
|
|
7
7
|
var viem = require('viem');
|
|
8
8
|
var accounts = require('viem/accounts');
|
|
9
|
+
var EthereumProvider = require('@walletconnect/ethereum-provider');
|
|
10
|
+
var walletconnectTron = require('@tronweb3/walletconnect-tron');
|
|
11
|
+
var QRCode = require('qrcode');
|
|
9
12
|
|
|
10
13
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
11
14
|
|
|
12
15
|
var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
|
|
16
|
+
var EthereumProvider__default = /*#__PURE__*/_interopDefault(EthereumProvider);
|
|
17
|
+
var QRCode__default = /*#__PURE__*/_interopDefault(QRCode);
|
|
18
|
+
|
|
19
|
+
var __defProp = Object.defineProperty;
|
|
20
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
21
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
22
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
23
|
+
var __esm = (fn, res) => function __init() {
|
|
24
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
25
|
+
};
|
|
26
|
+
var __export = (target, all) => {
|
|
27
|
+
for (var name in all)
|
|
28
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
29
|
+
};
|
|
30
|
+
var __copyProps = (to, from, except, desc) => {
|
|
31
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
32
|
+
for (let key of __getOwnPropNames(from))
|
|
33
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
34
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
35
|
+
}
|
|
36
|
+
return to;
|
|
37
|
+
};
|
|
38
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
39
|
+
exports.ChainType = void 0; exports.WalletType = void 0; exports.WalletState = void 0;
|
|
40
|
+
var init_types = __esm({
|
|
41
|
+
"src/core/types.ts"() {
|
|
42
|
+
exports.ChainType = chainUtils.ChainType;
|
|
43
|
+
exports.WalletType = /* @__PURE__ */ ((WalletType3) => {
|
|
44
|
+
WalletType3["METAMASK"] = "metamask";
|
|
45
|
+
WalletType3["WALLETCONNECT"] = "walletconnect";
|
|
46
|
+
WalletType3["COINBASE_WALLET"] = "coinbase-wallet";
|
|
47
|
+
WalletType3["TRONLINK"] = "tronlink";
|
|
48
|
+
WalletType3["WALLETCONNECT_TRON"] = "walletconnect-tron";
|
|
49
|
+
WalletType3["PRIVATE_KEY"] = "private-key";
|
|
50
|
+
WalletType3["DEEP_LINK_EVM"] = "deep-link-evm";
|
|
51
|
+
WalletType3["DEEP_LINK_TRON"] = "deep-link-tron";
|
|
52
|
+
return WalletType3;
|
|
53
|
+
})(exports.WalletType || {});
|
|
54
|
+
exports.WalletState = /* @__PURE__ */ ((WalletState2) => {
|
|
55
|
+
WalletState2["DISCONNECTED"] = "disconnected";
|
|
56
|
+
WalletState2["CONNECTING"] = "connecting";
|
|
57
|
+
WalletState2["CONNECTED"] = "connected";
|
|
58
|
+
WalletState2["ERROR"] = "error";
|
|
59
|
+
return WalletState2;
|
|
60
|
+
})(exports.WalletState || {});
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// src/adapters/deep-link/providers/tokenpocket.ts
|
|
65
|
+
var tokenpocket_exports = {};
|
|
66
|
+
__export(tokenpocket_exports, {
|
|
67
|
+
TokenPocketDeepLinkProvider: () => exports.TokenPocketDeepLinkProvider
|
|
68
|
+
});
|
|
69
|
+
exports.TokenPocketDeepLinkProvider = void 0;
|
|
70
|
+
var init_tokenpocket = __esm({
|
|
71
|
+
"src/adapters/deep-link/providers/tokenpocket.ts"() {
|
|
72
|
+
init_types();
|
|
73
|
+
exports.TokenPocketDeepLinkProvider = class {
|
|
74
|
+
constructor(options) {
|
|
75
|
+
this.name = "TokenPocket";
|
|
76
|
+
this.icon = "https://tokenpocket.pro/icon.png";
|
|
77
|
+
this.supportedChainTypes = [exports.ChainType.EVM, exports.ChainType.TRON];
|
|
78
|
+
this.callbackUrl = options?.callbackUrl;
|
|
79
|
+
this.callbackSchema = options?.callbackSchema;
|
|
80
|
+
}
|
|
81
|
+
async isAvailable() {
|
|
82
|
+
if (typeof window === "undefined") {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
const isTelegramMiniApp = !!(window.Telegram && window.Telegram.WebApp);
|
|
86
|
+
if (isTelegramMiniApp) {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
90
|
+
navigator.userAgent
|
|
91
|
+
);
|
|
92
|
+
return isMobile;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Generate unique actionId
|
|
96
|
+
*/
|
|
97
|
+
generateActionId() {
|
|
98
|
+
return `web-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Get callback configuration
|
|
102
|
+
*/
|
|
103
|
+
getCallbackConfig() {
|
|
104
|
+
if (this.callbackSchema) {
|
|
105
|
+
return { callbackSchema: this.callbackSchema };
|
|
106
|
+
}
|
|
107
|
+
if (this.callbackUrl) {
|
|
108
|
+
return { callbackUrl: this.callbackUrl };
|
|
109
|
+
}
|
|
110
|
+
if (typeof window !== "undefined" && window.location) {
|
|
111
|
+
return {
|
|
112
|
+
callbackSchema: `${window.location.protocol}//${window.location.host}${window.location.pathname}`
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
return {};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Get blockchain configuration based on chain type
|
|
119
|
+
*/
|
|
120
|
+
getBlockchainConfig(chainId, chainType) {
|
|
121
|
+
if (chainType === exports.ChainType.TRON) {
|
|
122
|
+
return {
|
|
123
|
+
chainId: String(chainId),
|
|
124
|
+
network: "tron"
|
|
125
|
+
};
|
|
126
|
+
} else if (chainType === exports.ChainType.EVM) {
|
|
127
|
+
return {
|
|
128
|
+
chainId: String(chainId),
|
|
129
|
+
network: "ethereum"
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
throw new Error(`Unsupported chain type: ${chainType}`);
|
|
133
|
+
}
|
|
134
|
+
buildSignMessageLink(params) {
|
|
135
|
+
const actionId = this.generateActionId();
|
|
136
|
+
const callback = this.getCallbackConfig();
|
|
137
|
+
const blockchain = this.getBlockchainConfig(params.chainId, params.chainType);
|
|
138
|
+
const param = {
|
|
139
|
+
action: "sign",
|
|
140
|
+
actionId,
|
|
141
|
+
message: params.message,
|
|
142
|
+
hash: false,
|
|
143
|
+
signType: params.chainType === exports.ChainType.TRON ? "ethPersonalSign" : "ethPersonalSign",
|
|
144
|
+
memo: `${params.chainType} message signature`,
|
|
145
|
+
blockchains: [blockchain],
|
|
146
|
+
dappName: "Enclave Wallet SDK",
|
|
147
|
+
dappIcon: "https://walletconnect.com/walletconnect-logo.svg",
|
|
148
|
+
protocol: "TokenPocket",
|
|
149
|
+
version: "1.1.8",
|
|
150
|
+
expired: 0,
|
|
151
|
+
...callback
|
|
152
|
+
};
|
|
153
|
+
const encodedParam = encodeURIComponent(JSON.stringify(param));
|
|
154
|
+
const url = `tpoutside://pull.activity?param=${encodedParam}`;
|
|
155
|
+
return {
|
|
156
|
+
url,
|
|
157
|
+
actionId,
|
|
158
|
+
...callback
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
buildSignTransactionLink(params) {
|
|
162
|
+
const actionId = this.generateActionId();
|
|
163
|
+
const callback = this.getCallbackConfig();
|
|
164
|
+
const blockchain = this.getBlockchainConfig(params.chainId, params.chainType);
|
|
165
|
+
let transactionData;
|
|
166
|
+
if (typeof params.transaction === "string") {
|
|
167
|
+
transactionData = params.transaction;
|
|
168
|
+
} else {
|
|
169
|
+
transactionData = JSON.stringify(params.transaction);
|
|
170
|
+
}
|
|
171
|
+
const param = {
|
|
172
|
+
action: "pushTransaction",
|
|
173
|
+
actionId,
|
|
174
|
+
txData: transactionData,
|
|
175
|
+
blockchains: [blockchain],
|
|
176
|
+
dappName: "Enclave Wallet SDK",
|
|
177
|
+
dappIcon: "https://walletconnect.com/walletconnect-logo.svg",
|
|
178
|
+
protocol: "TokenPocket",
|
|
179
|
+
version: "1.1.8",
|
|
180
|
+
expired: 0,
|
|
181
|
+
...callback
|
|
182
|
+
};
|
|
183
|
+
const encodedParam = encodeURIComponent(JSON.stringify(param));
|
|
184
|
+
const url = `tpoutside://pull.activity?param=${encodedParam}`;
|
|
185
|
+
return {
|
|
186
|
+
url,
|
|
187
|
+
actionId,
|
|
188
|
+
...callback
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
buildConnectLink(params) {
|
|
192
|
+
const actionId = this.generateActionId();
|
|
193
|
+
const blockchain = this.getBlockchainConfig(params.chainId, params.chainType);
|
|
194
|
+
const param = {
|
|
195
|
+
action: "login",
|
|
196
|
+
actionId,
|
|
197
|
+
blockchains: [blockchain],
|
|
198
|
+
dappName: "Enclave Wallet SDK",
|
|
199
|
+
dappIcon: "https://walletconnect.com/walletconnect-logo.svg",
|
|
200
|
+
protocol: "TokenPocket",
|
|
201
|
+
version: "1.0",
|
|
202
|
+
expired: 1602
|
|
203
|
+
// 30 minutes
|
|
204
|
+
};
|
|
205
|
+
const encodedParam = encodeURIComponent(JSON.stringify(param));
|
|
206
|
+
const url = `tpoutside://pull.activity?param=${encodedParam}`;
|
|
207
|
+
return {
|
|
208
|
+
url,
|
|
209
|
+
actionId
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
parseCallbackResult(urlParams) {
|
|
213
|
+
const actionId = urlParams.get("actionId");
|
|
214
|
+
const resultParam = urlParams.get("result");
|
|
215
|
+
const error = urlParams.get("error");
|
|
216
|
+
let result = null;
|
|
217
|
+
if (resultParam) {
|
|
218
|
+
try {
|
|
219
|
+
result = JSON.parse(decodeURIComponent(resultParam));
|
|
220
|
+
} catch (e) {
|
|
221
|
+
result = resultParam;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
actionId,
|
|
226
|
+
result,
|
|
227
|
+
error
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
getDefaultCallbackSchema() {
|
|
231
|
+
if (typeof window !== "undefined" && window.location) {
|
|
232
|
+
return `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
|
|
233
|
+
}
|
|
234
|
+
return "";
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
// src/adapters/deep-link/providers/tronlink.ts
|
|
241
|
+
var tronlink_exports = {};
|
|
242
|
+
__export(tronlink_exports, {
|
|
243
|
+
TronLinkDeepLinkProvider: () => exports.TronLinkDeepLinkProvider
|
|
244
|
+
});
|
|
245
|
+
exports.TronLinkDeepLinkProvider = void 0;
|
|
246
|
+
var init_tronlink = __esm({
|
|
247
|
+
"src/adapters/deep-link/providers/tronlink.ts"() {
|
|
248
|
+
init_types();
|
|
249
|
+
exports.TronLinkDeepLinkProvider = class {
|
|
250
|
+
constructor() {
|
|
251
|
+
this.name = "TronLink";
|
|
252
|
+
this.icon = "https://www.tronlink.org/static/logoIcon.svg";
|
|
253
|
+
this.supportedChainTypes = [exports.ChainType.TRON];
|
|
254
|
+
}
|
|
255
|
+
async isAvailable() {
|
|
256
|
+
if (typeof window === "undefined") {
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
const isTelegramMiniApp = !!(window.Telegram && window.Telegram.WebApp);
|
|
260
|
+
if (isTelegramMiniApp) {
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
264
|
+
navigator.userAgent
|
|
265
|
+
);
|
|
266
|
+
return isMobile;
|
|
267
|
+
}
|
|
268
|
+
buildSignMessageLink(params) {
|
|
269
|
+
if (params.chainType !== exports.ChainType.TRON) {
|
|
270
|
+
throw new Error("TronLink only supports TRON chain");
|
|
271
|
+
}
|
|
272
|
+
const encodedMessage = encodeURIComponent(params.message);
|
|
273
|
+
const url = `tronlink://signMessage?message=${encodedMessage}`;
|
|
274
|
+
const actionId = `tronlink-${Date.now()}`;
|
|
275
|
+
return {
|
|
276
|
+
url,
|
|
277
|
+
actionId
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
buildSignTransactionLink(params) {
|
|
281
|
+
if (params.chainType !== exports.ChainType.TRON) {
|
|
282
|
+
throw new Error("TronLink only supports TRON chain");
|
|
283
|
+
}
|
|
284
|
+
const transactionData = typeof params.transaction === "string" ? params.transaction : JSON.stringify(params.transaction);
|
|
285
|
+
const encodedData = encodeURIComponent(transactionData);
|
|
286
|
+
const url = `tronlink://signTransaction?transaction=${encodedData}`;
|
|
287
|
+
const actionId = `tronlink-${Date.now()}`;
|
|
288
|
+
return {
|
|
289
|
+
url,
|
|
290
|
+
actionId
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
buildConnectLink(params) {
|
|
294
|
+
if (params.chainType !== exports.ChainType.TRON) {
|
|
295
|
+
throw new Error("TronLink only supports TRON chain");
|
|
296
|
+
}
|
|
297
|
+
const url = `tronlink://open?action=connect&network=tron`;
|
|
298
|
+
return {
|
|
299
|
+
url
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
parseCallbackResult(_urlParams) {
|
|
303
|
+
return {
|
|
304
|
+
actionId: null,
|
|
305
|
+
result: null,
|
|
306
|
+
error: null
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// src/adapters/deep-link/providers/imtoken.ts
|
|
314
|
+
var imtoken_exports = {};
|
|
315
|
+
__export(imtoken_exports, {
|
|
316
|
+
ImTokenDeepLinkProvider: () => exports.ImTokenDeepLinkProvider
|
|
317
|
+
});
|
|
318
|
+
exports.ImTokenDeepLinkProvider = void 0;
|
|
319
|
+
var init_imtoken = __esm({
|
|
320
|
+
"src/adapters/deep-link/providers/imtoken.ts"() {
|
|
321
|
+
init_types();
|
|
322
|
+
exports.ImTokenDeepLinkProvider = class {
|
|
323
|
+
constructor(options) {
|
|
324
|
+
this.name = "ImToken";
|
|
325
|
+
this.icon = "https://token.im/static/img/logo.png";
|
|
326
|
+
this.supportedChainTypes = [exports.ChainType.EVM, exports.ChainType.TRON];
|
|
327
|
+
this.callbackUrl = options?.callbackUrl;
|
|
328
|
+
this.callbackSchema = options?.callbackSchema;
|
|
329
|
+
}
|
|
330
|
+
async isAvailable() {
|
|
331
|
+
if (typeof window === "undefined") {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
const isTelegramMiniApp = !!(window.Telegram && window.Telegram.WebApp);
|
|
335
|
+
if (isTelegramMiniApp) {
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
339
|
+
navigator.userAgent
|
|
340
|
+
);
|
|
341
|
+
return isMobile;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Generate unique actionId
|
|
345
|
+
*/
|
|
346
|
+
generateActionId() {
|
|
347
|
+
return `imtoken-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Get callback configuration
|
|
351
|
+
*/
|
|
352
|
+
getCallbackConfig() {
|
|
353
|
+
if (this.callbackSchema) {
|
|
354
|
+
return { callbackSchema: this.callbackSchema };
|
|
355
|
+
}
|
|
356
|
+
if (this.callbackUrl) {
|
|
357
|
+
return { callbackUrl: this.callbackUrl };
|
|
358
|
+
}
|
|
359
|
+
if (typeof window !== "undefined" && window.location) {
|
|
360
|
+
return {
|
|
361
|
+
callbackSchema: `${window.location.protocol}//${window.location.host}${window.location.pathname}`
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
return {};
|
|
365
|
+
}
|
|
366
|
+
buildSignMessageLink(params) {
|
|
367
|
+
const actionId = this.generateActionId();
|
|
368
|
+
const callback = this.getCallbackConfig();
|
|
369
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=signMessage&message=${encodeURIComponent(params.message)}&chainId=${params.chainId}`;
|
|
370
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
371
|
+
const url = `imtokenv2://navigate/DappView?url=${encodedDappUrl}`;
|
|
372
|
+
return {
|
|
373
|
+
url,
|
|
374
|
+
actionId,
|
|
375
|
+
...callback
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
buildSignTransactionLink(params) {
|
|
379
|
+
const actionId = this.generateActionId();
|
|
380
|
+
const callback = this.getCallbackConfig();
|
|
381
|
+
const transactionData = typeof params.transaction === "string" ? params.transaction : JSON.stringify(params.transaction);
|
|
382
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=signTransaction&transaction=${encodeURIComponent(transactionData)}&chainId=${params.chainId}`;
|
|
383
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
384
|
+
const url = `imtokenv2://navigate/DappView?url=${encodedDappUrl}`;
|
|
385
|
+
return {
|
|
386
|
+
url,
|
|
387
|
+
actionId,
|
|
388
|
+
...callback
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
buildConnectLink(params) {
|
|
392
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=connect&chainId=${params.chainId}`;
|
|
393
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
394
|
+
const url = `imtokenv2://navigate/DappView?url=${encodedDappUrl}`;
|
|
395
|
+
return {
|
|
396
|
+
url
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
parseCallbackResult(urlParams) {
|
|
400
|
+
const actionId = urlParams.get("actionId");
|
|
401
|
+
const resultParam = urlParams.get("result");
|
|
402
|
+
const error = urlParams.get("error");
|
|
403
|
+
let result = null;
|
|
404
|
+
if (resultParam) {
|
|
405
|
+
try {
|
|
406
|
+
result = JSON.parse(decodeURIComponent(resultParam));
|
|
407
|
+
} catch (e) {
|
|
408
|
+
result = resultParam;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return {
|
|
412
|
+
actionId,
|
|
413
|
+
result,
|
|
414
|
+
error
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
getDefaultCallbackSchema() {
|
|
418
|
+
if (typeof window !== "undefined" && window.location) {
|
|
419
|
+
return `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
|
|
420
|
+
}
|
|
421
|
+
return "";
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
// src/adapters/deep-link/providers/metamask.ts
|
|
428
|
+
var metamask_exports = {};
|
|
429
|
+
__export(metamask_exports, {
|
|
430
|
+
MetaMaskDeepLinkProvider: () => exports.MetaMaskDeepLinkProvider
|
|
431
|
+
});
|
|
432
|
+
exports.MetaMaskDeepLinkProvider = void 0;
|
|
433
|
+
var init_metamask = __esm({
|
|
434
|
+
"src/adapters/deep-link/providers/metamask.ts"() {
|
|
435
|
+
init_types();
|
|
436
|
+
exports.MetaMaskDeepLinkProvider = class {
|
|
437
|
+
constructor() {
|
|
438
|
+
this.name = "MetaMask";
|
|
439
|
+
this.icon = "https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg";
|
|
440
|
+
this.supportedChainTypes = [exports.ChainType.EVM];
|
|
441
|
+
}
|
|
442
|
+
async isAvailable() {
|
|
443
|
+
if (typeof window === "undefined") {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
const isTelegramMiniApp = !!(window.Telegram && window.Telegram.WebApp);
|
|
447
|
+
if (isTelegramMiniApp) {
|
|
448
|
+
return true;
|
|
449
|
+
}
|
|
450
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
451
|
+
navigator.userAgent
|
|
452
|
+
);
|
|
453
|
+
return isMobile;
|
|
454
|
+
}
|
|
455
|
+
buildSignMessageLink(params) {
|
|
456
|
+
if (params.chainType !== exports.ChainType.EVM) {
|
|
457
|
+
throw new Error("MetaMask only supports EVM chains");
|
|
458
|
+
}
|
|
459
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=signMessage&message=${encodeURIComponent(params.message)}&chainId=${params.chainId}`;
|
|
460
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
461
|
+
const url = `https://link.metamask.io/dapp/${encodedDappUrl}`;
|
|
462
|
+
const actionId = `metamask-${Date.now()}`;
|
|
463
|
+
return {
|
|
464
|
+
url,
|
|
465
|
+
actionId
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
buildSignTransactionLink(params) {
|
|
469
|
+
if (params.chainType !== exports.ChainType.EVM) {
|
|
470
|
+
throw new Error("MetaMask only supports EVM chains");
|
|
471
|
+
}
|
|
472
|
+
const transactionData = typeof params.transaction === "string" ? params.transaction : JSON.stringify(params.transaction);
|
|
473
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=signTransaction&transaction=${encodeURIComponent(transactionData)}&chainId=${params.chainId}`;
|
|
474
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
475
|
+
const url = `https://link.metamask.io/dapp/${encodedDappUrl}`;
|
|
476
|
+
const actionId = `metamask-${Date.now()}`;
|
|
477
|
+
return {
|
|
478
|
+
url,
|
|
479
|
+
actionId
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
buildConnectLink(params) {
|
|
483
|
+
if (params.chainType !== exports.ChainType.EVM) {
|
|
484
|
+
throw new Error("MetaMask only supports EVM chains");
|
|
485
|
+
}
|
|
486
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=connect&chainId=${params.chainId}`;
|
|
487
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
488
|
+
const url = `https://link.metamask.io/dapp/${encodedDappUrl}`;
|
|
489
|
+
return {
|
|
490
|
+
url
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
parseCallbackResult(urlParams) {
|
|
494
|
+
const actionId = urlParams.get("actionId");
|
|
495
|
+
const resultParam = urlParams.get("result");
|
|
496
|
+
const error = urlParams.get("error");
|
|
497
|
+
let result = null;
|
|
498
|
+
if (resultParam) {
|
|
499
|
+
try {
|
|
500
|
+
result = JSON.parse(decodeURIComponent(resultParam));
|
|
501
|
+
} catch (e) {
|
|
502
|
+
result = resultParam;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
return {
|
|
506
|
+
actionId,
|
|
507
|
+
result,
|
|
508
|
+
error
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
getDefaultCallbackSchema() {
|
|
512
|
+
if (typeof window !== "undefined" && window.location) {
|
|
513
|
+
return `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
|
|
514
|
+
}
|
|
515
|
+
return "";
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
});
|
|
13
520
|
|
|
14
|
-
// src/
|
|
521
|
+
// src/adapters/deep-link/providers/okx.ts
|
|
522
|
+
var okx_exports = {};
|
|
523
|
+
__export(okx_exports, {
|
|
524
|
+
OKXDeepLinkProvider: () => exports.OKXDeepLinkProvider
|
|
525
|
+
});
|
|
526
|
+
exports.OKXDeepLinkProvider = void 0;
|
|
527
|
+
var init_okx = __esm({
|
|
528
|
+
"src/adapters/deep-link/providers/okx.ts"() {
|
|
529
|
+
init_types();
|
|
530
|
+
exports.OKXDeepLinkProvider = class {
|
|
531
|
+
constructor() {
|
|
532
|
+
this.name = "OKX";
|
|
533
|
+
this.icon = "https://www.okx.com/favicon.ico";
|
|
534
|
+
this.supportedChainTypes = [exports.ChainType.EVM, exports.ChainType.TRON];
|
|
535
|
+
}
|
|
536
|
+
async isAvailable() {
|
|
537
|
+
if (typeof window === "undefined") {
|
|
538
|
+
return false;
|
|
539
|
+
}
|
|
540
|
+
const isTelegramMiniApp = !!(window.Telegram && window.Telegram.WebApp);
|
|
541
|
+
if (isTelegramMiniApp) {
|
|
542
|
+
return true;
|
|
543
|
+
}
|
|
544
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
545
|
+
navigator.userAgent
|
|
546
|
+
);
|
|
547
|
+
return isMobile;
|
|
548
|
+
}
|
|
549
|
+
buildSignMessageLink(params) {
|
|
550
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=signMessage&message=${encodeURIComponent(params.message)}&chainId=${params.chainId}`;
|
|
551
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
552
|
+
const url = `okx://wallet/dapp/url?dappUrl=${encodedDappUrl}`;
|
|
553
|
+
const actionId = `okx-${Date.now()}`;
|
|
554
|
+
return {
|
|
555
|
+
url,
|
|
556
|
+
actionId
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
buildSignTransactionLink(params) {
|
|
560
|
+
const transactionData = typeof params.transaction === "string" ? params.transaction : JSON.stringify(params.transaction);
|
|
561
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=signTransaction&transaction=${encodeURIComponent(transactionData)}&chainId=${params.chainId}`;
|
|
562
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
563
|
+
const url = `okx://wallet/dapp/url?dappUrl=${encodedDappUrl}`;
|
|
564
|
+
const actionId = `okx-${Date.now()}`;
|
|
565
|
+
return {
|
|
566
|
+
url,
|
|
567
|
+
actionId
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
buildConnectLink(params) {
|
|
571
|
+
const dappUrl = `${window.location.origin}${window.location.pathname}?action=connect&chainId=${params.chainId}`;
|
|
572
|
+
const encodedDappUrl = encodeURIComponent(dappUrl);
|
|
573
|
+
const url = `okx://wallet/dapp/url?dappUrl=${encodedDappUrl}`;
|
|
574
|
+
return {
|
|
575
|
+
url
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
parseCallbackResult(urlParams) {
|
|
579
|
+
const actionId = urlParams.get("actionId");
|
|
580
|
+
const resultParam = urlParams.get("result");
|
|
581
|
+
const error = urlParams.get("error");
|
|
582
|
+
let result = null;
|
|
583
|
+
if (resultParam) {
|
|
584
|
+
try {
|
|
585
|
+
result = JSON.parse(decodeURIComponent(resultParam));
|
|
586
|
+
} catch (e) {
|
|
587
|
+
result = resultParam;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return {
|
|
591
|
+
actionId,
|
|
592
|
+
result,
|
|
593
|
+
error
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
getDefaultCallbackSchema() {
|
|
597
|
+
if (typeof window !== "undefined" && window.location) {
|
|
598
|
+
return `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
|
|
599
|
+
}
|
|
600
|
+
return "";
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
});
|
|
15
605
|
var TypedEventEmitter = class {
|
|
16
606
|
constructor() {
|
|
17
607
|
this.emitter = new EventEmitter__default.default();
|
|
@@ -40,23 +630,12 @@ var TypedEventEmitter = class {
|
|
|
40
630
|
return this;
|
|
41
631
|
}
|
|
42
632
|
};
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
WalletType3["WALLETCONNECT_TRON"] = "walletconnect-tron";
|
|
50
|
-
WalletType3["PRIVATE_KEY"] = "private-key";
|
|
51
|
-
return WalletType3;
|
|
52
|
-
})(WalletType || {});
|
|
53
|
-
var WalletState = /* @__PURE__ */ ((WalletState2) => {
|
|
54
|
-
WalletState2["DISCONNECTED"] = "disconnected";
|
|
55
|
-
WalletState2["CONNECTING"] = "connecting";
|
|
56
|
-
WalletState2["CONNECTED"] = "connected";
|
|
57
|
-
WalletState2["ERROR"] = "error";
|
|
58
|
-
return WalletState2;
|
|
59
|
-
})(WalletState || {});
|
|
633
|
+
|
|
634
|
+
// src/core/adapter-registry.ts
|
|
635
|
+
init_types();
|
|
636
|
+
|
|
637
|
+
// src/adapters/base/wallet-adapter.ts
|
|
638
|
+
init_types();
|
|
60
639
|
|
|
61
640
|
// src/core/errors.ts
|
|
62
641
|
var WalletSDKError = class _WalletSDKError extends Error {
|
|
@@ -158,6 +737,13 @@ var WalletAdapter = class extends EventEmitter__default.default {
|
|
|
158
737
|
this.state = "disconnected" /* DISCONNECTED */;
|
|
159
738
|
this.currentAccount = null;
|
|
160
739
|
}
|
|
740
|
+
/**
|
|
741
|
+
* Check if the wallet is currently connected
|
|
742
|
+
* @returns true if the wallet is connected (state is CONNECTED and has an account)
|
|
743
|
+
*/
|
|
744
|
+
isConnected() {
|
|
745
|
+
return this.state === "connected" /* CONNECTED */ && this.currentAccount !== null;
|
|
746
|
+
}
|
|
161
747
|
/**
|
|
162
748
|
* Get the signer's address (implements ISigner interface)
|
|
163
749
|
* Returns the native address of the current account
|
|
@@ -227,6 +813,7 @@ var WalletAdapter = class extends EventEmitter__default.default {
|
|
|
227
813
|
};
|
|
228
814
|
|
|
229
815
|
// src/adapters/base/browser-wallet-adapter.ts
|
|
816
|
+
init_types();
|
|
230
817
|
var BrowserWalletAdapter = class extends WalletAdapter {
|
|
231
818
|
/**
|
|
232
819
|
* 检查钱包是否可用
|
|
@@ -260,6 +847,9 @@ var BrowserWalletAdapter = class extends WalletAdapter {
|
|
|
260
847
|
}
|
|
261
848
|
};
|
|
262
849
|
|
|
850
|
+
// src/adapters/evm/metamask.ts
|
|
851
|
+
init_types();
|
|
852
|
+
|
|
263
853
|
// src/utils/address/universal-address.ts
|
|
264
854
|
function createUniversalAddress(chainId, address) {
|
|
265
855
|
return `${chainId}:${address}`;
|
|
@@ -495,7 +1085,7 @@ var MetaMaskAdapter = class extends BrowserWalletAdapter {
|
|
|
495
1085
|
constructor() {
|
|
496
1086
|
super(...arguments);
|
|
497
1087
|
this.type = "metamask" /* METAMASK */;
|
|
498
|
-
this.chainType = ChainType.EVM;
|
|
1088
|
+
this.chainType = exports.ChainType.EVM;
|
|
499
1089
|
this.name = "MetaMask";
|
|
500
1090
|
this.icon = "https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg";
|
|
501
1091
|
this.walletClient = null;
|
|
@@ -522,7 +1112,7 @@ var MetaMaskAdapter = class extends BrowserWalletAdapter {
|
|
|
522
1112
|
universalAddress: createUniversalAddress(this.currentAccount.chainId, address),
|
|
523
1113
|
nativeAddress: address,
|
|
524
1114
|
chainId: this.currentAccount.chainId,
|
|
525
|
-
chainType: ChainType.EVM,
|
|
1115
|
+
chainType: exports.ChainType.EVM,
|
|
526
1116
|
isActive: true
|
|
527
1117
|
};
|
|
528
1118
|
this.setAccount(account);
|
|
@@ -558,6 +1148,7 @@ var MetaMaskAdapter = class extends BrowserWalletAdapter {
|
|
|
558
1148
|
*/
|
|
559
1149
|
async connect(chainId) {
|
|
560
1150
|
await this.ensureAvailable();
|
|
1151
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] : chainId;
|
|
561
1152
|
try {
|
|
562
1153
|
this.setState("connecting" /* CONNECTING */);
|
|
563
1154
|
const provider = this.getBrowserProvider();
|
|
@@ -571,10 +1162,10 @@ var MetaMaskAdapter = class extends BrowserWalletAdapter {
|
|
|
571
1162
|
method: "eth_chainId"
|
|
572
1163
|
});
|
|
573
1164
|
const parsedChainId = parseInt(currentChainId, 16);
|
|
574
|
-
if (
|
|
575
|
-
await this.switchChain(
|
|
1165
|
+
if (targetChainId && targetChainId !== parsedChainId) {
|
|
1166
|
+
await this.switchChain(targetChainId);
|
|
576
1167
|
}
|
|
577
|
-
const finalChainId =
|
|
1168
|
+
const finalChainId = targetChainId || parsedChainId;
|
|
578
1169
|
const viemChain = this.getViemChain(finalChainId);
|
|
579
1170
|
this.walletClient = viem.createWalletClient({
|
|
580
1171
|
account: accounts[0],
|
|
@@ -593,7 +1184,7 @@ var MetaMaskAdapter = class extends BrowserWalletAdapter {
|
|
|
593
1184
|
universalAddress: createUniversalAddress(finalChainId, address),
|
|
594
1185
|
nativeAddress: address,
|
|
595
1186
|
chainId: finalChainId,
|
|
596
|
-
chainType: ChainType.EVM,
|
|
1187
|
+
chainType: exports.ChainType.EVM,
|
|
597
1188
|
isActive: true
|
|
598
1189
|
};
|
|
599
1190
|
this.setState("connected" /* CONNECTED */);
|
|
@@ -960,11 +1551,12 @@ var MetaMaskAdapter = class extends BrowserWalletAdapter {
|
|
|
960
1551
|
};
|
|
961
1552
|
|
|
962
1553
|
// src/adapters/tron/tronlink.ts
|
|
1554
|
+
init_types();
|
|
963
1555
|
var _TronLinkAdapter = class _TronLinkAdapter extends BrowserWalletAdapter {
|
|
964
1556
|
constructor() {
|
|
965
1557
|
super(...arguments);
|
|
966
1558
|
this.type = "tronlink" /* TRONLINK */;
|
|
967
|
-
this.chainType = ChainType.TRON;
|
|
1559
|
+
this.chainType = exports.ChainType.TRON;
|
|
968
1560
|
this.name = "TronWeb";
|
|
969
1561
|
this.icon = "https://www.tronlink.org/static/logoIcon.svg";
|
|
970
1562
|
/**
|
|
@@ -986,7 +1578,7 @@ var _TronLinkAdapter = class _TronLinkAdapter extends BrowserWalletAdapter {
|
|
|
986
1578
|
universalAddress: createUniversalAddress(this.currentAccount.chainId, address),
|
|
987
1579
|
nativeAddress: address,
|
|
988
1580
|
chainId: this.currentAccount.chainId,
|
|
989
|
-
chainType: ChainType.TRON,
|
|
1581
|
+
chainType: exports.ChainType.TRON,
|
|
990
1582
|
isActive: true
|
|
991
1583
|
};
|
|
992
1584
|
this.setAccount(account);
|
|
@@ -1007,6 +1599,7 @@ var _TronLinkAdapter = class _TronLinkAdapter extends BrowserWalletAdapter {
|
|
|
1007
1599
|
*/
|
|
1008
1600
|
async connect(chainId) {
|
|
1009
1601
|
await this.ensureAvailable();
|
|
1602
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] : chainId;
|
|
1010
1603
|
try {
|
|
1011
1604
|
this.setState("connecting" /* CONNECTING */);
|
|
1012
1605
|
const w = window;
|
|
@@ -1061,12 +1654,12 @@ var _TronLinkAdapter = class _TronLinkAdapter extends BrowserWalletAdapter {
|
|
|
1061
1654
|
if (!address) {
|
|
1062
1655
|
throw new Error("Failed to get Tron address. Please make sure your wallet is unlocked and try again.");
|
|
1063
1656
|
}
|
|
1064
|
-
const tronChainId =
|
|
1657
|
+
const tronChainId = targetChainId || _TronLinkAdapter.TRON_MAINNET_CHAIN_ID;
|
|
1065
1658
|
const account = {
|
|
1066
1659
|
universalAddress: createUniversalAddress(tronChainId, address),
|
|
1067
1660
|
nativeAddress: address,
|
|
1068
1661
|
chainId: tronChainId,
|
|
1069
|
-
chainType: ChainType.TRON,
|
|
1662
|
+
chainType: exports.ChainType.TRON,
|
|
1070
1663
|
isActive: true
|
|
1071
1664
|
};
|
|
1072
1665
|
this.setState("connected" /* CONNECTED */);
|
|
@@ -1391,11 +1984,12 @@ var _TronLinkAdapter = class _TronLinkAdapter extends BrowserWalletAdapter {
|
|
|
1391
1984
|
// Tron 主网链 ID
|
|
1392
1985
|
_TronLinkAdapter.TRON_MAINNET_CHAIN_ID = 195;
|
|
1393
1986
|
var TronLinkAdapter = _TronLinkAdapter;
|
|
1987
|
+
init_types();
|
|
1394
1988
|
var EVMPrivateKeyAdapter = class extends WalletAdapter {
|
|
1395
1989
|
constructor() {
|
|
1396
1990
|
super(...arguments);
|
|
1397
1991
|
this.type = "private-key" /* PRIVATE_KEY */;
|
|
1398
|
-
this.chainType = ChainType.EVM;
|
|
1992
|
+
this.chainType = exports.ChainType.EVM;
|
|
1399
1993
|
this.name = "Private Key (EVM)";
|
|
1400
1994
|
this.privateKey = null;
|
|
1401
1995
|
this.walletClient = null;
|
|
@@ -1404,28 +1998,29 @@ var EVMPrivateKeyAdapter = class extends WalletAdapter {
|
|
|
1404
1998
|
/**
|
|
1405
1999
|
* 连接(导入私钥)
|
|
1406
2000
|
*/
|
|
1407
|
-
async connect(chainId
|
|
2001
|
+
async connect(chainId) {
|
|
1408
2002
|
if (!this.privateKey) {
|
|
1409
2003
|
throw new Error("Private key not set. Call setPrivateKey() first.");
|
|
1410
2004
|
}
|
|
1411
2005
|
try {
|
|
1412
2006
|
this.setState("connecting" /* CONNECTING */);
|
|
1413
2007
|
const account = accounts.privateKeyToAccount(this.privateKey);
|
|
2008
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] : chainId || 1;
|
|
1414
2009
|
this.walletClient = viem.createWalletClient({
|
|
1415
2010
|
account,
|
|
1416
|
-
chain: this.getViemChain(
|
|
2011
|
+
chain: this.getViemChain(targetChainId),
|
|
1417
2012
|
transport: viem.http()
|
|
1418
2013
|
});
|
|
1419
2014
|
this.publicClient = viem.createPublicClient({
|
|
1420
|
-
chain: this.getViemChain(
|
|
2015
|
+
chain: this.getViemChain(targetChainId),
|
|
1421
2016
|
transport: viem.http()
|
|
1422
2017
|
});
|
|
1423
2018
|
const address = formatEVMAddress(account.address);
|
|
1424
2019
|
const accountInfo = {
|
|
1425
|
-
universalAddress: createUniversalAddress(
|
|
2020
|
+
universalAddress: createUniversalAddress(targetChainId, address),
|
|
1426
2021
|
nativeAddress: address,
|
|
1427
|
-
chainId,
|
|
1428
|
-
chainType: ChainType.EVM,
|
|
2022
|
+
chainId: targetChainId,
|
|
2023
|
+
chainType: exports.ChainType.EVM,
|
|
1429
2024
|
isActive: true
|
|
1430
2025
|
};
|
|
1431
2026
|
this.setState("connected" /* CONNECTED */);
|
|
@@ -1636,68 +2231,2314 @@ var EVMPrivateKeyAdapter = class extends WalletAdapter {
|
|
|
1636
2231
|
};
|
|
1637
2232
|
}
|
|
1638
2233
|
};
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
this.
|
|
1644
|
-
this.
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
this.
|
|
1651
|
-
|
|
1652
|
-
|
|
2234
|
+
init_types();
|
|
2235
|
+
var _WalletConnectAdapter = class _WalletConnectAdapter extends WalletAdapter {
|
|
2236
|
+
constructor(projectId) {
|
|
2237
|
+
super();
|
|
2238
|
+
this.type = "walletconnect" /* WALLETCONNECT */;
|
|
2239
|
+
this.chainType = exports.ChainType.EVM;
|
|
2240
|
+
this.name = "WalletConnect";
|
|
2241
|
+
this.icon = "https://avatars.githubusercontent.com/u/37784886";
|
|
2242
|
+
this.provider = null;
|
|
2243
|
+
this.walletClient = null;
|
|
2244
|
+
this.publicClient = null;
|
|
2245
|
+
this.supportedChains = [];
|
|
2246
|
+
/**
|
|
2247
|
+
* Handle accounts changed
|
|
2248
|
+
*/
|
|
2249
|
+
this.handleAccountsChanged = (accounts) => {
|
|
2250
|
+
if (accounts.length === 0) {
|
|
2251
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
2252
|
+
this.setAccount(null);
|
|
2253
|
+
this.emitAccountChanged(null);
|
|
2254
|
+
} else {
|
|
2255
|
+
const address = formatEVMAddress(accounts[0]);
|
|
2256
|
+
const account = {
|
|
2257
|
+
universalAddress: createUniversalAddress(this.currentAccount.chainId, address),
|
|
2258
|
+
nativeAddress: address,
|
|
2259
|
+
chainId: this.currentAccount.chainId,
|
|
2260
|
+
chainType: exports.ChainType.EVM,
|
|
2261
|
+
isActive: true
|
|
2262
|
+
};
|
|
2263
|
+
this.setAccount(account);
|
|
2264
|
+
this.emitAccountChanged(account);
|
|
2265
|
+
}
|
|
2266
|
+
};
|
|
2267
|
+
/**
|
|
2268
|
+
* Handle chain changed
|
|
2269
|
+
*/
|
|
2270
|
+
this.handleChainChanged = (chainIdHex) => {
|
|
2271
|
+
const chainId = parseInt(chainIdHex, 16);
|
|
2272
|
+
if (this.currentAccount) {
|
|
2273
|
+
const account = {
|
|
2274
|
+
...this.currentAccount,
|
|
2275
|
+
chainId,
|
|
2276
|
+
universalAddress: createUniversalAddress(chainId, this.currentAccount.nativeAddress)
|
|
2277
|
+
};
|
|
2278
|
+
this.setAccount(account);
|
|
2279
|
+
this.emitChainChanged(chainId);
|
|
2280
|
+
const viemChain = this.getViemChain(chainId);
|
|
2281
|
+
const chainInfo = getChainInfo(chainId);
|
|
2282
|
+
const primaryRpcUrl = chainInfo?.rpcUrls[0];
|
|
2283
|
+
if (this.provider) {
|
|
2284
|
+
this.walletClient = viem.createWalletClient({
|
|
2285
|
+
account: this.currentAccount.nativeAddress,
|
|
2286
|
+
chain: viemChain,
|
|
2287
|
+
transport: viem.custom(this.provider)
|
|
2288
|
+
});
|
|
2289
|
+
this.publicClient = viem.createPublicClient({
|
|
2290
|
+
chain: viemChain,
|
|
2291
|
+
transport: primaryRpcUrl ? viem.http(primaryRpcUrl) : viem.custom(this.provider)
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
};
|
|
2296
|
+
/**
|
|
2297
|
+
* Handle disconnect
|
|
2298
|
+
*/
|
|
2299
|
+
this.handleDisconnect = () => {
|
|
2300
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
2301
|
+
this.setAccount(null);
|
|
2302
|
+
if (_WalletConnectAdapter.providerInstance === this.provider) {
|
|
2303
|
+
_WalletConnectAdapter.providerInstance = null;
|
|
2304
|
+
_WalletConnectAdapter.providerProjectId = null;
|
|
2305
|
+
}
|
|
2306
|
+
this.provider = null;
|
|
2307
|
+
this.walletClient = null;
|
|
2308
|
+
this.publicClient = null;
|
|
2309
|
+
this.emitDisconnected();
|
|
2310
|
+
};
|
|
2311
|
+
if (!projectId) {
|
|
2312
|
+
throw new ConfigurationError("WalletConnect projectId is required");
|
|
2313
|
+
}
|
|
2314
|
+
this.projectId = projectId;
|
|
1653
2315
|
}
|
|
1654
2316
|
/**
|
|
1655
|
-
*
|
|
2317
|
+
* Check if WalletConnect is available
|
|
2318
|
+
* WalletConnect is always available (it's a web-based connection)
|
|
2319
|
+
* Also works in Telegram Mini Apps
|
|
1656
2320
|
*/
|
|
1657
|
-
|
|
1658
|
-
|
|
2321
|
+
async isAvailable() {
|
|
2322
|
+
return typeof window !== "undefined";
|
|
1659
2323
|
}
|
|
1660
2324
|
/**
|
|
1661
|
-
*
|
|
2325
|
+
* Check if running in Telegram environment (Mini App or Web)
|
|
2326
|
+
* Both Telegram Mini App (in client) and Telegram Web (web.telegram.org)
|
|
2327
|
+
* provide window.Telegram.WebApp API, so they are treated the same way.
|
|
2328
|
+
*
|
|
2329
|
+
* Reference: https://docs.reown.com/appkit/integrations/telegram-mini-apps
|
|
1662
2330
|
*/
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
2331
|
+
isTelegramMiniApp() {
|
|
2332
|
+
if (typeof window === "undefined") return false;
|
|
2333
|
+
const tg = window.Telegram?.WebApp;
|
|
2334
|
+
if (!tg) return false;
|
|
2335
|
+
const platform = tg.platform || "unknown";
|
|
2336
|
+
console.log("[WalletConnect] Telegram environment detected:", {
|
|
2337
|
+
platform,
|
|
2338
|
+
version: tg.version,
|
|
2339
|
+
isMiniApp: platform !== "web",
|
|
2340
|
+
// Mini App if not web platform
|
|
2341
|
+
isWeb: platform === "web"
|
|
2342
|
+
// Telegram Web if web platform
|
|
2343
|
+
});
|
|
2344
|
+
return true;
|
|
1669
2345
|
}
|
|
1670
2346
|
/**
|
|
1671
|
-
*
|
|
2347
|
+
* Get Telegram WebApp instance if available
|
|
1672
2348
|
*/
|
|
1673
|
-
|
|
1674
|
-
|
|
2349
|
+
getTelegramWebApp() {
|
|
2350
|
+
if (typeof window === "undefined") return null;
|
|
2351
|
+
return window.Telegram?.WebApp || null;
|
|
1675
2352
|
}
|
|
1676
2353
|
/**
|
|
1677
|
-
*
|
|
2354
|
+
* Close Telegram deep link popup (wc:// links)
|
|
2355
|
+
* In Telegram Mini Apps, WalletConnect may open a wc:// deep link popup
|
|
2356
|
+
* that doesn't automatically close after the operation completes.
|
|
2357
|
+
* This method attempts to close it by:
|
|
2358
|
+
* 1. Trying to close any open windows/popups
|
|
2359
|
+
* 2. Using Telegram WebApp API if available
|
|
2360
|
+
* 3. Navigating back or closing the popup
|
|
1678
2361
|
*/
|
|
1679
|
-
|
|
1680
|
-
|
|
2362
|
+
closeTelegramDeepLinkPopup() {
|
|
2363
|
+
if (!this.isTelegramMiniApp()) {
|
|
2364
|
+
return;
|
|
2365
|
+
}
|
|
2366
|
+
try {
|
|
2367
|
+
const tg = this.getTelegramWebApp();
|
|
2368
|
+
if (!tg) {
|
|
2369
|
+
return;
|
|
2370
|
+
}
|
|
2371
|
+
if (typeof window !== "undefined") {
|
|
2372
|
+
window.focus();
|
|
2373
|
+
if (tg.BackButton && tg.BackButton.isVisible) {
|
|
2374
|
+
console.log("[WalletConnect] Closing Telegram deep link popup via BackButton");
|
|
2375
|
+
}
|
|
2376
|
+
setTimeout(() => {
|
|
2377
|
+
if (document.hasFocus()) {
|
|
2378
|
+
console.log("[WalletConnect] Main window has focus, popup likely closed");
|
|
2379
|
+
} else {
|
|
2380
|
+
window.focus();
|
|
2381
|
+
console.log("[WalletConnect] Attempted to focus main window to close popup");
|
|
2382
|
+
}
|
|
2383
|
+
}, 500);
|
|
2384
|
+
const handleVisibilityChange = () => {
|
|
2385
|
+
if (document.visibilityState === "visible") {
|
|
2386
|
+
console.log("[WalletConnect] Page became visible, popup may have closed");
|
|
2387
|
+
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
document.addEventListener("visibilitychange", handleVisibilityChange);
|
|
2391
|
+
setTimeout(() => {
|
|
2392
|
+
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
|
2393
|
+
}, 2e3);
|
|
2394
|
+
}
|
|
2395
|
+
} catch (error) {
|
|
2396
|
+
console.warn("[WalletConnect] Error closing Telegram deep link popup:", error);
|
|
2397
|
+
}
|
|
1681
2398
|
}
|
|
1682
2399
|
/**
|
|
1683
|
-
*
|
|
2400
|
+
* Connect wallet
|
|
2401
|
+
*
|
|
2402
|
+
* @param chainId - Single chain ID or array of chain IDs to request
|
|
2403
|
+
* If array is provided, wallet will be requested to connect to multiple chains
|
|
2404
|
+
* When multiple chains are requested, the wallet can switch between them
|
|
2405
|
+
* Default: 1 (Ethereum Mainnet)
|
|
2406
|
+
*
|
|
2407
|
+
* @example
|
|
2408
|
+
* // Single chain
|
|
2409
|
+
* await adapter.connect(1) // Ethereum only
|
|
2410
|
+
*
|
|
2411
|
+
* @example
|
|
2412
|
+
* // Multiple chains
|
|
2413
|
+
* await adapter.connect([1, 56, 137]) // Ethereum, BSC, Polygon
|
|
1684
2414
|
*/
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
const adapter = this.getAdapter(type);
|
|
1689
|
-
if (adapter && adapter.chainType === chainType) {
|
|
1690
|
-
types.push(type);
|
|
1691
|
-
}
|
|
2415
|
+
async connect(chainId) {
|
|
2416
|
+
if (typeof window === "undefined") {
|
|
2417
|
+
throw new Error("WalletConnect requires a browser environment");
|
|
1692
2418
|
}
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
2419
|
+
if (_WalletConnectAdapter.providerInstance && _WalletConnectAdapter.providerProjectId === this.projectId) {
|
|
2420
|
+
const existingProvider = _WalletConnectAdapter.providerInstance;
|
|
2421
|
+
if (existingProvider.accounts && existingProvider.accounts.length > 0) {
|
|
2422
|
+
this.provider = existingProvider;
|
|
2423
|
+
let targetChains;
|
|
2424
|
+
if (Array.isArray(chainId)) {
|
|
2425
|
+
targetChains = chainId.length > 0 ? chainId : [1];
|
|
2426
|
+
} else if (chainId) {
|
|
2427
|
+
targetChains = [chainId];
|
|
2428
|
+
} else {
|
|
2429
|
+
targetChains = [1];
|
|
2430
|
+
}
|
|
2431
|
+
const existingChains = this.supportedChains || [];
|
|
2432
|
+
const mergedChains = [.../* @__PURE__ */ new Set([...existingChains, ...targetChains])];
|
|
2433
|
+
this.supportedChains = mergedChains;
|
|
2434
|
+
const currentChainId = existingProvider.chainId || targetChains[0];
|
|
2435
|
+
const address = formatEVMAddress(existingProvider.accounts[0]);
|
|
2436
|
+
const account = {
|
|
2437
|
+
universalAddress: createUniversalAddress(currentChainId, address),
|
|
2438
|
+
nativeAddress: address,
|
|
2439
|
+
chainId: currentChainId,
|
|
2440
|
+
chainType: exports.ChainType.EVM,
|
|
2441
|
+
isActive: true
|
|
2442
|
+
};
|
|
2443
|
+
this.setState("connected" /* CONNECTED */);
|
|
2444
|
+
this.setAccount(account);
|
|
2445
|
+
if (!this.walletClient) {
|
|
2446
|
+
const viemChain = this.getViemChain(currentChainId);
|
|
2447
|
+
this.walletClient = viem.createWalletClient({
|
|
2448
|
+
account: existingProvider.accounts[0],
|
|
2449
|
+
chain: viemChain,
|
|
2450
|
+
transport: viem.custom(existingProvider)
|
|
2451
|
+
});
|
|
2452
|
+
const chainInfo = getChainInfo(currentChainId);
|
|
2453
|
+
const primaryRpcUrl = chainInfo?.rpcUrls[0];
|
|
2454
|
+
this.publicClient = viem.createPublicClient({
|
|
2455
|
+
chain: viemChain,
|
|
2456
|
+
transport: primaryRpcUrl ? viem.http(primaryRpcUrl) : viem.custom(existingProvider)
|
|
2457
|
+
});
|
|
2458
|
+
this.setupEventListeners();
|
|
2459
|
+
}
|
|
2460
|
+
console.log("[WalletConnect] Reusing existing provider session");
|
|
2461
|
+
return account;
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
if (this.state === "connected" /* CONNECTED */ && this.currentAccount && this.provider) {
|
|
2465
|
+
if (this.provider.accounts && this.provider.accounts.length > 0) {
|
|
2466
|
+
let targetChains;
|
|
2467
|
+
if (Array.isArray(chainId)) {
|
|
2468
|
+
targetChains = chainId.length > 0 ? chainId : [1];
|
|
2469
|
+
} else if (chainId) {
|
|
2470
|
+
targetChains = [chainId];
|
|
2471
|
+
} else {
|
|
2472
|
+
targetChains = [1];
|
|
2473
|
+
}
|
|
2474
|
+
const existingChains = this.supportedChains || [];
|
|
2475
|
+
const mergedChains = [.../* @__PURE__ */ new Set([...existingChains, ...targetChains])];
|
|
2476
|
+
this.supportedChains = mergedChains;
|
|
2477
|
+
console.log("[WalletConnect] Already connected, reusing existing connection");
|
|
2478
|
+
return this.currentAccount;
|
|
2479
|
+
} else {
|
|
2480
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
2481
|
+
this.setAccount(null);
|
|
2482
|
+
this.provider = null;
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
try {
|
|
2486
|
+
this.setState("connecting" /* CONNECTING */);
|
|
2487
|
+
let targetChains;
|
|
2488
|
+
if (Array.isArray(chainId)) {
|
|
2489
|
+
targetChains = chainId.length > 0 ? chainId : [1];
|
|
2490
|
+
} else if (chainId) {
|
|
2491
|
+
targetChains = [chainId];
|
|
2492
|
+
} else {
|
|
2493
|
+
targetChains = [1];
|
|
2494
|
+
}
|
|
2495
|
+
this.supportedChains = targetChains;
|
|
2496
|
+
const primaryChain = targetChains[0];
|
|
2497
|
+
const optionalChains = targetChains.slice(1);
|
|
2498
|
+
const isTelegram = this.isTelegramMiniApp();
|
|
2499
|
+
const telegramWebApp = this.getTelegramWebApp();
|
|
2500
|
+
let appUrl = "";
|
|
2501
|
+
if (typeof window !== "undefined") {
|
|
2502
|
+
try {
|
|
2503
|
+
if (window.location && window.location.origin) {
|
|
2504
|
+
appUrl = window.location.origin;
|
|
2505
|
+
} else if (window.location && window.location.href) {
|
|
2506
|
+
const url = new URL(window.location.href);
|
|
2507
|
+
appUrl = url.origin;
|
|
2508
|
+
}
|
|
2509
|
+
} catch (error) {
|
|
2510
|
+
console.warn("[WalletConnect] Failed to get origin from window.location:", error);
|
|
2511
|
+
}
|
|
2512
|
+
if (!appUrl) {
|
|
2513
|
+
appUrl = "https://enclave.network";
|
|
2514
|
+
}
|
|
2515
|
+
} else {
|
|
2516
|
+
appUrl = "https://enclave.network";
|
|
2517
|
+
}
|
|
2518
|
+
if (!appUrl || !appUrl.startsWith("http://") && !appUrl.startsWith("https://")) {
|
|
2519
|
+
appUrl = "https://enclave.network";
|
|
2520
|
+
}
|
|
2521
|
+
const icons = [
|
|
2522
|
+
"https://walletconnect.com/walletconnect-logo.svg",
|
|
2523
|
+
"https://avatars.githubusercontent.com/u/37784886"
|
|
2524
|
+
// WalletConnect GitHub avatar
|
|
2525
|
+
];
|
|
2526
|
+
const initOptions = {
|
|
2527
|
+
projectId: this.projectId,
|
|
2528
|
+
chains: [primaryChain],
|
|
2529
|
+
// Primary chain (required)
|
|
2530
|
+
showQrModal: true,
|
|
2531
|
+
// QR modal works in Telegram Mini Apps
|
|
2532
|
+
metadata: {
|
|
2533
|
+
name: "Enclave Wallet SDK",
|
|
2534
|
+
description: "Multi-chain wallet adapter for Enclave",
|
|
2535
|
+
url: appUrl,
|
|
2536
|
+
icons
|
|
2537
|
+
}
|
|
2538
|
+
};
|
|
2539
|
+
if (isTelegram && telegramWebApp) {
|
|
2540
|
+
const platform = telegramWebApp.platform || "unknown";
|
|
2541
|
+
const isMiniApp = platform !== "web";
|
|
2542
|
+
console.log("[WalletConnect] Detected Telegram environment:", {
|
|
2543
|
+
platform,
|
|
2544
|
+
isMiniApp,
|
|
2545
|
+
isWeb: platform === "web"
|
|
2546
|
+
});
|
|
2547
|
+
if (telegramWebApp.isExpanded === false) {
|
|
2548
|
+
telegramWebApp.expand();
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
if (optionalChains.length > 0) {
|
|
2552
|
+
initOptions.optionalChains = optionalChains;
|
|
2553
|
+
} else {
|
|
2554
|
+
initOptions.optionalChains = [primaryChain];
|
|
2555
|
+
}
|
|
2556
|
+
const hasExistingProvider = _WalletConnectAdapter.providerInstance && _WalletConnectAdapter.providerProjectId === this.projectId;
|
|
2557
|
+
const needsReinit = hasExistingProvider && _WalletConnectAdapter.providerChains !== null && JSON.stringify(_WalletConnectAdapter.providerChains.sort()) !== JSON.stringify(targetChains.sort());
|
|
2558
|
+
if (needsReinit) {
|
|
2559
|
+
console.log("[WalletConnect] Provider initialized with different chains, reinitializing...", {
|
|
2560
|
+
existing: _WalletConnectAdapter.providerChains,
|
|
2561
|
+
requested: targetChains
|
|
2562
|
+
});
|
|
2563
|
+
const existingProvider = _WalletConnectAdapter.providerInstance;
|
|
2564
|
+
if (existingProvider) {
|
|
2565
|
+
try {
|
|
2566
|
+
if (existingProvider.accounts && existingProvider.accounts.length > 0) {
|
|
2567
|
+
await existingProvider.disconnect();
|
|
2568
|
+
}
|
|
2569
|
+
} catch (error) {
|
|
2570
|
+
console.warn("[WalletConnect] Error disconnecting existing provider:", error);
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
_WalletConnectAdapter.providerInstance = null;
|
|
2574
|
+
_WalletConnectAdapter.providerChains = null;
|
|
2575
|
+
}
|
|
2576
|
+
if (_WalletConnectAdapter.providerInstance && _WalletConnectAdapter.providerProjectId === this.projectId) {
|
|
2577
|
+
this.provider = _WalletConnectAdapter.providerInstance;
|
|
2578
|
+
console.log("[WalletConnect] Reusing existing provider instance");
|
|
2579
|
+
if (this.provider.accounts && this.provider.accounts.length > 0) {
|
|
2580
|
+
console.log("[WalletConnect] Provider already has accounts, skipping enable()");
|
|
2581
|
+
} else {
|
|
2582
|
+
const hasSession = this.provider.session !== void 0 && this.provider.session !== null;
|
|
2583
|
+
console.log("[WalletConnect] Provider has no accounts, calling enable() to show QR modal");
|
|
2584
|
+
console.log("[WalletConnect] Provider state:", {
|
|
2585
|
+
accounts: this.provider.accounts,
|
|
2586
|
+
chainId: this.provider.chainId,
|
|
2587
|
+
hasSession,
|
|
2588
|
+
sessionTopic: this.provider.session?.topic
|
|
2589
|
+
});
|
|
2590
|
+
if (hasSession && (!this.provider.accounts || this.provider.accounts.length === 0)) {
|
|
2591
|
+
console.log("[WalletConnect] Found stale session, disconnecting before reconnecting...");
|
|
2592
|
+
try {
|
|
2593
|
+
await this.provider.disconnect();
|
|
2594
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
2595
|
+
} catch (disconnectError) {
|
|
2596
|
+
console.warn("[WalletConnect] Error disconnecting stale session:", disconnectError);
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
try {
|
|
2600
|
+
console.log("[WalletConnect] Calling enable()...");
|
|
2601
|
+
const enableResult = await this.provider.enable();
|
|
2602
|
+
console.log("[WalletConnect] enable() completed, result:", enableResult);
|
|
2603
|
+
console.log("[WalletConnect] Provider state after enable():", {
|
|
2604
|
+
accounts: this.provider.accounts,
|
|
2605
|
+
chainId: this.provider.chainId,
|
|
2606
|
+
session: this.provider.session ? {
|
|
2607
|
+
topic: this.provider.session.topic,
|
|
2608
|
+
namespaces: this.provider.session.namespaces ? Object.keys(this.provider.session.namespaces) : "none"
|
|
2609
|
+
} : "none"
|
|
2610
|
+
});
|
|
2611
|
+
} catch (error) {
|
|
2612
|
+
console.error("[WalletConnect] enable() error:", error);
|
|
2613
|
+
if (error.code === 4001 || error.message?.includes("rejected") || error.message?.includes("User rejected")) {
|
|
2614
|
+
throw new ConnectionRejectedError(this.type);
|
|
2615
|
+
}
|
|
2616
|
+
throw error;
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
} else if (_WalletConnectAdapter.providerInstance && _WalletConnectAdapter.providerProjectId === this.projectId) {
|
|
2620
|
+
this.provider = _WalletConnectAdapter.providerInstance;
|
|
2621
|
+
console.log("[WalletConnect] Reusing existing provider instance (not connected)");
|
|
2622
|
+
if (this.provider.accounts && this.provider.accounts.length > 0) {
|
|
2623
|
+
console.log("[WalletConnect] Provider already has accounts after init, skipping enable()");
|
|
2624
|
+
} else {
|
|
2625
|
+
const hasSession = this.provider.session !== void 0 && this.provider.session !== null;
|
|
2626
|
+
console.log("[WalletConnect] Provider has no accounts, calling enable() to show QR modal");
|
|
2627
|
+
console.log("[WalletConnect] Provider state:", {
|
|
2628
|
+
accounts: this.provider.accounts,
|
|
2629
|
+
chainId: this.provider.chainId,
|
|
2630
|
+
hasSession,
|
|
2631
|
+
sessionTopic: this.provider.session?.topic
|
|
2632
|
+
});
|
|
2633
|
+
if (hasSession && (!this.provider.accounts || this.provider.accounts.length === 0)) {
|
|
2634
|
+
console.log("[WalletConnect] Found stale session after init, disconnecting before reconnecting...");
|
|
2635
|
+
try {
|
|
2636
|
+
await this.provider.disconnect();
|
|
2637
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
2638
|
+
} catch (disconnectError) {
|
|
2639
|
+
console.warn("[WalletConnect] Error disconnecting stale session:", disconnectError);
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
try {
|
|
2643
|
+
await this.provider.enable();
|
|
2644
|
+
} catch (error) {
|
|
2645
|
+
console.error("[WalletConnect] enable() error:", error);
|
|
2646
|
+
if (error.code === 4001 || error.message?.includes("rejected") || error.message?.includes("User rejected")) {
|
|
2647
|
+
throw new ConnectionRejectedError(this.type);
|
|
2648
|
+
}
|
|
2649
|
+
throw error;
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
} else if (_WalletConnectAdapter.isInitializing && _WalletConnectAdapter.initPromise) {
|
|
2653
|
+
console.log("[WalletConnect] Waiting for ongoing initialization...");
|
|
2654
|
+
this.provider = await _WalletConnectAdapter.initPromise;
|
|
2655
|
+
_WalletConnectAdapter.providerInstance = this.provider;
|
|
2656
|
+
_WalletConnectAdapter.providerProjectId = this.projectId;
|
|
2657
|
+
_WalletConnectAdapter.providerChains = targetChains;
|
|
2658
|
+
if (this.provider.accounts && this.provider.accounts.length > 0) {
|
|
2659
|
+
console.log("[WalletConnect] Provider already has accounts after init, skipping enable()");
|
|
2660
|
+
} else {
|
|
2661
|
+
try {
|
|
2662
|
+
await this.provider.enable();
|
|
2663
|
+
} catch (error) {
|
|
2664
|
+
if (error.code === 4001 || error.message?.includes("rejected") || error.message?.includes("User rejected")) {
|
|
2665
|
+
throw new ConnectionRejectedError(this.type);
|
|
2666
|
+
}
|
|
2667
|
+
throw error;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
} else {
|
|
2671
|
+
console.log("[WalletConnect] Initializing new provider with chains:", {
|
|
2672
|
+
primary: primaryChain,
|
|
2673
|
+
optional: optionalChains,
|
|
2674
|
+
all: targetChains
|
|
2675
|
+
});
|
|
2676
|
+
_WalletConnectAdapter.isInitializing = true;
|
|
2677
|
+
_WalletConnectAdapter.initPromise = EthereumProvider__default.default.init(initOptions);
|
|
2678
|
+
try {
|
|
2679
|
+
this.provider = await _WalletConnectAdapter.initPromise;
|
|
2680
|
+
_WalletConnectAdapter.providerInstance = this.provider;
|
|
2681
|
+
_WalletConnectAdapter.providerProjectId = this.projectId;
|
|
2682
|
+
_WalletConnectAdapter.providerChains = targetChains;
|
|
2683
|
+
if (this.provider.accounts && this.provider.accounts.length > 0) {
|
|
2684
|
+
console.log("[WalletConnect] Provider has restored session, skipping enable()");
|
|
2685
|
+
} else {
|
|
2686
|
+
const hasSession = this.provider.session !== void 0 && this.provider.session !== null;
|
|
2687
|
+
console.log("[WalletConnect] New provider initialized, calling enable() to show QR modal");
|
|
2688
|
+
console.log("[WalletConnect] Provider state:", {
|
|
2689
|
+
accounts: this.provider.accounts,
|
|
2690
|
+
chainId: this.provider.chainId,
|
|
2691
|
+
hasSession,
|
|
2692
|
+
sessionTopic: this.provider.session?.topic
|
|
2693
|
+
});
|
|
2694
|
+
if (hasSession && (!this.provider.accounts || this.provider.accounts.length === 0)) {
|
|
2695
|
+
console.log("[WalletConnect] Found stale session after init, disconnecting before reconnecting...");
|
|
2696
|
+
try {
|
|
2697
|
+
await this.provider.disconnect();
|
|
2698
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
2699
|
+
} catch (disconnectError) {
|
|
2700
|
+
console.warn("[WalletConnect] Error disconnecting stale session:", disconnectError);
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
try {
|
|
2704
|
+
await this.provider.enable();
|
|
2705
|
+
} catch (error) {
|
|
2706
|
+
console.error("[WalletConnect] enable() error:", error);
|
|
2707
|
+
if (error.code === 4001 || error.message?.includes("rejected") || error.message?.includes("User rejected")) {
|
|
2708
|
+
throw new ConnectionRejectedError(this.type);
|
|
2709
|
+
}
|
|
2710
|
+
throw error;
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
} finally {
|
|
2714
|
+
_WalletConnectAdapter.isInitializing = false;
|
|
2715
|
+
_WalletConnectAdapter.initPromise = null;
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
let accounts = this.provider.accounts;
|
|
2719
|
+
if (!accounts || accounts.length === 0) {
|
|
2720
|
+
console.log("[WalletConnect] provider.accounts is empty, checking session.namespaces.eip155.accounts...");
|
|
2721
|
+
const session = this.provider.session;
|
|
2722
|
+
if (session && session.namespaces?.eip155?.accounts) {
|
|
2723
|
+
const sessionAccounts = session.namespaces.eip155.accounts.map((acc) => {
|
|
2724
|
+
const parts = acc.split(":");
|
|
2725
|
+
if (parts.length >= 3 && parts[0] === "eip155") {
|
|
2726
|
+
return parts[2];
|
|
2727
|
+
}
|
|
2728
|
+
return null;
|
|
2729
|
+
}).filter((addr) => addr !== null && addr.startsWith("0x"));
|
|
2730
|
+
if (sessionAccounts.length > 0) {
|
|
2731
|
+
const uniqueAccounts = [...new Set(sessionAccounts)];
|
|
2732
|
+
console.log("[WalletConnect] Found accounts in session.namespaces.eip155.accounts:", {
|
|
2733
|
+
raw: session.namespaces.eip155.accounts,
|
|
2734
|
+
extracted: uniqueAccounts,
|
|
2735
|
+
chains: session.namespaces.eip155.chains
|
|
2736
|
+
});
|
|
2737
|
+
accounts = uniqueAccounts;
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
if (!accounts || accounts.length === 0) {
|
|
2742
|
+
console.log("[WalletConnect] Accounts not available, waiting for provider.accounts to populate...");
|
|
2743
|
+
const maxWaitTime = 3e3;
|
|
2744
|
+
const checkInterval = 100;
|
|
2745
|
+
const maxChecks = maxWaitTime / checkInterval;
|
|
2746
|
+
for (let i = 0; i < maxChecks; i++) {
|
|
2747
|
+
await new Promise((resolve) => setTimeout(resolve, checkInterval));
|
|
2748
|
+
accounts = this.provider.accounts;
|
|
2749
|
+
if (accounts && accounts.length > 0) {
|
|
2750
|
+
console.log(`[WalletConnect] Accounts available after ${(i + 1) * checkInterval}ms`);
|
|
2751
|
+
break;
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
if (!accounts || accounts.length === 0) {
|
|
2756
|
+
const session = this.provider.session;
|
|
2757
|
+
const providerState = {
|
|
2758
|
+
providerAccounts: this.provider.accounts,
|
|
2759
|
+
providerChainId: this.provider.chainId,
|
|
2760
|
+
session: session ? {
|
|
2761
|
+
exists: true,
|
|
2762
|
+
topic: session.topic,
|
|
2763
|
+
namespaces: session.namespaces ? Object.keys(session.namespaces) : "none",
|
|
2764
|
+
eip155Namespace: session.namespaces?.eip155 ? {
|
|
2765
|
+
accounts: session.namespaces.eip155.accounts,
|
|
2766
|
+
// CAIP-10 format
|
|
2767
|
+
chains: session.namespaces.eip155.chains,
|
|
2768
|
+
// CAIP-2 format
|
|
2769
|
+
methods: session.namespaces.eip155.methods,
|
|
2770
|
+
events: session.namespaces.eip155.events
|
|
2771
|
+
} : "none",
|
|
2772
|
+
// Log full session structure for debugging
|
|
2773
|
+
fullSession: JSON.stringify(session, null, 2)
|
|
2774
|
+
} : "none",
|
|
2775
|
+
// Check if provider has any other properties that might contain accounts
|
|
2776
|
+
providerKeys: Object.keys(this.provider)
|
|
2777
|
+
};
|
|
2778
|
+
console.error("[WalletConnect] No accounts available after enable() and wait", providerState);
|
|
2779
|
+
console.error("[WalletConnect] Full provider object:", this.provider);
|
|
2780
|
+
console.error("[WalletConnect] Full session object:", session);
|
|
2781
|
+
console.error("[WalletConnect] Session namespaces structure:", session?.namespaces);
|
|
2782
|
+
throw new Error("WalletConnect connection established but no accounts available. Please check session.namespaces.eip155.accounts in the console logs above.");
|
|
2783
|
+
}
|
|
2784
|
+
const currentChainId = this.provider.chainId || targetChains[0];
|
|
2785
|
+
const viemChain = this.getViemChain(currentChainId);
|
|
2786
|
+
this.walletClient = viem.createWalletClient({
|
|
2787
|
+
account: accounts[0],
|
|
2788
|
+
chain: viemChain,
|
|
2789
|
+
transport: viem.custom(this.provider)
|
|
2790
|
+
});
|
|
2791
|
+
const chainInfo = getChainInfo(currentChainId);
|
|
2792
|
+
const primaryRpcUrl = chainInfo?.rpcUrls[0];
|
|
2793
|
+
this.publicClient = viem.createPublicClient({
|
|
2794
|
+
chain: viemChain,
|
|
2795
|
+
transport: primaryRpcUrl ? viem.http(primaryRpcUrl) : viem.custom(this.provider)
|
|
2796
|
+
});
|
|
2797
|
+
const address = formatEVMAddress(accounts[0]);
|
|
2798
|
+
const account = {
|
|
2799
|
+
universalAddress: createUniversalAddress(currentChainId, address),
|
|
2800
|
+
nativeAddress: address,
|
|
2801
|
+
chainId: currentChainId,
|
|
2802
|
+
chainType: exports.ChainType.EVM,
|
|
2803
|
+
isActive: true
|
|
2804
|
+
};
|
|
2805
|
+
this.setState("connected" /* CONNECTED */);
|
|
2806
|
+
this.setAccount(account);
|
|
2807
|
+
this.setupEventListeners();
|
|
2808
|
+
return account;
|
|
2809
|
+
} catch (error) {
|
|
2810
|
+
this.setState("error" /* ERROR */);
|
|
2811
|
+
this.setAccount(null);
|
|
2812
|
+
const origin = typeof window !== "undefined" && window.location ? window.location.origin : "";
|
|
2813
|
+
const errorCode = error?.code;
|
|
2814
|
+
const errorMessage = error?.message || String(error);
|
|
2815
|
+
const isOriginNotAllowed = errorCode === 3e3 || /origin not allowed/i.test(errorMessage) || /Unauthorized:\s*origin not allowed/i.test(errorMessage);
|
|
2816
|
+
const session = this.provider?.session;
|
|
2817
|
+
const providerState = this.provider ? {
|
|
2818
|
+
accounts: this.provider.accounts,
|
|
2819
|
+
chainId: this.provider.chainId,
|
|
2820
|
+
session: session ? {
|
|
2821
|
+
exists: true,
|
|
2822
|
+
topic: session.topic,
|
|
2823
|
+
namespaces: session.namespaces ? Object.keys(session.namespaces) : "none",
|
|
2824
|
+
eip155Namespace: session.namespaces?.eip155 ? {
|
|
2825
|
+
accounts: session.namespaces.eip155.accounts,
|
|
2826
|
+
chains: session.namespaces.eip155.chains,
|
|
2827
|
+
methods: session.namespaces.eip155.methods,
|
|
2828
|
+
events: session.namespaces.eip155.events
|
|
2829
|
+
} : "none"
|
|
2830
|
+
} : "none",
|
|
2831
|
+
providerKeys: Object.keys(this.provider)
|
|
2832
|
+
} : "no provider";
|
|
2833
|
+
console.error("[WalletConnect] Connection error:", {
|
|
2834
|
+
error,
|
|
2835
|
+
code: error.code,
|
|
2836
|
+
message: error.message,
|
|
2837
|
+
stack: error.stack,
|
|
2838
|
+
providerState
|
|
2839
|
+
});
|
|
2840
|
+
if (this.provider) {
|
|
2841
|
+
console.error("[WalletConnect] Full provider object:", this.provider);
|
|
2842
|
+
console.error("[WalletConnect] Full session object:", session);
|
|
2843
|
+
}
|
|
2844
|
+
if (error.code === 4001 || error.message && (error.message.includes("User rejected") || error.message.includes("rejected by user") || error.message.includes("User cancelled"))) {
|
|
2845
|
+
throw new ConnectionRejectedError(this.type);
|
|
2846
|
+
}
|
|
2847
|
+
if (isOriginNotAllowed) {
|
|
2848
|
+
throw new ConfigurationError(
|
|
2849
|
+
`WalletConnect relayer rejected this origin (code 3000: Unauthorized: origin not allowed).
|
|
2850
|
+
|
|
2851
|
+
Fix:
|
|
2852
|
+
1) Open WalletConnect Cloud \u2192 your project (${this.projectId})
|
|
2853
|
+
2) Add this site origin to the allowlist:
|
|
2854
|
+
- ${origin || "(unknown origin)"}
|
|
2855
|
+
|
|
2856
|
+
Common dev origins to allow:
|
|
2857
|
+
- http://localhost:5173
|
|
2858
|
+
- http://192.168.0.221:5173 (your LAN dev URL)
|
|
2859
|
+
- https://wallet-test.enclave-hq.com (your Cloudflare Tunnel/custom domain)
|
|
2860
|
+
|
|
2861
|
+
Original error: ${errorMessage}`
|
|
2862
|
+
);
|
|
2863
|
+
}
|
|
2864
|
+
throw error;
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
/**
|
|
2868
|
+
* Disconnect wallet
|
|
2869
|
+
*/
|
|
2870
|
+
async disconnect() {
|
|
2871
|
+
if (this.provider) {
|
|
2872
|
+
try {
|
|
2873
|
+
await this.provider.disconnect();
|
|
2874
|
+
} catch (error) {
|
|
2875
|
+
console.warn("[WalletConnect] Error during disconnect:", error);
|
|
2876
|
+
}
|
|
2877
|
+
if (_WalletConnectAdapter.providerInstance === this.provider) {
|
|
2878
|
+
_WalletConnectAdapter.providerInstance = null;
|
|
2879
|
+
_WalletConnectAdapter.providerProjectId = null;
|
|
2880
|
+
_WalletConnectAdapter.providerChains = null;
|
|
2881
|
+
}
|
|
2882
|
+
this.provider = null;
|
|
2883
|
+
}
|
|
2884
|
+
this.removeEventListeners();
|
|
2885
|
+
this.walletClient = null;
|
|
2886
|
+
this.publicClient = null;
|
|
2887
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
2888
|
+
this.setAccount(null);
|
|
2889
|
+
this.emitDisconnected();
|
|
2890
|
+
}
|
|
2891
|
+
/**
|
|
2892
|
+
* Sign message
|
|
2893
|
+
*/
|
|
2894
|
+
async signMessage(message) {
|
|
2895
|
+
this.ensureConnected();
|
|
2896
|
+
try {
|
|
2897
|
+
if (!this.provider) {
|
|
2898
|
+
throw new Error("Provider not initialized");
|
|
2899
|
+
}
|
|
2900
|
+
const signature = await this.provider.request({
|
|
2901
|
+
method: "personal_sign",
|
|
2902
|
+
params: [message, this.currentAccount.nativeAddress]
|
|
2903
|
+
});
|
|
2904
|
+
this.closeTelegramDeepLinkPopup();
|
|
2905
|
+
return signature;
|
|
2906
|
+
} catch (error) {
|
|
2907
|
+
if (error.code === 4001 || error.message?.includes("rejected")) {
|
|
2908
|
+
throw new SignatureRejectedError();
|
|
2909
|
+
}
|
|
2910
|
+
throw error;
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
/**
|
|
2914
|
+
* Sign TypedData (EIP-712)
|
|
2915
|
+
*/
|
|
2916
|
+
async signTypedData(typedData) {
|
|
2917
|
+
this.ensureConnected();
|
|
2918
|
+
try {
|
|
2919
|
+
if (!this.provider) {
|
|
2920
|
+
throw new Error("Provider not initialized");
|
|
2921
|
+
}
|
|
2922
|
+
const signature = await this.provider.request({
|
|
2923
|
+
method: "eth_signTypedData_v4",
|
|
2924
|
+
params: [this.currentAccount.nativeAddress, JSON.stringify(typedData)]
|
|
2925
|
+
});
|
|
2926
|
+
this.closeTelegramDeepLinkPopup();
|
|
2927
|
+
return signature;
|
|
2928
|
+
} catch (error) {
|
|
2929
|
+
if (error.code === 4001 || error.message?.includes("rejected")) {
|
|
2930
|
+
throw new SignatureRejectedError();
|
|
2931
|
+
}
|
|
2932
|
+
throw error;
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
/**
|
|
2936
|
+
* Sign transaction
|
|
2937
|
+
*/
|
|
2938
|
+
async signTransaction(transaction) {
|
|
2939
|
+
this.ensureConnected();
|
|
2940
|
+
try {
|
|
2941
|
+
if (!this.provider) {
|
|
2942
|
+
throw new Error("Provider not initialized");
|
|
2943
|
+
}
|
|
2944
|
+
const tx = {
|
|
2945
|
+
from: this.currentAccount.nativeAddress,
|
|
2946
|
+
to: transaction.to,
|
|
2947
|
+
value: transaction.value ? `0x${BigInt(transaction.value).toString(16)}` : void 0,
|
|
2948
|
+
data: transaction.data || "0x",
|
|
2949
|
+
gas: transaction.gas ? `0x${BigInt(transaction.gas).toString(16)}` : void 0,
|
|
2950
|
+
gasPrice: transaction.gasPrice && transaction.gasPrice !== "auto" ? `0x${BigInt(transaction.gasPrice).toString(16)}` : void 0,
|
|
2951
|
+
maxFeePerGas: transaction.maxFeePerGas ? `0x${BigInt(transaction.maxFeePerGas).toString(16)}` : void 0,
|
|
2952
|
+
maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? `0x${BigInt(transaction.maxPriorityFeePerGas).toString(16)}` : void 0,
|
|
2953
|
+
nonce: transaction.nonce !== void 0 ? `0x${transaction.nonce.toString(16)}` : void 0,
|
|
2954
|
+
chainId: transaction.chainId || this.currentAccount.chainId
|
|
2955
|
+
};
|
|
2956
|
+
const signature = await this.provider.request({
|
|
2957
|
+
method: "eth_signTransaction",
|
|
2958
|
+
params: [tx]
|
|
2959
|
+
});
|
|
2960
|
+
this.closeTelegramDeepLinkPopup();
|
|
2961
|
+
return signature;
|
|
2962
|
+
} catch (error) {
|
|
2963
|
+
if (error.code === 4001 || error.message?.includes("rejected")) {
|
|
2964
|
+
throw new SignatureRejectedError("Transaction signature was rejected by user");
|
|
2965
|
+
}
|
|
2966
|
+
throw error;
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
/**
|
|
2970
|
+
* Get supported chains from current connection
|
|
2971
|
+
* Returns the chains that were requested during connection
|
|
2972
|
+
*/
|
|
2973
|
+
getSupportedChains() {
|
|
2974
|
+
return [...this.supportedChains];
|
|
2975
|
+
}
|
|
2976
|
+
/**
|
|
2977
|
+
* Switch chain
|
|
2978
|
+
*
|
|
2979
|
+
* Note: WalletConnect v2 with mobile wallets may not support chain switching reliably.
|
|
2980
|
+
* Some wallets may ignore the switch request or fail silently.
|
|
2981
|
+
* It's recommended to include all needed chains in the initial connection.
|
|
2982
|
+
*
|
|
2983
|
+
* Reference: https://specs.walletconnect.com/2.0/specs/clients/sign/namespaces
|
|
2984
|
+
*/
|
|
2985
|
+
async switchChain(chainId) {
|
|
2986
|
+
if (!this.provider) {
|
|
2987
|
+
throw new Error("Provider not initialized");
|
|
2988
|
+
}
|
|
2989
|
+
const session = this.provider.session;
|
|
2990
|
+
const supportedChains = session?.namespaces?.eip155?.chains || [];
|
|
2991
|
+
const targetChainCAIP = `eip155:${chainId}`;
|
|
2992
|
+
const isChainApproved = supportedChains.includes(targetChainCAIP);
|
|
2993
|
+
if (!isChainApproved) {
|
|
2994
|
+
console.warn(`[WalletConnect] Chain ${chainId} (${targetChainCAIP}) not in session approved chains:`, supportedChains);
|
|
2995
|
+
console.warn("[WalletConnect] Chain switching may fail. Consider including all chains in initial connection.");
|
|
2996
|
+
}
|
|
2997
|
+
try {
|
|
2998
|
+
console.log(`[WalletConnect] Attempting to switch to chain ${chainId} (${targetChainCAIP})`);
|
|
2999
|
+
const result = await this.provider.request({
|
|
3000
|
+
method: "wallet_switchEthereumChain",
|
|
3001
|
+
params: [{ chainId: `0x${chainId.toString(16)}` }]
|
|
3002
|
+
});
|
|
3003
|
+
if (result !== null && result !== void 0) {
|
|
3004
|
+
console.warn("[WalletConnect] wallet_switchEthereumChain returned non-null result:", result);
|
|
3005
|
+
}
|
|
3006
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
3007
|
+
const currentChainId = this.provider.chainId;
|
|
3008
|
+
if (currentChainId !== chainId) {
|
|
3009
|
+
console.warn(`[WalletConnect] Chain switch may have failed. Expected ${chainId}, got ${currentChainId}`);
|
|
3010
|
+
console.warn("[WalletConnect] Some mobile wallets may not support chain switching via WalletConnect.");
|
|
3011
|
+
console.warn("[WalletConnect] User may need to manually switch chains in the wallet app.");
|
|
3012
|
+
}
|
|
3013
|
+
if (this.currentAccount) {
|
|
3014
|
+
const updatedAccount = {
|
|
3015
|
+
...this.currentAccount,
|
|
3016
|
+
chainId,
|
|
3017
|
+
universalAddress: createUniversalAddress(chainId, this.currentAccount.nativeAddress)
|
|
3018
|
+
};
|
|
3019
|
+
this.setAccount(updatedAccount);
|
|
3020
|
+
this.emitChainChanged(chainId);
|
|
3021
|
+
const viemChain = this.getViemChain(chainId);
|
|
3022
|
+
const chainInfo = getChainInfo(chainId);
|
|
3023
|
+
const primaryRpcUrl = chainInfo?.rpcUrls[0];
|
|
3024
|
+
this.walletClient = viem.createWalletClient({
|
|
3025
|
+
account: this.currentAccount.nativeAddress,
|
|
3026
|
+
chain: viemChain,
|
|
3027
|
+
transport: viem.custom(this.provider)
|
|
3028
|
+
});
|
|
3029
|
+
this.publicClient = viem.createPublicClient({
|
|
3030
|
+
chain: viemChain,
|
|
3031
|
+
transport: primaryRpcUrl ? viem.http(primaryRpcUrl) : viem.custom(this.provider)
|
|
3032
|
+
});
|
|
3033
|
+
}
|
|
3034
|
+
} catch (error) {
|
|
3035
|
+
console.error("[WalletConnect] Chain switch error:", {
|
|
3036
|
+
chainId,
|
|
3037
|
+
errorCode: error.code,
|
|
3038
|
+
errorMessage: error.message,
|
|
3039
|
+
supportedChains
|
|
3040
|
+
});
|
|
3041
|
+
if (error.code === 4902) {
|
|
3042
|
+
console.log(`[WalletConnect] Chain ${chainId} not found in wallet, attempting to add...`);
|
|
3043
|
+
const chainInfo = getChainInfo(chainId);
|
|
3044
|
+
if (chainInfo) {
|
|
3045
|
+
try {
|
|
3046
|
+
await this.addChain({
|
|
3047
|
+
chainId: chainInfo.id,
|
|
3048
|
+
chainName: chainInfo.name,
|
|
3049
|
+
nativeCurrency: chainInfo.nativeCurrency,
|
|
3050
|
+
rpcUrls: chainInfo.rpcUrls,
|
|
3051
|
+
blockExplorerUrls: chainInfo.blockExplorerUrls
|
|
3052
|
+
});
|
|
3053
|
+
console.log(`[WalletConnect] Chain added, attempting to switch again...`);
|
|
3054
|
+
await this.switchChain(chainId);
|
|
3055
|
+
} catch (addError) {
|
|
3056
|
+
console.error("[WalletConnect] Failed to add chain:", addError);
|
|
3057
|
+
throw new Error(`Failed to add chain ${chainId}: ${addError.message}`);
|
|
3058
|
+
}
|
|
3059
|
+
} else {
|
|
3060
|
+
throw new Error(`Chain ${chainId} not supported`);
|
|
3061
|
+
}
|
|
3062
|
+
} else if (error.code === 4001) {
|
|
3063
|
+
throw new Error("User rejected chain switch");
|
|
3064
|
+
} else if (error.code === 4100) {
|
|
3065
|
+
throw new Error("Wallet does not support wallet_switchEthereumChain. Please switch chains manually in your wallet app.");
|
|
3066
|
+
} else {
|
|
3067
|
+
console.warn("[WalletConnect] Chain switch may not be supported by this wallet. User may need to switch manually.");
|
|
3068
|
+
throw error;
|
|
3069
|
+
}
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
/**
|
|
3073
|
+
* Add chain
|
|
3074
|
+
*/
|
|
3075
|
+
async addChain(chainConfig) {
|
|
3076
|
+
if (!this.provider) {
|
|
3077
|
+
throw new Error("Provider not initialized");
|
|
3078
|
+
}
|
|
3079
|
+
await this.provider.request({
|
|
3080
|
+
method: "wallet_addEthereumChain",
|
|
3081
|
+
params: [{
|
|
3082
|
+
chainId: `0x${chainConfig.chainId.toString(16)}`,
|
|
3083
|
+
chainName: chainConfig.chainName,
|
|
3084
|
+
nativeCurrency: chainConfig.nativeCurrency,
|
|
3085
|
+
rpcUrls: chainConfig.rpcUrls,
|
|
3086
|
+
blockExplorerUrls: chainConfig.blockExplorerUrls
|
|
3087
|
+
}]
|
|
3088
|
+
});
|
|
3089
|
+
}
|
|
3090
|
+
/**
|
|
3091
|
+
* Read contract
|
|
3092
|
+
*/
|
|
3093
|
+
async readContract(params) {
|
|
3094
|
+
if (!this.publicClient) {
|
|
3095
|
+
throw new Error("Public client not initialized");
|
|
3096
|
+
}
|
|
3097
|
+
const result = await this.publicClient.readContract({
|
|
3098
|
+
address: params.address,
|
|
3099
|
+
abi: params.abi,
|
|
3100
|
+
functionName: params.functionName,
|
|
3101
|
+
...params.args ? { args: params.args } : {}
|
|
3102
|
+
});
|
|
3103
|
+
return result;
|
|
3104
|
+
}
|
|
3105
|
+
/**
|
|
3106
|
+
* Write contract
|
|
3107
|
+
*/
|
|
3108
|
+
async writeContract(params) {
|
|
3109
|
+
this.ensureConnected();
|
|
3110
|
+
if (!this.walletClient) {
|
|
3111
|
+
throw new Error("Wallet client not initialized");
|
|
3112
|
+
}
|
|
3113
|
+
try {
|
|
3114
|
+
const txOptions = {
|
|
3115
|
+
address: params.address,
|
|
3116
|
+
abi: params.abi,
|
|
3117
|
+
functionName: params.functionName,
|
|
3118
|
+
...params.args ? { args: params.args } : {},
|
|
3119
|
+
value: params.value ? BigInt(params.value) : void 0,
|
|
3120
|
+
gas: params.gas ? BigInt(params.gas) : void 0
|
|
3121
|
+
};
|
|
3122
|
+
if (params.maxFeePerGas || params.maxPriorityFeePerGas) {
|
|
3123
|
+
if (params.maxFeePerGas) {
|
|
3124
|
+
txOptions.maxFeePerGas = BigInt(params.maxFeePerGas);
|
|
3125
|
+
}
|
|
3126
|
+
if (params.maxPriorityFeePerGas) {
|
|
3127
|
+
txOptions.maxPriorityFeePerGas = BigInt(params.maxPriorityFeePerGas);
|
|
3128
|
+
}
|
|
3129
|
+
} else if (params.gasPrice && params.gasPrice !== "auto") {
|
|
3130
|
+
txOptions.gasPrice = BigInt(params.gasPrice);
|
|
3131
|
+
} else {
|
|
3132
|
+
if (this.publicClient) {
|
|
3133
|
+
try {
|
|
3134
|
+
const feesPerGas = await this.publicClient.estimateFeesPerGas().catch(() => null);
|
|
3135
|
+
if (feesPerGas) {
|
|
3136
|
+
const minPriorityFeeWei = BigInt(1e8);
|
|
3137
|
+
const maxPriorityFeePerGas = feesPerGas.maxPriorityFeePerGas > minPriorityFeeWei ? feesPerGas.maxPriorityFeePerGas : minPriorityFeeWei;
|
|
3138
|
+
const adjustedMaxFeePerGas = feesPerGas.maxFeePerGas > maxPriorityFeePerGas ? feesPerGas.maxFeePerGas : maxPriorityFeePerGas + BigInt(1e9);
|
|
3139
|
+
txOptions.maxFeePerGas = adjustedMaxFeePerGas;
|
|
3140
|
+
txOptions.maxPriorityFeePerGas = maxPriorityFeePerGas;
|
|
3141
|
+
} else {
|
|
3142
|
+
const gasPrice = await this.publicClient.getGasPrice();
|
|
3143
|
+
txOptions.gasPrice = gasPrice;
|
|
3144
|
+
}
|
|
3145
|
+
} catch (err) {
|
|
3146
|
+
}
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
const txHash = await this.walletClient.writeContract(txOptions);
|
|
3150
|
+
this.closeTelegramDeepLinkPopup();
|
|
3151
|
+
return txHash;
|
|
3152
|
+
} catch (error) {
|
|
3153
|
+
if (error.code === 4001 || error.message?.includes("rejected")) {
|
|
3154
|
+
throw new SignatureRejectedError("Transaction was rejected by user");
|
|
3155
|
+
}
|
|
3156
|
+
throw error;
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
/**
|
|
3160
|
+
* Estimate gas
|
|
3161
|
+
*/
|
|
3162
|
+
async estimateGas(params) {
|
|
3163
|
+
if (!this.publicClient) {
|
|
3164
|
+
throw new Error("Public client not initialized");
|
|
3165
|
+
}
|
|
3166
|
+
const gas = await this.publicClient.estimateContractGas({
|
|
3167
|
+
address: params.address,
|
|
3168
|
+
abi: params.abi,
|
|
3169
|
+
functionName: params.functionName,
|
|
3170
|
+
...params.args ? { args: params.args } : {},
|
|
3171
|
+
value: params.value ? BigInt(params.value) : void 0,
|
|
3172
|
+
account: this.currentAccount.nativeAddress
|
|
3173
|
+
});
|
|
3174
|
+
return gas;
|
|
3175
|
+
}
|
|
3176
|
+
/**
|
|
3177
|
+
* Wait for transaction
|
|
3178
|
+
*/
|
|
3179
|
+
async waitForTransaction(txHash, confirmations = 1) {
|
|
3180
|
+
if (!this.publicClient) {
|
|
3181
|
+
throw new Error("Public client not initialized");
|
|
3182
|
+
}
|
|
3183
|
+
const receipt = await this.publicClient.waitForTransactionReceipt({
|
|
3184
|
+
hash: txHash,
|
|
3185
|
+
confirmations
|
|
3186
|
+
});
|
|
3187
|
+
if (receipt.status === "reverted") {
|
|
3188
|
+
throw new TransactionFailedError(txHash, "Transaction reverted");
|
|
3189
|
+
}
|
|
3190
|
+
return {
|
|
3191
|
+
transactionHash: receipt.transactionHash,
|
|
3192
|
+
blockNumber: Number(receipt.blockNumber),
|
|
3193
|
+
blockHash: receipt.blockHash,
|
|
3194
|
+
from: receipt.from,
|
|
3195
|
+
to: receipt.to || void 0,
|
|
3196
|
+
status: receipt.status === "success" ? "success" : "failed",
|
|
3197
|
+
gasUsed: receipt.gasUsed.toString(),
|
|
3198
|
+
effectiveGasPrice: receipt.effectiveGasPrice?.toString(),
|
|
3199
|
+
logs: receipt.logs
|
|
3200
|
+
};
|
|
3201
|
+
}
|
|
3202
|
+
/**
|
|
3203
|
+
* Get provider
|
|
3204
|
+
*/
|
|
3205
|
+
getProvider() {
|
|
3206
|
+
return this.provider;
|
|
3207
|
+
}
|
|
3208
|
+
/**
|
|
3209
|
+
* Get signer
|
|
3210
|
+
*/
|
|
3211
|
+
getSigner() {
|
|
3212
|
+
return this.walletClient;
|
|
3213
|
+
}
|
|
3214
|
+
/**
|
|
3215
|
+
* Setup event listeners
|
|
3216
|
+
*/
|
|
3217
|
+
setupEventListeners() {
|
|
3218
|
+
if (!this.provider) return;
|
|
3219
|
+
this.provider.on("accountsChanged", this.handleAccountsChanged);
|
|
3220
|
+
this.provider.on("chainChanged", this.handleChainChanged);
|
|
3221
|
+
this.provider.on("disconnect", this.handleDisconnect);
|
|
3222
|
+
}
|
|
3223
|
+
/**
|
|
3224
|
+
* Remove event listeners
|
|
3225
|
+
*/
|
|
3226
|
+
removeEventListeners() {
|
|
3227
|
+
if (!this.provider) return;
|
|
3228
|
+
this.provider.removeListener("accountsChanged", this.handleAccountsChanged);
|
|
3229
|
+
this.provider.removeListener("chainChanged", this.handleChainChanged);
|
|
3230
|
+
this.provider.removeListener("disconnect", this.handleDisconnect);
|
|
3231
|
+
}
|
|
3232
|
+
/**
|
|
3233
|
+
* Get viem chain config
|
|
3234
|
+
*/
|
|
3235
|
+
getViemChain(chainId) {
|
|
3236
|
+
const chainInfo = getChainInfo(chainId);
|
|
3237
|
+
if (chainInfo) {
|
|
3238
|
+
return {
|
|
3239
|
+
id: chainId,
|
|
3240
|
+
name: chainInfo.name,
|
|
3241
|
+
network: chainInfo.name.toLowerCase().replace(/\s+/g, "-"),
|
|
3242
|
+
nativeCurrency: chainInfo.nativeCurrency,
|
|
3243
|
+
rpcUrls: {
|
|
3244
|
+
default: { http: chainInfo.rpcUrls },
|
|
3245
|
+
public: { http: chainInfo.rpcUrls }
|
|
3246
|
+
},
|
|
3247
|
+
blockExplorers: chainInfo.blockExplorerUrls ? {
|
|
3248
|
+
default: { name: "Explorer", url: chainInfo.blockExplorerUrls[0] }
|
|
3249
|
+
} : void 0
|
|
3250
|
+
};
|
|
3251
|
+
}
|
|
3252
|
+
return {
|
|
3253
|
+
id: chainId,
|
|
3254
|
+
name: `Chain ${chainId}`,
|
|
3255
|
+
network: `chain-${chainId}`,
|
|
3256
|
+
nativeCurrency: {
|
|
3257
|
+
name: "ETH",
|
|
3258
|
+
symbol: "ETH",
|
|
3259
|
+
decimals: 18
|
|
3260
|
+
},
|
|
3261
|
+
rpcUrls: {
|
|
3262
|
+
default: { http: [] },
|
|
3263
|
+
public: { http: [] }
|
|
3264
|
+
}
|
|
3265
|
+
};
|
|
3266
|
+
}
|
|
3267
|
+
};
|
|
3268
|
+
// Store supported chains from connection
|
|
3269
|
+
// Static provider instance to avoid multiple initializations
|
|
3270
|
+
_WalletConnectAdapter.providerInstance = null;
|
|
3271
|
+
_WalletConnectAdapter.providerProjectId = null;
|
|
3272
|
+
_WalletConnectAdapter.providerChains = null;
|
|
3273
|
+
// Store the chains used during initialization
|
|
3274
|
+
_WalletConnectAdapter.isInitializing = false;
|
|
3275
|
+
_WalletConnectAdapter.initPromise = null;
|
|
3276
|
+
var WalletConnectAdapter = _WalletConnectAdapter;
|
|
3277
|
+
init_types();
|
|
3278
|
+
var _WalletConnectTronAdapter = class _WalletConnectTronAdapter extends WalletAdapter {
|
|
3279
|
+
constructor(projectId) {
|
|
3280
|
+
super();
|
|
3281
|
+
this.type = "walletconnect-tron" /* WALLETCONNECT_TRON */;
|
|
3282
|
+
this.chainType = exports.ChainType.TRON;
|
|
3283
|
+
this.name = "WalletConnect (Tron)";
|
|
3284
|
+
this.icon = "https://avatars.githubusercontent.com/u/37784886";
|
|
3285
|
+
this.wallet = null;
|
|
3286
|
+
this.currentAddress = null;
|
|
3287
|
+
if (!projectId) {
|
|
3288
|
+
throw new ConfigurationError("WalletConnect projectId is required");
|
|
3289
|
+
}
|
|
3290
|
+
this.projectId = projectId;
|
|
3291
|
+
}
|
|
3292
|
+
/**
|
|
3293
|
+
* Check if WalletConnect is available
|
|
3294
|
+
*/
|
|
3295
|
+
async isAvailable() {
|
|
3296
|
+
return typeof window !== "undefined";
|
|
3297
|
+
}
|
|
3298
|
+
/**
|
|
3299
|
+
* Check if running in Telegram environment (Mini App or Web)
|
|
3300
|
+
* Both Telegram Mini App (in client) and Telegram Web (web.telegram.org)
|
|
3301
|
+
* provide window.Telegram.WebApp API, so they are treated the same way.
|
|
3302
|
+
*/
|
|
3303
|
+
isTelegramMiniApp() {
|
|
3304
|
+
if (typeof window === "undefined") return false;
|
|
3305
|
+
const tg = window.Telegram?.WebApp;
|
|
3306
|
+
if (!tg) return false;
|
|
3307
|
+
const platform = tg.platform || "unknown";
|
|
3308
|
+
console.log("[WalletConnect Tron] Telegram environment detected:", {
|
|
3309
|
+
platform,
|
|
3310
|
+
version: tg.version,
|
|
3311
|
+
isMiniApp: platform !== "web",
|
|
3312
|
+
// Mini App if not web platform
|
|
3313
|
+
isWeb: platform === "web"
|
|
3314
|
+
// Telegram Web if web platform
|
|
3315
|
+
});
|
|
3316
|
+
return true;
|
|
3317
|
+
}
|
|
3318
|
+
/**
|
|
3319
|
+
* Restore session from existing wallet (for storage restoration)
|
|
3320
|
+
*/
|
|
3321
|
+
async restoreSession(chainId) {
|
|
3322
|
+
if (typeof window === "undefined") {
|
|
3323
|
+
return null;
|
|
3324
|
+
}
|
|
3325
|
+
try {
|
|
3326
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID : chainId || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID;
|
|
3327
|
+
if (!_WalletConnectTronAdapter.walletInstance || _WalletConnectTronAdapter.walletProjectId !== this.projectId) {
|
|
3328
|
+
this.initializeWallet(targetChainId);
|
|
3329
|
+
}
|
|
3330
|
+
this.wallet = _WalletConnectTronAdapter.walletInstance;
|
|
3331
|
+
if (!this.wallet) {
|
|
3332
|
+
return null;
|
|
3333
|
+
}
|
|
3334
|
+
const status = await this.wallet.checkConnectStatus();
|
|
3335
|
+
if (status && status.address) {
|
|
3336
|
+
this.currentAddress = status.address;
|
|
3337
|
+
const account = {
|
|
3338
|
+
universalAddress: createUniversalAddress(targetChainId, status.address),
|
|
3339
|
+
nativeAddress: status.address,
|
|
3340
|
+
chainId: targetChainId,
|
|
3341
|
+
chainType: exports.ChainType.TRON,
|
|
3342
|
+
isActive: true
|
|
3343
|
+
};
|
|
3344
|
+
this.setState("connected" /* CONNECTED */);
|
|
3345
|
+
this.setAccount(account);
|
|
3346
|
+
this.setupEventListeners();
|
|
3347
|
+
return account;
|
|
3348
|
+
}
|
|
3349
|
+
return null;
|
|
3350
|
+
} catch (error) {
|
|
3351
|
+
console.debug("[WalletConnect Tron] Restore session failed:", error);
|
|
3352
|
+
return null;
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
/**
|
|
3356
|
+
* Initialize WalletConnect wallet instance
|
|
3357
|
+
* @param chainId - Optional chain ID to determine network (default: Mainnet)
|
|
3358
|
+
*/
|
|
3359
|
+
initializeWallet(chainId) {
|
|
3360
|
+
if (_WalletConnectTronAdapter.walletInstance && _WalletConnectTronAdapter.walletProjectId === this.projectId) {
|
|
3361
|
+
return;
|
|
3362
|
+
}
|
|
3363
|
+
let appUrl = "";
|
|
3364
|
+
if (typeof window !== "undefined") {
|
|
3365
|
+
try {
|
|
3366
|
+
if (window.location && window.location.origin) {
|
|
3367
|
+
appUrl = window.location.origin;
|
|
3368
|
+
} else if (window.location && window.location.href) {
|
|
3369
|
+
const url = new URL(window.location.href);
|
|
3370
|
+
appUrl = url.origin;
|
|
3371
|
+
}
|
|
3372
|
+
} catch (error) {
|
|
3373
|
+
console.warn("[WalletConnect Tron] Failed to get origin from window.location:", error);
|
|
3374
|
+
}
|
|
3375
|
+
if (appUrl && (appUrl.includes("serveo.net") || appUrl.includes("loca.lt") || appUrl.includes("ngrok.io") || appUrl.includes("ngrok-free.app") || appUrl.includes("cloudflared.io"))) {
|
|
3376
|
+
console.log("[WalletConnect Tron] Detected tunnel service URL:", appUrl);
|
|
3377
|
+
console.log("[WalletConnect Tron] \u26A0\uFE0F Make sure this URL is added to WalletConnect Cloud project allowlist");
|
|
3378
|
+
}
|
|
3379
|
+
if (!appUrl) {
|
|
3380
|
+
const tg = window.Telegram?.WebApp;
|
|
3381
|
+
if (tg && tg.initDataUnsafe?.start_param) {
|
|
3382
|
+
appUrl = "https://enclave.network";
|
|
3383
|
+
} else {
|
|
3384
|
+
appUrl = "https://enclave.network";
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
} else {
|
|
3388
|
+
appUrl = "https://enclave.network";
|
|
3389
|
+
}
|
|
3390
|
+
if (!appUrl || !appUrl.startsWith("http://") && !appUrl.startsWith("https://")) {
|
|
3391
|
+
appUrl = "https://enclave.network";
|
|
3392
|
+
}
|
|
3393
|
+
const icons = [
|
|
3394
|
+
"https://walletconnect.com/walletconnect-logo.svg",
|
|
3395
|
+
"https://avatars.githubusercontent.com/u/37784886"
|
|
3396
|
+
// WalletConnect GitHub avatar
|
|
3397
|
+
];
|
|
3398
|
+
let network = walletconnectTron.WalletConnectChainID.Mainnet;
|
|
3399
|
+
if (chainId !== void 0) {
|
|
3400
|
+
if (chainId === 195 || chainId === _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID) {
|
|
3401
|
+
network = walletconnectTron.WalletConnectChainID.Mainnet;
|
|
3402
|
+
} else if (chainId === 201910292) {
|
|
3403
|
+
network = walletconnectTron.WalletConnectChainID.Shasta;
|
|
3404
|
+
} else if (chainId === 2494104990) {
|
|
3405
|
+
network = walletconnectTron.WalletConnectChainID.Nile;
|
|
3406
|
+
}
|
|
3407
|
+
}
|
|
3408
|
+
const metadataInfo = {
|
|
3409
|
+
name: "Enclave Wallet SDK",
|
|
3410
|
+
description: "Multi-chain wallet adapter for Enclave",
|
|
3411
|
+
url: appUrl,
|
|
3412
|
+
icons,
|
|
3413
|
+
network,
|
|
3414
|
+
chainId,
|
|
3415
|
+
isTelegram: this.isTelegramMiniApp(),
|
|
3416
|
+
projectId: this.projectId,
|
|
3417
|
+
urlValid: appUrl && (appUrl.startsWith("http://") || appUrl.startsWith("https://")),
|
|
3418
|
+
iconsValid: icons && icons.length > 0 && icons.every((icon) => icon && icon.startsWith("http")),
|
|
3419
|
+
currentLocation: typeof window !== "undefined" ? window.location.href : "N/A",
|
|
3420
|
+
telegramPlatform: typeof window !== "undefined" && window.Telegram?.WebApp?.platform || "N/A"
|
|
3421
|
+
};
|
|
3422
|
+
console.log("[WalletConnect Tron] Initializing with metadata:", metadataInfo);
|
|
3423
|
+
if (!metadataInfo.urlValid) {
|
|
3424
|
+
console.warn("[WalletConnect Tron] \u26A0\uFE0F Invalid URL in metadata:", appUrl);
|
|
3425
|
+
}
|
|
3426
|
+
if (!metadataInfo.iconsValid) {
|
|
3427
|
+
console.warn("[WalletConnect Tron] \u26A0\uFE0F Invalid icons in metadata:", icons);
|
|
3428
|
+
}
|
|
3429
|
+
console.log("[WalletConnect Tron] Initializing wallet...", {
|
|
3430
|
+
network,
|
|
3431
|
+
chainId,
|
|
3432
|
+
note: "If no wallets are in WalletConnect Explorer for TRON, QR code will be displayed for scanning"
|
|
3433
|
+
});
|
|
3434
|
+
_WalletConnectTronAdapter.walletInstance = new walletconnectTron.WalletConnectWallet({
|
|
3435
|
+
network,
|
|
3436
|
+
options: {
|
|
3437
|
+
projectId: this.projectId,
|
|
3438
|
+
metadata: {
|
|
3439
|
+
name: "Enclave Wallet SDK",
|
|
3440
|
+
description: "Multi-chain wallet adapter for Enclave",
|
|
3441
|
+
url: appUrl,
|
|
3442
|
+
icons
|
|
3443
|
+
}
|
|
3444
|
+
},
|
|
3445
|
+
// Theme configuration
|
|
3446
|
+
themeMode: "light",
|
|
3447
|
+
themeVariables: {
|
|
3448
|
+
"--w3m-z-index": 1e4
|
|
3449
|
+
// Ensure modal appears above Telegram UI
|
|
3450
|
+
},
|
|
3451
|
+
// Web3Modal configuration for recommended wallets
|
|
3452
|
+
// According to official docs: https://developers.tron.network/docs/walletconnect-tron
|
|
3453
|
+
// Note: If no wallets are registered in WalletConnect Explorer for TRON,
|
|
3454
|
+
// explorerRecommendedWalletIds will have no effect, and QR code will be shown instead.
|
|
3455
|
+
// @ts-ignore - web3ModalConfig is supported but may not be in TypeScript types
|
|
3456
|
+
web3ModalConfig: {
|
|
3457
|
+
themeMode: "light",
|
|
3458
|
+
themeVariables: {
|
|
3459
|
+
"--w3m-z-index": 1e4
|
|
3460
|
+
},
|
|
3461
|
+
/**
|
|
3462
|
+
* Recommended Wallets are fetched from WalletConnect explore api:
|
|
3463
|
+
* https://walletconnect.com/explorer?type=wallet&version=2
|
|
3464
|
+
*
|
|
3465
|
+
* IMPORTANT: If wallets are not registered in Explorer for TRON, this list will be ignored.
|
|
3466
|
+
* The AppKit will show a QR code instead, which users can scan with any WalletConnect-compatible wallet.
|
|
3467
|
+
*
|
|
3468
|
+
* Wallet IDs (for reference, may not work if not in Explorer):
|
|
3469
|
+
* - TokenPocket: 20459438007b75f4f4acb98bf29aa3b800550309646d375da5fd4aac6c2a2c66
|
|
3470
|
+
* - TronLink: 1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369
|
|
3471
|
+
*/
|
|
3472
|
+
explorerRecommendedWalletIds: [
|
|
3473
|
+
// These IDs are kept for when wallets register in WalletConnect Explorer
|
|
3474
|
+
// Currently, if no TRON wallets are in Explorer, QR code will be shown
|
|
3475
|
+
"20459438007b75f4f4acb98bf29aa3b800550309646d375da5fd4aac6c2a2c66",
|
|
3476
|
+
// TokenPocket
|
|
3477
|
+
"1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369",
|
|
3478
|
+
// TronLink
|
|
3479
|
+
"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0"
|
|
3480
|
+
// TokenPocket (backup)
|
|
3481
|
+
]
|
|
3482
|
+
}
|
|
3483
|
+
});
|
|
3484
|
+
_WalletConnectTronAdapter.walletProjectId = this.projectId;
|
|
3485
|
+
}
|
|
3486
|
+
/**
|
|
3487
|
+
* Connect wallet
|
|
3488
|
+
*/
|
|
3489
|
+
async connect(chainId) {
|
|
3490
|
+
if (typeof window === "undefined") {
|
|
3491
|
+
throw new Error("WalletConnect requires a browser environment");
|
|
3492
|
+
}
|
|
3493
|
+
const currentState = this.state;
|
|
3494
|
+
if (currentState === "connecting" /* CONNECTING */) {
|
|
3495
|
+
console.warn("[WalletConnect Tron] Connection already in progress, waiting...");
|
|
3496
|
+
let attempts = 0;
|
|
3497
|
+
while (this.state === "connecting" /* CONNECTING */ && attempts < 50) {
|
|
3498
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
3499
|
+
attempts++;
|
|
3500
|
+
}
|
|
3501
|
+
if (this.state === "connected" /* CONNECTED */ && this.currentAccount) {
|
|
3502
|
+
return this.currentAccount;
|
|
3503
|
+
}
|
|
3504
|
+
if (this.state === "connecting" /* CONNECTING */) {
|
|
3505
|
+
throw new Error("Connection timeout - previous connection attempt is still pending");
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
if (this.state === "connected" /* CONNECTED */ && this.currentAccount) {
|
|
3509
|
+
return this.currentAccount;
|
|
3510
|
+
}
|
|
3511
|
+
try {
|
|
3512
|
+
this.setState("connecting" /* CONNECTING */);
|
|
3513
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID : chainId || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID;
|
|
3514
|
+
if (!_WalletConnectTronAdapter.walletInstance || _WalletConnectTronAdapter.walletProjectId !== this.projectId) {
|
|
3515
|
+
this.initializeWallet(targetChainId);
|
|
3516
|
+
}
|
|
3517
|
+
this.wallet = _WalletConnectTronAdapter.walletInstance;
|
|
3518
|
+
if (!this.wallet) {
|
|
3519
|
+
throw new Error("Failed to initialize WalletConnect wallet");
|
|
3520
|
+
}
|
|
3521
|
+
let network = walletconnectTron.WalletConnectChainID.Mainnet;
|
|
3522
|
+
if (targetChainId === 195) {
|
|
3523
|
+
network = walletconnectTron.WalletConnectChainID.Mainnet;
|
|
3524
|
+
} else if (targetChainId === 201910292) {
|
|
3525
|
+
network = walletconnectTron.WalletConnectChainID.Shasta;
|
|
3526
|
+
} else if (targetChainId === 2494104990) {
|
|
3527
|
+
network = walletconnectTron.WalletConnectChainID.Nile;
|
|
3528
|
+
}
|
|
3529
|
+
let address;
|
|
3530
|
+
try {
|
|
3531
|
+
console.log("[WalletConnect Tron] Attempting to connect...", {
|
|
3532
|
+
network,
|
|
3533
|
+
chainId: targetChainId,
|
|
3534
|
+
isTelegram: this.isTelegramMiniApp(),
|
|
3535
|
+
projectId: this.projectId
|
|
3536
|
+
});
|
|
3537
|
+
const result = await this.wallet.connect();
|
|
3538
|
+
address = result.address;
|
|
3539
|
+
if (!address) {
|
|
3540
|
+
throw new ConnectionRejectedError(this.type);
|
|
3541
|
+
}
|
|
3542
|
+
console.log("[WalletConnect Tron] Connection successful:", {
|
|
3543
|
+
address,
|
|
3544
|
+
network,
|
|
3545
|
+
chainId: targetChainId,
|
|
3546
|
+
isTelegram: this.isTelegramMiniApp()
|
|
3547
|
+
});
|
|
3548
|
+
} catch (error) {
|
|
3549
|
+
const errorMessage = error.message || String(error);
|
|
3550
|
+
const errorCode = error.code || error.error?.code;
|
|
3551
|
+
const origin = typeof window !== "undefined" && window.location ? window.location.origin : "";
|
|
3552
|
+
let detailedError = errorMessage;
|
|
3553
|
+
if (error.error) {
|
|
3554
|
+
if (typeof error.error === "string") {
|
|
3555
|
+
detailedError = error.error;
|
|
3556
|
+
} else if (error.error.message) {
|
|
3557
|
+
detailedError = error.error.message;
|
|
3558
|
+
} else if (error.error.data) {
|
|
3559
|
+
detailedError = JSON.stringify(error.error.data);
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
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");
|
|
3563
|
+
const isTimeout = errorMessage.includes("timeout") || errorMessage.includes("\u8D85\u65F6") || errorCode === "TIMEOUT";
|
|
3564
|
+
const isRejected = errorMessage.includes("rejected") || errorMessage.includes("\u62D2\u7EDD") || errorCode === 4001;
|
|
3565
|
+
const isOriginNotAllowed = errorCode === 3e3 || /origin not allowed/i.test(errorMessage) || /Unauthorized:\s*origin not allowed/i.test(errorMessage);
|
|
3566
|
+
const currentMetadata = this.wallet ? {
|
|
3567
|
+
// Try to get metadata from wallet instance if available
|
|
3568
|
+
projectId: this.projectId,
|
|
3569
|
+
network
|
|
3570
|
+
} : null;
|
|
3571
|
+
const errorDetails = {
|
|
3572
|
+
error: errorMessage,
|
|
3573
|
+
detailedError,
|
|
3574
|
+
code: errorCode,
|
|
3575
|
+
isTelegram: this.isTelegramMiniApp(),
|
|
3576
|
+
network,
|
|
3577
|
+
chainId: targetChainId,
|
|
3578
|
+
projectId: this.projectId,
|
|
3579
|
+
metadata: currentMetadata,
|
|
3580
|
+
// Get URL from window.location if available
|
|
3581
|
+
currentUrl: typeof window !== "undefined" ? window.location.href : "N/A",
|
|
3582
|
+
telegramPlatform: typeof window !== "undefined" && window.Telegram?.WebApp?.platform || "N/A",
|
|
3583
|
+
errorType: isNoWalletFound ? "NO_WALLET_FOUND" : isTimeout ? "TIMEOUT" : isRejected ? "REJECTED" : "UNKNOWN"
|
|
3584
|
+
};
|
|
3585
|
+
console.error("[WalletConnect Tron] Connection error - Full details:", errorDetails);
|
|
3586
|
+
console.error("[WalletConnect Tron] Error object:", error);
|
|
3587
|
+
console.error("[WalletConnect Tron] Error stack:", error.stack);
|
|
3588
|
+
if (isNoWalletFound) {
|
|
3589
|
+
const noWalletErrorDetails = [
|
|
3590
|
+
`
|
|
3591
|
+
=== WalletConnect Tron: No Matching Wallet Found ===`,
|
|
3592
|
+
`Error: ${errorMessage}`,
|
|
3593
|
+
`Detailed: ${detailedError}`,
|
|
3594
|
+
`Code: ${errorCode || "N/A"}`,
|
|
3595
|
+
``,
|
|
3596
|
+
`Environment:`,
|
|
3597
|
+
` - Telegram Mini App: ${this.isTelegramMiniApp() ? "Yes" : "No"}`,
|
|
3598
|
+
` - Platform: ${errorDetails.telegramPlatform}`,
|
|
3599
|
+
` - Current URL: ${errorDetails.currentUrl}`,
|
|
3600
|
+
``,
|
|
3601
|
+
`Configuration:`,
|
|
3602
|
+
` - Project ID: ${this.projectId ? "Set" : "Missing"}`,
|
|
3603
|
+
` - Network: ${network}`,
|
|
3604
|
+
` - Chain ID: ${targetChainId}`,
|
|
3605
|
+
` - Metadata URL: ${typeof window !== "undefined" ? window.location.origin : "N/A"}`,
|
|
3606
|
+
``,
|
|
3607
|
+
`Possible Causes:`,
|
|
3608
|
+
` 1. No WalletConnect-compatible wallet (TokenPocket, etc.) installed on device`,
|
|
3609
|
+
` 2. Wallet app not opened or not responding to deep link (wc://)`,
|
|
3610
|
+
` 3. Deep link handling issue in Telegram Mini App environment`,
|
|
3611
|
+
` 4. WalletConnect session timeout (user took too long to approve)`,
|
|
3612
|
+
` 5. Network connectivity issue preventing WalletConnect relay connection`,
|
|
3613
|
+
``,
|
|
3614
|
+
`Solutions:`,
|
|
3615
|
+
` 1. Ensure TokenPocket or other WalletConnect-compatible wallet is installed`,
|
|
3616
|
+
` 2. Try opening the wallet app manually before connecting`,
|
|
3617
|
+
` 3. In Telegram Mini App, ensure the deep link popup is not blocked`,
|
|
3618
|
+
` 4. Try connecting again (may need to wait a few seconds)`,
|
|
3619
|
+
` 5. Check network connection and WalletConnect relay server accessibility`,
|
|
3620
|
+
``,
|
|
3621
|
+
`For more details, see the error object logged above.`,
|
|
3622
|
+
`===========================================
|
|
3623
|
+
`
|
|
3624
|
+
].join("\n");
|
|
3625
|
+
console.error(noWalletErrorDetails);
|
|
3626
|
+
throw new ConnectionRejectedError(
|
|
3627
|
+
`WalletConnect Tron: \u6CA1\u6709\u627E\u5230\u652F\u6301\u7684\u94B1\u5305 (No matching wallet found)
|
|
3628
|
+
|
|
3629
|
+
\u53EF\u80FD\u7684\u539F\u56E0\uFF1A
|
|
3630
|
+
1. \u8BBE\u5907\u4E0A\u672A\u5B89\u88C5\u652F\u6301 WalletConnect \u7684\u94B1\u5305\uFF08\u5982 TokenPocket\uFF09
|
|
3631
|
+
2. \u94B1\u5305\u5E94\u7528\u672A\u6253\u5F00\u6216\u672A\u54CD\u5E94 deep link (wc://)
|
|
3632
|
+
3. \u5728 Telegram Mini App \u4E2D\uFF0Cdeep link \u5904\u7406\u53EF\u80FD\u6709\u95EE\u9898
|
|
3633
|
+
4. \u8FDE\u63A5\u8D85\u65F6\uFF08\u7528\u6237\u672A\u53CA\u65F6\u6279\u51C6\uFF09
|
|
3634
|
+
5. \u7F51\u7EDC\u8FDE\u63A5\u95EE\u9898
|
|
3635
|
+
|
|
3636
|
+
\u89E3\u51B3\u65B9\u6848\uFF1A
|
|
3637
|
+
1. \u786E\u4FDD\u5DF2\u5B89\u88C5 TokenPocket \u6216\u5176\u4ED6\u652F\u6301 WalletConnect \u7684\u94B1\u5305
|
|
3638
|
+
2. \u5C1D\u8BD5\u624B\u52A8\u6253\u5F00\u94B1\u5305\u5E94\u7528\u540E\u518D\u8FDE\u63A5
|
|
3639
|
+
3. \u5728 Telegram Mini App \u4E2D\uFF0C\u786E\u4FDD deep link \u5F39\u7A97\u672A\u88AB\u963B\u6B62
|
|
3640
|
+
4. \u7A0D\u7B49\u51E0\u79D2\u540E\u91CD\u8BD5\u8FDE\u63A5
|
|
3641
|
+
5. \u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C WalletConnect \u4E2D\u7EE7\u670D\u52A1\u5668\u53EF\u8BBF\u95EE\u6027
|
|
3642
|
+
|
|
3643
|
+
\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\u65E5\u5FD7\u3002`
|
|
3644
|
+
);
|
|
3645
|
+
}
|
|
3646
|
+
if (errorMessage.includes("Invalid") || errorMessage.includes("Configuration") || errorMessage.includes("App Config") || errorMessage.includes("Invalid App")) {
|
|
3647
|
+
const configErrorDetails = [
|
|
3648
|
+
`
|
|
3649
|
+
=== WalletConnect Tron Configuration Error ===`,
|
|
3650
|
+
`Error: ${errorMessage}`,
|
|
3651
|
+
`Detailed: ${detailedError}`,
|
|
3652
|
+
`Code: ${errorCode || "N/A"}`,
|
|
3653
|
+
`
|
|
3654
|
+
Environment:`,
|
|
3655
|
+
` - Telegram Mini App: ${this.isTelegramMiniApp() ? "Yes" : "No"}`,
|
|
3656
|
+
` - Platform: ${errorDetails.telegramPlatform}`,
|
|
3657
|
+
` - Current URL: ${errorDetails.currentUrl}`,
|
|
3658
|
+
`
|
|
3659
|
+
Configuration:`,
|
|
3660
|
+
` - Project ID: ${this.projectId ? "Set" : "Missing"}`,
|
|
3661
|
+
` - Network: ${network}`,
|
|
3662
|
+
` - Chain ID: ${targetChainId}`,
|
|
3663
|
+
`
|
|
3664
|
+
Possible Causes:`,
|
|
3665
|
+
` 1. Deep link (wc://) handling issue in Telegram Mini App`,
|
|
3666
|
+
` 2. Invalid metadata configuration (URL or icons not accessible)`,
|
|
3667
|
+
` 3. Network/chainId mismatch`,
|
|
3668
|
+
` 4. WalletConnect project ID not configured correctly`,
|
|
3669
|
+
` 5. Domain not added to WalletConnect Cloud allowlist`,
|
|
3670
|
+
`
|
|
3671
|
+
Please check:`,
|
|
3672
|
+
` - WalletConnect Project ID is valid and active`,
|
|
3673
|
+
` - Domain is added to WalletConnect Cloud allowlist (for serveo.net, etc.)`,
|
|
3674
|
+
` - Metadata URL is accessible: Check console for metadata logs`,
|
|
3675
|
+
` - Icons are accessible: Check console for icon URLs`,
|
|
3676
|
+
` - Network matches chainId: Expected ${network} for chainId ${targetChainId}`,
|
|
3677
|
+
`
|
|
3678
|
+
For more details, see the error object logged above.`,
|
|
3679
|
+
`===========================================
|
|
3680
|
+
`
|
|
3681
|
+
].join("\n");
|
|
3682
|
+
console.error(configErrorDetails);
|
|
3683
|
+
throw new ConfigurationError(
|
|
3684
|
+
`WalletConnect Tron connection failed: ${errorMessage}
|
|
3685
|
+
|
|
3686
|
+
Configuration Details:
|
|
3687
|
+
- Telegram Mini App: ${this.isTelegramMiniApp() ? "Yes" : "No"}
|
|
3688
|
+
- Platform: ${errorDetails.telegramPlatform}
|
|
3689
|
+
- Origin: ${origin || "(unknown)"}
|
|
3690
|
+
- Project ID: ${this.projectId ? "Set" : "Missing"}
|
|
3691
|
+
- Network: ${network}
|
|
3692
|
+
- Chain ID: ${targetChainId}
|
|
3693
|
+
|
|
3694
|
+
This "Invalid App Configuration" error may be caused by:
|
|
3695
|
+
1. Deep link (wc://) handling issue in Telegram Mini App
|
|
3696
|
+
2. Invalid metadata configuration (URL or icons)
|
|
3697
|
+
3. Network/chainId mismatch
|
|
3698
|
+
4. Domain not added to WalletConnect Cloud allowlist
|
|
3699
|
+
|
|
3700
|
+
Please check the console for detailed error information.`
|
|
3701
|
+
);
|
|
3702
|
+
}
|
|
3703
|
+
if (isOriginNotAllowed) {
|
|
3704
|
+
throw new ConfigurationError(
|
|
3705
|
+
`WalletConnect Tron relayer rejected this origin (code 3000: Unauthorized: origin not allowed).
|
|
3706
|
+
|
|
3707
|
+
Fix:
|
|
3708
|
+
1) Open WalletConnect Cloud \u2192 your project (${this.projectId})
|
|
3709
|
+
2) Add this site origin to the allowlist:
|
|
3710
|
+
- ${origin || "(unknown origin)"}
|
|
3711
|
+
|
|
3712
|
+
Common dev origins to allow:
|
|
3713
|
+
- http://localhost:5173
|
|
3714
|
+
- http://192.168.0.221:5173 (your LAN dev URL)
|
|
3715
|
+
- https://wallet-test.enclave-hq.com (your Cloudflare Tunnel/custom domain)
|
|
3716
|
+
|
|
3717
|
+
Original error: ${errorMessage}`
|
|
3718
|
+
);
|
|
3719
|
+
}
|
|
3720
|
+
if (isTimeout) {
|
|
3721
|
+
throw new ConnectionRejectedError(
|
|
3722
|
+
`WalletConnect Tron connection timeout. Please try again and ensure your wallet app is open and ready.`
|
|
3723
|
+
);
|
|
3724
|
+
}
|
|
3725
|
+
if (isRejected) {
|
|
3726
|
+
throw new ConnectionRejectedError(this.type);
|
|
3727
|
+
}
|
|
3728
|
+
throw error;
|
|
3729
|
+
}
|
|
3730
|
+
this.currentAddress = address;
|
|
3731
|
+
const account = {
|
|
3732
|
+
universalAddress: createUniversalAddress(targetChainId, address),
|
|
3733
|
+
nativeAddress: address,
|
|
3734
|
+
chainId: targetChainId,
|
|
3735
|
+
chainType: exports.ChainType.TRON,
|
|
3736
|
+
isActive: true
|
|
3737
|
+
};
|
|
3738
|
+
this.setState("connected" /* CONNECTED */);
|
|
3739
|
+
this.setAccount(account);
|
|
3740
|
+
this.setupEventListeners();
|
|
3741
|
+
return account;
|
|
3742
|
+
} catch (error) {
|
|
3743
|
+
this.setState("error" /* ERROR */);
|
|
3744
|
+
this.setAccount(null);
|
|
3745
|
+
this.currentAddress = null;
|
|
3746
|
+
if (error.message?.includes("rejected") || error.code === 4001) {
|
|
3747
|
+
throw new ConnectionRejectedError(this.type);
|
|
3748
|
+
}
|
|
3749
|
+
throw error;
|
|
3750
|
+
}
|
|
3751
|
+
}
|
|
3752
|
+
/**
|
|
3753
|
+
* Disconnect wallet
|
|
3754
|
+
*/
|
|
3755
|
+
async disconnect() {
|
|
3756
|
+
this.removeEventListeners();
|
|
3757
|
+
if (this.wallet) {
|
|
3758
|
+
try {
|
|
3759
|
+
await this.wallet.disconnect();
|
|
3760
|
+
} catch (error) {
|
|
3761
|
+
console.warn("[WalletConnect Tron] Error during disconnect:", error);
|
|
3762
|
+
}
|
|
3763
|
+
}
|
|
3764
|
+
this.wallet = null;
|
|
3765
|
+
this.currentAddress = null;
|
|
3766
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
3767
|
+
this.setAccount(null);
|
|
3768
|
+
this.emitDisconnected();
|
|
3769
|
+
}
|
|
3770
|
+
/**
|
|
3771
|
+
* Sign message
|
|
3772
|
+
*/
|
|
3773
|
+
async signMessage(message) {
|
|
3774
|
+
this.ensureConnected();
|
|
3775
|
+
try {
|
|
3776
|
+
if (!this.wallet) {
|
|
3777
|
+
throw new Error("Wallet not initialized");
|
|
3778
|
+
}
|
|
3779
|
+
const signature = await this.wallet.signMessage(message);
|
|
3780
|
+
if (typeof signature === "string") {
|
|
3781
|
+
return signature;
|
|
3782
|
+
} else if (signature && typeof signature === "object") {
|
|
3783
|
+
if ("signature" in signature) {
|
|
3784
|
+
return signature.signature;
|
|
3785
|
+
} else if ("result" in signature) {
|
|
3786
|
+
return signature.result;
|
|
3787
|
+
} else {
|
|
3788
|
+
return JSON.stringify(signature);
|
|
3789
|
+
}
|
|
3790
|
+
}
|
|
3791
|
+
throw new Error("Invalid signature format returned from wallet");
|
|
3792
|
+
} catch (error) {
|
|
3793
|
+
console.error("[WalletConnect Tron] Sign message error:", error);
|
|
3794
|
+
let errorMessage = "Unknown error";
|
|
3795
|
+
if (typeof error === "string") {
|
|
3796
|
+
errorMessage = error;
|
|
3797
|
+
} else if (error?.message) {
|
|
3798
|
+
errorMessage = error.message;
|
|
3799
|
+
} else if (error?.error?.message) {
|
|
3800
|
+
errorMessage = error.error.message;
|
|
3801
|
+
} else {
|
|
3802
|
+
try {
|
|
3803
|
+
errorMessage = JSON.stringify(error);
|
|
3804
|
+
} catch {
|
|
3805
|
+
errorMessage = String(error);
|
|
3806
|
+
}
|
|
3807
|
+
}
|
|
3808
|
+
if (errorMessage?.includes("rejected") || errorMessage?.includes("declined") || errorMessage?.includes("User rejected") || error?.code === 4001 || error?.code === "USER_REJECTED" || error?.error?.code === 4001) {
|
|
3809
|
+
throw new SignatureRejectedError();
|
|
3810
|
+
}
|
|
3811
|
+
if (errorMessage?.includes("not supported") || errorMessage?.includes("method not found") || errorMessage?.includes("Method not found") || error?.code === -32601 || error?.error?.code === -32601) {
|
|
3812
|
+
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.");
|
|
3813
|
+
}
|
|
3814
|
+
throw new Error(`WalletConnect Tron sign message failed: ${errorMessage}`);
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
/**
|
|
3818
|
+
* Sign transaction
|
|
3819
|
+
*
|
|
3820
|
+
* @param transaction - Tron transaction object
|
|
3821
|
+
* Can be created using TronWeb (if available) or any TRON transaction builder
|
|
3822
|
+
* Format: { raw_data: {...}, raw_data_hex: "...", txID: "..." }
|
|
3823
|
+
* @returns Signed transaction object or signature
|
|
3824
|
+
*/
|
|
3825
|
+
async signTransaction(transaction) {
|
|
3826
|
+
this.ensureConnected();
|
|
3827
|
+
try {
|
|
3828
|
+
if (!this.wallet) {
|
|
3829
|
+
throw new Error("Wallet not initialized");
|
|
3830
|
+
}
|
|
3831
|
+
if (!transaction) {
|
|
3832
|
+
throw new Error("Transaction object is required");
|
|
3833
|
+
}
|
|
3834
|
+
console.log("[WalletConnect Tron] Signing transaction:", {
|
|
3835
|
+
hasRawData: !!transaction.raw_data,
|
|
3836
|
+
hasRawDataHex: !!transaction.raw_data_hex,
|
|
3837
|
+
hasTxID: !!transaction.txID
|
|
3838
|
+
});
|
|
3839
|
+
const result = await this.wallet.signTransaction(transaction);
|
|
3840
|
+
if (typeof result === "string") {
|
|
3841
|
+
return result;
|
|
3842
|
+
} else if (result && typeof result === "object") {
|
|
3843
|
+
if ("txID" in result && typeof result.txID === "string") {
|
|
3844
|
+
return result.txID;
|
|
3845
|
+
} else if ("txid" in result && typeof result.txid === "string") {
|
|
3846
|
+
return result.txid;
|
|
3847
|
+
} else if ("signature" in result) {
|
|
3848
|
+
return JSON.stringify(result);
|
|
3849
|
+
} else {
|
|
3850
|
+
return JSON.stringify(result);
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
throw new Error("Invalid signature format returned from wallet");
|
|
3854
|
+
} catch (error) {
|
|
3855
|
+
console.error("[WalletConnect Tron] Sign transaction error:", error);
|
|
3856
|
+
let errorMessage = "Unknown error";
|
|
3857
|
+
if (typeof error === "string") {
|
|
3858
|
+
errorMessage = error;
|
|
3859
|
+
} else if (error?.message) {
|
|
3860
|
+
errorMessage = error.message;
|
|
3861
|
+
} else if (error?.error?.message) {
|
|
3862
|
+
errorMessage = error.error.message;
|
|
3863
|
+
} else if (error?.data?.message) {
|
|
3864
|
+
errorMessage = error.data.message;
|
|
3865
|
+
} else {
|
|
3866
|
+
try {
|
|
3867
|
+
errorMessage = JSON.stringify(error);
|
|
3868
|
+
} catch {
|
|
3869
|
+
errorMessage = String(error);
|
|
3870
|
+
}
|
|
3871
|
+
}
|
|
3872
|
+
if (errorMessage?.includes("rejected") || errorMessage?.includes("declined") || errorMessage?.includes("User rejected") || error?.code === 4001 || error?.code === "USER_REJECTED" || error?.error?.code === 4001) {
|
|
3873
|
+
throw new SignatureRejectedError("Transaction signature was rejected by user");
|
|
3874
|
+
}
|
|
3875
|
+
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) {
|
|
3876
|
+
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.");
|
|
3877
|
+
}
|
|
3878
|
+
throw new Error(`WalletConnect Tron sign transaction failed: ${errorMessage}`);
|
|
3879
|
+
}
|
|
3880
|
+
}
|
|
3881
|
+
/**
|
|
3882
|
+
* Read contract (not supported by WalletConnect)
|
|
3883
|
+
*/
|
|
3884
|
+
async readContract(_params) {
|
|
3885
|
+
this.ensureConnected();
|
|
3886
|
+
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.");
|
|
3887
|
+
}
|
|
3888
|
+
/**
|
|
3889
|
+
* Write contract (not yet implemented)
|
|
3890
|
+
*/
|
|
3891
|
+
async writeContract(_params) {
|
|
3892
|
+
throw new Error("Contract write not yet implemented for WalletConnect Tron");
|
|
3893
|
+
}
|
|
3894
|
+
/**
|
|
3895
|
+
* Estimate gas (not yet implemented)
|
|
3896
|
+
*/
|
|
3897
|
+
async estimateGas(_params) {
|
|
3898
|
+
throw new Error("Gas estimation not yet implemented for WalletConnect Tron");
|
|
3899
|
+
}
|
|
3900
|
+
/**
|
|
3901
|
+
* Wait for transaction (not yet implemented)
|
|
3902
|
+
*/
|
|
3903
|
+
async waitForTransaction(_txHash, _confirmations) {
|
|
3904
|
+
throw new Error("Transaction waiting not yet implemented for WalletConnect Tron");
|
|
3905
|
+
}
|
|
3906
|
+
/**
|
|
3907
|
+
* Setup event listeners
|
|
3908
|
+
*/
|
|
3909
|
+
setupEventListeners() {
|
|
3910
|
+
if (!this.wallet) {
|
|
3911
|
+
return;
|
|
3912
|
+
}
|
|
3913
|
+
this.wallet.on("accountsChanged", (accounts) => {
|
|
3914
|
+
if (accounts && accounts.length > 0 && accounts[0] !== this.currentAddress) {
|
|
3915
|
+
const newAddress = accounts[0];
|
|
3916
|
+
this.currentAddress = newAddress;
|
|
3917
|
+
if (this.currentAccount) {
|
|
3918
|
+
const newAccount = {
|
|
3919
|
+
...this.currentAccount,
|
|
3920
|
+
nativeAddress: newAddress,
|
|
3921
|
+
universalAddress: createUniversalAddress(this.currentAccount.chainId, newAddress)
|
|
3922
|
+
};
|
|
3923
|
+
this.setAccount(newAccount);
|
|
3924
|
+
this.emit("accountChanged", newAccount);
|
|
3925
|
+
}
|
|
3926
|
+
} else if (!accounts || accounts.length === 0) {
|
|
3927
|
+
this.disconnect();
|
|
3928
|
+
}
|
|
3929
|
+
});
|
|
3930
|
+
this.wallet.on("disconnect", () => {
|
|
3931
|
+
this.disconnect();
|
|
3932
|
+
});
|
|
3933
|
+
}
|
|
3934
|
+
/**
|
|
3935
|
+
* Remove event listeners
|
|
3936
|
+
*/
|
|
3937
|
+
removeEventListeners() {
|
|
3938
|
+
if (!this.wallet) {
|
|
3939
|
+
return;
|
|
3940
|
+
}
|
|
3941
|
+
this.wallet.removeAllListeners("accountsChanged");
|
|
3942
|
+
this.wallet.removeAllListeners("disconnect");
|
|
3943
|
+
}
|
|
3944
|
+
/**
|
|
3945
|
+
* Get provider (returns wallet instance)
|
|
3946
|
+
*/
|
|
3947
|
+
getProvider() {
|
|
3948
|
+
return this.wallet;
|
|
3949
|
+
}
|
|
3950
|
+
/**
|
|
3951
|
+
* Clear static wallet instance (for complete cleanup)
|
|
3952
|
+
*/
|
|
3953
|
+
static clearWalletInstance() {
|
|
3954
|
+
if (_WalletConnectTronAdapter.walletInstance) {
|
|
3955
|
+
_WalletConnectTronAdapter.walletInstance.disconnect().catch(() => {
|
|
3956
|
+
});
|
|
3957
|
+
_WalletConnectTronAdapter.walletInstance = null;
|
|
3958
|
+
_WalletConnectTronAdapter.walletProjectId = null;
|
|
3959
|
+
}
|
|
3960
|
+
}
|
|
3961
|
+
};
|
|
3962
|
+
// Tron 主网链 ID
|
|
3963
|
+
_WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID = 195;
|
|
3964
|
+
// Static wallet instance to avoid multiple initializations
|
|
3965
|
+
_WalletConnectTronAdapter.walletInstance = null;
|
|
3966
|
+
_WalletConnectTronAdapter.walletProjectId = null;
|
|
3967
|
+
var WalletConnectTronAdapter = _WalletConnectTronAdapter;
|
|
3968
|
+
|
|
3969
|
+
// src/adapters/deep-link/adapter.ts
|
|
3970
|
+
init_types();
|
|
3971
|
+
var DeepLinkProviderType = /* @__PURE__ */ ((DeepLinkProviderType2) => {
|
|
3972
|
+
DeepLinkProviderType2["TOKENPOCKET"] = "tokenpocket";
|
|
3973
|
+
DeepLinkProviderType2["TRONLINK"] = "tronlink";
|
|
3974
|
+
DeepLinkProviderType2["IMTOKEN"] = "imtoken";
|
|
3975
|
+
DeepLinkProviderType2["METAMASK"] = "metamask";
|
|
3976
|
+
DeepLinkProviderType2["OKX"] = "okx";
|
|
3977
|
+
return DeepLinkProviderType2;
|
|
3978
|
+
})(DeepLinkProviderType || {});
|
|
3979
|
+
var _DeepLinkAdapter = class _DeepLinkAdapter extends WalletAdapter {
|
|
3980
|
+
constructor(config) {
|
|
3981
|
+
super();
|
|
3982
|
+
this.currentChainId = null;
|
|
3983
|
+
this.currentChainType = null;
|
|
3984
|
+
this.provider = this.createProvider(config);
|
|
3985
|
+
this.name = `${this.provider.name} (Deep Link)`;
|
|
3986
|
+
this.icon = this.provider.icon;
|
|
3987
|
+
if (this.provider.supportedChainTypes.includes(exports.ChainType.EVM)) {
|
|
3988
|
+
this.chainType = exports.ChainType.EVM;
|
|
3989
|
+
this.type = "deep-link-evm" /* DEEP_LINK_EVM */;
|
|
3990
|
+
} else if (this.provider.supportedChainTypes.includes(exports.ChainType.TRON)) {
|
|
3991
|
+
this.chainType = exports.ChainType.TRON;
|
|
3992
|
+
this.type = "deep-link-tron" /* DEEP_LINK_TRON */;
|
|
3993
|
+
} else {
|
|
3994
|
+
this.chainType = exports.ChainType.EVM;
|
|
3995
|
+
this.type = "deep-link-evm" /* DEEP_LINK_EVM */;
|
|
3996
|
+
}
|
|
3997
|
+
if (typeof window !== "undefined") {
|
|
3998
|
+
this.setupCallbackHandler();
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
/**
|
|
4002
|
+
* Create provider instance based on type
|
|
4003
|
+
*/
|
|
4004
|
+
createProvider(config) {
|
|
4005
|
+
switch (config.providerType) {
|
|
4006
|
+
case "tokenpocket" /* TOKENPOCKET */: {
|
|
4007
|
+
const { TokenPocketDeepLinkProvider: TokenPocketDeepLinkProvider2 } = (init_tokenpocket(), __toCommonJS(tokenpocket_exports));
|
|
4008
|
+
return new TokenPocketDeepLinkProvider2({
|
|
4009
|
+
callbackUrl: config.callbackUrl,
|
|
4010
|
+
callbackSchema: config.callbackSchema
|
|
4011
|
+
});
|
|
4012
|
+
}
|
|
4013
|
+
case "tronlink" /* TRONLINK */: {
|
|
4014
|
+
const { TronLinkDeepLinkProvider: TronLinkDeepLinkProvider2 } = (init_tronlink(), __toCommonJS(tronlink_exports));
|
|
4015
|
+
return new TronLinkDeepLinkProvider2();
|
|
4016
|
+
}
|
|
4017
|
+
case "imtoken" /* IMTOKEN */: {
|
|
4018
|
+
const { ImTokenDeepLinkProvider: ImTokenDeepLinkProvider2 } = (init_imtoken(), __toCommonJS(imtoken_exports));
|
|
4019
|
+
return new ImTokenDeepLinkProvider2({
|
|
4020
|
+
callbackUrl: config.callbackUrl,
|
|
4021
|
+
callbackSchema: config.callbackSchema
|
|
4022
|
+
});
|
|
4023
|
+
}
|
|
4024
|
+
case "metamask" /* METAMASK */: {
|
|
4025
|
+
const { MetaMaskDeepLinkProvider: MetaMaskDeepLinkProvider2 } = (init_metamask(), __toCommonJS(metamask_exports));
|
|
4026
|
+
return new MetaMaskDeepLinkProvider2();
|
|
4027
|
+
}
|
|
4028
|
+
case "okx" /* OKX */: {
|
|
4029
|
+
const { OKXDeepLinkProvider: OKXDeepLinkProvider2 } = (init_okx(), __toCommonJS(okx_exports));
|
|
4030
|
+
return new OKXDeepLinkProvider2();
|
|
4031
|
+
}
|
|
4032
|
+
default:
|
|
4033
|
+
throw new Error(`Unsupported deep link provider type: ${config.providerType}`);
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
/**
|
|
4037
|
+
* Setup callback handler for deep link results
|
|
4038
|
+
*/
|
|
4039
|
+
setupCallbackHandler() {
|
|
4040
|
+
if (typeof window === "undefined") {
|
|
4041
|
+
return;
|
|
4042
|
+
}
|
|
4043
|
+
const handleUrlChange = () => {
|
|
4044
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
4045
|
+
const result = this.provider.parseCallbackResult(urlParams);
|
|
4046
|
+
if (result.actionId && _DeepLinkAdapter.pendingActions.has(result.actionId)) {
|
|
4047
|
+
const callback = _DeepLinkAdapter.pendingActions.get(result.actionId);
|
|
4048
|
+
if (result.error) {
|
|
4049
|
+
callback.reject(new Error(result.error));
|
|
4050
|
+
} else if (result.result) {
|
|
4051
|
+
callback.resolve(result.result);
|
|
4052
|
+
}
|
|
4053
|
+
_DeepLinkAdapter.pendingActions.delete(result.actionId);
|
|
4054
|
+
}
|
|
4055
|
+
};
|
|
4056
|
+
window.addEventListener("popstate", handleUrlChange);
|
|
4057
|
+
window.addEventListener("hashchange", handleUrlChange);
|
|
4058
|
+
handleUrlChange();
|
|
4059
|
+
}
|
|
4060
|
+
/**
|
|
4061
|
+
* Check if deep link is available
|
|
4062
|
+
*/
|
|
4063
|
+
async isAvailable() {
|
|
4064
|
+
return this.provider.isAvailable();
|
|
4065
|
+
}
|
|
4066
|
+
/**
|
|
4067
|
+
* Connect to wallet via deep link
|
|
4068
|
+
*
|
|
4069
|
+
* Note: Deep links typically don't support persistent connections
|
|
4070
|
+
* This method may throw ConnectionRejectedError as deep links are
|
|
4071
|
+
* primarily used for signing operations, not connection
|
|
4072
|
+
*/
|
|
4073
|
+
async connect(chainId) {
|
|
4074
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] : chainId || 1;
|
|
4075
|
+
let chainType;
|
|
4076
|
+
if (targetChainId === 195) {
|
|
4077
|
+
chainType = exports.ChainType.TRON;
|
|
4078
|
+
} else {
|
|
4079
|
+
chainType = exports.ChainType.EVM;
|
|
4080
|
+
}
|
|
4081
|
+
if (!this.provider.supportedChainTypes.includes(chainType)) {
|
|
4082
|
+
throw new Error(
|
|
4083
|
+
`Provider ${this.provider.name} does not support chain type ${chainType}`
|
|
4084
|
+
);
|
|
4085
|
+
}
|
|
4086
|
+
if (this.provider.buildConnectLink) {
|
|
4087
|
+
const linkInfo = this.provider.buildConnectLink({
|
|
4088
|
+
chainId: targetChainId,
|
|
4089
|
+
chainType
|
|
4090
|
+
});
|
|
4091
|
+
if (linkInfo.actionId) {
|
|
4092
|
+
return new Promise((resolve, reject) => {
|
|
4093
|
+
_DeepLinkAdapter.pendingActions.set(linkInfo.actionId, {
|
|
4094
|
+
resolve: (result) => {
|
|
4095
|
+
const address = result?.address || result?.account || result;
|
|
4096
|
+
if (!address || typeof address !== "string") {
|
|
4097
|
+
reject(new ConnectionRejectedError("Invalid connection result: no address found"));
|
|
4098
|
+
return;
|
|
4099
|
+
}
|
|
4100
|
+
const account = {
|
|
4101
|
+
universalAddress: createUniversalAddress(targetChainId, address),
|
|
4102
|
+
nativeAddress: address,
|
|
4103
|
+
chainId: targetChainId,
|
|
4104
|
+
chainType,
|
|
4105
|
+
isActive: true
|
|
4106
|
+
};
|
|
4107
|
+
this.setState("connected" /* CONNECTED */);
|
|
4108
|
+
this.setAccount(account);
|
|
4109
|
+
this.emit("connected", account);
|
|
4110
|
+
resolve(account);
|
|
4111
|
+
},
|
|
4112
|
+
reject: (error) => {
|
|
4113
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
4114
|
+
reject(error);
|
|
4115
|
+
}
|
|
4116
|
+
});
|
|
4117
|
+
window.location.href = linkInfo.url;
|
|
4118
|
+
setTimeout(() => {
|
|
4119
|
+
if (_DeepLinkAdapter.pendingActions.has(linkInfo.actionId)) {
|
|
4120
|
+
_DeepLinkAdapter.pendingActions.delete(linkInfo.actionId);
|
|
4121
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
4122
|
+
reject(new ConnectionRejectedError("Deep link connection timeout"));
|
|
4123
|
+
}
|
|
4124
|
+
}, 3e4);
|
|
4125
|
+
});
|
|
4126
|
+
} else {
|
|
4127
|
+
window.location.href = linkInfo.url;
|
|
4128
|
+
throw new ConnectionRejectedError(
|
|
4129
|
+
"Deep link connection initiated. Please complete the connection in your wallet app."
|
|
4130
|
+
);
|
|
4131
|
+
}
|
|
4132
|
+
} else {
|
|
4133
|
+
throw new ConnectionRejectedError(
|
|
4134
|
+
`Deep link connection is not supported by ${this.provider.name}. Deep links are primarily used for signing operations.`
|
|
4135
|
+
);
|
|
4136
|
+
}
|
|
4137
|
+
}
|
|
4138
|
+
/**
|
|
4139
|
+
* Disconnect from wallet
|
|
4140
|
+
*/
|
|
4141
|
+
async disconnect() {
|
|
4142
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
4143
|
+
this.setAccount(null);
|
|
4144
|
+
this.currentChainId = null;
|
|
4145
|
+
this.currentChainType = null;
|
|
4146
|
+
this.emitDisconnected();
|
|
4147
|
+
}
|
|
4148
|
+
/**
|
|
4149
|
+
* Sign a message
|
|
4150
|
+
*/
|
|
4151
|
+
async signMessage(message) {
|
|
4152
|
+
this.ensureConnected();
|
|
4153
|
+
if (!this.currentChainId || !this.currentChainType) {
|
|
4154
|
+
throw new WalletNotConnectedError(this.type);
|
|
4155
|
+
}
|
|
4156
|
+
const linkInfo = this.provider.buildSignMessageLink({
|
|
4157
|
+
message,
|
|
4158
|
+
chainId: this.currentChainId,
|
|
4159
|
+
chainType: this.currentChainType
|
|
4160
|
+
});
|
|
4161
|
+
if (linkInfo.callbackSchema || linkInfo.callbackUrl) {
|
|
4162
|
+
return new Promise((resolve, reject) => {
|
|
4163
|
+
_DeepLinkAdapter.pendingActions.set(linkInfo.actionId, { resolve, reject });
|
|
4164
|
+
window.location.href = linkInfo.url;
|
|
4165
|
+
setTimeout(() => {
|
|
4166
|
+
if (_DeepLinkAdapter.pendingActions.has(linkInfo.actionId)) {
|
|
4167
|
+
_DeepLinkAdapter.pendingActions.delete(linkInfo.actionId);
|
|
4168
|
+
reject(new SignatureRejectedError("Message signature timeout"));
|
|
4169
|
+
}
|
|
4170
|
+
}, 3e4);
|
|
4171
|
+
});
|
|
4172
|
+
} else {
|
|
4173
|
+
window.location.href = linkInfo.url;
|
|
4174
|
+
throw new SignatureRejectedError(
|
|
4175
|
+
"Deep link signature initiated. Please complete the signature in your wallet app."
|
|
4176
|
+
);
|
|
4177
|
+
}
|
|
4178
|
+
}
|
|
4179
|
+
/**
|
|
4180
|
+
* Sign a transaction
|
|
4181
|
+
*/
|
|
4182
|
+
async signTransaction(transaction) {
|
|
4183
|
+
this.ensureConnected();
|
|
4184
|
+
if (!this.currentChainId || !this.currentChainType) {
|
|
4185
|
+
throw new WalletNotConnectedError(this.type);
|
|
4186
|
+
}
|
|
4187
|
+
const linkInfo = this.provider.buildSignTransactionLink({
|
|
4188
|
+
transaction,
|
|
4189
|
+
chainId: this.currentChainId,
|
|
4190
|
+
chainType: this.currentChainType
|
|
4191
|
+
});
|
|
4192
|
+
if (linkInfo.callbackSchema || linkInfo.callbackUrl) {
|
|
4193
|
+
return new Promise((resolve, reject) => {
|
|
4194
|
+
_DeepLinkAdapter.pendingActions.set(linkInfo.actionId, { resolve, reject });
|
|
4195
|
+
window.location.href = linkInfo.url;
|
|
4196
|
+
setTimeout(() => {
|
|
4197
|
+
if (_DeepLinkAdapter.pendingActions.has(linkInfo.actionId)) {
|
|
4198
|
+
_DeepLinkAdapter.pendingActions.delete(linkInfo.actionId);
|
|
4199
|
+
reject(new SignatureRejectedError("Transaction signature timeout"));
|
|
4200
|
+
}
|
|
4201
|
+
}, 3e4);
|
|
4202
|
+
});
|
|
4203
|
+
} else {
|
|
4204
|
+
window.location.href = linkInfo.url;
|
|
4205
|
+
throw new SignatureRejectedError(
|
|
4206
|
+
"Deep link transaction signature initiated. Please complete the signature in your wallet app."
|
|
4207
|
+
);
|
|
4208
|
+
}
|
|
4209
|
+
}
|
|
4210
|
+
/**
|
|
4211
|
+
* Get provider (not applicable for deep links)
|
|
4212
|
+
*/
|
|
4213
|
+
getProvider() {
|
|
4214
|
+
return null;
|
|
4215
|
+
}
|
|
4216
|
+
/**
|
|
4217
|
+
* Static method to handle callback from wallet apps
|
|
4218
|
+
* This can be called from anywhere in the application
|
|
4219
|
+
*/
|
|
4220
|
+
static handleCallback() {
|
|
4221
|
+
if (typeof window === "undefined") {
|
|
4222
|
+
return;
|
|
4223
|
+
}
|
|
4224
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
4225
|
+
const actionId = urlParams.get("actionId");
|
|
4226
|
+
if (actionId && _DeepLinkAdapter.pendingActions.has(actionId)) {
|
|
4227
|
+
const callback = _DeepLinkAdapter.pendingActions.get(actionId);
|
|
4228
|
+
const result = urlParams.get("result");
|
|
4229
|
+
const error = urlParams.get("error");
|
|
4230
|
+
if (error) {
|
|
4231
|
+
callback.reject(new Error(error));
|
|
4232
|
+
} else if (result) {
|
|
4233
|
+
try {
|
|
4234
|
+
const parsedResult = JSON.parse(decodeURIComponent(result));
|
|
4235
|
+
callback.resolve(parsedResult);
|
|
4236
|
+
} catch (e) {
|
|
4237
|
+
callback.resolve(result);
|
|
4238
|
+
}
|
|
4239
|
+
}
|
|
4240
|
+
_DeepLinkAdapter.pendingActions.delete(actionId);
|
|
4241
|
+
}
|
|
4242
|
+
}
|
|
4243
|
+
/**
|
|
4244
|
+
* Set current account (called after successful connection)
|
|
4245
|
+
*/
|
|
4246
|
+
setAccount(account) {
|
|
4247
|
+
this.currentAccount = account;
|
|
4248
|
+
if (account) {
|
|
4249
|
+
this.currentChainId = account.chainId;
|
|
4250
|
+
this.currentChainType = account.chainType;
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
/**
|
|
4254
|
+
* Emit disconnected event
|
|
4255
|
+
*/
|
|
4256
|
+
emitDisconnected() {
|
|
4257
|
+
this.emit("disconnected");
|
|
4258
|
+
}
|
|
4259
|
+
};
|
|
4260
|
+
// Static map to store pending actions across all instances
|
|
4261
|
+
// Key: actionId, Value: { resolve, reject }
|
|
4262
|
+
_DeepLinkAdapter.pendingActions = /* @__PURE__ */ new Map();
|
|
4263
|
+
var DeepLinkAdapter = _DeepLinkAdapter;
|
|
4264
|
+
|
|
4265
|
+
// src/core/adapter-registry.ts
|
|
4266
|
+
var AdapterRegistry = class {
|
|
4267
|
+
constructor(config = {}) {
|
|
4268
|
+
this.adapters = /* @__PURE__ */ new Map();
|
|
4269
|
+
this.config = config;
|
|
4270
|
+
this.registerDefaultAdapters();
|
|
4271
|
+
}
|
|
4272
|
+
/**
|
|
4273
|
+
* Register default adapters
|
|
4274
|
+
*/
|
|
4275
|
+
registerDefaultAdapters() {
|
|
4276
|
+
this.register("metamask" /* METAMASK */, () => new MetaMaskAdapter());
|
|
4277
|
+
this.register("private-key" /* PRIVATE_KEY */, () => new EVMPrivateKeyAdapter());
|
|
4278
|
+
if (this.config.walletConnectProjectId) {
|
|
4279
|
+
this.register(
|
|
4280
|
+
"walletconnect" /* WALLETCONNECT */,
|
|
4281
|
+
() => new WalletConnectAdapter(this.config.walletConnectProjectId)
|
|
4282
|
+
);
|
|
4283
|
+
this.register(
|
|
4284
|
+
"walletconnect-tron" /* WALLETCONNECT_TRON */,
|
|
4285
|
+
() => new WalletConnectTronAdapter(this.config.walletConnectProjectId)
|
|
4286
|
+
);
|
|
4287
|
+
}
|
|
4288
|
+
this.register("tronlink" /* TRONLINK */, () => new TronLinkAdapter());
|
|
4289
|
+
this.register(
|
|
4290
|
+
"deep-link-evm" /* DEEP_LINK_EVM */,
|
|
4291
|
+
() => new DeepLinkAdapter({
|
|
4292
|
+
providerType: "tokenpocket" /* TOKENPOCKET */
|
|
4293
|
+
})
|
|
4294
|
+
);
|
|
4295
|
+
this.register(
|
|
4296
|
+
"deep-link-tron" /* DEEP_LINK_TRON */,
|
|
4297
|
+
() => new DeepLinkAdapter({
|
|
4298
|
+
providerType: "tokenpocket" /* TOKENPOCKET */
|
|
4299
|
+
})
|
|
4300
|
+
);
|
|
4301
|
+
}
|
|
4302
|
+
/**
|
|
4303
|
+
* Register adapter
|
|
4304
|
+
*/
|
|
4305
|
+
register(type, factory) {
|
|
4306
|
+
this.adapters.set(type, factory);
|
|
4307
|
+
}
|
|
4308
|
+
/**
|
|
4309
|
+
* Get adapter
|
|
4310
|
+
*/
|
|
4311
|
+
getAdapter(type) {
|
|
4312
|
+
const factory = this.adapters.get(type);
|
|
4313
|
+
if (!factory) {
|
|
4314
|
+
return null;
|
|
4315
|
+
}
|
|
4316
|
+
return factory();
|
|
4317
|
+
}
|
|
4318
|
+
/**
|
|
4319
|
+
* Check if adapter is registered
|
|
4320
|
+
*/
|
|
4321
|
+
has(type) {
|
|
4322
|
+
return this.adapters.has(type);
|
|
4323
|
+
}
|
|
4324
|
+
/**
|
|
4325
|
+
* Get all registered adapter types
|
|
4326
|
+
*/
|
|
4327
|
+
getRegisteredTypes() {
|
|
4328
|
+
return Array.from(this.adapters.keys());
|
|
4329
|
+
}
|
|
4330
|
+
/**
|
|
4331
|
+
* 根据链类型获取适配器类型列表
|
|
4332
|
+
*/
|
|
4333
|
+
getAdapterTypesByChainType(chainType) {
|
|
4334
|
+
const types = [];
|
|
4335
|
+
for (const type of this.adapters.keys()) {
|
|
4336
|
+
const adapter = this.getAdapter(type);
|
|
4337
|
+
if (adapter && adapter.chainType === chainType) {
|
|
4338
|
+
types.push(type);
|
|
4339
|
+
}
|
|
4340
|
+
}
|
|
4341
|
+
return types;
|
|
4342
|
+
}
|
|
4343
|
+
};
|
|
4344
|
+
|
|
4345
|
+
// src/core/wallet-manager.ts
|
|
4346
|
+
init_types();
|
|
4347
|
+
var QRCodeSignStatus = /* @__PURE__ */ ((QRCodeSignStatus2) => {
|
|
4348
|
+
QRCodeSignStatus2["WAITING"] = "waiting";
|
|
4349
|
+
QRCodeSignStatus2["PENDING"] = "pending";
|
|
4350
|
+
QRCodeSignStatus2["SUCCESS"] = "success";
|
|
4351
|
+
QRCodeSignStatus2["FAILED"] = "failed";
|
|
4352
|
+
QRCodeSignStatus2["TIMEOUT"] = "timeout";
|
|
4353
|
+
QRCodeSignStatus2["CANCELLED"] = "cancelled";
|
|
4354
|
+
return QRCodeSignStatus2;
|
|
4355
|
+
})(QRCodeSignStatus || {});
|
|
4356
|
+
var QRCodeSigner = class {
|
|
4357
|
+
constructor(config) {
|
|
4358
|
+
this.pollTimer = null;
|
|
4359
|
+
this.timeoutTimer = null;
|
|
4360
|
+
this.status = "waiting" /* WAITING */;
|
|
4361
|
+
this.qrCodeDataUrl = null;
|
|
4362
|
+
this.result = null;
|
|
4363
|
+
this.config = {
|
|
4364
|
+
requestId: config.requestId,
|
|
4365
|
+
requestUrl: config.requestUrl,
|
|
4366
|
+
pollUrl: config.pollUrl || "",
|
|
4367
|
+
pollInterval: config.pollInterval || 2e3,
|
|
4368
|
+
timeout: config.timeout || 3e5,
|
|
4369
|
+
// 5 minutes
|
|
4370
|
+
pollFn: config.pollFn
|
|
4371
|
+
};
|
|
4372
|
+
}
|
|
4373
|
+
/**
|
|
4374
|
+
* 生成二维码图片(Data URL)
|
|
4375
|
+
*/
|
|
4376
|
+
async generateQRCode(options) {
|
|
4377
|
+
if (this.qrCodeDataUrl) {
|
|
4378
|
+
return this.qrCodeDataUrl;
|
|
4379
|
+
}
|
|
4380
|
+
try {
|
|
4381
|
+
const qrCodeOptions = {
|
|
4382
|
+
width: options?.width || 300,
|
|
4383
|
+
margin: options?.margin || 2,
|
|
4384
|
+
color: {
|
|
4385
|
+
dark: options?.color?.dark || "#000000",
|
|
4386
|
+
light: options?.color?.light || "#FFFFFF"
|
|
4387
|
+
}
|
|
4388
|
+
};
|
|
4389
|
+
this.qrCodeDataUrl = await QRCode__default.default.toDataURL(this.config.requestUrl, qrCodeOptions);
|
|
4390
|
+
return this.qrCodeDataUrl;
|
|
4391
|
+
} catch (error) {
|
|
4392
|
+
throw new Error(`Failed to generate QR code: ${error instanceof Error ? error.message : String(error)}`);
|
|
4393
|
+
}
|
|
4394
|
+
}
|
|
4395
|
+
/**
|
|
4396
|
+
* 开始轮询签名结果
|
|
4397
|
+
*/
|
|
4398
|
+
async startPolling(onStatusChange, onResult) {
|
|
4399
|
+
if (this.status === "success" /* SUCCESS */ && this.result?.signature) {
|
|
4400
|
+
return this.result.signature;
|
|
4401
|
+
}
|
|
4402
|
+
if (this.status === "cancelled" /* CANCELLED */ || this.status === "timeout" /* TIMEOUT */) {
|
|
4403
|
+
throw new SignatureRejectedError("Signature request was cancelled or timed out");
|
|
4404
|
+
}
|
|
4405
|
+
this.timeoutTimer = setTimeout(() => {
|
|
4406
|
+
this.stopPolling();
|
|
4407
|
+
this.status = "timeout" /* TIMEOUT */;
|
|
4408
|
+
onStatusChange?.(this.status);
|
|
4409
|
+
throw new SignatureRejectedError("Signature request timed out");
|
|
4410
|
+
}, this.config.timeout);
|
|
4411
|
+
return new Promise((resolve, reject) => {
|
|
4412
|
+
const poll = async () => {
|
|
4413
|
+
try {
|
|
4414
|
+
let result = null;
|
|
4415
|
+
if (this.config.pollFn) {
|
|
4416
|
+
result = await this.config.pollFn(this.config.requestId);
|
|
4417
|
+
} else if (this.config.pollUrl) {
|
|
4418
|
+
result = await this.defaultPoll(this.config.requestId);
|
|
4419
|
+
} else {
|
|
4420
|
+
return;
|
|
4421
|
+
}
|
|
4422
|
+
if (result?.completed) {
|
|
4423
|
+
this.stopPolling();
|
|
4424
|
+
this.result = result;
|
|
4425
|
+
if (result.signature) {
|
|
4426
|
+
this.status = "success" /* SUCCESS */;
|
|
4427
|
+
onStatusChange?.(this.status);
|
|
4428
|
+
onResult?.(result);
|
|
4429
|
+
resolve(result.signature);
|
|
4430
|
+
} else if (result.error) {
|
|
4431
|
+
this.status = "failed" /* FAILED */;
|
|
4432
|
+
onStatusChange?.(this.status);
|
|
4433
|
+
reject(new SignatureRejectedError(result.error));
|
|
4434
|
+
}
|
|
4435
|
+
} else if (result) {
|
|
4436
|
+
if (this.status === "waiting" /* WAITING */) {
|
|
4437
|
+
this.status = "pending" /* PENDING */;
|
|
4438
|
+
onStatusChange?.(this.status);
|
|
4439
|
+
}
|
|
4440
|
+
this.pollTimer = setTimeout(poll, this.config.pollInterval);
|
|
4441
|
+
} else {
|
|
4442
|
+
this.pollTimer = setTimeout(poll, this.config.pollInterval);
|
|
4443
|
+
}
|
|
4444
|
+
} catch (error) {
|
|
4445
|
+
this.stopPolling();
|
|
4446
|
+
this.status = "failed" /* FAILED */;
|
|
4447
|
+
onStatusChange?.(this.status);
|
|
4448
|
+
reject(error);
|
|
4449
|
+
}
|
|
4450
|
+
};
|
|
4451
|
+
poll();
|
|
4452
|
+
});
|
|
4453
|
+
}
|
|
4454
|
+
/**
|
|
4455
|
+
* 默认 HTTP 轮询函数
|
|
4456
|
+
*/
|
|
4457
|
+
async defaultPoll(requestId) {
|
|
4458
|
+
if (!this.config.pollUrl) {
|
|
4459
|
+
return null;
|
|
4460
|
+
}
|
|
4461
|
+
try {
|
|
4462
|
+
const url = `${this.config.pollUrl}?requestId=${encodeURIComponent(requestId)}`;
|
|
4463
|
+
const response = await fetch(url, {
|
|
4464
|
+
method: "GET",
|
|
4465
|
+
headers: {
|
|
4466
|
+
"Content-Type": "application/json"
|
|
4467
|
+
}
|
|
4468
|
+
});
|
|
4469
|
+
if (!response.ok) {
|
|
4470
|
+
if (response.status === 404) {
|
|
4471
|
+
return null;
|
|
4472
|
+
}
|
|
4473
|
+
throw new NetworkError(`Poll request failed: ${response.statusText}`);
|
|
4474
|
+
}
|
|
4475
|
+
const data = await response.json();
|
|
4476
|
+
return {
|
|
4477
|
+
completed: data.completed === true,
|
|
4478
|
+
signature: data.signature,
|
|
4479
|
+
error: data.error,
|
|
4480
|
+
signer: data.signer
|
|
4481
|
+
};
|
|
4482
|
+
} catch (error) {
|
|
4483
|
+
if (error instanceof NetworkError) {
|
|
4484
|
+
throw error;
|
|
4485
|
+
}
|
|
4486
|
+
return null;
|
|
4487
|
+
}
|
|
4488
|
+
}
|
|
4489
|
+
/**
|
|
4490
|
+
* 停止轮询
|
|
4491
|
+
*/
|
|
4492
|
+
stopPolling() {
|
|
4493
|
+
if (this.pollTimer) {
|
|
4494
|
+
clearTimeout(this.pollTimer);
|
|
4495
|
+
this.pollTimer = null;
|
|
4496
|
+
}
|
|
4497
|
+
if (this.timeoutTimer) {
|
|
4498
|
+
clearTimeout(this.timeoutTimer);
|
|
4499
|
+
this.timeoutTimer = null;
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
/**
|
|
4503
|
+
* 取消签名请求
|
|
4504
|
+
*/
|
|
4505
|
+
cancel() {
|
|
4506
|
+
this.stopPolling();
|
|
4507
|
+
this.status = "cancelled" /* CANCELLED */;
|
|
4508
|
+
}
|
|
4509
|
+
/**
|
|
4510
|
+
* 获取当前状态
|
|
4511
|
+
*/
|
|
4512
|
+
getStatus() {
|
|
4513
|
+
return this.status;
|
|
4514
|
+
}
|
|
4515
|
+
/**
|
|
4516
|
+
* 获取二维码 URL
|
|
4517
|
+
*/
|
|
4518
|
+
getQRCodeUrl() {
|
|
4519
|
+
return this.config.requestUrl;
|
|
4520
|
+
}
|
|
4521
|
+
/**
|
|
4522
|
+
* 获取结果
|
|
4523
|
+
*/
|
|
4524
|
+
getResult() {
|
|
4525
|
+
return this.result;
|
|
4526
|
+
}
|
|
4527
|
+
/**
|
|
4528
|
+
* 清理资源
|
|
4529
|
+
*/
|
|
4530
|
+
cleanup() {
|
|
4531
|
+
this.stopPolling();
|
|
4532
|
+
this.qrCodeDataUrl = null;
|
|
4533
|
+
this.result = null;
|
|
4534
|
+
this.status = "waiting" /* WAITING */;
|
|
4535
|
+
}
|
|
4536
|
+
};
|
|
4537
|
+
|
|
4538
|
+
// src/core/wallet-manager.ts
|
|
4539
|
+
var WalletManager = class extends TypedEventEmitter {
|
|
4540
|
+
constructor(config = {}) {
|
|
4541
|
+
super();
|
|
1701
4542
|
// Primary wallet
|
|
1702
4543
|
this.primaryWallet = null;
|
|
1703
4544
|
// Connected wallet pool
|
|
@@ -1709,9 +4550,15 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
1709
4550
|
defaultTronChainId: config.defaultTronChainId ?? 195,
|
|
1710
4551
|
walletConnectProjectId: config.walletConnectProjectId ?? ""
|
|
1711
4552
|
};
|
|
1712
|
-
this.registry = new AdapterRegistry();
|
|
4553
|
+
this.registry = new AdapterRegistry(this.config);
|
|
1713
4554
|
}
|
|
1714
4555
|
// ===== Connection Management =====
|
|
4556
|
+
/**
|
|
4557
|
+
* Check if adapter is registered for a wallet type
|
|
4558
|
+
*/
|
|
4559
|
+
hasAdapter(type) {
|
|
4560
|
+
return this.registry.has(type);
|
|
4561
|
+
}
|
|
1715
4562
|
/**
|
|
1716
4563
|
* Connect primary wallet
|
|
1717
4564
|
*/
|
|
@@ -1778,7 +4625,7 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
1778
4625
|
this.connectedWallets.delete(chainType);
|
|
1779
4626
|
this.primaryWallet = null;
|
|
1780
4627
|
if (this.config.enableStorage) {
|
|
1781
|
-
this.
|
|
4628
|
+
this.clearStorage();
|
|
1782
4629
|
}
|
|
1783
4630
|
this.emit("disconnected");
|
|
1784
4631
|
}
|
|
@@ -1867,6 +4714,35 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
1867
4714
|
}
|
|
1868
4715
|
return adapter.signMessage(message);
|
|
1869
4716
|
}
|
|
4717
|
+
/**
|
|
4718
|
+
* Create QR code signer for message signing
|
|
4719
|
+
*
|
|
4720
|
+
* This method creates a QR code signer that can be used to display a QR code
|
|
4721
|
+
* for users to scan with their wallet app to sign a message.
|
|
4722
|
+
*
|
|
4723
|
+
* @param message - Message to sign
|
|
4724
|
+
* @param config - QR code signer configuration
|
|
4725
|
+
* @returns QRCodeSigner instance
|
|
4726
|
+
*
|
|
4727
|
+
* @example
|
|
4728
|
+
* ```typescript
|
|
4729
|
+
* const signer = walletManager.createQRCodeSigner('Hello World', {
|
|
4730
|
+
* requestId: 'sign-123',
|
|
4731
|
+
* requestUrl: 'https://example.com/sign?requestId=sign-123&message=Hello%20World',
|
|
4732
|
+
* pollUrl: 'https://api.example.com/sign/status',
|
|
4733
|
+
* })
|
|
4734
|
+
*
|
|
4735
|
+
* const qrCodeUrl = await signer.generateQRCode()
|
|
4736
|
+
* const signature = await signer.startPolling()
|
|
4737
|
+
* ```
|
|
4738
|
+
*/
|
|
4739
|
+
createQRCodeSigner(message, config) {
|
|
4740
|
+
return new QRCodeSigner({
|
|
4741
|
+
...config,
|
|
4742
|
+
// Encode message in request URL if not already encoded
|
|
4743
|
+
requestUrl: config.requestUrl.includes(encodeURIComponent(message)) ? config.requestUrl : `${config.requestUrl}${config.requestUrl.includes("?") ? "&" : "?"}message=${encodeURIComponent(message)}`
|
|
4744
|
+
});
|
|
4745
|
+
}
|
|
1870
4746
|
/**
|
|
1871
4747
|
* Sign TypedData (EVM only)
|
|
1872
4748
|
*/
|
|
@@ -2125,7 +5001,7 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
2125
5001
|
return null;
|
|
2126
5002
|
}
|
|
2127
5003
|
console.debug("[WalletManager] Wallet is available, attempting restoration");
|
|
2128
|
-
if (adapter.chainType === ChainType.EVM && data.primaryWalletType === "metamask" /* METAMASK */) {
|
|
5004
|
+
if (adapter.chainType === exports.ChainType.EVM && data.primaryWalletType === "metamask" /* METAMASK */) {
|
|
2129
5005
|
try {
|
|
2130
5006
|
const provider = typeof window !== "undefined" ? window.ethereum : null;
|
|
2131
5007
|
if (provider) {
|
|
@@ -2162,7 +5038,7 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
2162
5038
|
console.debug("Silent connection failed, trying normal connection:", silentError);
|
|
2163
5039
|
}
|
|
2164
5040
|
}
|
|
2165
|
-
if (adapter.chainType === ChainType.TRON && data.primaryWalletType === "tronlink" /* TRONLINK */) {
|
|
5041
|
+
if (adapter.chainType === exports.ChainType.TRON && data.primaryWalletType === "tronlink" /* TRONLINK */) {
|
|
2166
5042
|
try {
|
|
2167
5043
|
const tronWeb = adapter.getTronWeb?.();
|
|
2168
5044
|
if (tronWeb && tronWeb.defaultAddress?.base58) {
|
|
@@ -2177,6 +5053,29 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
2177
5053
|
console.debug("Silent TronLink connection failed:", silentError);
|
|
2178
5054
|
}
|
|
2179
5055
|
}
|
|
5056
|
+
if (data.primaryWalletType === "walletconnect-tron" /* WALLETCONNECT_TRON */) {
|
|
5057
|
+
try {
|
|
5058
|
+
const wcAdapter = adapter;
|
|
5059
|
+
if (typeof wcAdapter.restoreSession === "function") {
|
|
5060
|
+
console.debug("[WalletManager] Attempting to restore WalletConnect Tron session...");
|
|
5061
|
+
const account2 = await wcAdapter.restoreSession(data.primaryChainId);
|
|
5062
|
+
if (account2) {
|
|
5063
|
+
console.debug("[WalletManager] WalletConnect Tron session restored successfully");
|
|
5064
|
+
this.setPrimaryWallet(adapter);
|
|
5065
|
+
this.connectedWallets.set(adapter.chainType, adapter);
|
|
5066
|
+
this.setupAdapterListeners(adapter, true);
|
|
5067
|
+
this.emit("accountChanged", account2);
|
|
5068
|
+
return account2;
|
|
5069
|
+
} else {
|
|
5070
|
+
console.debug("[WalletManager] No valid WalletConnect Tron session found");
|
|
5071
|
+
return null;
|
|
5072
|
+
}
|
|
5073
|
+
}
|
|
5074
|
+
} catch (restoreError) {
|
|
5075
|
+
console.debug("[WalletManager] WalletConnect Tron restore failed:", restoreError);
|
|
5076
|
+
return null;
|
|
5077
|
+
}
|
|
5078
|
+
}
|
|
2180
5079
|
const account = await adapter.connect(data.primaryChainId);
|
|
2181
5080
|
this.setPrimaryWallet(adapter);
|
|
2182
5081
|
this.connectedWallets.set(adapter.chainType, adapter);
|
|
@@ -2223,7 +5122,466 @@ var WalletManager = class extends TypedEventEmitter {
|
|
|
2223
5122
|
}
|
|
2224
5123
|
};
|
|
2225
5124
|
|
|
5125
|
+
// src/index.ts
|
|
5126
|
+
init_types();
|
|
5127
|
+
init_tokenpocket();
|
|
5128
|
+
init_tronlink();
|
|
5129
|
+
init_imtoken();
|
|
5130
|
+
init_metamask();
|
|
5131
|
+
init_okx();
|
|
5132
|
+
|
|
5133
|
+
// src/adapters/tron/deep-link.ts
|
|
5134
|
+
init_types();
|
|
5135
|
+
var DeepLinkWalletType = /* @__PURE__ */ ((DeepLinkWalletType2) => {
|
|
5136
|
+
DeepLinkWalletType2["TOKENPOCKET"] = "tokenpocket";
|
|
5137
|
+
DeepLinkWalletType2["TRONLINK"] = "tronlink";
|
|
5138
|
+
return DeepLinkWalletType2;
|
|
5139
|
+
})(DeepLinkWalletType || {});
|
|
5140
|
+
var _TronDeepLinkAdapter = class _TronDeepLinkAdapter extends WalletAdapter {
|
|
5141
|
+
constructor(walletType = "tokenpocket" /* TOKENPOCKET */, options) {
|
|
5142
|
+
super();
|
|
5143
|
+
this.type = "tronlink" /* TRONLINK */;
|
|
5144
|
+
// Reuse TRONLINK type for now
|
|
5145
|
+
this.chainType = exports.ChainType.TRON;
|
|
5146
|
+
this.pendingActions = /* @__PURE__ */ new Map();
|
|
5147
|
+
this.walletType = walletType;
|
|
5148
|
+
this.callbackUrl = options?.callbackUrl;
|
|
5149
|
+
this.callbackSchema = options?.callbackSchema;
|
|
5150
|
+
if (walletType === "tokenpocket" /* TOKENPOCKET */) {
|
|
5151
|
+
this.name = "TokenPocket (Deep Link)";
|
|
5152
|
+
this.icon = "https://tokenpocket.pro/icon.png";
|
|
5153
|
+
} else if (walletType === "tronlink" /* TRONLINK */) {
|
|
5154
|
+
this.name = "TronLink (Deep Link)";
|
|
5155
|
+
this.icon = "https://www.tronlink.org/static/logoIcon.svg";
|
|
5156
|
+
} else {
|
|
5157
|
+
this.name = "TRON Deep Link";
|
|
5158
|
+
this.icon = "https://www.tronlink.org/static/logoIcon.svg";
|
|
5159
|
+
}
|
|
5160
|
+
if (walletType === "tokenpocket" /* TOKENPOCKET */ && typeof window !== "undefined") {
|
|
5161
|
+
this.setupCallbackHandler();
|
|
5162
|
+
}
|
|
5163
|
+
}
|
|
5164
|
+
/**
|
|
5165
|
+
* Setup callback handler for TokenPocket deep link results
|
|
5166
|
+
*
|
|
5167
|
+
* According to TokenPocket docs:
|
|
5168
|
+
* - callbackUrl: Wallet sends result to this URL (server-side callback)
|
|
5169
|
+
* - callbackSchema: Wallet launches H5 app through this schema (client-side callback)
|
|
5170
|
+
*
|
|
5171
|
+
* For H5 apps, we use callbackSchema to receive results in the same page
|
|
5172
|
+
*/
|
|
5173
|
+
setupCallbackHandler() {
|
|
5174
|
+
if (typeof window === "undefined") {
|
|
5175
|
+
return;
|
|
5176
|
+
}
|
|
5177
|
+
document.addEventListener("visibilitychange", () => {
|
|
5178
|
+
if (document.visibilityState === "visible") {
|
|
5179
|
+
console.log("[TronDeepLink] Page became visible, user may have returned from wallet app");
|
|
5180
|
+
this.checkCallbackFromUrl();
|
|
5181
|
+
}
|
|
5182
|
+
});
|
|
5183
|
+
this.checkCallbackFromUrl();
|
|
5184
|
+
}
|
|
5185
|
+
/**
|
|
5186
|
+
* Check if callback result is in URL parameters
|
|
5187
|
+
* TokenPocket may append callback results to URL when using callbackSchema
|
|
5188
|
+
*/
|
|
5189
|
+
checkCallbackFromUrl() {
|
|
5190
|
+
if (typeof window === "undefined") {
|
|
5191
|
+
return;
|
|
5192
|
+
}
|
|
5193
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
5194
|
+
const actionId = urlParams.get("actionId");
|
|
5195
|
+
const result = urlParams.get("result");
|
|
5196
|
+
const error = urlParams.get("error");
|
|
5197
|
+
if (actionId && this.pendingActions.has(actionId)) {
|
|
5198
|
+
const { resolve, reject } = this.pendingActions.get(actionId);
|
|
5199
|
+
if (error) {
|
|
5200
|
+
reject(new Error(error));
|
|
5201
|
+
} else if (result) {
|
|
5202
|
+
try {
|
|
5203
|
+
const parsedResult = JSON.parse(decodeURIComponent(result));
|
|
5204
|
+
resolve(parsedResult);
|
|
5205
|
+
} catch (e) {
|
|
5206
|
+
resolve(result);
|
|
5207
|
+
}
|
|
5208
|
+
}
|
|
5209
|
+
this.pendingActions.delete(actionId);
|
|
5210
|
+
const newUrl = window.location.pathname;
|
|
5211
|
+
window.history.replaceState({}, "", newUrl);
|
|
5212
|
+
}
|
|
5213
|
+
}
|
|
5214
|
+
/**
|
|
5215
|
+
* Check if deep link is available (mobile device or Telegram Mini App)
|
|
5216
|
+
*
|
|
5217
|
+
* Note: In Telegram Mini App, we're more lenient - even if platform detection
|
|
5218
|
+
* fails, deep links may still work, so the caller should handle Telegram Mini App
|
|
5219
|
+
* separately if needed.
|
|
5220
|
+
*/
|
|
5221
|
+
async isAvailable() {
|
|
5222
|
+
if (typeof window === "undefined") {
|
|
5223
|
+
return false;
|
|
5224
|
+
}
|
|
5225
|
+
const isTelegramMiniApp = !!(window.Telegram && window.Telegram.WebApp);
|
|
5226
|
+
if (isTelegramMiniApp) {
|
|
5227
|
+
const platform = window.Telegram.WebApp.platform || "unknown";
|
|
5228
|
+
const version = window.Telegram.WebApp.version || "unknown";
|
|
5229
|
+
console.log(`[TronDeepLink] Telegram Mini App detected, platform: ${platform}, version: ${version}`);
|
|
5230
|
+
if (platform === "unknown") {
|
|
5231
|
+
const userAgent = navigator.userAgent || "";
|
|
5232
|
+
if (/iPhone|iPad|iPod/i.test(userAgent)) {
|
|
5233
|
+
console.log(`[TronDeepLink] Detected iOS from user agent`);
|
|
5234
|
+
} else if (/Android/i.test(userAgent)) {
|
|
5235
|
+
console.log(`[TronDeepLink] Detected Android from user agent`);
|
|
5236
|
+
}
|
|
5237
|
+
}
|
|
5238
|
+
return true;
|
|
5239
|
+
}
|
|
5240
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
5241
|
+
navigator.userAgent
|
|
5242
|
+
);
|
|
5243
|
+
return isMobile;
|
|
5244
|
+
}
|
|
5245
|
+
/**
|
|
5246
|
+
* Connect wallet via deep link
|
|
5247
|
+
*
|
|
5248
|
+
* IMPORTANT: Deep links for TRON wallets are primarily for SIGNING, not connection.
|
|
5249
|
+
* TokenPocket and TronLink deep links support:
|
|
5250
|
+
* - Signing transactions: tron:signTransaction-version=1.0&protocol=TokenPocket&network=tron&chain_id=195&data={...}
|
|
5251
|
+
* - Signing messages: tron:signMessage-version=1.0&protocol=TokenPocket&network=tron&chain_id=195&data={...}
|
|
5252
|
+
*
|
|
5253
|
+
* For CONNECTION, you should use:
|
|
5254
|
+
* - WalletConnect (recommended for mobile)
|
|
5255
|
+
* - Browser extension (TronWeb/TronLink)
|
|
5256
|
+
*
|
|
5257
|
+
* Note: You can sign directly using signMessage() or signTransaction() without calling connect() first.
|
|
5258
|
+
* The wallet app will open and use the user's account automatically.
|
|
5259
|
+
*
|
|
5260
|
+
* This method attempts to open the wallet app, but cannot establish a connection
|
|
5261
|
+
* or retrieve the wallet address directly. The user must complete connection
|
|
5262
|
+
* through WalletConnect or browser extension after opening the app.
|
|
5263
|
+
*/
|
|
5264
|
+
async connect(chainId) {
|
|
5265
|
+
if (typeof window === "undefined") {
|
|
5266
|
+
throw new Error("Deep link requires a browser environment");
|
|
5267
|
+
}
|
|
5268
|
+
const targetChainId = Array.isArray(chainId) ? chainId[0] || _TronDeepLinkAdapter.TRON_MAINNET_CHAIN_ID : chainId || _TronDeepLinkAdapter.TRON_MAINNET_CHAIN_ID;
|
|
5269
|
+
try {
|
|
5270
|
+
this.setState("connecting" /* CONNECTING */);
|
|
5271
|
+
const isAvailable = await this.isAvailable();
|
|
5272
|
+
if (!isAvailable) {
|
|
5273
|
+
const isTelegram = !!(window.Telegram && window.Telegram.WebApp);
|
|
5274
|
+
if (isTelegram) {
|
|
5275
|
+
const platform = window.Telegram?.WebApp?.platform || "unknown";
|
|
5276
|
+
throw new Error(
|
|
5277
|
+
`Deep link is not available in Telegram Mini App on ${platform} platform. Please use WalletConnect or browser extension, or test on a mobile device.`
|
|
5278
|
+
);
|
|
5279
|
+
} else {
|
|
5280
|
+
throw new Error("Deep link is only available on mobile devices or Telegram Mini App. Please use WalletConnect or browser extension.");
|
|
5281
|
+
}
|
|
5282
|
+
}
|
|
5283
|
+
let deepLinkUrl = "";
|
|
5284
|
+
if (this.walletType === "tokenpocket" /* TOKENPOCKET */) {
|
|
5285
|
+
const actionId = `web-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
5286
|
+
const param = {
|
|
5287
|
+
action: "login",
|
|
5288
|
+
// Login action to open wallet
|
|
5289
|
+
actionId,
|
|
5290
|
+
blockchains: [{
|
|
5291
|
+
chainId: String(targetChainId),
|
|
5292
|
+
network: "tron"
|
|
5293
|
+
}],
|
|
5294
|
+
dappName: "Enclave Wallet SDK",
|
|
5295
|
+
dappIcon: "https://walletconnect.com/walletconnect-logo.svg",
|
|
5296
|
+
protocol: "TokenPocket",
|
|
5297
|
+
version: "1.0",
|
|
5298
|
+
expired: 1602
|
|
5299
|
+
// 30 minutes
|
|
5300
|
+
};
|
|
5301
|
+
const encodedParam = encodeURIComponent(JSON.stringify(param));
|
|
5302
|
+
deepLinkUrl = `tpoutside://pull.activity?param=${encodedParam}`;
|
|
5303
|
+
} else if (this.walletType === "tronlink" /* TRONLINK */) {
|
|
5304
|
+
deepLinkUrl = `tronlink://open?action=connect&network=tron`;
|
|
5305
|
+
}
|
|
5306
|
+
if (!deepLinkUrl) {
|
|
5307
|
+
throw new Error(`Unsupported wallet type: ${this.walletType}`);
|
|
5308
|
+
}
|
|
5309
|
+
console.log(`[TronDeepLink] ===== Connect via Deep Link =====`);
|
|
5310
|
+
console.log(`[TronDeepLink] Wallet Type:`, this.walletType);
|
|
5311
|
+
console.log(`[TronDeepLink] Chain ID:`, targetChainId);
|
|
5312
|
+
console.log(`[TronDeepLink] Deep Link URL:`, deepLinkUrl);
|
|
5313
|
+
console.log(`[TronDeepLink] Note: Deep links are for signing, not connection. After opening the app, please use WalletConnect to establish connection.`);
|
|
5314
|
+
console.log(`[TronDeepLink] ==================================`);
|
|
5315
|
+
window.location.href = deepLinkUrl;
|
|
5316
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
5317
|
+
throw new ConnectionRejectedError(
|
|
5318
|
+
`\u5DF2\u6253\u5F00 ${this.walletType === "tokenpocket" /* TOKENPOCKET */ ? "TokenPocket" : "TronLink"} \u5E94\u7528\u3002
|
|
5319
|
+
|
|
5320
|
+
\u6CE8\u610F\uFF1A\u6DF1\u5EA6\u94FE\u63A5\u4E3B\u8981\u7528\u4E8E\u7B7E\u540D\u4EA4\u6613\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5EFA\u7ACB\u8FDE\u63A5\u3002
|
|
5321
|
+
|
|
5322
|
+
\u8BF7\u4F7F\u7528\u4EE5\u4E0B\u65B9\u5F0F\u5B8C\u6210\u8FDE\u63A5\uFF1A
|
|
5323
|
+
1. \u5728\u94B1\u5305\u5E94\u7528\u4E2D\u4F7F\u7528 WalletConnect \u626B\u63CF\u4E8C\u7EF4\u7801
|
|
5324
|
+
2. \u6216\u4F7F\u7528\u6D4F\u89C8\u5668\u6269\u5C55\uFF08\u5982 TronLink\uFF09\u8FDE\u63A5
|
|
5325
|
+
|
|
5326
|
+
Deep link opened ${this.walletType} app. Please use WalletConnect or browser extension to complete the connection.`
|
|
5327
|
+
);
|
|
5328
|
+
} catch (error) {
|
|
5329
|
+
this.setState("error" /* ERROR */);
|
|
5330
|
+
this.setAccount(null);
|
|
5331
|
+
if (error instanceof ConnectionRejectedError) {
|
|
5332
|
+
throw error;
|
|
5333
|
+
}
|
|
5334
|
+
throw new Error(`Failed to open ${this.walletType} via deep link: ${error.message}`);
|
|
5335
|
+
}
|
|
5336
|
+
}
|
|
5337
|
+
/**
|
|
5338
|
+
* Disconnect wallet
|
|
5339
|
+
*/
|
|
5340
|
+
async disconnect() {
|
|
5341
|
+
this.setState("disconnected" /* DISCONNECTED */);
|
|
5342
|
+
this.setAccount(null);
|
|
5343
|
+
}
|
|
5344
|
+
/**
|
|
5345
|
+
* Sign message via deep link
|
|
5346
|
+
*
|
|
5347
|
+
* TokenPocket deep link format for signing:
|
|
5348
|
+
* tron:signMessage-version=1.0&protocol=TokenPocket&network=tron&chain_id=195&data={message}
|
|
5349
|
+
*
|
|
5350
|
+
* Reference: https://help.tokenpocket.pro/developer-cn/scan-protocol/tron
|
|
5351
|
+
*
|
|
5352
|
+
* Note: Deep links can sign directly without establishing a connection first.
|
|
5353
|
+
* The wallet app will open and use the user's account to sign the message.
|
|
5354
|
+
* The signature result will be returned via callback URL or app-to-app communication.
|
|
5355
|
+
*/
|
|
5356
|
+
async signMessage(message) {
|
|
5357
|
+
if (typeof window === "undefined") {
|
|
5358
|
+
throw new Error("Deep link requires a browser environment");
|
|
5359
|
+
}
|
|
5360
|
+
const isAvailable = await this.isAvailable();
|
|
5361
|
+
if (!isAvailable) {
|
|
5362
|
+
const isTelegram = !!(window.Telegram && window.Telegram.WebApp);
|
|
5363
|
+
if (isTelegram) {
|
|
5364
|
+
const platform = window.Telegram?.WebApp?.platform || "unknown";
|
|
5365
|
+
throw new Error(
|
|
5366
|
+
`Deep link signing is not available in Telegram Mini App on ${platform} platform. Please use WalletConnect or test on a mobile device.`
|
|
5367
|
+
);
|
|
5368
|
+
} else {
|
|
5369
|
+
throw new Error("Deep link signing is only available on mobile devices or Telegram Mini App.");
|
|
5370
|
+
}
|
|
5371
|
+
}
|
|
5372
|
+
let deepLinkUrl = "";
|
|
5373
|
+
if (this.walletType === "tokenpocket" /* TOKENPOCKET */) {
|
|
5374
|
+
const actionId = `web-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
5375
|
+
const param = {
|
|
5376
|
+
action: "sign",
|
|
5377
|
+
actionId,
|
|
5378
|
+
message,
|
|
5379
|
+
hash: false,
|
|
5380
|
+
signType: "ethPersonalSign",
|
|
5381
|
+
// For TRON, we use ethPersonalSign as it's similar
|
|
5382
|
+
memo: "TRON message signature",
|
|
5383
|
+
blockchains: [{
|
|
5384
|
+
chainId: "195",
|
|
5385
|
+
// TRON Mainnet chain ID as string
|
|
5386
|
+
network: "tron"
|
|
5387
|
+
}],
|
|
5388
|
+
dappName: "Enclave Wallet SDK",
|
|
5389
|
+
dappIcon: "https://walletconnect.com/walletconnect-logo.svg",
|
|
5390
|
+
protocol: "TokenPocket",
|
|
5391
|
+
version: "1.1.8",
|
|
5392
|
+
expired: 0
|
|
5393
|
+
// No expiration
|
|
5394
|
+
// callbackUrl: optional, if you want to receive callback
|
|
5395
|
+
// callbackSchema: optional, custom schema for callback
|
|
5396
|
+
};
|
|
5397
|
+
const encodedParam = encodeURIComponent(JSON.stringify(param));
|
|
5398
|
+
deepLinkUrl = `tpoutside://pull.activity?param=${encodedParam}`;
|
|
5399
|
+
console.log(`[TronDeepLink] Using TokenPocket tpoutside:// format for signMessage`);
|
|
5400
|
+
console.log(`[TronDeepLink] Param object:`, param);
|
|
5401
|
+
} else if (this.walletType === "tronlink" /* TRONLINK */) {
|
|
5402
|
+
const encodedMessage = encodeURIComponent(message);
|
|
5403
|
+
deepLinkUrl = `tronlink://signMessage?message=${encodedMessage}`;
|
|
5404
|
+
}
|
|
5405
|
+
if (!deepLinkUrl) {
|
|
5406
|
+
throw new MethodNotSupportedError("signMessage", this.type);
|
|
5407
|
+
}
|
|
5408
|
+
console.log(`[TronDeepLink] ===== Sign Message via Deep Link =====`);
|
|
5409
|
+
console.log(`[TronDeepLink] Wallet Type:`, this.walletType);
|
|
5410
|
+
console.log(`[TronDeepLink] Message:`, message);
|
|
5411
|
+
console.log(`[TronDeepLink] Deep Link URL:`, deepLinkUrl);
|
|
5412
|
+
console.log(`[TronDeepLink] Full URL length:`, deepLinkUrl.length);
|
|
5413
|
+
console.log(`[TronDeepLink] ========================================`);
|
|
5414
|
+
window.location.href = deepLinkUrl;
|
|
5415
|
+
throw new Error(
|
|
5416
|
+
`Deep link opened ${this.walletType} for signing. The signature will be handled by the wallet app. This adapter cannot retrieve the signature directly from deep links. Consider using WalletConnect or browser extension for programmatic signing.`
|
|
5417
|
+
);
|
|
5418
|
+
}
|
|
5419
|
+
/**
|
|
5420
|
+
* Sign transaction via deep link
|
|
5421
|
+
*
|
|
5422
|
+
* TokenPocket deep link format:
|
|
5423
|
+
* tron:signTransaction-version=1.0&protocol=TokenPocket&network=tron&chain_id=195&data={transaction}
|
|
5424
|
+
*
|
|
5425
|
+
* Reference: https://help.tokenpocket.pro/developer-cn/scan-protocol/tron
|
|
5426
|
+
*
|
|
5427
|
+
* Note: Deep links can sign directly without establishing a connection first.
|
|
5428
|
+
* The wallet app will open and use the user's account to sign the transaction.
|
|
5429
|
+
* The transaction data should be a JSON string containing the TRON transaction object.
|
|
5430
|
+
* The signature result will be returned via callback URL or app-to-app communication.
|
|
5431
|
+
*/
|
|
5432
|
+
async signTransaction(transaction) {
|
|
5433
|
+
if (typeof window === "undefined") {
|
|
5434
|
+
throw new Error("Deep link requires a browser environment");
|
|
5435
|
+
}
|
|
5436
|
+
const isAvailable = await this.isAvailable();
|
|
5437
|
+
if (!isAvailable) {
|
|
5438
|
+
const isTelegram = !!(window.Telegram && window.Telegram.WebApp);
|
|
5439
|
+
if (isTelegram) {
|
|
5440
|
+
const platform = window.Telegram?.WebApp?.platform || "unknown";
|
|
5441
|
+
throw new Error(
|
|
5442
|
+
`Deep link signing is not available in Telegram Mini App on ${platform} platform. Please use WalletConnect or test on a mobile device.`
|
|
5443
|
+
);
|
|
5444
|
+
} else {
|
|
5445
|
+
throw new Error("Deep link signing is only available on mobile devices or Telegram Mini App.");
|
|
5446
|
+
}
|
|
5447
|
+
}
|
|
5448
|
+
let deepLinkUrl = "";
|
|
5449
|
+
let actionId = "";
|
|
5450
|
+
let param = null;
|
|
5451
|
+
if (this.walletType === "tokenpocket" /* TOKENPOCKET */) {
|
|
5452
|
+
actionId = `web-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
5453
|
+
let transactionData;
|
|
5454
|
+
if (typeof transaction === "string") {
|
|
5455
|
+
transactionData = transaction;
|
|
5456
|
+
} else if (transaction.raw_data_hex) {
|
|
5457
|
+
transactionData = JSON.stringify(transaction);
|
|
5458
|
+
} else {
|
|
5459
|
+
transactionData = JSON.stringify(transaction);
|
|
5460
|
+
}
|
|
5461
|
+
param = {
|
|
5462
|
+
action: "pushTransaction",
|
|
5463
|
+
actionId,
|
|
5464
|
+
txData: transactionData,
|
|
5465
|
+
// Transaction data as JSON string
|
|
5466
|
+
blockchains: [{
|
|
5467
|
+
chainId: "195",
|
|
5468
|
+
// TRON Mainnet chain ID as string
|
|
5469
|
+
network: "tron"
|
|
5470
|
+
}],
|
|
5471
|
+
dappName: "Enclave Wallet SDK",
|
|
5472
|
+
dappIcon: "https://walletconnect.com/walletconnect-logo.svg",
|
|
5473
|
+
protocol: "TokenPocket",
|
|
5474
|
+
version: "1.1.8",
|
|
5475
|
+
expired: 0
|
|
5476
|
+
// No expiration
|
|
5477
|
+
};
|
|
5478
|
+
if (this.callbackSchema) {
|
|
5479
|
+
param.callbackSchema = this.callbackSchema;
|
|
5480
|
+
} else if (this.callbackUrl) {
|
|
5481
|
+
param.callbackUrl = this.callbackUrl;
|
|
5482
|
+
} else {
|
|
5483
|
+
if (typeof window !== "undefined" && window.location) {
|
|
5484
|
+
param.callbackSchema = `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
|
|
5485
|
+
}
|
|
5486
|
+
}
|
|
5487
|
+
const encodedParam = encodeURIComponent(JSON.stringify(param));
|
|
5488
|
+
deepLinkUrl = `tpoutside://pull.activity?param=${encodedParam}`;
|
|
5489
|
+
console.log(`[TronDeepLink] Using TokenPocket tpoutside:// format for signTransaction`);
|
|
5490
|
+
console.log(`[TronDeepLink] Param object (without txData):`, { ...param, txData: "[TRANSACTION DATA]" });
|
|
5491
|
+
} else if (this.walletType === "tronlink" /* TRONLINK */) {
|
|
5492
|
+
const transactionData = typeof transaction === "string" ? transaction : JSON.stringify(transaction);
|
|
5493
|
+
const encodedData = encodeURIComponent(transactionData);
|
|
5494
|
+
deepLinkUrl = `tronlink://signTransaction?transaction=${encodedData}`;
|
|
5495
|
+
}
|
|
5496
|
+
if (!deepLinkUrl) {
|
|
5497
|
+
throw new MethodNotSupportedError("signTransaction", this.type);
|
|
5498
|
+
}
|
|
5499
|
+
console.log(`[TronDeepLink] ===== Sign Transaction via Deep Link =====`);
|
|
5500
|
+
console.log(`[TronDeepLink] Wallet Type:`, this.walletType);
|
|
5501
|
+
console.log(`[TronDeepLink] Transaction:`, transaction);
|
|
5502
|
+
console.log(`[TronDeepLink] Transaction keys:`, transaction ? Object.keys(transaction) : "N/A");
|
|
5503
|
+
if (transaction && typeof transaction === "object") {
|
|
5504
|
+
console.log(`[TronDeepLink] Transaction has raw_data:`, !!transaction.raw_data);
|
|
5505
|
+
console.log(`[TronDeepLink] Transaction has raw_data_hex:`, !!transaction.raw_data_hex);
|
|
5506
|
+
console.log(`[TronDeepLink] Transaction has txID:`, !!transaction.txID);
|
|
5507
|
+
}
|
|
5508
|
+
if (actionId) {
|
|
5509
|
+
console.log(`[TronDeepLink] Action ID:`, actionId);
|
|
5510
|
+
}
|
|
5511
|
+
if (param) {
|
|
5512
|
+
console.log(`[TronDeepLink] Callback Schema:`, param.callbackSchema || param.callbackUrl || "None");
|
|
5513
|
+
}
|
|
5514
|
+
console.log(`[TronDeepLink] Deep Link URL:`, deepLinkUrl);
|
|
5515
|
+
console.log(`[TronDeepLink] Full URL length:`, deepLinkUrl.length);
|
|
5516
|
+
if (deepLinkUrl.length > 200) {
|
|
5517
|
+
console.log(`[TronDeepLink] URL (first 200 chars):`, deepLinkUrl.substring(0, 200) + "...");
|
|
5518
|
+
console.log(`[TronDeepLink] URL (last 100 chars):`, "..." + deepLinkUrl.substring(deepLinkUrl.length - 100));
|
|
5519
|
+
}
|
|
5520
|
+
console.log(`[TronDeepLink] ===========================================`);
|
|
5521
|
+
if (this.walletType === "tokenpocket" /* TOKENPOCKET */ && param && param.callbackSchema) {
|
|
5522
|
+
return new Promise((resolve, reject) => {
|
|
5523
|
+
this.pendingActions.set(actionId, { resolve, reject });
|
|
5524
|
+
window.location.href = deepLinkUrl;
|
|
5525
|
+
setTimeout(() => {
|
|
5526
|
+
if (this.pendingActions.has(actionId)) {
|
|
5527
|
+
this.pendingActions.delete(actionId);
|
|
5528
|
+
reject(new Error("Transaction signature timeout: No response from wallet app"));
|
|
5529
|
+
}
|
|
5530
|
+
}, 3e4);
|
|
5531
|
+
});
|
|
5532
|
+
}
|
|
5533
|
+
window.location.href = deepLinkUrl;
|
|
5534
|
+
throw new SignatureRejectedError(
|
|
5535
|
+
`\u5DF2\u6253\u5F00 ${this.walletType === "tokenpocket" /* TOKENPOCKET */ ? "TokenPocket" : "TronLink"} \u8FDB\u884C\u4EA4\u6613\u7B7E\u540D\u3002
|
|
5536
|
+
|
|
5537
|
+
\u6CE8\u610F\uFF1A\u6DF1\u5EA6\u94FE\u63A5\u65E0\u6CD5\u76F4\u63A5\u8FD4\u56DE\u7B7E\u540D\u7ED3\u679C\u3002
|
|
5538
|
+
|
|
5539
|
+
\u7B7E\u540D\u7ED3\u679C\u5C06\u901A\u8FC7\u4EE5\u4E0B\u65B9\u5F0F\u8FD4\u56DE\uFF1A
|
|
5540
|
+
1. \u94B1\u5305\u5E94\u7528\u7684\u56DE\u8C03 URL
|
|
5541
|
+
2. \u5E94\u7528\u95F4\u901A\u4FE1\uFF08App-to-App\uFF09
|
|
5542
|
+
|
|
5543
|
+
\u5982\u9700\u7A0B\u5E8F\u5316\u83B7\u53D6\u7B7E\u540D\uFF0C\u8BF7\u4F7F\u7528 WalletConnect \u6216\u6D4F\u89C8\u5668\u6269\u5C55\u3002
|
|
5544
|
+
|
|
5545
|
+
Deep link opened ${this.walletType} for transaction signing. The signature will be handled by the wallet app via callback. For programmatic signing, use WalletConnect or browser extension.`
|
|
5546
|
+
);
|
|
5547
|
+
}
|
|
5548
|
+
/**
|
|
5549
|
+
* Read contract (not supported via deep link)
|
|
5550
|
+
*/
|
|
5551
|
+
async readContract(_params) {
|
|
5552
|
+
throw new MethodNotSupportedError("readContract", this.type);
|
|
5553
|
+
}
|
|
5554
|
+
/**
|
|
5555
|
+
* Write contract (not supported via deep link)
|
|
5556
|
+
*/
|
|
5557
|
+
async writeContract(_params) {
|
|
5558
|
+
throw new MethodNotSupportedError("writeContract", this.type);
|
|
5559
|
+
}
|
|
5560
|
+
/**
|
|
5561
|
+
* Estimate gas (not supported)
|
|
5562
|
+
*/
|
|
5563
|
+
async estimateGas(_params) {
|
|
5564
|
+
throw new MethodNotSupportedError("estimateGas", this.type);
|
|
5565
|
+
}
|
|
5566
|
+
/**
|
|
5567
|
+
* Wait for transaction (not supported)
|
|
5568
|
+
*/
|
|
5569
|
+
async waitForTransaction(_txHash, _confirmations) {
|
|
5570
|
+
throw new MethodNotSupportedError("waitForTransaction", this.type);
|
|
5571
|
+
}
|
|
5572
|
+
/**
|
|
5573
|
+
* Get provider (not applicable for deep links)
|
|
5574
|
+
*/
|
|
5575
|
+
getProvider() {
|
|
5576
|
+
return null;
|
|
5577
|
+
}
|
|
5578
|
+
};
|
|
5579
|
+
// TRON Mainnet chain ID
|
|
5580
|
+
_TronDeepLinkAdapter.TRON_MAINNET_CHAIN_ID = 195;
|
|
5581
|
+
var TronDeepLinkAdapter = _TronDeepLinkAdapter;
|
|
5582
|
+
|
|
2226
5583
|
// src/auth/message-generator.ts
|
|
5584
|
+
init_types();
|
|
2227
5585
|
var AuthMessageGenerator = class {
|
|
2228
5586
|
constructor(domain) {
|
|
2229
5587
|
this.domain = domain;
|
|
@@ -2233,7 +5591,7 @@ var AuthMessageGenerator = class {
|
|
|
2233
5591
|
*/
|
|
2234
5592
|
generateAuthMessage(chainType, nonce, chainId, timestamp = Date.now(), statement) {
|
|
2235
5593
|
switch (chainType) {
|
|
2236
|
-
case ChainType.EVM:
|
|
5594
|
+
case exports.ChainType.EVM:
|
|
2237
5595
|
return this.generateEIP191Message({
|
|
2238
5596
|
domain: this.domain,
|
|
2239
5597
|
nonce,
|
|
@@ -2241,7 +5599,7 @@ var AuthMessageGenerator = class {
|
|
|
2241
5599
|
timestamp,
|
|
2242
5600
|
statement
|
|
2243
5601
|
});
|
|
2244
|
-
case ChainType.TRON:
|
|
5602
|
+
case exports.ChainType.TRON:
|
|
2245
5603
|
return this.generateTIP191Message({
|
|
2246
5604
|
domain: this.domain,
|
|
2247
5605
|
nonce,
|
|
@@ -2298,15 +5656,18 @@ var AuthMessageGenerator = class {
|
|
|
2298
5656
|
return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
2299
5657
|
}
|
|
2300
5658
|
};
|
|
5659
|
+
|
|
5660
|
+
// src/auth/signature-verifier.ts
|
|
5661
|
+
init_types();
|
|
2301
5662
|
var SignatureVerifier = class {
|
|
2302
5663
|
/**
|
|
2303
5664
|
* 验证签名
|
|
2304
5665
|
*/
|
|
2305
5666
|
async verifySignature(message, signature, expectedAddress, chainType) {
|
|
2306
5667
|
switch (chainType) {
|
|
2307
|
-
case ChainType.EVM:
|
|
5668
|
+
case exports.ChainType.EVM:
|
|
2308
5669
|
return this.verifyEIP191Signature(message, signature, expectedAddress);
|
|
2309
|
-
case ChainType.TRON:
|
|
5670
|
+
case exports.ChainType.TRON:
|
|
2310
5671
|
return this.verifyTIP191Signature(message, signature, expectedAddress);
|
|
2311
5672
|
default:
|
|
2312
5673
|
throw new Error(`Unsupported chain type: ${chainType}`);
|
|
@@ -2339,12 +5700,16 @@ var SignatureVerifier = class {
|
|
|
2339
5700
|
}
|
|
2340
5701
|
};
|
|
2341
5702
|
|
|
5703
|
+
// src/detection/detector.ts
|
|
5704
|
+
init_types();
|
|
5705
|
+
|
|
2342
5706
|
// src/detection/supported-wallets.ts
|
|
5707
|
+
init_types();
|
|
2343
5708
|
var SUPPORTED_WALLETS = {
|
|
2344
5709
|
["metamask" /* METAMASK */]: {
|
|
2345
5710
|
type: "metamask" /* METAMASK */,
|
|
2346
5711
|
name: "MetaMask",
|
|
2347
|
-
chainType: ChainType.EVM,
|
|
5712
|
+
chainType: exports.ChainType.EVM,
|
|
2348
5713
|
icon: "https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",
|
|
2349
5714
|
downloadUrl: "https://metamask.io/download/",
|
|
2350
5715
|
description: "The most popular Ethereum wallet"
|
|
@@ -2352,7 +5717,7 @@ var SUPPORTED_WALLETS = {
|
|
|
2352
5717
|
["walletconnect" /* WALLETCONNECT */]: {
|
|
2353
5718
|
type: "walletconnect" /* WALLETCONNECT */,
|
|
2354
5719
|
name: "WalletConnect",
|
|
2355
|
-
chainType: ChainType.EVM,
|
|
5720
|
+
chainType: exports.ChainType.EVM,
|
|
2356
5721
|
icon: "https://avatars.githubusercontent.com/u/37784886",
|
|
2357
5722
|
downloadUrl: "https://walletconnect.com/",
|
|
2358
5723
|
description: "Connect to 170+ wallets"
|
|
@@ -2360,7 +5725,7 @@ var SUPPORTED_WALLETS = {
|
|
|
2360
5725
|
["coinbase-wallet" /* COINBASE_WALLET */]: {
|
|
2361
5726
|
type: "coinbase-wallet" /* COINBASE_WALLET */,
|
|
2362
5727
|
name: "Coinbase Wallet",
|
|
2363
|
-
chainType: ChainType.EVM,
|
|
5728
|
+
chainType: exports.ChainType.EVM,
|
|
2364
5729
|
icon: "https://www.coinbase.com/img/favicon/favicon-96x96.png",
|
|
2365
5730
|
downloadUrl: "https://www.coinbase.com/wallet",
|
|
2366
5731
|
description: "Coinbase self-custody wallet"
|
|
@@ -2368,7 +5733,7 @@ var SUPPORTED_WALLETS = {
|
|
|
2368
5733
|
["tronlink" /* TRONLINK */]: {
|
|
2369
5734
|
type: "tronlink" /* TRONLINK */,
|
|
2370
5735
|
name: "TronWeb",
|
|
2371
|
-
chainType: ChainType.TRON,
|
|
5736
|
+
chainType: exports.ChainType.TRON,
|
|
2372
5737
|
icon: "https://www.tronlink.org/static/logoIcon.svg",
|
|
2373
5738
|
downloadUrl: "https://www.tronlink.org/",
|
|
2374
5739
|
description: "TronWeb \u517C\u5BB9\u94B1\u5305\uFF08\u652F\u6301 TronLink\u3001TokenPocket \u7B49\uFF09"
|
|
@@ -2376,16 +5741,30 @@ var SUPPORTED_WALLETS = {
|
|
|
2376
5741
|
["walletconnect-tron" /* WALLETCONNECT_TRON */]: {
|
|
2377
5742
|
type: "walletconnect-tron" /* WALLETCONNECT_TRON */,
|
|
2378
5743
|
name: "WalletConnect (Tron)",
|
|
2379
|
-
chainType: ChainType.TRON,
|
|
5744
|
+
chainType: exports.ChainType.TRON,
|
|
2380
5745
|
downloadUrl: "https://walletconnect.com/",
|
|
2381
5746
|
description: "WalletConnect for Tron"
|
|
2382
5747
|
},
|
|
2383
5748
|
["private-key" /* PRIVATE_KEY */]: {
|
|
2384
5749
|
type: "private-key" /* PRIVATE_KEY */,
|
|
2385
5750
|
name: "Private Key",
|
|
2386
|
-
chainType: ChainType.EVM,
|
|
5751
|
+
chainType: exports.ChainType.EVM,
|
|
2387
5752
|
// 可以用于任何链
|
|
2388
5753
|
description: "Import wallet using private key (for development)"
|
|
5754
|
+
},
|
|
5755
|
+
["deep-link-evm" /* DEEP_LINK_EVM */]: {
|
|
5756
|
+
type: "deep-link-evm" /* DEEP_LINK_EVM */,
|
|
5757
|
+
name: "Deep Link (EVM)",
|
|
5758
|
+
chainType: exports.ChainType.EVM,
|
|
5759
|
+
icon: "https://tokenpocket.pro/icon.png",
|
|
5760
|
+
description: "Deep link connection for EVM chains (TokenPocket, ImToken, etc.)"
|
|
5761
|
+
},
|
|
5762
|
+
["deep-link-tron" /* DEEP_LINK_TRON */]: {
|
|
5763
|
+
type: "deep-link-tron" /* DEEP_LINK_TRON */,
|
|
5764
|
+
name: "Deep Link (TRON)",
|
|
5765
|
+
chainType: exports.ChainType.TRON,
|
|
5766
|
+
icon: "https://tokenpocket.pro/icon.png",
|
|
5767
|
+
description: "Deep link connection for TRON chain (TokenPocket, TronLink, etc.)"
|
|
2389
5768
|
}
|
|
2390
5769
|
};
|
|
2391
5770
|
function getWalletMetadata(type) {
|
|
@@ -2393,12 +5772,12 @@ function getWalletMetadata(type) {
|
|
|
2393
5772
|
}
|
|
2394
5773
|
function getEVMWallets() {
|
|
2395
5774
|
return Object.values(SUPPORTED_WALLETS).filter(
|
|
2396
|
-
(wallet) => wallet.chainType === ChainType.EVM
|
|
5775
|
+
(wallet) => wallet.chainType === exports.ChainType.EVM
|
|
2397
5776
|
);
|
|
2398
5777
|
}
|
|
2399
5778
|
function getTronWallets() {
|
|
2400
5779
|
return Object.values(SUPPORTED_WALLETS).filter(
|
|
2401
|
-
(wallet) => wallet.chainType === ChainType.TRON
|
|
5780
|
+
(wallet) => wallet.chainType === exports.ChainType.TRON
|
|
2402
5781
|
);
|
|
2403
5782
|
}
|
|
2404
5783
|
|
|
@@ -2408,7 +5787,7 @@ var WalletDetector = class {
|
|
|
2408
5787
|
* Detect all wallet availability
|
|
2409
5788
|
*/
|
|
2410
5789
|
async detectAllWallets() {
|
|
2411
|
-
const walletTypes = Object.values(WalletType).filter(
|
|
5790
|
+
const walletTypes = Object.values(exports.WalletType).filter(
|
|
2412
5791
|
(type) => type !== "private-key" /* PRIVATE_KEY */
|
|
2413
5792
|
// Private key wallet does not need detection
|
|
2414
5793
|
);
|
|
@@ -2425,7 +5804,7 @@ var WalletDetector = class {
|
|
|
2425
5804
|
if (!metadata) {
|
|
2426
5805
|
return {
|
|
2427
5806
|
walletType,
|
|
2428
|
-
chainType: ChainType.EVM,
|
|
5807
|
+
chainType: exports.ChainType.EVM,
|
|
2429
5808
|
// Default
|
|
2430
5809
|
isAvailable: false,
|
|
2431
5810
|
detected: false
|
|
@@ -2533,11 +5912,12 @@ function shortenTronAddress(address, chars = 4) {
|
|
|
2533
5912
|
}
|
|
2534
5913
|
|
|
2535
5914
|
// src/utils/validation.ts
|
|
5915
|
+
init_types();
|
|
2536
5916
|
function validateAddress(address, chainType) {
|
|
2537
5917
|
switch (chainType) {
|
|
2538
|
-
case ChainType.EVM:
|
|
5918
|
+
case exports.ChainType.EVM:
|
|
2539
5919
|
return isValidEVMAddress(address);
|
|
2540
|
-
case ChainType.TRON:
|
|
5920
|
+
case exports.ChainType.TRON:
|
|
2541
5921
|
return isValidTronAddress(address);
|
|
2542
5922
|
default:
|
|
2543
5923
|
return false;
|
|
@@ -2558,9 +5938,9 @@ function isValidSignature(signature) {
|
|
|
2558
5938
|
}
|
|
2559
5939
|
function isValidTransactionHash(txHash, chainType) {
|
|
2560
5940
|
switch (chainType) {
|
|
2561
|
-
case ChainType.EVM:
|
|
5941
|
+
case exports.ChainType.EVM:
|
|
2562
5942
|
return /^0x[0-9a-fA-F]{64}$/.test(txHash);
|
|
2563
|
-
case ChainType.TRON:
|
|
5943
|
+
case exports.ChainType.TRON:
|
|
2564
5944
|
return /^[0-9a-fA-F]{64}$/.test(txHash);
|
|
2565
5945
|
default:
|
|
2566
5946
|
return false;
|
|
@@ -2607,26 +5987,31 @@ exports.AuthMessageGenerator = AuthMessageGenerator;
|
|
|
2607
5987
|
exports.BrowserWalletAdapter = BrowserWalletAdapter;
|
|
2608
5988
|
exports.CHAIN_INFO = CHAIN_INFO;
|
|
2609
5989
|
exports.ChainNotSupportedError = ChainNotSupportedError;
|
|
2610
|
-
exports.ChainType = ChainType;
|
|
2611
5990
|
exports.ConfigurationError = ConfigurationError;
|
|
2612
5991
|
exports.ConnectionRejectedError = ConnectionRejectedError;
|
|
5992
|
+
exports.DeepLinkAdapter = DeepLinkAdapter;
|
|
5993
|
+
exports.DeepLinkProviderType = DeepLinkProviderType;
|
|
5994
|
+
exports.DeepLinkWalletType = DeepLinkWalletType;
|
|
2613
5995
|
exports.EVMPrivateKeyAdapter = EVMPrivateKeyAdapter;
|
|
2614
5996
|
exports.MetaMaskAdapter = MetaMaskAdapter;
|
|
2615
5997
|
exports.MethodNotSupportedError = MethodNotSupportedError;
|
|
2616
5998
|
exports.NetworkError = NetworkError;
|
|
5999
|
+
exports.QRCodeSignStatus = QRCodeSignStatus;
|
|
6000
|
+
exports.QRCodeSigner = QRCodeSigner;
|
|
2617
6001
|
exports.SUPPORTED_WALLETS = SUPPORTED_WALLETS;
|
|
2618
6002
|
exports.SignatureRejectedError = SignatureRejectedError;
|
|
2619
6003
|
exports.SignatureVerifier = SignatureVerifier;
|
|
2620
6004
|
exports.TransactionFailedError = TransactionFailedError;
|
|
6005
|
+
exports.TronDeepLinkAdapter = TronDeepLinkAdapter;
|
|
2621
6006
|
exports.TronLinkAdapter = TronLinkAdapter;
|
|
2622
6007
|
exports.WalletAdapter = WalletAdapter;
|
|
6008
|
+
exports.WalletConnectAdapter = WalletConnectAdapter;
|
|
6009
|
+
exports.WalletConnectTronAdapter = WalletConnectTronAdapter;
|
|
2623
6010
|
exports.WalletDetector = WalletDetector;
|
|
2624
6011
|
exports.WalletManager = WalletManager;
|
|
2625
6012
|
exports.WalletNotAvailableError = WalletNotAvailableError;
|
|
2626
6013
|
exports.WalletNotConnectedError = WalletNotConnectedError;
|
|
2627
6014
|
exports.WalletSDKError = WalletSDKError;
|
|
2628
|
-
exports.WalletState = WalletState;
|
|
2629
|
-
exports.WalletType = WalletType;
|
|
2630
6015
|
exports.compareEVMAddresses = compareEVMAddresses;
|
|
2631
6016
|
exports.compareTronAddresses = compareTronAddresses;
|
|
2632
6017
|
exports.compareUniversalAddresses = compareUniversalAddresses;
|