@solana/web3.js 2.0.0-development → 2.0.0-experimental.0099b2a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +4 -4
  3. package/dist/index.browser.cjs +779 -10
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +750 -11
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +3531 -395
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +737 -11
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +768 -10
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +737 -11
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +78 -16
  16. package/dist/types/airdrop-confirmer.d.ts +20 -0
  17. package/dist/types/airdrop.d.ts +23 -0
  18. package/dist/types/cached-abortable-iterable.d.ts +11 -0
  19. package/dist/types/index.d.ts +10 -0
  20. package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
  21. package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
  22. package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
  23. package/dist/types/rpc-websocket-transport.d.ts +13 -0
  24. package/dist/types/rpc.d.ts +5 -3
  25. package/dist/types/send-transaction.d.ts +37 -0
  26. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +10 -0
  27. package/dist/types/transaction-confirmation-strategy-nonce.d.ts +15 -0
  28. package/dist/types/transaction-confirmation-strategy-racer.d.ts +14 -0
  29. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +13 -0
  30. package/dist/types/transaction-confirmation-strategy-timeout.d.ts +8 -0
  31. package/dist/types/transaction-confirmation.d.ts +37 -0
  32. package/package.json +24 -22
@@ -1,10 +1,173 @@
1
+ export * from '@solana/addresses';
1
2
  export * from '@solana/instructions';
2
3
  export * from '@solana/keys';
3
- import { createSolanaRpcApi } from '@solana/rpc-core';
4
- import { createJsonRpc, createHttpTransport } from '@solana/rpc-transport';
4
+ import { commitmentComparator } from '@solana/rpc-types';
5
+ export * from '@solana/rpc-types';
6
+ import { getSignatureFromTransaction, getBase64EncodedWireTransaction } from '@solana/transactions';
7
+ export * from '@solana/transactions';
8
+ import { pipe } from '@solana/functional';
9
+ import { createSolanaRpcApi, createSolanaRpcSubscriptionsApi, createSolanaRpcSubscriptionsApi_UNSTABLE } from '@solana/rpc-core';
10
+ import { createJsonRpc, createJsonSubscriptionRpc, createHttpTransport, createWebSocketTransport } from '@solana/rpc-transport';
5
11
  import fastStableStringify from 'fast-stable-stringify';
