@solana/web3.js 2.0.0-experimental.a8f1f88 → 2.0.0-experimental.aa4a701

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