@solana/web3.js 2.0.0-experimental.0de6c3e → 2.0.0-experimental.0e03ca9

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 +931 -27
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +866 -28
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +5322 -552
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +855 -28
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +922 -27
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +855 -28
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +273 -19
  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 +19 -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 +2 -2
  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 +7 -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 +16 -0
  41. package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
  42. package/dist/types/rpc.d.ts +12 -4
  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 -23
@@ -1,30 +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';
3
- import { createSolanaRpcApi } from '@solana/rpc-core';
4
- import { createJsonRpc, createHttpTransport } from '@solana/rpc-transport';
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';
16
+ export * from '@solana/transactions';
17
+ import { createSolanaRpcApi, createSolanaRpcSubscriptionsApi, createSolanaRpcSubscriptionsApi_UNSTABLE } from '@solana/rpc-core';
18
+ import { createJsonRpc, createJsonSubscriptionRpc, createHttpTransport, createWebSocketTransport } from '@solana/rpc-transport';
5
19
  import fastStableStringify from 'fast-stable-stringify';
6
20
 
7
- // 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
+ }
8
208
 
9
209
  // src/rpc-integer-overflow-error.ts
10
210
  var SolanaJsonRpcIntegerOverflowError = class extends Error {
211
+ methodName;
212
+ keyPath;
213
+ value;
11
214
  constructor(methodName, keyPath, value) {
12
- const argPosition = (typeof keyPath[0] === "number" ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;
13
- let ordinal = "";
14
- const lastDigit = argPosition % 10;
15
- const lastTwoDigits = argPosition % 100;
16
- if (lastDigit == 1 && lastTwoDigits != 11) {
17
- ordinal = argPosition + "st";
18
- } else if (lastDigit == 2 && lastTwoDigits != 12) {
19
- ordinal = argPosition + "nd";
20
- } else if (lastDigit == 3 && lastTwoDigits != 13) {
21
- 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
+ }
22
229
  } else {
23
- ordinal = argPosition + "th";
230
+ argumentLabel = `\`${keyPath[0].toString()}\``;
24
231
  }
25
232
  const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : null;
26
233
  super(
27
- `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\`.`
28
235
  );
29
236
  this.keyPath = keyPath;
30
237
  this.methodName = methodName;
@@ -37,16 +244,223 @@ var SolanaJsonRpcIntegerOverflowError = class extends Error {
37
244
 
38
245
  // src/rpc-default-config.ts
39
246
  var DEFAULT_RPC_CONFIG = {
247
+ defaultCommitment: "confirmed",
40
248
  onIntegerOverflow(methodName, keyPath, value) {
41
249
  throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);
42
250
  }
43
251
  };
44
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
+
45
440
  // src/rpc.ts
46
441
  function createSolanaRpc(config) {
442
+ const api = createSolanaRpcApi(DEFAULT_RPC_CONFIG);
47
443
  return createJsonRpc({
48
444
  ...config,
49
- api: createSolanaRpcApi(DEFAULT_RPC_CONFIG)
445
+ api
446
+ });
447
+ }
448
+ function createSolanaRpcSubscriptions(config) {
449
+ return pipe(
450
+ createJsonSubscriptionRpc({
451
+ ...config,
452
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
453
+ }),
454
+ (rpcSubscriptions) => getRpcSubscriptionsWithSubscriptionCoalescing({
455
+ getDeduplicationKey: (...args) => fastStableStringify(args),
456
+ rpcSubscriptions
457
+ })
458
+ );
459
+ }
460
+ function createSolanaRpcSubscriptions_UNSTABLE(config) {
461
+ return createJsonSubscriptionRpc({
462
+ ...config,
463
+ api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG)
50
464
  });
51
465
  }
52
466
 
@@ -67,13 +481,23 @@ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
67
481
  }
68
482
  if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {
69
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
+ })();
70
497
  coalescedRequestsByDeduplicationKey[deduplicationKey] = {
71
498
  abortController,
72
499
  numConsumers: 0,
73
- responsePromise: transport({
74
- ...config,
75
- signal: abortController.signal
76
- })
500
+ responsePromise
77
501
  };
78
502
  }
79
503
  const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];
@@ -101,13 +525,14 @@ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
101
525
  }
102
526
  };
103
527
  }