12
+ import { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';
6
13
 
7
- // src/index.ts
14
+ // ../build-scripts/env-shim.ts
15
+ var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
16
+
17
+ // src/transaction-confirmation-strategy-racer.ts
18
+ async function raceStrategies(signature, config, getSpecificStrategiesForRace) {
19
+ const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;
20
+ callerAbortSignal?.throwIfAborted();
21
+ const abortController = new AbortController();
22
+ if (callerAbortSignal) {
23
+ const handleAbort = () => {
24
+ abortController.abort();
25
+ };
26
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
27
+ }
28
+ try {
29
+ const specificStrategies = getSpecificStrategiesForRace({
30
+ ...config,
31
+ abortSignal: abortController.signal
32
+ });
33
+ return await Promise.race([
34
+ getRecentSignatureConfirmationPromise({
35
+ abortSignal: abortController.signal,
36
+ commitment,
37
+ signature
38
+ }),
39
+ ...specificStrategies
40
+ ]);
41
+ } finally {
42
+ abortController.abort();
43
+ }
44
+ }
45
+ function createRecentSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions) {
46
+ return async function getRecentSignatureConfirmationPromise({
47
+ abortSignal: callerAbortSignal,
48
+ commitment,
49
+ signature
50
+ }) {
51
+ const abortController = new AbortController();
52
+ function handleAbort() {
53
+ abortController.abort();
54
+ }
55
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
56
+ const signatureStatusNotifications = await rpcSubscriptions.signatureNotifications(signature, { commitment }).subscribe({ abortSignal: abortController.signal });
57
+ const signatureDidCommitPromise = (async () => {
58
+ for await (const signatureStatusNotification of signatureStatusNotifications) {
59
+ if (signatureStatusNotification.value.err) {
60
+ throw new Error(`The transaction with signature \`${signature}\` failed.`, {
61
+ cause: signatureStatusNotification.value.err
62
+ });
63
+ } else {
64
+ return;
65
+ }
66
+ }
67
+ })();
68
+ const signatureStatusLookupPromise = (async () => {
69
+ const { value: signatureStatusResults } = await rpc.getSignatureStatuses([signature]).send({ abortSignal: abortController.signal });
70
+ const signatureStatus = signatureStatusResults[0];
71
+ if (signatureStatus && signatureStatus.confirmationStatus && commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0) {
72
+ return;
73
+ } else {
74
+ await new Promise(() => {
75
+ });
76
+ }
77
+ })();
78
+ try {
79
+ return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);
80
+ } finally {
81
+ abortController.abort();
82
+ }
83
+ };
84
+ }
85
+
86
+ // src/transaction-confirmation-strategy-timeout.ts
87
+ async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }) {
88
+ return await new Promise((_, reject) => {
89
+ const handleAbort = (e) => {
90
+ clearTimeout(timeoutId);
91
+ const abortError = new DOMException(e.target.reason, "AbortError");
92
+ reject(abortError);
93
+ };
94
+ callerAbortSignal.addEventListener("abort", handleAbort);
95
+ const timeoutMs = commitment === "processed" ? 3e4 : 6e4;
96
+ const startMs = performance.now();
97
+ const timeoutId = (
98
+ // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure
99
+ // elapsed time instead of active time.
100
+ // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
101
+ setTimeout(() => {
102
+ const elapsedMs = performance.now() - startMs;
103
+ reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, "TimeoutError"));
104
+ }, timeoutMs)
105
+ );
106
+ });
107
+ }
108
+
109
+ // src/airdrop-confirmer.ts
110
+ function createDefaultSignatureOnlyRecentTransactionConfirmer({
111
+ rpc,
112
+ rpcSubscriptions
113
+ }) {
114
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
115
+ rpc,
116
+ rpcSubscriptions
117
+ );
118
+ return async function confirmSignatureOnlyRecentTransaction(config) {
119
+ await waitForRecentTransactionConfirmationUntilTimeout({
120
+ ...config,
121
+ getRecentSignatureConfirmationPromise,
122
+ getTimeoutPromise
123
+ });
124
+ };
125
+ }
126
+ async function waitForRecentTransactionConfirmationUntilTimeout(config) {
127
+ await raceStrategies(
128
+ config.signature,
129
+ config,
130
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise: getTimeoutPromise2 }) {
131
+ return [
132
+ getTimeoutPromise2({
133
+ abortSignal,
134
+ commitment
135
+ })
136
+ ];
137
+ }
138
+ );
139
+ }
140
+
141
+ // src/airdrop.ts
142
+ function createDefaultAirdropRequester({ rpc, rpcSubscriptions }) {
143
+ const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({
144
+ rpc,
145
+ rpcSubscriptions
146
+ });
147
+ return async function requestAirdrop(config) {
148
+ return await requestAndConfirmAirdrop({
149
+ ...config,
150
+ confirmSignatureOnlyTransaction,
151
+ rpc
152
+ });
153
+ };
154
+ }
155
+ async function requestAndConfirmAirdrop({
156
+ abortSignal,
157
+ commitment,
158
+ confirmSignatureOnlyTransaction,
159
+ lamports,
160
+ recipientAddress,
161
+ rpc
162
+ }) {
163
+ const airdropTransactionSignature = await rpc.requestAirdrop(recipientAddress, lamports, { commitment }).send({ abortSignal });
164
+ await confirmSignatureOnlyTransaction({
165
+ abortSignal,
166
+ commitment,
167
+ signature: airdropTransactionSignature
168
+ });
169
+ return airdropTransactionSignature;
170
+ }
8
171
 
9
172
  // src/rpc-integer-overflow-error.ts
10
173
  var SolanaJsonRpcIntegerOverflowError = class extends Error {
@@ -42,6 +205,193 @@ var DEFAULT_RPC_CONFIG = {
42
205
  }
43
206
  };
44
207
 
