@solana/web3.js 2.0.0-experimental.b8960ad → 2.0.0-experimental.b93299a

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