@solana/connector 0.1.6 → 0.1.8

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 (50) hide show
  1. package/README.md +122 -44
  2. package/dist/{chunk-VMSZJPR5.mjs → chunk-6F6M6L7R.mjs} +152 -173
  3. package/dist/chunk-6F6M6L7R.mjs.map +1 -0
  4. package/dist/{chunk-NQXK7PGX.js → chunk-AOIXHVRH.js} +82 -235
  5. package/dist/chunk-AOIXHVRH.js.map +1 -0
  6. package/dist/chunk-DSUCH44G.js +678 -0
  7. package/dist/chunk-DSUCH44G.js.map +1 -0
  8. package/dist/{chunk-JUZVCBAI.js → chunk-FTXIXM43.js} +240 -271
  9. package/dist/chunk-FTXIXM43.js.map +1 -0
  10. package/dist/{chunk-QKVL45F6.mjs → chunk-G575OAT4.mjs} +73 -218
  11. package/dist/chunk-G575OAT4.mjs.map +1 -0
  12. package/dist/chunk-J7DHGLW6.mjs +638 -0
  13. package/dist/chunk-J7DHGLW6.mjs.map +1 -0
  14. package/dist/{chunk-ULUYX23Q.js → chunk-K3BNIGPX.js} +1023 -404
  15. package/dist/chunk-K3BNIGPX.js.map +1 -0
  16. package/dist/{chunk-3STZXVXD.mjs → chunk-TTOKQAPX.mjs} +998 -388
  17. package/dist/chunk-TTOKQAPX.mjs.map +1 -0
  18. package/dist/compat.d.mts +1 -1
  19. package/dist/compat.d.ts +1 -1
  20. package/dist/compat.js +40 -39
  21. package/dist/compat.js.map +1 -1
  22. package/dist/compat.mjs +39 -38
  23. package/dist/compat.mjs.map +1 -1
  24. package/dist/headless.d.mts +540 -152
  25. package/dist/headless.d.ts +540 -152
  26. package/dist/headless.js +226 -190
  27. package/dist/headless.mjs +3 -3
  28. package/dist/index.d.mts +8 -6
  29. package/dist/index.d.ts +8 -6
  30. package/dist/index.js +286 -218
  31. package/dist/index.mjs +4 -4
  32. package/dist/react.d.mts +283 -16
  33. package/dist/react.d.ts +283 -16
  34. package/dist/react.js +60 -28
  35. package/dist/react.mjs +2 -2
  36. package/dist/{wallet-standard-shim--YcrQNRt.d.ts → standard-shim-CT49DM5l.d.mts} +72 -252
  37. package/dist/{wallet-standard-shim-Dx7H8Ctf.d.mts → standard-shim-D9guL5fz.d.ts} +72 -252
  38. package/dist/{transaction-signer-D9d8nxwb.d.mts → transaction-signer-T-KVQFi8.d.mts} +2 -2
  39. package/dist/{transaction-signer-D9d8nxwb.d.ts → transaction-signer-T-KVQFi8.d.ts} +2 -2
  40. package/package.json +3 -3
  41. package/dist/chunk-3STZXVXD.mjs.map +0 -1
  42. package/dist/chunk-I64FD2EH.js +0 -312
  43. package/dist/chunk-I64FD2EH.js.map +0 -1
  44. package/dist/chunk-JUZVCBAI.js.map +0 -1
  45. package/dist/chunk-NQXK7PGX.js.map +0 -1
  46. package/dist/chunk-QKVL45F6.mjs.map +0 -1
  47. package/dist/chunk-QL3IT3TS.mjs +0 -299
  48. package/dist/chunk-QL3IT3TS.mjs.map +0 -1
  49. package/dist/chunk-ULUYX23Q.js.map +0 -1
  50. package/dist/chunk-VMSZJPR5.mjs.map +0 -1