208
+ // src/cached-abortable-iterable.ts
209
+ function registerIterableCleanup(iterable, cleanupFn) {
210
+ (async () => {
211
+ try {
212
+ for await (const _ of iterable)
213
+ ;
214
+ } catch {
215
+ } finally {
216
+ cleanupFn();
217
+ }
218
+ })();
219
+ }
220
+ function getCachedAbortableIterableFactory({
221
+ getAbortSignalFromInputArgs,
222
+ getCacheEntryMissingError,
223
+ getCacheKeyFromInputArgs,
224
+ onCacheHit,
225
+ onCreateIterable
226
+ }) {
227
+ const cache = /* @__PURE__ */ new Map();
228
+ function getCacheEntryOrThrow(cacheKey) {
229
+ const currentCacheEntry = cache.get(cacheKey);
230
+ if (!currentCacheEntry) {
231
+ throw getCacheEntryMissingError(cacheKey);
232
+ }
233
+ return currentCacheEntry;
234
+ }
235
+ return async (...args) => {
236
+ const cacheKey = getCacheKeyFromInputArgs(...args);
237
+ const signal = getAbortSignalFromInputArgs(...args);
238
+ if (cacheKey === void 0) {
239
+ return await onCreateIterable(signal, ...args);
240
+ }
241
+ const cleanup = () => {
242
+ cache.delete(cacheKey);
243
+ signal.removeEventListener("abort", handleAbort);
244
+ };
245
+ const handleAbort = () => {
246
+ const cacheEntry = getCacheEntryOrThrow(cacheKey);
247
+ if (cacheEntry.purgeScheduled !== true) {
248
+ cacheEntry.purgeScheduled = true;
249
+ globalThis.queueMicrotask(() => {
250
+ cacheEntry.purgeScheduled = false;
251
+ if (cacheEntry.referenceCount === 0) {
252
+ cacheEntry.abortController.abort();
253
+ cleanup();
254
+ }
255
+ });
256
+ }
257
+ cacheEntry.referenceCount--;
258
+ };
259
+ signal.addEventListener("abort", handleAbort);
260
+ try {
261
+ const cacheEntry = cache.get(cacheKey);
262
+ if (!cacheEntry) {
263
+ const singletonAbortController = new AbortController();
264
+ const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);
265
+ const newCacheEntry = {
266
+ abortController: singletonAbortController,
267
+ iterable: newIterablePromise,
268
+ purgeScheduled: false,
269
+ referenceCount: 1
270
+ };
271
+ cache.set(cacheKey, newCacheEntry);
272
+ const newIterable = await newIterablePromise;
273
+ registerIterableCleanup(newIterable, cleanup);
274
+ newCacheEntry.iterable = newIterable;
275
+ return newIterable;
276
+ } else {
277
+ cacheEntry.referenceCount++;
278
+ const iterableOrIterablePromise = cacheEntry.iterable;
279
+ const cachedIterable = "then" in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;
280
+ await onCacheHit(cachedIterable, ...args);
281
+ return cachedIterable;
282
+ }
283
+ } catch (e) {
284
+ cleanup();
285
+ throw e;
286
+ }
287
+ };
288
+ }
289
+
290
+ // src/rpc-subscription-coalescer.ts
291
+ var EXPLICIT_ABORT_TOKEN = Symbol(
292
+ __DEV__ ? "This symbol is thrown from a subscription's iterator when the subscription is explicitly aborted by the user" : void 0
293
+ );
294
+ function registerIterableCleanup2(iterable, cleanupFn) {
295
+ (async () => {
296
+ try {
297
+ for await (const _ of iterable)
298
+ ;
299
+ } catch {
300
+ } finally {
301
+ cleanupFn();
302
+ }
303
+ })();
304
+ }
305
+ function getRpcSubscriptionsWithSubscriptionCoalescing({
306
+ getDeduplicationKey,
307
+ rpcSubscriptions
308
+ }) {
309
+ const cache = /* @__PURE__ */ new Map();
310
+ return new Proxy(rpcSubscriptions, {
311
+ defineProperty() {
312
+ return false;
313
+ },
314
+ deleteProperty() {
315
+ return false;
316
+ },
317
+ get(target, p, receiver) {
318
+ const subscriptionMethod = Reflect.get(target, p, receiver);
319
+ if (typeof subscriptionMethod !== "function") {
320
+ return subscriptionMethod;
321
+ }
322
+ return function(...rawParams) {
323
+ const deduplicationKey = getDeduplicationKey(p, rawParams);
324
+ if (deduplicationKey === void 0) {
325
+ return subscriptionMethod(...rawParams);
326
+ }
327
+ if (cache.has(deduplicationKey)) {
328
+ return cache.get(deduplicationKey);
329
+ }
330
+ const iterableFactory = getCachedAbortableIterableFactory({
331
+ getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,
332
+ getCacheEntryMissingError(deduplicationKey2) {
333
+ return new Error(
334
+ `Found no cache entry for subscription with deduplication key \`${deduplicationKey2?.toString()}\``
335
+ );
336
+ },
337
+ getCacheKeyFromInputArgs: () => deduplicationKey,
338
+ async onCacheHit(_iterable, _config) {
339
+ },
340
+ async onCreateIterable(abortSignal, config) {
341
+ const pendingSubscription2 = subscriptionMethod(
342
+ ...rawParams
343
+ );
344
+ const iterable = await pendingSubscription2.subscribe({
345
+ ...config,
346
+ abortSignal
347
+ });
348
+ registerIterableCleanup2(iterable, () => {
349
+ cache.delete(deduplicationKey);
350
+ });
351
+ return iterable;
352
+ }
353
+ });
354
+ const pendingSubscription = {
355
+ async subscribe(...args) {
356
+ const iterable = await iterableFactory(...args);
357
+ const { abortSignal } = args[0];
358
+ let abortPromise;
359
+ return {
360
+ ...iterable,
361
+ async *[Symbol.asyncIterator]() {
362
+ abortPromise || (abortPromise = abortSignal.aborted ? Promise.reject(EXPLICIT_ABORT_TOKEN) : new Promise((_, reject) => {
363
+ abortSignal.addEventListener("abort", () => {
364
+ reject(EXPLICIT_ABORT_TOKEN);
365
+ });
366
+ }));
367
+ try {
368
+ const iterator = iterable[Symbol.asyncIterator]();
369
+ while (true) {
370
+ const iteratorResult = await Promise.race([iterator.next(), abortPromise]);
371
+ if (iteratorResult.done) {
372
+ return;
373
+ } else {
374
+ yield iteratorResult.value;
375
+ }
376
+ }
377
+ } catch (e) {
378
+ if (e === EXPLICIT_ABORT_TOKEN) {
379
+ return;
380
+ }
381
+ cache.delete(deduplicationKey);
382
+ throw e;
383
+ }
384
+ }
385
+ };
386
+ }
387
+ };
388
+ cache.set(deduplicationKey, pendingSubscription);
389
+ return pendingSubscription;
390
+ };
391
+ }
392
+ });
393
+ }
394
+
45
395
  // src/rpc.ts
