@solana/connector 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1460 -0
  2. package/dist/chunk-52WUWW5R.mjs +2533 -0
  3. package/dist/chunk-52WUWW5R.mjs.map +1 -0
  4. package/dist/chunk-5NSUFMCB.js +393 -0
  5. package/dist/chunk-5NSUFMCB.js.map +1 -0
  6. package/dist/chunk-5ZUVZZWU.mjs +180 -0
  7. package/dist/chunk-5ZUVZZWU.mjs.map +1 -0
  8. package/dist/chunk-7TADXRFD.mjs +298 -0
  9. package/dist/chunk-7TADXRFD.mjs.map +1 -0
  10. package/dist/chunk-ACFSCMUI.mjs +359 -0
  11. package/dist/chunk-ACFSCMUI.mjs.map +1 -0
  12. package/dist/chunk-SGAIPK7Q.js +314 -0
  13. package/dist/chunk-SGAIPK7Q.js.map +1 -0
  14. package/dist/chunk-SMUUAKC3.js +186 -0
  15. package/dist/chunk-SMUUAKC3.js.map +1 -0
  16. package/dist/chunk-ZLPQUOFK.js +2594 -0
  17. package/dist/chunk-ZLPQUOFK.js.map +1 -0
  18. package/dist/compat.d.mts +106 -0
  19. package/dist/compat.d.ts +106 -0
  20. package/dist/compat.js +98 -0
  21. package/dist/compat.js.map +1 -0
  22. package/dist/compat.mjs +94 -0
  23. package/dist/compat.mjs.map +1 -0
  24. package/dist/headless.d.mts +400 -0
  25. package/dist/headless.d.ts +400 -0
  26. package/dist/headless.js +325 -0
  27. package/dist/headless.js.map +1 -0
  28. package/dist/headless.mjs +4 -0
  29. package/dist/headless.mjs.map +1 -0
  30. package/dist/index.d.mts +10 -0
  31. package/dist/index.d.ts +10 -0
  32. package/dist/index.js +382 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/index.mjs +5 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/react.d.mts +645 -0
  37. package/dist/react.d.ts +645 -0
  38. package/dist/react.js +65 -0
  39. package/dist/react.js.map +1 -0
  40. package/dist/react.mjs +4 -0
  41. package/dist/react.mjs.map +1 -0
  42. package/dist/transaction-signer-BtJPGXIg.d.mts +373 -0
  43. package/dist/transaction-signer-BtJPGXIg.d.ts +373 -0
  44. package/dist/wallet-standard-shim-Af7ejSld.d.mts +1090 -0
  45. package/dist/wallet-standard-shim-BGlvGRbB.d.ts +1090 -0
  46. package/package.json +87 -10
  47. package/index.js +0 -1
