@solana/connector 0.0.0 → 0.1.1

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-5ZUVZZWU.mjs +180 -0
  3. package/dist/chunk-5ZUVZZWU.mjs.map +1 -0
  4. package/dist/chunk-6PBQ5CXV.mjs +635 -0
  5. package/dist/chunk-6PBQ5CXV.mjs.map +1 -0
  6. package/dist/chunk-D4JGBIP7.js +314 -0
  7. package/dist/chunk-D4JGBIP7.js.map +1 -0
  8. package/dist/chunk-EGYXJT54.mjs +298 -0
  9. package/dist/chunk-EGYXJT54.mjs.map +1 -0
  10. package/dist/chunk-P4ZLJI4L.js +706 -0
  11. package/dist/chunk-P4ZLJI4L.js.map +1 -0
  12. package/dist/chunk-P5A3XNFF.js +2482 -0
  13. package/dist/chunk-P5A3XNFF.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-TAAXHAV2.mjs +2419 -0
  17. package/dist/chunk-TAAXHAV2.mjs.map +1 -0
  18. package/dist/compat.d.mts +47 -0
  19. package/dist/compat.d.ts +47 -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 +515 -0
  25. package/dist/headless.d.ts +515 -0
  26. package/dist/headless.js +445 -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 +14 -0
  31. package/dist/index.d.ts +14 -0
  32. package/dist/index.js +502 -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 +496 -0
  37. package/dist/react.d.ts +496 -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-D3csM_Mf.d.mts +199 -0
  43. package/dist/transaction-signer-D3csM_Mf.d.ts +199 -0
  44. package/dist/wallet-standard-shim-C1tisl9S.d.ts +926 -0
  45. package/dist/wallet-standard-shim-Cg0GVGwu.d.mts +926 -0
  46. package/package.json +93 -10
  47. package/index.js +0 -1
