@solana/web3.js 2.0.0-experimental.5c3e7e8 → 2.0.0-experimental.5e737f9

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