@solana/web3.js 2.0.0-experimental.9ea7d74 → 2.0.0-experimental.a0b9a27

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