@@ -0,0 +1,2419 @@
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
+ __publicField(this, "context");
55
+ __publicField(this, "originalError");
56
+ __publicField(this, "timestamp");
57
+ this.name = this.constructor.name, this.context = context, this.originalError = originalError, this.timestamp = (/* @__PURE__ */ new Date()).toISOString(), Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
58
+ }
59
+ toJSON() {
60
+ return {
61
+ name: this.name,
62
+ code: this.code,
63
+ message: this.message,
64
+ recoverable: this.recoverable,
65
+ context: this.context,
66
+ timestamp: this.timestamp,
67
+ originalError: this.originalError?.message
68
+ };
69
+ }
70
+ }, ConnectionError = class extends ConnectorError {
71
+ constructor(code, message, context, originalError) {
72
+ super(message, context, originalError);
73
+ __publicField(this, "code");
74
+ __publicField(this, "recoverable", true);
75
+ this.code = code;
76
+ }
77
+ }, ValidationError = class extends ConnectorError {
78
+ constructor(code, message, context, originalError) {
79
+ super(message, context, originalError);
80
+ __publicField(this, "code");
81
+ __publicField(this, "recoverable", false);
82
+ this.code = code;
83
+ }
84
+ }, ConfigurationError = class extends ConnectorError {
85
+ constructor(code, message, context, originalError) {
86
+ super(message, context, originalError);
87
+ __publicField(this, "code");
88
+ __publicField(this, "recoverable", false);
89
+ this.code = code;
90
+ }
91
+ }, NetworkError = class extends ConnectorError {
92
+ constructor(code, message, context, originalError) {
93
+ super(message, context, originalError);
94
+ __publicField(this, "code");
95
+ __publicField(this, "recoverable", true);
96
+ this.code = code;
97
+ }
98
+ }, TransactionError = class extends ConnectorError {
99
+ constructor(code, message, context, originalError) {
100
+ super(message, context, originalError);
101
+ __publicField(this, "code");
102
+ __publicField(this, "recoverable");
103
+ this.code = code, this.recoverable = ["USER_REJECTED", "SEND_FAILED", "SIMULATION_FAILED"].includes(code);
104
+ }
105
+ };
106
+ function isConnectorError(error) {
107
+ return error instanceof ConnectorError;
108
+ }
109
+ function isConnectionError(error) {
110
+ return error instanceof ConnectionError;
111
+ }
112
+ function isValidationError(error) {
113
+ return error instanceof ValidationError;
114
+ }
115
+ function isConfigurationError(error) {
116
+ return error instanceof ConfigurationError;
117
+ }
118
+ function isNetworkError(error) {
119
+ return error instanceof NetworkError;
120
+ }
121
+ function isTransactionError(error) {
122
+ return error instanceof TransactionError;
123
+ }
124
+ var Errors = {
125
+ walletNotConnected: (context) => new ConnectionError("WALLET_NOT_CONNECTED", "No wallet connected", context),
126
+ walletNotFound: (walletName) => new ConnectionError("WALLET_NOT_FOUND", `Wallet not found${walletName ? `: ${walletName}` : ""}`, { walletName }),
127
+ connectionFailed: (originalError) => new ConnectionError("CONNECTION_FAILED", "Failed to connect to wallet", void 0, originalError),
128
+ accountNotAvailable: (address) => new ConnectionError("ACCOUNT_NOT_AVAILABLE", "Requested account not available", { address }),
129
+ invalidTransaction: (reason, context) => new ValidationError("INVALID_TRANSACTION", `Invalid transaction: ${reason}`, context),
130
+ invalidFormat: (expectedFormat, actualFormat) => new ValidationError("INVALID_FORMAT", `Invalid format: expected ${expectedFormat}`, { expectedFormat, actualFormat }),
131
+ unsupportedFormat: (format) => new ValidationError("UNSUPPORTED_FORMAT", `Unsupported format: ${format}`, { format }),
132
+ missingProvider: (hookName) => new ConfigurationError(
133
+ "MISSING_PROVIDER",
134
+ `${hookName} must be used within ConnectorProvider. Wrap your app with <ConnectorProvider> or <UnifiedProvider>.`,
135
+ { hookName }
136
+ ),
137
+ clusterNotFound: (clusterId, availableClusters) => new ConfigurationError(
138
+ "CLUSTER_NOT_FOUND",
139
+ `Cluster ${clusterId} not found. Available clusters: ${availableClusters.join(", ")}`,
140
+ { clusterId, availableClusters }
141
+ ),
142
+ rpcError: (message, originalError) => new NetworkError("RPC_ERROR", message, void 0, originalError),
143
+ networkTimeout: () => new NetworkError("NETWORK_TIMEOUT", "Network request timed out"),
144
+ signingFailed: (originalError) => new TransactionError("SIGNING_FAILED", "Failed to sign transaction", void 0, originalError),
145
+ featureNotSupported: (feature) => new TransactionError("FEATURE_NOT_SUPPORTED", `Wallet does not support ${feature}`, { feature }),
146
+ userRejected: (operation) => new TransactionError("USER_REJECTED", `User rejected ${operation}`, { operation })
147
+ };
148
+ function toConnectorError(error, defaultMessage = "An unexpected error occurred") {
149
+ if (isConnectorError(error))
150
+ return error;
151
+ if (error instanceof Error) {
152
+ let message = error.message.toLowerCase();
153
+ 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);
154
+ }
155
+ return new TransactionError("SIGNING_FAILED", defaultMessage, { originalError: String(error) });
156
+ }
157
+ function getUserFriendlyMessage(error) {
158
+ return isConnectorError(error) ? {
159
+ WALLET_NOT_CONNECTED: "Please connect your wallet to continue.",
160
+ WALLET_NOT_FOUND: "Wallet not found. Please install a supported wallet.",
161
+ CONNECTION_FAILED: "Failed to connect to wallet. Please try again.",
162
+ USER_REJECTED: "Transaction was cancelled.",
163
+ FEATURE_NOT_SUPPORTED: "This wallet does not support this feature.",
164
+ SIGNING_FAILED: "Failed to sign transaction. Please try again.",
165
+ SEND_FAILED: "Failed to send transaction. Please try again.",
166
+ INVALID_CLUSTER: "Invalid network configuration.",
167
+ CLUSTER_NOT_FOUND: "Network not found.",
168
+ MISSING_PROVIDER: "Application not properly configured.",
169
+ RPC_ERROR: "Network error. Please check your connection.",
170
+ NETWORK_TIMEOUT: "Request timed out. Please try again."
171
+ }[error.code] || error.message || "An error occurred." : "An unexpected error occurred. Please try again.";
172
+ }
173
+ var PUBLIC_RPC_ENDPOINTS = {
174
+ mainnet: "https://api.mainnet-beta.solana.com",
175
+ devnet: "https://api.devnet.solana.com",
176
+ testnet: "https://api.testnet.solana.com",
177
+ localnet: "http://localhost:8899"
178
+ };
179
+ function normalizeNetwork(network) {
180
+ switch (network.toLowerCase().replace("-beta", "")) {
181
+ case "mainnet":
182
+ return "mainnet";
183
+ case "devnet":
184
+ return "devnet";
185
+ case "testnet":
186
+ return "testnet";
187
+ case "localnet":
188
+ return "localnet";
189
+ default:
190
+ return "mainnet";
191
+ }
192
+ }
193
+ function toClusterId(network) {
194
+ return `solana:${normalizeNetwork(network)}`;
195
+ }
196
+ function getDefaultRpcUrl(network) {
197
+ let normalized = normalizeNetwork(network);
198
+ try {
199
+ return getPublicSolanaRpcUrl(normalized);
200
+ } catch {
201
+ return PUBLIC_RPC_ENDPOINTS[normalized] ?? PUBLIC_RPC_ENDPOINTS.localnet;
202
+ }
203
+ }
204
+ function isMainnet(network) {
205
+ return normalizeNetwork(network) === "mainnet";
206
+ }
207
+ function isDevnet(network) {
208
+ return normalizeNetwork(network) === "devnet";
209
+ }
210
+ function isTestnet(network) {
211
+ return normalizeNetwork(network) === "testnet";
212
+ }
213
+ function isLocalnet(network) {
214
+ return normalizeNetwork(network) === "localnet";
215
+ }
216
+ function getNetworkDisplayName(network) {
217
+ let normalized = normalizeNetwork(network);
218
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
219
+ }
220
+ function getClusterRpcUrl(cluster) {
221
+ if (typeof cluster == "string") {
222
+ let presets2 = {
223
+ ...PUBLIC_RPC_ENDPOINTS,
224
+ "mainnet-beta": PUBLIC_RPC_ENDPOINTS.mainnet
225
+ };
226
+ if (presets2[cluster])
227
+ return presets2[cluster];
228
+ throw new Error(`Unknown cluster: ${cluster}`);
229
+ }
230
+ let url = cluster.url || cluster.rpcUrl;
231
+ if (!url)
232
+ throw new Error("Cluster URL is required");
233
+ if (url.startsWith("http://") || url.startsWith("https://"))
234
+ return url;
235
+ let presets = {
236
+ ...PUBLIC_RPC_ENDPOINTS,
237
+ "mainnet-beta": PUBLIC_RPC_ENDPOINTS.mainnet
238
+ };
239
+ return presets[url] ? presets[url] : url;
240
+ }
241
+ function getClusterExplorerUrl(cluster, path) {
242
+ let clusterSegment = cluster.id.split(":")[1] || "devnet", isMainnet2 = cluster.id === "solana:mainnet" || cluster.id === "solana:mainnet-beta", base = isMainnet2 ? "https://explorer.solana.com" : `https://explorer.solana.com?cluster=${clusterSegment}`;
243
+ return path ? isMainnet2 ? `https://explorer.solana.com/${path}` : `https://explorer.solana.com/${path}?cluster=${clusterSegment}` : base;
244
+ }
245
+ function getTransactionUrl(signature, cluster) {
246
+ let clusterType = getClusterType(cluster), explorerCluster = clusterType === "custom" || clusterType === "localnet" ? "devnet" : clusterType;
247
+ return getExplorerLink({
248
+ transaction: signature,
249
+ cluster: explorerCluster === "mainnet" ? "mainnet" : explorerCluster
250
+ });
251
+ }
252
+ function getAddressUrl(address, cluster) {
253
+ let clusterType = getClusterType(cluster), explorerCluster = clusterType === "custom" || clusterType === "localnet" ? "devnet" : clusterType;
254
+ return getExplorerLink({
255
+ address,
256
+ cluster: explorerCluster === "mainnet" ? "mainnet" : explorerCluster
257
+ });
258
+ }
259
+ function getTokenUrl(tokenAddress, cluster) {
260
+ return getClusterExplorerUrl(cluster, `token/${tokenAddress}`);
261
+ }
262
+ function getBlockUrl(slot, cluster) {
263
+ return getClusterExplorerUrl(cluster, `block/${slot}`);
264
+ }
265
+ function isMainnetCluster(cluster) {
266
+ return cluster.id === "solana:mainnet" || cluster.id === "solana:mainnet-beta";
267
+ }
268
+ function isDevnetCluster(cluster) {
269
+ return cluster.id === "solana:devnet";
270
+ }
271
+ function isTestnetCluster(cluster) {
272
+ return cluster.id === "solana:testnet";
273
+ }
274
+ function isLocalCluster(cluster) {
275
+ let url = cluster.url || cluster.rpcUrl;
276
+ return url ? cluster.id === "solana:localnet" || url.includes("localhost") || url.includes("127.0.0.1") : cluster.id === "solana:localnet";
277
+ }
278
+ function getClusterName(cluster) {
279
+ if (cluster.label) return cluster.label;
280
+ if (cluster.name) return cluster.name;
281
+ let parts = cluster.id.split(":");
282
+ if (parts.length >= 2 && parts[1]) {
283
+ let name = parts.slice(1).join(":");
284
+ return name.charAt(0).toUpperCase() + name.slice(1).replace(/-/g, " ");
285
+ }
286
+ return "Unknown";
287
+ }
288
+ function getClusterType(cluster) {
289
+ return isMainnetCluster(cluster) ? "mainnet" : isDevnetCluster(cluster) ? "devnet" : isTestnetCluster(cluster) ? "testnet" : isLocalCluster(cluster) ? "localnet" : "custom";
290
+ }
291
+ function getClusterChainId(cluster) {
292
+ let clusterType = getClusterType(cluster);
293
+ if (clusterType === "localnet" || clusterType === "custom")
294
+ return null;
295
+ switch (clusterType) {
296
+ case "mainnet":
297
+ return "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
298
+ case "devnet":
299
+ return "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
300
+ case "testnet":
301
+ return "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";
302
+ default:
303
+ return null;
304
+ }
305
+ }
306
+ function getChainIdForWalletStandard(cluster) {
307
+ return getClusterChainId(cluster);
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 (error) {
846
+ logger3.warn("Error during unsubscribe cleanup", { error });
847
+ }
848
+ this.unsubscribers = [];
849
+ }
850
+ };
851
+
852
+ // src/lib/connection/connection-manager.ts
853
+ function getConnectFeature(wallet) {
854
+ return wallet.features["standard:connect"]?.connect ?? null;
855
+ }
856
+ function getDisconnectFeature(wallet) {
857
+ return wallet.features["standard:disconnect"]?.disconnect ?? null;
858
+ }
859
+ function getEventsFeature(wallet) {
860
+ return wallet.features["standard:events"]?.on ?? null;
861
+ }
862
+ var ConnectionManager = class extends BaseCollaborator {
863
+ constructor(stateManager, eventEmitter, walletStorage, debug = false) {
864
+ super({ stateManager, eventEmitter, debug }, "ConnectionManager");
865
+ __publicField(this, "walletStorage");
866
+ __publicField(this, "walletChangeUnsub", null);
867
+ __publicField(this, "pollTimer", null);
868
+ __publicField(this, "pollAttempts", 0);
869
+ this.walletStorage = walletStorage;
870
+ }
871
+ /**
872
+ * Connect to a wallet
873
+ */
874
+ async connect(wallet, walletName) {
875
+ if (typeof window > "u") return;
876
+ let name = walletName || wallet.name;
877
+ this.eventEmitter.emit({
878
+ type: "connecting",
879
+ wallet: name,
880
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
881
+ }), this.stateManager.updateState({ connecting: true }, true);
882
+ try {
883
+ let connect = getConnectFeature(wallet);
884
+ if (!connect) throw new Error(`Wallet ${name} does not support standard connect`);
885
+ let result = await connect({ silent: false }), walletAccounts = wallet.accounts, accountMap = /* @__PURE__ */ new Map();
886
+ for (let a of [...walletAccounts, ...result.accounts]) accountMap.set(a.address, a);
887
+ 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;
888
+ this.stateManager.updateState(
889
+ {
890
+ selectedWallet: wallet,
891
+ connected: true,
892
+ connecting: false,
893
+ accounts,
894
+ selectedAccount: selected
895
+ },
896
+ true
897
+ ), this.log("\u2705 Connection successful - state updated:", {
898
+ connected: true,
899
+ selectedWallet: wallet.name,
900
+ selectedAccount: selected,
901
+ accountsCount: accounts.length
902
+ }), selected ? this.eventEmitter.emit({
903
+ type: "wallet:connected",
904
+ wallet: name,
905
+ account: selected,
906
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
907
+ }) : this.log("\u26A0\uFE0F Connection succeeded but no account available", {
908
+ wallet: wallet.name,
909
+ accountsCount: accounts.length
910
+ }), 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();
911
+ } catch (e) {
912
+ let errorMessage = e instanceof Error ? e.message : String(e);
913
+ throw this.eventEmitter.emit({
914
+ type: "connection:failed",
915
+ wallet: name,
916
+ error: errorMessage,
917
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
918
+ }), this.eventEmitter.emit({
919
+ type: "error",
920
+ error: e instanceof Error ? e : new Error(errorMessage),
921
+ context: "wallet-connection",
922
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
923
+ }), this.stateManager.updateState(
924
+ {
925
+ selectedWallet: null,
926
+ connected: false,
927
+ connecting: false,
928
+ accounts: [],
929
+ selectedAccount: null
930
+ },
931
+ true
932
+ ), e;
933
+ }
934
+ }
935
+ /**
936
+ * Disconnect from wallet
937
+ */
938
+ async disconnect() {
939
+ this.walletChangeUnsub && (this.walletChangeUnsub(), this.walletChangeUnsub = null), this.stopPollingWalletAccounts();
940
+ let wallet = this.getState().selectedWallet;
941
+ if (wallet) {
942
+ let disconnect = getDisconnectFeature(wallet);
943
+ disconnect && await disconnect();
944
+ }
945
+ this.stateManager.updateState(
946
+ {
947
+ selectedWallet: null,
948
+ connected: false,
949
+ accounts: [],
950
+ selectedAccount: null
951
+ },
952
+ true
953
+ ), this.eventEmitter.emit({
954
+ type: "wallet:disconnected",
955
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
956
+ }), this.walletStorage && "clear" in this.walletStorage && typeof this.walletStorage.clear == "function" ? this.walletStorage.clear() : this.walletStorage?.set(void 0);
957
+ }
958
+ /**
959
+ * Select a different account
960
+ */
961
+ async selectAccount(address) {
962
+ let state = this.getState(), current = state.selectedWallet;
963
+ if (!current) throw new Error("No wallet connected");
964
+ if (!address || address.length < 5)
965
+ throw new Error(`Invalid address format: ${address}`);
966
+ let target = state.accounts.find((acc) => acc.address === address)?.raw ?? null;
967
+ if (!target)
968
+ try {
969
+ let connect = getConnectFeature(current);
970
+ if (connect) {
971
+ let accounts = (await connect()).accounts.map((a) => this.toAccountInfo(a));
972
+ target = accounts.find((acc) => acc.address === address)?.raw ?? null, this.stateManager.updateState({ accounts });
973
+ }
974
+ } catch {
975
+ throw new Error("Failed to reconnect wallet for account selection");
976
+ }
977
+ if (!target) throw new Error(`Requested account not available: ${address}`);
978
+ this.stateManager.updateState({ selectedAccount: target.address }), this.eventEmitter.emit({
979
+ type: "account:changed",
980
+ account: target.address,
981
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
982
+ });
983
+ }
984
+ /**
985
+ * Convert wallet account to AccountInfo
986
+ */
987
+ toAccountInfo(account) {
988
+ return {
989
+ address: account.address,
990
+ icon: account.icon,
991
+ raw: account
992
+ };
993
+ }
994
+ /**
995
+ * Subscribe to wallet change events
996
+ */
997
+ subscribeToWalletEvents() {
998
+ this.walletChangeUnsub && (this.walletChangeUnsub(), this.walletChangeUnsub = null), this.stopPollingWalletAccounts();
999
+ let wallet = this.getState().selectedWallet;
1000
+ if (!wallet) return;
1001
+ let eventsOn = getEventsFeature(wallet);
1002
+ if (!eventsOn) {
1003
+ this.startPollingWalletAccounts();
1004
+ return;
1005
+ }
1006
+ try {
1007
+ this.walletChangeUnsub = eventsOn("change", (properties) => {
1008
+ let changeAccounts = properties?.accounts ?? [];
1009
+ if (changeAccounts.length === 0) return;
1010
+ let nextAccounts = changeAccounts.map((a) => this.toAccountInfo(a));
1011
+ nextAccounts.length > 0 && this.stateManager.updateState({
1012
+ accounts: nextAccounts
1013
+ });
1014
+ });
1015
+ } catch {
1016
+ this.startPollingWalletAccounts();
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Start polling wallet accounts (fallback when events not available)
1021
+ * Uses exponential backoff to reduce polling frequency over time
1022
+ */
1023
+ startPollingWalletAccounts() {
1024
+ if (this.pollTimer) return;
1025
+ let wallet = this.getState().selectedWallet;
1026
+ if (!wallet) return;
1027
+ this.pollAttempts = 0;
1028
+ let poll = () => {
1029
+ if (this.pollAttempts >= 20) {
1030
+ this.stopPollingWalletAccounts(), this.log("Stopped wallet polling after max attempts");
1031
+ return;
1032
+ }
1033
+ try {
1034
+ let state = this.getState(), nextAccounts = wallet.accounts.map((a) => this.toAccountInfo(a));
1035
+ state.accounts.length === 0 && nextAccounts.length > 0 && (this.stateManager.updateState({
1036
+ accounts: nextAccounts,
1037
+ selectedAccount: state.selectedAccount || nextAccounts[0]?.address || null
1038
+ }), this.pollAttempts = 0);
1039
+ } catch (error) {
1040
+ this.log("Wallet polling error:", error);
1041
+ }
1042
+ this.pollAttempts++;
1043
+ let intervalIndex = Math.min(this.pollAttempts, POLL_INTERVALS_MS.length - 1), interval = POLL_INTERVALS_MS[intervalIndex];
1044
+ this.pollTimer = setTimeout(poll, interval);
1045
+ };
1046
+ poll();
1047
+ }
1048
+ /**
1049
+ * Stop polling wallet accounts
1050
+ */
1051
+ stopPollingWalletAccounts() {
1052
+ this.pollTimer && (clearTimeout(this.pollTimer), this.pollTimer = null, this.pollAttempts = 0);
1053
+ }
1054
+ /**
1055
+ * Get stored wallet name
1056
+ */
1057
+ getStoredWallet() {
1058
+ return this.walletStorage?.get() ?? null;
1059
+ }
1060
+ };
1061
+
1062
+ // src/lib/connection/auto-connector.ts
1063
+ var logger4 = createLogger("AutoConnector"), MIN_ADDRESS_LENGTH = 30, AutoConnector = class {
1064
+ constructor(walletDetector, connectionManager, stateManager, walletStorage, debug = false) {
1065
+ __publicField(this, "walletDetector");
1066
+ __publicField(this, "connectionManager");
1067
+ __publicField(this, "stateManager");
1068
+ __publicField(this, "walletStorage");
1069
+ __publicField(this, "debug");
1070
+ this.walletDetector = walletDetector, this.connectionManager = connectionManager, this.stateManager = stateManager, this.walletStorage = walletStorage, this.debug = debug;
1071
+ }
1072
+ async attemptAutoConnect() {
1073
+ return await this.attemptInstantConnect() ? true : (await this.attemptStandardConnect(), this.stateManager.getSnapshot().connected);
1074
+ }
1075
+ async attemptInstantConnect() {
1076
+ let storedWalletName = this.walletStorage?.get();
1077
+ if (!storedWalletName) return false;
1078
+ let directWallet = this.walletDetector.detectDirectWallet(storedWalletName);
1079
+ if (!directWallet) return false;
1080
+ this.debug && logger4.info("Instant auto-connect: found wallet directly in window", { walletName: storedWalletName });
1081
+ try {
1082
+ let features = {};
1083
+ if (directWallet.connect && (features["standard:connect"] = {
1084
+ connect: async (...args) => {
1085
+ let options = args[0], result = await directWallet.connect(options);
1086
+ 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))
1087
+ return result;
1088
+ let legacyResult = result;
1089
+ if (legacyResult?.publicKey && typeof legacyResult.publicKey.toString == "function")
1090
+ return {
1091
+ accounts: [
1092
+ {
1093
+ address: legacyResult.publicKey.toString(),
1094
+ publicKey: legacyResult.publicKey.toBytes ? legacyResult.publicKey.toBytes() : new Uint8Array(),
1095
+ chains: ["solana:mainnet", "solana:devnet", "solana:testnet"],
1096
+ features: []
1097
+ }
1098
+ ]
1099
+ };
1100
+ if (directWallet.publicKey && typeof directWallet.publicKey.toString == "function") {
1101
+ let address = directWallet.publicKey.toString();
1102
+ return this.debug && logger4.debug("Using legacy wallet pattern - publicKey from wallet object"), {
1103
+ accounts: [
1104
+ {
1105
+ address,
1106
+ publicKey: directWallet.publicKey.toBytes ? directWallet.publicKey.toBytes() : new Uint8Array(),
1107
+ chains: ["solana:mainnet", "solana:devnet", "solana:testnet"],
1108
+ features: []
1109
+ }
1110
+ ]
1111
+ };
1112
+ }
1113
+ let publicKeyResult = result;
1114
+ return publicKeyResult && typeof publicKeyResult.toString == "function" && publicKeyResult.toString().length > MIN_ADDRESS_LENGTH ? {
1115
+ accounts: [
1116
+ {
1117
+ address: publicKeyResult.toString(),
1118
+ publicKey: publicKeyResult.toBytes ? publicKeyResult.toBytes() : new Uint8Array(),
1119
+ chains: ["solana:mainnet", "solana:devnet", "solana:testnet"],
1120
+ features: []
1121
+ }
1122
+ ]
1123
+ } : (this.debug && logger4.error("Legacy wallet: No valid publicKey found in any expected location"), { accounts: [] });
1124
+ }
1125
+ }), directWallet.disconnect) {
1126
+ let disconnectFn = directWallet.disconnect;
1127
+ features["standard:disconnect"] = {
1128
+ disconnect: () => disconnectFn.call(directWallet)
1129
+ };
1130
+ }
1131
+ if (directWallet.signTransaction) {
1132
+ let signTransactionFn = directWallet.signTransaction;
1133
+ features["standard:signTransaction"] = {
1134
+ signTransaction: (tx) => signTransactionFn.call(directWallet, tx)
1135
+ };
1136
+ }
1137
+ if (directWallet.signMessage) {
1138
+ let signMessageFn = directWallet.signMessage;
1139
+ features["standard:signMessage"] = {
1140
+ signMessage: (...args) => {
1141
+ let msg = args[0];
1142
+ return signMessageFn.call(directWallet, msg);
1143
+ }
1144
+ };
1145
+ }
1146
+ directWallet.features && Object.assign(features, directWallet.features);
1147
+ let walletIcon = directWallet.icon || directWallet._metadata?.icon || directWallet.adapter?.icon || directWallet.metadata?.icon || directWallet.iconUrl, wallet = {
1148
+ version: "1.0.0",
1149
+ name: storedWalletName,
1150
+ icon: walletIcon,
1151
+ chains: directWallet.chains || [
1152
+ "solana:mainnet",
1153
+ "solana:devnet",
1154
+ "solana:testnet"
1155
+ ],
1156
+ features,
1157
+ accounts: []
1158
+ };
1159
+ return this.stateManager.updateState(
1160
+ {
1161
+ wallets: [
1162
+ {
1163
+ wallet,
1164
+ installed: true,
1165
+ connectable: true
1166
+ }
1167
+ ]
1168
+ },
1169
+ true
1170
+ ), 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(() => {
1171
+ let ws = getWalletsRegistry().get();
1172
+ this.debug && logger4.debug("Checking for wallet standard update", {
1173
+ wsLength: ws.length,
1174
+ currentWalletsLength: this.stateManager.getSnapshot().wallets.length,
1175
+ shouldUpdate: ws.length > 1
1176
+ }), ws.length > 1 && this.walletDetector.initialize();
1177
+ }, 500), true;
1178
+ } catch (error) {
1179
+ return this.debug && logger4.error("Instant auto-connect failed", {
1180
+ walletName: storedWalletName,
1181
+ error: error instanceof Error ? error.message : error
1182
+ }), false;
1183
+ }
1184
+ }
1185
+ async attemptStandardConnect() {
1186
+ try {
1187
+ if (this.stateManager.getSnapshot().connected) {
1188
+ this.debug && logger4.info("Auto-connect: Already connected, skipping fallback auto-connect");
1189
+ return;
1190
+ }
1191
+ let storedWalletName = this.walletStorage?.get();
1192
+ if (this.debug && (logger4.debug("Auto-connect: stored wallet", { storedWalletName }), logger4.debug("Auto-connect: available wallets", {
1193
+ wallets: this.stateManager.getSnapshot().wallets.map((w) => w.wallet.name)
1194
+ })), !storedWalletName) return;
1195
+ let walletInfo = this.stateManager.getSnapshot().wallets.find((w) => w.wallet.name === storedWalletName);
1196
+ walletInfo ? (this.debug && logger4.info("Auto-connect: Found stored wallet, connecting"), await this.connectionManager.connect(walletInfo.wallet, storedWalletName)) : setTimeout(() => {
1197
+ let retryWallet = this.stateManager.getSnapshot().wallets.find((w) => w.wallet.name === storedWalletName);
1198
+ retryWallet && (this.debug && logger4.info("Auto-connect: Retry successful"), this.connectionManager.connect(retryWallet.wallet, storedWalletName).catch((err) => {
1199
+ logger4.error("Auto-connect retry connection failed", { error: err });
1200
+ }));
1201
+ }, 1e3);
1202
+ } catch (e) {
1203
+ this.debug && logger4.error("Auto-connect failed", { error: e }), this.walletStorage?.set(void 0);
1204
+ }
1205
+ }
1206
+ };
1207
+
1208
+ // src/lib/cluster/cluster-manager.ts
1209
+ var ClusterManager = class extends BaseCollaborator {
1210
+ constructor(stateManager, eventEmitter, clusterStorage, config, debug = false) {
1211
+ super({ stateManager, eventEmitter, debug }, "ClusterManager");
1212
+ __publicField(this, "clusterStorage");
1213
+ if (this.clusterStorage = clusterStorage, config) {
1214
+ let clusters = config.clusters ?? [], initialClusterId = this.clusterStorage?.get() ?? config.initialCluster ?? "solana:mainnet", initialCluster = clusters.find((c) => c.id === initialClusterId) ?? clusters[0] ?? null;
1215
+ this.stateManager.updateState({
1216
+ cluster: initialCluster,
1217
+ clusters
1218
+ });
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Set the active cluster (network)
1223
+ */
1224
+ async setCluster(clusterId) {
1225
+ let state = this.getState(), previousClusterId = state.cluster?.id || null, cluster = state.clusters.find((c) => c.id === clusterId);
1226
+ if (!cluster)
1227
+ throw Errors.clusterNotFound(
1228
+ clusterId,
1229
+ state.clusters.map((c) => c.id)
1230
+ );
1231
+ 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({
1232
+ type: "cluster:changed",
1233
+ cluster: clusterId,
1234
+ previousCluster: previousClusterId,
1235
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1236
+ }), this.log("\u{1F310} Cluster changed:", { from: previousClusterId, to: clusterId });
1237
+ }
1238
+ /**
1239
+ * Get the currently active cluster
1240
+ */
1241
+ getCluster() {
1242
+ return this.getState().cluster;
1243
+ }
1244
+ /**
1245
+ * Get all available clusters
1246
+ */
1247
+ getClusters() {
1248
+ return this.getState().clusters;
1249
+ }
1250
+ };
1251
+
1252
+ // src/lib/transaction/transaction-tracker.ts
1253
+ var TransactionTracker = class extends BaseCollaborator {
1254
+ constructor(stateManager, eventEmitter, maxTransactions = 20, debug = false) {
1255
+ super({ stateManager, eventEmitter, debug }, "TransactionTracker");
1256
+ __publicField(this, "transactions", []);
1257
+ __publicField(this, "totalTransactions", 0);
1258
+ __publicField(this, "maxTransactions");
1259
+ this.maxTransactions = maxTransactions;
1260
+ }
1261
+ /**
1262
+ * Track a transaction for debugging and monitoring
1263
+ */
1264
+ trackTransaction(activity) {
1265
+ let clusterId = this.getState().cluster?.id || "solana:devnet", fullActivity = {
1266
+ ...activity,
1267
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1268
+ cluster: clusterId
1269
+ };
1270
+ this.transactions.unshift(fullActivity), this.transactions.length > this.maxTransactions && this.transactions.pop(), this.totalTransactions++, this.eventEmitter.emit({
1271
+ type: "transaction:tracked",
1272
+ signature: fullActivity.signature,
1273
+ status: fullActivity.status,
1274
+ timestamp: fullActivity.timestamp
1275
+ }), this.log("[Connector] Transaction tracked:", fullActivity);
1276
+ }
1277
+ /**
1278
+ * Update transaction status (e.g., from pending to confirmed/failed)
1279
+ */
1280
+ updateStatus(signature, status, error) {
1281
+ let tx = this.transactions.find((t) => t.signature === signature);
1282
+ tx && (tx.status = status, error && (tx.error = error), this.eventEmitter.emit({
1283
+ type: "transaction:updated",
1284
+ signature,
1285
+ status,
1286
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1287
+ }), this.log("[Connector] Transaction updated:", { signature, status, error }));
1288
+ }
1289
+ /**
1290
+ * Get transaction history
1291
+ */
1292
+ getTransactions() {
1293
+ return [...this.transactions];
1294
+ }
1295
+ /**
1296
+ * Get total transaction count
1297
+ */
1298
+ getTotalCount() {
1299
+ return this.totalTransactions;
1300
+ }
1301
+ /**
1302
+ * Clear transaction history
1303
+ */
1304
+ clearHistory() {
1305
+ this.transactions = [];
1306
+ }
1307
+ };
1308
+
1309
+ // src/lib/health/health-monitor.ts
1310
+ var HealthMonitor = class {
1311
+ constructor(stateManager, walletStorage, clusterStorage, isInitialized) {
1312
+ __publicField(this, "stateManager");
1313
+ __publicField(this, "walletStorage");
1314
+ __publicField(this, "clusterStorage");
1315
+ __publicField(this, "isInitialized");
1316
+ this.stateManager = stateManager, this.walletStorage = walletStorage, this.clusterStorage = clusterStorage, this.isInitialized = isInitialized ?? (() => true);
1317
+ }
1318
+ /**
1319
+ * Check connector health and availability
1320
+ */
1321
+ getHealth() {
1322
+ let errors = [], walletStandardAvailable = false;
1323
+ try {
1324
+ let registry2 = getWalletsRegistry();
1325
+ walletStandardAvailable = !!(registry2 && typeof registry2.get == "function"), walletStandardAvailable || errors.push("Wallet Standard registry not properly initialized");
1326
+ } catch (error) {
1327
+ errors.push(`Wallet Standard error: ${error instanceof Error ? error.message : "Unknown error"}`), walletStandardAvailable = false;
1328
+ }
1329
+ let storageAvailable = false;
1330
+ try {
1331
+ if (!this.walletStorage || !this.clusterStorage)
1332
+ errors.push("Storage adapters not configured"), storageAvailable = false;
1333
+ else {
1334
+ if ("isAvailable" in this.walletStorage && typeof this.walletStorage.isAvailable == "function")
1335
+ storageAvailable = this.walletStorage.isAvailable();
1336
+ else if (typeof window < "u")
1337
+ try {
1338
+ let testKey = "__connector_storage_test__";
1339
+ window.localStorage.setItem(testKey, "test"), window.localStorage.removeItem(testKey), storageAvailable = true;
1340
+ } catch {
1341
+ storageAvailable = false;
1342
+ }
1343
+ storageAvailable || errors.push("localStorage unavailable (private browsing mode or quota exceeded)");
1344
+ }
1345
+ } catch (error) {
1346
+ errors.push(`Storage error: ${error instanceof Error ? error.message : "Unknown error"}`), storageAvailable = false;
1347
+ }
1348
+ let state = this.stateManager.getSnapshot();
1349
+ 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"), {
1350
+ initialized: this.isInitialized(),
1351
+ walletStandardAvailable,
1352
+ storageAvailable,
1353
+ walletsDetected: state.wallets.length,
1354
+ errors,
1355
+ connectionState: {
1356
+ connected: state.connected,
1357
+ connecting: state.connecting,
1358
+ hasSelectedWallet: !!state.selectedWallet,
1359
+ hasSelectedAccount: !!state.selectedAccount
1360
+ },
1361
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1362
+ };
1363
+ }
1364
+ };
1365
+
1366
+ // src/lib/core/connector-client.ts
1367
+ var logger5 = createLogger("ConnectorClient"), ConnectorClient = class {
1368
+ constructor(config = {}) {
1369
+ __publicField(this, "stateManager");
1370
+ __publicField(this, "eventEmitter");
1371
+ __publicField(this, "walletDetector");
1372
+ __publicField(this, "connectionManager");
1373
+ __publicField(this, "autoConnector");
1374
+ __publicField(this, "clusterManager");
1375
+ __publicField(this, "transactionTracker");
1376
+ __publicField(this, "debugMetrics");
1377
+ __publicField(this, "healthMonitor");
1378
+ __publicField(this, "initialized", false);
1379
+ __publicField(this, "config");
1380
+ this.config = config;
1381
+ let initialState = {
1382
+ wallets: [],
1383
+ selectedWallet: null,
1384
+ connected: false,
1385
+ connecting: false,
1386
+ accounts: [],
1387
+ selectedAccount: null,
1388
+ cluster: null,
1389
+ clusters: []
1390
+ };
1391
+ 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(
1392
+ this.stateManager,
1393
+ this.eventEmitter,
1394
+ config.storage?.wallet,
1395
+ config.debug ?? false
1396
+ ), this.autoConnector = new AutoConnector(
1397
+ this.walletDetector,
1398
+ this.connectionManager,
1399
+ this.stateManager,
1400
+ config.storage?.wallet,
1401
+ config.debug ?? false
1402
+ ), this.clusterManager = new ClusterManager(
1403
+ this.stateManager,
1404
+ this.eventEmitter,
1405
+ config.storage?.cluster,
1406
+ config.cluster,
1407
+ config.debug ?? false
1408
+ ), this.transactionTracker = new TransactionTracker(
1409
+ this.stateManager,
1410
+ this.eventEmitter,
1411
+ DEFAULT_MAX_TRACKED_TRANSACTIONS,
1412
+ config.debug ?? false
1413
+ ), this.healthMonitor = new HealthMonitor(
1414
+ this.stateManager,
1415
+ config.storage?.wallet,
1416
+ config.storage?.cluster,
1417
+ () => this.initialized
1418
+ ), this.initialize();
1419
+ }
1420
+ initialize() {
1421
+ if (!(typeof window > "u") && !this.initialized)
1422
+ try {
1423
+ this.walletDetector.initialize(), this.config.autoConnect && setTimeout(() => {
1424
+ this.autoConnector.attemptAutoConnect().catch((err) => {
1425
+ this.config.debug && logger5.error("Auto-connect error", { error: err });
1426
+ });
1427
+ }, 100), this.initialized = true;
1428
+ } catch (e) {
1429
+ this.config.debug && logger5.error("Connector initialization failed", { error: e });
1430
+ }
1431
+ }
1432
+ async select(walletName) {
1433
+ let wallet = this.stateManager.getSnapshot().wallets.find((w) => w.wallet.name === walletName)?.wallet;
1434
+ if (!wallet) throw new Error(`Wallet ${walletName} not found`);
1435
+ await this.connectionManager.connect(wallet, walletName);
1436
+ }
1437
+ async disconnect() {
1438
+ await this.connectionManager.disconnect();
1439
+ }
1440
+ async selectAccount(address) {
1441
+ await this.connectionManager.selectAccount(address);
1442
+ }
1443
+ async setCluster(clusterId) {
1444
+ await this.clusterManager.setCluster(clusterId);
1445
+ }
1446
+ getCluster() {
1447
+ return this.clusterManager.getCluster();
1448
+ }
1449
+ getClusters() {
1450
+ return this.clusterManager.getClusters();
1451
+ }
1452
+ getRpcUrl() {
1453
+ let cluster = this.clusterManager.getCluster();
1454
+ if (!cluster) return null;
1455
+ try {
1456
+ return getClusterRpcUrl(cluster);
1457
+ } catch (error) {
1458
+ return this.config.debug && logger5.error("Failed to get RPC URL", { error }), null;
1459
+ }
1460
+ }
1461
+ subscribe(listener) {
1462
+ return this.stateManager.subscribe(listener);
1463
+ }
1464
+ getSnapshot() {
1465
+ return this.stateManager.getSnapshot();
1466
+ }
1467
+ resetStorage() {
1468
+ this.config.debug && logger5.info("Resetting all storage to initial values");
1469
+ let storageKeys = ["account", "wallet", "cluster"];
1470
+ for (let key of storageKeys) {
1471
+ let storage = this.config.storage?.[key];
1472
+ if (storage && "reset" in storage && typeof storage.reset == "function")
1473
+ try {
1474
+ storage.reset(), this.config.debug && logger5.debug("Reset storage", { key });
1475
+ } catch (error) {
1476
+ this.config.debug && logger5.error("Failed to reset storage", { key, error });
1477
+ }
1478
+ }
1479
+ this.eventEmitter.emit({
1480
+ type: "storage:reset",
1481
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1482
+ });
1483
+ }
1484
+ on(listener) {
1485
+ return this.eventEmitter.on(listener);
1486
+ }
1487
+ off(listener) {
1488
+ this.eventEmitter.off(listener);
1489
+ }
1490
+ offAll() {
1491
+ this.eventEmitter.offAll();
1492
+ }
1493
+ emitEvent(event) {
1494
+ this.eventEmitter.emit(event);
1495
+ }
1496
+ trackTransaction(activity) {
1497
+ this.transactionTracker.trackTransaction(activity);
1498
+ }
1499
+ updateTransactionStatus(signature, status, error) {
1500
+ this.transactionTracker.updateStatus(signature, status, error);
1501
+ }
1502
+ clearTransactionHistory() {
1503
+ this.transactionTracker.clearHistory();
1504
+ }
1505
+ getHealth() {
1506
+ return this.healthMonitor.getHealth();
1507
+ }
1508
+ getDebugMetrics() {
1509
+ this.stateManager.getSnapshot();
1510
+ return this.debugMetrics.updateListenerCounts(this.eventEmitter.getListenerCount(), 0), this.debugMetrics.getMetrics();
1511
+ }
1512
+ getDebugState() {
1513
+ return {
1514
+ ...this.getDebugMetrics(),
1515
+ transactions: this.transactionTracker.getTransactions(),
1516
+ totalTransactions: this.transactionTracker.getTotalCount()
1517
+ };
1518
+ }
1519
+ resetDebugMetrics() {
1520
+ this.debugMetrics.resetMetrics();
1521
+ }
1522
+ destroy() {
1523
+ this.connectionManager.disconnect().catch(() => {
1524
+ }), this.walletDetector.destroy(), this.eventEmitter.offAll(), this.stateManager.clear();
1525
+ }
1526
+ };
1527
+ 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 {
1528
+ static log(error, errorInfo, context) {
1529
+ if (process.env.NODE_ENV === "development" && logger6.error(error.message, {
1530
+ error,
1531
+ errorInfo,
1532
+ context
1533
+ }), process.env.NODE_ENV === "production" && typeof window < "u")
1534
+ try {
1535
+ let gtag = window.gtag;
1536
+ typeof gtag == "function" && gtag("event", "exception", {
1537
+ description: error.message,
1538
+ fatal: false,
1539
+ custom_map: { error_type: "wallet_error", ...context }
1540
+ });
1541
+ } catch {
1542
+ }
1543
+ }
1544
+ };
1545
+ function classifyError(error) {
1546
+ if (isConnectorError(error))
1547
+ return {
1548
+ ...error,
1549
+ type: {
1550
+ WALLET_NOT_CONNECTED: "CONNECTION_FAILED" /* CONNECTION_FAILED */,
1551
+ WALLET_NOT_FOUND: "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1552
+ CONNECTION_FAILED: "CONNECTION_FAILED" /* CONNECTION_FAILED */,
1553
+ USER_REJECTED: "USER_REJECTED" /* USER_REJECTED */,
1554
+ RPC_ERROR: "NETWORK_ERROR" /* NETWORK_ERROR */,
1555
+ NETWORK_TIMEOUT: "NETWORK_ERROR" /* NETWORK_ERROR */,
1556
+ SIGNING_FAILED: "TRANSACTION_FAILED" /* TRANSACTION_FAILED */,
1557
+ SEND_FAILED: "TRANSACTION_FAILED" /* TRANSACTION_FAILED */
1558
+ }[error.code] || "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
1559
+ recoverable: error.recoverable,
1560
+ context: error.context
1561
+ };
1562
+ let walletError = error;
1563
+ if (walletError.type) return walletError;
1564
+ let type = "UNKNOWN_ERROR" /* UNKNOWN_ERROR */, recoverable = false;
1565
+ 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), {
1566
+ ...error,
1567
+ type,
1568
+ recoverable,
1569
+ context: { originalMessage: error.message }
1570
+ };
1571
+ }
1572
+ var ConnectorErrorBoundary = class extends Component {
1573
+ constructor(props) {
1574
+ super(props);
1575
+ __publicField(this, "retryTimeouts", /* @__PURE__ */ new Set());
1576
+ __publicField(this, "retry", () => {
1577
+ let { maxRetries = 3 } = this.props;
1578
+ this.state.retryCount >= maxRetries || this.setState((prevState) => ({
1579
+ hasError: false,
1580
+ error: null,
1581
+ errorInfo: null,
1582
+ retryCount: prevState.retryCount + 1
1583
+ }));
1584
+ });
1585
+ this.state = {
1586
+ hasError: false,
1587
+ error: null,
1588
+ errorInfo: null,
1589
+ errorId: "",
1590
+ retryCount: 0
1591
+ };
1592
+ }
1593
+ static getDerivedStateFromError(error) {
1594
+ return {
1595
+ hasError: true,
1596
+ error,
1597
+ errorId: `error_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
1598
+ };
1599
+ }
1600
+ componentDidCatch(error, errorInfo) {
1601
+ this.setState({ errorInfo }), ErrorLogger.log(error, errorInfo, {
1602
+ retryCount: this.state.retryCount,
1603
+ errorId: this.state.errorId,
1604
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1605
+ }), this.props.onError?.(error, errorInfo);
1606
+ }
1607
+ componentWillUnmount() {
1608
+ this.retryTimeouts.forEach((timeout) => clearTimeout(timeout));
1609
+ }
1610
+ render() {
1611
+ if (this.state.hasError && this.state.error) {
1612
+ let walletError = classifyError(this.state.error);
1613
+ return this.props.fallback ? this.props.fallback(walletError, this.retry) : /* @__PURE__ */ jsx(DefaultErrorFallback, { error: walletError, onRetry: this.retry });
1614
+ }
1615
+ return this.props.children;
1616
+ }
1617
+ };
1618
+ function DefaultErrorFallback({ error, onRetry }) {
1619
+ let [isPending, startTransition] = useTransition(), [isRetrying, setIsRetrying] = useState(false), handleRetry = useCallback(() => {
1620
+ setIsRetrying(true), startTransition(() => {
1621
+ setTimeout(() => {
1622
+ onRetry(), setIsRetrying(false);
1623
+ }, 500);
1624
+ });
1625
+ }, [onRetry]), { title, message, actionText, showRetry } = useMemo(() => {
1626
+ switch (error.type) {
1627
+ case "USER_REJECTED" /* USER_REJECTED */:
1628
+ return {
1629
+ title: "Transaction Cancelled",
1630
+ message: "You cancelled the transaction. No problem!",
1631
+ actionText: "Try Again",
1632
+ showRetry: true
1633
+ };
1634
+ case "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */:
1635
+ return {
1636
+ title: "Wallet Not Found",
1637
+ message: "Please install a supported Solana wallet to continue.",
1638
+ actionText: "Check Wallets",
1639
+ showRetry: true
1640
+ };
1641
+ case "NETWORK_ERROR" /* NETWORK_ERROR */:
1642
+ return {
1643
+ title: "Network Error",
1644
+ message: "Having trouble connecting. Please check your internet connection.",
1645
+ actionText: "Retry",
1646
+ showRetry: true
1647
+ };
1648
+ case "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */:
1649
+ return {
1650
+ title: "Insufficient Funds",
1651
+ message: "You don't have enough SOL for this transaction.",
1652
+ actionText: "Add Funds",
1653
+ showRetry: false
1654
+ };
1655
+ default:
1656
+ return {
1657
+ title: "Something went wrong",
1658
+ message: "An unexpected error occurred. Please try again.",
1659
+ actionText: "Retry",
1660
+ showRetry: error.recoverable
1661
+ };
1662
+ }
1663
+ }, [error.type, error.recoverable]);
1664
+ return /* @__PURE__ */ jsxs(
1665
+ "div",
1666
+ {
1667
+ style: {
1668
+ display: "flex",
1669
+ flexDirection: "column",
1670
+ alignItems: "center",
1671
+ justifyContent: "center",
1672
+ padding: "2rem",
1673
+ textAlign: "center",
1674
+ borderRadius: "12px",
1675
+ border: "1px solid #e5e7eb",
1676
+ backgroundColor: "#fafafa",
1677
+ maxWidth: "400px",
1678
+ margin: "0 auto"
1679
+ },
1680
+ children: [
1681
+ /* @__PURE__ */ jsx(
1682
+ "div",
1683
+ {
1684
+ style: {
1685
+ width: "48px",
1686
+ height: "48px",
1687
+ borderRadius: "50%",
1688
+ backgroundColor: "#fee2e2",
1689
+ display: "flex",
1690
+ alignItems: "center",
1691
+ justifyContent: "center",
1692
+ marginBottom: "1rem"
1693
+ },
1694
+ 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" }) })
1695
+ }
1696
+ ),
1697
+ /* @__PURE__ */ jsx(
1698
+ "h3",
1699
+ {
1700
+ style: {
1701
+ margin: "0 0 0.5rem 0",
1702
+ fontSize: "1.125rem",
1703
+ fontWeight: "600",
1704
+ color: "#111827"
1705
+ },
1706
+ children: title
1707
+ }
1708
+ ),
1709
+ /* @__PURE__ */ jsx(
1710
+ "p",
1711
+ {
1712
+ style: {
1713
+ margin: "0 0 1.5rem 0",
1714
+ fontSize: "0.875rem",
1715
+ color: "#6b7280",
1716
+ lineHeight: "1.5"
1717
+ },
1718
+ children: message
1719
+ }
1720
+ ),
1721
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "0.75rem", flexWrap: "wrap" }, children: [
1722
+ showRetry && /* @__PURE__ */ jsx(
1723
+ "button",
1724
+ {
1725
+ onClick: handleRetry,
1726
+ disabled: isPending || isRetrying,
1727
+ style: {
1728
+ padding: "0.5rem 1rem",
1729
+ backgroundColor: "#3b82f6",
1730
+ color: "white",
1731
+ border: "none",
1732
+ borderRadius: "6px",
1733
+ fontSize: "0.875rem",
1734
+ fontWeight: "500",
1735
+ cursor: isPending || isRetrying ? "wait" : "pointer",
1736
+ opacity: isPending || isRetrying ? 0.7 : 1,
1737
+ transition: "all 0.2s"
1738
+ },
1739
+ children: isRetrying ? "Retrying..." : actionText
1740
+ }
1741
+ ),
1742
+ /* @__PURE__ */ jsx(
1743
+ "button",
1744
+ {
1745
+ onClick: () => window.location.reload(),
1746
+ style: {
1747
+ padding: "0.5rem 1rem",
1748
+ backgroundColor: "transparent",
1749
+ color: "#6b7280",
1750
+ border: "1px solid #d1d5db",
1751
+ borderRadius: "6px",
1752
+ fontSize: "0.875rem",
1753
+ fontWeight: "500",
1754
+ cursor: "pointer",
1755
+ transition: "all 0.2s"
1756
+ },
1757
+ children: "Refresh Page"
1758
+ }
1759
+ )
1760
+ ] }),
1761
+ process.env.NODE_ENV === "development" && /* @__PURE__ */ jsxs(
1762
+ "details",
1763
+ {
1764
+ style: {
1765
+ marginTop: "1rem",
1766
+ fontSize: "0.75rem",
1767
+ color: "#6b7280",
1768
+ width: "100%"
1769
+ },
1770
+ children: [
1771
+ /* @__PURE__ */ jsx("summary", { style: { cursor: "pointer", marginBottom: "0.5rem" }, children: "Error Details" }),
1772
+ /* @__PURE__ */ jsx(
1773
+ "pre",
1774
+ {
1775
+ style: {
1776
+ whiteSpace: "pre-wrap",
1777
+ wordBreak: "break-all",
1778
+ backgroundColor: "#f3f4f6",
1779
+ padding: "0.5rem",
1780
+ borderRadius: "4px",
1781
+ overflow: "auto",
1782
+ maxHeight: "200px"
1783
+ },
1784
+ children: error.message
1785
+ }
1786
+ )
1787
+ ]
1788
+ }
1789
+ )
1790
+ ]
1791
+ }
1792
+ );
1793
+ }
1794
+ function withErrorBoundary(Component2, errorBoundaryProps) {
1795
+ let WrappedComponent = (props) => /* @__PURE__ */ jsx(ConnectorErrorBoundary, { ...errorBoundaryProps, children: /* @__PURE__ */ jsx(Component2, { ...props }) });
1796
+ return WrappedComponent.displayName = `withErrorBoundary(${Component2.displayName || Component2.name})`, WrappedComponent;
1797
+ }
1798
+ var logger7 = createLogger("Polyfills"), installed = false;
1799
+ function installPolyfills() {
1800
+ if (!(installed || typeof window > "u"))
1801
+ try {
1802
+ install(), installed = true, process.env.NODE_ENV === "development" && logger7 && logger7.info("Browser compatibility polyfills installed");
1803
+ } catch (error) {
1804
+ logger7 && logger7.warn("Failed to install polyfills", { error }), installed = true;
1805
+ }
1806
+ }
1807
+ function isPolyfillInstalled() {
1808
+ return installed;
1809
+ }
1810
+ function isCryptoAvailable() {
1811
+ if (typeof window > "u") return false;
1812
+ try {
1813
+ return !!(window.crypto && window.crypto.subtle && typeof window.crypto.subtle.sign == "function");
1814
+ } catch {
1815
+ return false;
1816
+ }
1817
+ }
1818
+ function getPolyfillStatus() {
1819
+ return {
1820
+ installed,
1821
+ cryptoAvailable: isCryptoAvailable(),
1822
+ environment: typeof window < "u" ? "browser" : "server"
1823
+ };
1824
+ }
1825
+ function formatAddress(address, options = {}) {
1826
+ let { length = 4, separator = "..." } = options;
1827
+ return !address || address.length <= length * 2 + separator.length ? address : `${address.slice(0, length)}${separator}${address.slice(-length)}`;
1828
+ }
1829
+ function formatSOL(lamports, options = {}) {
1830
+ let { decimals = 4, suffix = true, fast = false } = options;
1831
+ if (fast && typeof lamports == "number") {
1832
+ let formatted2 = (lamports / LAMPORTS_PER_SOL).toFixed(decimals);
1833
+ return suffix ? `${formatted2} SOL` : formatted2;
1834
+ }
1835
+ let lamportsBigInt = typeof lamports == "bigint" ? lamports : BigInt(lamports), formatted = (Number(lamportsBigInt) / LAMPORTS_PER_SOL).toFixed(decimals);
1836
+ return suffix ? `${formatted} SOL` : formatted;
1837
+ }
1838
+ function formatNumber(value, options = {}) {
1839
+ let { decimals, locale = "en-US" } = options;
1840
+ return new Intl.NumberFormat(locale, {
1841
+ minimumFractionDigits: decimals,
1842
+ maximumFractionDigits: decimals
1843
+ }).format(value);
1844
+ }
1845
+ function truncate(text, maxLength, position = "middle") {
1846
+ if (!text || text.length <= maxLength) return text;
1847
+ if (position === "end")
1848
+ return text.slice(0, maxLength - 3) + "...";
1849
+ let half = Math.floor((maxLength - 3) / 2);
1850
+ return text.slice(0, half) + "..." + text.slice(-half);
1851
+ }
1852
+ function formatTokenAmount(amount, decimals, options = {}) {
1853
+ let value = Number(amount) / Math.pow(10, decimals), minDecimals = options.minimumDecimals ?? 0, maxDecimals = options.maximumDecimals ?? decimals;
1854
+ return value.toLocaleString("en-US", {
1855
+ minimumFractionDigits: minDecimals,
1856
+ maximumFractionDigits: maxDecimals
1857
+ });
1858
+ }
1859
+ 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 || {});
1860
+ function isClipboardAvailable() {
1861
+ if (typeof window > "u" || typeof document > "u")
1862
+ return { modern: false, fallback: false, available: false };
1863
+ let modern = typeof navigator?.clipboard?.writeText == "function", fallback = typeof document.execCommand == "function";
1864
+ return {
1865
+ modern,
1866
+ fallback,
1867
+ available: modern || fallback
1868
+ };
1869
+ }
1870
+ function validateAddress(address) {
1871
+ try {
1872
+ return isAddress(address);
1873
+ } catch {
1874
+ return false;
1875
+ }
1876
+ }
1877
+ function validateSignature(signature) {
1878
+ return !signature || typeof signature != "string" || signature.length < 87 || signature.length > 88 ? false : /^[1-9A-HJ-NP-Za-km-z]+$/.test(signature);
1879
+ }
1880
+ function formatValue(value, options) {
1881
+ let { format = "full", customFormatter, shortFormatChars = 4 } = options;
1882
+ if (format === "custom" && customFormatter)
1883
+ try {
1884
+ return customFormatter(value);
1885
+ } catch {
1886
+ return value;
1887
+ }
1888
+ if (format === "short") {
1889
+ if (value.length > 32 && value.length < 50)
1890
+ return formatAddress(value, { length: shortFormatChars });
1891
+ if (value.length > shortFormatChars * 2)
1892
+ return `${value.slice(0, shortFormatChars)}...${value.slice(-shortFormatChars)}`;
1893
+ }
1894
+ return value;
1895
+ }
1896
+ function copyUsingFallback(text) {
1897
+ try {
1898
+ let textArea = document.createElement("textarea");
1899
+ textArea.value = text, textArea.style.position = "fixed", textArea.style.left = "-999999px", textArea.style.top = "-999999px", document.body.appendChild(textArea), textArea.focus(), textArea.select();
1900
+ let successful = document.execCommand("copy");
1901
+ return document.body.removeChild(textArea), successful;
1902
+ } catch {
1903
+ return false;
1904
+ }
1905
+ }
1906
+ async function copyToClipboard(text, options = {}) {
1907
+ let { onSuccess, onError, validate, validateType = "none", useFallback = true } = options;
1908
+ if (!text || typeof text != "string" || text.trim() === "") {
1909
+ let error2 = "empty_value" /* EMPTY_VALUE */, message2 = "No text provided to copy";
1910
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1911
+ }
1912
+ if (typeof window > "u" || typeof navigator > "u") {
1913
+ let error2 = "ssr" /* SSR */, message2 = "Clipboard not available in server-side rendering context";
1914
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1915
+ }
1916
+ if (validate && !validate(text)) {
1917
+ let error2 = "invalid_value" /* INVALID_VALUE */, message2 = "Value failed custom validation";
1918
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1919
+ }
1920
+ if (validateType === "address" && !validateAddress(text)) {
1921
+ let error2 = "invalid_value" /* INVALID_VALUE */, message2 = "Invalid Solana address format";
1922
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1923
+ }
1924
+ if (validateType === "signature" && !validateSignature(text)) {
1925
+ let error2 = "invalid_value" /* INVALID_VALUE */, message2 = "Invalid transaction signature format";
1926
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1927
+ }
1928
+ let formattedValue = formatValue(text, options), availability = isClipboardAvailable();
1929
+ if (!availability.available) {
1930
+ let error2 = "not_supported" /* NOT_SUPPORTED */, message2 = "Clipboard API not supported in this browser";
1931
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1932
+ }
1933
+ if (availability.modern)
1934
+ try {
1935
+ return await navigator.clipboard.writeText(formattedValue), onSuccess?.(), { success: true, copiedValue: formattedValue };
1936
+ } catch (err) {
1937
+ if (err instanceof Error && (err.name === "NotAllowedError" || err.message.toLowerCase().includes("permission"))) {
1938
+ let error3 = "permission_denied" /* PERMISSION_DENIED */, message3 = "Clipboard permission denied by user or browser";
1939
+ return onError?.(error3, message3), { success: false, error: error3, errorMessage: message3 };
1940
+ }
1941
+ if (useFallback && availability.fallback && copyUsingFallback(formattedValue))
1942
+ return onSuccess?.(), { success: true, usedFallback: true, copiedValue: formattedValue };
1943
+ let error2 = "unknown" /* UNKNOWN */, message2 = err instanceof Error ? err.message : "Failed to copy to clipboard";
1944
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1945
+ }
1946
+ if (useFallback && availability.fallback) {
1947
+ if (copyUsingFallback(formattedValue))
1948
+ return onSuccess?.(), { success: true, usedFallback: true, copiedValue: formattedValue };
1949
+ let error2 = "unknown" /* UNKNOWN */, message2 = "Failed to copy using fallback method";
1950
+ return onError?.(error2, message2), { success: false, error: error2, errorMessage: message2 };
1951
+ }
1952
+ let error = "not_supported" /* NOT_SUPPORTED */, message = "No clipboard method available";
1953
+ return onError?.(error, message), { success: false, error, errorMessage: message };
1954
+ }
1955
+ async function copyAddressToClipboard(address, options) {
1956
+ return copyToClipboard(address, {
1957
+ ...options,
1958
+ validateType: "address"
1959
+ });
1960
+ }
1961
+ async function copySignatureToClipboard(signature, options) {
1962
+ return copyToClipboard(signature, {
1963
+ ...options,
1964
+ validateType: "signature"
1965
+ });
1966
+ }
1967
+
1968
+ // src/lib/transaction/transaction-validator.ts
1969
+ var logger8 = createLogger("TransactionValidator"), MAX_TRANSACTION_SIZE = 1232, MIN_TRANSACTION_SIZE = 64, TransactionValidator = class {
1970
+ /**
1971
+ * Validate a transaction before signing
1972
+ *
1973
+ * @param transaction - The transaction to validate
1974
+ * @param options - Validation options
1975
+ * @returns Validation result with errors and warnings
1976
+ */
1977
+ static validate(transaction, options = {}) {
1978
+ let {
1979
+ maxSize = MAX_TRANSACTION_SIZE,
1980
+ minSize = MIN_TRANSACTION_SIZE,
1981
+ checkDuplicateSignatures = true,
1982
+ strict = false
1983
+ } = options, errors = [], warnings = [], size;
1984
+ if (!transaction)
1985
+ return errors.push("Transaction is null or undefined"), { valid: false, errors, warnings };
1986
+ try {
1987
+ let serialized;
1988
+ if (typeof transaction.serialize == "function")
1989
+ try {
1990
+ serialized = transaction.serialize();
1991
+ } catch (serializeError) {
1992
+ logger8.debug("Transaction not yet serializable (may need signing)", {
1993
+ error: serializeError instanceof Error ? serializeError.message : String(serializeError)
1994
+ });
1995
+ }
1996
+ else if (transaction instanceof Uint8Array)
1997
+ serialized = transaction;
1998
+ else
1999
+ return errors.push(
2000
+ "Transaction type not recognized - must be a Transaction object with serialize() or Uint8Array"
2001
+ ), { valid: false, errors, warnings };
2002
+ 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"));
2003
+ } catch (error) {
2004
+ let errorMessage = error instanceof Error ? error.message : String(error);
2005
+ errors.push(`Transaction validation failed: ${errorMessage}`), logger8.error("Validation error", { error: errorMessage });
2006
+ }
2007
+ if (checkDuplicateSignatures && typeof transaction == "object" && "signatures" in transaction) {
2008
+ let signatures = transaction.signatures;
2009
+ Array.isArray(signatures) && new Set(
2010
+ signatures.map((sig) => {
2011
+ let pubKey = sig?.publicKey;
2012
+ return pubKey ? String(pubKey) : null;
2013
+ }).filter(Boolean)
2014
+ ).size < signatures.length && warnings.push("Transaction contains duplicate signers");
2015
+ }
2016
+ strict && warnings.length > 0 && (errors.push(...warnings.map((w) => `Strict mode: ${w}`)), warnings.length = 0);
2017
+ let valid = errors.length === 0;
2018
+ 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 }), {
2019
+ valid,
2020
+ errors,
2021
+ warnings,
2022
+ size
2023
+ };
2024
+ }
2025
+ /**
2026
+ * Check for suspicious patterns in serialized transaction
2027
+ * This is a heuristic check to detect potentially malicious transactions
2028
+ *
2029
+ * @param serialized - Serialized transaction bytes
2030
+ * @returns True if suspicious patterns detected
2031
+ */
2032
+ static hasSuspiciousPattern(serialized) {
2033
+ if (serialized.every((byte) => byte === 0) || serialized.every((byte) => byte === 255)) return true;
2034
+ let byteCounts = /* @__PURE__ */ new Map();
2035
+ for (let byte of serialized)
2036
+ byteCounts.set(byte, (byteCounts.get(byte) || 0) + 1);
2037
+ return Math.max(...Array.from(byteCounts.values())) / serialized.length > 0.5;
2038
+ }
2039
+ /**
2040
+ * Quick validation check - returns true if valid, throws on error
2041
+ * Useful for inline validation
2042
+ *
2043
+ * @param transaction - Transaction to validate
2044
+ * @param options - Validation options
2045
+ * @throws Error if validation fails
2046
+ *
2047
+ * @example
2048
+ * ```ts
2049
+ * TransactionValidator.assertValid(transaction);
2050
+ * // Continues if valid, throws if invalid
2051
+ * await signer.signTransaction(transaction);
2052
+ * ```
2053
+ */
2054
+ static assertValid(transaction, options) {
2055
+ let result = this.validate(transaction, options);
2056
+ if (!result.valid)
2057
+ throw new Error(`Transaction validation failed: ${result.errors.join(", ")}`);
2058
+ result.warnings.length > 0 && logger8.warn("Transaction validation warnings", { warnings: result.warnings });
2059
+ }
2060
+ /**
2061
+ * Batch validate multiple transactions
2062
+ * More efficient than validating one-by-one
2063
+ *
2064
+ * @param transactions - Array of transactions to validate
2065
+ * @param options - Validation options
2066
+ * @returns Array of validation results
2067
+ */
2068
+ static validateBatch(transactions, options) {
2069
+ return transactions.map((tx, index) => (logger8.debug(`Validating transaction ${index + 1}/${transactions.length}`), this.validate(tx, options)));
2070
+ }
2071
+ };
2072
+
2073
+ // src/lib/transaction/transaction-signer.ts
2074
+ var logger9 = createLogger("TransactionSigner");
2075
+ function createTransactionSigner(config) {
2076
+ let { wallet, account, cluster, eventEmitter } = config;
2077
+ if (!wallet || !account)
2078
+ return null;
2079
+ let features = wallet.features, address = account.address, capabilities = {
2080
+ canSign: !!features["solana:signTransaction"],
2081
+ canSend: !!features["solana:signAndSendTransaction"],
2082
+ canSignMessage: !!features["solana:signMessage"],
2083
+ supportsBatchSigning: !!features["solana:signAllTransactions"]
2084
+ }, signer = {
2085
+ address,
2086
+ async signTransaction(transaction) {
2087
+ if (!capabilities.canSign)
2088
+ throw Errors.featureNotSupported("transaction signing");
2089
+ let validation = TransactionValidator.validate(transaction);
2090
+ if (!validation.valid)
2091
+ throw logger9.error("Transaction validation failed", { errors: validation.errors }), Errors.invalidTransaction(validation.errors.join(", "));
2092
+ validation.warnings.length > 0 && logger9.warn("Transaction validation warnings", { warnings: validation.warnings });
2093
+ try {
2094
+ let signFeature = features["solana:signTransaction"], { serialized, wasWeb3js } = prepareTransactionForWallet(transaction);
2095
+ logger9.debug("Signing transaction", {
2096
+ wasWeb3js,
2097
+ serializedLength: serialized.length,
2098
+ serializedType: serialized.constructor.name,
2099
+ accountAddress: account?.address,
2100
+ hasAccount: !!account
2101
+ });
2102
+ let result, usedFormat = "";
2103
+ try {
2104
+ logger9.debug("Trying array format: transactions: [Uint8Array]"), result = await signFeature.signTransaction({
2105
+ account,
2106
+ transactions: [serialized],
2107
+ ...cluster ? { chain: cluster.id } : {}
2108
+ }), usedFormat = "array";
2109
+ } catch (err1) {
2110
+ let error1 = err1 instanceof Error ? err1 : new Error(String(err1));
2111
+ logger9.debug("Array format failed, trying singular format", { error: error1.message });
2112
+ try {
2113
+ logger9.debug("Trying singular format: transaction: Uint8Array"), result = await signFeature.signTransaction({
2114
+ account,
2115
+ transaction: serialized,
2116
+ ...cluster ? { chain: cluster.id } : {}
2117
+ }), usedFormat = "singular";
2118
+ } catch (err2) {
2119
+ let error2 = err2 instanceof Error ? err2 : new Error(String(err2));
2120
+ throw logger9.error("Both array and singular formats failed", { error: error2.message }), error2;
2121
+ }
2122
+ }
2123
+ logger9.debug("Wallet signed successfully", { format: usedFormat });
2124
+ let signedTx;
2125
+ if (Array.isArray(result.signedTransactions) && result.signedTransactions[0])
2126
+ signedTx = result.signedTransactions[0];
2127
+ else if (result.signedTransaction)
2128
+ signedTx = result.signedTransaction;
2129
+ else if (Array.isArray(result) && result[0])
2130
+ signedTx = result[0];
2131
+ else if (result instanceof Uint8Array)
2132
+ signedTx = result;
2133
+ else
2134
+ throw new Error(`Unexpected wallet response format: ${JSON.stringify(Object.keys(result))}`);
2135
+ if (logger9.debug("Extracted signed transaction", {
2136
+ hasSignedTx: !!signedTx,
2137
+ signedTxType: signedTx?.constructor?.name,
2138
+ signedTxLength: signedTx?.length,
2139
+ isUint8Array: signedTx instanceof Uint8Array,
2140
+ hasSerialize: typeof signedTx?.serialize == "function"
2141
+ }), signedTx && typeof signedTx.serialize == "function")
2142
+ return logger9.debug("Wallet returned web3.js object directly, no conversion needed"), signedTx;
2143
+ if (signedTx && signedTx.signedTransaction) {
2144
+ logger9.debug("Found signedTransaction property");
2145
+ let bytes = signedTx.signedTransaction;
2146
+ if (bytes instanceof Uint8Array)
2147
+ return await convertSignedTransaction(bytes, wasWeb3js);
2148
+ }
2149
+ if (signedTx instanceof Uint8Array)
2150
+ return await convertSignedTransaction(signedTx, wasWeb3js);
2151
+ throw logger9.error("Unexpected wallet response format", {
2152
+ type: typeof signedTx,
2153
+ constructor: signedTx?.constructor?.name
2154
+ }), new ValidationError(
2155
+ "INVALID_FORMAT",
2156
+ "Wallet returned unexpected format - not a Transaction or Uint8Array"
2157
+ );
2158
+ } catch (error) {
2159
+ throw Errors.signingFailed(error);
2160
+ }
2161
+ },
2162
+ async signAllTransactions(transactions) {
2163
+ if (transactions.length === 0)
2164
+ return [];
2165
+ if (capabilities.supportsBatchSigning)
2166
+ try {
2167
+ 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({
2168
+ account,
2169
+ transactions: serializedTxs,
2170
+ ...cluster ? { chain: cluster.id } : {}
2171
+ });
2172
+ return await Promise.all(
2173
+ result.signedTransactions.map(
2174
+ (signedBytes) => convertSignedTransaction(signedBytes, wasWeb3js)
2175
+ )
2176
+ );
2177
+ } catch (error) {
2178
+ throw new TransactionError(
2179
+ "SIGNING_FAILED",
2180
+ "Failed to sign transactions in batch",
2181
+ { count: transactions.length },
2182
+ error
2183
+ );
2184
+ }
2185
+ if (!capabilities.canSign)
2186
+ throw Errors.featureNotSupported("transaction signing");
2187
+ let signed = [];
2188
+ for (let i = 0; i < transactions.length; i++)
2189
+ try {
2190
+ let signedTx = await signer.signTransaction(transactions[i]);
2191
+ signed.push(signedTx);
2192
+ } catch (error) {
2193
+ throw new TransactionError(
2194
+ "SIGNING_FAILED",
2195
+ `Failed to sign transaction ${i + 1} of ${transactions.length}`,
2196
+ { index: i, total: transactions.length },
2197
+ error
2198
+ );
2199
+ }
2200
+ return signed;
2201
+ },
2202
+ async signAndSendTransaction(transaction, options) {
2203
+ if (!capabilities.canSend)
2204
+ throw Errors.featureNotSupported("sending transactions");
2205
+ try {
2206
+ let sendFeature = features["solana:signAndSendTransaction"], { serialized } = prepareTransactionForWallet(transaction);
2207
+ eventEmitter && eventEmitter.emit({
2208
+ type: "transaction:preparing",
2209
+ transaction: serialized,
2210
+ size: serialized.length,
2211
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2212
+ });
2213
+ let inputBase = {
2214
+ account,
2215
+ ...cluster ? { chain: cluster.id } : {},
2216
+ ...options ? { options } : {}
2217
+ };
2218
+ eventEmitter && eventEmitter.emit({
2219
+ type: "transaction:signing",
2220
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2221
+ });
2222
+ let result;
2223
+ try {
2224
+ result = await sendFeature.signAndSendTransaction({
2225
+ ...inputBase,
2226
+ transactions: [serialized]
2227
+ });
2228
+ } catch {
2229
+ result = await sendFeature.signAndSendTransaction({
2230
+ ...inputBase,
2231
+ transaction: serialized
2232
+ });
2233
+ }
2234
+ let signature = typeof result == "object" && result.signature ? result.signature : String(result);
2235
+ return eventEmitter && eventEmitter.emit({
2236
+ type: "transaction:sent",
2237
+ signature,
2238
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2239
+ }), signature;
2240
+ } catch (error) {
2241
+ throw new TransactionError("SEND_FAILED", "Failed to send transaction", void 0, error);
2242
+ }
2243
+ },
2244
+ async signAndSendTransactions(transactions, options) {
2245
+ if (transactions.length === 0)
2246
+ return [];
2247
+ if (!capabilities.canSend)
2248
+ throw Errors.featureNotSupported("sending transactions");
2249
+ let signatures = [];
2250
+ for (let i = 0; i < transactions.length; i++)
2251
+ try {
2252
+ let sig = await signer.signAndSendTransaction(transactions[i], options);
2253
+ signatures.push(sig);
2254
+ } catch (error) {
2255
+ throw new TransactionError(
2256
+ "SEND_FAILED",
2257
+ `Failed to send transaction ${i + 1} of ${transactions.length}`,
2258
+ { index: i, total: transactions.length },
2259
+ error
2260
+ );
2261
+ }
2262
+ return signatures;
2263
+ },
2264
+ ...capabilities.canSignMessage && {
2265
+ async signMessage(message) {
2266
+ try {
2267
+ return (await features["solana:signMessage"].signMessage({
2268
+ account,
2269
+ message,
2270
+ ...cluster ? { chain: cluster.id } : {}
2271
+ })).signature;
2272
+ } catch (error) {
2273
+ throw new TransactionError("SIGNING_FAILED", "Failed to sign message", void 0, error);
2274
+ }
2275
+ }
2276
+ },
2277
+ getCapabilities() {
2278
+ return { ...capabilities };
2279
+ }
2280
+ };
2281
+ return signer;
2282
+ }
2283
+ var TransactionSignerError = class extends TransactionError {
2284
+ constructor(message, code, originalError) {
2285
+ let newCode = code === "WALLET_NOT_CONNECTED" ? "FEATURE_NOT_SUPPORTED" : code;
2286
+ super(newCode, message, void 0, originalError), this.name = "TransactionSignerError";
2287
+ }
2288
+ };
2289
+ function isTransactionSignerError(error) {
2290
+ return error instanceof TransactionSignerError || error instanceof TransactionError;
2291
+ }
2292
+ var logger10 = createLogger("GillTransactionSigner");
2293
+ function encodeShortVecLength(value) {
2294
+ let bytes = [], remaining = value;
2295
+ for (; remaining >= 128; )
2296
+ bytes.push(remaining & 127 | 128), remaining >>= 7;
2297
+ return bytes.push(remaining), new Uint8Array(bytes);
2298
+ }
2299
+ function decodeShortVecLength(data) {
2300
+ let length = 0, size = 0;
2301
+ for (; ; ) {
2302
+ if (size >= data.length)
2303
+ throw new Error("Invalid shortvec encoding: unexpected end of data");
2304
+ let byte = data[size];
2305
+ if (length |= (byte & 127) << size * 7, size += 1, (byte & 128) === 0)
2306
+ break;
2307
+ if (size > 10)
2308
+ throw new Error("Invalid shortvec encoding: length prefix too long");
2309
+ }
2310
+ return { length, bytesConsumed: size };
2311
+ }
2312
+ function createTransactionBytesForSigning(messageBytes, numSigners) {
2313
+ let numSignaturesBytes = encodeShortVecLength(numSigners), signatureSlots = new Uint8Array(numSigners * 64), totalLength = numSignaturesBytes.length + signatureSlots.length + messageBytes.length, transactionBytes = new Uint8Array(totalLength), offset = 0;
2314
+ return transactionBytes.set(numSignaturesBytes, offset), offset += numSignaturesBytes.length, transactionBytes.set(signatureSlots, offset), offset += signatureSlots.length, transactionBytes.set(messageBytes, offset), transactionBytes;
2315
+ }
2316
+ function extractSignature(signedTx) {
2317
+ if (signedTx instanceof Uint8Array) {
2318
+ let { length: numSignatures, bytesConsumed } = decodeShortVecLength(signedTx);
2319
+ if (numSignatures === 0)
2320
+ throw new Error("No signatures found in serialized transaction");
2321
+ let signatureStart = bytesConsumed;
2322
+ return signedTx.slice(signatureStart, signatureStart + 64);
2323
+ }
2324
+ if (isWeb3jsTransaction(signedTx)) {
2325
+ let signatures = signedTx.signatures;
2326
+ if (!signatures || signatures.length === 0)
2327
+ throw new Error("No signatures found in web3.js transaction");
2328
+ let firstSig = signatures[0];
2329
+ if (firstSig instanceof Uint8Array)
2330
+ return firstSig;
2331
+ if (firstSig && typeof firstSig == "object" && "signature" in firstSig && firstSig.signature)
2332
+ return firstSig.signature;
2333
+ throw new Error("Could not extract signature from web3.js transaction");
2334
+ }
2335
+ throw new Error("Cannot extract signature from transaction format");
2336
+ }
2337
+ function createGillTransactionSigner(connectorSigner) {
2338
+ let signerAddress = address(connectorSigner.address);
2339
+ return {
2340
+ address: signerAddress,
2341
+ async modifyAndSignTransactions(transactions) {
2342
+ let transactionData = transactions.map((tx) => {
2343
+ let messageBytes = new Uint8Array(tx.messageBytes), numSigners = Object.keys(tx.signatures).length, wireFormat = createTransactionBytesForSigning(messageBytes, numSigners);
2344
+ return logger10.debug("Preparing wire format for wallet", {
2345
+ signerAddress,
2346
+ messageBytesLength: messageBytes.length,
2347
+ wireFormatLength: wireFormat.length,
2348
+ structure: {
2349
+ numSigsByte: wireFormat[0],
2350
+ firstSigSlotPreview: Array.from(wireFormat.slice(1, 17)),
2351
+ messageBytesStart: wireFormat.length - messageBytes.length
2352
+ }
2353
+ }), {
2354
+ originalTransaction: tx,
2355
+ messageBytes,
2356
+ wireFormat
2357
+ };
2358
+ }), transactionsForWallet = transactionData.map((data) => data.wireFormat);
2359
+ return (await connectorSigner.signAllTransactions(transactionsForWallet)).map((signedTx, index) => {
2360
+ let { originalTransaction, wireFormat } = transactionData[index];
2361
+ try {
2362
+ let signedTxBytes;
2363
+ if (signedTx instanceof Uint8Array)
2364
+ signedTxBytes = signedTx;
2365
+ else if (isWeb3jsTransaction(signedTx)) {
2366
+ let txObj = signedTx;
2367
+ if (typeof txObj.serialize == "function")
2368
+ signedTxBytes = txObj.serialize();
2369
+ else
2370
+ throw new Error("Web3.js transaction without serialize method");
2371
+ } else
2372
+ throw new Error("Unknown signed transaction format");
2373
+ if (logger10.debug("Wallet returned signed transaction", {
2374
+ returnedLength: signedTxBytes.length,
2375
+ sentLength: wireFormat.length,
2376
+ lengthsMatch: signedTxBytes.length === wireFormat.length,
2377
+ signedFirstBytes: Array.from(signedTxBytes.slice(0, 20)),
2378
+ sentFirstBytes: Array.from(wireFormat.slice(0, 20))
2379
+ }), signedTxBytes.length !== wireFormat.length) {
2380
+ logger10.warn("Wallet modified transaction! Using wallet version", {
2381
+ originalLength: wireFormat.length,
2382
+ modifiedLength: signedTxBytes.length,
2383
+ difference: signedTxBytes.length - wireFormat.length
2384
+ });
2385
+ let walletTransaction = getTransactionDecoder().decode(signedTxBytes), originalWithLifetime = originalTransaction, result = {
2386
+ ...walletTransaction,
2387
+ ...originalWithLifetime.lifetimeConstraint ? {
2388
+ lifetimeConstraint: originalWithLifetime.lifetimeConstraint
2389
+ } : {}
2390
+ };
2391
+ return logger10.debug("Using modified transaction from wallet", {
2392
+ modifiedMessageBytesLength: walletTransaction.messageBytes.length,
2393
+ signatures: Object.keys(walletTransaction.signatures)
2394
+ }), result;
2395
+ }
2396
+ let signatureBytes = extractSignature(signedTxBytes), signatureBase58 = getSignatureFromBytes(signatureBytes);
2397
+ return logger10.debug("Extracted signature from wallet (unmodified)", {
2398
+ signerAddress,
2399
+ signatureLength: signatureBytes.length,
2400
+ signatureBase58
2401
+ // Human-readable signature for debugging/logging
2402
+ }), {
2403
+ ...originalTransaction,
2404
+ signatures: Object.freeze({
2405
+ ...originalTransaction.signatures,
2406
+ [signerAddress]: signatureBytes
2407
+ })
2408
+ };
2409
+ } catch (error) {
2410
+ return logger10.error("Failed to decode signed transaction", { error }), originalTransaction;
2411
+ }
2412
+ });
2413
+ }
2414
+ };
2415
+ }
2416
+
2417
+ 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, getChainIdForWalletStandard, getClusterChainId, 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 };
2418
+ //# sourceMappingURL=chunk-TAAXHAV2.mjs.map
2419
+ //# sourceMappingURL=chunk-TAAXHAV2.mjs.map