@solana/client 1.1.2 → 1.1.4

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.
@@ -1,3721 +0,0 @@
1
- 'use strict';
2
-
3
- var kit = require('@solana/kit');
4
- var transactionConfirmation = require('@solana/transaction-confirmation');
5
- var addressLookupTable = require('@solana-program/address-lookup-table');
6
- var system = require('@solana-program/system');
7
- var codecsStrings = require('@solana/codecs-strings');
8
- var token = require('@solana-program/token');
9
- var stake = require('@solana-program/stake');
10
- var computeBudget = require('@solana-program/compute-budget');
11
- var vanilla = require('zustand/vanilla');
12
- var app = require('@wallet-standard/app');
13
- var features = require('@wallet-standard/features');
14
- var transactions = require('@solana/transactions');
15
- var walletStandardFeatures = require('@solana/wallet-standard-features');
16
-
17
- var __defProp = Object.defineProperty;
18
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
19
-
20
- // src/actions.ts
21
- function connectWallet(client, params) {
22
- return client.actions.connectWallet(params.connectorId, params.options);
23
- }
24
- __name(connectWallet, "connectWallet");
25
- function disconnectWallet(client, _params) {
26
- return client.actions.disconnectWallet();
27
- }
28
- __name(disconnectWallet, "disconnectWallet");
29
- function fetchAccount(client, params) {
30
- return client.actions.fetchAccount(params.address, params.commitment);
31
- }
32
- __name(fetchAccount, "fetchAccount");
33
- function fetchBalance(client, params) {
34
- return client.actions.fetchBalance(params.address, params.commitment);
35
- }
36
- __name(fetchBalance, "fetchBalance");
37
- function fetchLookupTable(client, params) {
38
- return client.actions.fetchLookupTable(params.address, params.commitment);
39
- }
40
- __name(fetchLookupTable, "fetchLookupTable");
41
- function fetchLookupTables(client, params) {
42
- return client.actions.fetchLookupTables(params.addresses, params.commitment);
43
- }
44
- __name(fetchLookupTables, "fetchLookupTables");
45
- function fetchNonceAccount(client, params) {
46
- return client.actions.fetchNonceAccount(params.address, params.commitment);
47
- }
48
- __name(fetchNonceAccount, "fetchNonceAccount");
49
- function requestAirdrop(client, params) {
50
- return client.actions.requestAirdrop(params.address, params.lamports);
51
- }
52
- __name(requestAirdrop, "requestAirdrop");
53
- function sendTransaction(client, params) {
54
- return client.actions.sendTransaction(params.transaction, params.commitment);
55
- }
56
- __name(sendTransaction, "sendTransaction");
57
- function setCluster(client, params) {
58
- return client.actions.setCluster(params.endpoint, params.config);
59
- }
60
- __name(setCluster, "setCluster");
61
-
62
- // src/utils.ts
63
- function deepFreeze(value) {
64
- if (typeof value !== "object" || value === null) {
65
- return value;
66
- }
67
- const objectValue = value;
68
- for (const key of Reflect.ownKeys(objectValue)) {
69
- const property = objectValue[key];
70
- deepFreeze(property);
71
- }
72
- return Object.freeze(value);
73
- }
74
- __name(deepFreeze, "deepFreeze");
75
- function now() {
76
- return Date.now();
77
- }
78
- __name(now, "now");
79
- function toErrorMessage(error) {
80
- if (error instanceof Error) {
81
- return error.message;
82
- }
83
- if (typeof error === "string") {
84
- return error;
85
- }
86
- try {
87
- return JSON.stringify(error);
88
- } catch {
89
- return String(error);
90
- }
91
- }
92
- __name(toErrorMessage, "toErrorMessage");
93
-
94
- // src/logging/logger.ts
95
- function createLogger(logger) {
96
- if (logger) {
97
- return logger;
98
- }
99
- return ({ data, level, message }) => {
100
- const payload = data ? { ...data } : {};
101
- switch (level) {
102
- case "error":
103
- console.error(`[react-core] ${message}`, payload);
104
- break;
105
- case "warn":
106
- console.warn(`[react-core] ${message}`, payload);
107
- break;
108
- case "info":
109
- console.info(`[react-core] ${message}`, payload);
110
- break;
111
- default:
112
- console.debug(`[react-core] ${message}`, payload);
113
- }
114
- };
115
- }
116
- __name(createLogger, "createLogger");
117
- function formatError(error) {
118
- return {
119
- error,
120
- message: toErrorMessage(error)
121
- };
122
- }
123
- __name(formatError, "formatError");
124
- function createChainedAbortController(parent) {
125
- const controller = new AbortController();
126
- if (!parent) {
127
- return controller;
128
- }
129
- if (parent.aborted) {
130
- controller.abort(parent.reason);
131
- return controller;
132
- }
133
- const onAbort = /* @__PURE__ */ __name(() => {
134
- controller.abort(parent.reason);
135
- parent.removeEventListener("abort", onAbort);
136
- }, "onAbort");
137
- parent.addEventListener("abort", onAbort, { once: true });
138
- return controller;
139
- }
140
- __name(createChainedAbortController, "createChainedAbortController");
141
- function toBigint(value) {
142
- if (value === void 0) {
143
- return void 0;
144
- }
145
- return typeof value === "bigint" ? value : BigInt(Math.floor(value));
146
- }
147
- __name(toBigint, "toBigint");
148
- var DEFAULT_SIMULATION_CONFIG = Object.freeze({
149
- encoding: "base64",
150
- replaceRecentBlockhash: true,
151
- sigVerify: false
152
- });
153
- function createSolanaRpcClient(config) {
154
- const endpoint = config.endpoint;
155
- const websocketEndpoint = config.websocketEndpoint ?? endpoint;
156
- const commitment = config.commitment ?? "confirmed";
157
- const rpc = kit.createSolanaRpc(endpoint, config.rpcConfig);
158
- const rpcSubscriptions = kit.createSolanaRpcSubscriptions(websocketEndpoint, config.rpcSubscriptionsConfig);
159
- async function sendAndConfirmTransaction(transaction, options = {}) {
160
- const abortController = createChainedAbortController(options.abortSignal);
161
- const targetCommitment = options.commitment ?? commitment;
162
- const wireTransaction = kit.getBase64EncodedWireTransaction(transaction);
163
- const response = await rpc.sendTransaction(wireTransaction, {
164
- encoding: "base64",
165
- maxRetries: toBigint(options.maxRetries),
166
- minContextSlot: toBigint(options.minContextSlot),
167
- preflightCommitment: targetCommitment,
168
- skipPreflight: options.skipPreflight
169
- }).send({ abortSignal: abortController.signal });
170
- const getBlockHeightExceedencePromise = transactionConfirmation.createBlockHeightExceedencePromiseFactory({
171
- rpc,
172
- rpcSubscriptions
173
- });
174
- const getRecentSignatureConfirmationPromise = transactionConfirmation.createRecentSignatureConfirmationPromiseFactory({
175
- rpc,
176
- rpcSubscriptions
177
- });
178
- await transactionConfirmation.waitForRecentTransactionConfirmation({
179
- abortSignal: abortController.signal,
180
- commitment: targetCommitment,
181
- getBlockHeightExceedencePromise,
182
- getRecentSignatureConfirmationPromise,
183
- transaction
184
- });
185
- return response;
186
- }
187
- __name(sendAndConfirmTransaction, "sendAndConfirmTransaction");
188
- async function simulateTransaction(transaction, options = {}) {
189
- const wireTransaction = kit.getBase64EncodedWireTransaction(transaction);
190
- const baseConfig = options.config ?? {};
191
- const mergedConfig = {
192
- ...DEFAULT_SIMULATION_CONFIG,
193
- ...baseConfig,
194
- commitment: baseConfig.commitment ?? options.commitment ?? commitment
195
- };
196
- const normalizedConfig = mergedConfig.sigVerify === true && mergedConfig.replaceRecentBlockhash !== false ? { ...mergedConfig, replaceRecentBlockhash: false } : mergedConfig;
197
- return rpc.simulateTransaction(wireTransaction, normalizedConfig).send({ abortSignal: options.abortSignal });
198
- }
199
- __name(simulateTransaction, "simulateTransaction");
200
- return {
201
- commitment,
202
- endpoint,
203
- rpc,
204
- rpcSubscriptions,
205
- sendAndConfirmTransaction,
206
- simulateTransaction,
207
- websocketEndpoint
208
- };
209
- }
210
- __name(createSolanaRpcClient, "createSolanaRpcClient");
211
-
212
- // src/serialization/state.ts
213
- var SERIALIZABLE_STATE_VERSION = 1;
214
- function getInitialSerializableState(config) {
215
- return {
216
- autoconnect: false,
217
- commitment: config.commitment,
218
- endpoint: config.endpoint,
219
- lastConnectorId: null,
220
- lastPublicKey: null,
221
- version: SERIALIZABLE_STATE_VERSION,
222
- websocketEndpoint: config.websocketEndpoint
223
- };
224
- }
225
- __name(getInitialSerializableState, "getInitialSerializableState");
226
- function applySerializableState(config, state) {
227
- if (!state) {
228
- return config;
229
- }
230
- return {
231
- ...config,
232
- commitment: state.commitment ?? config.commitment,
233
- endpoint: state.endpoint ?? config.endpoint,
234
- websocketEndpoint: state.websocketEndpoint ?? config.websocketEndpoint
235
- };
236
- }
237
- __name(applySerializableState, "applySerializableState");
238
- function serializeSolanaState(state) {
239
- return JSON.stringify(state);
240
- }
241
- __name(serializeSolanaState, "serializeSolanaState");
242
- function deserializeSolanaState(json) {
243
- if (!json) return null;
244
- try {
245
- const parsed = JSON.parse(json);
246
- if (typeof parsed !== "object" || parsed === null) return null;
247
- const state = parsed;
248
- return {
249
- autoconnect: state.autoconnect ?? false,
250
- commitment: state.commitment,
251
- endpoint: state.endpoint,
252
- lastConnectorId: state.lastConnectorId ?? null,
253
- lastPublicKey: state.lastPublicKey ?? null,
254
- version: state.version ?? SERIALIZABLE_STATE_VERSION,
255
- websocketEndpoint: state.websocketEndpoint
256
- };
257
- } catch {
258
- return null;
259
- }
260
- }
261
- __name(deserializeSolanaState, "deserializeSolanaState");
262
- function getSerializableStateSnapshot(client) {
263
- const state = client.store.getState();
264
- const wallet = state.wallet;
265
- const autoConnectPreference = wallet.autoConnect;
266
- let lastConnectorId = null;
267
- let lastPublicKey = null;
268
- if ("connectorId" in wallet) {
269
- lastConnectorId = wallet.connectorId ?? null;
270
- if (wallet.status === "connected") {
271
- lastPublicKey = wallet.session.account.address.toString();
272
- }
273
- }
274
- return {
275
- autoconnect: autoConnectPreference ?? Boolean(lastConnectorId),
276
- commitment: state.cluster.commitment,
277
- endpoint: state.cluster.endpoint,
278
- lastConnectorId,
279
- lastPublicKey,
280
- version: SERIALIZABLE_STATE_VERSION,
281
- websocketEndpoint: state.cluster.websocketEndpoint
282
- };
283
- }
284
- __name(getSerializableStateSnapshot, "getSerializableStateSnapshot");
285
- function subscribeSolanaState(client, listener) {
286
- let previous = serializeSolanaState(getSerializableStateSnapshot(client));
287
- listener(JSON.parse(previous));
288
- const unsubscribe = client.store.subscribe(() => {
289
- const snapshot = getSerializableStateSnapshot(client);
290
- const serialized = serializeSolanaState(snapshot);
291
- if (serialized === previous) {
292
- return;
293
- }
294
- previous = serialized;
295
- listener(snapshot);
296
- });
297
- return unsubscribe;
298
- }
299
- __name(subscribeSolanaState, "subscribeSolanaState");
300
-
301
- // src/utils/cluster.ts
302
- function ensureHttpProtocol(endpoint) {
303
- if (endpoint.startsWith("http://") || endpoint.startsWith("https://") || endpoint.startsWith("ws://") || endpoint.startsWith("wss://")) {
304
- return endpoint;
305
- }
306
- return `https://${endpoint}`;
307
- }
308
- __name(ensureHttpProtocol, "ensureHttpProtocol");
309
- var MONIKER_ENDPOINTS = {
310
- devnet: {
311
- endpoint: "https://api.devnet.solana.com",
312
- websocketEndpoint: "wss://api.devnet.solana.com"
313
- },
314
- localhost: {
315
- endpoint: "http://127.0.0.1:8899",
316
- websocketEndpoint: "ws://127.0.0.1:8900"
317
- },
318
- localnet: {
319
- endpoint: "http://127.0.0.1:8899",
320
- websocketEndpoint: "ws://127.0.0.1:8900"
321
- },
322
- "mainnet-beta": {
323
- endpoint: "https://api.mainnet-beta.solana.com",
324
- websocketEndpoint: "wss://api.mainnet-beta.solana.com"
325
- },
326
- mainnet: {
327
- endpoint: "https://api.mainnet-beta.solana.com",
328
- websocketEndpoint: "wss://api.mainnet-beta.solana.com"
329
- },
330
- testnet: {
331
- endpoint: "https://api.testnet.solana.com",
332
- websocketEndpoint: "wss://api.testnet.solana.com"
333
- }
334
- };
335
- function inferWebsocketEndpoint(endpoint) {
336
- if (endpoint.startsWith("https://")) {
337
- return endpoint.replace("https://", "wss://");
338
- }
339
- if (endpoint.startsWith("http://")) {
340
- return endpoint.replace("http://", "ws://");
341
- }
342
- if (endpoint.startsWith("ws://") || endpoint.startsWith("wss://")) {
343
- return endpoint;
344
- }
345
- return endpoint;
346
- }
347
- __name(inferWebsocketEndpoint, "inferWebsocketEndpoint");
348
- function resolveCluster(config) {
349
- const moniker = config.moniker ?? (config.endpoint ? "custom" : "devnet");
350
- const mapped = moniker === "custom" ? void 0 : MONIKER_ENDPOINTS[moniker];
351
- const endpoint = ensureHttpProtocol(config.endpoint ?? mapped?.endpoint);
352
- const rawWebsocket = config.websocketEndpoint ? ensureHttpProtocol(config.websocketEndpoint) : void 0;
353
- const websocketEndpoint = inferWebsocketEndpoint(
354
- rawWebsocket ?? mapped?.websocketEndpoint ?? endpoint
355
- );
356
- return {
357
- endpoint,
358
- moniker,
359
- websocketEndpoint
360
- };
361
- }
362
- __name(resolveCluster, "resolveCluster");
363
-
364
- // src/wallet/registry.ts
365
- function createWalletRegistry(connectors) {
366
- const byId = /* @__PURE__ */ new Map();
367
- for (const connector of connectors) {
368
- if (!byId.has(connector.id)) {
369
- byId.set(connector.id, connector);
370
- }
371
- }
372
- return {
373
- all: [...byId.values()],
374
- /**
375
- * Looks up a connector by identifier.
376
- *
377
- * @param id - Unique connector identifier.
378
- * @returns The registered connector, if present.
379
- */
380
- get(id) {
381
- return byId.get(id);
382
- }
383
- };
384
- }
385
- __name(createWalletRegistry, "createWalletRegistry");
386
- function updateState(store, update) {
387
- store.setState((state) => ({
388
- ...state,
389
- ...update,
390
- lastUpdatedAt: now()
391
- }));
392
- }
393
- __name(updateState, "updateState");
394
- function createActions({ connectors, logger: inputLogger, runtime, store }) {
395
- const logger = inputLogger ?? createLogger();
396
- let walletEventsCleanup;
397
- function getCommitment(commitment) {
398
- return commitment ?? store.getState().cluster.commitment;
399
- }
400
- __name(getCommitment, "getCommitment");
401
- async function warmupCluster(endpoint, commitment) {
402
- try {
403
- const start = now();
404
- await runtime.rpc.getLatestBlockhash({ commitment }).send({ abortSignal: AbortSignal.timeout(1e4) });
405
- return now() - start;
406
- } catch (error) {
407
- logger({
408
- data: { endpoint, ...formatError(error) },
409
- level: "warn",
410
- message: "cluster warmup failed"
411
- });
412
- return void 0;
413
- }
414
- }
415
- __name(warmupCluster, "warmupCluster");
416
- async function setCluster2(endpoint, config) {
417
- const nextCommitment = config?.commitment ?? store.getState().cluster.commitment;
418
- const websocketEndpoint = config?.websocketEndpoint ?? endpoint;
419
- store.setState((state) => ({
420
- ...state,
421
- cluster: {
422
- commitment: nextCommitment,
423
- endpoint,
424
- status: { status: "connecting" },
425
- websocketEndpoint
426
- },
427
- lastUpdatedAt: now()
428
- }));
429
- try {
430
- const newRpcClient = createSolanaRpcClient({
431
- commitment: nextCommitment,
432
- endpoint,
433
- websocketEndpoint
434
- });
435
- runtime.rpc = newRpcClient.rpc;
436
- runtime.rpcSubscriptions = newRpcClient.rpcSubscriptions;
437
- const latencyMs = await warmupCluster(endpoint, nextCommitment);
438
- store.setState((state) => ({
439
- ...state,
440
- cluster: {
441
- commitment: nextCommitment,
442
- endpoint,
443
- status: { latencyMs, status: "ready" },
444
- websocketEndpoint
445
- },
446
- lastUpdatedAt: now()
447
- }));
448
- } catch (error) {
449
- store.setState((state) => ({
450
- ...state,
451
- cluster: {
452
- commitment: nextCommitment,
453
- endpoint,
454
- status: { error, status: "error" },
455
- websocketEndpoint
456
- },
457
- lastUpdatedAt: now()
458
- }));
459
- logger({
460
- data: { endpoint, ...formatError(error) },
461
- level: "error",
462
- message: "cluster setup failed"
463
- });
464
- throw error;
465
- }
466
- }
467
- __name(setCluster2, "setCluster");
468
- async function connectWallet2(connectorId, options = {}) {
469
- walletEventsCleanup?.();
470
- walletEventsCleanup = void 0;
471
- const connector = connectors.get(connectorId);
472
- if (!connector) {
473
- throw new Error(`No wallet connector registered for id "${connectorId}".`);
474
- }
475
- if (!connector.isSupported()) {
476
- throw new Error(`Wallet connector "${connectorId}" is not supported in this environment.`);
477
- }
478
- const autoConnectPreference = options.autoConnect ?? false;
479
- store.setState((state) => ({
480
- ...state,
481
- lastUpdatedAt: now(),
482
- wallet: { autoConnect: autoConnectPreference, connectorId, status: "connecting" }
483
- }));
484
- try {
485
- const session = await connector.connect(options);
486
- store.setState((state) => ({
487
- ...state,
488
- lastUpdatedAt: now(),
489
- wallet: { autoConnect: autoConnectPreference, connectorId, session, status: "connected" }
490
- }));
491
- if (session.onAccountsChanged) {
492
- walletEventsCleanup = session.onAccountsChanged((accounts) => {
493
- if (accounts.length === 0) {
494
- walletEventsCleanup?.();
495
- walletEventsCleanup = void 0;
496
- void disconnectWallet3();
497
- }
498
- });
499
- }
500
- logger({
501
- data: { address: session.account.address.toString(), connectorId },
502
- level: "info",
503
- message: "wallet connected"
504
- });
505
- } catch (error) {
506
- store.setState((state) => ({
507
- ...state,
508
- lastUpdatedAt: now(),
509
- wallet: { autoConnect: autoConnectPreference, connectorId, error, status: "error" }
510
- }));
511
- logger({
512
- data: { connectorId, ...formatError(error) },
513
- level: "error",
514
- message: "wallet connection failed"
515
- });
516
- throw error;
517
- }
518
- }
519
- __name(connectWallet2, "connectWallet");
520
- async function disconnectWallet3() {
521
- const wallet = store.getState().wallet;
522
- if (wallet.status === "disconnected") {
523
- return;
524
- }
525
- walletEventsCleanup?.();
526
- walletEventsCleanup = void 0;
527
- try {
528
- if (wallet.status === "connected") {
529
- await wallet.session.disconnect();
530
- const connector = connectors.get(wallet.connectorId);
531
- if (connector) {
532
- await connector.disconnect();
533
- }
534
- } else if (wallet.status === "connecting") {
535
- const connector = connectors.get(wallet.connectorId);
536
- if (connector) {
537
- await connector.disconnect();
538
- }
539
- }
540
- } finally {
541
- updateState(store, { wallet: { status: "disconnected" } });
542
- }
543
- }
544
- __name(disconnectWallet3, "disconnectWallet");
545
- async function fetchBalance2(address5, commitment) {
546
- const key = address5.toString();
547
- store.setState((state) => ({
548
- ...state,
549
- accounts: {
550
- ...state.accounts,
551
- [key]: {
552
- address: address5,
553
- data: state.accounts[key]?.data,
554
- error: void 0,
555
- fetching: true,
556
- lamports: state.accounts[key]?.lamports ?? null,
557
- lastFetchedAt: now(),
558
- slot: state.accounts[key]?.slot ?? null
559
- }
560
- },
561
- lastUpdatedAt: now()
562
- }));
563
- try {
564
- const response = await runtime.rpc.getBalance(address5, { commitment: getCommitment(commitment) }).send({ abortSignal: AbortSignal.timeout(1e4) });
565
- const lamports2 = response.value;
566
- store.setState((state) => ({
567
- ...state,
568
- accounts: {
569
- ...state.accounts,
570
- [key]: {
571
- address: address5,
572
- data: state.accounts[key]?.data,
573
- error: void 0,
574
- fetching: false,
575
- lamports: lamports2,
576
- lastFetchedAt: now(),
577
- slot: response.context.slot
578
- }
579
- },
580
- lastUpdatedAt: now()
581
- }));
582
- return lamports2;
583
- } catch (error) {
584
- store.setState((state) => ({
585
- ...state,
586
- accounts: {
587
- ...state.accounts,
588
- [key]: {
589
- address: address5,
590
- data: state.accounts[key]?.data,
591
- error,
592
- fetching: false,
593
- lamports: state.accounts[key]?.lamports ?? null,
594
- lastFetchedAt: now(),
595
- slot: state.accounts[key]?.slot ?? null
596
- }
597
- },
598
- lastUpdatedAt: now()
599
- }));
600
- logger({
601
- data: { address: key, ...formatError(error) },
602
- level: "error",
603
- message: "balance fetch failed"
604
- });
605
- throw error;
606
- }
607
- }
608
- __name(fetchBalance2, "fetchBalance");
609
- async function fetchAccount2(address5, commitment) {
610
- const key = address5.toString();
611
- store.setState((state) => ({
612
- ...state,
613
- accounts: {
614
- ...state.accounts,
615
- [key]: {
616
- address: address5,
617
- data: state.accounts[key]?.data,
618
- error: void 0,
619
- fetching: true,
620
- lamports: state.accounts[key]?.lamports ?? null,
621
- lastFetchedAt: now(),
622
- slot: state.accounts[key]?.slot ?? null
623
- }
624
- },
625
- lastUpdatedAt: now()
626
- }));
627
- try {
628
- const response = await runtime.rpc.getAccountInfo(address5, { commitment: getCommitment(commitment), encoding: "base64" }).send({ abortSignal: AbortSignal.timeout(1e4) });
629
- const value = response.value;
630
- const lamports2 = value?.lamports ?? null;
631
- store.setState((state) => ({
632
- ...state,
633
- accounts: {
634
- ...state.accounts,
635
- [key]: {
636
- address: address5,
637
- data: value,
638
- error: void 0,
639
- fetching: false,
640
- lamports: lamports2,
641
- lastFetchedAt: now(),
642
- slot: response.context.slot
643
- }
644
- },
645
- lastUpdatedAt: now()
646
- }));
647
- return store.getState().accounts[key];
648
- } catch (error) {
649
- store.setState((state) => ({
650
- ...state,
651
- accounts: {
652
- ...state.accounts,
653
- [key]: {
654
- address: address5,
655
- data: state.accounts[key]?.data,
656
- error,
657
- fetching: false,
658
- lamports: state.accounts[key]?.lamports ?? null,
659
- lastFetchedAt: now(),
660
- slot: state.accounts[key]?.slot ?? null
661
- }
662
- },
663
- lastUpdatedAt: now()
664
- }));
665
- logger({
666
- data: { address: key, ...formatError(error) },
667
- level: "error",
668
- message: "account fetch failed"
669
- });
670
- throw error;
671
- }
672
- }
673
- __name(fetchAccount2, "fetchAccount");
674
- async function fetchLookupTable2(addr, commitment) {
675
- const account = await addressLookupTable.fetchAddressLookupTable(runtime.rpc, addr, {
676
- commitment: getCommitment(commitment)
677
- });
678
- const { addresses, authority, deactivationSlot, lastExtendedSlot, lastExtendedSlotStartIndex } = account.data;
679
- return {
680
- addresses,
681
- authority: kit.isSome(authority) ? authority.value : void 0,
682
- deactivationSlot,
683
- lastExtendedSlot,
684
- lastExtendedSlotStartIndex
685
- };
686
- }
687
- __name(fetchLookupTable2, "fetchLookupTable");
688
- async function fetchLookupTables2(addresses, commitment) {
689
- if (addresses.length === 0) return [];
690
- const accounts = await addressLookupTable.fetchAllAddressLookupTable(runtime.rpc, addresses, {
691
- commitment: getCommitment(commitment)
692
- });
693
- return accounts.map(({ data }) => ({
694
- addresses: data.addresses,
695
- authority: kit.isSome(data.authority) ? data.authority.value : void 0,
696
- deactivationSlot: data.deactivationSlot,
697
- lastExtendedSlot: data.lastExtendedSlot,
698
- lastExtendedSlotStartIndex: data.lastExtendedSlotStartIndex
699
- }));
700
- }
701
- __name(fetchLookupTables2, "fetchLookupTables");
702
- async function fetchNonceAccount2(addr, commitment) {
703
- const account = await system.fetchNonce(runtime.rpc, addr, {
704
- commitment: getCommitment(commitment)
705
- });
706
- return { authority: account.data.authority, blockhash: account.data.blockhash };
707
- }
708
- __name(fetchNonceAccount2, "fetchNonceAccount");
709
- async function sendTransaction2(transaction, commitment) {
710
- const targetCommitment = getCommitment(commitment);
711
- const abortController = new AbortController();
712
- const signature5 = await runtime.rpc.sendTransaction(kit.getBase64EncodedWireTransaction(transaction), {
713
- encoding: "base64",
714
- preflightCommitment: targetCommitment
715
- }).send({ abortSignal: abortController.signal });
716
- const key = signature5.toString();
717
- store.setState((state) => ({
718
- ...state,
719
- lastUpdatedAt: now(),
720
- transactions: {
721
- ...state.transactions,
722
- [key]: {
723
- lastUpdatedAt: now(),
724
- signature: signature5,
725
- status: "sending"
726
- }
727
- }
728
- }));
729
- const getBlockHeightExceedencePromise = transactionConfirmation.createBlockHeightExceedencePromiseFactory({
730
- rpc: runtime.rpc,
731
- rpcSubscriptions: runtime.rpcSubscriptions
732
- });
733
- const getRecentSignatureConfirmationPromise = transactionConfirmation.createRecentSignatureConfirmationPromiseFactory({
734
- rpc: runtime.rpc,
735
- rpcSubscriptions: runtime.rpcSubscriptions
736
- });
737
- try {
738
- await transactionConfirmation.waitForRecentTransactionConfirmation({
739
- abortSignal: abortController.signal,
740
- commitment: targetCommitment,
741
- getBlockHeightExceedencePromise,
742
- getRecentSignatureConfirmationPromise,
743
- transaction
744
- });
745
- store.setState((state) => ({
746
- ...state,
747
- lastUpdatedAt: now(),
748
- transactions: {
749
- ...state.transactions,
750
- [key]: {
751
- lastUpdatedAt: now(),
752
- signature: signature5,
753
- status: "confirmed"
754
- }
755
- }
756
- }));
757
- return signature5;
758
- } catch (error) {
759
- store.setState((state) => ({
760
- ...state,
761
- lastUpdatedAt: now(),
762
- transactions: {
763
- ...state.transactions,
764
- [key]: {
765
- error,
766
- lastUpdatedAt: now(),
767
- signature: signature5,
768
- status: "failed"
769
- }
770
- }
771
- }));
772
- logger({
773
- data: { signature: key, ...formatError(error) },
774
- level: "error",
775
- message: "transaction failed to confirm"
776
- });
777
- throw error;
778
- }
779
- }
780
- __name(sendTransaction2, "sendTransaction");
781
- async function requestAirdrop2(address5, lamports2) {
782
- try {
783
- const factory = kit.airdropFactory({
784
- rpc: runtime.rpc,
785
- rpcSubscriptions: runtime.rpcSubscriptions
786
- });
787
- const signature5 = await factory({
788
- commitment: getCommitment("confirmed"),
789
- lamports: lamports2,
790
- recipientAddress: address5
791
- });
792
- logger({
793
- data: { address: address5.toString(), lamports: lamports2.toString(), signature: signature5 },
794
- level: "info",
795
- message: "airdrop requested"
796
- });
797
- return signature5;
798
- } catch (error) {
799
- logger({
800
- data: { address: address5.toString(), lamports: lamports2.toString(), ...formatError(error) },
801
- level: "error",
802
- message: "airdrop request failed"
803
- });
804
- throw error;
805
- }
806
- }
807
- __name(requestAirdrop2, "requestAirdrop");
808
- return {
809
- connectWallet: connectWallet2,
810
- disconnectWallet: disconnectWallet3,
811
- fetchAccount: fetchAccount2,
812
- fetchBalance: fetchBalance2,
813
- fetchLookupTable: fetchLookupTable2,
814
- fetchLookupTables: fetchLookupTables2,
815
- fetchNonceAccount: fetchNonceAccount2,
816
- requestAirdrop: requestAirdrop2,
817
- sendTransaction: sendTransaction2,
818
- setCluster: setCluster2
819
- };
820
- }
821
- __name(createActions, "createActions");
822
-
823
- // src/numeric/math.ts
824
- var TEN = 10n;
825
- function pow10(exponent) {
826
- assertDecimals(exponent, "exponent");
827
- return TEN ** BigInt(exponent);
828
- }
829
- __name(pow10, "pow10");
830
- function assertNonNegative(value, label = "value") {
831
- if (value < 0n) {
832
- throw new RangeError(`${label} must be non-negative`);
833
- }
834
- }
835
- __name(assertNonNegative, "assertNonNegative");
836
- function assertDecimals(decimals, label = "decimals") {
837
- if (!Number.isInteger(decimals) || decimals < 0 || decimals > 38) {
838
- throw new RangeError(`${label} must be an integer between 0 and 38`);
839
- }
840
- }
841
- __name(assertDecimals, "assertDecimals");
842
- function toBigint2(value, label = "value") {
843
- if (typeof value === "bigint") {
844
- return value;
845
- }
846
- if (typeof value === "number") {
847
- if (!Number.isFinite(value) || !Number.isInteger(value)) {
848
- throw new RangeError(`${label} must be a finite integer when provided as a number`);
849
- }
850
- if (!Number.isSafeInteger(value)) {
851
- throw new RangeError(`${label} must be within the safe integer range when provided as a number`);
852
- }
853
- return BigInt(value);
854
- }
855
- const trimmed = value.trim();
856
- const match = /^[-+]?\d+$/.exec(trimmed);
857
- if (!match) {
858
- throw new SyntaxError(`${label} must be an integer string`);
859
- }
860
- return BigInt(match[0]);
861
- }
862
- __name(toBigint2, "toBigint");
863
- function checkedAdd(lhs, rhs, label = "result") {
864
- const result = lhs + rhs;
865
- assertNonNegative(result, label);
866
- return result;
867
- }
868
- __name(checkedAdd, "checkedAdd");
869
- function checkedSubtract(lhs, rhs, label = "result") {
870
- const result = lhs - rhs;
871
- assertNonNegative(result, label);
872
- return result;
873
- }
874
- __name(checkedSubtract, "checkedSubtract");
875
- function checkedMultiply(lhs, rhs, label = "result") {
876
- const result = lhs * rhs;
877
- assertNonNegative(result, label);
878
- return result;
879
- }
880
- __name(checkedMultiply, "checkedMultiply");
881
- function checkedDivide(dividend, divisor, label = "result") {
882
- if (divisor === 0n) {
883
- throw new RangeError("divisor must be non-zero");
884
- }
885
- const result = dividend / divisor;
886
- assertNonNegative(result, label);
887
- return result;
888
- }
889
- __name(checkedDivide, "checkedDivide");
890
-
891
- // src/numeric/rational.ts
892
- function divideWithRounding(dividend, divisor, rounding) {
893
- if (divisor <= 0n) {
894
- throw new RangeError("divisor must be positive");
895
- }
896
- const base = dividend / divisor;
897
- const remainder = dividend % divisor;
898
- if (remainder === 0n) {
899
- return base;
900
- }
901
- switch (rounding) {
902
- case "ceil":
903
- return base + 1n;
904
- case "round": {
905
- const twice = remainder * 2n;
906
- return twice >= divisor ? base + 1n : base;
907
- }
908
- default:
909
- return base;
910
- }
911
- }
912
- __name(divideWithRounding, "divideWithRounding");
913
- function createRatio(numeratorInput, denominatorInput) {
914
- const numerator = toBigint2(numeratorInput, "numerator");
915
- const denominator = toBigint2(denominatorInput, "denominator");
916
- if (denominator <= 0n) {
917
- throw new RangeError("denominator must be positive");
918
- }
919
- assertNonNegative(numerator, "numerator");
920
- return Object.freeze({ denominator, numerator });
921
- }
922
- __name(createRatio, "createRatio");
923
- function applyRatio(amount, ratio, options = {}) {
924
- assertNonNegative(amount, "amount");
925
- const dividend = amount * ratio.numerator;
926
- const rounding = options.rounding ?? "floor";
927
- return divideWithRounding(dividend, ratio.denominator, rounding);
928
- }
929
- __name(applyRatio, "applyRatio");
930
-
931
- // src/numeric/amounts.ts
932
- var DECIMAL_PATTERN = /^\d+(?:\.\d+)?$/;
933
- function normalizeNumberInput(value, decimals, label) {
934
- if (!Number.isFinite(value)) {
935
- throw new RangeError(`${label} must be a finite number`);
936
- }
937
- if (Number.isInteger(value)) {
938
- return value.toString(10);
939
- }
940
- const stringValue = value.toString(10);
941
- if (stringValue.includes("e") || stringValue.includes("E")) {
942
- throw new RangeError(`${label} cannot use exponential notation; provide a string instead`);
943
- }
944
- const parts = stringValue.split(".");
945
- if (parts[1] && parts[1].length > decimals + 6) {
946
- throw new RangeError(`${label} exceeds safe precision; provide a string instead`);
947
- }
948
- return stringValue;
949
- }
950
- __name(normalizeNumberInput, "normalizeNumberInput");
951
- function decimalToBaseUnits(value, decimals, scale, options) {
952
- const label = options.label ?? "value";
953
- const rounding = options.rounding ?? "floor";
954
- const sanitized = value.replace(/_/g, "").trim();
955
- if (sanitized === "") {
956
- throw new SyntaxError(`${label} must not be empty`);
957
- }
958
- if (!DECIMAL_PATTERN.test(sanitized)) {
959
- throw new SyntaxError(`${label} must be a non-negative decimal string`);
960
- }
961
- const [integerPartRaw, fractionalRaw] = sanitized.split(".");
962
- const integerPart = integerPartRaw || "0";
963
- assertNonNegative(BigInt(integerPart), label);
964
- let result = BigInt(integerPart) * scale;
965
- const fractionalDigits = fractionalRaw ?? "";
966
- if (decimals === 0) {
967
- if (fractionalDigits.length === 0) {
968
- return result;
969
- }
970
- const hasFractional = /[1-9]/.test(fractionalDigits);
971
- if (rounding === "ceil" && hasFractional) {
972
- return result + 1n;
973
- }
974
- if (rounding === "round" && fractionalDigits[0] !== void 0 && fractionalDigits[0] >= "5") {
975
- return result + 1n;
976
- }
977
- return result;
978
- }
979
- const truncatedFractional = fractionalDigits.slice(0, decimals).padEnd(decimals, "0");
980
- const fractionalComponent = truncatedFractional === "" ? 0n : BigInt(truncatedFractional);
981
- result += fractionalComponent;
982
- if (fractionalDigits.length > decimals) {
983
- const remainderDigits = fractionalDigits.slice(decimals);
984
- const hasRemainder = /[1-9]/.test(remainderDigits);
985
- if (rounding === "ceil" && hasRemainder) {
986
- result += 1n;
987
- } else if (rounding === "round") {
988
- const firstRemainderDigit = remainderDigits[0];
989
- if (firstRemainderDigit !== void 0 && firstRemainderDigit >= "5") {
990
- result += 1n;
991
- }
992
- }
993
- }
994
- return result;
995
- }
996
- __name(decimalToBaseUnits, "decimalToBaseUnits");
997
- function formatBaseUnits(amount, decimals, scale, options) {
998
- assertNonNegative(amount, "amount");
999
- const minimumFractionDigits = options.minimumFractionDigits ?? 0;
1000
- if (minimumFractionDigits < 0 || minimumFractionDigits > decimals) {
1001
- throw new RangeError("minimumFractionDigits must be between 0 and the token decimals");
1002
- }
1003
- const trimTrailingZeros = options.trimTrailingZeros ?? true;
1004
- if (decimals === 0) {
1005
- return amount.toString();
1006
- }
1007
- const whole = amount / scale;
1008
- let fraction = (amount % scale).toString().padStart(decimals, "0");
1009
- if (trimTrailingZeros) {
1010
- fraction = fraction.replace(/0+$/, "");
1011
- }
1012
- if (fraction.length < minimumFractionDigits) {
1013
- fraction = fraction.padEnd(minimumFractionDigits, "0");
1014
- }
1015
- if (fraction.length === 0) {
1016
- return whole.toString();
1017
- }
1018
- return `${whole.toString()}.${fraction}`;
1019
- }
1020
- __name(formatBaseUnits, "formatBaseUnits");
1021
- function createTokenAmount(decimals) {
1022
- assertDecimals(decimals, "decimals");
1023
- const scale = pow10(decimals);
1024
- function fromBaseUnits(value, label) {
1025
- const amount = toBigint2(value, label ?? "amount");
1026
- assertNonNegative(amount, label ?? "amount");
1027
- return amount;
1028
- }
1029
- __name(fromBaseUnits, "fromBaseUnits");
1030
- function fromDecimal(value, options = {}) {
1031
- const label = options.label ?? "value";
1032
- if (typeof value === "number") {
1033
- if (Number.isInteger(value)) {
1034
- if (!Number.isSafeInteger(value)) {
1035
- throw new RangeError(`${label} must be within the safe integer range when provided as a number`);
1036
- }
1037
- return fromBaseUnits(BigInt(value) * scale, label);
1038
- }
1039
- if (decimals === 0) {
1040
- throw new RangeError(`${label} cannot include fractional digits for a token with 0 decimals`);
1041
- }
1042
- const normalized = normalizeNumberInput(value, decimals, label);
1043
- return decimalToBaseUnits(normalized, decimals, scale, options);
1044
- }
1045
- return decimalToBaseUnits(value, decimals, scale, options);
1046
- }
1047
- __name(fromDecimal, "fromDecimal");
1048
- function toDecimalString(amount, options = {}) {
1049
- return formatBaseUnits(fromBaseUnits(amount), decimals, scale, options);
1050
- }
1051
- __name(toDecimalString, "toDecimalString");
1052
- function add(lhs, rhs) {
1053
- return checkedAdd(fromBaseUnits(lhs), fromBaseUnits(rhs));
1054
- }
1055
- __name(add, "add");
1056
- function subtract(lhs, rhs) {
1057
- return checkedSubtract(fromBaseUnits(lhs), fromBaseUnits(rhs));
1058
- }
1059
- __name(subtract, "subtract");
1060
- function multiplyByRatio(amount, ratio, options) {
1061
- return applyRatio(fromBaseUnits(amount), ratio, options);
1062
- }
1063
- __name(multiplyByRatio, "multiplyByRatio");
1064
- function isZero(amount) {
1065
- return fromBaseUnits(amount) === 0n;
1066
- }
1067
- __name(isZero, "isZero");
1068
- function compare(lhs, rhs) {
1069
- const left = fromBaseUnits(lhs);
1070
- const right = fromBaseUnits(rhs);
1071
- if (left > right) {
1072
- return 1;
1073
- }
1074
- if (left < right) {
1075
- return -1;
1076
- }
1077
- return 0;
1078
- }
1079
- __name(compare, "compare");
1080
- return Object.freeze({
1081
- add,
1082
- compare,
1083
- decimals,
1084
- fromBaseUnits,
1085
- fromDecimal,
1086
- isZero,
1087
- multiplyByRatio,
1088
- scale,
1089
- subtract,
1090
- toDecimalString
1091
- });
1092
- }
1093
- __name(createTokenAmount, "createTokenAmount");
1094
-
1095
- // src/numeric/lamports.ts
1096
- var BASE_LAMPORTS = createTokenAmount(9);
1097
- var LAMPORTS_PER_SOL = BASE_LAMPORTS.scale;
1098
- var lamportsMath = Object.freeze({
1099
- /**
1100
- * Adds two lamport amounts.
1101
- *
1102
- * @param lhs - First lamport operand.
1103
- * @param rhs - Second lamport operand.
1104
- * @returns Sum as lamports.
1105
- */
1106
- add(lhs, rhs) {
1107
- return BASE_LAMPORTS.add(lhs, rhs);
1108
- },
1109
- /**
1110
- * Compares two lamport amounts.
1111
- *
1112
- * @param lhs - First lamport operand.
1113
- * @param rhs - Second lamport operand.
1114
- * @returns `1`, `0`, or `-1` corresponding to the comparison result.
1115
- */
1116
- compare(lhs, rhs) {
1117
- return BASE_LAMPORTS.compare(lhs, rhs);
1118
- },
1119
- decimals: BASE_LAMPORTS.decimals,
1120
- /**
1121
- * Validates and converts raw lamport inputs.
1122
- *
1123
- * @param value - Integer-like lamport amount.
1124
- * @param label - Optional label used for error reporting.
1125
- * @returns Normalized lamport bigint.
1126
- */
1127
- fromLamports(value, label) {
1128
- return BASE_LAMPORTS.fromBaseUnits(value, label);
1129
- },
1130
- /**
1131
- * Converts SOL denominated values into lamports.
1132
- *
1133
- * @param value - Decimal representation of SOL.
1134
- * @param options - Optional rounding and labelling configuration.
1135
- * @returns Lamport amount.
1136
- */
1137
- fromSol(value, options) {
1138
- return BASE_LAMPORTS.fromDecimal(value, options);
1139
- },
1140
- /**
1141
- * Determines whether a lamport amount equals zero.
1142
- *
1143
- * @param amount - Lamports to inspect.
1144
- * @returns `true` when the amount is zero.
1145
- */
1146
- isZero(amount) {
1147
- return BASE_LAMPORTS.isZero(amount);
1148
- },
1149
- /**
1150
- * Applies a ratio to lamports.
1151
- *
1152
- * @param amount - Lamport amount to scale.
1153
- * @param ratio - Ratio produced by {@link createRatio}.
1154
- * @param options - Optional rounding configuration.
1155
- * @returns Scaled lamport amount.
1156
- */
1157
- multiplyByRatio(amount, ratio, options) {
1158
- return BASE_LAMPORTS.multiplyByRatio(amount, ratio, options);
1159
- },
1160
- raw: BASE_LAMPORTS,
1161
- scale: BASE_LAMPORTS.scale,
1162
- /**
1163
- * Subtracts two lamport amounts.
1164
- *
1165
- * @param lhs - First lamport operand.
1166
- * @param rhs - Second lamport operand.
1167
- * @returns Difference as lamports.
1168
- */
1169
- subtract(lhs, rhs) {
1170
- return BASE_LAMPORTS.subtract(lhs, rhs);
1171
- },
1172
- /**
1173
- * Formats lamports into a human-readable SOL string.
1174
- *
1175
- * @param amount - Lamport amount to format.
1176
- * @param options - Formatting preferences.
1177
- * @returns SOL string representation.
1178
- */
1179
- toSolString(amount, options) {
1180
- return BASE_LAMPORTS.toDecimalString(amount, options);
1181
- }
1182
- });
1183
- function lamports(value, label) {
1184
- return lamportsMath.fromLamports(value, label);
1185
- }
1186
- __name(lamports, "lamports");
1187
- function lamportsFromSol(value, options) {
1188
- return lamportsMath.fromSol(value, options);
1189
- }
1190
- __name(lamportsFromSol, "lamportsFromSol");
1191
- function lamportsToSolString(amount, options) {
1192
- return lamportsMath.toSolString(amount, options);
1193
- }
1194
- __name(lamportsToSolString, "lamportsToSolString");
1195
- function isWalletSession(value) {
1196
- if (typeof value !== "object" || value === null) {
1197
- return false;
1198
- }
1199
- return "account" in value && "connector" in value && "disconnect" in value;
1200
- }
1201
- __name(isWalletSession, "isWalletSession");
1202
- function createWalletTransactionSigner(session, config = {}) {
1203
- const { commitment } = config;
1204
- const address5 = session.account.address;
1205
- if (session.signTransaction) {
1206
- const signTransaction = session.signTransaction.bind(session);
1207
- const modifyingSigner = Object.freeze({
1208
- address: address5,
1209
- async modifyAndSignTransactions(transactions) {
1210
- const signedTransactions = [];
1211
- for (const transaction of transactions) {
1212
- const castTransaction = transaction;
1213
- const signed = await signTransaction(
1214
- castTransaction
1215
- );
1216
- const signature5 = signed.signatures[address5];
1217
- if (!signature5) {
1218
- throw new Error("Wallet did not populate the expected fee payer signature.");
1219
- }
1220
- const mergedTransaction = Object.freeze({
1221
- ...castTransaction,
1222
- messageBytes: signed.messageBytes,
1223
- signatures: Object.freeze({
1224
- ...castTransaction.signatures,
1225
- ...signed.signatures
1226
- })
1227
- });
1228
- signedTransactions.push(mergedTransaction);
1229
- }
1230
- return Object.freeze(signedTransactions);
1231
- },
1232
- async signTransactions(transactions) {
1233
- const signedTransactions = await this.modifyAndSignTransactions(transactions);
1234
- return Object.freeze(
1235
- signedTransactions.map((signedTransaction) => {
1236
- const signature5 = signedTransaction.signatures[address5];
1237
- if (!signature5) {
1238
- throw new Error("Expected signer to produce a signature for the provided address.");
1239
- }
1240
- return Object.freeze({ [address5]: signature5 });
1241
- })
1242
- );
1243
- }
1244
- });
1245
- return {
1246
- mode: "partial",
1247
- signer: modifyingSigner
1248
- };
1249
- }
1250
- if (session.sendTransaction) {
1251
- const base58Encoder = codecsStrings.getBase58Encoder();
1252
- const sendTransaction2 = session.sendTransaction.bind(session);
1253
- const sendingSigner = Object.freeze({
1254
- address: address5,
1255
- async signAndSendTransactions(transactions) {
1256
- const signatures = [];
1257
- for (const transaction of transactions) {
1258
- const signatureString = await sendTransaction2(
1259
- transaction,
1260
- commitment ? { commitment } : void 0
1261
- );
1262
- const bytes = base58Encoder.encode(signatureString);
1263
- signatures.push(kit.signatureBytes(bytes));
1264
- }
1265
- return signatures;
1266
- }
1267
- });
1268
- return {
1269
- mode: "send",
1270
- signer: sendingSigner
1271
- };
1272
- }
1273
- throw new Error("Wallet session does not support signing or sending transactions.");
1274
- }
1275
- __name(createWalletTransactionSigner, "createWalletTransactionSigner");
1276
- function resolveSignerMode(signer) {
1277
- if (kit.isTransactionPartialSigner(signer)) {
1278
- return "partial";
1279
- }
1280
- if (kit.isTransactionSendingSigner(signer)) {
1281
- return "send";
1282
- }
1283
- return "partial";
1284
- }
1285
- __name(resolveSignerMode, "resolveSignerMode");
1286
-
1287
- // src/features/sol.ts
1288
- function ensureAddress(value) {
1289
- return typeof value === "string" ? kit.address(value) : value;
1290
- }
1291
- __name(ensureAddress, "ensureAddress");
1292
- async function resolveLifetime(runtime, commitment, fallback) {
1293
- if (fallback) {
1294
- return fallback;
1295
- }
1296
- const { value } = await runtime.rpc.getLatestBlockhash({ commitment }).send();
1297
- return value;
1298
- }
1299
- __name(resolveLifetime, "resolveLifetime");
1300
- function resolveSigner(authority, commitment) {
1301
- if (isWalletSession(authority)) {
1302
- const { signer, mode } = createWalletTransactionSigner(authority, { commitment });
1303
- return { mode, signer };
1304
- }
1305
- return { mode: resolveSignerMode(authority), signer: authority };
1306
- }
1307
- __name(resolveSigner, "resolveSigner");
1308
- function toLamportAmount(input) {
1309
- return lamportsMath.fromLamports(input);
1310
- }
1311
- __name(toLamportAmount, "toLamportAmount");
1312
- function createSolTransferHelper(runtime) {
1313
- async function prepareTransfer(config) {
1314
- const commitment = config.commitment;
1315
- const lifetime = await resolveLifetime(runtime, commitment, config.lifetime);
1316
- const { signer, mode } = resolveSigner(config.authority, commitment);
1317
- const destination = ensureAddress(config.destination);
1318
- const amount = toLamportAmount(config.amount);
1319
- const message = kit.pipe(
1320
- kit.createTransactionMessage({ version: config.transactionVersion ?? 0 }),
1321
- (m) => kit.setTransactionMessageFeePayer(signer.address, m),
1322
- (m) => kit.setTransactionMessageLifetimeUsingBlockhash(lifetime, m),
1323
- (m) => kit.appendTransactionMessageInstruction(
1324
- system.getTransferSolInstruction({ amount, destination, source: signer }),
1325
- m
1326
- )
1327
- );
1328
- return {
1329
- commitment,
1330
- lifetime,
1331
- message,
1332
- mode,
1333
- signer,
1334
- plan: kit.singleTransactionPlan(message)
1335
- };
1336
- }
1337
- __name(prepareTransfer, "prepareTransfer");
1338
- async function sendPreparedTransfer(prepared, options = {}) {
1339
- if (prepared.mode === "send" && kit.isTransactionSendingSigner(prepared.signer)) {
1340
- const signatureBytes2 = await kit.signAndSendTransactionMessageWithSigners(prepared.message, {
1341
- abortSignal: options.abortSignal,
1342
- minContextSlot: options.minContextSlot
1343
- });
1344
- const base58Decoder2 = codecsStrings.getBase58Decoder();
1345
- return kit.signature(base58Decoder2.decode(signatureBytes2));
1346
- }
1347
- const commitment = options.commitment ?? prepared.commitment;
1348
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
1349
- let latestSignature = null;
1350
- const executor = kit.createTransactionPlanExecutor({
1351
- async executeTransactionMessage(message, config = {}) {
1352
- const signed = await kit.signTransactionMessageWithSigners(message, {
1353
- abortSignal: config.abortSignal ?? options.abortSignal,
1354
- minContextSlot: options.minContextSlot
1355
- });
1356
- const wire = kit.getBase64EncodedWireTransaction(signed);
1357
- const response = await runtime.rpc.sendTransaction(wire, {
1358
- encoding: "base64",
1359
- maxRetries,
1360
- preflightCommitment: commitment,
1361
- skipPreflight: options.skipPreflight
1362
- }).send({ abortSignal: config.abortSignal ?? options.abortSignal });
1363
- latestSignature = kit.signature(response);
1364
- return { transaction: signed };
1365
- }
1366
- });
1367
- await executor(prepared.plan ?? kit.singleTransactionPlan(prepared.message), { abortSignal: options.abortSignal });
1368
- if (!latestSignature) {
1369
- throw new Error("Failed to resolve transaction signature.");
1370
- }
1371
- return latestSignature;
1372
- }
1373
- __name(sendPreparedTransfer, "sendPreparedTransfer");
1374
- async function sendTransfer(config, options) {
1375
- const prepared = await prepareTransfer(config);
1376
- return await sendPreparedTransfer(prepared, options);
1377
- }
1378
- __name(sendTransfer, "sendTransfer");
1379
- return {
1380
- prepareTransfer,
1381
- sendPreparedTransfer,
1382
- sendTransfer
1383
- };
1384
- }
1385
- __name(createSolTransferHelper, "createSolTransferHelper");
1386
- function ensureAddress2(value, fallback) {
1387
- if (value) {
1388
- return typeof value === "string" ? kit.address(value) : value;
1389
- }
1390
- if (!fallback) {
1391
- throw new Error("An address value was expected but not provided.");
1392
- }
1393
- return fallback;
1394
- }
1395
- __name(ensureAddress2, "ensureAddress");
1396
- async function resolveLifetime2(runtime, commitment, fallback) {
1397
- if (fallback) {
1398
- return fallback;
1399
- }
1400
- const { value } = await runtime.rpc.getLatestBlockhash({ commitment }).send();
1401
- return value;
1402
- }
1403
- __name(resolveLifetime2, "resolveLifetime");
1404
- function resolveSigner2(authority, commitment) {
1405
- if (isWalletSession(authority)) {
1406
- const { signer, mode } = createWalletTransactionSigner(authority, { commitment });
1407
- return { mode, signer };
1408
- }
1409
- return { mode: resolveSignerMode(authority), signer: authority };
1410
- }
1411
- __name(resolveSigner2, "resolveSigner");
1412
- function createSplTokenHelper(runtime, config) {
1413
- const mintAddress = ensureAddress2(config.mint);
1414
- const tokenProgram = ensureAddress2(config.tokenProgram, kit.address(token.TOKEN_PROGRAM_ADDRESS));
1415
- let cachedDecimals = config.decimals;
1416
- let cachedMath;
1417
- async function resolveDecimals(commitment) {
1418
- if (cachedDecimals !== void 0) {
1419
- return cachedDecimals;
1420
- }
1421
- const account = await token.fetchMint(runtime.rpc, mintAddress, { commitment });
1422
- cachedDecimals = account.data.decimals;
1423
- return cachedDecimals;
1424
- }
1425
- __name(resolveDecimals, "resolveDecimals");
1426
- async function getTokenMath(commitment) {
1427
- if (cachedMath) {
1428
- return cachedMath;
1429
- }
1430
- const decimals = await resolveDecimals(commitment);
1431
- cachedMath = createTokenAmount(decimals);
1432
- return cachedMath;
1433
- }
1434
- __name(getTokenMath, "getTokenMath");
1435
- async function deriveAssociatedTokenAddress(owner) {
1436
- const [ata] = await token.findAssociatedTokenPda({
1437
- mint: mintAddress,
1438
- owner: ensureAddress2(owner),
1439
- tokenProgram
1440
- });
1441
- return ata;
1442
- }
1443
- __name(deriveAssociatedTokenAddress, "deriveAssociatedTokenAddress");
1444
- async function fetchBalance2(owner, commitment) {
1445
- const ataAddress = await deriveAssociatedTokenAddress(owner);
1446
- const decimals = await resolveDecimals(commitment);
1447
- try {
1448
- const { value } = await runtime.rpc.getTokenAccountBalance(ataAddress, { commitment }).send();
1449
- const math = await getTokenMath(commitment);
1450
- const amount = math.fromBaseUnits(value.amount, "balance");
1451
- const uiAmount = value.uiAmountString ?? value.amount;
1452
- return {
1453
- amount,
1454
- ataAddress,
1455
- decimals,
1456
- exists: true,
1457
- uiAmount
1458
- };
1459
- } catch {
1460
- return {
1461
- amount: 0n,
1462
- ataAddress,
1463
- decimals,
1464
- exists: false,
1465
- uiAmount: "0"
1466
- };
1467
- }
1468
- }
1469
- __name(fetchBalance2, "fetchBalance");
1470
- async function prepareTransfer(config2) {
1471
- const commitment = config2.commitment;
1472
- const lifetime = await resolveLifetime2(runtime, commitment, config2.lifetime);
1473
- const { signer, mode } = resolveSigner2(config2.authority, commitment);
1474
- const sourceOwner = ensureAddress2(config2.sourceOwner, signer.address);
1475
- const destinationOwner = ensureAddress2(config2.destinationOwner);
1476
- const sourceAta = ensureAddress2(config2.sourceToken, await deriveAssociatedTokenAddress(sourceOwner));
1477
- const destinationAta = ensureAddress2(
1478
- config2.destinationToken,
1479
- await deriveAssociatedTokenAddress(destinationOwner)
1480
- );
1481
- const math = await getTokenMath(commitment);
1482
- const decimals = await resolveDecimals(commitment);
1483
- const amount = config2.amountInBaseUnits ? math.fromBaseUnits(config2.amount, "amount") : math.fromDecimal(config2.amount, { label: "amount" });
1484
- const instructionList = [];
1485
- if (config2.ensureDestinationAta ?? true) {
1486
- const { value } = await runtime.rpc.getAccountInfo(destinationAta, {
1487
- commitment,
1488
- dataSlice: { length: 0, offset: 0 },
1489
- encoding: "base64"
1490
- }).send();
1491
- if (!value) {
1492
- instructionList.push(
1493
- token.getCreateAssociatedTokenInstruction({
1494
- ata: destinationAta,
1495
- mint: mintAddress,
1496
- owner: destinationOwner,
1497
- payer: signer,
1498
- tokenProgram
1499
- })
1500
- );
1501
- }
1502
- }
1503
- instructionList.push(
1504
- token.getTransferCheckedInstruction({
1505
- amount,
1506
- authority: signer,
1507
- decimals,
1508
- destination: destinationAta,
1509
- mint: mintAddress,
1510
- source: sourceAta
1511
- })
1512
- );
1513
- let message = kit.pipe(
1514
- kit.createTransactionMessage({ version: config2.transactionVersion ?? 0 }),
1515
- (m) => kit.setTransactionMessageFeePayer(signer.address, m),
1516
- (m) => kit.setTransactionMessageLifetimeUsingBlockhash(lifetime, m)
1517
- );
1518
- for (const instruction of instructionList) {
1519
- message = kit.appendTransactionMessageInstruction(instruction, message);
1520
- }
1521
- return {
1522
- amount,
1523
- commitment,
1524
- decimals,
1525
- destinationAta,
1526
- lifetime,
1527
- message,
1528
- mode,
1529
- signer,
1530
- sourceAta,
1531
- plan: kit.singleTransactionPlan(message)
1532
- };
1533
- }
1534
- __name(prepareTransfer, "prepareTransfer");
1535
- async function sendPreparedTransfer(prepared, options = {}) {
1536
- if (prepared.mode === "send" && kit.isTransactionSendingSigner(prepared.signer)) {
1537
- const signatureBytes2 = await kit.signAndSendTransactionMessageWithSigners(prepared.message, {
1538
- abortSignal: options.abortSignal,
1539
- minContextSlot: options.minContextSlot
1540
- });
1541
- const base58Decoder2 = codecsStrings.getBase58Decoder();
1542
- return kit.signature(base58Decoder2.decode(signatureBytes2));
1543
- }
1544
- const commitment = options.commitment ?? prepared.commitment;
1545
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
1546
- let latestSignature = null;
1547
- const executor = kit.createTransactionPlanExecutor({
1548
- async executeTransactionMessage(message, config2 = {}) {
1549
- const signed = await kit.signTransactionMessageWithSigners(message, {
1550
- abortSignal: config2.abortSignal ?? options.abortSignal,
1551
- minContextSlot: options.minContextSlot
1552
- });
1553
- const wire = kit.getBase64EncodedWireTransaction(signed);
1554
- const response = await runtime.rpc.sendTransaction(wire, {
1555
- encoding: "base64",
1556
- maxRetries,
1557
- preflightCommitment: commitment,
1558
- skipPreflight: options.skipPreflight
1559
- }).send({ abortSignal: config2.abortSignal ?? options.abortSignal });
1560
- latestSignature = kit.signature(response);
1561
- return { transaction: signed };
1562
- }
1563
- });
1564
- await executor(prepared.plan ?? kit.singleTransactionPlan(prepared.message), { abortSignal: options.abortSignal });
1565
- if (!latestSignature) {
1566
- throw new Error("Failed to resolve transaction signature.");
1567
- }
1568
- return latestSignature;
1569
- }
1570
- __name(sendPreparedTransfer, "sendPreparedTransfer");
1571
- async function sendTransfer(config2, options) {
1572
- const prepared = await prepareTransfer(config2);
1573
- try {
1574
- return await sendPreparedTransfer(prepared, options);
1575
- } catch (error) {
1576
- if (kit.isSolanaError(error, kit.SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED)) {
1577
- const retriedPrepared = await prepareTransfer({ ...config2, lifetime: void 0 });
1578
- return await sendPreparedTransfer(retriedPrepared, options);
1579
- }
1580
- throw error;
1581
- }
1582
- }
1583
- __name(sendTransfer, "sendTransfer");
1584
- return {
1585
- deriveAssociatedTokenAddress,
1586
- fetchBalance: fetchBalance2,
1587
- prepareTransfer,
1588
- sendPreparedTransfer,
1589
- sendTransfer
1590
- };
1591
- }
1592
- __name(createSplTokenHelper, "createSplTokenHelper");
1593
- var STAKE_PROGRAM_ID = "Stake11111111111111111111111111111111111111";
1594
- var SYSVAR_CLOCK = "SysvarC1ock11111111111111111111111111111111";
1595
- var SYSVAR_STAKE_HISTORY = "SysvarStakeHistory1111111111111111111111111";
1596
- var UNUSED_STAKE_CONFIG_ACC = "StakeConfig11111111111111111111111111111111";
1597
- var STAKE_STATE_LEN = 200;
1598
- function ensureAddress3(value) {
1599
- return typeof value === "string" ? kit.address(value) : value;
1600
- }
1601
- __name(ensureAddress3, "ensureAddress");
1602
- async function resolveLifetime3(runtime, commitment, fallback) {
1603
- if (fallback) {
1604
- return fallback;
1605
- }
1606
- const { value } = await runtime.rpc.getLatestBlockhash({ commitment }).send();
1607
- return value;
1608
- }
1609
- __name(resolveLifetime3, "resolveLifetime");
1610
- function resolveSigner3(authority, commitment) {
1611
- if (isWalletSession(authority)) {
1612
- const { signer, mode } = createWalletTransactionSigner(authority, { commitment });
1613
- return { mode, signer };
1614
- }
1615
- return { mode: resolveSignerMode(authority), signer: authority };
1616
- }
1617
- __name(resolveSigner3, "resolveSigner");
1618
- function toLamportAmount2(input) {
1619
- return lamportsMath.fromLamports(input);
1620
- }
1621
- __name(toLamportAmount2, "toLamportAmount");
1622
- function createStakeHelper(runtime) {
1623
- async function prepareStake(config) {
1624
- const commitment = config.commitment;
1625
- const lifetime = await resolveLifetime3(runtime, commitment, config.lifetime);
1626
- const { signer, mode } = resolveSigner3(config.authority, commitment);
1627
- const validatorAddress = ensureAddress3(config.validatorId);
1628
- const amount = toLamportAmount2(config.amount);
1629
- const rentExempt = await runtime.rpc.getMinimumBalanceForRentExemption(BigInt(STAKE_STATE_LEN)).send();
1630
- const totalLamports = rentExempt + amount;
1631
- const stakeAccount = await kit.generateKeyPairSigner();
1632
- const createIx = system.getCreateAccountInstruction({
1633
- payer: signer,
1634
- newAccount: stakeAccount,
1635
- lamports: totalLamports,
1636
- space: BigInt(STAKE_STATE_LEN),
1637
- programAddress: STAKE_PROGRAM_ID
1638
- });
1639
- const initializeIx = stake.getInitializeInstruction({
1640
- stake: stakeAccount.address,
1641
- arg0: {
1642
- staker: signer.address,
1643
- withdrawer: signer.address
1644
- },
1645
- arg1: {
1646
- unixTimestamp: 0n,
1647
- epoch: 0n,
1648
- custodian: signer.address
1649
- }
1650
- });
1651
- const delegateIx = stake.getDelegateStakeInstruction({
1652
- stake: stakeAccount.address,
1653
- vote: validatorAddress,
1654
- stakeHistory: SYSVAR_STAKE_HISTORY,
1655
- unused: UNUSED_STAKE_CONFIG_ACC,
1656
- stakeAuthority: signer
1657
- });
1658
- const message = kit.pipe(
1659
- kit.createTransactionMessage({ version: config.transactionVersion ?? 0 }),
1660
- (m) => kit.setTransactionMessageFeePayer(signer.address, m),
1661
- (m) => kit.setTransactionMessageLifetimeUsingBlockhash(lifetime, m),
1662
- (m) => kit.appendTransactionMessageInstructions([createIx, initializeIx, delegateIx], m)
1663
- );
1664
- return {
1665
- commitment,
1666
- lifetime,
1667
- message,
1668
- mode,
1669
- signer,
1670
- stakeAccount,
1671
- plan: kit.singleTransactionPlan(message)
1672
- };
1673
- }
1674
- __name(prepareStake, "prepareStake");
1675
- async function sendPreparedStake(prepared, options = {}) {
1676
- if (prepared.mode === "send" && kit.isTransactionSendingSigner(prepared.signer)) {
1677
- const signatureBytes2 = await kit.signAndSendTransactionMessageWithSigners(prepared.message, {
1678
- abortSignal: options.abortSignal,
1679
- minContextSlot: options.minContextSlot
1680
- });
1681
- const base58Decoder2 = codecsStrings.getBase58Decoder();
1682
- return kit.signature(base58Decoder2.decode(signatureBytes2));
1683
- }
1684
- const commitment = options.commitment ?? prepared.commitment;
1685
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
1686
- let latestSignature = null;
1687
- const executor = kit.createTransactionPlanExecutor({
1688
- async executeTransactionMessage(message, config = {}) {
1689
- const signed = await kit.signTransactionMessageWithSigners(message, {
1690
- abortSignal: config.abortSignal ?? options.abortSignal,
1691
- minContextSlot: options.minContextSlot
1692
- });
1693
- const wire = kit.getBase64EncodedWireTransaction(signed);
1694
- const response = await runtime.rpc.sendTransaction(wire, {
1695
- encoding: "base64",
1696
- maxRetries,
1697
- preflightCommitment: commitment,
1698
- skipPreflight: options.skipPreflight
1699
- }).send({ abortSignal: config.abortSignal ?? options.abortSignal });
1700
- latestSignature = kit.signature(response);
1701
- return { transaction: signed };
1702
- }
1703
- });
1704
- await executor(prepared.plan ?? kit.singleTransactionPlan(prepared.message), { abortSignal: options.abortSignal });
1705
- if (!latestSignature) {
1706
- throw new Error("Failed to resolve transaction signature.");
1707
- }
1708
- return latestSignature;
1709
- }
1710
- __name(sendPreparedStake, "sendPreparedStake");
1711
- async function sendStake(config, options) {
1712
- const prepared = await prepareStake(config);
1713
- return await sendPreparedStake(prepared, options);
1714
- }
1715
- __name(sendStake, "sendStake");
1716
- async function prepareUnstake(config) {
1717
- const commitment = config.commitment;
1718
- const lifetime = await resolveLifetime3(runtime, commitment, config.lifetime);
1719
- const { signer, mode } = resolveSigner3(config.authority, commitment);
1720
- const stakeAccountAddress = ensureAddress3(config.stakeAccount);
1721
- const deactivateIx = stake.getDeactivateInstruction({
1722
- stake: stakeAccountAddress,
1723
- clockSysvar: SYSVAR_CLOCK,
1724
- stakeAuthority: signer
1725
- });
1726
- const message = kit.pipe(
1727
- kit.createTransactionMessage({ version: config.transactionVersion ?? 0 }),
1728
- (m) => kit.setTransactionMessageFeePayer(signer.address, m),
1729
- (m) => kit.setTransactionMessageLifetimeUsingBlockhash(lifetime, m),
1730
- (m) => kit.appendTransactionMessageInstructions([deactivateIx], m)
1731
- );
1732
- return {
1733
- commitment,
1734
- lifetime,
1735
- message,
1736
- mode,
1737
- signer,
1738
- plan: kit.singleTransactionPlan(message)
1739
- };
1740
- }
1741
- __name(prepareUnstake, "prepareUnstake");
1742
- async function sendPreparedUnstake(prepared, options = {}) {
1743
- if (prepared.mode === "send" && kit.isTransactionSendingSigner(prepared.signer)) {
1744
- const signatureBytes2 = await kit.signAndSendTransactionMessageWithSigners(prepared.message, {
1745
- abortSignal: options.abortSignal,
1746
- minContextSlot: options.minContextSlot
1747
- });
1748
- const base58Decoder2 = codecsStrings.getBase58Decoder();
1749
- return kit.signature(base58Decoder2.decode(signatureBytes2));
1750
- }
1751
- const commitment = options.commitment ?? prepared.commitment;
1752
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
1753
- let latestSignature = null;
1754
- const executor = kit.createTransactionPlanExecutor({
1755
- async executeTransactionMessage(message, config = {}) {
1756
- const signed = await kit.signTransactionMessageWithSigners(message, {
1757
- abortSignal: config.abortSignal ?? options.abortSignal,
1758
- minContextSlot: options.minContextSlot
1759
- });
1760
- const wire = kit.getBase64EncodedWireTransaction(signed);
1761
- const response = await runtime.rpc.sendTransaction(wire, {
1762
- encoding: "base64",
1763
- maxRetries,
1764
- preflightCommitment: commitment,
1765
- skipPreflight: options.skipPreflight
1766
- }).send({ abortSignal: config.abortSignal ?? options.abortSignal });
1767
- latestSignature = kit.signature(response);
1768
- return { transaction: signed };
1769
- }
1770
- });
1771
- await executor(prepared.plan);
1772
- if (!latestSignature) {
1773
- throw new Error("Failed to resolve transaction signature.");
1774
- }
1775
- return latestSignature;
1776
- }
1777
- __name(sendPreparedUnstake, "sendPreparedUnstake");
1778
- async function sendUnstake(config, options) {
1779
- const prepared = await prepareUnstake(config);
1780
- return await sendPreparedUnstake(prepared, options);
1781
- }
1782
- __name(sendUnstake, "sendUnstake");
1783
- async function prepareWithdraw(config) {
1784
- const commitment = config.commitment;
1785
- const lifetime = await resolveLifetime3(runtime, commitment, config.lifetime);
1786
- const { signer, mode } = resolveSigner3(config.authority, commitment);
1787
- const stakeAccountAddress = ensureAddress3(config.stakeAccount);
1788
- const destinationAddress = ensureAddress3(config.destination);
1789
- const amount = toLamportAmount2(config.amount);
1790
- const withdrawIx = stake.getWithdrawInstruction({
1791
- stake: stakeAccountAddress,
1792
- recipient: destinationAddress,
1793
- clockSysvar: SYSVAR_CLOCK,
1794
- stakeHistory: SYSVAR_STAKE_HISTORY,
1795
- withdrawAuthority: signer,
1796
- args: amount
1797
- });
1798
- const message = kit.pipe(
1799
- kit.createTransactionMessage({ version: config.transactionVersion ?? 0 }),
1800
- (m) => kit.setTransactionMessageFeePayer(signer.address, m),
1801
- (m) => kit.setTransactionMessageLifetimeUsingBlockhash(lifetime, m),
1802
- (m) => kit.appendTransactionMessageInstructions([withdrawIx], m)
1803
- );
1804
- return {
1805
- commitment,
1806
- lifetime,
1807
- message,
1808
- mode,
1809
- signer,
1810
- plan: kit.singleTransactionPlan(message)
1811
- };
1812
- }
1813
- __name(prepareWithdraw, "prepareWithdraw");
1814
- async function sendPreparedWithdraw(prepared, options = {}) {
1815
- if (prepared.mode === "send" && kit.isTransactionSendingSigner(prepared.signer)) {
1816
- const signatureBytes2 = await kit.signAndSendTransactionMessageWithSigners(prepared.message, {
1817
- abortSignal: options.abortSignal,
1818
- minContextSlot: options.minContextSlot
1819
- });
1820
- const base58Decoder2 = codecsStrings.getBase58Decoder();
1821
- return kit.signature(base58Decoder2.decode(signatureBytes2));
1822
- }
1823
- const commitment = options.commitment ?? prepared.commitment;
1824
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
1825
- let latestSignature = null;
1826
- const executor = kit.createTransactionPlanExecutor({
1827
- async executeTransactionMessage(message, config = {}) {
1828
- const signed = await kit.signTransactionMessageWithSigners(message, {
1829
- abortSignal: config.abortSignal ?? options.abortSignal,
1830
- minContextSlot: options.minContextSlot
1831
- });
1832
- const wire = kit.getBase64EncodedWireTransaction(signed);
1833
- const response = await runtime.rpc.sendTransaction(wire, {
1834
- encoding: "base64",
1835
- maxRetries,
1836
- preflightCommitment: commitment,
1837
- skipPreflight: options.skipPreflight
1838
- }).send({ abortSignal: config.abortSignal ?? options.abortSignal });
1839
- latestSignature = kit.signature(response);
1840
- return { transaction: signed };
1841
- }
1842
- });
1843
- await executor(prepared.plan);
1844
- if (!latestSignature) {
1845
- throw new Error("Failed to resolve transaction signature.");
1846
- }
1847
- return latestSignature;
1848
- }
1849
- __name(sendPreparedWithdraw, "sendPreparedWithdraw");
1850
- async function sendWithdraw(config, options) {
1851
- const prepared = await prepareWithdraw(config);
1852
- return await sendPreparedWithdraw(prepared, options);
1853
- }
1854
- __name(sendWithdraw, "sendWithdraw");
1855
- async function getStakeAccounts(wallet, validatorId) {
1856
- const walletAddress = typeof wallet === "string" ? wallet : String(wallet);
1857
- const accounts = await runtime.rpc.getProgramAccounts(STAKE_PROGRAM_ID, {
1858
- encoding: "jsonParsed",
1859
- filters: [
1860
- {
1861
- memcmp: {
1862
- offset: 44n,
1863
- bytes: walletAddress,
1864
- encoding: "base58"
1865
- }
1866
- }
1867
- ]
1868
- }).send();
1869
- if (!validatorId) {
1870
- return accounts;
1871
- }
1872
- const validatorIdStr = typeof validatorId === "string" ? validatorId : String(validatorId);
1873
- return accounts.filter((acc) => {
1874
- const data = acc.account?.data;
1875
- if (data && "parsed" in data) {
1876
- const info = data.parsed?.info;
1877
- return info?.stake?.delegation?.voter === validatorIdStr;
1878
- }
1879
- return false;
1880
- });
1881
- }
1882
- __name(getStakeAccounts, "getStakeAccounts");
1883
- return {
1884
- getStakeAccounts,
1885
- prepareStake,
1886
- prepareUnstake,
1887
- prepareWithdraw,
1888
- sendPreparedStake,
1889
- sendPreparedUnstake,
1890
- sendPreparedWithdraw,
1891
- sendStake,
1892
- sendUnstake,
1893
- sendWithdraw
1894
- };
1895
- }
1896
- __name(createStakeHelper, "createStakeHelper");
1897
- function transactionToBase64(tx) {
1898
- if ("messageBytes" in tx) {
1899
- return kit.getBase64EncodedWireTransaction(tx);
1900
- }
1901
- return kit.getBase64EncodedWireTransaction(kit.compileTransaction(tx));
1902
- }
1903
- __name(transactionToBase64, "transactionToBase64");
1904
- async function transactionToBase64WithSigners(tx) {
1905
- if ("messageBytes" in tx) {
1906
- return transactionToBase64(tx);
1907
- }
1908
- const signed = await kit.partiallySignTransactionMessageWithSigners(tx);
1909
- return transactionToBase64(signed);
1910
- }
1911
- __name(transactionToBase64WithSigners, "transactionToBase64WithSigners");
1912
-
1913
- // src/transactions/prepareTransaction.ts
1914
- var DEFAULT_COMPUTE_UNIT_LIMIT_MULTIPLIER = 1.1;
1915
- var DEFAULT_COMPUTE_UNIT_LIMIT = 2e5;
1916
- var MAX_COMPUTE_UNIT_LIMIT = 14e5;
1917
- function isComputeUnitLimitInstruction(instruction) {
1918
- return instruction.programAddress === computeBudget.COMPUTE_BUDGET_PROGRAM_ADDRESS && instruction.data?.[0] === 2;
1919
- }
1920
- __name(isComputeUnitLimitInstruction, "isComputeUnitLimitInstruction");
1921
- function didExceedComputeBudget(error) {
1922
- let current = error;
1923
- while (kit.isSolanaError(current)) {
1924
- if (kit.isSolanaError(current, kit.SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED)) {
1925
- return true;
1926
- }
1927
- current = current.cause;
1928
- }
1929
- return false;
1930
- }
1931
- __name(didExceedComputeBudget, "didExceedComputeBudget");
1932
- async function estimateComputeUnits(rpc, transaction) {
1933
- let target = transaction;
1934
- const hasLifetime = transaction.lifetimeConstraint !== void 0;
1935
- if (!hasLifetime) {
1936
- const latest = await rpc.getLatestBlockhash().send();
1937
- target = kit.setTransactionMessageLifetimeUsingBlockhash(
1938
- latest.value,
1939
- transaction
1940
- );
1941
- }
1942
- const base64Transaction = transactionToBase64(target);
1943
- try {
1944
- const { value } = await rpc.simulateTransaction(base64Transaction, {
1945
- encoding: "base64",
1946
- replaceRecentBlockhash: false,
1947
- sigVerify: false
1948
- }).send();
1949
- return Number(value.unitsConsumed ?? 0) || 0;
1950
- } catch (error) {
1951
- if (didExceedComputeBudget(error)) {
1952
- return MAX_COMPUTE_UNIT_LIMIT;
1953
- }
1954
- throw error;
1955
- }
1956
- }
1957
- __name(estimateComputeUnits, "estimateComputeUnits");
1958
- async function prepareTransaction(config) {
1959
- const multiplier = config.computeUnitLimitMultiplier ?? DEFAULT_COMPUTE_UNIT_LIMIT_MULTIPLIER;
1960
- const shouldResetBlockhash = config.blockhashReset !== false;
1961
- const shouldResetComputeUnits = config.computeUnitLimitReset ?? false;
1962
- let transaction = config.transaction;
1963
- const computeLimitIndex = transaction.instructions.findIndex(isComputeUnitLimitInstruction);
1964
- if (computeLimitIndex === -1 || shouldResetComputeUnits) {
1965
- const unitsFromSimulation = await estimateComputeUnits(config.rpc, transaction);
1966
- const estimatedUnits = unitsFromSimulation ? Math.ceil(unitsFromSimulation * multiplier) : DEFAULT_COMPUTE_UNIT_LIMIT;
1967
- const units = Math.min(
1968
- MAX_COMPUTE_UNIT_LIMIT,
1969
- Math.max(DEFAULT_COMPUTE_UNIT_LIMIT, Math.max(1, estimatedUnits))
1970
- );
1971
- const instruction = computeBudget.getSetComputeUnitLimitInstruction({ units });
1972
- if (computeLimitIndex === -1) {
1973
- transaction = kit.appendTransactionMessageInstruction(instruction, transaction);
1974
- } else {
1975
- const nextInstructions = [...transaction.instructions];
1976
- nextInstructions.splice(computeLimitIndex, 1, instruction);
1977
- transaction = Object.freeze({
1978
- ...transaction,
1979
- instructions: Object.freeze(nextInstructions)
1980
- });
1981
- }
1982
- }
1983
- let transactionHasLifetime = transaction.lifetimeConstraint !== void 0;
1984
- if (shouldResetBlockhash || !transactionHasLifetime) {
1985
- const latest = await config.rpc.getLatestBlockhash().send();
1986
- if (!transactionHasLifetime) {
1987
- transaction = kit.setTransactionMessageLifetimeUsingBlockhash(latest.value, transaction);
1988
- } else if (shouldResetBlockhash) {
1989
- transaction = Object.freeze({
1990
- ...transaction,
1991
- lifetimeConstraint: latest.value
1992
- });
1993
- }
1994
- transactionHasLifetime = true;
1995
- }
1996
- if (config.logRequest) {
1997
- config.logRequest({ base64WireTransaction: transactionToBase64(transaction) });
1998
- }
1999
- return transaction;
2000
- }
2001
- __name(prepareTransaction, "prepareTransaction");
2002
-
2003
- // src/features/transactions.ts
2004
- function toAddress(value) {
2005
- return typeof value === "string" ? kit.address(value) : value;
2006
- }
2007
- __name(toAddress, "toAddress");
2008
- function hasSetComputeUnitLimitInstruction(instructions) {
2009
- return instructions.some(
2010
- (instruction) => kit.isInstructionForProgram(instruction, computeBudget.COMPUTE_BUDGET_PROGRAM_ADDRESS) && kit.isInstructionWithData(instruction) && instruction.data[0] === computeBudget.ComputeBudgetInstruction.SetComputeUnitLimit
2011
- );
2012
- }
2013
- __name(hasSetComputeUnitLimitInstruction, "hasSetComputeUnitLimitInstruction");
2014
- function hasSetComputeUnitPriceInstruction(instructions) {
2015
- return instructions.some(
2016
- (instruction) => kit.isInstructionForProgram(instruction, computeBudget.COMPUTE_BUDGET_PROGRAM_ADDRESS) && kit.isInstructionWithData(instruction) && instruction.data[0] === computeBudget.ComputeBudgetInstruction.SetComputeUnitPrice
2017
- );
2018
- }
2019
- __name(hasSetComputeUnitPriceInstruction, "hasSetComputeUnitPriceInstruction");
2020
- function instructionUsesAddressLookup(instruction) {
2021
- if ("addressTableLookup" in instruction && instruction.addressTableLookup != null) {
2022
- return true;
2023
- }
2024
- if ("addressTableLookups" in instruction && Array.isArray(instruction.addressTableLookups) && instruction.addressTableLookups.length > 0) {
2025
- return true;
2026
- }
2027
- return false;
2028
- }
2029
- __name(instructionUsesAddressLookup, "instructionUsesAddressLookup");
2030
- function resolveVersion(requested, instructions) {
2031
- if (requested && requested !== "auto") {
2032
- return requested;
2033
- }
2034
- return instructions.some(instructionUsesAddressLookup) ? 0 : "legacy";
2035
- }
2036
- __name(resolveVersion, "resolveVersion");
2037
- function normaliseCommitment(request, getFallbackCommitment) {
2038
- return request.commitment ?? getFallbackCommitment();
2039
- }
2040
- __name(normaliseCommitment, "normaliseCommitment");
2041
- function resolveFeePayerAddress(feePayer, authoritySigner) {
2042
- if (!feePayer && !authoritySigner) {
2043
- throw new Error("A fee payer must be provided via `feePayer` or `authority`.");
2044
- }
2045
- if (feePayer && typeof feePayer === "object" && "address" in feePayer) {
2046
- return { address: feePayer.address, signer: feePayer };
2047
- }
2048
- if (feePayer) {
2049
- const address5 = toAddress(feePayer);
2050
- if (authoritySigner && authoritySigner.address === address5) {
2051
- return { address: address5, signer: authoritySigner };
2052
- }
2053
- return { address: address5 };
2054
- }
2055
- if (!authoritySigner) {
2056
- throw new Error("Unable to resolve authority signer for the fee payer.");
2057
- }
2058
- const authorityAddress = authoritySigner.address;
2059
- return { address: authorityAddress, signer: authoritySigner };
2060
- }
2061
- __name(resolveFeePayerAddress, "resolveFeePayerAddress");
2062
- function resolveComputeUnitLimit(request, instructions) {
2063
- const value = request.computeUnitLimit;
2064
- if (value === void 0 || hasSetComputeUnitLimitInstruction(instructions)) {
2065
- return void 0;
2066
- }
2067
- return typeof value === "bigint" ? value : BigInt(Math.floor(value));
2068
- }
2069
- __name(resolveComputeUnitLimit, "resolveComputeUnitLimit");
2070
- function resolveComputeUnitPrice(request, instructions) {
2071
- if (request.computeUnitPrice === void 0 || hasSetComputeUnitPriceInstruction(instructions)) {
2072
- return void 0;
2073
- }
2074
- if (typeof request.computeUnitPrice === "bigint") {
2075
- return request.computeUnitPrice;
2076
- }
2077
- return BigInt(Math.floor(request.computeUnitPrice));
2078
- }
2079
- __name(resolveComputeUnitPrice, "resolveComputeUnitPrice");
2080
- async function createTransactionRecipe(request, context) {
2081
- if (!request.instructions.length) {
2082
- throw new Error("Add at least one instruction before preparing a transaction.");
2083
- }
2084
- const { getFallbackCommitment, runtime } = context;
2085
- request.abortSignal?.throwIfAborted();
2086
- const commitment = normaliseCommitment(request, getFallbackCommitment);
2087
- let authoritySigner;
2088
- let mode = "partial";
2089
- if (request.authority) {
2090
- if (isWalletSession(request.authority)) {
2091
- const { signer, mode: walletMode } = createWalletTransactionSigner(request.authority, { commitment });
2092
- authoritySigner = signer;
2093
- mode = walletMode;
2094
- } else {
2095
- authoritySigner = request.authority;
2096
- mode = resolveSignerMode(authoritySigner);
2097
- }
2098
- }
2099
- const { address: feePayer, signer: feePayerSigner } = resolveFeePayerAddress(request.feePayer, authoritySigner);
2100
- if (mode === "send") {
2101
- if (!feePayerSigner || !kit.isTransactionSendingSigner(feePayerSigner)) {
2102
- mode = "partial";
2103
- }
2104
- }
2105
- const baseInstructions = [...request.instructions];
2106
- const version = resolveVersion(request.version, baseInstructions);
2107
- const lifetime = request.lifetime ?? (await runtime.rpc.getLatestBlockhash({ commitment }).send({ abortSignal: request.abortSignal })).value;
2108
- request.abortSignal?.throwIfAborted();
2109
- const resolvedComputeUnitLimit = resolveComputeUnitLimit(request, baseInstructions);
2110
- const computeUnitPrice = resolveComputeUnitPrice(request, baseInstructions);
2111
- const prefixInstructions = [];
2112
- if (resolvedComputeUnitLimit !== void 0) {
2113
- prefixInstructions.push(computeBudget.getSetComputeUnitLimitInstruction({ units: Number(resolvedComputeUnitLimit) }));
2114
- }
2115
- if (computeUnitPrice !== void 0) {
2116
- prefixInstructions.push(computeBudget.getSetComputeUnitPriceInstruction({ microLamports: Number(computeUnitPrice) }));
2117
- }
2118
- const instructionSequence = [...prefixInstructions, ...baseInstructions];
2119
- const createMessage = /* @__PURE__ */ __name(async () => kit.pipe(
2120
- kit.createTransactionMessage({ version }),
2121
- (message) => feePayerSigner ? kit.setTransactionMessageFeePayerSigner(feePayerSigner, message) : kit.setTransactionMessageFeePayer(feePayer, message),
2122
- (message) => kit.setTransactionMessageLifetimeUsingBlockhash(lifetime, message)
2123
- ), "createMessage");
2124
- return Object.freeze({
2125
- commitment,
2126
- computeUnitLimit: resolvedComputeUnitLimit,
2127
- computeUnitPrice,
2128
- createTransactionMessage: createMessage,
2129
- feePayer,
2130
- instructionPlan: kit.getMessagePackerInstructionPlanFromInstructions(instructionSequence),
2131
- instructions: Object.freeze(baseInstructions),
2132
- lifetime,
2133
- mode,
2134
- version
2135
- });
2136
- }
2137
- __name(createTransactionRecipe, "createTransactionRecipe");
2138
- function assertSingleTransactionPlan(plan) {
2139
- if (plan.kind !== "single") {
2140
- throw new Error("Transaction recipe produced a multi-transaction plan which is not supported.");
2141
- }
2142
- return plan;
2143
- }
2144
- __name(assertSingleTransactionPlan, "assertSingleTransactionPlan");
2145
- function createTransactionHelper(runtime, getFallbackCommitment) {
2146
- async function prepare(request) {
2147
- const recipe = await createTransactionRecipe(request, { getFallbackCommitment, runtime });
2148
- const planner = kit.createTransactionPlanner({
2149
- createTransactionMessage: recipe.createTransactionMessage
2150
- });
2151
- const plan = await planner(recipe.instructionPlan, { abortSignal: request.abortSignal });
2152
- const singlePlan = assertSingleTransactionPlan(plan);
2153
- const prepared = Object.freeze({
2154
- commitment: recipe.commitment,
2155
- computeUnitLimit: recipe.computeUnitLimit,
2156
- computeUnitPrice: recipe.computeUnitPrice,
2157
- feePayer: recipe.feePayer,
2158
- instructions: recipe.instructions,
2159
- lifetime: recipe.lifetime,
2160
- message: singlePlan.message,
2161
- mode: recipe.mode,
2162
- plan,
2163
- version: recipe.version
2164
- });
2165
- return prepared;
2166
- }
2167
- __name(prepare, "prepare");
2168
- async function sign(prepared, options = {}) {
2169
- return await kit.signTransactionMessageWithSigners(prepared.message, {
2170
- abortSignal: options.abortSignal,
2171
- minContextSlot: options.minContextSlot
2172
- });
2173
- }
2174
- __name(sign, "sign");
2175
- async function toWire(prepared, options = {}) {
2176
- const signed = await sign(prepared, options);
2177
- return kit.getBase64EncodedWireTransaction(signed);
2178
- }
2179
- __name(toWire, "toWire");
2180
- async function send(prepared, options = {}) {
2181
- if (!prepared.plan || prepared.mode === "send") {
2182
- return sendDirect(prepared, options);
2183
- }
2184
- return sendWithExecutor(prepared, options);
2185
- }
2186
- __name(send, "send");
2187
- async function sendDirect(prepared, options) {
2188
- const commitment = options.commitment ?? prepared.commitment;
2189
- if (prepared.mode === "send") {
2190
- const signatureBytes2 = await kit.signAndSendTransactionMessageWithSigners(prepared.message, {
2191
- abortSignal: options.abortSignal,
2192
- minContextSlot: options.minContextSlot
2193
- });
2194
- const base58Decoder2 = codecsStrings.getBase58Decoder();
2195
- return kit.signature(base58Decoder2.decode(signatureBytes2));
2196
- }
2197
- const signed = await sign(prepared, {
2198
- abortSignal: options.abortSignal,
2199
- minContextSlot: options.minContextSlot
2200
- });
2201
- const wire = kit.getBase64EncodedWireTransaction(signed);
2202
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
2203
- const response = await runtime.rpc.sendTransaction(wire, {
2204
- encoding: "base64",
2205
- maxRetries,
2206
- preflightCommitment: commitment,
2207
- skipPreflight: options.skipPreflight
2208
- }).send({ abortSignal: options.abortSignal });
2209
- return kit.signature(response);
2210
- }
2211
- __name(sendDirect, "sendDirect");
2212
- async function sendWithExecutor(prepared, options) {
2213
- if (!prepared.plan) {
2214
- return sendDirect(prepared, options);
2215
- }
2216
- const commitment = options.commitment ?? prepared.commitment;
2217
- const maxRetries = options.maxRetries === void 0 ? void 0 : typeof options.maxRetries === "bigint" ? options.maxRetries : BigInt(options.maxRetries);
2218
- let latestSignature = null;
2219
- const executor = kit.createTransactionPlanExecutor({
2220
- async executeTransactionMessage(message, config = {}) {
2221
- const signed = await kit.signTransactionMessageWithSigners(message, {
2222
- abortSignal: config.abortSignal ?? options.abortSignal,
2223
- minContextSlot: options.minContextSlot
2224
- });
2225
- const wire = kit.getBase64EncodedWireTransaction(signed);
2226
- const response = await runtime.rpc.sendTransaction(wire, {
2227
- encoding: "base64",
2228
- maxRetries,
2229
- preflightCommitment: commitment,
2230
- skipPreflight: options.skipPreflight
2231
- }).send({ abortSignal: config.abortSignal ?? options.abortSignal });
2232
- latestSignature = kit.signature(response);
2233
- return { transaction: signed };
2234
- }
2235
- });
2236
- await executor(prepared.plan, { abortSignal: options.abortSignal });
2237
- if (!latestSignature) {
2238
- throw new Error("Failed to resolve transaction signature.");
2239
- }
2240
- return latestSignature;
2241
- }
2242
- __name(sendWithExecutor, "sendWithExecutor");
2243
- async function prepareAndSend(request, options = {}) {
2244
- const { prepareTransaction: overrides, ...rest } = request;
2245
- const prepared = await prepare(rest);
2246
- if (overrides === false) {
2247
- return send(prepared, options);
2248
- }
2249
- const prepareConfig = overrides ?? {};
2250
- const tunedMessage = await prepareTransaction({
2251
- blockhashReset: prepareConfig.blockhashReset ?? false,
2252
- ...prepareConfig,
2253
- rpc: runtime.rpc,
2254
- transaction: prepared.message
2255
- });
2256
- const tunedPrepared = Object.freeze({
2257
- ...prepared,
2258
- message: tunedMessage,
2259
- plan: kit.singleTransactionPlan(tunedMessage)
2260
- });
2261
- return send(tunedPrepared, options);
2262
- }
2263
- __name(prepareAndSend, "prepareAndSend");
2264
- return Object.freeze({
2265
- prepare,
2266
- sign,
2267
- toWire,
2268
- send,
2269
- prepareAndSend
2270
- });
2271
- }
2272
- __name(createTransactionHelper, "createTransactionHelper");
2273
-
2274
- // src/client/createClientHelpers.ts
2275
- function withDefaultCommitment(config, getFallback, baseCommitment) {
2276
- if (config.commitment !== void 0) {
2277
- return config;
2278
- }
2279
- const commitment = baseCommitment ?? getFallback();
2280
- return {
2281
- ...config,
2282
- commitment
2283
- };
2284
- }
2285
- __name(withDefaultCommitment, "withDefaultCommitment");
2286
- function wrapSolTransferHelper(helper, getFallback) {
2287
- return {
2288
- prepareTransfer: /* @__PURE__ */ __name((config) => helper.prepareTransfer(withDefaultCommitment(config, getFallback)), "prepareTransfer"),
2289
- sendPreparedTransfer: helper.sendPreparedTransfer,
2290
- sendTransfer: /* @__PURE__ */ __name((config, options) => helper.sendTransfer(withDefaultCommitment(config, getFallback), options), "sendTransfer")
2291
- };
2292
- }
2293
- __name(wrapSolTransferHelper, "wrapSolTransferHelper");
2294
- function wrapSplTokenHelper(helper, getFallback, baseCommitment) {
2295
- const resolveCommitment = /* @__PURE__ */ __name((commitment) => commitment ?? baseCommitment ?? getFallback(), "resolveCommitment");
2296
- return {
2297
- deriveAssociatedTokenAddress: helper.deriveAssociatedTokenAddress,
2298
- fetchBalance: /* @__PURE__ */ __name((owner, commitment) => helper.fetchBalance(owner, resolveCommitment(commitment)), "fetchBalance"),
2299
- prepareTransfer: /* @__PURE__ */ __name((config) => helper.prepareTransfer(withDefaultCommitment(config, getFallback, baseCommitment)), "prepareTransfer"),
2300
- sendPreparedTransfer: helper.sendPreparedTransfer,
2301
- sendTransfer: /* @__PURE__ */ __name((config, options) => helper.sendTransfer(withDefaultCommitment(config, getFallback, baseCommitment), options), "sendTransfer")
2302
- };
2303
- }
2304
- __name(wrapSplTokenHelper, "wrapSplTokenHelper");
2305
- function wrapStakeHelper(helper, getFallback) {
2306
- return {
2307
- getStakeAccounts: helper.getStakeAccounts,
2308
- prepareStake: /* @__PURE__ */ __name((config) => helper.prepareStake(withDefaultCommitment(config, getFallback)), "prepareStake"),
2309
- prepareUnstake: /* @__PURE__ */ __name((config) => helper.prepareUnstake(withDefaultCommitment(config, getFallback)), "prepareUnstake"),
2310
- prepareWithdraw: /* @__PURE__ */ __name((config) => helper.prepareWithdraw(withDefaultCommitment(config, getFallback)), "prepareWithdraw"),
2311
- sendPreparedStake: helper.sendPreparedStake,
2312
- sendPreparedUnstake: helper.sendPreparedUnstake,
2313
- sendPreparedWithdraw: helper.sendPreparedWithdraw,
2314
- sendStake: /* @__PURE__ */ __name((config, options) => helper.sendStake(withDefaultCommitment(config, getFallback), options), "sendStake"),
2315
- sendUnstake: /* @__PURE__ */ __name((config, options) => helper.sendUnstake(withDefaultCommitment(config, getFallback), options), "sendUnstake"),
2316
- sendWithdraw: /* @__PURE__ */ __name((config, options) => helper.sendWithdraw(withDefaultCommitment(config, getFallback), options), "sendWithdraw")
2317
- };
2318
- }
2319
- __name(wrapStakeHelper, "wrapStakeHelper");
2320
- function normaliseConfigValue(value) {
2321
- if (value === null || value === void 0) {
2322
- return void 0;
2323
- }
2324
- if (typeof value === "string") {
2325
- return value;
2326
- }
2327
- if (typeof value === "object" && "toString" in value) {
2328
- return String(value.toString());
2329
- }
2330
- return JSON.stringify(value);
2331
- }
2332
- __name(normaliseConfigValue, "normaliseConfigValue");
2333
- function serialiseSplConfig(config) {
2334
- return JSON.stringify({
2335
- associatedTokenProgram: normaliseConfigValue(config.associatedTokenProgram),
2336
- commitment: normaliseConfigValue(config.commitment),
2337
- decimals: config.decimals,
2338
- mint: normaliseConfigValue(config.mint),
2339
- tokenProgram: normaliseConfigValue(config.tokenProgram)
2340
- });
2341
- }
2342
- __name(serialiseSplConfig, "serialiseSplConfig");
2343
- function createClientHelpers(runtime, store) {
2344
- const getFallbackCommitment = /* @__PURE__ */ __name(() => store.getState().cluster.commitment, "getFallbackCommitment");
2345
- const splTokenCache = /* @__PURE__ */ new Map();
2346
- let solTransfer;
2347
- let stake;
2348
- let transaction;
2349
- const getSolTransfer = /* @__PURE__ */ __name(() => {
2350
- if (!solTransfer) {
2351
- solTransfer = wrapSolTransferHelper(createSolTransferHelper(runtime), getFallbackCommitment);
2352
- }
2353
- return solTransfer;
2354
- }, "getSolTransfer");
2355
- const getStake = /* @__PURE__ */ __name(() => {
2356
- if (!stake) {
2357
- stake = wrapStakeHelper(createStakeHelper(runtime), getFallbackCommitment);
2358
- }
2359
- return stake;
2360
- }, "getStake");
2361
- const getTransaction = /* @__PURE__ */ __name(() => {
2362
- if (!transaction) {
2363
- transaction = createTransactionHelper(runtime, getFallbackCommitment);
2364
- }
2365
- return transaction;
2366
- }, "getTransaction");
2367
- function getSplTokenHelper(config) {
2368
- const cacheKey = serialiseSplConfig(config);
2369
- const cached = splTokenCache.get(cacheKey);
2370
- if (cached) {
2371
- return cached.scoped;
2372
- }
2373
- const helper = createSplTokenHelper(runtime, config);
2374
- const scoped = wrapSplTokenHelper(helper, getFallbackCommitment, config.commitment);
2375
- splTokenCache.set(cacheKey, {
2376
- baseCommitment: config.commitment,
2377
- scoped
2378
- });
2379
- return scoped;
2380
- }
2381
- __name(getSplTokenHelper, "getSplTokenHelper");
2382
- const prepareTransactionWithRuntime = /* @__PURE__ */ __name((options) => prepareTransaction({
2383
- ...options,
2384
- rpc: runtime.rpc
2385
- }), "prepareTransactionWithRuntime");
2386
- return Object.freeze({
2387
- get solTransfer() {
2388
- return getSolTransfer();
2389
- },
2390
- splToken: getSplTokenHelper,
2391
- get stake() {
2392
- return getStake();
2393
- },
2394
- get transaction() {
2395
- return getTransaction();
2396
- },
2397
- prepareTransaction: prepareTransactionWithRuntime
2398
- });
2399
- }
2400
- __name(createClientHelpers, "createClientHelpers");
2401
- function createClusterStatus() {
2402
- return { status: "idle" };
2403
- }
2404
- __name(createClusterStatus, "createClusterStatus");
2405
- function createInitialClientState(config) {
2406
- const { commitment, endpoint, websocketEndpoint } = config;
2407
- const timestamp = Date.now();
2408
- return deepFreeze({
2409
- accounts: {},
2410
- cluster: {
2411
- commitment,
2412
- endpoint,
2413
- status: createClusterStatus(),
2414
- websocketEndpoint
2415
- },
2416
- lastUpdatedAt: timestamp,
2417
- subscriptions: {
2418
- account: {},
2419
- signature: {}
2420
- },
2421
- transactions: {},
2422
- wallet: { status: "disconnected" }
2423
- });
2424
- }
2425
- __name(createInitialClientState, "createInitialClientState");
2426
- function createClientStore(initialState) {
2427
- return vanilla.createStore(() => initialState);
2428
- }
2429
- __name(createClientStore, "createClientStore");
2430
- function createDefaultClientStore(config) {
2431
- return createClientStore(createInitialClientState(config));
2432
- }
2433
- __name(createDefaultClientStore, "createDefaultClientStore");
2434
-
2435
- // src/client/watchers.ts
2436
- function createWatchers({ logger: inputLogger, runtime, store }) {
2437
- const logger = inputLogger ?? createLogger();
2438
- function setSubscriptionStatus(kind, id, status) {
2439
- store.setState((state) => ({
2440
- ...state,
2441
- lastUpdatedAt: now(),
2442
- subscriptions: {
2443
- ...state.subscriptions,
2444
- [kind]: {
2445
- ...state.subscriptions[kind],
2446
- [id]: status
2447
- }
2448
- }
2449
- }));
2450
- }
2451
- __name(setSubscriptionStatus, "setSubscriptionStatus");
2452
- function onAbort(kind, id) {
2453
- setSubscriptionStatus(kind, id, { status: "inactive" });
2454
- }
2455
- __name(onAbort, "onAbort");
2456
- function createSubscriptionHandle(kind, id, abortController) {
2457
- function abort() {
2458
- abortController.abort();
2459
- onAbort(kind, id);
2460
- }
2461
- __name(abort, "abort");
2462
- return { abort };
2463
- }
2464
- __name(createSubscriptionHandle, "createSubscriptionHandle");
2465
- async function handleAccountNotifications(config, listener, abortController) {
2466
- const commitment = config.commitment ?? store.getState().cluster.commitment;
2467
- const plan = runtime.rpcSubscriptions.accountNotifications(config.address, { commitment });
2468
- const key = config.address.toString();
2469
- setSubscriptionStatus("account", key, { status: "activating" });
2470
- abortController.signal.addEventListener("abort", () => onAbort("account", key));
2471
- try {
2472
- const iterator = await plan.subscribe({ abortSignal: abortController.signal });
2473
- setSubscriptionStatus("account", key, { status: "active" });
2474
- for await (const notification of iterator) {
2475
- const lamports2 = notification.value?.lamports ?? null;
2476
- const slot = notification.context?.slot ?? null;
2477
- const entry = {
2478
- address: config.address,
2479
- data: notification.value?.data,
2480
- error: void 0,
2481
- fetching: false,
2482
- lamports: lamports2,
2483
- lastFetchedAt: now(),
2484
- slot
2485
- };
2486
- listener(entry);
2487
- store.setState((state) => ({
2488
- ...state,
2489
- accounts: {
2490
- ...state.accounts,
2491
- [key]: entry
2492
- },
2493
- lastUpdatedAt: now()
2494
- }));
2495
- }
2496
- } catch (error) {
2497
- if (!abortController.signal.aborted) {
2498
- logger({
2499
- data: { address: key, ...formatError(error) },
2500
- level: "error",
2501
- message: "account subscription failed"
2502
- });
2503
- setSubscriptionStatus("account", key, { error, status: "error" });
2504
- }
2505
- }
2506
- }
2507
- __name(handleAccountNotifications, "handleAccountNotifications");
2508
- function watchAccount(config, listener) {
2509
- const abortController = new AbortController();
2510
- handleAccountNotifications(config, listener, abortController).catch((error) => {
2511
- if (!abortController.signal.aborted) {
2512
- logger({
2513
- data: { address: config.address.toString(), ...formatError(error) },
2514
- level: "error",
2515
- message: "account watcher error"
2516
- });
2517
- }
2518
- });
2519
- return createSubscriptionHandle("account", config.address.toString(), abortController);
2520
- }
2521
- __name(watchAccount, "watchAccount");
2522
- function watchBalance(config, listener) {
2523
- return watchAccount(config, (account) => {
2524
- if (account.lamports !== null) {
2525
- listener(account.lamports);
2526
- }
2527
- });
2528
- }
2529
- __name(watchBalance, "watchBalance");
2530
- async function handleSignatureNotifications(config, listener, abortController) {
2531
- const commitment = config.commitment ?? store.getState().cluster.commitment;
2532
- const plan = runtime.rpcSubscriptions.signatureNotifications(config.signature, {
2533
- commitment,
2534
- enableReceivedNotification: config.enableReceivedNotification
2535
- });
2536
- const key = config.signature.toString();
2537
- setSubscriptionStatus("signature", key, { status: "activating" });
2538
- abortController.signal.addEventListener("abort", () => onAbort("signature", key));
2539
- try {
2540
- const iterator = await plan.subscribe({ abortSignal: abortController.signal });
2541
- setSubscriptionStatus("signature", key, { status: "active" });
2542
- for await (const notification of iterator) {
2543
- listener(notification);
2544
- store.setState((state) => ({
2545
- ...state,
2546
- lastUpdatedAt: now(),
2547
- transactions: {
2548
- ...state.transactions,
2549
- [key]: {
2550
- lastUpdatedAt: now(),
2551
- signature: config.signature,
2552
- status: "waiting"
2553
- }
2554
- }
2555
- }));
2556
- }
2557
- } catch (error) {
2558
- if (!abortController.signal.aborted) {
2559
- logger({
2560
- data: { signature: key, ...formatError(error) },
2561
- level: "error",
2562
- message: "signature subscription failed"
2563
- });
2564
- setSubscriptionStatus("signature", key, { error, status: "error" });
2565
- }
2566
- }
2567
- }
2568
- __name(handleSignatureNotifications, "handleSignatureNotifications");
2569
- function watchSignature(config, listener) {
2570
- const abortController = new AbortController();
2571
- handleSignatureNotifications(config, listener, abortController).catch((error) => {
2572
- if (!abortController.signal.aborted) {
2573
- logger({
2574
- data: { signature: config.signature.toString(), ...formatError(error) },
2575
- level: "error",
2576
- message: "signature watcher error"
2577
- });
2578
- }
2579
- });
2580
- return createSubscriptionHandle("signature", config.signature.toString(), abortController);
2581
- }
2582
- __name(watchSignature, "watchSignature");
2583
- return {
2584
- watchAccount,
2585
- watchBalance,
2586
- watchSignature
2587
- };
2588
- }
2589
- __name(createWatchers, "createWatchers");
2590
-
2591
- // src/client/createClient.ts
2592
- function createClient(config) {
2593
- const hydratedConfig = config.initialState ? applySerializableState(config, config.initialState) : config;
2594
- const resolvedCluster = resolveCluster({
2595
- endpoint: hydratedConfig.rpc ?? hydratedConfig.endpoint,
2596
- moniker: hydratedConfig.cluster,
2597
- websocketEndpoint: hydratedConfig.websocket ?? hydratedConfig.websocketEndpoint
2598
- });
2599
- const commitment = hydratedConfig.commitment ?? "confirmed";
2600
- const initialState = createInitialClientState({
2601
- commitment,
2602
- endpoint: resolvedCluster.endpoint,
2603
- websocketEndpoint: resolvedCluster.websocketEndpoint
2604
- });
2605
- const store = config.createStore ? config.createStore(initialState) : createClientStore(initialState);
2606
- const rpcClient = hydratedConfig.rpcClient ?? createSolanaRpcClient({
2607
- commitment,
2608
- endpoint: resolvedCluster.endpoint,
2609
- websocketEndpoint: resolvedCluster.websocketEndpoint
2610
- });
2611
- const runtime = {
2612
- rpc: rpcClient.rpc,
2613
- rpcSubscriptions: rpcClient.rpcSubscriptions
2614
- };
2615
- const connectors = createWalletRegistry(hydratedConfig.walletConnectors ?? []);
2616
- const logger = createLogger(hydratedConfig.logger);
2617
- const actions = createActions({ connectors, logger, runtime, store });
2618
- const watchers = createWatchers({ logger, runtime, store });
2619
- const helpers = createClientHelpers(runtime, store);
2620
- store.setState((state) => ({
2621
- ...state,
2622
- cluster: {
2623
- ...state.cluster,
2624
- status: { status: "connecting" }
2625
- },
2626
- lastUpdatedAt: now()
2627
- }));
2628
- actions.setCluster(resolvedCluster.endpoint, {
2629
- commitment,
2630
- websocketEndpoint: resolvedCluster.websocketEndpoint
2631
- }).catch(
2632
- (error) => logger({
2633
- data: formatError(error),
2634
- level: "error",
2635
- message: "initial cluster setup failed"
2636
- })
2637
- );
2638
- function destroy() {
2639
- store.setState(() => initialState);
2640
- }
2641
- __name(destroy, "destroy");
2642
- return {
2643
- actions,
2644
- config,
2645
- connectors,
2646
- destroy,
2647
- get helpers() {
2648
- return helpers;
2649
- },
2650
- runtime,
2651
- store,
2652
- get solTransfer() {
2653
- return helpers.solTransfer;
2654
- },
2655
- get SolTransfer() {
2656
- return helpers.solTransfer;
2657
- },
2658
- splToken: helpers.splToken,
2659
- SplToken: helpers.splToken,
2660
- SplHelper: helpers.splToken,
2661
- get stake() {
2662
- return helpers.stake;
2663
- },
2664
- get transaction() {
2665
- return helpers.transaction;
2666
- },
2667
- prepareTransaction: helpers.prepareTransaction,
2668
- watchers
2669
- };
2670
- }
2671
- __name(createClient, "createClient");
2672
- var base58Decoder = codecsStrings.getBase58Decoder();
2673
- var transactionDecoder = transactions.getTransactionDecoder();
2674
- var transactionEncoder = transactions.getTransactionEncoder();
2675
- function deriveConnectorId(wallet) {
2676
- const kebab = wallet.name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
2677
- return `wallet-standard:${kebab}`;
2678
- }
2679
- __name(deriveConnectorId, "deriveConnectorId");
2680
- function getPrimaryAccount(accounts) {
2681
- const primary = accounts[0];
2682
- if (!primary) {
2683
- throw new Error("Wallet returned no accounts.");
2684
- }
2685
- return primary;
2686
- }
2687
- __name(getPrimaryAccount, "getPrimaryAccount");
2688
- function mapCommitment(commitment) {
2689
- if (commitment === "processed" || commitment === "confirmed" || commitment === "finalized") {
2690
- return commitment;
2691
- }
2692
- return void 0;
2693
- }
2694
- __name(mapCommitment, "mapCommitment");
2695
- function toSessionAccount(walletAccount) {
2696
- return {
2697
- address: kit.address(walletAccount.address),
2698
- label: walletAccount.label,
2699
- publicKey: new Uint8Array(walletAccount.publicKey)
2700
- };
2701
- }
2702
- __name(toSessionAccount, "toSessionAccount");
2703
- function getChain(account) {
2704
- const [preferred] = account.chains ?? [];
2705
- return preferred;
2706
- }
2707
- __name(getChain, "getChain");
2708
- async function disconnectWallet2(wallet) {
2709
- const disconnectFeature = wallet.features[features.StandardDisconnect];
2710
- if (disconnectFeature) {
2711
- await disconnectFeature.disconnect();
2712
- }
2713
- }
2714
- __name(disconnectWallet2, "disconnectWallet");
2715
- function createWalletStandardConnector(wallet, options = {}) {
2716
- const metadata = {
2717
- canAutoConnect: options.canAutoConnect ?? Boolean(wallet.features[features.StandardConnect]),
2718
- icon: options.icon ?? wallet.icon,
2719
- id: options.id ?? deriveConnectorId(wallet),
2720
- kind: options.kind ?? "wallet-standard",
2721
- name: options.name ?? wallet.name,
2722
- ready: typeof window !== "undefined"
2723
- };
2724
- async function connect(connectionOptions = {}) {
2725
- const connectFeature = wallet.features[features.StandardConnect];
2726
- const eventsFeature = wallet.features[features.StandardEvents];
2727
- const shouldConnectSilently = Boolean(connectionOptions.autoConnect);
2728
- const allowInteractiveFallback = connectionOptions.allowInteractiveFallback ?? true;
2729
- let walletAccounts = wallet.accounts;
2730
- if (connectFeature) {
2731
- const connectWithMode = /* @__PURE__ */ __name(async (silent) => connectFeature.connect({
2732
- silent
2733
- }), "connectWithMode");
2734
- try {
2735
- const { accounts } = await connectWithMode(shouldConnectSilently);
2736
- if (accounts.length) {
2737
- walletAccounts = accounts;
2738
- }
2739
- } catch (error) {
2740
- if (!shouldConnectSilently || !allowInteractiveFallback) {
2741
- throw error;
2742
- }
2743
- const { accounts } = await connectWithMode(false);
2744
- if (accounts.length) {
2745
- walletAccounts = accounts;
2746
- }
2747
- }
2748
- }
2749
- let currentAccount = getPrimaryAccount(walletAccounts);
2750
- let sessionAccount = toSessionAccount(currentAccount);
2751
- const signMessageFeature = wallet.features[walletStandardFeatures.SolanaSignMessage];
2752
- const signTransactionFeature = wallet.features[walletStandardFeatures.SolanaSignTransaction];
2753
- const signAndSendFeature = wallet.features[walletStandardFeatures.SolanaSignAndSendTransaction];
2754
- const resolvedChain = options.defaultChain ?? getChain(currentAccount);
2755
- const signMessage = signMessageFeature ? async (message) => {
2756
- const [output] = await signMessageFeature.signMessage({
2757
- account: currentAccount,
2758
- message
2759
- });
2760
- return output.signature;
2761
- } : void 0;
2762
- const signTransaction = signTransactionFeature ? async (transaction) => {
2763
- const wireBytes = new Uint8Array(transactionEncoder.encode(transaction));
2764
- const request = resolvedChain ? {
2765
- account: currentAccount,
2766
- chain: resolvedChain,
2767
- transaction: wireBytes
2768
- } : {
2769
- account: currentAccount,
2770
- transaction: wireBytes
2771
- };
2772
- const [output] = await signTransactionFeature.signTransaction(request);
2773
- return transactionDecoder.decode(output.signedTransaction);
2774
- } : void 0;
2775
- const sendTransaction2 = signAndSendFeature ? async (transaction, config) => {
2776
- const wireBytes = new Uint8Array(transactionEncoder.encode(transaction));
2777
- const chain = options.defaultChain ?? getChain(currentAccount) ?? "solana:mainnet-beta";
2778
- const [output] = await signAndSendFeature.signAndSendTransaction({
2779
- account: currentAccount,
2780
- chain,
2781
- options: {
2782
- commitment: mapCommitment(config?.commitment)
2783
- },
2784
- transaction: wireBytes
2785
- });
2786
- return base58Decoder.decode(output.signature);
2787
- } : void 0;
2788
- async function disconnectSession() {
2789
- changeUnsubscribe?.();
2790
- await disconnectWallet2(wallet);
2791
- }
2792
- __name(disconnectSession, "disconnectSession");
2793
- let changeUnsubscribe;
2794
- const onAccountsChanged = eventsFeature ? (listener) => {
2795
- const off = eventsFeature.on("change", ({ accounts }) => {
2796
- if (!accounts) return;
2797
- if (!accounts.length) {
2798
- listener([]);
2799
- return;
2800
- }
2801
- currentAccount = accounts[0];
2802
- sessionAccount = toSessionAccount(currentAccount);
2803
- listener(accounts.map(toSessionAccount));
2804
- });
2805
- return off;
2806
- } : void 0;
2807
- return {
2808
- account: sessionAccount,
2809
- connector: metadata,
2810
- disconnect: disconnectSession,
2811
- onAccountsChanged: onAccountsChanged ? (listener) => {
2812
- changeUnsubscribe = onAccountsChanged(listener);
2813
- return () => {
2814
- changeUnsubscribe?.();
2815
- changeUnsubscribe = void 0;
2816
- };
2817
- } : void 0,
2818
- sendTransaction: sendTransaction2,
2819
- signMessage,
2820
- signTransaction
2821
- };
2822
- }
2823
- __name(connect, "connect");
2824
- async function disconnect() {
2825
- await disconnectWallet2(wallet);
2826
- }
2827
- __name(disconnect, "disconnect");
2828
- function isSupported() {
2829
- return typeof window !== "undefined";
2830
- }
2831
- __name(isSupported, "isSupported");
2832
- return {
2833
- ...metadata,
2834
- connect,
2835
- disconnect,
2836
- isSupported
2837
- };
2838
- }
2839
- __name(createWalletStandardConnector, "createWalletStandardConnector");
2840
- function mapWalletToConnector(wallet, overrides) {
2841
- return createWalletStandardConnector(wallet, overrides?.(wallet));
2842
- }
2843
- __name(mapWalletToConnector, "mapWalletToConnector");
2844
- function getWalletStandardConnectors(options = {}) {
2845
- const { get } = app.getWallets();
2846
- const connectors = get().map((wallet) => mapWalletToConnector(wallet, options.overrides));
2847
- const seen = /* @__PURE__ */ new Set();
2848
- return connectors.filter((connector) => {
2849
- if (seen.has(connector.id)) {
2850
- return false;
2851
- }
2852
- seen.add(connector.id);
2853
- return true;
2854
- });
2855
- }
2856
- __name(getWalletStandardConnectors, "getWalletStandardConnectors");
2857
- function watchWalletStandardConnectors(onChange, options = {}) {
2858
- const { get, on } = app.getWallets();
2859
- const emit = /* @__PURE__ */ __name(() => {
2860
- const connectors = get().map((wallet) => mapWalletToConnector(wallet, options.overrides));
2861
- const seen = /* @__PURE__ */ new Set();
2862
- const deduplicated = connectors.filter((connector) => {
2863
- if (seen.has(connector.id)) {
2864
- return false;
2865
- }
2866
- seen.add(connector.id);
2867
- return true;
2868
- });
2869
- onChange(deduplicated);
2870
- }, "emit");
2871
- emit();
2872
- const offRegister = on("register", emit);
2873
- const offUnregister = on("unregister", emit);
2874
- return () => {
2875
- offRegister();
2876
- offUnregister();
2877
- };
2878
- }
2879
- __name(watchWalletStandardConnectors, "watchWalletStandardConnectors");
2880
-
2881
- // src/wallet/connectors.ts
2882
- function autoDiscover(options = {}) {
2883
- const { get } = app.getWallets();
2884
- const wallets = get().filter((wallet) => options.filter ? options.filter(wallet) : true);
2885
- const connectors = wallets.map((wallet) => createWalletStandardConnector(wallet, options.overrides?.(wallet)));
2886
- const seen = /* @__PURE__ */ new Set();
2887
- return connectors.filter((connector) => {
2888
- if (seen.has(connector.id)) return false;
2889
- seen.add(connector.id);
2890
- return true;
2891
- });
2892
- }
2893
- __name(autoDiscover, "autoDiscover");
2894
- function injected(options) {
2895
- const connector = {
2896
- canAutoConnect: true,
2897
- id: "wallet-standard:injected",
2898
- kind: "wallet-standard",
2899
- name: "Injected Wallet",
2900
- ready: typeof window !== "undefined",
2901
- async connect() {
2902
- const wallets = app.getWallets().get();
2903
- const first = wallets.find((wallet) => features.StandardConnect in wallet.features);
2904
- if (!first) {
2905
- throw new Error("No Wallet Standard wallets available.");
2906
- }
2907
- return createWalletStandardConnector(first, options).connect();
2908
- },
2909
- async disconnect() {
2910
- },
2911
- isSupported() {
2912
- return typeof window !== "undefined";
2913
- }
2914
- };
2915
- return connector;
2916
- }
2917
- __name(injected, "injected");
2918
- function filterByName(name) {
2919
- const lower = name.toLowerCase();
2920
- return (wallet) => wallet.name.toLowerCase().includes(lower);
2921
- }
2922
- __name(filterByName, "filterByName");
2923
- function phantom(options) {
2924
- return autoDiscover({
2925
- filter: filterByName("phantom"),
2926
- overrides: /* @__PURE__ */ __name(() => ({ ...options, id: "wallet-standard:phantom" }), "overrides")
2927
- });
2928
- }
2929
- __name(phantom, "phantom");
2930
- function solflare(options) {
2931
- return autoDiscover({
2932
- filter: filterByName("solflare"),
2933
- overrides: /* @__PURE__ */ __name(() => ({ ...options, id: "wallet-standard:solflare" }), "overrides")
2934
- });
2935
- }
2936
- __name(solflare, "solflare");
2937
- function backpack(options) {
2938
- return autoDiscover({
2939
- filter: filterByName("backpack"),
2940
- overrides: /* @__PURE__ */ __name(() => ({ ...options, id: "wallet-standard:backpack" }), "overrides")
2941
- });
2942
- }
2943
- __name(backpack, "backpack");
2944
-
2945
- // src/client/defaultClient.ts
2946
- function defaultWalletConnectors() {
2947
- return [...phantom(), ...solflare(), ...backpack(), ...autoDiscover()];
2948
- }
2949
- __name(defaultWalletConnectors, "defaultWalletConnectors");
2950
- function normalizeUrl(value) {
2951
- if (!value) return void 0;
2952
- const trimmed = value.trim();
2953
- return trimmed.length ? trimmed : void 0;
2954
- }
2955
- __name(normalizeUrl, "normalizeUrl");
2956
- function resolveClientConfig(config = {}) {
2957
- const {
2958
- cluster,
2959
- endpoint: endpointOverride,
2960
- rpc,
2961
- websocket,
2962
- websocketEndpoint,
2963
- walletConnectors,
2964
- ...passthrough
2965
- } = config;
2966
- const resolvedEndpoint = normalizeUrl(rpc) ?? normalizeUrl(endpointOverride) ?? normalizeUrl(config.endpoint);
2967
- const resolvedCluster = resolveCluster({
2968
- endpoint: resolvedEndpoint,
2969
- moniker: cluster ?? void 0,
2970
- websocketEndpoint: normalizeUrl(websocket ?? websocketEndpoint)
2971
- });
2972
- const resolvedConnectors = walletConnectors === void 0 || walletConnectors === "default" ? defaultWalletConnectors() : walletConnectors;
2973
- return {
2974
- ...passthrough,
2975
- endpoint: resolvedCluster.endpoint,
2976
- websocketEndpoint: resolvedCluster.websocketEndpoint,
2977
- walletConnectors: resolvedConnectors
2978
- };
2979
- }
2980
- __name(resolveClientConfig, "resolveClientConfig");
2981
- function createDefaultClient(config = {}) {
2982
- return createClient(resolveClientConfig(config));
2983
- }
2984
- __name(createDefaultClient, "createDefaultClient");
2985
-
2986
- // src/state/asyncState.ts
2987
- function createInitialAsyncState() {
2988
- return { status: "idle" };
2989
- }
2990
- __name(createInitialAsyncState, "createInitialAsyncState");
2991
- function createAsyncState(status, payload = {}) {
2992
- return {
2993
- data: payload.data,
2994
- error: payload.error,
2995
- status
2996
- };
2997
- }
2998
- __name(createAsyncState, "createAsyncState");
2999
-
3000
- // src/controllers/solTransferController.ts
3001
- function ensureAuthority(input, resolveDefault) {
3002
- const authority = input.authority ?? resolveDefault?.();
3003
- if (!authority) {
3004
- throw new Error("Connect a wallet or supply an `authority` before sending SOL transfers.");
3005
- }
3006
- return {
3007
- ...input,
3008
- authority
3009
- };
3010
- }
3011
- __name(ensureAuthority, "ensureAuthority");
3012
- function createSolTransferController(config) {
3013
- const listeners = /* @__PURE__ */ new Set();
3014
- const helper = config.helper;
3015
- const authorityProvider = config.authorityProvider;
3016
- let state = createInitialAsyncState();
3017
- function notify() {
3018
- for (const listener of listeners) {
3019
- listener();
3020
- }
3021
- }
3022
- __name(notify, "notify");
3023
- function setState(next) {
3024
- state = next;
3025
- notify();
3026
- }
3027
- __name(setState, "setState");
3028
- async function send(config2, options) {
3029
- const request = ensureAuthority(config2, authorityProvider);
3030
- setState(createAsyncState("loading"));
3031
- try {
3032
- const signature5 = await helper.sendTransfer(request, options);
3033
- setState(createAsyncState("success", { data: signature5 }));
3034
- return signature5;
3035
- } catch (error) {
3036
- setState(createAsyncState("error", { error }));
3037
- throw error;
3038
- }
3039
- }
3040
- __name(send, "send");
3041
- function subscribe(listener) {
3042
- listeners.add(listener);
3043
- return () => {
3044
- listeners.delete(listener);
3045
- };
3046
- }
3047
- __name(subscribe, "subscribe");
3048
- function reset() {
3049
- setState(createInitialAsyncState());
3050
- }
3051
- __name(reset, "reset");
3052
- return {
3053
- getHelper: /* @__PURE__ */ __name(() => helper, "getHelper"),
3054
- getState: /* @__PURE__ */ __name(() => state, "getState"),
3055
- reset,
3056
- send,
3057
- subscribe
3058
- };
3059
- }
3060
- __name(createSolTransferController, "createSolTransferController");
3061
-
3062
- // src/controllers/splTransferController.ts
3063
- function ensureTransferConfig(input, resolveAuthority, resolveSourceOwner) {
3064
- const authority = input.authority ?? resolveAuthority?.();
3065
- if (!authority) {
3066
- throw new Error("Connect a wallet or supply an `authority` before sending SPL tokens.");
3067
- }
3068
- const sourceOwner = input.sourceOwner ?? resolveSourceOwner?.();
3069
- if (!sourceOwner) {
3070
- throw new Error("Unable to resolve a source owner for the SPL token transfer.");
3071
- }
3072
- return {
3073
- ...input,
3074
- authority,
3075
- sourceOwner
3076
- };
3077
- }
3078
- __name(ensureTransferConfig, "ensureTransferConfig");
3079
- function createSplTransferController(config) {
3080
- const helper = config.helper;
3081
- const authorityProvider = config.authorityProvider;
3082
- const sourceOwnerProvider = config.sourceOwnerProvider;
3083
- const listeners = /* @__PURE__ */ new Set();
3084
- let state = createInitialAsyncState();
3085
- function notify() {
3086
- for (const listener of listeners) {
3087
- listener();
3088
- }
3089
- }
3090
- __name(notify, "notify");
3091
- function setState(next) {
3092
- state = next;
3093
- notify();
3094
- }
3095
- __name(setState, "setState");
3096
- async function send(config2, options) {
3097
- const resolvedConfig = ensureTransferConfig(
3098
- config2,
3099
- config2.authority ? void 0 : authorityProvider,
3100
- config2.sourceOwner ? void 0 : sourceOwnerProvider
3101
- );
3102
- setState(createAsyncState("loading"));
3103
- try {
3104
- const signature5 = await helper.sendTransfer(resolvedConfig, options);
3105
- setState(createAsyncState("success", { data: signature5 }));
3106
- return signature5;
3107
- } catch (error) {
3108
- setState(createAsyncState("error", { error }));
3109
- throw error;
3110
- }
3111
- }
3112
- __name(send, "send");
3113
- function subscribe(listener) {
3114
- listeners.add(listener);
3115
- return () => {
3116
- listeners.delete(listener);
3117
- };
3118
- }
3119
- __name(subscribe, "subscribe");
3120
- function reset() {
3121
- setState(createInitialAsyncState());
3122
- }
3123
- __name(reset, "reset");
3124
- return {
3125
- getHelper: /* @__PURE__ */ __name(() => helper, "getHelper"),
3126
- getState: /* @__PURE__ */ __name(() => state, "getState"),
3127
- reset,
3128
- send,
3129
- subscribe
3130
- };
3131
- }
3132
- __name(createSplTransferController, "createSplTransferController");
3133
-
3134
- // src/controllers/stakeController.ts
3135
- function ensureAuthority2(input, resolveDefault) {
3136
- const authority = input.authority ?? resolveDefault?.();
3137
- if (!authority) {
3138
- throw new Error("Connect a wallet or supply an `authority` before staking SOL.");
3139
- }
3140
- return {
3141
- ...input,
3142
- authority
3143
- };
3144
- }
3145
- __name(ensureAuthority2, "ensureAuthority");
3146
- function ensureUnstakeAuthority(input, resolveDefault) {
3147
- const authority = input.authority ?? resolveDefault?.();
3148
- if (!authority) {
3149
- throw new Error("Connect a wallet or supply an `authority` before unstaking SOL.");
3150
- }
3151
- return {
3152
- ...input,
3153
- authority
3154
- };
3155
- }
3156
- __name(ensureUnstakeAuthority, "ensureUnstakeAuthority");
3157
- function ensureWithdrawAuthority(input, resolveDefault) {
3158
- const authority = input.authority ?? resolveDefault?.();
3159
- if (!authority) {
3160
- throw new Error("Connect a wallet or supply an `authority` before withdrawing SOL.");
3161
- }
3162
- return {
3163
- ...input,
3164
- authority
3165
- };
3166
- }
3167
- __name(ensureWithdrawAuthority, "ensureWithdrawAuthority");
3168
- function createStakeController(config) {
3169
- const listeners = /* @__PURE__ */ new Set();
3170
- const unstakeListeners = /* @__PURE__ */ new Set();
3171
- const withdrawListeners = /* @__PURE__ */ new Set();
3172
- const helper = config.helper;
3173
- const authorityProvider = config.authorityProvider;
3174
- let state = createInitialAsyncState();
3175
- let unstakeState = createInitialAsyncState();
3176
- let withdrawState = createInitialAsyncState();
3177
- function notify() {
3178
- for (const listener of listeners) {
3179
- listener();
3180
- }
3181
- }
3182
- __name(notify, "notify");
3183
- function notifyUnstake() {
3184
- for (const listener of unstakeListeners) {
3185
- listener();
3186
- }
3187
- }
3188
- __name(notifyUnstake, "notifyUnstake");
3189
- function notifyWithdraw() {
3190
- for (const listener of withdrawListeners) {
3191
- listener();
3192
- }
3193
- }
3194
- __name(notifyWithdraw, "notifyWithdraw");
3195
- function setState(next) {
3196
- state = next;
3197
- notify();
3198
- }
3199
- __name(setState, "setState");
3200
- function setUnstakeState(next) {
3201
- unstakeState = next;
3202
- notifyUnstake();
3203
- }
3204
- __name(setUnstakeState, "setUnstakeState");
3205
- function setWithdrawState(next) {
3206
- withdrawState = next;
3207
- notifyWithdraw();
3208
- }
3209
- __name(setWithdrawState, "setWithdrawState");
3210
- async function stake(config2, options) {
3211
- const request = ensureAuthority2(config2, authorityProvider);
3212
- setState(createAsyncState("loading"));
3213
- try {
3214
- const signature5 = await helper.sendStake(request, options);
3215
- setState(createAsyncState("success", { data: signature5 }));
3216
- return signature5;
3217
- } catch (error) {
3218
- setState(createAsyncState("error", { error }));
3219
- throw error;
3220
- }
3221
- }
3222
- __name(stake, "stake");
3223
- async function unstake(config2, options) {
3224
- const request = ensureUnstakeAuthority(config2, authorityProvider);
3225
- setUnstakeState(createAsyncState("loading"));
3226
- try {
3227
- const signature5 = await helper.sendUnstake(request, options);
3228
- setUnstakeState(createAsyncState("success", { data: signature5 }));
3229
- return signature5;
3230
- } catch (error) {
3231
- setUnstakeState(createAsyncState("error", { error }));
3232
- throw error;
3233
- }
3234
- }
3235
- __name(unstake, "unstake");
3236
- async function withdraw(config2, options) {
3237
- const request = ensureWithdrawAuthority(config2, authorityProvider);
3238
- setWithdrawState(createAsyncState("loading"));
3239
- try {
3240
- const signature5 = await helper.sendWithdraw(request, options);
3241
- setWithdrawState(createAsyncState("success", { data: signature5 }));
3242
- return signature5;
3243
- } catch (error) {
3244
- setWithdrawState(createAsyncState("error", { error }));
3245
- throw error;
3246
- }
3247
- }
3248
- __name(withdraw, "withdraw");
3249
- function subscribe(listener) {
3250
- listeners.add(listener);
3251
- return () => {
3252
- listeners.delete(listener);
3253
- };
3254
- }
3255
- __name(subscribe, "subscribe");
3256
- function subscribeUnstake(listener) {
3257
- unstakeListeners.add(listener);
3258
- return () => {
3259
- unstakeListeners.delete(listener);
3260
- };
3261
- }
3262
- __name(subscribeUnstake, "subscribeUnstake");
3263
- function subscribeWithdraw(listener) {
3264
- withdrawListeners.add(listener);
3265
- return () => {
3266
- withdrawListeners.delete(listener);
3267
- };
3268
- }
3269
- __name(subscribeWithdraw, "subscribeWithdraw");
3270
- function reset() {
3271
- setState(createInitialAsyncState());
3272
- }
3273
- __name(reset, "reset");
3274
- function resetUnstake() {
3275
- setUnstakeState(createInitialAsyncState());
3276
- }
3277
- __name(resetUnstake, "resetUnstake");
3278
- function resetWithdraw() {
3279
- setWithdrawState(createInitialAsyncState());
3280
- }
3281
- __name(resetWithdraw, "resetWithdraw");
3282
- return {
3283
- getHelper: /* @__PURE__ */ __name(() => helper, "getHelper"),
3284
- getState: /* @__PURE__ */ __name(() => state, "getState"),
3285
- getUnstakeState: /* @__PURE__ */ __name(() => unstakeState, "getUnstakeState"),
3286
- getWithdrawState: /* @__PURE__ */ __name(() => withdrawState, "getWithdrawState"),
3287
- reset,
3288
- resetUnstake,
3289
- resetWithdraw,
3290
- stake,
3291
- unstake,
3292
- withdraw,
3293
- subscribe,
3294
- subscribeUnstake,
3295
- subscribeWithdraw
3296
- };
3297
- }
3298
- __name(createStakeController, "createStakeController");
3299
-
3300
- // src/serialization/json.ts
3301
- function bigintToJson(value) {
3302
- return value.toString();
3303
- }
3304
- __name(bigintToJson, "bigintToJson");
3305
- function bigintFromJson(value) {
3306
- return toBigint2(value, "bigint");
3307
- }
3308
- __name(bigintFromJson, "bigintFromJson");
3309
- function lamportsToJson(value) {
3310
- return value.toString();
3311
- }
3312
- __name(lamportsToJson, "lamportsToJson");
3313
- function lamportsFromJson(value) {
3314
- return lamports(value, "lamports");
3315
- }
3316
- __name(lamportsFromJson, "lamportsFromJson");
3317
- var COMMITMENT_PRIORITY = {
3318
- processed: 0,
3319
- confirmed: 1,
3320
- finalized: 2
3321
- };
3322
- var SIGNATURE_STATUS_TIMEOUT_MS = 2e4;
3323
- function normalizeSignature(input) {
3324
- if (!input) {
3325
- return void 0;
3326
- }
3327
- return typeof input === "string" ? kit.signature(input) : input;
3328
- }
3329
- __name(normalizeSignature, "normalizeSignature");
3330
- function deriveConfirmationStatus(status) {
3331
- if (!status) {
3332
- return null;
3333
- }
3334
- if (status.confirmationStatus === "processed" || status.confirmationStatus === "confirmed" || status.confirmationStatus === "finalized") {
3335
- return status.confirmationStatus;
3336
- }
3337
- if (status.confirmations === null) {
3338
- return "finalized";
3339
- }
3340
- if (typeof status.confirmations === "number" && status.confirmations > 0) {
3341
- return "confirmed";
3342
- }
3343
- return "processed";
3344
- }
3345
- __name(deriveConfirmationStatus, "deriveConfirmationStatus");
3346
- function confirmationMeetsCommitment(confirmation, target) {
3347
- if (!confirmation) {
3348
- return false;
3349
- }
3350
- return COMMITMENT_PRIORITY[confirmation] >= COMMITMENT_PRIORITY[target];
3351
- }
3352
- __name(confirmationMeetsCommitment, "confirmationMeetsCommitment");
3353
- var MEMO_PROGRAM_ADDRESS = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
3354
- function ensureNonMemoInstructionIndex(instructions) {
3355
- const index = instructions.findIndex((instruction) => instruction.programAddress !== MEMO_PROGRAM_ADDRESS);
3356
- if (instructions.length === 0 || index === -1) {
3357
- throw new kit.SolanaError(kit.SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR, {
3358
- cause: "At least one non-memo instruction is required.",
3359
- index: instructions.length || index
3360
- });
3361
- }
3362
- return index;
3363
- }
3364
- __name(ensureNonMemoInstructionIndex, "ensureNonMemoInstructionIndex");
3365
- function insertReferenceKey(reference, transaction) {
3366
- return insertReferenceKeys([reference], transaction);
3367
- }
3368
- __name(insertReferenceKey, "insertReferenceKey");
3369
- function insertReferenceKeys(references, transaction) {
3370
- const index = ensureNonMemoInstructionIndex(transaction.instructions);
3371
- const targetInstruction = transaction.instructions[index];
3372
- const accounts = [
3373
- ...targetInstruction.accounts ?? [],
3374
- ...references.map((address5) => ({ address: address5, role: kit.AccountRole.READONLY }))
3375
- ];
3376
- const updatedInstructions = [...transaction.instructions];
3377
- updatedInstructions.splice(index, 1, { ...targetInstruction, accounts });
3378
- return Object.freeze({
3379
- ...transaction,
3380
- instructions: Object.freeze(updatedInstructions)
3381
- });
3382
- }
3383
- __name(insertReferenceKeys, "insertReferenceKeys");
3384
-
3385
- // src/transactions/transactionPoolController.ts
3386
- function createStore2(initial) {
3387
- let snapshot = initial;
3388
- const listeners = /* @__PURE__ */ new Set();
3389
- return {
3390
- getSnapshot: /* @__PURE__ */ __name(() => snapshot, "getSnapshot"),
3391
- setSnapshot(next) {
3392
- snapshot = next;
3393
- for (const listener of listeners) {
3394
- listener();
3395
- }
3396
- },
3397
- subscribe(listener) {
3398
- listeners.add(listener);
3399
- return () => {
3400
- listeners.delete(listener);
3401
- };
3402
- }
3403
- };
3404
- }
3405
- __name(createStore2, "createStore");
3406
- function freezeInstructions(list) {
3407
- return Object.freeze([...list]);
3408
- }
3409
- __name(freezeInstructions, "freezeInstructions");
3410
- function createTransactionPoolController(config) {
3411
- const helper = config.helper;
3412
- const initialInstructions = freezeInstructions(config.initialInstructions ?? []);
3413
- const blockhashMaxAgeMs = config.blockhashMaxAgeMs ?? 3e4;
3414
- let latestBlockhashCache;
3415
- const instructionsStore = createStore2(initialInstructions);
3416
- const preparedStore = createStore2(null);
3417
- const prepareStateStore = createStore2(
3418
- createInitialAsyncState()
3419
- );
3420
- const sendStateStore = createStore2(
3421
- createInitialAsyncState()
3422
- );
3423
- function resetDerivedState() {
3424
- preparedStore.setSnapshot(null);
3425
- prepareStateStore.setSnapshot(createInitialAsyncState());
3426
- sendStateStore.setSnapshot(createInitialAsyncState());
3427
- }
3428
- __name(resetDerivedState, "resetDerivedState");
3429
- function commitInstructions(next) {
3430
- instructionsStore.setSnapshot(freezeInstructions(next));
3431
- resetDerivedState();
3432
- }
3433
- __name(commitInstructions, "commitInstructions");
3434
- function addInstruction(instruction) {
3435
- const next = [...instructionsStore.getSnapshot(), instruction];
3436
- commitInstructions(next);
3437
- }
3438
- __name(addInstruction, "addInstruction");
3439
- function addInstructions(instructionSet) {
3440
- if (!instructionSet.length) {
3441
- return;
3442
- }
3443
- const next = [...instructionsStore.getSnapshot(), ...instructionSet];
3444
- commitInstructions(next);
3445
- }
3446
- __name(addInstructions, "addInstructions");
3447
- function replaceInstructions(instructionSet) {
3448
- commitInstructions(instructionSet);
3449
- }
3450
- __name(replaceInstructions, "replaceInstructions");
3451
- function clearInstructions() {
3452
- commitInstructions([]);
3453
- }
3454
- __name(clearInstructions, "clearInstructions");
3455
- function removeInstruction(index) {
3456
- const current = instructionsStore.getSnapshot();
3457
- if (index < 0 || index >= current.length) {
3458
- return;
3459
- }
3460
- const next = current.filter((_, ii) => ii !== index);
3461
- commitInstructions(next);
3462
- }
3463
- __name(removeInstruction, "removeInstruction");
3464
- function reset() {
3465
- commitInstructions(initialInstructions);
3466
- }
3467
- __name(reset, "reset");
3468
- function ensureInstructions(instructionList) {
3469
- if (!instructionList.length) {
3470
- throw new Error("Add at least one instruction before preparing a transaction.");
3471
- }
3472
- }
3473
- __name(ensureInstructions, "ensureInstructions");
3474
- function resolveCachedLifetime() {
3475
- if (!latestBlockhashCache) {
3476
- return void 0;
3477
- }
3478
- if (Date.now() - latestBlockhashCache.updatedAt > blockhashMaxAgeMs) {
3479
- return void 0;
3480
- }
3481
- return latestBlockhashCache.value;
3482
- }
3483
- __name(resolveCachedLifetime, "resolveCachedLifetime");
3484
- async function prepare(options = {}) {
3485
- const { instructions: overrideInstructions, ...rest } = options;
3486
- const nextInstructions = overrideInstructions ?? instructionsStore.getSnapshot();
3487
- ensureInstructions(nextInstructions);
3488
- prepareStateStore.setSnapshot(createAsyncState("loading"));
3489
- try {
3490
- const cachedLifetime = rest.lifetime ?? resolveCachedLifetime();
3491
- const restWithLifetime = cachedLifetime && !rest.lifetime ? { ...rest, lifetime: cachedLifetime } : rest;
3492
- const prepared = await helper.prepare({
3493
- ...restWithLifetime,
3494
- instructions: nextInstructions
3495
- });
3496
- preparedStore.setSnapshot(prepared);
3497
- prepareStateStore.setSnapshot(createAsyncState("success", { data: prepared }));
3498
- return prepared;
3499
- } catch (error) {
3500
- prepareStateStore.setSnapshot(createAsyncState("error", { error }));
3501
- throw error;
3502
- }
3503
- }
3504
- __name(prepare, "prepare");
3505
- function resolvePrepared(override) {
3506
- const target = override ?? preparedStore.getSnapshot();
3507
- if (!target) {
3508
- throw new Error("Prepare a transaction before sending.");
3509
- }
3510
- return target;
3511
- }
3512
- __name(resolvePrepared, "resolvePrepared");
3513
- function resolveLifetimeOptions(options) {
3514
- if (options.lifetime) {
3515
- return options;
3516
- }
3517
- const cachedLifetime = resolveCachedLifetime();
3518
- if (!cachedLifetime) {
3519
- return options;
3520
- }
3521
- return { ...options, lifetime: cachedLifetime };
3522
- }
3523
- __name(resolveLifetimeOptions, "resolveLifetimeOptions");
3524
- async function send(options = {}) {
3525
- const { prepared: overridePrepared, ...rest } = options;
3526
- const target = resolvePrepared(overridePrepared);
3527
- sendStateStore.setSnapshot(createAsyncState("loading"));
3528
- try {
3529
- const signature5 = await helper.send(target, rest);
3530
- sendStateStore.setSnapshot(createAsyncState("success", { data: signature5 }));
3531
- return signature5;
3532
- } catch (error) {
3533
- sendStateStore.setSnapshot(createAsyncState("error", { error }));
3534
- throw error;
3535
- }
3536
- }
3537
- __name(send, "send");
3538
- async function prepareAndSend(request = {}, sendOptions) {
3539
- const { instructions: overrideInstructions, ...rest } = request;
3540
- const nextInstructions = overrideInstructions ?? instructionsStore.getSnapshot();
3541
- ensureInstructions(nextInstructions);
3542
- sendStateStore.setSnapshot(createAsyncState("loading"));
3543
- try {
3544
- const restWithLifetime = resolveLifetimeOptions(rest);
3545
- const signature5 = await helper.prepareAndSend(
3546
- {
3547
- ...restWithLifetime,
3548
- instructions: nextInstructions
3549
- },
3550
- sendOptions
3551
- );
3552
- sendStateStore.setSnapshot(createAsyncState("success", { data: signature5 }));
3553
- return signature5;
3554
- } catch (error) {
3555
- sendStateStore.setSnapshot(createAsyncState("error", { error }));
3556
- throw error;
3557
- }
3558
- }
3559
- __name(prepareAndSend, "prepareAndSend");
3560
- function sign(options = {}) {
3561
- const { prepared: overridePrepared, ...rest } = options;
3562
- const target = resolvePrepared(overridePrepared);
3563
- return helper.sign(target, rest);
3564
- }
3565
- __name(sign, "sign");
3566
- function toWire(options = {}) {
3567
- const { prepared: overridePrepared, ...rest } = options;
3568
- const target = resolvePrepared(overridePrepared);
3569
- return helper.toWire(target, rest);
3570
- }
3571
- __name(toWire, "toWire");
3572
- function subscribeInstructions(listener) {
3573
- return instructionsStore.subscribe(listener);
3574
- }
3575
- __name(subscribeInstructions, "subscribeInstructions");
3576
- function subscribePrepared(listener) {
3577
- return preparedStore.subscribe(listener);
3578
- }
3579
- __name(subscribePrepared, "subscribePrepared");
3580
- function subscribePrepareState(listener) {
3581
- return prepareStateStore.subscribe(listener);
3582
- }
3583
- __name(subscribePrepareState, "subscribePrepareState");
3584
- function subscribeSendState(listener) {
3585
- return sendStateStore.subscribe(listener);
3586
- }
3587
- __name(subscribeSendState, "subscribeSendState");
3588
- function setLatestBlockhashCache(cache) {
3589
- latestBlockhashCache = cache;
3590
- }
3591
- __name(setLatestBlockhashCache, "setLatestBlockhashCache");
3592
- return {
3593
- addInstruction,
3594
- addInstructions,
3595
- clearInstructions,
3596
- get helper() {
3597
- return helper;
3598
- },
3599
- getInstructions: instructionsStore.getSnapshot,
3600
- getPrepareState: prepareStateStore.getSnapshot,
3601
- getPrepared: preparedStore.getSnapshot,
3602
- getSendState: sendStateStore.getSnapshot,
3603
- getLatestBlockhashCache: /* @__PURE__ */ __name(() => latestBlockhashCache, "getLatestBlockhashCache"),
3604
- prepare,
3605
- prepareAndSend,
3606
- removeInstruction,
3607
- replaceInstructions,
3608
- reset,
3609
- send,
3610
- setLatestBlockhashCache,
3611
- sign,
3612
- subscribeInstructions,
3613
- subscribePrepareState,
3614
- subscribePrepared,
3615
- subscribeSendState,
3616
- toWire
3617
- };
3618
- }
3619
- __name(createTransactionPoolController, "createTransactionPoolController");
3620
- function toAddress2(addressLike) {
3621
- return typeof addressLike === "string" ? kit.address(addressLike) : addressLike;
3622
- }
3623
- __name(toAddress2, "toAddress");
3624
- function toAddressString(addressLike) {
3625
- return toAddress2(addressLike).toString();
3626
- }
3627
- __name(toAddressString, "toAddressString");
3628
-
3629
- // src/utils/stableStringify.ts
3630
- function stableStringify(value) {
3631
- const result = JSON.stringify(value, (_key, candidate) => {
3632
- if (typeof candidate === "bigint") {
3633
- return { __type: "bigint", value: candidate.toString() };
3634
- }
3635
- if (candidate instanceof Uint8Array) {
3636
- return Array.from(candidate);
3637
- }
3638
- return candidate;
3639
- });
3640
- return result ?? "undefined";
3641
- }
3642
- __name(stableStringify, "stableStringify");
3643
-
3644
- exports.LAMPORTS_PER_SOL = LAMPORTS_PER_SOL;
3645
- exports.SIGNATURE_STATUS_TIMEOUT_MS = SIGNATURE_STATUS_TIMEOUT_MS;
3646
- exports.applyRatio = applyRatio;
3647
- exports.applySerializableState = applySerializableState;
3648
- exports.assertDecimals = assertDecimals;
3649
- exports.assertNonNegative = assertNonNegative;
3650
- exports.autoDiscover = autoDiscover;
3651
- exports.backpack = backpack;
3652
- exports.bigintFromJson = bigintFromJson;
3653
- exports.bigintToJson = bigintToJson;
3654
- exports.checkedAdd = checkedAdd;
3655
- exports.checkedDivide = checkedDivide;
3656
- exports.checkedMultiply = checkedMultiply;
3657
- exports.checkedSubtract = checkedSubtract;
3658
- exports.confirmationMeetsCommitment = confirmationMeetsCommitment;
3659
- exports.connectWallet = connectWallet;
3660
- exports.createAsyncState = createAsyncState;
3661
- exports.createClient = createClient;
3662
- exports.createClientStore = createClientStore;
3663
- exports.createDefaultClient = createDefaultClient;
3664
- exports.createDefaultClientStore = createDefaultClientStore;
3665
- exports.createInitialAsyncState = createInitialAsyncState;
3666
- exports.createInitialClientState = createInitialClientState;
3667
- exports.createRatio = createRatio;
3668
- exports.createSolTransferController = createSolTransferController;
3669
- exports.createSolTransferHelper = createSolTransferHelper;
3670
- exports.createSolanaRpcClient = createSolanaRpcClient;
3671
- exports.createSplTokenHelper = createSplTokenHelper;
3672
- exports.createSplTransferController = createSplTransferController;
3673
- exports.createStakeController = createStakeController;
3674
- exports.createStakeHelper = createStakeHelper;
3675
- exports.createTokenAmount = createTokenAmount;
3676
- exports.createTransactionHelper = createTransactionHelper;
3677
- exports.createTransactionPoolController = createTransactionPoolController;
3678
- exports.createTransactionRecipe = createTransactionRecipe;
3679
- exports.createWalletRegistry = createWalletRegistry;
3680
- exports.createWalletStandardConnector = createWalletStandardConnector;
3681
- exports.defaultWalletConnectors = defaultWalletConnectors;
3682
- exports.deriveConfirmationStatus = deriveConfirmationStatus;
3683
- exports.deserializeSolanaState = deserializeSolanaState;
3684
- exports.disconnectWallet = disconnectWallet;
3685
- exports.fetchAccount = fetchAccount;
3686
- exports.fetchBalance = fetchBalance;
3687
- exports.fetchLookupTable = fetchLookupTable;
3688
- exports.fetchLookupTables = fetchLookupTables;
3689
- exports.fetchNonceAccount = fetchNonceAccount;
3690
- exports.getInitialSerializableState = getInitialSerializableState;
3691
- exports.getWalletStandardConnectors = getWalletStandardConnectors;
3692
- exports.injected = injected;
3693
- exports.insertReferenceKey = insertReferenceKey;
3694
- exports.insertReferenceKeys = insertReferenceKeys;
3695
- exports.lamports = lamports;
3696
- exports.lamportsFromJson = lamportsFromJson;
3697
- exports.lamportsFromSol = lamportsFromSol;
3698
- exports.lamportsMath = lamportsMath;
3699
- exports.lamportsToJson = lamportsToJson;
3700
- exports.lamportsToSolString = lamportsToSolString;
3701
- exports.normalizeSignature = normalizeSignature;
3702
- exports.phantom = phantom;
3703
- exports.pow10 = pow10;
3704
- exports.prepareTransaction = prepareTransaction;
3705
- exports.requestAirdrop = requestAirdrop;
3706
- exports.resolveClientConfig = resolveClientConfig;
3707
- exports.resolveCluster = resolveCluster;
3708
- exports.sendTransaction = sendTransaction;
3709
- exports.serializeSolanaState = serializeSolanaState;
3710
- exports.setCluster = setCluster;
3711
- exports.solflare = solflare;
3712
- exports.stableStringify = stableStringify;
3713
- exports.subscribeSolanaState = subscribeSolanaState;
3714
- exports.toAddress = toAddress2;
3715
- exports.toAddressString = toAddressString;
3716
- exports.toBigint = toBigint2;
3717
- exports.transactionToBase64 = transactionToBase64;
3718
- exports.transactionToBase64WithSigners = transactionToBase64WithSigners;
3719
- exports.watchWalletStandardConnectors = watchWalletStandardConnectors;
3720
- //# sourceMappingURL=index.browser.cjs.map
3721
- //# sourceMappingURL=index.browser.cjs.map