@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,417 @@ function createDefaultRpcTransport(config) {
131
554
  }
132
555
  }
133
556
  }),
134
- getSolanaRpcPayloadDeduplicationKey
557
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
558
+ );
559
+ }
560
+
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
+ if (globalThis.navigator.onLine) {
604
+ restartPingTimer();
605
+ }
606
+ let handleOffline;
607
+ let handleOnline;
608
+ {
609
+ handleOffline = () => {
610
+ clearInterval(intervalId);
611
+ };
612
+ handleOnline = () => {
613
+ sendPing();
614
+ restartPingTimer();
615
+ };
616
+ globalThis.window.addEventListener("offline", handleOffline);
617
+ globalThis.window.addEventListener("online", handleOnline);
618
+ }
619
+ }
620
+ return pingableConnections.get(connection);
621
+ };
622
+ }
623
+
624
+ // src/rpc-websocket-connection-sharding.ts
625
+ var NULL_SHARD_CACHE_KEY = Symbol(
626
+ __DEV__ ? "Cache key to use when there is no connection sharding strategy" : void 0
627
+ );
628
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
629
+ return getCachedAbortableIterableFactory({
630
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
631
+ getCacheEntryMissingError(shardKey) {
632
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
633
+ },
634
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
635
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
636
+ onCreateIterable: (abortSignal, config) => transport({
637
+ ...config,
638
+ signal: abortSignal
639
+ })
640
+ });
641
+ }
642
+
643
+ // src/rpc-websocket-transport.ts
644
+ function createDefaultRpcSubscriptionsTransport(config) {
645
+ const { getShard, intervalMs, ...rest } = config;
646
+ return pipe(
647
+ createWebSocketTransport({
648
+ ...rest,
649
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
650
+ 131072
651
+ }),
652
+ (transport) => getWebSocketTransportWithAutoping({
653
+ intervalMs: intervalMs ?? 5e3,
654
+ transport
655
+ }),
656
+ (transport) => getWebSocketTransportWithConnectionSharding({
657
+ getShard,
658
+ transport
659
+ })
135
660
  );
136
661
  }
137
662
 