@@ -0,0 +1,2533 @@
1
+ import { createLogger, __publicField, isWeb3jsTransaction, prepareTransactionForWallet, convertSignedTransaction } from './chunk-5ZUVZZWU.mjs';
2
+ import { getPublicSolanaRpcUrl, getExplorerLink, LAMPORTS_PER_SOL, address, getTransactionDecoder, getSignatureFromBytes, isAddress } from 'gill';
3
+ import { Component, useTransition, useState, useCallback, useMemo } from 'react';
4
+ import { jsx, jsxs } from 'react/jsx-runtime';
5
+ import { install } from '@solana/webcrypto-ed25519-polyfill';
6
+
7
+ // src/lib/adapters/wallet-standard-shim.ts
8
+ var registry = null;
9
+ function getWalletsRegistry() {
10
+ if (typeof window > "u")
11
+ return {
12
+ get: () => [],
13
+ on: () => () => {
14
+ }
15
+ };
16
+ if (!registry) {
17
+ let nav = window.navigator;
18
+ nav.wallets && typeof nav.wallets.get == "function" ? registry = nav.wallets : import('@wallet-standard/app').then((mod) => {
19
+ let walletStandardRegistry = mod.getWallets?.();
20
+ walletStandardRegistry && (registry = walletStandardRegistry);
21
+ }).catch(() => {
22
+ });
23
+ }
24
+ return {
25
+ get: () => {
26
+ try {
27
+ let activeRegistry = window.navigator.wallets || registry;
28
+ if (activeRegistry && typeof activeRegistry.get == "function") {
29
+ let wallets = activeRegistry.get();
30
+ return Array.isArray(wallets) ? wallets : [];
31
+ }
32
+ return [];
33
+ } catch {
34
+ return [];
35
+ }
36
+ },
37
+ on: (event, callback) => {
38
+ try {
39
+ let activeRegistry = window.navigator.wallets || registry;
40
+ return activeRegistry && typeof activeRegistry.on == "function" ? activeRegistry.on(event, callback) : () => {
41
+ };
42
+ } catch {
43
+ return () => {
44
+ };
45
+ }
46
+ }
47
+ };
48
+ }
49
+
50
+ // src/lib/errors/index.ts
51
+ var ConnectorError = class extends Error {
52
+ constructor(message, context, originalError) {
53
+ super(message);
54
+ /**
55
+ * Additional context about the error
56
+ */
57
+ __publicField(this, "context");
58
+ /**
59
+ * The underlying error that caused this error
60
+ */
61
+ __publicField(this, "originalError");
62
+ /**
63
+ * Timestamp when error occurred
64
+ */
65
+ __publicField(this, "timestamp");
66
+ this.name = this.constructor.name, this.context = context, this.originalError = originalError, this.timestamp = (/* @__PURE__ */ new Date()).toISOString(), Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
67
+ }
68
+ /**
69
+ * Get a JSON representation of the error
70
+ */
71
+ toJSON() {
72
+ return {
73
+ name: this.name,
74
+ code: this.code,
75
+ message: this.message,
76
+ recoverable: this.recoverable,
77
+ context: this.context,
78
+ timestamp: this.timestamp,
79
+ originalError: this.originalError?.message
80
+ };
81
+ }
82
+ }, ConnectionError = class extends ConnectorError {
83
+ constructor(code, message, context, originalError) {
84
+ super(message, context, originalError);
85
+ __publicField(this, "code");
86
+ __publicField(this, "recoverable", true);
87
+ this.code = code;
88
+ }
89
+ }, ValidationError = class extends ConnectorError {
90
+ constructor(code, message, context, originalError) {
91
+ super(message, context, originalError);
92
+ __publicField(this, "code");
93
+ __publicField(this, "recoverable", false);
94
+ this.code = code;
95
+ }
96
+ }, ConfigurationError = class extends ConnectorError {
97
+ constructor(code, message, context, originalError) {
98
+ super(message, context, originalError);
99
+ __publicField(this, "code");
100
+ __publicField(this, "recoverable", false);
101
+ this.code = code;
102
+ }
103
+ }, NetworkError = class extends ConnectorError {
104
+ constructor(code, message, context, originalError) {
105
+ super(message, context, originalError);
106
+ __publicField(this, "code");
107
+ __publicField(this, "recoverable", true);
108
+ this.code = code;
109
+ }
110
+ }, TransactionError = class extends ConnectorError {
111
+ constructor(code, message, context, originalError) {
112
+ super(message, context, originalError);
113
+ __publicField(this, "code");
114
+ __publicField(this, "recoverable");
115
+ this.code = code, this.recoverable = ["USER_REJECTED", "SEND_FAILED", "SIMULATION_FAILED"].includes(code);
116
+ }
117
+ };
118
+ function isConnectorError(error) {
119
+ return error instanceof ConnectorError;
120
+ }
121
+ function isConnectionError(error) {
122
+ return error instanceof ConnectionError;
123
+ }
124
+ function isValidationError(error) {
125
+ return error instanceof ValidationError;
126
+ }
127
+ function isConfigurationError(error) {
128
+ return error instanceof ConfigurationError;
129
+ }
130
+ function isNetworkError(error) {
131
+ return error instanceof NetworkError;
132
+ }
133
+ function isTransactionError(error) {
134
+ return error instanceof TransactionError;
135
+ }
136
+ var Errors = {
137
+ // Connection errors
138
+ walletNotConnected: (context) => new ConnectionError("WALLET_NOT_CONNECTED", "No wallet connected", context),
139
+ walletNotFound: (walletName) => new ConnectionError("WALLET_NOT_FOUND", `Wallet not found${walletName ? `: ${walletName}` : ""}`, {
140
+ walletName
141
+ }),
142
+ connectionFailed: (originalError) => new ConnectionError("CONNECTION_FAILED", "Failed to connect to wallet", void 0, originalError),
143
+ accountNotAvailable: (address) => new ConnectionError("ACCOUNT_NOT_AVAILABLE", "Requested account not available", { address }),
144
+ // Validation errors
145
+ invalidTransaction: (reason, context) => new ValidationError("INVALID_TRANSACTION", `Invalid transaction: ${reason}`, context),
146
+ invalidFormat: (expectedFormat, actualFormat) => new ValidationError("INVALID_FORMAT", `Invalid format: expected ${expectedFormat}`, {
147
+ expectedFormat,
148
+ actualFormat
149
+ }),
150
+ unsupportedFormat: (format) => new ValidationError("UNSUPPORTED_FORMAT", `Unsupported format: ${format}`, { format }),
151
+ // Configuration errors
152
+ missingProvider: (hookName) => new ConfigurationError(
153
+ "MISSING_PROVIDER",
154
+ `${hookName} must be used within ConnectorProvider. Wrap your app with <ConnectorProvider> or <UnifiedProvider>.`,
155
+ { hookName }
156
+ ),
157
+ clusterNotFound: (clusterId, availableClusters) => new ConfigurationError(
158
+ "CLUSTER_NOT_FOUND",
159
+ `Cluster ${clusterId} not found. Available clusters: ${availableClusters.join(", ")}`,
160
+ { clusterId, availableClusters }
161
+ ),
162
+ // Network errors
163
+ rpcError: (message, originalError) => new NetworkError("RPC_ERROR", message, void 0, originalError),
164
+ networkTimeout: () => new NetworkError("NETWORK_TIMEOUT", "Network request timed out"),
165
+ // Transaction errors
166
+ signingFailed: (originalError) => new TransactionError("SIGNING_FAILED", "Failed to sign transaction", void 0, originalError),
167
+ featureNotSupported: (feature) => new TransactionError("FEATURE_NOT_SUPPORTED", `Wallet does not support ${feature}`, { feature }),
168
+ userRejected: (operation) => new TransactionError("USER_REJECTED", `User rejected ${operation}`, { operation })
169
+ };
170
+ function toConnectorError(error, defaultMessage = "An unexpected error occurred") {
171
+ if (isConnectorError(error))
172
+ return error;
173
+ if (error instanceof Error) {
174
+ let message = error.message.toLowerCase();
175
+ return message.includes("user rejected") || message.includes("user denied") ? Errors.userRejected("transaction") : message.includes("wallet not found") || message.includes("not installed") ? Errors.walletNotFound() : message.includes("not connected") ? Errors.walletNotConnected() : message.includes("network") || message.includes("fetch") ? Errors.rpcError(error.message, error) : message.includes("invalid") ? new ValidationError("VALIDATION_FAILED", error.message, void 0, error) : new TransactionError("SIGNING_FAILED", error.message, void 0, error);
176
+ }
177
+ return new TransactionError("SIGNING_FAILED", defaultMessage, { originalError: String(error) });
178
+ }
179
+ function getUserFriendlyMessage(error) {
180
+ return isConnectorError(error) ? {
181
+ WALLET_NOT_CONNECTED: "Please connect your wallet to continue.",
182
+ WALLET_NOT_FOUND: "Wallet not found. Please install a supported wallet.",
183
+ CONNECTION_FAILED: "Failed to connect to wallet. Please try again.",
184
+ USER_REJECTED: "Transaction was cancelled.",
185
+ FEATURE_NOT_SUPPORTED: "This wallet does not support this feature.",
186
+ SIGNING_FAILED: "Failed to sign transaction. Please try again.",
187
+ SEND_FAILED: "Failed to send transaction. Please try again.",
188
+ INVALID_CLUSTER: "Invalid network configuration.",
189
+ CLUSTER_NOT_FOUND: "Network not found.",
190
+ MISSING_PROVIDER: "Application not properly configured.",
191
+ RPC_ERROR: "Network error. Please check your connection.",
192
+ NETWORK_TIMEOUT: "Request timed out. Please try again."
193
+ }[error.code] || error.message || "An error occurred." : "An unexpected error occurred. Please try again.";
194
+ }
195
+ var PUBLIC_RPC_ENDPOINTS = {
196
+ mainnet: "https://api.mainnet-beta.solana.com",
197
+ devnet: "https://api.devnet.solana.com",
198
+ testnet: "https://api.testnet.solana.com",
199
+ localnet: "http://localhost:8899"
200
+ };
201
+ function normalizeNetwork(network) {
202
+ switch (network.toLowerCase().replace("-beta", "")) {
203
+ case "mainnet":
204
+ return "mainnet";
205
+ case "devnet":
206
+ return "devnet";
207
+ case "testnet":
208
+ return "testnet";
209
+ case "localnet":
210
+ return "localnet";
211
+ default:
212
+ return "mainnet";
213
+ }
214
+ }
215
+ function toClusterId(network) {
216
+ return `solana:${normalizeNetwork(network)}`;
217
+ }
218
+ function getDefaultRpcUrl(network) {
219
+ let normalized = normalizeNetwork(network);
220
+ try {
221
+ return getPublicSolanaRpcUrl(normalized);
222
+ } catch {
223
+ return PUBLIC_RPC_ENDPOINTS[normalized] ?? PUBLIC_RPC_ENDPOINTS.localnet;
224
+ }
225
+ }
226
+ function isMainnet(network) {
227
+ return normalizeNetwork(network) === "mainnet";
228
+ }
229
+ function isDevnet(network) {
230
+ return normalizeNetwork(network) === "devnet";
231
+ }
232
+ function isTestnet(network) {
233
+ return normalizeNetwork(network) === "testnet";
234
+ }
235
+ function isLocalnet(network) {
236
+ return normalizeNetwork(network) === "localnet";
237
+ }
238
+ function getNetworkDisplayName(network) {
239
+ let normalized = normalizeNetwork(network);
240
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
241
+ }
242
+ function getClusterRpcUrl(cluster) {
243
+ if (!cluster)
244
+ throw new Error("Invalid cluster configuration: unable to determine RPC URL for cluster unknown");
245
+ let url;
246
+ if (typeof cluster == "string" ? url = cluster : typeof cluster == "object" && cluster !== null ? "url" in cluster && typeof cluster.url == "string" ? url = cluster.url : "rpcUrl" in cluster && typeof cluster.rpcUrl == "string" ? url = cluster.rpcUrl : url = "" : url = "", url?.startsWith("http://") || url?.startsWith("https://"))
247
+ return url;
248
+ let presets = {
249
+ ...PUBLIC_RPC_ENDPOINTS,
250
+ "mainnet-beta": PUBLIC_RPC_ENDPOINTS.mainnet
251
+ };
252
+ if (url && presets[url])
253
+ return presets[url];
254
+ if (!url || url === "[object Object]")
255
+ throw new Error(
256
+ `Invalid cluster configuration: unable to determine RPC URL for cluster ${cluster?.id ?? "unknown"}`
257
+ );
258
+ return url;
259
+ }
260
+ function getClusterExplorerUrl(cluster, path) {
261
+ if (!cluster || !cluster.id)
262
+ return path ? `https://explorer.solana.com/${path}?cluster=devnet` : "https://explorer.solana.com?cluster=devnet";
263
+ let parts = cluster.id.split(":"), clusterSegment = parts.length >= 2 && parts[1] ? parts[1] : "devnet", isMainnet2 = cluster.id === "solana:mainnet" || cluster.id === "solana:mainnet-beta" || clusterSegment === "mainnet" || clusterSegment === "mainnet-beta", base = isMainnet2 ? "https://explorer.solana.com" : `https://explorer.solana.com?cluster=${clusterSegment}`;
264
+ return path ? isMainnet2 ? `https://explorer.solana.com/${path}` : `https://explorer.solana.com/${path}?cluster=${clusterSegment}` : base;
265
+ }
266
+ function getTransactionUrl(signature, cluster) {
267
+ let clusterType = getClusterType(cluster), explorerCluster = clusterType === "custom" || clusterType === "localnet" ? "devnet" : clusterType;
268
+ return getExplorerLink({
269
+ transaction: signature,
270
+ cluster: explorerCluster === "mainnet" ? "mainnet" : explorerCluster
271
+ });
272
+ }
273
+ function getAddressUrl(address, cluster) {
274
+ let clusterType = getClusterType(cluster), explorerCluster = clusterType === "custom" || clusterType === "localnet" ? "devnet" : clusterType;
275
+ return getExplorerLink({
276
+ address,
277
+ cluster: explorerCluster === "mainnet" ? "mainnet" : explorerCluster
278
+ });
279
+ }
280
+ function getTokenUrl(tokenAddress, cluster) {
281
+ return getClusterExplorerUrl(cluster, `token/${tokenAddress}`);
282
+ }
283
+ function getBlockUrl(slot, cluster) {
284
+ return getClusterExplorerUrl(cluster, `block/${slot}`);
285
+ }
286
+ function isMainnetCluster(cluster) {
287
+ return cluster.id === "solana:mainnet" || cluster.id === "solana:mainnet-beta";
288
+ }
289
+ function isDevnetCluster(cluster) {
290
+ return cluster.id === "solana:devnet";
291
+ }
292
+ function isTestnetCluster(cluster) {
293
+ return cluster.id === "solana:testnet";
294
+ }
295
+ function isLocalCluster(cluster) {
296
+ let url = "";
297
+ return "url" in cluster && typeof cluster.url == "string" ? url = cluster.url : "rpcUrl" in cluster && typeof cluster.rpcUrl == "string" && (url = cluster.rpcUrl), cluster.id === "solana:localnet" || url.includes("localhost") || url.includes("127.0.0.1");
298
+ }
299
+ function getClusterName(cluster) {
300
+ if (cluster.label) return cluster.label;
301
+ if ("name" in cluster && typeof cluster.name == "string")
302
+ return cluster.name;
303
+ let parts = cluster.id.split(":");
304
+ return parts.length >= 2 && parts[1] ? parts.slice(1).join(":") : "Unknown";
305
+ }
306
+ function getClusterType(cluster) {
307
+ return isMainnetCluster(cluster) ? "mainnet" : isDevnetCluster(cluster) ? "devnet" : isTestnetCluster(cluster) ? "testnet" : isLocalCluster(cluster) ? "localnet" : "custom";
308
+ }
309
+
310
+ // src/lib/constants.ts
311
+ var POLL_INTERVALS_MS = [1e3, 2e3, 3e3, 5e3, 5e3], DEFAULT_MAX_RETRIES = 3, DEFAULT_MAX_TRACKED_TRANSACTIONS = 20;
312
+
313
+ // src/lib/core/state-manager.ts
314
+ var StateManager = class {
315
+ constructor(initialState) {
316
+ __publicField(this, "state");
317
+ __publicField(this, "listeners", /* @__PURE__ */ new Set());
318
+ __publicField(this, "notifyTimeout");
319
+ this.state = initialState;
320
+ }
321
+ /**
322
+ * Optimized state update with structural sharing
323
+ * Only updates if values actually changed
324
+ */
325
+ updateState(updates, immediate = false) {
326
+ let hasChanges = false, nextState = { ...this.state };
327
+ for (let [key, value] of Object.entries(updates)) {
328
+ let stateKey = key, currentValue = nextState[stateKey];
329
+ Array.isArray(value) && Array.isArray(currentValue) ? this.arraysEqual(value, currentValue) || (nextState[stateKey] = value, hasChanges = true) : value && typeof value == "object" && currentValue && typeof currentValue == "object" ? this.objectsEqual(value, currentValue) || (nextState[stateKey] = value, hasChanges = true) : currentValue !== value && (nextState[stateKey] = value, hasChanges = true);
330
+ }
331
+ return hasChanges && (this.state = nextState, immediate ? this.notifyImmediate() : this.notify()), hasChanges;
332
+ }
333
+ /**
334
+ * Fast array equality check for wallet/account arrays
335
+ */
336
+ arraysEqual(a, b) {
337
+ return a.length !== b.length ? false : a[0] && typeof a[0] == "object" && "name" in a[0] && b[0] && typeof b[0] == "object" && "name" in b[0] ? a.every((item, i) => {
338
+ let aItem = item, bItem = b[i];
339
+ if (!bItem || typeof bItem != "object") return false;
340
+ let keysA = Object.keys(aItem), keysB = Object.keys(bItem);
341
+ return keysA.length !== keysB.length ? false : keysA.every((key) => aItem[key] === bItem[key]);
342
+ }) : a[0] && typeof a[0] == "object" && "address" in a[0] && b[0] && typeof b[0] == "object" && "address" in b[0] ? a.every((item, i) => {
343
+ let aItem = item, bItem = b[i];
344
+ return aItem.address === bItem?.address;
345
+ }) : a === b;
346
+ }
347
+ /**
348
+ * Deep equality check for objects
349
+ * Used to prevent unnecessary state updates when object contents haven't changed
350
+ */
351
+ objectsEqual(a, b) {
352
+ if (a === b) return true;
353
+ if (!a || !b || typeof a != "object" || typeof b != "object") return false;
354
+ let keysA = Object.keys(a), keysB = Object.keys(b);
355
+ return keysA.length !== keysB.length ? false : keysA.every((key) => a[key] === b[key]);
356
+ }
357
+ subscribe(listener) {
358
+ return this.listeners.add(listener), () => this.listeners.delete(listener);
359
+ }
360
+ getSnapshot() {
361
+ return this.state;
362
+ }
363
+ notify() {
364
+ this.notifyTimeout && clearTimeout(this.notifyTimeout), this.notifyTimeout = setTimeout(() => {
365
+ this.listeners.forEach((l) => l(this.state)), this.notifyTimeout = void 0;
366
+ }, 16);
367
+ }
368
+ notifyImmediate() {
369
+ this.notifyTimeout && (clearTimeout(this.notifyTimeout), this.notifyTimeout = void 0), this.listeners.forEach((l) => l(this.state));
370
+ }
371
+ clear() {
372
+ this.listeners.clear();
373
+ }
374
+ };
375
+
376
+ // src/lib/core/event-emitter.ts
377
+ var logger = createLogger("EventEmitter"), EventEmitter = class {
378
+ constructor(debug = false) {
379
+ __publicField(this, "listeners", /* @__PURE__ */ new Set());
380
+ __publicField(this, "debug");
381
+ this.debug = debug;
382
+ }
383
+ /**
384
+ * Subscribe to connector events
385
+ */
386
+ on(listener) {
387
+ return this.listeners.add(listener), () => this.listeners.delete(listener);
388
+ }
389
+ /**
390
+ * Remove a specific event listener
391
+ */
392
+ off(listener) {
393
+ this.listeners.delete(listener);
394
+ }
395
+ /**
396
+ * Remove all event listeners
397
+ */
398
+ offAll() {
399
+ this.listeners.clear();
400
+ }
401
+ /**
402
+ * Emit an event to all listeners
403
+ * Automatically adds timestamp if not already present
404
+ */
405
+ emit(event) {
406
+ let eventWithTimestamp = {
407
+ ...event,
408
+ timestamp: event.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
409
+ };
410
+ this.debug && logger.debug("Event emitted", { type: eventWithTimestamp.type, event: eventWithTimestamp }), this.listeners.forEach((listener) => {
411
+ try {
412
+ listener(eventWithTimestamp);
413
+ } catch (error) {
414
+ logger.error("Event listener error", { error });
415
+ }
416
+ });
417
+ }
418
+ /**
419
+ * Get the number of active listeners
420
+ */
421
+ getListenerCount() {
422
+ return this.listeners.size;
423
+ }
424
+ /**
425
+ * Generate ISO timestamp for events
426
+ * Utility method for creating timestamps consistently
427
+ */
428
+ static timestamp() {
429
+ return (/* @__PURE__ */ new Date()).toISOString();
430
+ }
431
+ };
432
+
433
+ // src/lib/core/debug-metrics.ts
434
+ var DebugMetrics = class {
435
+ constructor() {
436
+ __publicField(this, "stateUpdates", 0);
437
+ __publicField(this, "noopUpdates", 0);
438
+ __publicField(this, "updateTimes", []);
439
+ __publicField(this, "lastUpdateTime", 0);
440
+ __publicField(this, "eventListenerCount", 0);
441
+ __publicField(this, "subscriptionCount", 0);
442
+ }
443
+ /**
444
+ * Record a state update attempt
445
+ */
446
+ recordUpdate(duration, hadChanges) {
447
+ hadChanges ? this.stateUpdates++ : this.noopUpdates++, this.updateTimes.push(duration), this.updateTimes.length > 100 && this.updateTimes.shift(), this.lastUpdateTime = Date.now();
448
+ }
449
+ /**
450
+ * Update listener counts
451
+ */
452
+ updateListenerCounts(eventListeners, subscriptions) {
453
+ this.eventListenerCount = eventListeners, this.subscriptionCount = subscriptions;
454
+ }
455
+ /**
456
+ * Get current metrics
457
+ */
458
+ getMetrics() {
459
+ let totalUpdates = this.stateUpdates + this.noopUpdates, optimizationRate = totalUpdates > 0 ? Math.round(this.noopUpdates / totalUpdates * 100) : 0, avgUpdateTime = this.updateTimes.length > 0 ? this.updateTimes.reduce((a, b) => a + b, 0) / this.updateTimes.length : 0;
460
+ return {
461
+ stateUpdates: this.stateUpdates,
462
+ noopUpdates: this.noopUpdates,
463
+ optimizationRate,
464
+ eventListenerCount: this.eventListenerCount,
465
+ subscriptionCount: this.subscriptionCount,
466
+ avgUpdateTimeMs: Math.round(avgUpdateTime * 100) / 100,
467
+ lastUpdateTime: this.lastUpdateTime
468
+ };
469
+ }
470
+ /**
471
+ * Reset all metrics
472
+ */
473
+ resetMetrics() {
474
+ this.stateUpdates = 0, this.noopUpdates = 0, this.updateTimes = [], this.lastUpdateTime = 0;
475
+ }
476
+ };
477
+
478
+ // src/lib/core/base-collaborator.ts
479
+ var BaseCollaborator = class {
480
+ constructor(config, loggerPrefix) {
481
+ __publicField(this, "stateManager");
482
+ __publicField(this, "eventEmitter");
483
+ __publicField(this, "debug");
484
+ __publicField(this, "logger");
485
+ this.stateManager = config.stateManager, this.eventEmitter = config.eventEmitter, this.debug = config.debug ?? false, this.logger = createLogger(loggerPrefix);
486
+ }
487
+ /**
488
+ * Log debug message if debug mode is enabled
489
+ */
490
+ log(message, data) {
491
+ this.debug && this.logger.debug(message, data);
492
+ }
493
+ /**
494
+ * Log error message if debug mode is enabled
495
+ */
496
+ error(message, data) {
497
+ this.debug && this.logger.error(message, data);
498
+ }
499
+ /**
500
+ * Get current state snapshot
501
+ */
502
+ getState() {
503
+ return this.stateManager.getSnapshot();
504
+ }
505
+ };
506
+
507
+ // src/lib/connection/wallet-authenticity-verifier.ts
508
+ var logger2 = createLogger("WalletAuthenticity"), WalletAuthenticityVerifier = class {
509
+ /**
510
+ * Verify a wallet's authenticity using dynamic heuristics
511
+ *
512
+ * @param wallet - The wallet object to verify
513
+ * @param walletName - Expected wallet name
514
+ * @returns Verification result with confidence score
515
+ */
516
+ static verify(wallet, walletName) {
517
+ let warnings = [], name = walletName.toLowerCase();
518
+ logger2.debug("Verifying wallet with dynamic heuristics", { name });
519
+ let securityScore = {
520
+ walletStandardCompliance: 0,
521
+ methodIntegrity: 0,
522
+ chainSupport: 0,
523
+ maliciousPatterns: 1,
524
+ // Start at 1, deduct for issues
525
+ identityConsistency: 0
526
+ }, walletStandardScore = this.checkWalletStandardCompliance(wallet);
527
+ securityScore.walletStandardCompliance = walletStandardScore.score, warnings.push(...walletStandardScore.warnings);
528
+ let methodIntegrityScore = this.checkMethodIntegrity(wallet);
529
+ securityScore.methodIntegrity = methodIntegrityScore.score, warnings.push(...methodIntegrityScore.warnings);
530
+ let chainSupportScore = this.checkChainSupport(wallet);
531
+ securityScore.chainSupport = chainSupportScore.score, warnings.push(...chainSupportScore.warnings);
532
+ let maliciousPatterns = this.detectMaliciousPatterns(wallet, name);
533
+ securityScore.maliciousPatterns = maliciousPatterns.score, warnings.push(...maliciousPatterns.warnings);
534
+ let identityScore = this.checkIdentityConsistency(wallet, name);
535
+ securityScore.identityConsistency = identityScore.score, warnings.push(...identityScore.warnings);
536
+ let weights = {
537
+ walletStandardCompliance: 0.25,
538
+ methodIntegrity: 0.2,
539
+ chainSupport: 0.15,
540
+ maliciousPatterns: 0.3,
541
+ // Highest weight - security critical
542
+ identityConsistency: 0.1
543
+ }, confidence = securityScore.walletStandardCompliance * weights.walletStandardCompliance + securityScore.methodIntegrity * weights.methodIntegrity + securityScore.chainSupport * weights.chainSupport + securityScore.maliciousPatterns * weights.maliciousPatterns + securityScore.identityConsistency * weights.identityConsistency, authentic = confidence >= 0.6 && securityScore.maliciousPatterns > 0.5, reason = authentic ? "Wallet passed all security checks" : `Wallet failed security checks (confidence: ${Math.round(confidence * 100)}%)`;
544
+ return logger2.debug("Wallet verification complete", {
545
+ name,
546
+ authentic,
547
+ confidence: Math.round(confidence * 100) / 100,
548
+ warnings: warnings.length
549
+ }), {
550
+ authentic,
551
+ confidence,
552
+ reason,
553
+ warnings,
554
+ securityScore
555
+ };
556
+ }
557
+ /**
558
+ * Check Wallet Standard compliance
559
+ * Returns score 0-1 based on how well the wallet implements the standard
560
+ */
561
+ static checkWalletStandardCompliance(wallet) {
562
+ let warnings = [], score = 0;
563
+ if (wallet.features && typeof wallet.features == "object") {
564
+ score += 0.3;
565
+ let requiredFeatures = ["standard:connect", "standard:disconnect", "standard:events"], presentFeatures = requiredFeatures.filter((feature) => feature in wallet.features);
566
+ score += presentFeatures.length / requiredFeatures.length * 0.4;
567
+ let solanaFeatures = [
568
+ "solana:signTransaction",
569
+ "solana:signAndSendTransaction",
570
+ "solana:signMessage",
571
+ "solana:signAllTransactions"
572
+ ], presentSolanaFeatures = solanaFeatures.filter((feature) => feature in wallet.features);
573
+ score += presentSolanaFeatures.length / solanaFeatures.length * 0.3, presentFeatures.length < requiredFeatures.length && warnings.push("Wallet missing some standard features");
574
+ } else
575
+ warnings.push("Wallet does not implement Wallet Standard");
576
+ return { score: Math.min(score, 1), warnings };
577
+ }
578
+ /**
579
+ * Validate method integrity
580
+ * Checks if methods appear to be genuine and not tampered with
581
+ */
582
+ static checkMethodIntegrity(wallet) {
583
+ let warnings = [], score = 0, walletObj = wallet, criticalMethods = ["connect", "disconnect"], existingMethods = criticalMethods.filter((method) => typeof walletObj[method] == "function");
584
+ if (existingMethods.length === 0)
585
+ return warnings.push("Wallet missing critical methods"), { score: 0, warnings };
586
+ score += existingMethods.length / criticalMethods.length * 0.5;
587
+ let suspiciousMethodCount = 0;
588
+ for (let method of existingMethods) {
589
+ let funcStr = walletObj[method].toString();
590
+ funcStr.length > 1e3 && (suspiciousMethodCount++, warnings.push(`Method ${method} has unusually long implementation`));
591
+ let suspiciousKeywords = ["fetch(", "XMLHttpRequest", "sendToServer", "exfiltrate", "steal", "phish"];
592
+ for (let keyword of suspiciousKeywords)
593
+ if (funcStr.includes(keyword)) {
594
+ suspiciousMethodCount++, warnings.push(`Method ${method} contains suspicious code pattern`);
595
+ break;
596
+ }
597
+ }
598
+ let suspiciousRatio = suspiciousMethodCount / existingMethods.length;
599
+ return score += (1 - suspiciousRatio) * 0.5, { score: Math.max(0, Math.min(score, 1)), warnings };
600
+ }
601
+ /**
602
+ * Verify Solana chain support
603
+ */
604
+ static checkChainSupport(wallet) {
605
+ let warnings = [], score = 0;
606
+ return Array.isArray(wallet.chains) ? wallet.chains.some((chain) => String(chain).toLowerCase().includes("solana")) ? score = 1 : (warnings.push("Wallet does not explicitly support Solana chain"), score = 0.3) : wallet.chains === void 0 && (warnings.push("Wallet does not declare supported chains"), score = 0.5), { score, warnings };
607
+ }
608
+ /**
609
+ * Detect common patterns used by malicious wallet extensions
610
+ */
611
+ static detectMaliciousPatterns(wallet, expectedName) {
612
+ let warnings = [], score = 1, walletObj = wallet, identityFlags = Object.keys(walletObj).filter(
613
+ (key) => key.startsWith("is") && (key.endsWith("Wallet") || key.endsWith("wallet") || /^is[A-Z]/.test(key)) && walletObj[key] === true
614
+ );
615
+ identityFlags.length > 2 && (score -= 0.3, warnings.push(`Multiple wallet identity flags detected: ${identityFlags.join(", ")}`));
616
+ let explicitlyMaliciousProps = [
617
+ "stealPrivateKey",
618
+ "getPrivateKey",
619
+ "exportPrivateKey",
620
+ "sendToAttacker",
621
+ "phishingUrl",
622
+ "malware",
623
+ "backdoor"
624
+ ], lowerCaseKeys = Object.keys(walletObj).map((k) => k.toLowerCase());
625
+ for (let prop of explicitlyMaliciousProps)
626
+ lowerCaseKeys.includes(prop.toLowerCase()) && (score = 0, warnings.push(`Explicitly malicious property detected: ${prop}`));
627
+ let urlProps = ["iconUrl", "url", "homepage", "website"];
628
+ for (let prop of urlProps) {
629
+ let value = walletObj[prop];
630
+ typeof value == "string" && this.isSuspiciousUrl(value) && (score -= 0.2, warnings.push(`Suspicious URL in ${prop}: ${value}`));
631
+ }
632
+ if ("__proto__" in walletObj || "constructor" in walletObj) {
633
+ let proto = Object.getPrototypeOf(walletObj);
634
+ proto !== Object.prototype && proto !== null && (score -= 0.1, warnings.push("Wallet has unusual prototype chain"));
635
+ }
636
+ let propCount = Object.keys(walletObj).length;
637
+ return propCount > 100 && (score -= 0.1, warnings.push(`Wallet has unusually many properties (${propCount})`)), { score: Math.max(0, score), warnings };
638
+ }
639
+ /**
640
+ * Check if wallet identity is consistent with expected name
641
+ */
642
+ static checkIdentityConsistency(wallet, expectedName) {
643
+ let warnings = [], score = 0, walletObj = wallet, name = expectedName.toLowerCase(), identityIndicators = [
644
+ walletObj.name,
645
+ walletObj.providerName,
646
+ walletObj.metadata?.name,
647
+ walletObj._metadata?.name
648
+ ].filter(Boolean), hasMatch = false;
649
+ for (let indicator of identityIndicators)
650
+ if (typeof indicator == "string" && indicator.toLowerCase().includes(name)) {
651
+ hasMatch = true, score += 0.5;
652
+ break;
653
+ }
654
+ let capitalizedName = name.charAt(0).toUpperCase() + name.slice(1), identityFlags = [
655
+ `is${capitalizedName}`,
656
+ `is${capitalizedName}Wallet`,
657
+ `is${capitalizedName.toLowerCase()}`
658
+ ];
659
+ for (let flag of identityFlags)
660
+ if (walletObj[flag] === true) {
661
+ hasMatch = true, score += 0.5;
662
+ break;
663
+ }
664
+ return hasMatch || warnings.push(`Wallet identity does not match expected name: ${expectedName}`), { score: Math.min(score, 1), warnings };
665
+ }
666
+ /**
667
+ * Check if a URL looks suspicious
668
+ */
669
+ static isSuspiciousUrl(url) {
670
+ try {
671
+ let parsed = new URL(url), suspiciousPatterns = [
672
+ "bit.ly",
673
+ "tinyurl.com",
674
+ "tiny.cc",
675
+ "is.gd",
676
+ "goo.gl",
677
+ "t.co",
678
+ ".tk",
679
+ // Free domain TLDs
680
+ ".ml",
681
+ ".ga",
682
+ ".cf",
683
+ ".gq"
684
+ ], hostname = parsed.hostname.toLowerCase();
685
+ return !!(suspiciousPatterns.some((pattern) => hostname.includes(pattern)) || /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname) || hostname.split(".").length > 4);
686
+ } catch {
687
+ return true;
688
+ }
689
+ }
690
+ /**
691
+ * Batch verify multiple wallets
692
+ *
693
+ * @param wallets - Array of wallet objects with their names
694
+ * @returns Map of wallet names to verification results
695
+ */
696
+ static verifyBatch(wallets) {
697
+ let results = /* @__PURE__ */ new Map();
698
+ for (let { wallet, name } of wallets)
699
+ results.set(name, this.verify(wallet, name));
700
+ return results;
701
+ }
702
+ /**
703
+ * Get a human-readable security report for a wallet
704
+ *
705
+ * @param result - Verification result
706
+ * @returns Formatted security report
707
+ */
708
+ static getSecurityReport(result) {
709
+ let lines = [];
710
+ return lines.push(`Security Assessment: ${result.authentic ? "\u2705 PASSED" : "\u274C FAILED"}`), lines.push(`Overall Confidence: ${Math.round(result.confidence * 100)}%`), lines.push(""), lines.push("Score Breakdown:"), lines.push(
711
+ ` - Wallet Standard Compliance: ${Math.round(result.securityScore.walletStandardCompliance * 100)}%`
712
+ ), lines.push(` - Method Integrity: ${Math.round(result.securityScore.methodIntegrity * 100)}%`), lines.push(` - Chain Support: ${Math.round(result.securityScore.chainSupport * 100)}%`), lines.push(` - Malicious Patterns: ${Math.round(result.securityScore.maliciousPatterns * 100)}%`), lines.push(` - Identity Consistency: ${Math.round(result.securityScore.identityConsistency * 100)}%`), result.warnings.length > 0 && (lines.push(""), lines.push("Warnings:"), result.warnings.forEach((w) => lines.push(` \u26A0\uFE0F ${w}`))), lines.join(`
713
+ `);
714
+ }
715
+ };
716
+
717
+ // src/lib/connection/wallet-detector.ts
718
+ var logger3 = createLogger("WalletDetector");
719
+ function hasFeature(wallet, featureName) {
720
+ return wallet.features != null && wallet.features[featureName] !== void 0;
721
+ }
722
+ function verifyWalletName(wallet, requestedName) {
723
+ let name = requestedName.toLowerCase(), walletObj = wallet, nameFields = [
724
+ walletObj.name,
725
+ walletObj.providerName,
726
+ walletObj.metadata?.name
727
+ ].filter(Boolean);
728
+ for (let field of nameFields)
729
+ if (typeof field == "string" && field.toLowerCase().includes(name))
730
+ return true;
731
+ let capitalizedName = name.charAt(0).toUpperCase() + name.slice(1), commonFlagPatterns = [`is${capitalizedName}`, `is${capitalizedName}Wallet`];
732
+ for (let flagName of commonFlagPatterns)
733
+ if (walletObj[flagName] === true)
734
+ return true;
735
+ return false;
736
+ }
737
+ var WalletDetector = class extends BaseCollaborator {
738
+ constructor(stateManager, eventEmitter, debug = false) {
739
+ super({ stateManager, eventEmitter, debug }, "WalletDetector");
740
+ __publicField(this, "unsubscribers", []);
741
+ }
742
+ /**
743
+ * Initialize wallet detection
744
+ */
745
+ initialize() {
746
+ if (!(typeof window > "u"))
747
+ try {
748
+ let walletsApi = getWalletsRegistry(), update = () => {
749
+ let ws = walletsApi.get(), previousCount = this.getState().wallets.length, newCount = ws.length;
750
+ newCount !== previousCount && this.log("\u{1F50D} WalletDetector: found wallets:", newCount);
751
+ let unique = this.deduplicateWallets(ws);
752
+ this.stateManager.updateState({
753
+ wallets: unique.map((w) => this.mapToWalletInfo(w))
754
+ }), newCount !== previousCount && newCount > 0 && this.eventEmitter.emit({
755
+ type: "wallets:detected",
756
+ count: newCount,
757
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
758
+ });
759
+ };
760
+ update(), this.unsubscribers.push(walletsApi.on("register", update)), this.unsubscribers.push(walletsApi.on("unregister", update)), setTimeout(() => {
761
+ this.getState().connected || update();
762
+ }, 1e3);
763
+ } catch {
764
+ }
765
+ }
766
+ /**
767
+ * Check if a specific wallet is available immediately via direct window object detection
768
+ */
769
+ detectDirectWallet(walletName) {
770
+ if (typeof window > "u") return null;
771
+ let name = walletName.toLowerCase(), windowObj = window, checks = [
772
+ () => windowObj[name],
773
+ () => windowObj[`${name}Wallet`],
774
+ () => windowObj.solana,
775
+ () => {
776
+ let keys = Object.keys(window).filter((k) => k.toLowerCase().includes(name));
777
+ return keys.length > 0 ? windowObj[keys[0]] : null;
778
+ }
779
+ ];
780
+ for (let check of checks)
781
+ try {
782
+ let result = check();
783
+ if (result && typeof result == "object") {
784
+ let wallet = result;
785
+ if (!verifyWalletName(wallet, walletName))
786
+ continue;
787
+ let verification = WalletAuthenticityVerifier.verify(wallet, walletName);
788
+ if (!verification.authentic) {
789
+ logger3.warn("Rejecting potentially malicious wallet", {
790
+ name: walletName,
791
+ reason: verification.reason,
792
+ confidence: verification.confidence
793
+ });
794
+ continue;
795
+ }
796
+ verification.warnings.length > 0 && logger3.warn("Wallet verification warnings", {
797
+ name: walletName,
798
+ warnings: verification.warnings
799
+ });
800
+ let hasStandardConnect = wallet.features?.["standard:connect"], hasLegacyConnect = typeof wallet.connect == "function";
801
+ if (hasStandardConnect || hasLegacyConnect)
802
+ return logger3.debug("Authentic wallet detected", {
803
+ name: walletName,
804
+ confidence: verification.confidence
805
+ }), wallet;
806
+ }
807
+ } catch {
808
+ continue;
809
+ }
810
+ return null;
811
+ }
812
+ /**
813
+ * Get currently detected wallets
814
+ */
815
+ getDetectedWallets() {
816
+ return this.getState().wallets;
817
+ }
818
+ /**
819
+ * Convert a Wallet Standard wallet to WalletInfo with capability checks
820
+ */
821
+ mapToWalletInfo(wallet) {
822
+ let hasConnect = hasFeature(wallet, "standard:connect"), hasDisconnect = hasFeature(wallet, "standard:disconnect"), isSolana = Array.isArray(wallet.chains) && wallet.chains.some((c) => typeof c == "string" && c.includes("solana"));
823
+ return {
824
+ wallet,
825
+ installed: true,
826
+ connectable: hasConnect && hasDisconnect && isSolana
827
+ };
828
+ }
829
+ /**
830
+ * Deduplicate wallets by name (keeps first occurrence)
831
+ */
832
+ deduplicateWallets(wallets) {
833
+ let seen = /* @__PURE__ */ new Map();
834
+ for (let wallet of wallets)
835
+ seen.has(wallet.name) || seen.set(wallet.name, wallet);
836
+ return Array.from(seen.values());
837
+ }
838
+ /**
839
+ * Cleanup resources
840
+ */
841
+ destroy() {
842
+ for (let unsubscribe of this.unsubscribers)
843
+ try {
844
+ unsubscribe();
845
+ } catch {
846
+ }
847
+ this.unsubscribers = [];
848
+ }
849
+ };
850
+
851
+ // src/lib/connection/connection-manager.ts
852
+ function getConnectFeature(wallet) {
853
+ return wallet.features["standard:connect"]?.connect ?? null;
854
+ }
855
+ function getDisconnectFeature(wallet) {
856
+ return wallet.features["standard:disconnect"]?.disconnect ?? null;
857
+ }
858
+ function getEventsFeature(wallet) {
859
+ return wallet.features["standard:events"]?.on ?? null;
860
+ }
861
+ var ConnectionManager = class extends BaseCollaborator {
862
+ constructor(stateManager, eventEmitter, walletStorage, debug = false) {
863
+ super({ stateManager, eventEmitter, debug }, "ConnectionManager");
864
+ __publicField(this, "walletStorage");
865
+ __publicField(this, "walletChangeUnsub", null);
866
+ __publicField(this, "pollTimer", null);
867
+ __publicField(this, "pollAttempts", 0);
868
+ this.walletStorage = walletStorage;
869
+ }
870
+ /**
871
+ * Connect to a wallet
872
+ */
873
+ async connect(wallet, walletName) {
874
+ if (typeof window > "u") return;
875
+ let name = walletName || wallet.name;
876
+ this.eventEmitter.emit({
877
+ type: "connecting",
878
+ wallet: name,
879
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
880
+ }), this.stateManager.updateState({ connecting: true }, true);
881
+ try {
882
+ let connect = getConnectFeature(wallet);
883
+ if (!connect) throw new Error(`Wallet ${name} does not support standard connect`);
884
+ let result = await connect({ silent: false }), walletAccounts = wallet.accounts, accountMap = /* @__PURE__ */ new Map();
885
+ for (let a of [...walletAccounts, ...result.accounts]) accountMap.set(a.address, a);
886
+ let accounts = Array.from(accountMap.values()).map((a) => this.toAccountInfo(a)), state = this.getState(), previouslySelected = state.selectedAccount, previousAddresses = new Set(state.accounts.map((a) => a.address)), selected = accounts.find((a) => !previousAddresses.has(a.address))?.address ?? previouslySelected ?? accounts[0]?.address ?? null;
887
+ this.stateManager.updateState(
888
+ {
889
+ selectedWallet: wallet,
890
+ connected: true,
891
+ connecting: false,
892
+ accounts,
893
+ selectedAccount: selected
894
+ },
895
+ true
896
+ ), this.log("\u2705 Connection successful - state updated:", {
897
+ connected: true,
898
+ selectedWallet: wallet.name,
899
+ selectedAccount: selected,
900
+ accountsCount: accounts.length
901
+ }), this.eventEmitter.emit({
902
+ type: "wallet:connected",
903
+ wallet: name,
904
+ account: selected || "",
905
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
906
+ }), this.walletStorage && (!("isAvailable" in this.walletStorage) || typeof this.walletStorage.isAvailable != "function" || this.walletStorage.isAvailable() ? this.walletStorage.set(name) : this.log("Storage not available (private browsing?), skipping wallet persistence")), this.subscribeToWalletEvents();
907
+ } catch (e) {
908
+ let errorMessage = e instanceof Error ? e.message : String(e);
909
+ throw this.eventEmitter.emit({
910
+ type: "connection:failed",
911
+ wallet: name,
912
+ error: errorMessage,
913
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
914
+ }), this.eventEmitter.emit({
915
+ type: "error",
916
+ error: e instanceof Error ? e : new Error(errorMessage),
917
+ context: "wallet-connection",
918
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
919
+ }), this.stateManager.updateState(
920
+ {
921
+ selectedWallet: null,
922
+ connected: false,
923
+ connecting: false,
924
+ accounts: [],
925
+ selectedAccount: null
926
+ },
927
+ true
928
+ ), e;
929
+ }
930
+ }
931
+ /**
932
+ * Disconnect from wallet
933
+ */
934
+ async disconnect() {
935
+ if (this.walletChangeUnsub) {
936
+ try {
937
+ this.walletChangeUnsub();
938
+ } catch {
939
+ }
940
+ this.walletChangeUnsub = null;
941
+ }
942
+ this.stopPollingWalletAccounts();
943
+ let wallet = this.getState().selectedWallet;
944
+ if (wallet) {
945
+ let disconnect = getDisconnectFeature(wallet);
946
+ if (disconnect)
947
+ try {
948
+ await disconnect();
949
+ } catch {
950
+ }
951
+ }
952
+ this.stateManager.updateState(
953
+ {
954
+ selectedWallet: null,
955
+ connected: false,
956
+ accounts: [],
957
+ selectedAccount: null
958
+ },
959
+ true
960
+ ), this.eventEmitter.emit({
961
+ type: "wallet:disconnected",
962
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
963
+ }), this.walletStorage && "clear" in this.walletStorage && typeof this.walletStorage.clear == "function" ? this.walletStorage.clear() : this.walletStorage?.set(void 0);
964
+ }
965
+ /**
966
+ * Select a different account
967
+ */
968
+ async selectAccount(address) {
969
+ let state = this.getState(), current = state.selectedWallet;
970
+ if (!current) throw new Error("No wallet connected");
971
+ if (!address || address.length < 5)
972
+ throw new Error(`Invalid address format: ${address}`);
973
+ let target = state.accounts.find((acc) => acc.address === address)?.raw ?? null;
974
+ if (!target)
975
+ try {
976
+ let connect = getConnectFeature(current);
977
+ if (connect) {
978
+ let accounts = (await connect()).accounts.map((a) => this.toAccountInfo(a));
979
+ target = accounts.find((acc) => acc.address === address)?.raw ?? null, this.stateManager.updateState({ accounts });
980
+ }
981
+ } catch {
982
+ throw new Error("Failed to reconnect wallet for account selection");
983
+ }
984
+ if (!target) throw new Error(`Requested account not available: ${address}`);
985
+ this.stateManager.updateState({ selectedAccount: target.address }), this.eventEmitter.emit({
986
+ type: "account:changed",
987
+ account: target.address,
988
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
989
+ });
990
+ }
991
+ /**
992
+ * Convert wallet account to AccountInfo
993
+ */
994
+ toAccountInfo(account) {
995
+ return {
996
+ address: account.address,
997
+ icon: account.icon,
998
+ raw: account
999
+ };
1000
+ }
1001
+ /**
1002
+ * Subscribe to wallet change events
1003
+ */
1004
+ subscribeToWalletEvents() {
1005
+ if (this.walletChangeUnsub) {
1006
+ try {
1007
+ this.walletChangeUnsub();
1008
+ } catch {
1009
+ }
1010
+ this.walletChangeUnsub = null;
1011
+ }
1012
+ this.stopPollingWalletAccounts();
1013
+ let wallet = this.getState().selectedWallet;
1014
+ if (!wallet) return;
1015
+ let eventsOn = getEventsFeature(wallet);
1016
+ if (!eventsOn) {
1017
+ this.startPollingWalletAccounts();
1018
+ return;
1019
+ }
1020
+ try {
1021
+ this.walletChangeUnsub = eventsOn("change", (properties) => {
1022
+ let changeAccounts = properties?.accounts ?? [];
1023
+ if (changeAccounts.length === 0) return;
1024
+ let nextAccounts = changeAccounts.map((a) => this.toAccountInfo(a));
1025
+ nextAccounts.length > 0 && this.stateManager.updateState({
1026
+ accounts: nextAccounts
1027
+ });
1028
+ });
1029
+ } catch {
1030
+ this.startPollingWalletAccounts();
1031
+ }
1032
+ }
1033
+ /**
1034
+ * Start polling wallet accounts (fallback when events not available)
1035
+ * Uses exponential backoff to reduce polling frequency over time
1036
+ */
1037
+ startPollingWalletAccounts() {
1038
+ if (this.pollTimer) return;
1039
+ let wallet = this.getState().selectedWallet;
1040
+ if (!wallet) return;
1041
+ this.pollAttempts = 0;
1042
+ let poll = () => {
1043
+ if (this.pollAttempts >= 20) {
1044
+ this.stopPollingWalletAccounts(), this.log("Stopped wallet polling after max attempts");
1045
+ return;
1046
+ }
1047
+ try {
1048
+ let state = this.getState(), nextAccounts = wallet.accounts.map((a) => this.toAccountInfo(a));
1049
+ state.accounts.length === 0 && nextAccounts.length > 0 && (this.stateManager.updateState({
1050
+ accounts: nextAccounts,
1051
+ selectedAccount: state.selectedAccount || nextAccounts[0]?.address || null
1052
+ }), this.pollAttempts = 0);
1053
+ } catch (error) {
1054
+ this.log("Wallet polling error:", error);
1055
+ }
1056
+ this.pollAttempts++;
1057
+ let intervalIndex = Math.min(this.pollAttempts, POLL_INTERVALS_MS.length - 1), interval = POLL_INTERVALS_MS[intervalIndex];
1058
+ this.pollTimer = setTimeout(poll, interval);
1059
+ };
1060
+ poll();
1061
+ }
1062
+ /**
1063
+ * Stop polling wallet accounts
1064
+ */
1065
+ stopPollingWalletAccounts() {
1066
+ this.pollTimer && (clearTimeout(this.pollTimer), this.pollTimer = null, this.pollAttempts = 0);
1067
+ }
1068
+ /**
1069
+ * Get stored wallet name
1070
+ */
1071
+ getStoredWallet() {
1072
+ return this.walletStorage?.get() ?? null;
1073
+ }
1074
+ };
1075
+
1076
+ // src/lib/connection/auto-connector.ts
1077
+ var logger4 = createLogger("AutoConnector"), MIN_ADDRESS_LENGTH = 30, AutoConnector = class {
1078
+ constructor(walletDetector, connectionManager, stateManager, walletStorage, debug = false) {
1079
+ __publicField(this, "walletDetector");
1080
+ __publicField(this, "connectionManager");
1081
+ __publicField(this, "stateManager");
1082
+ __publicField(this, "walletStorage");
1083
+ __publicField(this, "debug");
1084
+ this.walletDetector = walletDetector, this.connectionManager = connectionManager, this.stateManager = stateManager, this.walletStorage = walletStorage, this.debug = debug;
1085
+ }
1086
+ /**
1087
+ * Attempt auto-connection using both instant and fallback strategies
1088
+ */
1089
+ async attemptAutoConnect() {
1090
+ return await this.attemptInstantConnect() ? true : (await this.attemptStandardConnect(), this.stateManager.getSnapshot().connected);
1091
+ }
1092
+ /**
1093
+ * Attempt instant auto-connection using direct wallet detection
1094
+ * Bypasses wallet standard initialization for maximum speed
1095
+ */
1096
+ async attemptInstantConnect() {
1097
+ let storedWalletName = this.walletStorage?.get();
1098
+ if (!storedWalletName) return false;
1099
+ let directWallet = this.walletDetector.detectDirectWallet(storedWalletName);
1100
+ if (!directWallet) return false;
1101
+ this.debug && logger4.info("Instant auto-connect: found wallet directly in window", { walletName: storedWalletName });
1102
+ try {
1103
+ let features = {};
1104
+ if (directWallet.connect && (features["standard:connect"] = {
1105
+ connect: async (...args) => {
1106
+ let options = args[0], result = await directWallet.connect(options);
1107
+ if (this.debug && (logger4.debug("Direct wallet connect result", { result }), logger4.debug("Direct wallet publicKey property", { publicKey: directWallet.publicKey })), result && typeof result == "object" && "accounts" in result && Array.isArray(result.accounts))
1108
+ return result;
1109
+ let legacyResult = result;
1110
+ if (legacyResult?.publicKey && typeof legacyResult.publicKey.toString == "function")
1111
+ return {
1112
+ accounts: [
1113
+ {
1114
+ address: legacyResult.publicKey.toString(),
1115
+ publicKey: legacyResult.publicKey.toBytes ? legacyResult.publicKey.toBytes() : new Uint8Array(),
1116
+ chains: ["solana:mainnet", "solana:devnet", "solana:testnet"],
1117
+ features: []
1118
+ }
1119
+ ]
1120
+ };
1121
+ if (directWallet.publicKey && typeof directWallet.publicKey.toString == "function") {
1122
+ let address = directWallet.publicKey.toString();
1123
+ return this.debug && logger4.debug("Using legacy wallet pattern - publicKey from wallet object"), {
1124
+ accounts: [
1125
+ {
1126
+ address,
1127
+ publicKey: directWallet.publicKey.toBytes ? directWallet.publicKey.toBytes() : new Uint8Array(),
1128
+ chains: ["solana:mainnet", "solana:devnet", "solana:testnet"],
1129
+ features: []
1130
+ }
1131
+ ]
1132
+ };
1133
+ }
1134
+ let publicKeyResult = result;
1135
+ return publicKeyResult && typeof publicKeyResult.toString == "function" && publicKeyResult.toString().length > MIN_ADDRESS_LENGTH ? {
1136
+ accounts: [
1137
+ {
1138
+ address: publicKeyResult.toString(),
1139
+ publicKey: publicKeyResult.toBytes ? publicKeyResult.toBytes() : new Uint8Array(),
1140
+ chains: ["solana:mainnet", "solana:devnet", "solana:testnet"],
1141
+ features: []
1142
+ }
1143
+ ]
1144
+ } : (this.debug && logger4.error("Legacy wallet: No valid publicKey found in any expected location"), { accounts: [] });
1145
+ }
1146
+ }), directWallet.disconnect) {
1147
+ let disconnectFn = directWallet.disconnect;
1148
+ features["standard:disconnect"] = {
1149
+ disconnect: () => disconnectFn.call(directWallet)
1150
+ };
1151
+ }
1152
+ if (directWallet.signTransaction) {
1153
+ let signTransactionFn = directWallet.signTransaction;
1154
+ features["standard:signTransaction"] = {
1155
+ signTransaction: (tx) => signTransactionFn.call(directWallet, tx)
1156
+ };
1157
+ }
1158
+ if (directWallet.signMessage) {
1159
+ let signMessageFn = directWallet.signMessage;
1160
+ features["standard:signMessage"] = {
1161
+ signMessage: (...args) => {
1162
+ let msg = args[0];
1163
+ return signMessageFn.call(directWallet, msg);
1164
+ }
1165
+ };
1166
+ }
1167
+ directWallet.features && Object.assign(features, directWallet.features);
1168
+ let walletIcon = directWallet.icon || directWallet._metadata?.icon || directWallet.adapter?.icon || directWallet.metadata?.icon || directWallet.iconUrl, wallet = {
1169
+ version: "1.0.0",
1170
+ name: storedWalletName,
1171
+ icon: walletIcon,
1172
+ chains: directWallet.chains || [
1173
+ "solana:mainnet",
1174
+ "solana:devnet",
1175
+ "solana:testnet"
1176
+ ],
1177
+ features,
1178
+ accounts: []
1179
+ };
1180
+ return this.stateManager.updateState(
1181
+ {
1182
+ wallets: [
1183
+ {
1184
+ wallet,
1185
+ installed: true,
1186
+ connectable: true
1187
+ }
1188
+ ]
1189
+ },
1190
+ true
1191
+ ), this.debug && logger4.info("Attempting to connect via instant auto-connect", { walletName: storedWalletName }), await this.connectionManager.connect(wallet, storedWalletName), this.debug && logger4.info("Instant auto-connect successful", { walletName: storedWalletName }), setTimeout(() => {
1192
+ let ws = getWalletsRegistry().get();
1193
+ this.debug && logger4.debug("Checking for wallet standard update", {
1194
+ wsLength: ws.length,
1195
+ currentWalletsLength: this.stateManager.getSnapshot().wallets.length,
1196
+ shouldUpdate: ws.length > 1
1197
+ }), ws.length > 1 && this.walletDetector.initialize();
1198
+ }, 500), true;
1199
+ } catch (error) {
1200
+ return this.debug && logger4.error("Instant auto-connect failed", {
1201
+ walletName: storedWalletName,
1202
+ error: error instanceof Error ? error.message : error
1203
+ }), false;
1204
+ }
1205
+ }
1206
+ /**
1207
+ * Attempt auto-connection via standard wallet detection (fallback)
1208
+ */
1209
+ async attemptStandardConnect() {
1210
+ try {
1211
+ if (this.stateManager.getSnapshot().connected) {
1212
+ this.debug && logger4.info("Auto-connect: Already connected, skipping fallback auto-connect");
1213
+ return;
1214
+ }
1215
+ let storedWalletName = this.walletStorage?.get();
1216
+ if (this.debug && (logger4.debug("Auto-connect: stored wallet", { storedWalletName }), logger4.debug("Auto-connect: available wallets", {
1217
+ wallets: this.stateManager.getSnapshot().wallets.map((w) => w.wallet.name)
1218
+ })), !storedWalletName) return;
1219
+ let walletInfo = this.stateManager.getSnapshot().wallets.find((w) => w.wallet.name === storedWalletName);
1220
+ walletInfo ? (this.debug && logger4.info("Auto-connect: Found stored wallet, connecting"), await this.connectionManager.connect(walletInfo.wallet, storedWalletName)) : setTimeout(() => {
1221
+ let retryWallet = this.stateManager.getSnapshot().wallets.find((w) => w.wallet.name === storedWalletName);
1222
+ retryWallet && (this.debug && logger4.info("Auto-connect: Retry successful"), this.connectionManager.connect(retryWallet.wallet, storedWalletName).catch((err) => {
1223
+ logger4.error("Auto-connect retry connection failed", { error: err });
1224
+ }));
1225
+ }, 1e3);
1226
+ } catch (e) {
1227
+ this.debug && logger4.error("Auto-connect failed", { error: e }), this.walletStorage?.set(void 0);
1228
+ }
1229
+ }
1230
+ };
1231
+
1232
+ // src/lib/cluster/cluster-manager.ts
1233
+ var ClusterManager = class extends BaseCollaborator {
1234
+ constructor(stateManager, eventEmitter, clusterStorage, config, debug = false) {
1235
+ super({ stateManager, eventEmitter, debug }, "ClusterManager");
1236
+ __publicField(this, "clusterStorage");
1237
+ if (this.clusterStorage = clusterStorage, config) {
1238
+ let clusters = config.clusters ?? [], initialClusterId = this.clusterStorage?.get() ?? config.initialCluster ?? "solana:mainnet", initialCluster = clusters.find((c) => c.id === initialClusterId) ?? clusters[0] ?? null;
1239
+ this.stateManager.updateState({
1240
+ cluster: initialCluster,
1241
+ clusters
1242
+ });
1243
+ }
1244
+ }
1245
+ /**
1246
+ * Set the active cluster (network)
1247
+ */
1248
+ async setCluster(clusterId) {
1249
+ let state = this.getState(), previousClusterId = state.cluster?.id || null, cluster = state.clusters.find((c) => c.id === clusterId);
1250
+ if (!cluster)
1251
+ throw Errors.clusterNotFound(
1252
+ clusterId,
1253
+ state.clusters.map((c) => c.id)
1254
+ );
1255
+ this.stateManager.updateState({ cluster }, true), this.clusterStorage && (!("isAvailable" in this.clusterStorage) || typeof this.clusterStorage.isAvailable != "function" || this.clusterStorage.isAvailable() ? this.clusterStorage.set(clusterId) : this.log("Storage not available (private browsing?), skipping cluster persistence")), previousClusterId !== clusterId && this.eventEmitter.emit({
1256
+ type: "cluster:changed",
1257
+ cluster: clusterId,
1258
+ previousCluster: previousClusterId,
1259
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1260
+ }), this.log("\u{1F310} Cluster changed:", { from: previousClusterId, to: clusterId });
1261
+ }
1262
+ /**
1263
+ * Get the currently active cluster
1264
+ */
1265
+ getCluster() {
1266
+ return this.getState().cluster;
1267
+ }
1268
+ /**
1269
+ * Get all available clusters
1270
+ */
1271
+ getClusters() {
1272
+ return this.getState().clusters;
1273
+ }
1274
+ };
1275
+
1276
+ // src/lib/transaction/transaction-tracker.ts
1277
+ var TransactionTracker = class extends BaseCollaborator {
1278
+ constructor(stateManager, eventEmitter, maxTransactions = 20, debug = false) {
1279
+ super({ stateManager, eventEmitter, debug }, "TransactionTracker");
1280
+ __publicField(this, "transactions", []);
1281
+ __publicField(this, "totalTransactions", 0);
1282
+ __publicField(this, "maxTransactions");
1283
+ this.maxTransactions = maxTransactions;
1284
+ }
1285
+ /**
1286
+ * Track a transaction for debugging and monitoring
1287
+ */
1288
+ trackTransaction(activity) {
1289
+ let state = this.getState(), fullActivity = {
1290
+ ...activity,
1291
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1292
+ cluster: state.cluster?.id || "solana:devnet"
1293
+ };
1294
+ this.transactions.unshift(fullActivity), this.transactions.length > this.maxTransactions && this.transactions.pop(), this.totalTransactions++, this.eventEmitter.emit({
1295
+ type: "transaction:tracked",
1296
+ signature: fullActivity.signature,
1297
+ status: fullActivity.status,
1298
+ timestamp: fullActivity.timestamp
1299
+ }), this.log("[Connector] Transaction tracked:", fullActivity);
1300
+ }
1301
+ /**
1302
+ * Update transaction status (e.g., from pending to confirmed/failed)
1303
+ */
1304
+ updateStatus(signature, status, error) {
1305
+ let tx = this.transactions.find((t) => t.signature === signature);
1306
+ tx && (tx.status = status, error && (tx.error = error), this.eventEmitter.emit({
1307
+ type: "transaction:updated",
1308
+ signature,
1309
+ status,
1310
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1311
+ }), this.log("[Connector] Transaction updated:", { signature, status, error }));
1312
+ }
1313
+ /**
1314
+ * Get transaction history
1315
+ */
1316
+ getTransactions() {
1317
+ return [...this.transactions];
1318
+ }
1319
+ /**
1320
+ * Get total transaction count
1321
+ */
1322
+ getTotalCount() {
1323
+ return this.totalTransactions;
1324
+ }
1325
+ /**
1326
+ * Clear transaction history
1327
+ */
1328
+ clearHistory() {
1329
+ this.transactions = [];
1330
+ }
1331
+ };
1332
+
1333
+ // src/lib/health/health-monitor.ts
1334
+ var HealthMonitor = class {
1335
+ constructor(stateManager, walletStorage, clusterStorage, isInitialized) {
1336
+ __publicField(this, "stateManager");
1337
+ __publicField(this, "walletStorage");
1338
+ __publicField(this, "clusterStorage");
1339
+ __publicField(this, "isInitialized");
1340
+ this.stateManager = stateManager, this.walletStorage = walletStorage, this.clusterStorage = clusterStorage, this.isInitialized = isInitialized ?? (() => true);
1341
+ }
1342
+ /**
1343
+ * Check connector health and availability
1344
+ */
1345
+ getHealth() {
1346
+ let errors = [], walletStandardAvailable = false;
1347
+ try {
1348
+ let registry2 = getWalletsRegistry();
1349
+ walletStandardAvailable = !!(registry2 && typeof registry2.get == "function"), walletStandardAvailable || errors.push("Wallet Standard registry not properly initialized");
1350
+ } catch (error) {
1351
+ errors.push(`Wallet Standard error: ${error instanceof Error ? error.message : "Unknown error"}`), walletStandardAvailable = false;
1352
+ }
1353
+ let storageAvailable = false;
1354
+ try {
1355
+ if (!this.walletStorage || !this.clusterStorage)
1356
+ errors.push("Storage adapters not configured"), storageAvailable = false;
1357
+ else {
1358
+ if ("isAvailable" in this.walletStorage && typeof this.walletStorage.isAvailable == "function")
1359
+ storageAvailable = this.walletStorage.isAvailable();
1360
+ else if (typeof window < "u")
1361
+ try {
1362
+ let testKey = "__connector_storage_test__";
1363
+ window.localStorage.setItem(testKey, "test"), window.localStorage.removeItem(testKey), storageAvailable = true;
1364
+ } catch {
1365
+ storageAvailable = false;
1366
+ }
1367
+ storageAvailable || errors.push("localStorage unavailable (private browsing mode or quota exceeded)");
1368
+ }
1369
+ } catch (error) {
1370
+ errors.push(`Storage error: ${error instanceof Error ? error.message : "Unknown error"}`), storageAvailable = false;
1371
+ }
1372
+ let state = this.stateManager.getSnapshot();
1373
+ return state.connected && !state.selectedWallet && errors.push("Inconsistent state: marked as connected but no wallet selected"), state.connected && !state.selectedAccount && errors.push("Inconsistent state: marked as connected but no account selected"), state.connecting && state.connected && errors.push("Inconsistent state: both connecting and connected flags are true"), {
1374
+ initialized: this.isInitialized(),
1375
+ walletStandardAvailable,
1376
+ storageAvailable,
1377
+ walletsDetected: state.wallets.length,
1378
+ errors,
1379
+ connectionState: {
1380
+ connected: state.connected,
1381
+ connecting: state.connecting,
1382
+ hasSelectedWallet: !!state.selectedWallet,
1383
+ hasSelectedAccount: !!state.selectedAccount
1384
+ },
1385
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1386
+ };
1387
+ }
1388
+ };
1389
+
1390
+ // src/lib/core/connector-client.ts
1391
+ var logger5 = createLogger("ConnectorClient"), ConnectorClient = class {
1392
+ constructor(config = {}) {
1393
+ __publicField(this, "stateManager");
1394
+ __publicField(this, "eventEmitter");
1395
+ __publicField(this, "walletDetector");
1396
+ __publicField(this, "connectionManager");
1397
+ __publicField(this, "autoConnector");
1398
+ __publicField(this, "clusterManager");
1399
+ __publicField(this, "transactionTracker");
1400
+ __publicField(this, "debugMetrics");
1401
+ __publicField(this, "healthMonitor");
1402
+ __publicField(this, "initialized", false);
1403
+ __publicField(this, "config");
1404
+ this.config = config;
1405
+ let initialState = {
1406
+ wallets: [],
1407
+ selectedWallet: null,
1408
+ connected: false,
1409
+ connecting: false,
1410
+ accounts: [],
1411
+ selectedAccount: null,
1412
+ cluster: null,
1413
+ clusters: []
1414
+ };
1415
+ this.stateManager = new StateManager(initialState), this.eventEmitter = new EventEmitter(config.debug), this.debugMetrics = new DebugMetrics(), this.walletDetector = new WalletDetector(this.stateManager, this.eventEmitter, config.debug ?? false), this.connectionManager = new ConnectionManager(
1416
+ this.stateManager,
1417
+ this.eventEmitter,
1418
+ config.storage?.wallet,
1419
+ config.debug ?? false
1420
+ ), this.autoConnector = new AutoConnector(
1421
+ this.walletDetector,
1422
+ this.connectionManager,
1423
+ this.stateManager,
1424
+ config.storage?.wallet,
1425
+ config.debug ?? false
1426
+ ), this.clusterManager = new ClusterManager(
1427
+ this.stateManager,
1428
+ this.eventEmitter,
1429
+ config.storage?.cluster,
1430
+ config.cluster,
1431
+ config.debug ?? false
1432
+ ), this.transactionTracker = new TransactionTracker(
1433
+ this.stateManager,
1434
+ this.eventEmitter,
1435
+ DEFAULT_MAX_TRACKED_TRANSACTIONS,
1436
+ config.debug ?? false
1437
+ ), this.healthMonitor = new HealthMonitor(
1438
+ this.stateManager,
1439
+ config.storage?.wallet,
1440
+ config.storage?.cluster,
1441
+ () => this.initialized
1442
+ ), this.initialize();
1443
+ }
1444
+ /**
1445
+ * Initialize the connector
1446
+ */
1447
+ initialize() {
1448
+ if (!(typeof window > "u") && !this.initialized)
1449
+ try {
1450
+ this.walletDetector.initialize(), this.config.autoConnect && setTimeout(() => {
1451
+ this.autoConnector.attemptAutoConnect().catch((err) => {
1452
+ this.config.debug && logger5.error("Auto-connect error", { error: err });
1453
+ });
1454
+ }, 100), this.initialized = true;
1455
+ } catch (e) {
1456
+ this.config.debug && logger5.error("Connector initialization failed", { error: e });
1457
+ }
1458
+ }
1459
+ // ============================================================================
1460
+ // Public API - Delegates to collaborators
1461
+ // ============================================================================
1462
+ /**
1463
+ * Connect to a wallet by name
1464
+ */
1465
+ async select(walletName) {
1466
+ let wallet = this.stateManager.getSnapshot().wallets.find((w) => w.wallet.name === walletName)?.wallet;
1467
+ if (!wallet) throw new Error(`Wallet ${walletName} not found`);
1468
+ await this.connectionManager.connect(wallet, walletName);
1469
+ }
1470
+ /**
1471
+ * Disconnect from the current wallet
1472
+ */
1473
+ async disconnect() {
1474
+ await this.connectionManager.disconnect();
1475
+ }
1476
+ /**
1477
+ * Select a different account
1478
+ */
1479
+ async selectAccount(address) {
1480
+ await this.connectionManager.selectAccount(address);
1481
+ }
1482
+ /**
1483
+ * Set the active cluster (network)
1484
+ */
1485
+ async setCluster(clusterId) {
1486
+ await this.clusterManager.setCluster(clusterId);
1487
+ }
1488
+ /**
1489
+ * Get the currently active cluster
1490
+ */
1491
+ getCluster() {
1492
+ return this.clusterManager.getCluster();
1493
+ }
1494
+ /**
1495
+ * Get all available clusters
1496
+ */
1497
+ getClusters() {
1498
+ return this.clusterManager.getClusters();
1499
+ }
1500
+ /**
1501
+ * Get the RPC URL for the current cluster
1502
+ * @returns RPC URL or null if no cluster is selected
1503
+ */
1504
+ getRpcUrl() {
1505
+ let cluster = this.clusterManager.getCluster();
1506
+ if (!cluster) return null;
1507
+ try {
1508
+ return getClusterRpcUrl(cluster);
1509
+ } catch (error) {
1510
+ return this.config.debug && logger5.error("Failed to get RPC URL", { error }), null;
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Subscribe to state changes
1515
+ */
1516
+ subscribe(listener) {
1517
+ return this.stateManager.subscribe(listener);
1518
+ }
1519
+ /**
1520
+ * Get current state snapshot
1521
+ */
1522
+ getSnapshot() {
1523
+ return this.stateManager.getSnapshot();
1524
+ }
1525
+ /**
1526
+ * Reset all storage to initial values
1527
+ * Useful for "logout", "forget this device", or clearing user data
1528
+ *
1529
+ * This will:
1530
+ * - Clear saved wallet name
1531
+ * - Clear saved account address
1532
+ * - Reset cluster to initial value (does not clear)
1533
+ *
1534
+ * Note: This does NOT disconnect the wallet. Call disconnect() separately if needed.
1535
+ *
1536
+ * @example
1537
+ * ```ts
1538
+ * // Complete logout flow
1539
+ * await client.disconnect();
1540
+ * client.resetStorage();
1541
+ * ```
1542
+ */
1543
+ resetStorage() {
1544
+ this.config.debug && logger5.info("Resetting all storage to initial values");
1545
+ let storageKeys = ["account", "wallet", "cluster"];
1546
+ for (let key of storageKeys) {
1547
+ let storage = this.config.storage?.[key];
1548
+ if (storage && "reset" in storage && typeof storage.reset == "function")
1549
+ try {
1550
+ storage.reset(), this.config.debug && logger5.debug("Reset storage", { key });
1551
+ } catch (error) {
1552
+ this.config.debug && logger5.error("Failed to reset storage", { key, error });
1553
+ }
1554
+ }
1555
+ this.eventEmitter.emit({
1556
+ type: "storage:reset",
1557
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1558
+ });
1559
+ }
1560
+ /**
1561
+ * Subscribe to connector events
1562
+ */
1563
+ on(listener) {
1564
+ return this.eventEmitter.on(listener);
1565
+ }
1566
+ /**
1567
+ * Remove a specific event listener
1568
+ */
1569
+ off(listener) {
1570
+ this.eventEmitter.off(listener);
1571
+ }
1572
+ /**
1573
+ * Remove all event listeners
1574
+ */
1575
+ offAll() {
1576
+ this.eventEmitter.offAll();
1577
+ }
1578
+ /**
1579
+ * Emit a connector event
1580
+ * Internal method used by transaction signer and other components
1581
+ * @internal
1582
+ */
1583
+ emitEvent(event) {
1584
+ this.eventEmitter.emit(event);
1585
+ }
1586
+ /**
1587
+ * Track a transaction for debugging and monitoring
1588
+ */
1589
+ trackTransaction(activity) {
1590
+ this.transactionTracker.trackTransaction(activity);
1591
+ }
1592
+ /**
1593
+ * Update transaction status
1594
+ */
1595
+ updateTransactionStatus(signature, status, error) {
1596
+ this.transactionTracker.updateStatus(signature, status, error);
1597
+ }
1598
+ /**
1599
+ * Clear transaction history
1600
+ */
1601
+ clearTransactionHistory() {
1602
+ this.transactionTracker.clearHistory();
1603
+ }
1604
+ /**
1605
+ * Get connector health and diagnostics
1606
+ */
1607
+ getHealth() {
1608
+ return this.healthMonitor.getHealth();
1609
+ }
1610
+ /**
1611
+ * Get performance and debug metrics
1612
+ */
1613
+ getDebugMetrics() {
1614
+ this.stateManager.getSnapshot();
1615
+ return this.debugMetrics.updateListenerCounts(this.eventEmitter.getListenerCount(), 0), this.debugMetrics.getMetrics();
1616
+ }
1617
+ /**
1618
+ * Get debug state including transactions
1619
+ */
1620
+ getDebugState() {
1621
+ return {
1622
+ ...this.getDebugMetrics(),
1623
+ transactions: this.transactionTracker.getTransactions(),
1624
+ totalTransactions: this.transactionTracker.getTotalCount()
1625
+ };
1626
+ }
1627
+ /**
1628
+ * Reset debug metrics
1629
+ */
1630
+ resetDebugMetrics() {
1631
+ this.debugMetrics.resetMetrics();
1632
+ }
1633
+ /**
1634
+ * Cleanup resources
1635
+ */
1636
+ destroy() {
1637
+ this.connectionManager.disconnect().catch(() => {
1638
+ }), this.walletDetector.destroy(), this.eventEmitter.offAll(), this.stateManager.clear();
1639
+ }
1640
+ };
1641
+ var logger6 = createLogger("ErrorBoundary"), WalletErrorType = /* @__PURE__ */ ((WalletErrorType2) => (WalletErrorType2.CONNECTION_FAILED = "CONNECTION_FAILED", WalletErrorType2.TRANSACTION_FAILED = "TRANSACTION_FAILED", WalletErrorType2.NETWORK_ERROR = "NETWORK_ERROR", WalletErrorType2.WALLET_NOT_FOUND = "WALLET_NOT_FOUND", WalletErrorType2.USER_REJECTED = "USER_REJECTED", WalletErrorType2.INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS", WalletErrorType2.UNKNOWN_ERROR = "UNKNOWN_ERROR", WalletErrorType2))(WalletErrorType || {}), ErrorLogger = class {
1642
+ static log(error, errorInfo, context) {
1643
+ if (process.env.NODE_ENV === "development" && logger6.error(error.message, {
1644
+ error,
1645
+ errorInfo,
1646
+ context
1647
+ }), process.env.NODE_ENV === "production" && typeof window < "u")
1648
+ try {
1649
+ let gtag = window.gtag;
1650
+ typeof gtag == "function" && gtag("event", "exception", {
1651
+ description: error.message,
1652
+ fatal: false,
1653
+ custom_map: { error_type: "wallet_error", ...context }
1654
+ });
1655
+ } catch {
1656
+ }
1657
+ }
1658
+ };
1659
+ function classifyError(error) {
1660
+ if (isConnectorError(error))
1661
+ return {
1662
+ ...error,
1663
+ type: {
1664
+ WALLET_NOT_CONNECTED: "CONNECTION_FAILED" /* CONNECTION_FAILED */,
1665
+ WALLET_NOT_FOUND: "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1666
+ CONNECTION_FAILED: "CONNECTION_FAILED" /* CONNECTION_FAILED */,
1667
+ USER_REJECTED: "USER_REJECTED" /* USER_REJECTED */,
1668
+ RPC_ERROR: "NETWORK_ERROR" /* NETWORK_ERROR */,
1669
+ NETWORK_TIMEOUT: "NETWORK_ERROR" /* NETWORK_ERROR */,
1670
+ SIGNING_FAILED: "TRANSACTION_FAILED" /* TRANSACTION_FAILED */,
1671
+ SEND_FAILED: "TRANSACTION_FAILED" /* TRANSACTION_FAILED */
1672
+ }[error.code] || "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
1673
+ recoverable: error.recoverable,
1674
+ context: error.context
1675
+ };
1676
+ let walletError = error;
1677
+ if (walletError.type) return walletError;
1678
+ let type = "UNKNOWN_ERROR" /* UNKNOWN_ERROR */, recoverable = false;
1679
+ return error.message.includes("User rejected") || error.message.includes("User denied") ? (type = "USER_REJECTED" /* USER_REJECTED */, recoverable = true) : error.message.includes("Insufficient funds") ? (type = "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */, recoverable = false) : error.message.includes("Network") || error.message.includes("fetch") ? (type = "NETWORK_ERROR" /* NETWORK_ERROR */, recoverable = true) : error.message.includes("Wallet not found") || error.message.includes("not installed") ? (type = "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */, recoverable = true) : (error.message.includes("Failed to connect") || error.message.includes("Connection")) && (type = "CONNECTION_FAILED" /* CONNECTION_FAILED */, recoverable = true), {
1680
+ ...error,
1681
+ type,
1682
+ recoverable,
1683
+ context: { originalMessage: error.message }
1684
+ };
1685
+ }
1686
+ var ConnectorErrorBoundary = class extends Component {
1687
+ constructor(props) {
1688
+ super(props);
1689
+ __publicField(this, "retryTimeouts", /* @__PURE__ */ new Set());
1690
+ __publicField(this, "retry", () => {
1691
+ let { maxRetries = 3 } = this.props;
1692
+ this.state.retryCount >= maxRetries || this.setState((prevState) => ({
1693
+ hasError: false,
1694
+ error: null,
1695
+ errorInfo: null,
1696
+ retryCount: prevState.retryCount + 1
1697
+ }));
1698
+ });
1699
+ this.state = {
1700
+ hasError: false,
1701
+ error: null,
1702
+ errorInfo: null,
1703
+ errorId: "",
1704
+ retryCount: 0
1705
+ };
1706
+ }
1707
+ static getDerivedStateFromError(error) {
1708
+ return {
1709
+ hasError: true,
1710
+ error,
1711
+ errorId: `error_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
1712
+ };
1713
+ }
1714
+ componentDidCatch(error, errorInfo) {
1715
+ this.setState({ errorInfo }), ErrorLogger.log(error, errorInfo, {
1716
+ retryCount: this.state.retryCount,
1717
+ errorId: this.state.errorId,
1718
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1719
+ }), this.props.onError?.(error, errorInfo);
1720
+ }
1721
+ componentWillUnmount() {
1722
+ this.retryTimeouts.forEach((timeout) => clearTimeout(timeout));
1723
+ }
1724
+ render() {
1725
+ if (this.state.hasError && this.state.error) {
1726
+ let walletError = classifyError(this.state.error);
1727
+ return this.props.fallback ? this.props.fallback(walletError, this.retry) : /* @__PURE__ */ jsx(DefaultErrorFallback, { error: walletError, onRetry: this.retry });
1728
+ }
1729
+ return this.props.children;
1730
+ }
1731
+ };
1732
+ function DefaultErrorFallback({ error, onRetry }) {
1733
+ let [isPending, startTransition] = useTransition(), [isRetrying, setIsRetrying] = useState(false), handleRetry = useCallback(() => {
1734
+ setIsRetrying(true), startTransition(() => {
1735
+ setTimeout(() => {
1736
+ onRetry(), setIsRetrying(false);
1737
+ }, 500);
1738
+ });
1739
+ }, [onRetry]), { title, message, actionText, showRetry } = useMemo(() => {
1740
+ switch (error.type) {
1741
+ case "USER_REJECTED" /* USER_REJECTED */:
1742
+ return {
1743
+ title: "Transaction Cancelled",
1744
+ message: "You cancelled the transaction. No problem!",
1745
+ actionText: "Try Again",
1746
+ showRetry: true
1747
+ };
1748
+ case "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */:
1749
+ return {
1750
+ title: "Wallet Not Found",
1751
+ message: "Please install a supported Solana wallet to continue.",
1752
+ actionText: "Check Wallets",
1753
+ showRetry: true
1754
+ };
1755
+ case "NETWORK_ERROR" /* NETWORK_ERROR */:
1756
+ return {
1757
+ title: "Network Error",
1758
+ message: "Having trouble connecting. Please check your internet connection.",
1759
+ actionText: "Retry",
1760
+ showRetry: true
1761
+ };
1762
+ case "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */:
1763
+ return {
1764
+ title: "Insufficient Funds",
1765
+ message: "You don't have enough SOL for this transaction.",
1766
+ actionText: "Add Funds",
1767
+ showRetry: false
1768
+ };
1769
+ default:
1770
+ return {
1771
+ title: "Something went wrong",
1772
+ message: "An unexpected error occurred. Please try again.",
1773
+ actionText: "Retry",
1774
+ showRetry: error.recoverable
1775
+ };
1776
+ }
1777
+ }, [error.type, error.recoverable]);
1778
+ return /* @__PURE__ */ jsxs(
1779
+ "div",
1780
+ {
1781
+ style: {
1782
+ display: "flex",
1783
+ flexDirection: "column",
1784
+ alignItems: "center",
1785
+ justifyContent: "center",
1786
+ padding: "2rem",
1787
+ textAlign: "center",
1788
+ borderRadius: "12px",
1789
+ border: "1px solid #e5e7eb",
1790
+ backgroundColor: "#fafafa",
1791
+ maxWidth: "400px",
1792
+ margin: "0 auto"
1793
+ },
1794
+ children: [
1795
+ /* @__PURE__ */ jsx(
1796
+ "div",
1797
+ {
1798
+ style: {
1799
+ width: "48px",
1800
+ height: "48px",
1801
+ borderRadius: "50%",
1802
+ backgroundColor: "#fee2e2",
1803
+ display: "flex",
1804
+ alignItems: "center",
1805
+ justifyContent: "center",
1806
+ marginBottom: "1rem"
1807
+ },
1808
+ children: /* @__PURE__ */ jsx("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "#dc2626", children: /* @__PURE__ */ jsx("path", { d: "M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" }) })
1809
+ }
1810
+ ),
1811
+ /* @__PURE__ */ jsx(
1812
+ "h3",
1813
+ {
1814
+ style: {
1815
+ margin: "0 0 0.5rem 0",
1816
+ fontSize: "1.125rem",
1817
+ fontWeight: "600",
1818
+ color: "#111827"
1819
+ },
1820
+ children: title
1821
+ }
1822
+ ),
1823
+ /* @__PURE__ */ jsx(
1824
+ "p",
1825
+ {
1826
+ style: {
1827
+ margin: "0 0 1.5rem 0",
1828
+ fontSize: "0.875rem",
1829
+ color: "#6b7280",
1830
+ lineHeight: "1.5"
1831
+ },
1832
+ children: message
1833
+ }
1834
+ ),
1835
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "0.75rem", flexWrap: "wrap" }, children: [
1836
+ showRetry && /* @__PURE__ */ jsx(
1837
+ "button",
1838
+ {
1839
+ onClick: handleRetry,
1840
+ disabled: isPending || isRetrying,
1841
+ style: {
1842
+ padding: "0.5rem 1rem",
1843
+ backgroundColor: "#3b82f6",
1844
+ color: "white",
1845
+ border: "none",
1846
+ borderRadius: "6px",
1847
+ fontSize: "0.875rem",
1848
+ fontWeight: "500",
1849
+ cursor: isPending || isRetrying ? "wait" : "pointer",
1850
+ opacity: isPending || isRetrying ? 0.7 : 1,
1851
+ transition: "all 0.2s"
1852
+ },
1853
+ children: isRetrying ? "Retrying..." : actionText
1854
+ }
1855
+ ),
1856
+ /* @__PURE__ */ jsx(
1857
+ "button",
1858
+ {
1859
+ onClick: () => window.location.reload(),
1860
+ style: {
1861
+ padding: "0.5rem 1rem",
1862
+ backgroundColor: "transparent",
1863
+ color: "#6b7280",
1864
+ border: "1px solid #d1d5db",
1865
+ borderRadius: "6px",
1866
+ fontSize: "0.875rem",
1867
+ fontWeight: "500",
1868
+ cursor: "pointer",
1869
+ transition: "all 0.2s"
1870
+ },
1871
+ children: "Refresh Page"
1872
+ }
1873
+ )
1874
+ ] }),
1875
+ process.env.NODE_ENV === "development" && /* @__PURE__ */ jsxs(
1876
+ "details",
1877
+ {
1878
+ style: {
1879
+ marginTop: "1rem",
1880
+ fontSize: "0.75rem",
1881
+ color: "#6b7280",
1882
+ width: "100%"
1883
+ },
1884
+ children: [
1885
+ /* @__PURE__ */ jsx("summary", { style: { cursor: "pointer", marginBottom: "0.5rem" }, children: "Error Details" }),
1886
+ /* @__PURE__ */ jsx(
1887
+ "pre",
1888
+ {
1889
+ style: {
1890
+ whiteSpace: "pre-wrap",
1891
+ wordBreak: "break-all",
1892
+ backgroundColor: "#f3f4f6",
1893
+ padding: "0.5rem",
1894
+ borderRadius: "4px",
1895
+ overflow: "auto",
1896
+ maxHeight: "200px"
1897
+ },
1898
+ children: error.message
1899
+ }
1900
+ )
1901
+ ]
1902
+ }
1903
+ )
1904
+ ]
1905
+ }
1906
+ );
1907
+ }
1908
+ function withErrorBoundary(Component2, errorBoundaryProps) {
1909
+ let WrappedComponent = (props) => /* @__PURE__ */ jsx(ConnectorErrorBoundary, { ...errorBoundaryProps, children: /* @__PURE__ */ jsx(Component2, { ...props }) });
1910
+ return WrappedComponent.displayName = `withErrorBoundary(${Component2.displayName || Component2.name})`, WrappedComponent;
1911
+ }
1912
+ var logger7 = createLogger("Polyfills"), installed = false;
1913
+ function installPolyfills() {
1914
+ if (!(installed || typeof window > "u"))
1915
+ try {
1916
+ install(), installed = true, process.env.NODE_ENV === "development" && logger7 && logger7.info("Browser compatibility polyfills installed");
1917
+ } catch (error) {
1918
+ logger7 && logger7.warn("Failed to install polyfills", { error }), installed = true;
1919
+ }
1920
+ }
1921
+ function isPolyfillInstalled() {
1922
+ return installed;
1923
+ }
1924
+ function isCryptoAvailable() {
1925
+ if (typeof window > "u") return false;
1926
+ try {
1927
+ return !!(window.crypto && window.crypto.subtle && typeof window.crypto.subtle.sign == "function");
1928
+ } catch {
1929
+ return false;
1930
+ }
1931
+ }
1932
+ function getPolyfillStatus() {
1933
+ return {
1934
+ installed,
1935
+ cryptoAvailable: isCryptoAvailable(),
1936
+ environment: typeof window < "u" ? "browser" : "server"
1937
+ };
1938
+ }
1939
+ function formatAddress(address, options = {}) {
1940
+ let { length = 4, separator = "..." } = options;
1941
+ return !address || address.length <= length * 2 + separator.length ? address : `${address.slice(0, length)}${separator}${address.slice(-length)}`;
1942
+ }
1943
+ function formatSOL(lamports, options = {}) {
1944
+ let { decimals = 4, suffix = true, fast = false } = options;
1945
+ if (fast && typeof lamports == "number") {
1946
+ let formatted2 = (lamports / LAMPORTS_PER_SOL).toFixed(decimals);
1947
+ return suffix ? `${formatted2} SOL` : formatted2;
1948
+ }
1949
+ let lamportsBigInt = typeof lamports == "bigint" ? lamports : BigInt(lamports), formatted = (Number(lamportsBigInt) / LAMPORTS_PER_SOL).toFixed(decimals);
1950
+ return suffix ? `${formatted} SOL` : formatted;
1951
+ }
1952
+ function formatNumber(value, options = {}) {
1953
+ let { decimals, locale = "en-US" } = options;
1954
+ return new Intl.NumberFormat(locale, {
1955
+ minimumFractionDigits: decimals,
1956
+ maximumFractionDigits: decimals
1957
+ }).format(value);
1958
+ }
1959
+ function truncate(text, maxLength, position = "middle") {
1960
+ if (!text || text.length <= maxLength) return text;
1961
+ if (position === "end")
1962
+ return text.slice(0, maxLength - 3) + "...";
1963
+ let half = Math.floor((maxLength - 3) / 2);
1964
+ return text.slice(0, half) + "..." + text.slice(-half);
1965
+ }
1966
+ function formatTokenAmount(amount, decimals, options = {}) {
1967
+ let value = Number(amount) / Math.pow(10, decimals), minDecimals = options.minimumDecimals ?? 0, maxDecimals = options.maximumDecimals ?? decimals;
1968
+ return value.toLocaleString("en-US", {
1969
+ minimumFractionDigits: minDecimals,
1970
+ maximumFractionDigits: maxDecimals
1971
+ });
1972
+ }
1973
+ var ClipboardErrorType = /* @__PURE__ */ ((ClipboardErrorType2) => (ClipboardErrorType2.NOT_SUPPORTED = "not_supported", ClipboardErrorType2.PERMISSION_DENIED = "permission_denied", ClipboardErrorType2.SSR = "ssr", ClipboardErrorType2.EMPTY_VALUE = "empty_value", ClipboardErrorType2.INVALID_VALUE = "invalid_value", ClipboardErrorType2.UNKNOWN = "unknown", ClipboardErrorType2))(ClipboardErrorType || {});
1974
+ function isClipboardAvailable() {
1975
+ if (typeof window > "u" || typeof document > "u")
1976
+ return { modern: false, fallback: false, available: false };
1977
+ let modern = typeof navigator?.clipboard?.writeText == "function", fallback = typeof document.execCommand == "function";
1978
+ return {
1979
+ modern,
1980
+ fallback,
1981
+ available: modern || fallback
1982
+ };
1983
+ }
1984
+ function validateAddress(address) {
1985
+ try {
1986
+ return isAddress(address);
1987
+ } catch {
1988
+ return false;
1989
+ }
1990
+ }
1991
+ function validateSignature(signature) {
1992
+ return !signature || typeof signature != "string" || signature.length < 87 || signature.length > 88 ? false : /^[1-9A-HJ-NP-Za-km-z]+$/.test(signature);
1993
+ }
1994
+ function formatValue(value, options) {
1995
+ let { format = "full", customFormatter, shortFormatChars = 4 } = options;
1996
+ if (format === "custom" && customFormatter)
1997
+ try {
1998
+ return customFormatter(value);
1999
+ } catch {
2000
+ return value;
2001
+ }
2002
+ if (format === "short") {
2003
+ if (value.length > 32 && value.length < 50)
2004
+ return formatAddress(value, { length: shortFormatChars });
2005
+ if (value.length > shortFormatChars * 2)
2006
+ return `${value.slice(0, shortFormatChars)}...${value.slice(-shortFormatChars)}`;
2007
+ }
2008
+ return value;
2009
+ }
2010
+ function copyUsingFallback(text) {
2011
+ try {
2012
+ let textArea = document.createElement("textarea");
2013
+ textArea.value = text, textArea.style.position = "fixed", textArea.style.left = "-999999px", textArea.style.top = "-999999px", document.body.appendChild(textArea), textArea.focus(), textArea.select();
2014
+ let successful = document.execCommand("copy");
2015
+ return document.body.removeChild(textArea), successful;
2016
+ } catch {
2017
+ return false;
2018
+ }
2019
+ }
2020
+ async function copyToClipboard(text, options = {}) {
2021
+ let { onSuccess, onError, validate, validateType = "none", useFallback = true } = options;
2022
+ if (!text || typeof text != "string" || text.trim() === "") {
2023
+ let error2 = "empty_value" /* EMPTY_VALUE */, message2 = "No text provided to copy";
2024
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2025
+ }
2026
+ if (typeof window > "u" || typeof navigator > "u") {
2027
+ let error2 = "ssr" /* SSR */, message2 = "Clipboard not available in server-side rendering context";
2028
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2029
+ }
2030
+ if (validate && !validate(text)) {
2031
+ let error2 = "invalid_value" /* INVALID_VALUE */, message2 = "Value failed custom validation";
2032
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2033
+ }
2034
+ if (validateType === "address" && !validateAddress(text)) {
2035
+ let error2 = "invalid_value" /* INVALID_VALUE */, message2 = "Invalid Solana address format";
2036
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2037
+ }
2038
+ if (validateType === "signature" && !validateSignature(text)) {
2039
+ let error2 = "invalid_value" /* INVALID_VALUE */, message2 = "Invalid transaction signature format";
2040
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2041
+ }
2042
+ let formattedValue = formatValue(text, options), availability = isClipboardAvailable();
2043
+ if (!availability.available) {
2044
+ let error2 = "not_supported" /* NOT_SUPPORTED */, message2 = "Clipboard API not supported in this browser";
2045
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2046
+ }
2047
+ if (availability.modern)
2048
+ try {
2049
+ return await navigator.clipboard.writeText(formattedValue), onSuccess?.(), { success: true, copiedValue: formattedValue };
2050
+ } catch (err) {
2051
+ if (err instanceof Error && (err.name === "NotAllowedError" || err.message.toLowerCase().includes("permission"))) {
2052
+ let error3 = "permission_denied" /* PERMISSION_DENIED */, message3 = "Clipboard permission denied by user or browser";
2053
+ return onError?.(error3, message3), { success: false, error: error3, errorMessage: message3 };
2054
+ }
2055
+ if (useFallback && availability.fallback && copyUsingFallback(formattedValue))
2056
+ return onSuccess?.(), { success: true, usedFallback: true, copiedValue: formattedValue };
2057
+ let error2 = "unknown" /* UNKNOWN */, message2 = err instanceof Error ? err.message : "Failed to copy to clipboard";
2058
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2059
+ }
2060
+ if (useFallback && availability.fallback) {
2061
+ if (copyUsingFallback(formattedValue))
2062
+ return onSuccess?.(), { success: true, usedFallback: true, copiedValue: formattedValue };
2063
+ let error2 = "unknown" /* UNKNOWN */, message2 = "Failed to copy using fallback method";
2064
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
2065
+ }
2066
+ let error = "not_supported" /* NOT_SUPPORTED */, message = "No clipboard method available";
2067
+ return onError?.(error, message), { success: false, error, errorMessage: message };
2068
+ }
2069
+ async function copyAddressToClipboard(address, options) {
2070
+ return copyToClipboard(address, {
2071
+ ...options,
2072
+ validateType: "address"
2073
+ });
2074
+ }
2075
+ async function copySignatureToClipboard(signature, options) {
2076
+ return copyToClipboard(signature, {
2077
+ ...options,
2078
+ validateType: "signature"
2079
+ });
2080
+ }
2081
+
2082
+ // src/lib/transaction/transaction-validator.ts
2083
+ var logger8 = createLogger("TransactionValidator"), MAX_TRANSACTION_SIZE = 1232, MIN_TRANSACTION_SIZE = 64, TransactionValidator = class {
2084
+ /**
2085
+ * Validate a transaction before signing
2086
+ *
2087
+ * @param transaction - The transaction to validate
2088
+ * @param options - Validation options
2089
+ * @returns Validation result with errors and warnings
2090
+ */
2091
+ static validate(transaction, options = {}) {
2092
+ let {
2093
+ maxSize = MAX_TRANSACTION_SIZE,
2094
+ minSize = MIN_TRANSACTION_SIZE,
2095
+ checkDuplicateSignatures = true,
2096
+ strict = false
2097
+ } = options, errors = [], warnings = [], size;
2098
+ if (!transaction)
2099
+ return errors.push("Transaction is null or undefined"), { valid: false, errors, warnings };
2100
+ try {
2101
+ let serialized;
2102
+ if (typeof transaction.serialize == "function")
2103
+ try {
2104
+ serialized = transaction.serialize();
2105
+ } catch (serializeError) {
2106
+ logger8.debug("Transaction not yet serializable (may need signing)", {
2107
+ error: serializeError instanceof Error ? serializeError.message : String(serializeError)
2108
+ });
2109
+ }
2110
+ else if (transaction instanceof Uint8Array)
2111
+ serialized = transaction;
2112
+ else
2113
+ return errors.push(
2114
+ "Transaction type not recognized - must be a Transaction object with serialize() or Uint8Array"
2115
+ ), { valid: false, errors, warnings };
2116
+ serialized && (size = serialized.length, size > maxSize && (errors.push(`Transaction too large: ${size} bytes (max ${maxSize} bytes)`), logger8.warn("Transaction exceeds maximum size", { size, maxSize })), size < minSize && warnings.push(`Transaction is very small: ${size} bytes (min recommended ${minSize} bytes)`), size === 0 && errors.push("Transaction is empty (0 bytes)"), this.hasSuspiciousPattern(serialized) && warnings.push("Transaction contains unusual patterns - please review carefully"));
2117
+ } catch (error) {
2118
+ let errorMessage = error instanceof Error ? error.message : String(error);
2119
+ errors.push(`Transaction validation failed: ${errorMessage}`), logger8.error("Validation error", { error: errorMessage });
2120
+ }
2121
+ if (checkDuplicateSignatures && typeof transaction == "object" && "signatures" in transaction) {
2122
+ let signatures = transaction.signatures;
2123
+ Array.isArray(signatures) && new Set(
2124
+ signatures.map((sig) => {
2125
+ let pubKey = sig?.publicKey;
2126
+ return pubKey ? String(pubKey) : null;
2127
+ }).filter(Boolean)
2128
+ ).size < signatures.length && warnings.push("Transaction contains duplicate signers");
2129
+ }
2130
+ strict && warnings.length > 0 && (errors.push(...warnings.map((w) => `Strict mode: ${w}`)), warnings.length = 0);
2131
+ let valid = errors.length === 0;
2132
+ return valid ? warnings.length > 0 ? logger8.debug("Transaction validation passed with warnings", { warnings, size }) : logger8.debug("Transaction validation passed", { size }) : logger8.warn("Transaction validation failed", { errors, size }), {
2133
+ valid,
2134
+ errors,
2135
+ warnings,
2136
+ size
2137
+ };
2138
+ }
2139
+ /**
2140
+ * Check for suspicious patterns in serialized transaction
2141
+ * This is a heuristic check to detect potentially malicious transactions
2142
+ *
2143
+ * @param serialized - Serialized transaction bytes
2144
+ * @returns True if suspicious patterns detected
2145
+ */
2146
+ static hasSuspiciousPattern(serialized) {
2147
+ if (serialized.every((byte) => byte === 0) || serialized.every((byte) => byte === 255)) return true;
2148
+ let byteCounts = /* @__PURE__ */ new Map();
2149
+ for (let byte of serialized)
2150
+ byteCounts.set(byte, (byteCounts.get(byte) || 0) + 1);
2151
+ return Math.max(...Array.from(byteCounts.values())) / serialized.length > 0.5;
2152
+ }
2153
+ /**
2154
+ * Quick validation check - returns true if valid, throws on error
2155
+ * Useful for inline validation
2156
+ *
2157
+ * @param transaction - Transaction to validate
2158
+ * @param options - Validation options
2159
+ * @throws Error if validation fails
2160
+ *
2161
+ * @example
2162
+ * ```ts
2163
+ * TransactionValidator.assertValid(transaction);
2164
+ * // Continues if valid, throws if invalid
2165
+ * await signer.signTransaction(transaction);
2166
+ * ```
2167
+ */
2168
+ static assertValid(transaction, options) {
2169
+ let result = this.validate(transaction, options);
2170
+ if (!result.valid)
2171
+ throw new Error(`Transaction validation failed: ${result.errors.join(", ")}`);
2172
+ result.warnings.length > 0 && logger8.warn("Transaction validation warnings", { warnings: result.warnings });
2173
+ }
2174
+ /**
2175
+ * Batch validate multiple transactions
2176
+ * More efficient than validating one-by-one
2177
+ *
2178
+ * @param transactions - Array of transactions to validate
2179
+ * @param options - Validation options
2180
+ * @returns Array of validation results
2181
+ */
2182
+ static validateBatch(transactions, options) {
2183
+ return transactions.map((tx, index) => (logger8.debug(`Validating transaction ${index + 1}/${transactions.length}`), this.validate(tx, options)));
2184
+ }
2185
+ };
2186
+
2187
+ // src/lib/transaction/transaction-signer.ts
2188
+ var logger9 = createLogger("TransactionSigner");
2189
+ function createTransactionSigner(config) {
2190
+ let { wallet, account, cluster, eventEmitter } = config;
2191
+ if (!wallet || !account)
2192
+ return null;
2193
+ let features = wallet.features, address = account.address, capabilities = {
2194
+ canSign: !!features["solana:signTransaction"],
2195
+ canSend: !!features["solana:signAndSendTransaction"],
2196
+ canSignMessage: !!features["solana:signMessage"],
2197
+ supportsBatchSigning: !!features["solana:signAllTransactions"]
2198
+ }, signer = {
2199
+ address,
2200
+ async signTransaction(transaction) {
2201
+ if (!capabilities.canSign)
2202
+ throw Errors.featureNotSupported("transaction signing");
2203
+ let validation = TransactionValidator.validate(transaction);
2204
+ if (!validation.valid)
2205
+ throw logger9.error("Transaction validation failed", { errors: validation.errors }), Errors.invalidTransaction(validation.errors.join(", "));
2206
+ validation.warnings.length > 0 && logger9.warn("Transaction validation warnings", { warnings: validation.warnings });
2207
+ try {
2208
+ let signFeature = features["solana:signTransaction"], { serialized, wasWeb3js } = prepareTransactionForWallet(transaction);
2209
+ logger9.debug("Signing transaction", {
2210
+ wasWeb3js,
2211
+ serializedLength: serialized.length,
2212
+ serializedType: serialized.constructor.name,
2213
+ accountAddress: account?.address,
2214
+ hasAccount: !!account
2215
+ });
2216
+ let result, usedFormat = "";
2217
+ try {
2218
+ logger9.debug("Trying array format: transactions: [Uint8Array]"), result = await signFeature.signTransaction({
2219
+ account,
2220
+ transactions: [serialized],
2221
+ ...cluster ? { chain: cluster.id } : {}
2222
+ }), usedFormat = "array";
2223
+ } catch (err1) {
2224
+ let error1 = err1 instanceof Error ? err1 : new Error(String(err1));
2225
+ logger9.debug("Array format failed, trying singular format", { error: error1.message });
2226
+ try {
2227
+ logger9.debug("Trying singular format: transaction: Uint8Array"), result = await signFeature.signTransaction({
2228
+ account,
2229
+ transaction: serialized,
2230
+ ...cluster ? { chain: cluster.id } : {}
2231
+ }), usedFormat = "singular";
2232
+ } catch (err2) {
2233
+ let error2 = err2 instanceof Error ? err2 : new Error(String(err2));
2234
+ throw logger9.error("Both array and singular formats failed", { error: error2.message }), error2;
2235
+ }
2236
+ }
2237
+ logger9.debug("Wallet signed successfully", { format: usedFormat });
2238
+ let signedTx;
2239
+ if (Array.isArray(result.signedTransactions) && result.signedTransactions[0])
2240
+ signedTx = result.signedTransactions[0];
2241
+ else if (result.signedTransaction)
2242
+ signedTx = result.signedTransaction;
2243
+ else if (Array.isArray(result) && result[0])
2244
+ signedTx = result[0];
2245
+ else if (result instanceof Uint8Array)
2246
+ signedTx = result;
2247
+ else
2248
+ throw new Error(`Unexpected wallet response format: ${JSON.stringify(Object.keys(result))}`);
2249
+ if (logger9.debug("Extracted signed transaction", {
2250
+ hasSignedTx: !!signedTx,
2251
+ signedTxType: signedTx?.constructor?.name,
2252
+ signedTxLength: signedTx?.length,
2253
+ isUint8Array: signedTx instanceof Uint8Array,
2254
+ hasSerialize: typeof signedTx?.serialize == "function"
2255
+ }), signedTx && typeof signedTx.serialize == "function")
2256
+ return logger9.debug("Wallet returned web3.js object directly, no conversion needed"), signedTx;
2257
+ if (signedTx && signedTx.signedTransaction) {
2258
+ logger9.debug("Found signedTransaction property");
2259
+ let bytes = signedTx.signedTransaction;
2260
+ if (bytes instanceof Uint8Array)
2261
+ return await convertSignedTransaction(bytes, wasWeb3js);
2262
+ }
2263
+ if (signedTx instanceof Uint8Array)
2264
+ return await convertSignedTransaction(signedTx, wasWeb3js);
2265
+ throw logger9.error("Unexpected wallet response format", {
2266
+ type: typeof signedTx,
2267
+ constructor: signedTx?.constructor?.name
2268
+ }), new ValidationError(
2269
+ "INVALID_FORMAT",
2270
+ "Wallet returned unexpected format - not a Transaction or Uint8Array"
2271
+ );
2272
+ } catch (error) {
2273
+ throw Errors.signingFailed(error);
2274
+ }
2275
+ },
2276
+ async signAllTransactions(transactions) {
2277
+ if (transactions.length === 0)
2278
+ return [];
2279
+ if (capabilities.supportsBatchSigning)
2280
+ try {
2281
+ let signFeature = features["solana:signAllTransactions"], prepared = transactions.map((tx) => prepareTransactionForWallet(tx)), serializedTxs = prepared.map((p) => p.serialized), wasWeb3js = prepared[0].wasWeb3js, result = await signFeature.signAllTransactions({
2282
+ account,
2283
+ transactions: serializedTxs,
2284
+ ...cluster ? { chain: cluster.id } : {}
2285
+ });
2286
+ return await Promise.all(
2287
+ result.signedTransactions.map(
2288
+ (signedBytes) => convertSignedTransaction(signedBytes, wasWeb3js)
2289
+ )
2290
+ );
2291
+ } catch (error) {
2292
+ throw new TransactionError(
2293
+ "SIGNING_FAILED",
2294
+ "Failed to sign transactions in batch",
2295
+ { count: transactions.length },
2296
+ error
2297
+ );
2298
+ }
2299
+ if (!capabilities.canSign)
2300
+ throw Errors.featureNotSupported("transaction signing");
2301
+ let signed = [];
2302
+ for (let i = 0; i < transactions.length; i++)
2303
+ try {
2304
+ let signedTx = await signer.signTransaction(transactions[i]);
2305
+ signed.push(signedTx);
2306
+ } catch (error) {
2307
+ throw new TransactionError(
2308
+ "SIGNING_FAILED",
2309
+ `Failed to sign transaction ${i + 1} of ${transactions.length}`,
2310
+ { index: i, total: transactions.length },
2311
+ error
2312
+ );
2313
+ }
2314
+ return signed;
2315
+ },
2316
+ async signAndSendTransaction(transaction, options) {
2317
+ if (!capabilities.canSend)
2318
+ throw Errors.featureNotSupported("sending transactions");
2319
+ try {
2320
+ let sendFeature = features["solana:signAndSendTransaction"], { serialized } = prepareTransactionForWallet(transaction);
2321
+ eventEmitter && eventEmitter.emit({
2322
+ type: "transaction:preparing",
2323
+ transaction: serialized,
2324
+ size: serialized.length,
2325
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2326
+ });
2327
+ let inputBase = {
2328
+ account,
2329
+ ...cluster ? { chain: cluster.id } : {},
2330
+ ...options ? { options } : {}
2331
+ };
2332
+ eventEmitter && eventEmitter.emit({
2333
+ type: "transaction:signing",
2334
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2335
+ });
2336
+ let result;
2337
+ try {
2338
+ result = await sendFeature.signAndSendTransaction({
2339
+ ...inputBase,
2340
+ transactions: [serialized]
2341
+ });
2342
+ } catch {
2343
+ result = await sendFeature.signAndSendTransaction({
2344
+ ...inputBase,
2345
+ transaction: serialized
2346
+ });
2347
+ }
2348
+ let signature = typeof result == "object" && result.signature ? result.signature : String(result);
2349
+ return eventEmitter && eventEmitter.emit({
2350
+ type: "transaction:sent",
2351
+ signature,
2352
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2353
+ }), signature;
2354
+ } catch (error) {
2355
+ throw new TransactionError("SEND_FAILED", "Failed to send transaction", void 0, error);
2356
+ }
2357
+ },
2358
+ async signAndSendTransactions(transactions, options) {
2359
+ if (transactions.length === 0)
2360
+ return [];
2361
+ if (!capabilities.canSend)
2362
+ throw Errors.featureNotSupported("sending transactions");
2363
+ let signatures = [];
2364
+ for (let i = 0; i < transactions.length; i++)
2365
+ try {
2366
+ let sig = await signer.signAndSendTransaction(transactions[i], options);
2367
+ signatures.push(sig);
2368
+ } catch (error) {
2369
+ throw new TransactionError(
2370
+ "SEND_FAILED",
2371
+ `Failed to send transaction ${i + 1} of ${transactions.length}`,
2372
+ { index: i, total: transactions.length },
2373
+ error
2374
+ );
2375
+ }
2376
+ return signatures;
2377
+ },
2378
+ ...capabilities.canSignMessage && {
2379
+ async signMessage(message) {
2380
+ try {
2381
+ return (await features["solana:signMessage"].signMessage({
2382
+ account,
2383
+ message,
2384
+ ...cluster ? { chain: cluster.id } : {}
2385
+ })).signature;
2386
+ } catch (error) {
2387
+ throw new TransactionError("SIGNING_FAILED", "Failed to sign message", void 0, error);
2388
+ }
2389
+ }
2390
+ },
2391
+ getCapabilities() {
2392
+ return { ...capabilities };
2393
+ }
2394
+ };
2395
+ return signer;
2396
+ }
2397
+ var TransactionSignerError = class extends TransactionError {
2398
+ constructor(message, code, originalError) {
2399
+ let newCode = code === "WALLET_NOT_CONNECTED" ? "FEATURE_NOT_SUPPORTED" : code;
2400
+ super(newCode, message, void 0, originalError), this.name = "TransactionSignerError";
2401
+ }
2402
+ };
2403
+ function isTransactionSignerError(error) {
2404
+ return error instanceof TransactionSignerError || error instanceof TransactionError;
2405
+ }
2406
+ var logger10 = createLogger("GillTransactionSigner");
2407
+ function encodeShortVecLength(value) {
2408
+ let bytes = [], remaining = value;
2409
+ for (; remaining >= 128; )
2410
+ bytes.push(remaining & 127 | 128), remaining >>= 7;
2411
+ return bytes.push(remaining), new Uint8Array(bytes);
2412
+ }
2413
+ function decodeShortVecLength(data) {
2414
+ let length = 0, size = 0;
2415
+ for (; ; ) {
2416
+ if (size >= data.length)
2417
+ throw new Error("Invalid shortvec encoding: unexpected end of data");
2418
+ let byte = data[size];
2419
+ if (length |= (byte & 127) << size * 7, size += 1, (byte & 128) === 0)
2420
+ break;
2421
+ if (size > 10)
2422
+ throw new Error("Invalid shortvec encoding: length prefix too long");
2423
+ }
2424
+ return { length, bytesConsumed: size };
2425
+ }
2426
+ function createTransactionBytesForSigning(messageBytes, numSigners) {
2427
+ let numSignaturesBytes = encodeShortVecLength(numSigners), signatureSlots = new Uint8Array(numSigners * 64), totalLength = numSignaturesBytes.length + signatureSlots.length + messageBytes.length, transactionBytes = new Uint8Array(totalLength), offset = 0;
2428
+ return transactionBytes.set(numSignaturesBytes, offset), offset += numSignaturesBytes.length, transactionBytes.set(signatureSlots, offset), offset += signatureSlots.length, transactionBytes.set(messageBytes, offset), transactionBytes;
2429
+ }
2430
+ function extractSignature(signedTx) {
2431
+ if (signedTx instanceof Uint8Array) {
2432
+ let { length: numSignatures, bytesConsumed } = decodeShortVecLength(signedTx);
2433
+ if (numSignatures === 0)
2434
+ throw new Error("No signatures found in serialized transaction");
2435
+ let signatureStart = bytesConsumed;
2436
+ return signedTx.slice(signatureStart, signatureStart + 64);
2437
+ }
2438
+ if (isWeb3jsTransaction(signedTx)) {
2439
+ let signatures = signedTx.signatures;
2440
+ if (!signatures || signatures.length === 0)
2441
+ throw new Error("No signatures found in web3.js transaction");
2442
+ let firstSig = signatures[0];
2443
+ if (firstSig instanceof Uint8Array)
2444
+ return firstSig;
2445
+ if (firstSig && typeof firstSig == "object" && "signature" in firstSig && firstSig.signature)
2446
+ return firstSig.signature;
2447
+ throw new Error("Could not extract signature from web3.js transaction");
2448
+ }
2449
+ throw new Error("Cannot extract signature from transaction format");
2450
+ }
2451
+ function createGillTransactionSigner(connectorSigner) {
2452
+ let signerAddress = address(connectorSigner.address);
2453
+ return {
2454
+ address: signerAddress,
2455
+ async modifyAndSignTransactions(transactions) {
2456
+ let transactionData = transactions.map((tx) => {
2457
+ let messageBytes = new Uint8Array(tx.messageBytes), numSigners = Object.keys(tx.signatures).length, wireFormat = createTransactionBytesForSigning(messageBytes, numSigners);
2458
+ return logger10.debug("Preparing wire format for wallet", {
2459
+ signerAddress,
2460
+ messageBytesLength: messageBytes.length,
2461
+ wireFormatLength: wireFormat.length,
2462
+ structure: {
2463
+ numSigsByte: wireFormat[0],
2464
+ firstSigSlotPreview: Array.from(wireFormat.slice(1, 17)),
2465
+ messageBytesStart: wireFormat.length - messageBytes.length
2466
+ }
2467
+ }), {
2468
+ originalTransaction: tx,
2469
+ messageBytes,
2470
+ wireFormat
2471
+ };
2472
+ }), transactionsForWallet = transactionData.map((data) => data.wireFormat);
2473
+ return (await connectorSigner.signAllTransactions(transactionsForWallet)).map((signedTx, index) => {
2474
+ let { originalTransaction, wireFormat } = transactionData[index];
2475
+ try {
2476
+ let signedTxBytes;
2477
+ if (signedTx instanceof Uint8Array)
2478
+ signedTxBytes = signedTx;
2479
+ else if (isWeb3jsTransaction(signedTx)) {
2480
+ let txObj = signedTx;
2481
+ if (typeof txObj.serialize == "function")
2482
+ signedTxBytes = txObj.serialize();
2483
+ else
2484
+ throw new Error("Web3.js transaction without serialize method");
2485
+ } else
2486
+ throw new Error("Unknown signed transaction format");
2487
+ if (logger10.debug("Wallet returned signed transaction", {
2488
+ returnedLength: signedTxBytes.length,
2489
+ sentLength: wireFormat.length,
2490
+ lengthsMatch: signedTxBytes.length === wireFormat.length,
2491
+ signedFirstBytes: Array.from(signedTxBytes.slice(0, 20)),
2492
+ sentFirstBytes: Array.from(wireFormat.slice(0, 20))
2493
+ }), signedTxBytes.length !== wireFormat.length) {
2494
+ logger10.warn("Wallet modified transaction! Using wallet version", {
2495
+ originalLength: wireFormat.length,
2496
+ modifiedLength: signedTxBytes.length,
2497
+ difference: signedTxBytes.length - wireFormat.length
2498
+ });
2499
+ let walletTransaction = getTransactionDecoder().decode(signedTxBytes), originalWithLifetime = originalTransaction, result = {
2500
+ ...walletTransaction,
2501
+ ...originalWithLifetime.lifetimeConstraint ? {
2502
+ lifetimeConstraint: originalWithLifetime.lifetimeConstraint
2503
+ } : {}
2504
+ };
2505
+ return logger10.debug("Using modified transaction from wallet", {
2506
+ modifiedMessageBytesLength: walletTransaction.messageBytes.length,
2507
+ signatures: Object.keys(walletTransaction.signatures)
2508
+ }), result;
2509
+ }
2510
+ let signatureBytes = extractSignature(signedTxBytes), signatureBase58 = getSignatureFromBytes(signatureBytes);
2511
+ return logger10.debug("Extracted signature from wallet (unmodified)", {
2512
+ signerAddress,
2513
+ signatureLength: signatureBytes.length,
2514
+ signatureBase58
2515
+ // Human-readable signature for debugging/logging
2516
+ }), {
2517
+ ...originalTransaction,
2518
+ signatures: Object.freeze({
2519
+ ...originalTransaction.signatures,
2520
+ [signerAddress]: signatureBytes
2521
+ })
2522
+ };
2523
+ } catch (error) {
2524
+ return logger10.error("Failed to decode signed transaction", { error }), originalTransaction;
2525
+ }
2526
+ });
2527
+ }
2528
+ };
2529
+ }
2530
+
2531
+ export { ClipboardErrorType, ConfigurationError, ConnectionError, ConnectorClient, ConnectorError, ConnectorErrorBoundary, DEFAULT_MAX_RETRIES, Errors, NetworkError, PUBLIC_RPC_ENDPOINTS, TransactionError, TransactionSignerError, ValidationError, WalletErrorType, copyAddressToClipboard, copySignatureToClipboard, copyToClipboard, createGillTransactionSigner, createTransactionSigner, formatAddress, formatNumber, formatSOL, formatTokenAmount, getAddressUrl, getBlockUrl, getClusterExplorerUrl, getClusterName, getClusterRpcUrl, getClusterType, getDefaultRpcUrl, getNetworkDisplayName, getPolyfillStatus, getTokenUrl, getTransactionUrl, getUserFriendlyMessage, getWalletsRegistry, installPolyfills, isClipboardAvailable, isConfigurationError, isConnectionError, isConnectorError, isCryptoAvailable, isDevnet, isDevnetCluster, isLocalCluster, isLocalnet, isMainnet, isMainnetCluster, isNetworkError, isPolyfillInstalled, isTestnet, isTestnetCluster, isTransactionError, isTransactionSignerError, isValidationError, normalizeNetwork, toClusterId, toConnectorError, truncate, withErrorBoundary };
2532
+ //# sourceMappingURL=chunk-52WUWW5R.mjs.map
2533
+ //# sourceMappingURL=chunk-52WUWW5R.mjs.map