104
- function getSolanaRpcPayloadDeduplicationKey(payload) {
528
+ function isJsonRpcPayload(payload) {
105
529
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
106
- return;
107
- }
108
- if ("jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && "params" in payload) {
109
- return fastStableStringify([payload.method, payload.params]);
530
+ return false;
110
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([payload.method, payload.params]) : void 0;
111
536
  }
112
537
 
113
538
  // src/rpc-transport.ts
@@ -119,7 +544,7 @@ function normalizeHeaders(headers) {
119
544
  return out;
120
545
  }
121
546
  function createDefaultRpcTransport(config) {
122
- return getRpcTransportWithRequestCoalescing(
547
+ return pipe(
123
548
  createHttpTransport({
124
549
  ...config,
125
550
  headers: {
@@ -130,10 +555,423 @@ function createDefaultRpcTransport(config) {
130
555
  }
131
556
  }
132
557
  }),
133
- getSolanaRpcPayloadDeduplicationKey
558
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
559
+ );
560
+ }
561
+
562
+ // src/rpc-websocket-autopinger.ts
563
+ var PING_PAYLOAD = {
564
+ jsonrpc: "2.0",
565
+ method: "ping"
566
+ };
567
+ function getWebSocketTransportWithAutoping({
568
+ intervalMs,
569
+ transport
570
+ }) {
571
+ const pingableConnections = /* @__PURE__ */ new Map();
572
+ return async (...args) => {
573
+ const connection = await transport(...args);
574
+ let intervalId;
575
+ function sendPing() {
576
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);
577
+ }
578
+ function restartPingTimer() {
579
+ clearInterval(intervalId);
580
+ intervalId = setInterval(sendPing, intervalMs);
581
+ }
582
+ if (pingableConnections.has(connection) === false) {
583
+ pingableConnections.set(connection, {
584
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
585
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (...args2) => {
586
+ restartPingTimer();
587
+ return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args2);
588
+ }
589
+ });
590
+ (async () => {
591
+ try {
592
+ for await (const _ of connection) {
593
+ restartPingTimer();
594
+ }
595
+ } catch {
596
+ } finally {
597
+ pingableConnections.delete(connection);
598
+ clearInterval(intervalId);
599
+ if (handleOffline) {
600
+ globalThis.window.removeEventListener("offline", handleOffline);
601
+ }
602
+ if (handleOnline) {
603
+ globalThis.window.removeEventListener("online", handleOnline);
604
+ }
605
+ }
606
+ })();
607
+ if (globalThis.navigator.onLine) {
608
+ restartPingTimer();
609
+ }
610
+ let handleOffline;
611
+ let handleOnline;
612
+ {
613
+ handleOffline = () => {
614
+ clearInterval(intervalId);
615
+ };
616
+ handleOnline = () => {
617
+ sendPing();
618
+ restartPingTimer();
619
+ };
620
+ globalThis.window.addEventListener("offline", handleOffline);
621
+ globalThis.window.addEventListener("online", handleOnline);
622
+ }
623
+ }
624
+ return pingableConnections.get(connection);
625
+ };
626
+ }
627
+
628
+ // src/rpc-websocket-connection-sharding.ts
629
+ var NULL_SHARD_CACHE_KEY = Symbol(
630
+ __DEV__ ? "Cache key to use when there is no connection sharding strategy" : void 0
631
+ );
632
+ function getWebSocketTransportWithConnectionSharding({
633
+ getShard,
634
+ transport
635
+ }) {
636
+ return getCachedAbortableIterableFactory({
637
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
638
+ getCacheEntryMissingError(shardKey) {
639
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
640
+ },
641
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
642
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
643
+ onCreateIterable: (abortSignal, config) => transport({
644
+ ...config,
645
+ signal: abortSignal
646
+ })
647
+ });
648
+ }
649
+
650
+ // src/rpc-websocket-transport.ts
651
+ function createDefaultRpcSubscriptionsTransport(config) {
652
+ const { getShard, intervalMs, ...rest } = config;
653
+ return pipe(
654
+ createWebSocketTransport({
655
+ ...rest,
656
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
657
+ 131072
658
+ }),
659
+ (transport) => getWebSocketTransportWithAutoping({
660
+ intervalMs: intervalMs ?? 5e3,
661
+ transport
662
+ }),
663
+ (transport) => getWebSocketTransportWithConnectionSharding({
664
+ getShard,
665
+ transport
666
+ })
134
667
  );
135
668
  }
136
669
 
