@solana/web3.js 2.0.0-experimental.24998c4 → 2.0.0-experimental.24d71d6

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