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