46
396
  function createSolanaRpc(config) {
47
397
  return createJsonRpc({
@@ -49,6 +399,24 @@ function createSolanaRpc(config) {
49
399
  api: createSolanaRpcApi(DEFAULT_RPC_CONFIG)
50
400
  });
51
401
  }
402
+ function createSolanaRpcSubscriptions(config) {
403
+ return pipe(
404
+ createJsonSubscriptionRpc({
405
+ ...config,
406
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
407
+ }),
408
+ (rpcSubscriptions) => getRpcSubscriptionsWithSubscriptionCoalescing({
409
+ getDeduplicationKey: (...args) => fastStableStringify(args),
410
+ rpcSubscriptions
411
+ })
412
+ );
413
+ }
414
+ function createSolanaRpcSubscriptions_UNSTABLE(config) {
415
+ return createJsonSubscriptionRpc({
416
+ ...config,
417
+ api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG)
418
+ });
419
+ }
52
420
 
53
421
  // src/rpc-request-coalescer.ts
54
422
  function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
@@ -101,13 +469,14 @@ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
101
469
  }
102
470
  };
103
471
  }
104
- function getSolanaRpcPayloadDeduplicationKey(payload) {
472
+ function isJsonRpcPayload(payload) {
105
473
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
106
- return;
107
- }
108
- if ("jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && "params" in payload) {
109
- return fastStableStringify([payload.method, payload.params]);
474
+ return false;
110
475
  }
476
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
477
+ }
478
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
479
+ return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : void 0;
111
480
  }
112
481
 
113
482
  // src/rpc-transport.ts
