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