137
- export { createDefaultRpcTransport, createSolanaRpc };
670
+ // src/transaction-confirmation-strategy-blockheight.ts
671
+ function createBlockHeightExceedencePromiseFactory({
672
+ rpc,
673
+ rpcSubscriptions
674
+ }) {
675
+ return async function getBlockHeightExceedencePromise({
676
+ abortSignal: callerAbortSignal,
677
+ commitment,
678
+ lastValidBlockHeight
679
+ }) {
680
+ const abortController = new AbortController();
681
+ const handleAbort = () => {
682
+ abortController.abort();
683
+ };
684
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
685
+ async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {
686
+ const { absoluteSlot, blockHeight } = await rpc.getEpochInfo({ commitment }).send({ abortSignal: abortController.signal });
687
+ return {
688
+ blockHeight,
689
+ differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight
690
+ };
691
+ }
692
+ try {
693
+ const [slotNotifications, { blockHeight, differenceBetweenSlotHeightAndBlockHeight }] = await Promise.all([
694
+ rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),
695
+ getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight()
696
+ ]);
697
+ if (blockHeight <= lastValidBlockHeight) {
698
+ let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;
699
+ for await (const slotNotification of slotNotifications) {
700
+ const { slot } = slotNotification;
701
+ if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {
702
+ const {
703
+ blockHeight: currentBlockHeight,
704
+ differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight
705
+ } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();
706
+ if (currentBlockHeight > lastValidBlockHeight) {
707
+ break;
708
+ } else {
709
+ lastKnownDifferenceBetweenSlotHeightAndBlockHeight = currentDifferenceBetweenSlotHeightAndBlockHeight;
710
+ }
711
+ }
712
+ }
713
+ }
714
+ throw new Error(
715
+ "The network has progressed past the last block for which this transaction could have been committed."
716
+ );
717
+ } finally {
718
+ abortController.abort();
719
+ }
720
+ };
721
+ }
722
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
723
+ 4 + // state(u32)
724
+ 32;
725
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
726
+ return async function getNonceInvalidationPromise({
727
+ abortSignal: callerAbortSignal,
728
+ commitment,
729
+ currentNonceValue,
730
+ nonceAccountAddress
731
+ }) {
732
+ const abortController = new AbortController();
733
+ function handleAbort() {
734
+ abortController.abort();
735
+ }
736
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
737
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
738
+ const base58Decoder = getBase58Decoder();
739
+ const base64Encoder = getBase64Encoder();
740
+ function getNonceFromAccountData([base64EncodedBytes]) {
741
+ const data = base64Encoder.encode(base64EncodedBytes);
742
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
743
+ return base58Decoder.decode(nonceValueBytes);
744
+ }
745
+ const nonceAccountDidAdvancePromise = (async () => {
746
+ for await (const accountNotification of accountNotifications) {
747
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
748
+ if (nonceValue !== currentNonceValue) {
749
+ throw new Error(
750
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
751
+ );
752
+ }
753
+ }
754
+ })();
755
+ const nonceIsAlreadyInvalidPromise = (async () => {
756
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
757
+ commitment,
758
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
759
+ encoding: "base58"
760
+ }).send({ abortSignal: abortController.signal });
761
+ if (!nonceAccount) {
762
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
763
+ }
764
+ const nonceValue = (
765
+ // This works because we asked for the exact slice of data representing the nonce
766
+ // value, and furthermore asked for it in `base58` encoding.
767
+ nonceAccount.data[0]
768
+ );
769
+ if (nonceValue !== currentNonceValue) {
770
+ throw new Error(
771
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
772
+ );
773
+ } else {
774
+ await new Promise(() => {
775
+ });
776
+ }
777
+ })();
778
+ try {
779
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
780
+ } finally {
781
+ abortController.abort();
782
+ }
783
+ };
784
+ }
785
+
786
+ // src/transaction-confirmation.ts
787
+ function createDefaultDurableNonceTransactionConfirmer({
788
+ rpc,
789
+ rpcSubscriptions
790
+ }) {
791
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
792
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
793
+ rpc,
794
+ rpcSubscriptions
795
+ );
796
+ return async function confirmDurableNonceTransaction(config) {
797
+ await waitForDurableNonceTransactionConfirmation({
798
+ ...config,
799
+ getNonceInvalidationPromise,
800
+ getRecentSignatureConfirmationPromise
801
+ });
802
+ };
803
+ }
804
+ function createDefaultRecentTransactionConfirmer({
805
+ rpc,
806
+ rpcSubscriptions
807
+ }) {
808
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({
809
+ rpc,
810
+ rpcSubscriptions
811
+ });
812
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
813
+ rpc,
814
+ rpcSubscriptions
815
+ );
816
+ return async function confirmRecentTransaction(config) {
817
+ await waitForRecentTransactionConfirmation({
818
+ ...config,
819
+ getBlockHeightExceedencePromise,
820
+ getRecentSignatureConfirmationPromise
821
+ });
822
+ };
823
+ }
824
+ async function waitForDurableNonceTransactionConfirmation(config) {
825
+ await raceStrategies(
826
+ getSignatureFromTransaction(config.transaction),
827
+ config,
828
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
829
+ return [
830
+ getNonceInvalidationPromise({
831
+ abortSignal,
832
+ commitment,
833
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
834
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
835
+ })
836
+ ];
837
+ }
838
+ );
839
+ }
840
+ async function waitForRecentTransactionConfirmation(config) {
841
+ await raceStrategies(
842
+ getSignatureFromTransaction(config.transaction),
843
+ config,
844
+ function getSpecificStrategiesForRace({
845
+ abortSignal,
846
+ commitment,
847
+ getBlockHeightExceedencePromise,
848
+ transaction
849
+ }) {
850
+ return [
851
+ getBlockHeightExceedencePromise({
852
+ abortSignal,
853
+ commitment,
854
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
855
+ })
856
+ ];
857
+ }
858
+ );
859
+ }
860
+
861
+ // src/send-transaction.ts
862
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
863
+ if (
864
+ // The developer has supplied no value for `preflightCommitment`.
865
+ !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
866
+ commitmentComparator(
867
+ commitment,
868
+ "finalized"
869
+ /* default value of `preflightCommitment` */
870
+ ) < 0
871
+ ) {
872
+ return {
873
+ ...config,
874
+ // In the common case, it is unlikely that you want to simulate a transaction at
875
+ // `finalized` commitment when your standard of commitment for confirming the
876
+ // transaction is lower. Cap the simulation commitment level to the level of the
877
+ // confirmation commitment.
878
+ preflightCommitment: commitment
879
+ };
880
+ }
881
+ return config;
882
+ }
883
+ async function sendTransaction_INTERNAL({
884
+ abortSignal,
885
+ commitment,
886
+ rpc,
887
+ transaction,
888
+ ...sendTransactionConfig
889
+ }) {
890
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
891
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
892
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
893
+ encoding: "base64"
894
+ }).send({ abortSignal });
895
+ }
896
+ function createDefaultDurableNonceTransactionSender({
897
+ rpc,
898
+ rpcSubscriptions
899
+ }) {
900
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
901
+ rpc,
902
+ rpcSubscriptions
903
+ });
904
+ return async function sendDurableNonceTransaction(transaction, config) {
905
+ await sendAndConfirmDurableNonceTransaction({
906
+ ...config,
907
+ confirmDurableNonceTransaction,
908
+ rpc,
909
+ transaction
910
+ });
911
+ };
912
+ }
913
+ function createDefaultTransactionSender({
914
+ rpc,
915
+ rpcSubscriptions
916
+ }) {
917
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
918
+ rpc,
919
+ rpcSubscriptions
920
+ });
921
+ return async function sendTransaction(transaction, config) {
922
+ await sendAndConfirmTransaction({
923
+ ...config,
924
+ confirmRecentTransaction,
925
+ rpc,
926
+ transaction
927
+ });
928
+ };
929
+ }
930
+ async function sendAndConfirmDurableNonceTransaction({
931
+ abortSignal,
932
+ commitment,
933
+ confirmDurableNonceTransaction,
934
+ rpc,
935
+ transaction,
936
+ ...sendTransactionConfig
937
+ }) {
938
+ const transactionSignature = await sendTransaction_INTERNAL({
939
+ ...sendTransactionConfig,
940
+ abortSignal,
941
+ commitment,
942
+ rpc,
943
+ transaction
944
+ });
945
+ await confirmDurableNonceTransaction({
946
+ abortSignal,
947
+ commitment,
948
+ transaction
949
+ });
950
+ return transactionSignature;
951
+ }
952
+ async function sendAndConfirmTransaction({
953
+ abortSignal,
954
+ commitment,
955
+ confirmRecentTransaction,
956
+ rpc,
957
+ transaction,
958
+ ...sendTransactionConfig
959
+ }) {
960
+ const transactionSignature = await sendTransaction_INTERNAL({
961
+ ...sendTransactionConfig,
962
+ abortSignal,
963
+ commitment,
964
+ rpc,
965
+ transaction
966
+ });
967
+ await confirmRecentTransaction({
968
+ abortSignal,
969
+ commitment,
970
+ transaction
971
+ });
972
+ return transactionSignature;
973
+ }
974
+
975
+ export { createBlockHeightExceedencePromiseFactory, createDefaultAirdropRequester, createDefaultDurableNonceTransactionConfirmer, createDefaultDurableNonceTransactionSender, createDefaultRecentTransactionConfirmer, createDefaultRpcSubscriptionsTransport, createDefaultRpcTransport, createDefaultTransactionSender, createNonceInvalidationPromiseFactory, createRecentSignatureConfirmationPromiseFactory, createSolanaRpc, createSolanaRpcSubscriptions, createSolanaRpcSubscriptions_UNSTABLE, decodeTransaction, requestAndConfirmAirdrop, sendAndConfirmDurableNonceTransaction, sendAndConfirmTransaction, waitForDurableNonceTransactionConfirmation, waitForRecentTransactionConfirmation };
138
976
  //# sourceMappingURL=out.js.map
139
977
  //# sourceMappingURL=index.browser.js.map