@solana/react-hooks 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1333 @@
1
+ 'use strict';
2
+
3
+ var client = require('@solana/client');
4
+ var react = require('react');
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+ var useSWR = require('swr');
7
+ var zustand = require('zustand');
8
+ var kit = require('@solana/kit');
9
+ var addresses = require('@solana/addresses');
10
+ var errors$1 = require('@solana/errors');
11
+ var promises = require('@solana/promises');
12
+ var transactionMessages = require('@solana/transaction-messages');
13
+ var transactions = require('@solana/transactions');
14
+ var walletStandardFeatures = require('@solana/wallet-standard-features');
15
+ var errors = require('@wallet-standard/errors');
16
+ var ui = require('@wallet-standard/ui');
17
+ var uiRegistry = require('@wallet-standard/ui-registry');
18
+
19
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
20
+
21
+ var useSWR__default = /*#__PURE__*/_interopDefault(useSWR);
22
+
23
+ var __defProp = Object.defineProperty;
24
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
25
+ var SolanaClientContext = react.createContext(null);
26
+ function SolanaClientProvider({ children, client: providedClient, config }) {
27
+ const client$1 = react.useMemo(() => {
28
+ if (providedClient) {
29
+ return providedClient;
30
+ }
31
+ if (!config) {
32
+ throw new Error("SolanaClientProvider requires either a `client` or `config` prop.");
33
+ }
34
+ return client.createClient(config);
35
+ }, [config, providedClient]);
36
+ react.useEffect(() => {
37
+ if (providedClient) {
38
+ return;
39
+ }
40
+ return () => {
41
+ client$1.destroy();
42
+ };
43
+ }, [client$1, providedClient]);
44
+ return /* @__PURE__ */ jsxRuntime.jsx(SolanaClientContext.Provider, { value: client$1, children });
45
+ }
46
+ __name(SolanaClientProvider, "SolanaClientProvider");
47
+ function useSolanaClient() {
48
+ const client = react.useContext(SolanaClientContext);
49
+ if (!client) {
50
+ throw new Error("useSolanaClient must be used within a SolanaClientProvider.");
51
+ }
52
+ return client;
53
+ }
54
+ __name(useSolanaClient, "useSolanaClient");
55
+ var QuerySuspenseContext = react.createContext(void 0);
56
+ function useQuerySuspensePreference() {
57
+ return react.useContext(QuerySuspenseContext);
58
+ }
59
+ __name(useQuerySuspensePreference, "useQuerySuspensePreference");
60
+ var identitySelector = /* @__PURE__ */ __name((state) => state, "identitySelector");
61
+ function useClientStore(selector) {
62
+ const client = useSolanaClient();
63
+ const appliedSelector = selector ?? identitySelector;
64
+ const slice = zustand.useStore(client.store, appliedSelector);
65
+ return selector ? slice : slice;
66
+ }
67
+ __name(useClientStore, "useClientStore");
68
+
69
+ // src/query.ts
70
+ var QUERY_NAMESPACE = "@solana/react-hooks";
71
+ function useSolanaRpcQuery(scope, args, fetcher, options = {}) {
72
+ const client = useSolanaClient();
73
+ const cluster = useClientStore((state) => state.cluster);
74
+ const { disabled = false, ...restOptions } = options;
75
+ const providerSuspensePreference = useQuerySuspensePreference();
76
+ const suspenseEnabled = !disabled && Boolean(providerSuspensePreference);
77
+ const swrOptions = {
78
+ ...restOptions,
79
+ suspense: suspenseEnabled
80
+ };
81
+ const key = react.useMemo(() => {
82
+ if (disabled) {
83
+ return null;
84
+ }
85
+ return [QUERY_NAMESPACE, scope, cluster.endpoint, cluster.commitment, ...args];
86
+ }, [cluster.commitment, cluster.endpoint, args, scope, disabled]);
87
+ const swr = useSWR__default.default(key, () => fetcher(client), swrOptions);
88
+ const [dataUpdatedAt, setDataUpdatedAt] = react.useState(
89
+ () => swr.data !== void 0 ? Date.now() : void 0
90
+ );
91
+ react.useEffect(() => {
92
+ if (swr.data !== void 0) {
93
+ setDataUpdatedAt(Date.now());
94
+ }
95
+ }, [swr.data]);
96
+ const status = swr.error ? "error" : swr.isLoading ? "loading" : swr.data !== void 0 ? "success" : "idle";
97
+ const refresh = react.useCallback(() => swr.mutate(void 0, { revalidate: true }), [swr.mutate]);
98
+ return {
99
+ data: swr.data,
100
+ dataUpdatedAt,
101
+ error: swr.error ?? null,
102
+ isError: status === "error",
103
+ isLoading: swr.isLoading,
104
+ isSuccess: status === "success",
105
+ isValidating: swr.isValidating,
106
+ mutate: swr.mutate,
107
+ refresh,
108
+ status
109
+ };
110
+ }
111
+ __name(useSolanaRpcQuery, "useSolanaRpcQuery");
112
+ var DEFAULT_BLOCKHASH_REFRESH_INTERVAL = 3e4;
113
+ function useLatestBlockhash(options) {
114
+ const { commitment, minContextSlot, refreshInterval = DEFAULT_BLOCKHASH_REFRESH_INTERVAL, ...rest } = options ?? {};
115
+ const normalizedMinContextSlot = react.useMemo(() => {
116
+ if (minContextSlot === void 0) {
117
+ return void 0;
118
+ }
119
+ return typeof minContextSlot === "bigint" ? minContextSlot : BigInt(Math.floor(minContextSlot));
120
+ }, [minContextSlot]);
121
+ const keyArgs = react.useMemo(
122
+ () => [commitment ?? null, normalizedMinContextSlot ?? null],
123
+ [commitment, normalizedMinContextSlot]
124
+ );
125
+ const fetcher = react.useCallback(
126
+ async (client) => {
127
+ const fallbackCommitment = commitment ?? client.store.getState().cluster.commitment;
128
+ const plan = client.runtime.rpc.getLatestBlockhash({
129
+ commitment: fallbackCommitment,
130
+ minContextSlot: normalizedMinContextSlot
131
+ });
132
+ return plan.send({ abortSignal: AbortSignal.timeout(15e3) });
133
+ },
134
+ [commitment, normalizedMinContextSlot]
135
+ );
136
+ const query = useSolanaRpcQuery("latestBlockhash", keyArgs, fetcher, {
137
+ refreshInterval,
138
+ ...rest
139
+ });
140
+ return {
141
+ ...query,
142
+ blockhash: query.data?.value.blockhash ?? null,
143
+ contextSlot: query.data?.context.slot,
144
+ lastValidBlockHeight: query.data?.value.lastValidBlockHeight ?? null
145
+ };
146
+ }
147
+ __name(useLatestBlockhash, "useLatestBlockhash");
148
+ function useProgramAccounts(programAddress, options) {
149
+ const { commitment, config, ...queryOptions } = options ?? {};
150
+ const { disabled: disabledOption, ...restQueryOptions } = queryOptions;
151
+ const address2 = react.useMemo(() => programAddress ? client.toAddress(programAddress) : void 0, [programAddress]);
152
+ const addressKey = react.useMemo(() => address2 ? client.toAddressString(address2) : null, [address2]);
153
+ const configKey = react.useMemo(() => client.stableStringify(config ?? null), [config]);
154
+ const fetcher = react.useCallback(
155
+ async (client) => {
156
+ if (!address2) {
157
+ throw new Error("Provide a program address before querying program accounts.");
158
+ }
159
+ const fallbackCommitment = commitment ?? config?.commitment ?? client.store.getState().cluster.commitment;
160
+ const mergedConfig = {
161
+ ...config ?? {},
162
+ commitment: fallbackCommitment
163
+ };
164
+ const plan = client.runtime.rpc.getProgramAccounts(address2, mergedConfig);
165
+ return plan.send({ abortSignal: AbortSignal.timeout(2e4) });
166
+ },
167
+ [address2, commitment, config]
168
+ );
169
+ const disabled = disabledOption ?? !address2;
170
+ const query = useSolanaRpcQuery("programAccounts", [addressKey, configKey], fetcher, {
171
+ ...restQueryOptions,
172
+ disabled
173
+ });
174
+ return {
175
+ ...query,
176
+ accounts: query.data ?? []
177
+ };
178
+ }
179
+ __name(useProgramAccounts, "useProgramAccounts");
180
+ function useSimulateTransaction(transaction, options) {
181
+ const { commitment, config, refreshInterval, ...rest } = options ?? {};
182
+ const { disabled: disabledOption, revalidateIfStale, revalidateOnFocus, ...queryOptions } = rest;
183
+ const wire = react.useMemo(() => {
184
+ if (!transaction) {
185
+ return null;
186
+ }
187
+ if (typeof transaction === "string") {
188
+ return transaction;
189
+ }
190
+ return kit.getBase64EncodedWireTransaction(transaction);
191
+ }, [transaction]);
192
+ const configKey = react.useMemo(() => client.stableStringify(config ?? null), [config]);
193
+ const fetcher = react.useCallback(
194
+ async (client) => {
195
+ if (!wire) {
196
+ throw new Error("Provide a transaction payload before simulating.");
197
+ }
198
+ const resolvedConfig = {
199
+ ...config ?? {},
200
+ commitment: commitment ?? config?.commitment ?? client.store.getState().cluster.commitment
201
+ };
202
+ const plan = client.runtime.rpc.simulateTransaction(wire, resolvedConfig);
203
+ return plan.send({ abortSignal: AbortSignal.timeout(2e4) });
204
+ },
205
+ [commitment, config, wire]
206
+ );
207
+ const disabled = disabledOption ?? !wire;
208
+ const query = useSolanaRpcQuery("simulateTransaction", [wire, configKey], fetcher, {
209
+ ...queryOptions,
210
+ refreshInterval,
211
+ disabled,
212
+ revalidateIfStale: revalidateIfStale ?? false,
213
+ revalidateOnFocus: revalidateOnFocus ?? false
214
+ });
215
+ return {
216
+ ...query,
217
+ logs: query.data?.value.logs ?? []
218
+ };
219
+ }
220
+ __name(useSimulateTransaction, "useSimulateTransaction");
221
+
222
+ // src/hooks.ts
223
+ function createClusterSelector() {
224
+ return (state) => state.cluster;
225
+ }
226
+ __name(createClusterSelector, "createClusterSelector");
227
+ function createClusterStatusSelector() {
228
+ return (state) => state.cluster.status;
229
+ }
230
+ __name(createClusterStatusSelector, "createClusterStatusSelector");
231
+ function createWalletSelector() {
232
+ return (state) => state.wallet;
233
+ }
234
+ __name(createWalletSelector, "createWalletSelector");
235
+ function createAccountSelector(key) {
236
+ return (state) => key ? state.accounts[key] : void 0;
237
+ }
238
+ __name(createAccountSelector, "createAccountSelector");
239
+ function useClusterState() {
240
+ const selector = react.useMemo(createClusterSelector, []);
241
+ return useClientStore(selector);
242
+ }
243
+ __name(useClusterState, "useClusterState");
244
+ function useClusterStatus() {
245
+ const selector = react.useMemo(createClusterStatusSelector, []);
246
+ return useClientStore(selector);
247
+ }
248
+ __name(useClusterStatus, "useClusterStatus");
249
+ function useWallet() {
250
+ const selector = react.useMemo(createWalletSelector, []);
251
+ return useClientStore(selector);
252
+ }
253
+ __name(useWallet, "useWallet");
254
+ function useWalletSession() {
255
+ const wallet = useWallet();
256
+ if (wallet.status === "connected") {
257
+ return wallet.session;
258
+ }
259
+ return void 0;
260
+ }
261
+ __name(useWalletSession, "useWalletSession");
262
+ function useWalletActions() {
263
+ const client = useSolanaClient();
264
+ return client.actions;
265
+ }
266
+ __name(useWalletActions, "useWalletActions");
267
+ function useConnectWallet() {
268
+ const client = useSolanaClient();
269
+ return react.useCallback(
270
+ (connectorId, options) => client.actions.connectWallet(connectorId, options),
271
+ [client]
272
+ );
273
+ }
274
+ __name(useConnectWallet, "useConnectWallet");
275
+ function useDisconnectWallet() {
276
+ const client = useSolanaClient();
277
+ return react.useCallback(() => client.actions.disconnectWallet(), [client]);
278
+ }
279
+ __name(useDisconnectWallet, "useDisconnectWallet");
280
+ function useSolTransfer() {
281
+ const client$1 = useSolanaClient();
282
+ const session = useWalletSession();
283
+ const helper = client$1.solTransfer;
284
+ const sessionRef = react.useRef(session);
285
+ react.useEffect(() => {
286
+ sessionRef.current = session;
287
+ }, [session]);
288
+ const controller = react.useMemo(
289
+ () => client.createSolTransferController({
290
+ authorityProvider: /* @__PURE__ */ __name(() => sessionRef.current, "authorityProvider"),
291
+ helper
292
+ }),
293
+ [helper]
294
+ );
295
+ const state = react.useSyncExternalStore(
296
+ controller.subscribe,
297
+ controller.getState,
298
+ controller.getState
299
+ );
300
+ const send = react.useCallback(
301
+ (config, options) => controller.send(config, options),
302
+ [controller]
303
+ );
304
+ return {
305
+ error: state.error ?? null,
306
+ helper,
307
+ isSending: state.status === "loading",
308
+ reset: controller.reset,
309
+ send,
310
+ signature: state.data ?? null,
311
+ status: state.status
312
+ };
313
+ }
314
+ __name(useSolTransfer, "useSolTransfer");
315
+ function useSplToken(mint, options = {}) {
316
+ const client$1 = useSolanaClient();
317
+ const session = useWalletSession();
318
+ const normalizedMint = react.useMemo(() => String(mint), [mint]);
319
+ const helperConfig = react.useMemo(
320
+ () => ({
321
+ commitment: options.commitment,
322
+ mint: normalizedMint,
323
+ ...options.config ?? {}
324
+ }),
325
+ [normalizedMint, options.commitment, options.config]
326
+ );
327
+ const helper = react.useMemo(() => client$1.splToken(helperConfig), [client$1, helperConfig]);
328
+ const ownerRaw = options.owner ?? session?.account.address;
329
+ const owner = react.useMemo(() => ownerRaw ? String(ownerRaw) : null, [ownerRaw]);
330
+ const balanceKey = owner ? ["spl-balance", normalizedMint, owner, options.commitment ?? null] : null;
331
+ const fetchBalance = react.useCallback(() => {
332
+ if (!owner) {
333
+ throw new Error("Unable to fetch SPL balance without an owner.");
334
+ }
335
+ return helper.fetchBalance(owner, options.commitment);
336
+ }, [helper, owner, options.commitment]);
337
+ const { data, error, isLoading, isValidating, mutate } = useSWR__default.default(balanceKey, fetchBalance, {
338
+ revalidateOnFocus: options.revalidateOnFocus ?? false
339
+ });
340
+ const sessionRef = react.useRef(session);
341
+ react.useEffect(() => {
342
+ sessionRef.current = session;
343
+ }, [session]);
344
+ const ownerRef = react.useRef(owner);
345
+ react.useEffect(() => {
346
+ ownerRef.current = owner;
347
+ }, [owner]);
348
+ const controller = react.useMemo(
349
+ () => client.createSplTransferController({
350
+ authorityProvider: /* @__PURE__ */ __name(() => sessionRef.current ?? void 0, "authorityProvider"),
351
+ helper,
352
+ sourceOwnerProvider: /* @__PURE__ */ __name(() => ownerRef.current ?? void 0, "sourceOwnerProvider")
353
+ }),
354
+ [helper]
355
+ );
356
+ const sendState = react.useSyncExternalStore(
357
+ controller.subscribe,
358
+ controller.getState,
359
+ controller.getState
360
+ );
361
+ const refresh = react.useCallback(() => {
362
+ if (!owner) {
363
+ return Promise.resolve(void 0);
364
+ }
365
+ return mutate(() => helper.fetchBalance(owner, options.commitment), { revalidate: false });
366
+ }, [helper, mutate, owner, options.commitment]);
367
+ const send = react.useCallback(
368
+ async (config, sendOptions) => {
369
+ const signature = await controller.send(config, sendOptions);
370
+ if (owner) {
371
+ await mutate(() => helper.fetchBalance(owner, options.commitment), { revalidate: false });
372
+ }
373
+ return signature;
374
+ },
375
+ [controller, helper, mutate, options.commitment, owner]
376
+ );
377
+ const resetSend = react.useCallback(() => {
378
+ controller.reset();
379
+ }, [controller]);
380
+ const status = owner === null ? "disconnected" : error ? "error" : isLoading && !data ? "loading" : "ready";
381
+ return {
382
+ balance: data ?? null,
383
+ error: error ?? null,
384
+ helper,
385
+ isFetching: Boolean(owner) && (isLoading || isValidating),
386
+ isSending: sendState.status === "loading",
387
+ owner,
388
+ refresh,
389
+ refreshing: Boolean(owner) && isValidating,
390
+ resetSend,
391
+ send,
392
+ sendError: sendState.error ?? null,
393
+ sendSignature: sendState.data ?? null,
394
+ sendStatus: sendState.status,
395
+ status
396
+ };
397
+ }
398
+ __name(useSplToken, "useSplToken");
399
+ function useAccount(addressLike, options = {}) {
400
+ const client$1 = useSolanaClient();
401
+ const shouldSkip = options.skip ?? !addressLike;
402
+ const address2 = react.useMemo(() => {
403
+ if (shouldSkip || !addressLike) {
404
+ return void 0;
405
+ }
406
+ return client.toAddress(addressLike);
407
+ }, [addressLike, shouldSkip]);
408
+ const accountKey = react.useMemo(() => address2?.toString(), [address2]);
409
+ const selector = react.useMemo(() => createAccountSelector(accountKey), [accountKey]);
410
+ const account = useClientStore(selector);
411
+ react.useEffect(() => {
412
+ if (!address2) {
413
+ return;
414
+ }
415
+ const commitment = options.commitment;
416
+ if (options.fetch !== false) {
417
+ void client$1.actions.fetchAccount(address2, commitment).catch(() => void 0);
418
+ }
419
+ if (options.watch) {
420
+ const subscription = client$1.watchers.watchAccount({ address: address2, commitment }, () => void 0);
421
+ return () => {
422
+ subscription.abort();
423
+ };
424
+ }
425
+ return void 0;
426
+ }, [address2, client$1, options.commitment, options.fetch, options.watch]);
427
+ return account;
428
+ }
429
+ __name(useAccount, "useAccount");
430
+ function useBalance(addressLike, options = {}) {
431
+ const mergedOptions = react.useMemo(
432
+ () => ({
433
+ commitment: options.commitment,
434
+ fetch: options.fetch ?? true,
435
+ skip: options.skip,
436
+ watch: options.watch ?? true
437
+ }),
438
+ [options.commitment, options.fetch, options.skip, options.watch]
439
+ );
440
+ const client$1 = useSolanaClient();
441
+ const shouldSkip = mergedOptions.skip ?? !addressLike;
442
+ const address2 = react.useMemo(() => {
443
+ if (shouldSkip || !addressLike) {
444
+ return void 0;
445
+ }
446
+ return client.toAddress(addressLike);
447
+ }, [addressLike, shouldSkip]);
448
+ const accountKey = react.useMemo(() => address2?.toString(), [address2]);
449
+ const selector = react.useMemo(() => createAccountSelector(accountKey), [accountKey]);
450
+ const account = useClientStore(selector);
451
+ react.useEffect(() => {
452
+ if (!address2) {
453
+ return;
454
+ }
455
+ const commitment = mergedOptions.commitment;
456
+ if (mergedOptions.fetch !== false) {
457
+ void client$1.actions.fetchBalance(address2, commitment).catch(() => void 0);
458
+ }
459
+ if (mergedOptions.watch) {
460
+ const watcher = client$1.watchers.watchBalance({ address: address2, commitment }, () => void 0);
461
+ return () => {
462
+ watcher.abort();
463
+ };
464
+ }
465
+ return void 0;
466
+ }, [address2, client$1, mergedOptions.commitment, mergedOptions.fetch, mergedOptions.watch]);
467
+ const lamports = account?.lamports ?? null;
468
+ const fetching = account?.fetching ?? false;
469
+ const slot = account?.slot;
470
+ const error = account?.error;
471
+ return react.useMemo(
472
+ () => ({
473
+ account,
474
+ error,
475
+ fetching,
476
+ lamports,
477
+ slot
478
+ }),
479
+ [account, error, fetching, lamports, slot]
480
+ );
481
+ }
482
+ __name(useBalance, "useBalance");
483
+ function useWalletStandardConnectors(options) {
484
+ const overrides = options?.overrides;
485
+ const memoisedOptions = react.useMemo(() => overrides ? { overrides } : void 0, [overrides]);
486
+ const [connectors, setConnectors] = react.useState(
487
+ () => client.getWalletStandardConnectors(memoisedOptions ?? {})
488
+ );
489
+ react.useEffect(() => {
490
+ setConnectors(client.getWalletStandardConnectors(memoisedOptions ?? {}));
491
+ const unwatch = client.watchWalletStandardConnectors(setConnectors, memoisedOptions ?? {});
492
+ return () => {
493
+ unwatch();
494
+ };
495
+ }, [memoisedOptions]);
496
+ return connectors;
497
+ }
498
+ __name(useWalletStandardConnectors, "useWalletStandardConnectors");
499
+ function useTransactionPool(config = {}) {
500
+ const initialInstructions = react.useMemo(
501
+ () => config.instructions ?? [],
502
+ [config.instructions]
503
+ );
504
+ const client$1 = useSolanaClient();
505
+ const helper = client$1.helpers.transaction;
506
+ const blockhashMaxAgeMs = config.latestBlockhash?.refreshInterval ?? 3e4;
507
+ const controller = react.useMemo(
508
+ () => client.createTransactionPoolController({
509
+ blockhashMaxAgeMs,
510
+ helper,
511
+ initialInstructions
512
+ }),
513
+ [blockhashMaxAgeMs, helper, initialInstructions]
514
+ );
515
+ const latestBlockhash = useLatestBlockhash(config.latestBlockhash);
516
+ react.useEffect(() => {
517
+ const value = latestBlockhash.data?.value;
518
+ if (!value) {
519
+ controller.setLatestBlockhashCache(void 0);
520
+ return;
521
+ }
522
+ const cache = {
523
+ updatedAt: latestBlockhash.dataUpdatedAt ?? Date.now(),
524
+ value
525
+ };
526
+ controller.setLatestBlockhashCache(cache);
527
+ }, [controller, latestBlockhash.data, latestBlockhash.dataUpdatedAt]);
528
+ const instructions = react.useSyncExternalStore(
529
+ controller.subscribeInstructions,
530
+ controller.getInstructions,
531
+ controller.getInstructions
532
+ );
533
+ const prepared = react.useSyncExternalStore(
534
+ controller.subscribePrepared,
535
+ controller.getPrepared,
536
+ controller.getPrepared
537
+ );
538
+ const prepareState = react.useSyncExternalStore(
539
+ controller.subscribePrepareState,
540
+ controller.getPrepareState,
541
+ controller.getPrepareState
542
+ );
543
+ const sendState = react.useSyncExternalStore(
544
+ controller.subscribeSendState,
545
+ controller.getSendState,
546
+ controller.getSendState
547
+ );
548
+ return {
549
+ addInstruction: controller.addInstruction,
550
+ addInstructions: controller.addInstructions,
551
+ clearInstructions: controller.clearInstructions,
552
+ instructions,
553
+ isPreparing: prepareState.status === "loading",
554
+ isSending: sendState.status === "loading",
555
+ prepared,
556
+ prepare: controller.prepare,
557
+ prepareError: prepareState.error ?? null,
558
+ prepareStatus: prepareState.status,
559
+ removeInstruction: controller.removeInstruction,
560
+ replaceInstructions: controller.replaceInstructions,
561
+ reset: controller.reset,
562
+ send: controller.send,
563
+ sendError: sendState.error ?? null,
564
+ sendSignature: sendState.data ?? null,
565
+ sendStatus: sendState.status,
566
+ prepareAndSend: controller.prepareAndSend,
567
+ sign: controller.sign,
568
+ toWire: controller.toWire,
569
+ latestBlockhash
570
+ };
571
+ }
572
+ __name(useTransactionPool, "useTransactionPool");
573
+ function useSendTransaction() {
574
+ const client$1 = useSolanaClient();
575
+ const helper = client$1.transaction;
576
+ const session = useWalletSession();
577
+ const [state, setState] = react.useState(
578
+ () => client.createInitialAsyncState()
579
+ );
580
+ const execute = react.useCallback(
581
+ async (operation) => {
582
+ setState(client.createAsyncState("loading"));
583
+ try {
584
+ const signature = await operation();
585
+ setState(client.createAsyncState("success", { data: signature }));
586
+ return signature;
587
+ } catch (error) {
588
+ setState(client.createAsyncState("error", { error }));
589
+ throw error;
590
+ }
591
+ },
592
+ []
593
+ );
594
+ const ensureAuthority = react.useCallback(
595
+ (request) => {
596
+ if (request.authority) {
597
+ return request;
598
+ }
599
+ if (!session) {
600
+ throw new Error("Connect a wallet or supply an `authority` before sending transactions.");
601
+ }
602
+ return { ...request, authority: session };
603
+ },
604
+ [session]
605
+ );
606
+ const send = react.useCallback(
607
+ async (request, options) => {
608
+ const normalizedRequest = ensureAuthority(request);
609
+ return execute(() => helper.prepareAndSend(normalizedRequest, options));
610
+ },
611
+ [ensureAuthority, execute, helper]
612
+ );
613
+ const sendPrepared = react.useCallback(
614
+ async (prepared, options) => execute(() => helper.send(prepared, options)),
615
+ [execute, helper]
616
+ );
617
+ const reset = react.useCallback(() => {
618
+ setState(client.createInitialAsyncState());
619
+ }, []);
620
+ return {
621
+ error: state.error ?? null,
622
+ isSending: state.status === "loading",
623
+ reset,
624
+ send,
625
+ sendPrepared,
626
+ signature: state.data ?? null,
627
+ status: state.status
628
+ };
629
+ }
630
+ __name(useSendTransaction, "useSendTransaction");
631
+ function useSignatureStatus(signatureInput, options = {}) {
632
+ const { config, ...queryOptions } = options;
633
+ const signature = react.useMemo(() => client.normalizeSignature(signatureInput), [signatureInput]);
634
+ const signatureKey = signature?.toString() ?? null;
635
+ const configKey = react.useMemo(() => JSON.stringify(config ?? null), [config]);
636
+ const fetcher = react.useCallback(
637
+ async (client$1) => {
638
+ if (!signatureKey) {
639
+ throw new Error("Provide a signature before querying its status.");
640
+ }
641
+ if (!signature) {
642
+ throw new Error("Provide a signature before querying its status.");
643
+ }
644
+ const plan = client$1.runtime.rpc.getSignatureStatuses([signature], config);
645
+ const response = await plan.send({ abortSignal: AbortSignal.timeout(client.SIGNATURE_STATUS_TIMEOUT_MS) });
646
+ return response.value[0] ?? null;
647
+ },
648
+ [config, signature, signatureKey]
649
+ );
650
+ const disabled = queryOptions.disabled ?? !signatureKey;
651
+ const query = useSolanaRpcQuery(
652
+ "signatureStatus",
653
+ [signatureKey, configKey],
654
+ fetcher,
655
+ {
656
+ ...queryOptions,
657
+ disabled
658
+ }
659
+ );
660
+ const confirmationStatus = client.deriveConfirmationStatus(query.data ?? null);
661
+ return {
662
+ ...query,
663
+ confirmationStatus,
664
+ signatureStatus: query.data ?? null
665
+ };
666
+ }
667
+ __name(useSignatureStatus, "useSignatureStatus");
668
+ function useWaitForSignature(signatureInput, options = {}) {
669
+ const {
670
+ commitment = "confirmed",
671
+ disabled: disabledOption,
672
+ subscribe = true,
673
+ watchCommitment,
674
+ ...signatureStatusOptions
675
+ } = options;
676
+ const { refreshInterval, ...restStatusOptions } = signatureStatusOptions;
677
+ const subscribeCommitment = watchCommitment ?? commitment;
678
+ const client$1 = useSolanaClient();
679
+ const normalizedSignature = react.useMemo(() => client.normalizeSignature(signatureInput), [signatureInput]);
680
+ const disabled = disabledOption ?? !normalizedSignature;
681
+ const statusQuery = useSignatureStatus(signatureInput, {
682
+ ...restStatusOptions,
683
+ refreshInterval: refreshInterval ?? 2e3,
684
+ disabled
685
+ });
686
+ const [subscriptionSettled, setSubscriptionSettled] = react.useState(false);
687
+ react.useEffect(() => {
688
+ if (normalizedSignature === void 0) {
689
+ setSubscriptionSettled(false);
690
+ return;
691
+ }
692
+ setSubscriptionSettled(false);
693
+ }, [normalizedSignature]);
694
+ react.useEffect(() => {
695
+ if (!normalizedSignature || disabled || !subscribe) {
696
+ return;
697
+ }
698
+ const subscription = client$1.watchers.watchSignature(
699
+ {
700
+ commitment: subscribeCommitment,
701
+ enableReceivedNotification: true,
702
+ signature: normalizedSignature
703
+ },
704
+ () => {
705
+ setSubscriptionSettled(true);
706
+ }
707
+ );
708
+ return () => {
709
+ subscription.abort();
710
+ };
711
+ }, [client$1, disabled, normalizedSignature, subscribe, subscribeCommitment]);
712
+ const hasSignature = Boolean(normalizedSignature) && !disabled;
713
+ const signatureError = statusQuery.signatureStatus?.err ?? null;
714
+ const waitError = statusQuery.error ?? signatureError ?? null;
715
+ const meetsCommitment = client.confirmationMeetsCommitment(statusQuery.confirmationStatus, commitment);
716
+ const settled = subscriptionSettled || meetsCommitment;
717
+ let waitStatus = "idle";
718
+ if (!hasSignature) {
719
+ waitStatus = "idle";
720
+ } else if (waitError) {
721
+ waitStatus = "error";
722
+ } else if (settled) {
723
+ waitStatus = "success";
724
+ } else {
725
+ waitStatus = "waiting";
726
+ }
727
+ return {
728
+ ...statusQuery,
729
+ isError: waitStatus === "error",
730
+ isSuccess: waitStatus === "success",
731
+ isWaiting: waitStatus === "waiting",
732
+ waitError,
733
+ waitStatus
734
+ };
735
+ }
736
+ __name(useWaitForSignature, "useWaitForSignature");
737
+ var createCache = /* @__PURE__ */ __name(() => /* @__PURE__ */ new Map(), "createCache");
738
+ var DEFAULT_QUERY_CONFIG = Object.freeze({
739
+ dedupingInterval: 1e3,
740
+ focusThrottleInterval: 1e3,
741
+ provider: /* @__PURE__ */ __name(() => createCache(), "provider"),
742
+ revalidateOnFocus: false,
743
+ revalidateOnReconnect: true
744
+ });
745
+ function SolanaQueryProvider({
746
+ children,
747
+ config,
748
+ resetOnClusterChange = true,
749
+ suspense
750
+ }) {
751
+ const cluster = useClientStore((state) => state.cluster);
752
+ const cacheRegistryRef = react.useRef(/* @__PURE__ */ new Map());
753
+ const cacheKey = resetOnClusterChange ? `${cluster.endpoint}|${cluster.commitment}` : "global";
754
+ const cache = react.useMemo(() => {
755
+ const registry = cacheRegistryRef.current;
756
+ if (!resetOnClusterChange) {
757
+ const existing = registry.get("global");
758
+ if (existing) {
759
+ return existing;
760
+ }
761
+ const next2 = createCache();
762
+ registry.set("global", next2);
763
+ return next2;
764
+ }
765
+ const next = createCache();
766
+ registry.set(cacheKey, next);
767
+ return next;
768
+ }, [cacheKey, resetOnClusterChange]);
769
+ const value = react.useMemo(() => {
770
+ const base = {
771
+ ...DEFAULT_QUERY_CONFIG,
772
+ ...config
773
+ };
774
+ if (!config?.provider) {
775
+ base.provider = () => cache;
776
+ }
777
+ if (base.suspense === void 0 && suspense !== void 0) {
778
+ base.suspense = suspense;
779
+ }
780
+ return base;
781
+ }, [cache, config, suspense]);
782
+ return /* @__PURE__ */ jsxRuntime.jsx(QuerySuspenseContext.Provider, { value: suspense, children: /* @__PURE__ */ jsxRuntime.jsx(useSWR.SWRConfig, { value, children }) });
783
+ }
784
+ __name(SolanaQueryProvider, "SolanaQueryProvider");
785
+ function SolanaProvider({ children, client, config, query, walletPersistence }) {
786
+ const shouldIncludeQueryLayer = query !== false && query?.disabled !== true;
787
+ const queryProps = shouldIncludeQueryLayer && query ? query : {};
788
+ const persistenceConfig = walletPersistence === false ? void 0 : walletPersistence ?? {};
789
+ const content = shouldIncludeQueryLayer ? /* @__PURE__ */ jsxRuntime.jsx(
790
+ SolanaQueryProvider,
791
+ {
792
+ config: queryProps.config,
793
+ resetOnClusterChange: queryProps.resetOnClusterChange,
794
+ suspense: queryProps.suspense,
795
+ children
796
+ }
797
+ ) : children;
798
+ return /* @__PURE__ */ jsxRuntime.jsxs(SolanaClientProvider, { client, config, children: [
799
+ persistenceConfig ? /* @__PURE__ */ jsxRuntime.jsx(WalletPersistence, { ...persistenceConfig }) : null,
800
+ content
801
+ ] });
802
+ }
803
+ __name(SolanaProvider, "SolanaProvider");
804
+ var DEFAULT_STORAGE_KEY = "solana:last-connector";
805
+ function WalletPersistence({ autoConnect = true, storage, storageKey = DEFAULT_STORAGE_KEY }) {
806
+ const wallet = useWallet();
807
+ const connectWallet = useConnectWallet();
808
+ const client = useSolanaClient();
809
+ const storageRef = react.useRef(storage ?? getDefaultStorage());
810
+ const [hasAttemptedAutoConnect, setHasAttemptedAutoConnect] = react.useState(false);
811
+ const hasPersistedConnectorRef = react.useRef(false);
812
+ const clientRef = react.useRef(null);
813
+ react.useEffect(() => {
814
+ storageRef.current = storage ?? getDefaultStorage();
815
+ }, [storage]);
816
+ react.useEffect(() => {
817
+ if (clientRef.current !== client) {
818
+ clientRef.current = client;
819
+ setHasAttemptedAutoConnect(false);
820
+ }
821
+ }, [client]);
822
+ react.useEffect(() => {
823
+ const activeStorage = storageRef.current;
824
+ if (!activeStorage) return;
825
+ if ("connectorId" in wallet && wallet.connectorId) {
826
+ const connectorId = wallet.connectorId;
827
+ if (connectorId) {
828
+ safelyWrite(() => activeStorage.setItem(storageKey, connectorId));
829
+ hasPersistedConnectorRef.current = true;
830
+ return;
831
+ }
832
+ }
833
+ if (wallet.status === "disconnected" && hasPersistedConnectorRef.current) {
834
+ safelyWrite(() => activeStorage.removeItem(storageKey));
835
+ hasPersistedConnectorRef.current = false;
836
+ }
837
+ }, [storageKey, wallet]);
838
+ react.useEffect(() => {
839
+ if (!autoConnect || hasAttemptedAutoConnect) {
840
+ return;
841
+ }
842
+ if (wallet.status === "connected" || wallet.status === "connecting") {
843
+ setHasAttemptedAutoConnect(true);
844
+ return;
845
+ }
846
+ const activeStorage = storageRef.current;
847
+ if (!activeStorage) {
848
+ setHasAttemptedAutoConnect(true);
849
+ return;
850
+ }
851
+ let cancelled = false;
852
+ const connectorId = safelyRead(() => activeStorage.getItem(storageKey));
853
+ if (!connectorId) {
854
+ setHasAttemptedAutoConnect(true);
855
+ return;
856
+ }
857
+ const connector = client.connectors.get(connectorId);
858
+ if (!connector) {
859
+ return;
860
+ }
861
+ void (async () => {
862
+ try {
863
+ await connectWallet(connectorId, { autoConnect: true });
864
+ } catch {
865
+ } finally {
866
+ if (!cancelled) {
867
+ setHasAttemptedAutoConnect(true);
868
+ }
869
+ }
870
+ })();
871
+ return () => {
872
+ cancelled = true;
873
+ };
874
+ }, [autoConnect, client, connectWallet, hasAttemptedAutoConnect, storageKey, wallet.status]);
875
+ return null;
876
+ }
877
+ __name(WalletPersistence, "WalletPersistence");
878
+ function safelyRead(reader) {
879
+ try {
880
+ return reader();
881
+ } catch {
882
+ return null;
883
+ }
884
+ }
885
+ __name(safelyRead, "safelyRead");
886
+ function safelyWrite(writer) {
887
+ try {
888
+ writer();
889
+ } catch {
890
+ }
891
+ }
892
+ __name(safelyWrite, "safelyWrite");
893
+ function getDefaultStorage() {
894
+ if (typeof globalThis !== "object" || globalThis === null) {
895
+ return null;
896
+ }
897
+ const candidate = globalThis.localStorage;
898
+ if (!candidate) {
899
+ return null;
900
+ }
901
+ return candidate;
902
+ }
903
+ __name(getDefaultStorage, "getDefaultStorage");
904
+ function useWalletConnection(options = {}) {
905
+ const wallet = useWallet();
906
+ const connectWallet = useConnectWallet();
907
+ const disconnectWallet = useDisconnectWallet();
908
+ const discovered = useWalletStandardConnectors(options.discoveryOptions);
909
+ const connectors = options.connectors ?? discovered;
910
+ const connect = react.useCallback(
911
+ (connectorId, connectOptions) => connectWallet(connectorId, connectOptions),
912
+ [connectWallet]
913
+ );
914
+ const disconnect = react.useCallback(() => disconnectWallet(), [disconnectWallet]);
915
+ const state = react.useMemo(() => {
916
+ const connectorId = "connectorId" in wallet ? wallet.connectorId : void 0;
917
+ const session = wallet.status === "connected" ? wallet.session : void 0;
918
+ const error = wallet.status === "error" ? wallet.error ?? null : null;
919
+ return {
920
+ connect,
921
+ connected: wallet.status === "connected",
922
+ connecting: wallet.status === "connecting",
923
+ connectors,
924
+ connectorId,
925
+ disconnect,
926
+ error,
927
+ status: wallet.status,
928
+ wallet: session
929
+ };
930
+ }, [connect, connectors, disconnect, wallet]);
931
+ return state;
932
+ }
933
+ __name(useWalletConnection, "useWalletConnection");
934
+ function WalletConnectionManager({ children, connectors, discoveryOptions }) {
935
+ const state = useWalletConnection({ connectors, discoveryOptions });
936
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children(state) });
937
+ }
938
+ __name(WalletConnectionManager, "WalletConnectionManager");
939
+ function useWalletModalState(options = {}) {
940
+ const connection = useWalletConnection(options);
941
+ const [isOpen, setIsOpen] = react.useState(options.initialOpen ?? false);
942
+ const [selectedConnector, setSelectedConnector] = react.useState(null);
943
+ const closeOnConnect = options.closeOnConnect ?? true;
944
+ const open = react.useCallback(() => setIsOpen(true), []);
945
+ const close = react.useCallback(() => setIsOpen(false), []);
946
+ const toggle = react.useCallback(() => setIsOpen((value) => !value), []);
947
+ const select = react.useCallback((connectorId) => setSelectedConnector(connectorId), []);
948
+ const connect = react.useCallback(
949
+ async (connectorId, connectOptions) => {
950
+ await connection.connect(connectorId, connectOptions);
951
+ setSelectedConnector(connectorId);
952
+ if (closeOnConnect) {
953
+ setIsOpen(false);
954
+ }
955
+ },
956
+ [closeOnConnect, connection]
957
+ );
958
+ return {
959
+ ...connection,
960
+ close,
961
+ connect,
962
+ isOpen,
963
+ open,
964
+ selectedConnector,
965
+ select,
966
+ toggle
967
+ };
968
+ }
969
+ __name(useWalletModalState, "useWalletModalState");
970
+ function useSignAndSendTransaction(uiWalletAccount, chain) {
971
+ const signAndSendTransactions = useSignAndSendTransactions(uiWalletAccount, chain);
972
+ return react.useCallback(
973
+ async (input) => {
974
+ const [result] = await signAndSendTransactions(input);
975
+ return result;
976
+ },
977
+ [signAndSendTransactions]
978
+ );
979
+ }
980
+ __name(useSignAndSendTransaction, "useSignAndSendTransaction");
981
+ function useSignAndSendTransactions(uiWalletAccount, chain) {
982
+ if (!uiWalletAccount.chains.includes(chain)) {
983
+ throw new errors.WalletStandardError(errors.WALLET_STANDARD_ERROR__FEATURES__WALLET_ACCOUNT_CHAIN_UNSUPPORTED, {
984
+ address: uiWalletAccount.address,
985
+ chain,
986
+ featureName: walletStandardFeatures.SolanaSignAndSendTransaction,
987
+ supportedChains: [...uiWalletAccount.chains],
988
+ supportedFeatures: [...uiWalletAccount.features]
989
+ });
990
+ }
991
+ const signAndSendTransactionFeature = ui.getWalletAccountFeature(
992
+ uiWalletAccount,
993
+ walletStandardFeatures.SolanaSignAndSendTransaction
994
+ );
995
+ const account = uiRegistry.getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(uiWalletAccount);
996
+ return react.useCallback(
997
+ async (...inputs) => {
998
+ const inputsWithChainAndAccount = inputs.map(({ options, ...rest }) => {
999
+ const minContextSlot = options?.minContextSlot;
1000
+ return {
1001
+ ...rest,
1002
+ account,
1003
+ chain,
1004
+ ...minContextSlot != null ? {
1005
+ options: {
1006
+ minContextSlot: Number(minContextSlot)
1007
+ }
1008
+ } : null
1009
+ };
1010
+ });
1011
+ const results = await signAndSendTransactionFeature.signAndSendTransaction(...inputsWithChainAndAccount);
1012
+ return results;
1013
+ },
1014
+ [account, chain, signAndSendTransactionFeature]
1015
+ );
1016
+ }
1017
+ __name(useSignAndSendTransactions, "useSignAndSendTransactions");
1018
+ function useSignIn(uiWalletHandle) {
1019
+ const signIns = useSignIns(uiWalletHandle);
1020
+ return react.useCallback(
1021
+ async (input) => {
1022
+ const [result] = await signIns(input);
1023
+ return result;
1024
+ },
1025
+ [signIns]
1026
+ );
1027
+ }
1028
+ __name(useSignIn, "useSignIn");
1029
+ function useSignIns(uiWalletHandle) {
1030
+ let signMessageFeature;
1031
+ if ("address" in uiWalletHandle && typeof uiWalletHandle.address === "string") {
1032
+ uiRegistry.getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(uiWalletHandle);
1033
+ signMessageFeature = ui.getWalletAccountFeature(
1034
+ uiWalletHandle,
1035
+ walletStandardFeatures.SolanaSignIn
1036
+ );
1037
+ } else {
1038
+ signMessageFeature = ui.getWalletFeature(uiWalletHandle, walletStandardFeatures.SolanaSignIn);
1039
+ }
1040
+ const wallet = uiRegistry.getWalletForHandle_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(uiWalletHandle);
1041
+ return react.useCallback(
1042
+ async (...inputs) => {
1043
+ const inputsWithAddressAndChainId = inputs.map((input) => ({
1044
+ ...input,
1045
+ // Prioritize the `UiWalletAccount` address if it exists.
1046
+ ..."address" in uiWalletHandle ? { address: uiWalletHandle.address } : null
1047
+ }));
1048
+ const results = await signMessageFeature.signIn(...inputsWithAddressAndChainId);
1049
+ const resultsWithoutSignatureType = results.map(
1050
+ ({
1051
+ account,
1052
+ signatureType: _signatureType,
1053
+ // Solana signatures are always of type `ed25519` so drop this property.
1054
+ ...rest
1055
+ }) => ({
1056
+ ...rest,
1057
+ account: uiRegistry.getOrCreateUiWalletAccountForStandardWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(
1058
+ wallet,
1059
+ account
1060
+ )
1061
+ })
1062
+ );
1063
+ return resultsWithoutSignatureType;
1064
+ },
1065
+ [signMessageFeature, uiWalletHandle, wallet]
1066
+ );
1067
+ }
1068
+ __name(useSignIns, "useSignIns");
1069
+ function useSignMessage(...config) {
1070
+ const signMessages = useSignMessages(...config);
1071
+ return react.useCallback(
1072
+ async (input) => {
1073
+ const [result] = await signMessages(input);
1074
+ return result;
1075
+ },
1076
+ [signMessages]
1077
+ );
1078
+ }
1079
+ __name(useSignMessage, "useSignMessage");
1080
+ function useSignMessages(uiWalletAccount) {
1081
+ const signMessageFeature = ui.getWalletAccountFeature(
1082
+ uiWalletAccount,
1083
+ walletStandardFeatures.SolanaSignMessage
1084
+ );
1085
+ const account = uiRegistry.getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(uiWalletAccount);
1086
+ return react.useCallback(
1087
+ async (...inputs) => {
1088
+ const inputsWithAccount = inputs.map((input) => ({ ...input, account }));
1089
+ const results = await signMessageFeature.signMessage(...inputsWithAccount);
1090
+ const resultsWithoutSignatureType = results.map(
1091
+ ({
1092
+ signatureType: _signatureType,
1093
+ // Solana signatures are always of type `ed25519` so drop this property.
1094
+ ...rest
1095
+ }) => rest
1096
+ );
1097
+ return resultsWithoutSignatureType;
1098
+ },
1099
+ [signMessageFeature, account]
1100
+ );
1101
+ }
1102
+ __name(useSignMessages, "useSignMessages");
1103
+ function useSignTransaction(uiWalletAccount, chain) {
1104
+ const signTransactions = useSignTransactions(uiWalletAccount, chain);
1105
+ return react.useCallback(
1106
+ async (input) => {
1107
+ const [result] = await signTransactions(input);
1108
+ return result;
1109
+ },
1110
+ [signTransactions]
1111
+ );
1112
+ }
1113
+ __name(useSignTransaction, "useSignTransaction");
1114
+ function useSignTransactions(uiWalletAccount, chain) {
1115
+ if (!uiWalletAccount.chains.includes(chain)) {
1116
+ throw new errors.WalletStandardError(errors.WALLET_STANDARD_ERROR__FEATURES__WALLET_ACCOUNT_CHAIN_UNSUPPORTED, {
1117
+ address: uiWalletAccount.address,
1118
+ chain,
1119
+ featureName: walletStandardFeatures.SolanaSignAndSendTransaction,
1120
+ supportedChains: [...uiWalletAccount.chains],
1121
+ supportedFeatures: [...uiWalletAccount.features]
1122
+ });
1123
+ }
1124
+ const signTransactionFeature = ui.getWalletAccountFeature(
1125
+ uiWalletAccount,
1126
+ walletStandardFeatures.SolanaSignTransaction
1127
+ );
1128
+ const account = uiRegistry.getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(uiWalletAccount);
1129
+ return react.useCallback(
1130
+ async (...inputs) => {
1131
+ const inputsWithAccountAndChain = inputs.map(({ options, ...rest }) => {
1132
+ const minContextSlot = options?.minContextSlot;
1133
+ return {
1134
+ ...rest,
1135
+ account,
1136
+ chain,
1137
+ ...minContextSlot != null ? {
1138
+ options: {
1139
+ minContextSlot: Number(minContextSlot)
1140
+ }
1141
+ } : null
1142
+ };
1143
+ });
1144
+ const results = await signTransactionFeature.signTransaction(...inputsWithAccountAndChain);
1145
+ return results;
1146
+ },
1147
+ [signTransactionFeature, account, chain]
1148
+ );
1149
+ }
1150
+ __name(useSignTransactions, "useSignTransactions");
1151
+ function useWalletAccountMessageSigner(uiWalletAccount) {
1152
+ const signMessage = useSignMessage(uiWalletAccount);
1153
+ return react.useMemo(
1154
+ () => ({
1155
+ address: addresses.address(uiWalletAccount.address),
1156
+ async modifyAndSignMessages(messages, config) {
1157
+ config?.abortSignal?.throwIfAborted();
1158
+ if (messages.length > 1) {
1159
+ throw new errors$1.SolanaError(errors$1.SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED);
1160
+ }
1161
+ if (messages.length === 0) {
1162
+ return messages;
1163
+ }
1164
+ const { content: originalMessage, signatures: originalSignatureMap } = messages[0];
1165
+ const input = {
1166
+ message: originalMessage
1167
+ };
1168
+ const { signedMessage, signature } = await promises.getAbortablePromise(signMessage(input), config?.abortSignal);
1169
+ const messageWasModified = originalMessage.length !== signedMessage.length || originalMessage.some((originalByte, ii) => originalByte !== signedMessage[ii]);
1170
+ const originalSignature = originalSignatureMap[uiWalletAccount.address];
1171
+ const signatureIsNew = !originalSignature?.every((originalByte, ii) => originalByte === signature[ii]);
1172
+ if (!signatureIsNew && !messageWasModified) {
1173
+ return messages;
1174
+ }
1175
+ const nextSignatureMap = messageWasModified ? { [uiWalletAccount.address]: signature } : { ...originalSignatureMap, [uiWalletAccount.address]: signature };
1176
+ const outputMessages = Object.freeze([
1177
+ Object.freeze({
1178
+ content: signedMessage,
1179
+ signatures: Object.freeze(nextSignatureMap)
1180
+ })
1181
+ ]);
1182
+ return outputMessages;
1183
+ }
1184
+ }),
1185
+ [uiWalletAccount, signMessage]
1186
+ );
1187
+ }
1188
+ __name(useWalletAccountMessageSigner, "useWalletAccountMessageSigner");
1189
+ function useWalletAccountTransactionSigner(uiWalletAccount, chain) {
1190
+ const encoderRef = react.useRef(null);
1191
+ const signTransaction = useSignTransaction(uiWalletAccount, chain);
1192
+ return react.useMemo(
1193
+ () => ({
1194
+ address: addresses.address(uiWalletAccount.address),
1195
+ async modifyAndSignTransactions(transactions$1, config = {}) {
1196
+ const { abortSignal, ...options } = config;
1197
+ abortSignal?.throwIfAborted();
1198
+ let transactionCodec = encoderRef.current;
1199
+ if (!transactionCodec) {
1200
+ transactionCodec = transactions.getTransactionCodec();
1201
+ encoderRef.current = transactionCodec;
1202
+ }
1203
+ if (transactions$1.length > 1) {
1204
+ throw new errors$1.SolanaError(errors$1.SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED);
1205
+ }
1206
+ if (transactions$1.length === 0) {
1207
+ return transactions$1;
1208
+ }
1209
+ const [transaction] = transactions$1;
1210
+ const wireTransactionBytes = transactionCodec.encode(transaction);
1211
+ const inputWithOptions = {
1212
+ ...options,
1213
+ transaction: wireTransactionBytes
1214
+ };
1215
+ const { signedTransaction } = await promises.getAbortablePromise(signTransaction(inputWithOptions), abortSignal);
1216
+ const decodedSignedTransaction = transactionCodec.decode(
1217
+ signedTransaction
1218
+ );
1219
+ transactions.assertIsTransactionWithinSizeLimit(decodedSignedTransaction);
1220
+ const existingLifetime = "lifetimeConstraint" in transaction ? transaction.lifetimeConstraint : void 0;
1221
+ if (existingLifetime) {
1222
+ if (uint8ArraysEqual(decodedSignedTransaction.messageBytes, transaction.messageBytes)) {
1223
+ return Object.freeze([
1224
+ {
1225
+ ...decodedSignedTransaction,
1226
+ lifetimeConstraint: existingLifetime
1227
+ }
1228
+ ]);
1229
+ }
1230
+ const compiledTransactionMessage2 = transactionMessages.getCompiledTransactionMessageDecoder().decode(
1231
+ decodedSignedTransaction.messageBytes
1232
+ );
1233
+ const currentToken = "blockhash" in existingLifetime ? existingLifetime.blockhash : existingLifetime.nonce;
1234
+ if (compiledTransactionMessage2.lifetimeToken === currentToken) {
1235
+ return Object.freeze([
1236
+ {
1237
+ ...decodedSignedTransaction,
1238
+ lifetimeConstraint: existingLifetime
1239
+ }
1240
+ ]);
1241
+ }
1242
+ }
1243
+ const compiledTransactionMessage = transactionMessages.getCompiledTransactionMessageDecoder().decode(
1244
+ decodedSignedTransaction.messageBytes
1245
+ );
1246
+ const lifetimeConstraint = await transactions.getTransactionLifetimeConstraintFromCompiledTransactionMessage(compiledTransactionMessage);
1247
+ return Object.freeze([
1248
+ {
1249
+ ...decodedSignedTransaction,
1250
+ lifetimeConstraint
1251
+ }
1252
+ ]);
1253
+ }
1254
+ }),
1255
+ [uiWalletAccount.address, signTransaction]
1256
+ );
1257
+ }
1258
+ __name(useWalletAccountTransactionSigner, "useWalletAccountTransactionSigner");
1259
+ function uint8ArraysEqual(arr1, arr2) {
1260
+ return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
1261
+ }
1262
+ __name(uint8ArraysEqual, "uint8ArraysEqual");
1263
+ function useWalletAccountTransactionSendingSigner(uiWalletAccount, chain) {
1264
+ const encoderRef = react.useRef(null);
1265
+ const signAndSendTransaction = useSignAndSendTransaction(uiWalletAccount, chain);
1266
+ return react.useMemo(
1267
+ () => ({
1268
+ address: addresses.address(uiWalletAccount.address),
1269
+ async signAndSendTransactions(transactions$1, config = {}) {
1270
+ const { abortSignal, ...options } = config;
1271
+ abortSignal?.throwIfAborted();
1272
+ let transactionEncoder = encoderRef.current;
1273
+ if (!transactionEncoder) {
1274
+ transactionEncoder = transactions.getTransactionEncoder();
1275
+ encoderRef.current = transactionEncoder;
1276
+ }
1277
+ if (transactions$1.length > 1) {
1278
+ throw new errors$1.SolanaError(errors$1.SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED);
1279
+ }
1280
+ if (transactions$1.length === 0) {
1281
+ return [];
1282
+ }
1283
+ const [transaction] = transactions$1;
1284
+ const wireTransactionBytes = transactionEncoder.encode(transaction);
1285
+ const inputWithOptions = {
1286
+ ...options,
1287
+ transaction: wireTransactionBytes
1288
+ };
1289
+ const { signature } = await promises.getAbortablePromise(signAndSendTransaction(inputWithOptions), abortSignal);
1290
+ return Object.freeze([signature]);
1291
+ }
1292
+ }),
1293
+ [signAndSendTransaction, uiWalletAccount.address]
1294
+ );
1295
+ }
1296
+ __name(useWalletAccountTransactionSendingSigner, "useWalletAccountTransactionSendingSigner");
1297
+
1298
+ exports.SolanaClientProvider = SolanaClientProvider;
1299
+ exports.SolanaProvider = SolanaProvider;
1300
+ exports.SolanaQueryProvider = SolanaQueryProvider;
1301
+ exports.WalletConnectionManager = WalletConnectionManager;
1302
+ exports.useAccount = useAccount;
1303
+ exports.useBalance = useBalance;
1304
+ exports.useClientStore = useClientStore;
1305
+ exports.useClusterState = useClusterState;
1306
+ exports.useClusterStatus = useClusterStatus;
1307
+ exports.useConnectWallet = useConnectWallet;
1308
+ exports.useDisconnectWallet = useDisconnectWallet;
1309
+ exports.useLatestBlockhash = useLatestBlockhash;
1310
+ exports.useProgramAccounts = useProgramAccounts;
1311
+ exports.useSendTransaction = useSendTransaction;
1312
+ exports.useSignAndSendTransaction = useSignAndSendTransaction;
1313
+ exports.useSignIn = useSignIn;
1314
+ exports.useSignMessage = useSignMessage;
1315
+ exports.useSignTransaction = useSignTransaction;
1316
+ exports.useSignatureStatus = useSignatureStatus;
1317
+ exports.useSimulateTransaction = useSimulateTransaction;
1318
+ exports.useSolTransfer = useSolTransfer;
1319
+ exports.useSolanaClient = useSolanaClient;
1320
+ exports.useSplToken = useSplToken;
1321
+ exports.useTransactionPool = useTransactionPool;
1322
+ exports.useWaitForSignature = useWaitForSignature;
1323
+ exports.useWallet = useWallet;
1324
+ exports.useWalletAccountMessageSigner = useWalletAccountMessageSigner;
1325
+ exports.useWalletAccountTransactionSendingSigner = useWalletAccountTransactionSendingSigner;
1326
+ exports.useWalletAccountTransactionSigner = useWalletAccountTransactionSigner;
1327
+ exports.useWalletActions = useWalletActions;
1328
+ exports.useWalletConnection = useWalletConnection;
1329
+ exports.useWalletModalState = useWalletModalState;
1330
+ exports.useWalletSession = useWalletSession;
1331
+ exports.useWalletStandardConnectors = useWalletStandardConnectors;
1332
+ //# sourceMappingURL=index.node.cjs.map
1333
+ //# sourceMappingURL=index.node.cjs.map