@@ -0,0 +1,638 @@
1
+ import { createSolanaRpc, createSolanaRpcSubscriptions, setTransactionMessageLifetimeUsingBlockhash, assertIsTransactionMessageWithBlockhashLifetime } from '@solana/kit';
2
+ import { getBase58Encoder, getBase58Decoder } from '@solana/codecs';
3
+ import { address } from '@solana/addresses';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
8
+
9
+ // src/lib/kit/constants.ts
10
+ var LAMPORTS_PER_SOL = 1e9;
11
+ function lamportsToSol(lamports) {
12
+ return Number(lamports) / 1e9;
13
+ }
14
+ function solToLamports(sol) {
15
+ return BigInt(Math.floor(sol * 1e9));
16
+ }
17
+
18
+ // src/lib/kit/rpc.ts
19
+ function getPublicSolanaRpcUrl(cluster) {
20
+ switch (cluster) {
21
+ case "devnet":
22
+ return "https://api.devnet.solana.com";
23
+ case "testnet":
24
+ return "https://api.testnet.solana.com";
25
+ case "mainnet-beta":
26
+ case "mainnet":
27
+ return "https://api.mainnet-beta.solana.com";
28
+ case "localnet":
29
+ case "localhost":
30
+ return "http://127.0.0.1:8899";
31
+ default:
32
+ throw new Error("Invalid cluster moniker");
33
+ }
34
+ }
35
+
36
+ // src/lib/kit/explorer.ts
37
+ function getExplorerLink(props = {}) {
38
+ let url = new URL("https://explorer.solana.com"), cluster = props.cluster;
39
+ return (!cluster || cluster === "mainnet") && (cluster = "mainnet-beta"), "address" in props && props.address ? url.pathname = `/address/${props.address}` : "transaction" in props && props.transaction ? url.pathname = `/tx/${props.transaction}` : "block" in props && props.block !== void 0 && (url.pathname = `/block/${props.block}`), cluster !== "mainnet-beta" && (cluster === "localnet" || cluster === "localhost" ? (url.searchParams.set("cluster", "custom"), url.searchParams.set("customUrl", "http://localhost:8899")) : url.searchParams.set("cluster", cluster)), url.toString();
40
+ }
41
+ function createSolanaClient({
42
+ urlOrMoniker,
43
+ rpcConfig,
44
+ rpcSubscriptionsConfig
45
+ }) {
46
+ if (!urlOrMoniker) throw new Error("Cluster url or moniker is required");
47
+ let parsedUrl;
48
+ if (urlOrMoniker instanceof URL)
49
+ parsedUrl = urlOrMoniker;
50
+ else
51
+ try {
52
+ parsedUrl = new URL(urlOrMoniker.toString());
53
+ } catch {
54
+ try {
55
+ parsedUrl = new URL(
56
+ getPublicSolanaRpcUrl(urlOrMoniker.toString())
57
+ );
58
+ } catch {
59
+ throw new Error("Invalid URL or cluster moniker");
60
+ }
61
+ }
62
+ if (!parsedUrl.protocol.match(/^https?:/i))
63
+ throw new Error("Unsupported protocol. Only HTTP and HTTPS are supported");
64
+ rpcConfig?.port && (parsedUrl.port = rpcConfig.port.toString());
65
+ let rpcUrl = parsedUrl.toString(), rpc = createSolanaRpc(rpcUrl);
66
+ parsedUrl.protocol = parsedUrl.protocol.replace("http", "ws"), rpcSubscriptionsConfig?.port ? parsedUrl.port = rpcSubscriptionsConfig.port.toString() : (parsedUrl.hostname === "localhost" || parsedUrl.hostname.startsWith("127")) && (parsedUrl.port = "8900");
67
+ let rpcSubscriptions = createSolanaRpcSubscriptions(
68
+ parsedUrl.toString()
69
+ );
70
+ return {
71
+ rpc,
72
+ rpcSubscriptions,
73
+ urlOrMoniker: rpcUrl
74
+ };
75
+ }
76
+
77
+ // src/lib/kit/debug.ts
78
+ var LOG_LEVELS = {
79
+ debug: 0,
80
+ info: 1,
81
+ warn: 2,
82
+ error: 3
83
+ };
84
+ function getMinLogLevel() {
85
+ return typeof process < "u" && process.env?.CONNECTOR_DEBUG_LEVEL ? process.env.CONNECTOR_DEBUG_LEVEL : typeof globalThis < "u" && globalThis.__CONNECTOR_DEBUG_LEVEL__ ? globalThis.__CONNECTOR_DEBUG_LEVEL__ : typeof window < "u" && window.__CONNECTOR_DEBUG_LEVEL__ ? window.__CONNECTOR_DEBUG_LEVEL__ : "info";
86
+ }
87
+ function isDebugEnabled() {
88
+ return !!(typeof process < "u" && (process.env?.CONNECTOR_DEBUG_LEVEL || process.env?.CONNECTOR_DEBUG === "true" || process.env?.CONNECTOR_DEBUG === "1") || typeof globalThis < "u" && (globalThis.__CONNECTOR_DEBUG__ === true || globalThis.__CONNECTOR_DEBUG_LEVEL__) || typeof window < "u" && (window.__CONNECTOR_DEBUG__ === true || window.__CONNECTOR_DEBUG_LEVEL__));
89
+ }
90
+ function debug(message, level = "info", prefix = "[Connector]") {
91
+ if (!isDebugEnabled() || LOG_LEVELS[level] < LOG_LEVELS[getMinLogLevel()]) return;
92
+ let formattedMessage = typeof message == "string" ? message : JSON.stringify(message, null, 2);
93
+ switch (level) {
94
+ case "debug":
95
+ console.log(prefix, formattedMessage);
96
+ break;
97
+ case "info":
98
+ console.info(prefix, formattedMessage);
99
+ break;
100
+ case "warn":
101
+ console.warn(prefix, formattedMessage);
102
+ break;
103
+ case "error":
104
+ console.error(prefix, formattedMessage);
105
+ break;
106
+ }
107
+ }
108
+
109
+ // src/lib/kit/prepare-transaction.ts
110
+ async function prepareTransaction(config) {
111
+ let blockhashReset = config.blockhashReset !== false, transaction = config.transaction, hasLifetimeConstraint = "lifetimeConstraint" in transaction;
112
+ if (blockhashReset || !hasLifetimeConstraint) {
113
+ let { value: latestBlockhash } = await config.rpc.getLatestBlockhash().send();
114
+ hasLifetimeConstraint ? blockhashReset && (isDebugEnabled() && debug("Auto resetting the latest blockhash.", "debug"), transaction = {
115
+ ...transaction,
116
+ lifetimeConstraint: latestBlockhash
117
+ }) : (isDebugEnabled() && debug("Transaction missing latest blockhash, fetching one.", "debug"), transaction = setTransactionMessageLifetimeUsingBlockhash(
118
+ latestBlockhash,
119
+ transaction
120
+ ));
121
+ }
122
+ return assertIsTransactionMessageWithBlockhashLifetime(transaction), transaction;
123
+ }
124
+
125
+ // src/lib/errors/index.ts
126
+ var ConnectorError = class extends Error {
127
+ constructor(message, context, originalError) {
128
+ super(message);
129
+ __publicField(this, "context");
130
+ __publicField(this, "originalError");
131
+ __publicField(this, "timestamp");
132
+ this.name = this.constructor.name, this.context = context, this.originalError = originalError, this.timestamp = (/* @__PURE__ */ new Date()).toISOString(), Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
133
+ }
134
+ toJSON() {
135
+ return {
136
+ name: this.name,
137
+ code: this.code,
138
+ message: this.message,
139
+ recoverable: this.recoverable,
140
+ context: this.context,
141
+ timestamp: this.timestamp,
142
+ originalError: this.originalError?.message
143
+ };
144
+ }
145
+ }, ConnectionError = class extends ConnectorError {
146
+ constructor(code, message, context, originalError) {
147
+ super(message, context, originalError);
148
+ __publicField(this, "code");
149
+ __publicField(this, "recoverable", true);
150
+ this.code = code;
151
+ }
152
+ }, ValidationError = class extends ConnectorError {
153
+ constructor(code, message, context, originalError) {
154
+ super(message, context, originalError);
155
+ __publicField(this, "code");
156
+ __publicField(this, "recoverable", false);
157
+ this.code = code;
158
+ }
159
+ }, ConfigurationError = class extends ConnectorError {
160
+ constructor(code, message, context, originalError) {
161
+ super(message, context, originalError);
162
+ __publicField(this, "code");
163
+ __publicField(this, "recoverable", false);
164
+ this.code = code;
165
+ }
166
+ }, NetworkError = class extends ConnectorError {
167
+ constructor(code, message, context, originalError) {
168
+ super(message, context, originalError);
169
+ __publicField(this, "code");
170
+ __publicField(this, "recoverable", true);
171
+ this.code = code;
172
+ }
173
+ }, TransactionError = class extends ConnectorError {
174
+ constructor(code, message, context, originalError) {
175
+ super(message, context, originalError);
176
+ __publicField(this, "code");
177
+ __publicField(this, "recoverable");
178
+ this.code = code, this.recoverable = ["USER_REJECTED", "SEND_FAILED", "SIMULATION_FAILED"].includes(code);
179
+ }
180
+ };
181
+ function isConnectorError(error) {
182
+ return error instanceof ConnectorError;
183
+ }
184
+ function isConnectionError(error) {
185
+ return error instanceof ConnectionError;
186
+ }
187
+ function isValidationError(error) {
188
+ return error instanceof ValidationError;
189
+ }
190
+ function isConfigurationError(error) {
191
+ return error instanceof ConfigurationError;
192
+ }
193
+ function isNetworkError(error) {
194
+ return error instanceof NetworkError;
195
+ }
196
+ function isTransactionError(error) {
197
+ return error instanceof TransactionError;
198
+ }
199
+ var Errors = {
200
+ walletNotConnected: (context) => new ConnectionError("WALLET_NOT_CONNECTED", "No wallet connected", context),
201
+ walletNotFound: (walletName) => new ConnectionError("WALLET_NOT_FOUND", `Wallet not found${walletName ? `: ${walletName}` : ""}`, {
202
+ walletName
203
+ }),
204
+ connectionFailed: (originalError) => new ConnectionError("CONNECTION_FAILED", "Failed to connect to wallet", void 0, originalError),
205
+ accountNotAvailable: (address2) => new ConnectionError("ACCOUNT_NOT_AVAILABLE", "Requested account not available", { address: address2 }),
206
+ invalidTransaction: (reason, context) => new ValidationError("INVALID_TRANSACTION", `Invalid transaction: ${reason}`, context),
207
+ invalidFormat: (expectedFormat, actualFormat) => new ValidationError("INVALID_FORMAT", `Invalid format: expected ${expectedFormat}`, {
208
+ expectedFormat,
209
+ actualFormat
210
+ }),
211
+ unsupportedFormat: (format) => new ValidationError("UNSUPPORTED_FORMAT", `Unsupported format: ${format}`, { format }),
212
+ missingProvider: (hookName) => new ConfigurationError(
213
+ "MISSING_PROVIDER",
214
+ `${hookName} must be used within ConnectorProvider. Wrap your app with <ConnectorProvider> or <UnifiedProvider>.`,
215
+ { hookName }
216
+ ),
217
+ clusterNotFound: (clusterId, availableClusters) => new ConfigurationError(
218
+ "CLUSTER_NOT_FOUND",
219
+ `Cluster ${clusterId} not found. Available clusters: ${availableClusters.join(", ")}`,
220
+ { clusterId, availableClusters }
221
+ ),
222
+ rpcError: (message, originalError) => new NetworkError("RPC_ERROR", message, void 0, originalError),
223
+ networkTimeout: () => new NetworkError("NETWORK_TIMEOUT", "Network request timed out"),
224
+ signingFailed: (originalError) => new TransactionError("SIGNING_FAILED", "Failed to sign transaction", void 0, originalError),
225
+ featureNotSupported: (feature) => new TransactionError("FEATURE_NOT_SUPPORTED", `Wallet does not support ${feature}`, { feature }),
226
+ userRejected: (operation) => new TransactionError("USER_REJECTED", `User rejected ${operation}`, { operation })
227
+ };
228
+ function toConnectorError(error, defaultMessage = "An unexpected error occurred") {
229
+ if (isConnectorError(error))
230
+ return error;
231
+ if (error instanceof Error) {
232
+ let message = error.message.toLowerCase();
233
+ 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);
234
+ }
235
+ return new TransactionError("SIGNING_FAILED", defaultMessage, { originalError: String(error) });
236
+ }
237
+ function getUserFriendlyMessage(error) {
238
+ return isConnectorError(error) ? {
239
+ WALLET_NOT_CONNECTED: "Please connect your wallet to continue.",
240
+ WALLET_NOT_FOUND: "Wallet not found. Please install a supported wallet.",
241
+ CONNECTION_FAILED: "Failed to connect to wallet. Please try again.",
242
+ USER_REJECTED: "Transaction was cancelled.",
243
+ FEATURE_NOT_SUPPORTED: "This wallet does not support this feature.",
244
+ SIGNING_FAILED: "Failed to sign transaction. Please try again.",
245
+ SEND_FAILED: "Failed to send transaction. Please try again.",
246
+ INVALID_CLUSTER: "Invalid network configuration.",
247
+ CLUSTER_NOT_FOUND: "Network not found.",
248
+ MISSING_PROVIDER: "Application not properly configured.",
249
+ RPC_ERROR: "Network error. Please check your connection.",
250
+ NETWORK_TIMEOUT: "Request timed out. Please try again."
251
+ }[error.code] || error.message || "An error occurred." : "An unexpected error occurred. Please try again.";
252
+ }
253
+ function detectMessageModification(original, modified) {
254
+ if (original.length !== modified.length)
255
+ return true;
256
+ for (let i = 0; i < original.length; i++)
257
+ if (original[i] !== modified[i])
258
+ return true;
259
+ return false;
260
+ }
261
+ function updateSignatureDictionary(original, signed, originalSignatures, address2, signature) {
262
+ let wasModified = detectMessageModification(original, signed), signatureBytes = signature, newSignatures = {};
263
+ return newSignatures[address2] = signatureBytes, wasModified ? newSignatures : {
264
+ ...originalSignatures,
265
+ ...newSignatures
266
+ };
267
+ }
268
+ function freezeSigner(signer) {
269
+ return Object.freeze(signer);
270
+ }
271
+ function base58ToSignatureBytes(signature) {
272
+ try {
273
+ let bytes = getBase58Encoder().encode(signature);
274
+ if (bytes.length !== 64)
275
+ throw new Error(`Invalid signature length: expected 64 bytes, got ${bytes.length}`);
276
+ return bytes;
277
+ } catch (error) {
278
+ throw new Error(`Failed to decode base58 signature: ${error instanceof Error ? error.message : String(error)}`);
279
+ }
280
+ }
281
+ function signatureBytesToBase58(bytes) {
282
+ try {
283
+ if (bytes.length !== 64)
284
+ throw new Error(`Invalid signature length: expected 64 bytes, got ${bytes.length}`);
285
+ return getBase58Decoder().decode(bytes);
286
+ } catch (error) {
287
+ throw new Error(
288
+ `Failed to encode signature to base58: ${error instanceof Error ? error.message : String(error)}`
289
+ );
290
+ }
291
+ }
292
+
293
+ // src/lib/kit/signer-factories.ts
294
+ function createMessageSignerFromWallet(walletAddress, signMessageFn) {
295
+ return freezeSigner({
296
+ address: walletAddress,
297
+ async modifyAndSignMessages(messages, config) {
298
+ if (messages.length !== 1)
299
+ throw new ValidationError("INVALID_FORMAT", "Wallets only support signing one message at a time", {
300
+ receivedCount: messages.length,
301
+ expectedCount: 1
302
+ });
303
+ let [message] = messages, { content, signatures: originalSignatures } = message;
304
+ if (config?.abortSignal?.aborted)
305
+ throw Errors.userRejected("message signing");
306
+ try {
307
+ let signature = await signMessageFn(content), signatures = updateSignatureDictionary(
308
+ content,
309
+ content,
310
+ // Message content doesn't change in signMessage
311
+ originalSignatures,
312
+ walletAddress,
313
+ signature
314
+ );
315
+ return [
316
+ {
317
+ content,
318
+ signatures
319
+ }
320
+ ];
321
+ } catch (error) {
322
+ if (error instanceof Error) {
323
+ let message2 = error.message.toLowerCase();
324
+ throw message2.includes("user rejected") || message2.includes("user denied") ? Errors.userRejected("message signing") : new TransactionError("SIGNING_FAILED", "Failed to sign message", void 0, error);
325
+ }
326
+ throw new TransactionError("SIGNING_FAILED", "Failed to sign message", {
327
+ originalError: String(error)
328
+ });
329
+ }
330
+ }
331
+ });
332
+ }
333
+ function createTransactionSendingSignerFromWallet(walletAddress, chain, sendTransactionFn) {
334
+ return freezeSigner({
335
+ address: walletAddress,
336
+ async signAndSendTransactions(transactions, config) {
337
+ if (transactions.length !== 1)
338
+ throw new ValidationError("INVALID_FORMAT", "Wallets only support sending one transaction at a time", {
339
+ receivedCount: transactions.length,
340
+ expectedCount: 1
341
+ });
342
+ let [transaction] = transactions;
343
+ if (config?.abortSignal?.aborted)
344
+ throw Errors.userRejected("transaction sending");
345
+ try {
346
+ let signatureString = await sendTransactionFn(transaction);
347
+ return [base58ToSignatureBytes(signatureString)];
348
+ } catch (error) {
349
+ if (error instanceof Error) {
350
+ let message = error.message.toLowerCase();
351
+ throw message.includes("user rejected") || message.includes("user denied") ? Errors.userRejected("transaction sending") : message.includes("network") || message.includes("rpc") ? new TransactionError("SEND_FAILED", "Failed to send transaction", void 0, error) : new TransactionError("SEND_FAILED", "Failed to send transaction", void 0, error);
352
+ }
353
+ throw new TransactionError("SEND_FAILED", "Failed to send transaction", {
354
+ originalError: String(error)
355
+ });
356
+ }
357
+ }
358
+ });
359
+ }
360
+ function createKitSignersFromWallet(wallet, account, connection, network) {
361
+ if (!wallet || !account)
362
+ return {
363
+ address: null,
364
+ addressString: null,
365
+ messageSigner: null,
366
+ transactionSigner: null
367
+ };
368
+ let walletAddress = null, walletAddressString = null;
369
+ try {
370
+ walletAddress = address(account.address), walletAddressString = account.address;
371
+ } catch {
372
+ return {
373
+ address: null,
374
+ addressString: null,
375
+ messageSigner: null,
376
+ transactionSigner: null
377
+ };
378
+ }
379
+ let chain = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
380
+ if (network)
381
+ chain = {
382
+ mainnet: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
383
+ devnet: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
384
+ testnet: "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"
385
+ }[network] || chain;
386
+ else if (connection) {
387
+ let rpcUrl = connection.rpcEndpoint || "";
388
+ rpcUrl.includes("mainnet") || rpcUrl.includes("api.mainnet-beta") ? chain = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" : rpcUrl.includes("testnet") ? chain = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z" : chain = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
389
+ }
390
+ let features = wallet.features, hasSignMessage = !!features["solana:signMessage"], hasSignAndSendTransaction = !!features["solana:signAndSendTransaction"], hasSendTransaction = !!features["solana:sendTransaction"], messageSigner = hasSignMessage ? createMessageSignerFromWallet(walletAddress, async (message) => {
391
+ if (!hasSignMessage)
392
+ throw Errors.featureNotSupported("message signing");
393
+ try {
394
+ let signFeature = features["solana:signMessage"], messageBytes = message instanceof Uint8Array ? message : new Uint8Array(message), results = await signFeature.signMessage({
395
+ account,
396
+ message: messageBytes,
397
+ ...chain ? { chain } : {}
398
+ });
399
+ if (!Array.isArray(results) || results.length === 0)
400
+ throw new Error("Wallet returned empty results array");
401
+ let firstResult = results[0];
402
+ if (!firstResult?.signature)
403
+ throw new Error("Wallet returned no signature in first result");
404
+ return firstResult.signature;
405
+ } catch (error) {
406
+ throw console.error("signMessage error:", error), error instanceof Error ? error : new Error(String(error));
407
+ }
408
+ }) : null, transactionSigner = hasSignAndSendTransaction || hasSendTransaction ? createTransactionSendingSignerFromWallet(walletAddress, chain, async (transaction) => {
409
+ if (hasSignAndSendTransaction)
410
+ try {
411
+ return (await features["solana:signAndSendTransaction"].signAndSendTransaction({
412
+ account,
413
+ transactions: [transaction],
414
+ ...chain ? { chain } : {},
415
+ ...connection ? { connection } : {}
416
+ })).signatures[0] || "";
417
+ } catch (error) {
418
+ throw error instanceof Error ? error : new Error(String(error));
419
+ }
420
+ if (hasSendTransaction)
421
+ try {
422
+ return (await features["solana:sendTransaction"].sendTransaction({
423
+ account,
424
+ transactions: [transaction],
425
+ ...chain ? { chain } : {}
426
+ })).signatures[0] || "";
427
+ } catch (error) {
428
+ throw error instanceof Error ? error : new Error(String(error));
429
+ }
430
+ throw Errors.featureNotSupported("transaction sending");
431
+ }) : null;
432
+ return {
433
+ address: walletAddress,
434
+ addressString: walletAddressString,
435
+ messageSigner,
436
+ transactionSigner
437
+ };
438
+ }
439
+
440
+ // src/lib/utils/secure-logger.ts
441
+ var SENSITIVE_KEYS = [
442
+ "address",
443
+ "publickey",
444
+ "signature",
445
+ "account",
446
+ "rpcurl",
447
+ "url",
448
+ "apikey",
449
+ "api_key",
450
+ "token",
451
+ "secret",
452
+ "password",
453
+ "private",
454
+ "seed",
455
+ "mnemonic"
456
+ ], LOG_LEVELS2 = {
457
+ debug: 0,
458
+ info: 1,
459
+ warn: 2,
460
+ error: 3
461
+ }, SecureLogger = class {
462
+ constructor(config = {}) {
463
+ __publicField(this, "config");
464
+ let isDevelopment = typeof process < "u" && process.env?.NODE_ENV === "development";
465
+ this.config = {
466
+ // Default to disabled - logging is opt-in via __CONNECTOR_DEBUG__ or explicit config
467
+ enabled: config.enabled ?? false,
468
+ level: config.level ?? "debug",
469
+ redactSensitive: config.redactSensitive ?? !isDevelopment,
470
+ prefix: config.prefix ?? "Connector",
471
+ useConnectorDebug: config.useConnectorDebug ?? true
472
+ // Default to using connector's debug system
473
+ };
474
+ }
475
+ /**
476
+ * Log debug information (lowest priority)
477
+ */
478
+ debug(message, data) {
479
+ this.log("debug", message, data);
480
+ }
481
+ /**
482
+ * Log general information
483
+ */
484
+ info(message, data) {
485
+ this.log("info", message, data);
486
+ }
487
+ /**
488
+ * Log warnings
489
+ */
490
+ warn(message, data) {
491
+ this.log("warn", message, data);
492
+ }
493
+ /**
494
+ * Log errors (highest priority)
495
+ */
496
+ error(message, data) {
497
+ this.log("error", message, data);
498
+ }
499
+ /**
500
+ * Internal log method that handles level filtering and redaction
501
+ * Integrates with connector's debug system when enabled
502
+ */
503
+ log(level, message, data) {
504
+ let debugEnabled = this.config.useConnectorDebug ? isDebugEnabled() : false;
505
+ if (!this.config.enabled && !debugEnabled) return;
506
+ let effectiveLevel = this.config.level;
507
+ if (this.config.useConnectorDebug && typeof globalThis < "u") {
508
+ let connectorLevel = globalThis.__CONNECTOR_DEBUG_LEVEL__;
509
+ connectorLevel && ["debug", "info", "warn", "error"].includes(connectorLevel) && (effectiveLevel = connectorLevel);
510
+ }
511
+ if (LOG_LEVELS2[level] < LOG_LEVELS2[effectiveLevel])
512
+ return;
513
+ let processedData = this.config.redactSensitive ? this.redact(data) : data, fullMessage = processedData !== void 0 ? `${message} ${typeof processedData == "object" ? JSON.stringify(processedData, null, 2) : processedData}` : message;
514
+ if (this.config.useConnectorDebug && debugEnabled)
515
+ debug(fullMessage, level, this.config.prefix);
516
+ else {
517
+ let prefix = `[${this.config.prefix}]`;
518
+ switch (level) {
519
+ case "debug":
520
+ console.debug(prefix, message, processedData !== void 0 ? processedData : "");
521
+ break;
522
+ case "info":
523
+ console.info(prefix, message, processedData !== void 0 ? processedData : "");
524
+ break;
525
+ case "warn":
526
+ console.warn(prefix, message, processedData !== void 0 ? processedData : "");
527
+ break;
528
+ case "error":
529
+ console.error(prefix, message, processedData !== void 0 ? processedData : "");
530
+ break;
531
+ }
532
+ }
533
+ }
534
+ /**
535
+ * Recursively redact sensitive information from data
536
+ */
537
+ redact(data) {
538
+ if (data == null || typeof data != "object")
539
+ return data;
540
+ if (Array.isArray(data))
541
+ return data.map((item) => this.redact(item));
542
+ let redacted = {};
543
+ for (let [key, value] of Object.entries(data)) {
544
+ let keyLower = key.toLowerCase();
545
+ SENSITIVE_KEYS.some((sensitiveKey) => keyLower.includes(sensitiveKey)) ? redacted[key] = this.maskValue(value) : typeof value == "object" && value !== null ? redacted[key] = this.redact(value) : redacted[key] = value;
546
+ }
547
+ return redacted;
548
+ }
549
+ /**
550
+ * Mask a sensitive value for logging
551
+ * Shows first 4 and last 4 characters for strings longer than 8 chars
552
+ */
553
+ maskValue(value) {
554
+ if (value == null)
555
+ return "***";
556
+ let str = String(value);
557
+ return str.length <= 8 ? "***" : `${str.slice(0, 4)}...${str.slice(-4)}`;
558
+ }
559
+ /**
560
+ * Update logger configuration at runtime
561
+ */
562
+ updateConfig(config) {
563
+ this.config = { ...this.config, ...config };
564
+ }
565
+ /**
566
+ * Get current configuration
567
+ */
568
+ getConfig() {
569
+ return { ...this.config };
570
+ }
571
+ }; new SecureLogger({
572
+ prefix: "Connector"
573
+ });
574
+ function createLogger(prefix, config) {
575
+ return new SecureLogger({ ...config, prefix });
576
+ }
577
+
578
+ // src/lib/core/try-catch.ts
579
+ async function tryCatch(promise) {
580
+ try {
581
+ return { data: await promise, error: null };
582
+ } catch (error) {
583
+ return { data: null, error };
584
+ }
585
+ }
586
+ function tryCatchSync(fn) {
587
+ try {
588
+ return { data: fn(), error: null };
589
+ } catch (error) {
590
+ return { data: null, error };
591
+ }
592
+ }
593
+ function isSuccess(result) {
594
+ return result.error === null;
595
+ }
596
+ function isFailure(result) {
597
+ return result.error !== null;
598
+ }
599
+
600
+ // src/utils/transaction-format.ts
601
+ function isWeb3jsTransaction(tx) {
602
+ return tx !== null && typeof tx == "object" && "serialize" in tx && typeof tx.serialize == "function";
603
+ }
604
+ function serializeTransaction(tx) {
605
+ if (isWeb3jsTransaction(tx))
606
+ return tx.serialize({
607
+ requireAllSignatures: false,
608
+ verifySignatures: false
609
+ });
610
+ if (tx instanceof Uint8Array)
611
+ return tx;
612
+ if (ArrayBuffer.isView(tx))
613
+ return new Uint8Array(tx.buffer, tx.byteOffset, tx.byteLength);
614
+ throw new Error("Unsupported transaction format - must be Transaction, VersionedTransaction, or Uint8Array");
615
+ }
616
+ function isLegacyTransaction(bytes) {
617
+ return bytes.length === 0 ? false : (bytes[0] & 128) === 0;
618
+ }
619
+ async function deserializeToWeb3jsTransaction(bytes) {
620
+ if (isLegacyTransaction(bytes)) {
621
+ let { Transaction } = await import('@solana/web3.js');
622
+ return Transaction.from(bytes);
623
+ } else {
624
+ let { VersionedTransaction } = await import('@solana/web3.js');
625
+ return VersionedTransaction.deserialize(bytes);
626
+ }
627
+ }
628
+ function prepareTransactionForWallet(tx) {
629
+ let wasWeb3js = isWeb3jsTransaction(tx);
630
+ return { serialized: serializeTransaction(tx), wasWeb3js };
631
+ }
632
+ async function convertSignedTransaction(signedBytes, wasWeb3js) {
633
+ return wasWeb3js ? await deserializeToWeb3jsTransaction(signedBytes) : signedBytes;
634
+ }
635
+
636
+ export { ConfigurationError, ConnectionError, ConnectorError, Errors, LAMPORTS_PER_SOL, NetworkError, TransactionError, ValidationError, __publicField, base58ToSignatureBytes, convertSignedTransaction, createKitSignersFromWallet, createLogger, createMessageSignerFromWallet, createSolanaClient, createTransactionSendingSignerFromWallet, detectMessageModification, freezeSigner, getExplorerLink, getPublicSolanaRpcUrl, getUserFriendlyMessage, isConfigurationError, isConnectionError, isConnectorError, isFailure, isNetworkError, isSuccess, isTransactionError, isValidationError, isWeb3jsTransaction, lamportsToSol, prepareTransaction, prepareTransactionForWallet, signatureBytesToBase58, solToLamports, toConnectorError, tryCatch, tryCatchSync, updateSignatureDictionary };
637
+ //# sourceMappingURL=chunk-J7DHGLW6.mjs.map
638
+ //# sourceMappingURL=chunk-J7DHGLW6.mjs.map