@@ -119,7 +488,7 @@ function normalizeHeaders(headers) {
119
488
  return out;
120
489
  }
121
490
  function createDefaultRpcTransport(config) {
122
- return getRpcTransportWithRequestCoalescing(
491
+ return pipe(
123
492
  createHttpTransport({
124
493
  ...config,
125
494
  headers: {
@@ -130,8 +499,378 @@ function createDefaultRpcTransport(config) {
130
499
  }
131
500
  }
132
501
  }),
133
- getSolanaRpcPayloadDeduplicationKey
502
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
134
503
  );
135
504
  }
136
505
 
137
- export { createDefaultRpcTransport, createSolanaRpc };
506
+ // src/rpc-websocket-autopinger.ts
507
+ var PING_PAYLOAD = {
508
+ jsonrpc: "2.0",
509
+ method: "ping"
510
+ };
511
+ function getWebSocketTransportWithAutoping({ intervalMs, transport }) {
512
+ const pingableConnections = /* @__PURE__ */ new Map();
513
+ return async (...args) => {
514
+ const connection = await transport(...args);
515
+ let intervalId;
516
+ function sendPing() {
517
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);
518
+ }
519
+ function restartPingTimer() {
520
+ clearInterval(intervalId);
521
+ intervalId = setInterval(sendPing, intervalMs);
522
+ }
523
+ if (pingableConnections.has(connection) === false) {
524
+ pingableConnections.set(connection, {
525
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
526
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (...args2) => {
527
+ restartPingTimer();
528
+ return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args2);
529
+ }
530
+ });
531
+ (async () => {
532
+ try {
533
+ for await (const _ of connection) {
534
+ restartPingTimer();
535
+ }
536
+ } catch {
537
+ } finally {
538
+ pingableConnections.delete(connection);
539
+ clearInterval(intervalId);
540
+ if (handleOffline) {
541
+ globalThis.window.removeEventListener("offline", handleOffline);
542
+ }
543
+ if (handleOnline) {
544
+ globalThis.window.removeEventListener("online", handleOnline);
545
+ }
546
+ }
547
+ })();
548
+ if (globalThis.navigator.onLine) {
549
+ restartPingTimer();
550
+ }
551
+ let handleOffline;
552
+ let handleOnline;
553
+ {
554
+ handleOffline = () => {
555
+ clearInterval(intervalId);
556
+ };
557
+ handleOnline = () => {
558
+ sendPing();
559
+ restartPingTimer();
560
+ };
561
+ globalThis.window.addEventListener("offline", handleOffline);
562
+ globalThis.window.addEventListener("online", handleOnline);
563
+ }
564
+ }
565
+ return pingableConnections.get(connection);
566
+ };
567
+ }
568
+
569
+ // src/rpc-websocket-connection-sharding.ts
570
+ var NULL_SHARD_CACHE_KEY = Symbol(
571
+ __DEV__ ? "Cache key to use when there is no connection sharding strategy" : void 0
572
+ );
573
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
574
+ return getCachedAbortableIterableFactory({
575
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
576
+ getCacheEntryMissingError(shardKey) {
577
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
578
+ },
579
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
580
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
581
+ onCreateIterable: (abortSignal, config) => transport({
582
+ ...config,
583
+ signal: abortSignal
584
+ })
585
+ });
586
+ }
587
+
588
+ // src/rpc-websocket-transport.ts
589
+ function createDefaultRpcSubscriptionsTransport(config) {
590
+ const { getShard, intervalMs, ...rest } = config;
591
+ return pipe(
592
+ createWebSocketTransport({
593
+ ...rest,
594
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
595
+ 131072
596
+ }),
597
+ (transport) => getWebSocketTransportWithAutoping({
598
+ intervalMs: intervalMs ?? 5e3,
599
+ transport
600
+ }),
601
+ (transport) => getWebSocketTransportWithConnectionSharding({
602
+ getShard,
603
+ transport
604
+ })
605
+ );
606
+ }
607
+
608
+ // src/transaction-confirmation-strategy-blockheight.ts
609
+ function createBlockHeightExceedencePromiseFactory(rpcSubscriptions) {
610
+ return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {
611
+ const abortController = new AbortController();
612
+ function handleAbort() {
613
+ abortController.abort();
614
+ }
615
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
616
+ const slotNotifications = await rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal });
617
+ try {
618
+ for await (const slotNotification of slotNotifications) {
619
+ if (slotNotification.slot > lastValidBlockHeight) {
620
+ throw new Error(
621
+ "The network has progressed past the last block for which this transaction could have committed."
622
+ );
623
+ }
624
+ }
625
+ } finally {
626
+ abortController.abort();
627
+ }
628
+ };
629
+ }
630
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
631
+ 4 + // state(u32)
632
+ 32;
633
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
634
+ return async function getNonceInvalidationPromise({
635
+ abortSignal: callerAbortSignal,
636
+ commitment,
637
+ currentNonceValue,
638
+ nonceAccountAddress
639
+ }) {
640
+ const abortController = new AbortController();
641
+ function handleAbort() {
642
+ abortController.abort();
643
+ }
644
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
645
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
646
+ const base58Decoder = getBase58Decoder();
647
+ const base64Encoder = getBase64Encoder();
648
+ function getNonceFromAccountData([base64EncodedBytes]) {
649
+ const data = base64Encoder.encode(base64EncodedBytes);
650
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
651
+ return base58Decoder.decode(nonceValueBytes)[0];
652
+ }
653
+ const nonceAccountDidAdvancePromise = (async () => {
654
+ for await (const accountNotification of accountNotifications) {
655
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
656
+ if (nonceValue !== currentNonceValue) {
657
+ throw new Error(
658
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
659
+ );
660
+ }
661
+ }
662
+ })();
663
+ const nonceIsAlreadyInvalidPromise = (async () => {
664
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
665
+ commitment,
666
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
667
+ encoding: "base58"
668
+ }).send({ abortSignal: abortController.signal });
669
+ if (!nonceAccount) {
670
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
671
+ }
672
+ const nonceValue = (
673
+ // This works because we asked for the exact slice of data representing the nonce
674
+ // value, and furthermore asked for it in `base58` encoding.
675
+ nonceAccount.data[0]
676
+ );
677
+ if (nonceValue !== currentNonceValue) {
678
+ throw new Error(
679
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
680
+ );
681
+ } else {
682
+ await new Promise(() => {
683
+ });
684
+ }
685
+ })();
686
+ try {
687
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
688
+ } finally {
689
+ abortController.abort();
690
+ }
691
+ };
692
+ }
693
+
694
+ // src/transaction-confirmation.ts
695
+ function createDefaultDurableNonceTransactionConfirmer({
696
+ rpc,
697
+ rpcSubscriptions
698
+ }) {
699
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
700
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
701
+ rpc,
702
+ rpcSubscriptions
703
+ );
704
+ return async function confirmDurableNonceTransaction(config) {
705
+ await waitForDurableNonceTransactionConfirmation({
706
+ ...config,
707
+ getNonceInvalidationPromise,
708
+ getRecentSignatureConfirmationPromise
709
+ });
710
+ };
711
+ }
712
+ function createDefaultRecentTransactionConfirmer({
713
+ rpc,
714
+ rpcSubscriptions
715
+ }) {
716
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);
717
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
718
+ rpc,
719
+ rpcSubscriptions
720
+ );
721
+ return async function confirmRecentTransaction(config) {
722
+ await waitForRecentTransactionConfirmation({
723
+ ...config,
724
+ getBlockHeightExceedencePromise,
725
+ getRecentSignatureConfirmationPromise
726
+ });
727
+ };
728
+ }
729
+ async function waitForDurableNonceTransactionConfirmation(config) {
730
+ await raceStrategies(
731
+ getSignatureFromTransaction(config.transaction),
732
+ config,
733
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
734
+ return [
735
+ getNonceInvalidationPromise({
736
+ abortSignal,
737
+ commitment,
738
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
739
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
740
+ })
741
+ ];
742
+ }
743
+ );
744
+ }
745
+ async function waitForRecentTransactionConfirmation(config) {
746
+ await raceStrategies(
747
+ getSignatureFromTransaction(config.transaction),
748
+ config,
749
+ function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {
750
+ return [
751
+ getBlockHeightExceedencePromise({
752
+ abortSignal,
753
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
754
+ })
755
+ ];
756
+ }
757
+ );
758
+ }
759
+
760
+ // src/send-transaction.ts
761
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
762
+ if (
763
+ // The developer has supplied no value for `preflightCommitment`.
764
+ !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
765
+ commitmentComparator(
766
+ commitment,
767
+ "finalized"
768
+ /* default value of `preflightCommitment` */
769
+ ) < 0
770
+ ) {
771
+ return {
772
+ ...config,
773
+ // In the common case, it is unlikely that you want to simulate a transaction at
774
+ // `finalized` commitment when your standard of commitment for confirming the
775
+ // transaction is lower. Cap the simulation commitment level to the level of the
776
+ // confirmation commitment.
777
+ preflightCommitment: commitment
778
+ };
779
+ }
780
+ return config;
781
+ }
782
+ async function sendTransaction_INTERNAL({
783
+ abortSignal,
784
+ commitment,
785
+ rpc,
786
+ transaction,
787
+ ...sendTransactionConfig
788
+ }) {
789
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
790
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
791
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
792
+ encoding: "base64"
793
+ }).send({ abortSignal });
794
+ }
795
+ function createDefaultDurableNonceTransactionSender({
796
+ rpc,
797
+ rpcSubscriptions
798
+ }) {
799
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
800
+ rpc,
801
+ rpcSubscriptions
802
+ });
803
+ return async function sendDurableNonceTransaction(transaction, config) {
804
+ await sendAndConfirmDurableNonceTransaction({
805
+ ...config,
806
+ confirmDurableNonceTransaction,
807
+ rpc,
808
+ transaction
809
+ });
810
+ };
811
+ }
812
+ function createDefaultTransactionSender({
813
+ rpc,
814
+ rpcSubscriptions
815
+ }) {
816
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
817
+ rpc,
818
+ rpcSubscriptions
819
+ });
820
+ return async function sendTransaction(transaction, config) {
821
+ await sendAndConfirmTransaction({
822
+ ...config,
823
+ confirmRecentTransaction,
824
+ rpc,
825
+ transaction
826
+ });
827
+ };
828
+ }
829
+ async function sendAndConfirmDurableNonceTransaction({
830
+ abortSignal,
831
+ commitment,
832
+ confirmDurableNonceTransaction,
833
+ rpc,
834
+ transaction,
835
+ ...sendTransactionConfig
836
+ }) {
837
+ const transactionSignature = await sendTransaction_INTERNAL({
838
+ ...sendTransactionConfig,
839
+ abortSignal,
840
+ commitment,
841
+ rpc,
842
+ transaction
843
+ });
844
+ await confirmDurableNonceTransaction({
845
+ abortSignal,
846
+ commitment,
847
+ transaction
848
+ });
849
+ return transactionSignature;
850
+ }
851
+ async function sendAndConfirmTransaction({
852
+ abortSignal,
853
+ commitment,
854
+ confirmRecentTransaction,
855
+ rpc,
856
+ transaction,
857
+ ...sendTransactionConfig
858
+ }) {
859
+ const transactionSignature = await sendTransaction_INTERNAL({
860
+ ...sendTransactionConfig,
861
+ abortSignal,
862
+ commitment,
863
+ rpc,
864
+ transaction
865
+ });
866
+ await confirmRecentTransaction({
867
+ abortSignal,
868
+ commitment,
869
+ transaction
870
+ });
871
+ return transactionSignature;
872
+ }
873
+
874
+ export { createBlockHeightExceedencePromiseFactory, createDefaultAirdropRequester, createDefaultDurableNonceTransactionConfirmer, createDefaultDurableNonceTransactionSender, createDefaultRecentTransactionConfirmer, createDefaultRpcSubscriptionsTransport, createDefaultRpcTransport, createDefaultTransactionSender, createNonceInvalidationPromiseFactory, createRecentSignatureConfirmationPromiseFactory, createSolanaRpc, createSolanaRpcSubscriptions, createSolanaRpcSubscriptions_UNSTABLE, requestAndConfirmAirdrop, sendAndConfirmDurableNonceTransaction, sendAndConfirmTransaction, waitForDurableNonceTransactionConfirmation, waitForRecentTransactionConfirmation };
875
+ //# sourceMappingURL=out.js.map
876
+ //# sourceMappingURL=index.browser.js.map