@solana/web3.js 2.0.0-experimental.95bfd9f → 2.0.0-experimental.9741939

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