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