138
- export { createDefaultRpcTransport, createSolanaRpc };
663
+ // src/transaction-confirmation-strategy-blockheight.ts
664
+ function createBlockHeightExceedencePromiseFactory({
665
+ rpc,
666
+ rpcSubscriptions
667
+ }) {
668
+ return async function getBlockHeightExceedencePromise({
669
+ abortSignal: callerAbortSignal,
670
+ commitment,
671
+ lastValidBlockHeight
672
+ }) {
673
+ const abortController = new AbortController();
674
+ const handleAbort = () => {
675
+ abortController.abort();
676
+ };
677
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
678
+ async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {
679
+ const { absoluteSlot, blockHeight } = await rpc.getEpochInfo({ commitment }).send({ abortSignal: abortController.signal });
680
+ return {
681
+ blockHeight,
682
+ differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight
683
+ };
684
+ }
685
+ try {
686
+ const [slotNotifications, { blockHeight, differenceBetweenSlotHeightAndBlockHeight }] = await Promise.all([
687
+ rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),
688
+ getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight()
689
+ ]);
690
+ if (blockHeight <= lastValidBlockHeight) {
691
+ let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;
692
+ for await (const slotNotification of slotNotifications) {
693
+ const { slot } = slotNotification;
694
+ if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {
695
+ const {
696
+ blockHeight: currentBlockHeight,
697
+ differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight
698
+ } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();
699
+ if (currentBlockHeight > lastValidBlockHeight) {
700
+ break;
701
+ } else {
702
+ lastKnownDifferenceBetweenSlotHeightAndBlockHeight = currentDifferenceBetweenSlotHeightAndBlockHeight;
703
+ }
704
+ }
705
+ }
706
+ }
707
+ throw new Error(
708
+ "The network has progressed past the last block for which this transaction could have been committed."
709
+ );
710
+ } finally {
711
+ abortController.abort();
712
+ }
713
+ };
714
+ }
715
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
716
+ 4 + // state(u32)
717
+ 32;
718
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
719
+ return async function getNonceInvalidationPromise({
720
+ abortSignal: callerAbortSignal,
721
+ commitment,
722
+ currentNonceValue,
723
+ nonceAccountAddress
724
+ }) {
725
+ const abortController = new AbortController();
726
+ function handleAbort() {
727
+ abortController.abort();
728
+ }
729
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
730
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
731
+ const base58Decoder = getBase58Decoder();
732
+ const base64Encoder = getBase64Encoder();
733
+ function getNonceFromAccountData([base64EncodedBytes]) {
734
+ const data = base64Encoder.encode(base64EncodedBytes);
735
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
736
+ return base58Decoder.decode(nonceValueBytes);
737
+ }
738
+ const nonceAccountDidAdvancePromise = (async () => {
739
+ for await (const accountNotification of accountNotifications) {
740
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
741
+ if (nonceValue !== currentNonceValue) {
742
+ throw new Error(
743
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
744
+ );
745
+ }
746
+ }
747
+ })();
748
+ const nonceIsAlreadyInvalidPromise = (async () => {
749
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
750
+ commitment,
751
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
752
+ encoding: "base58"
753
+ }).send({ abortSignal: abortController.signal });
754
+ if (!nonceAccount) {
755
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
756
+ }
757
+ const nonceValue = (
758
+ // This works because we asked for the exact slice of data representing the nonce
759
+ // value, and furthermore asked for it in `base58` encoding.
760
+ nonceAccount.data[0]
761
+ );
762
+ if (nonceValue !== currentNonceValue) {
763
+ throw new Error(
764
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
765
+ );
766
+ } else {
767
+ await new Promise(() => {
768
+ });
769
+ }
770
+ })();
771
+ try {
772
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
773
+ } finally {
774
+ abortController.abort();
775
+ }
776
+ };
777
+ }
778
+
779
+ // src/transaction-confirmation.ts
780
+ function createDefaultDurableNonceTransactionConfirmer({
781
+ rpc,
782
+ rpcSubscriptions
783
+ }) {
784
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
785
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
786
+ rpc,
787
+ rpcSubscriptions
788
+ );
789
+ return async function confirmDurableNonceTransaction(config) {
790
+ await waitForDurableNonceTransactionConfirmation({
791
+ ...config,
792
+ getNonceInvalidationPromise,
793
+ getRecentSignatureConfirmationPromise
794
+ });
795
+ };
796
+ }
797
+ function createDefaultRecentTransactionConfirmer({
798
+ rpc,
799
+ rpcSubscriptions
800
+ }) {
801
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({
802
+ rpc,
803
+ rpcSubscriptions
804
+ });
805
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
806
+ rpc,
807
+ rpcSubscriptions
808
+ );
809
+ return async function confirmRecentTransaction(config) {
810
+ await waitForRecentTransactionConfirmation({
811
+ ...config,
812
+ getBlockHeightExceedencePromise,
813
+ getRecentSignatureConfirmationPromise
814
+ });
815
+ };
816
+ }
817
+ async function waitForDurableNonceTransactionConfirmation(config) {
818
+ await raceStrategies(
819
+ getSignatureFromTransaction(config.transaction),
820
+ config,
821
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
822
+ return [
823
+ getNonceInvalidationPromise({
824
+ abortSignal,
825
+ commitment,
826
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
827
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
828
+ })
829
+ ];
830
+ }
831
+ );
832
+ }
833
+ async function waitForRecentTransactionConfirmation(config) {
834
+ await raceStrategies(
835
+ getSignatureFromTransaction(config.transaction),
836
+ config,
837
+ function getSpecificStrategiesForRace({
838
+ abortSignal,
839
+ commitment,
840
+ getBlockHeightExceedencePromise,
841
+ transaction
842
+ }) {
843
+ return [
844
+ getBlockHeightExceedencePromise({
845
+ abortSignal,
846
+ commitment,
847
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
848
+ })
849
+ ];
850
+ }
851
+ );
852
+ }
853
+
854
+ // src/send-transaction.ts
855
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
856
+ if (
857
+ // The developer has supplied no value for `preflightCommitment`.
858
+ !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
859
+ commitmentComparator(
860
+ commitment,
861
+ "finalized"
862
+ /* default value of `preflightCommitment` */
863
+ ) < 0
864
+ ) {
865
+ return {
866
+ ...config,
867
+ // In the common case, it is unlikely that you want to simulate a transaction at
868
+ // `finalized` commitment when your standard of commitment for confirming the
869
+ // transaction is lower. Cap the simulation commitment level to the level of the
870
+ // confirmation commitment.
871
+ preflightCommitment: commitment
872
+ };
873
+ }
874
+ return config;
875
+ }
876
+ async function sendTransaction_INTERNAL({
877
+ abortSignal,
878
+ commitment,
879
+ rpc,
880
+ transaction,
881
+ ...sendTransactionConfig
882
+ }) {
883
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
884
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
885
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
886
+ encoding: "base64"
887
+ }).send({ abortSignal });
888
+ }
889
+ function createDefaultDurableNonceTransactionSender({
890
+ rpc,
891
+ rpcSubscriptions
892
+ }) {
893
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
894
+ rpc,
895
+ rpcSubscriptions
896
+ });
897
+ return async function sendDurableNonceTransaction(transaction, config) {
898
+ await sendAndConfirmDurableNonceTransaction({
899
+ ...config,
900
+ confirmDurableNonceTransaction,
901
+ rpc,
902
+ transaction
903
+ });
904
+ };
905
+ }
906
+ function createDefaultTransactionSender({
907
+ rpc,
908
+ rpcSubscriptions
909
+ }) {
910
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
911
+ rpc,
912
+ rpcSubscriptions
913
+ });
914
+ return async function sendTransaction(transaction, config) {
915
+ await sendAndConfirmTransaction({
916
+ ...config,
917
+ confirmRecentTransaction,
918
+ rpc,
919
+ transaction
920
+ });
921
+ };
922
+ }
923
+ async function sendAndConfirmDurableNonceTransaction({
924
+ abortSignal,
925
+ commitment,
926
+ confirmDurableNonceTransaction,
927
+ rpc,
928
+ transaction,
929
+ ...sendTransactionConfig
930
+ }) {
931
+ const transactionSignature = await sendTransaction_INTERNAL({
932
+ ...sendTransactionConfig,
933
+ abortSignal,
934
+ commitment,
935
+ rpc,
936
+ transaction
937
+ });
938
+ await confirmDurableNonceTransaction({
939
+ abortSignal,
940
+ commitment,
941
+ transaction
942
+ });
943
+ return transactionSignature;
944
+ }
945
+ async function sendAndConfirmTransaction({
946
+ abortSignal,
947
+ commitment,
948
+ confirmRecentTransaction,
949
+ rpc,
950
+ transaction,
951
+ ...sendTransactionConfig
952
+ }) {
953
+ const transactionSignature = await sendTransaction_INTERNAL({
954
+ ...sendTransactionConfig,
955
+ abortSignal,
956
+ commitment,
957
+ rpc,
958
+ transaction
959
+ });
960
+ await confirmRecentTransaction({
961
+ abortSignal,
962
+ commitment,
963
+ transaction
964
+ });
965
+ return transactionSignature;
966
+ }
967
+
968
+ export { createBlockHeightExceedencePromiseFactory, createDefaultAirdropRequester, createDefaultDurableNonceTransactionConfirmer, createDefaultDurableNonceTransactionSender, createDefaultRecentTransactionConfirmer, createDefaultRpcSubscriptionsTransport, createDefaultRpcTransport, createDefaultTransactionSender, createNonceInvalidationPromiseFactory, createRecentSignatureConfirmationPromiseFactory, createSolanaRpc, createSolanaRpcSubscriptions, createSolanaRpcSubscriptions_UNSTABLE, decodeTransaction, requestAndConfirmAirdrop, sendAndConfirmDurableNonceTransaction, sendAndConfirmTransaction, waitForDurableNonceTransactionConfirmation, waitForRecentTransactionConfirmation };
139
969
  //# sourceMappingURL=out.js.map
140
970
  //# sourceMappingURL=index.browser.js.map