@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,36 +1,204 @@
1
1
  'use strict';
2
2
 
3
+ var addresses = require('@solana/addresses');
4
+ var functional = require('@solana/functional');
3
5
  var instructions = require('@solana/instructions');
4
6
  var keys = require('@solana/keys');
7
+ var rpcTypes = require('@solana/rpc-types');
8
+ var transactions = require('@solana/transactions');
5
9
  var rpcCore = require('@solana/rpc-core');
6
10
  var rpcTransport = require('@solana/rpc-transport');
7
11
  var fastStableStringify = require('fast-stable-stringify');
12
+ var codecsStrings = require('@solana/codecs-strings');
8
13
 
9
14
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
15
 
11
16
  var fastStableStringify__default = /*#__PURE__*/_interopDefault(fastStableStringify);
12
17
 
13
- // 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
+ }
14
175
 
15
176
  // src/rpc-integer-overflow-error.ts
16
177
  var SolanaJsonRpcIntegerOverflowError = class extends Error {
178
+ methodName;
179
+ keyPath;
180
+ value;
17
181
  constructor(methodName, keyPath, value) {
18
- const argPosition = (typeof keyPath[0] === "number" ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;
19
- let ordinal = "";
20
- const lastDigit = argPosition % 10;
21
- const lastTwoDigits = argPosition % 100;
22
- if (lastDigit == 1 && lastTwoDigits != 11) {
23
- ordinal = argPosition + "st";
24
- } else if (lastDigit == 2 && lastTwoDigits != 12) {
25
- ordinal = argPosition + "nd";
26
- } else if (lastDigit == 3 && lastTwoDigits != 13) {
27
- 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
+ }
28
196
  } else {
29
- ordinal = argPosition + "th";
197
+ argumentLabel = `\`${keyPath[0].toString()}\``;
30
198
  }
31
199
  const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : null;
32
200
  super(
33
- `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\`.`
34
202
  );
35
203
  this.keyPath = keyPath;
36
204
  this.methodName = methodName;
@@ -43,11 +211,199 @@ var SolanaJsonRpcIntegerOverflowError = class extends Error {
43
211
 
44
212
  // src/rpc-default-config.ts
45
213
  var DEFAULT_RPC_CONFIG = {
214
+ defaultCommitment: "confirmed",
46
215
  onIntegerOverflow(methodName, keyPath, value) {
47
216
  throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);
48
217
  }
49
218
  };
50
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
+
51
407
  // src/rpc.ts
52
408
  function createSolanaRpc(config) {
53
409
  return rpcTransport.createJsonRpc({
@@ -55,6 +411,24 @@ function createSolanaRpc(config) {
55
411
  api: rpcCore.createSolanaRpcApi(DEFAULT_RPC_CONFIG)
56
412
  });
57
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
+ }
58
432
 
59
433
  // src/rpc-request-coalescer.ts
60
434
  function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
@@ -107,13 +481,14 @@ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
107
481
  }
108
482
  };
109
483
  }
110
- function getSolanaRpcPayloadDeduplicationKey(payload) {
484
+ function isJsonRpcPayload(payload) {
111
485
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
112
- return;
113
- }
114
- if ("jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && "params" in payload) {
115
- return fastStableStringify__default.default([payload.method, payload.params]);
486
+ return false;
116
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;
117
492
  }
118
493
 
119
494
  // src/rpc-transport.ts
@@ -125,7 +500,7 @@ function normalizeHeaders(headers) {
125
500
  return out;
126
501
  }
127
502
  function createDefaultRpcTransport(config) {
128
- return getRpcTransportWithRequestCoalescing(
503
+ return functional.pipe(
129
504
  rpcTransport.createHttpTransport({
130
505
  ...config,
131
506
  headers: {
@@ -136,23 +511,470 @@ function createDefaultRpcTransport(config) {
136
511
  }
137
512
  }
138
513
  }),
139
- getSolanaRpcPayloadDeduplicationKey
514
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
140
515
  );
141
516
  }
142
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({
622
+ rpc,
623
+ rpcSubscriptions
624
+ }) {
625
+ return async function getBlockHeightExceedencePromise({
626
+ abortSignal: callerAbortSignal,
627
+ commitment,
628
+ lastValidBlockHeight
629
+ }) {
630
+ const abortController = new AbortController();
631
+ const handleAbort = () => {
632
+ abortController.abort();
633
+ };
634
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
635
+ async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {
636
+ const { absoluteSlot, blockHeight } = await rpc.getEpochInfo({ commitment }).send({ abortSignal: abortController.signal });
637
+ return {
638
+ blockHeight,
639
+ differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight
640
+ };
641
+ }
642
+ try {
643
+ const [slotNotifications, { blockHeight, differenceBetweenSlotHeightAndBlockHeight }] = await Promise.all([
644
+ rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),
645
+ getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight()
646
+ ]);
647
+ if (blockHeight <= lastValidBlockHeight) {
648
+ let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;
649
+ for await (const slotNotification of slotNotifications) {
650
+ const { slot } = slotNotification;
651
+ if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {
652
+ const {
653
+ blockHeight: currentBlockHeight,
654
+ differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight
655
+ } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();
656
+ if (currentBlockHeight > lastValidBlockHeight) {
657
+ break;
658
+ } else {
659
+ lastKnownDifferenceBetweenSlotHeightAndBlockHeight = currentDifferenceBetweenSlotHeightAndBlockHeight;
660
+ }
661
+ }
662
+ }
663
+ }
664
+ throw new Error(
665
+ "The network has progressed past the last block for which this transaction could have been committed."
666
+ );
667
+ } finally {
668
+ abortController.abort();
669
+ }
670
+ };
671
+ }
672
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
673
+ 4 + // state(u32)
674
+ 32;
675
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
676
+ return async function getNonceInvalidationPromise({
677
+ abortSignal: callerAbortSignal,
678
+ commitment,
679
+ currentNonceValue,
680
+ nonceAccountAddress
681
+ }) {
682
+ const abortController = new AbortController();
683
+ function handleAbort() {
684
+ abortController.abort();
685
+ }
686
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
687
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
688
+ const base58Decoder = codecsStrings.getBase58Decoder();
689
+ const base64Encoder = codecsStrings.getBase64Encoder();
690
+ function getNonceFromAccountData([base64EncodedBytes]) {
691
+ const data = base64Encoder.encode(base64EncodedBytes);
692
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
693
+ return base58Decoder.decode(nonceValueBytes);
694
+ }
695
+ const nonceAccountDidAdvancePromise = (async () => {
696
+ for await (const accountNotification of accountNotifications) {
697
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
698
+ if (nonceValue !== currentNonceValue) {
699
+ throw new Error(
700
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
701
+ );
702
+ }
703
+ }
704
+ })();
705
+ const nonceIsAlreadyInvalidPromise = (async () => {
706
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
707
+ commitment,
708
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
709
+ encoding: "base58"
710
+ }).send({ abortSignal: abortController.signal });
711
+ if (!nonceAccount) {
712
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
713
+ }
714
+ const nonceValue = (
715
+ // This works because we asked for the exact slice of data representing the nonce
716
+ // value, and furthermore asked for it in `base58` encoding.
717
+ nonceAccount.data[0]
718
+ );
719
+ if (nonceValue !== currentNonceValue) {
720
+ throw new Error(
721
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
722
+ );
723
+ } else {
724
+ await new Promise(() => {
725
+ });
726
+ }
727
+ })();
728
+ try {
729
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
730
+ } finally {
731
+ abortController.abort();
732
+ }
733
+ };
734
+ }
735
+
736
+ // src/transaction-confirmation.ts
737
+ function createDefaultDurableNonceTransactionConfirmer({
738
+ rpc,
739
+ rpcSubscriptions
740
+ }) {
741
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
742
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
743
+ rpc,
744
+ rpcSubscriptions
745
+ );
746
+ return async function confirmDurableNonceTransaction(config) {
747
+ await waitForDurableNonceTransactionConfirmation({
748
+ ...config,
749
+ getNonceInvalidationPromise,
750
+ getRecentSignatureConfirmationPromise
751
+ });
752
+ };
753
+ }
754
+ function createDefaultRecentTransactionConfirmer({
755
+ rpc,
756
+ rpcSubscriptions
757
+ }) {
758
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({
759
+ rpc,
760
+ rpcSubscriptions
761
+ });
762
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
763
+ rpc,
764
+ rpcSubscriptions
765
+ );
766
+ return async function confirmRecentTransaction(config) {
767
+ await waitForRecentTransactionConfirmation({
768
+ ...config,
769
+ getBlockHeightExceedencePromise,
770
+ getRecentSignatureConfirmationPromise
771
+ });
772
+ };
773
+ }
774
+ async function waitForDurableNonceTransactionConfirmation(config) {
775
+ await raceStrategies(
776
+ transactions.getSignatureFromTransaction(config.transaction),
777
+ config,
778
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
779
+ return [
780
+ getNonceInvalidationPromise({
781
+ abortSignal,
782
+ commitment,
783
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
784
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
785
+ })
786
+ ];
787
+ }
788
+ );
789
+ }
790
+ async function waitForRecentTransactionConfirmation(config) {
791
+ await raceStrategies(
792
+ transactions.getSignatureFromTransaction(config.transaction),
793
+ config,
794
+ function getSpecificStrategiesForRace({
795
+ abortSignal,
796
+ commitment,
797
+ getBlockHeightExceedencePromise,
798
+ transaction
799
+ }) {
800
+ return [
801
+ getBlockHeightExceedencePromise({
802
+ abortSignal,
803
+ commitment,
804
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
805
+ })
806
+ ];
807
+ }
808
+ );
809
+ }
810
+
811
+ // src/send-transaction.ts
812
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
813
+ if (
814
+ // The developer has supplied no value for `preflightCommitment`.
815
+ !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
816
+ rpcTypes.commitmentComparator(
817
+ commitment,
818
+ "finalized"
819
+ /* default value of `preflightCommitment` */
820
+ ) < 0
821
+ ) {
822
+ return {
823
+ ...config,
824
+ // In the common case, it is unlikely that you want to simulate a transaction at
825
+ // `finalized` commitment when your standard of commitment for confirming the
826
+ // transaction is lower. Cap the simulation commitment level to the level of the
827
+ // confirmation commitment.
828
+ preflightCommitment: commitment
829
+ };
830
+ }
831
+ return config;
832
+ }
833
+ async function sendTransaction_INTERNAL({
834
+ abortSignal,
835
+ commitment,
836
+ rpc,
837
+ transaction,
838
+ ...sendTransactionConfig
839
+ }) {
840
+ const base64EncodedWireTransaction = transactions.getBase64EncodedWireTransaction(transaction);
841
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
842
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
843
+ encoding: "base64"
844
+ }).send({ abortSignal });
845
+ }
846
+ function createDefaultDurableNonceTransactionSender({
847
+ rpc,
848
+ rpcSubscriptions
849
+ }) {
850
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
851
+ rpc,
852
+ rpcSubscriptions
853
+ });
854
+ return async function sendDurableNonceTransaction(transaction, config) {
855
+ await sendAndConfirmDurableNonceTransaction({
856
+ ...config,
857
+ confirmDurableNonceTransaction,
858
+ rpc,
859
+ transaction
860
+ });
861
+ };
862
+ }
863
+ function createDefaultTransactionSender({
864
+ rpc,
865
+ rpcSubscriptions
866
+ }) {
867
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
868
+ rpc,
869
+ rpcSubscriptions
870
+ });
871
+ return async function sendTransaction(transaction, config) {
872
+ await sendAndConfirmTransaction({
873
+ ...config,
874
+ confirmRecentTransaction,
875
+ rpc,
876
+ transaction
877
+ });
878
+ };
879
+ }
880
+ async function sendAndConfirmDurableNonceTransaction({
881
+ abortSignal,
882
+ commitment,
883
+ confirmDurableNonceTransaction,
884
+ rpc,
885
+ transaction,
886
+ ...sendTransactionConfig
887
+ }) {
888
+ const transactionSignature = await sendTransaction_INTERNAL({
889
+ ...sendTransactionConfig,
890
+ abortSignal,
891
+ commitment,
892
+ rpc,
893
+ transaction
894
+ });
895
+ await confirmDurableNonceTransaction({
896
+ abortSignal,
897
+ commitment,
898
+ transaction
899
+ });
900
+ return transactionSignature;
901
+ }
902
+ async function sendAndConfirmTransaction({
903
+ abortSignal,
904
+ commitment,
905
+ confirmRecentTransaction,
906
+ rpc,
907
+ transaction,
908
+ ...sendTransactionConfig
909
+ }) {
910
+ const transactionSignature = await sendTransaction_INTERNAL({
911
+ ...sendTransactionConfig,
912
+ abortSignal,
913
+ commitment,
914
+ rpc,
915
+ transaction
916
+ });
917
+ await confirmRecentTransaction({
918
+ abortSignal,
919
+ commitment,
920
+ transaction
921
+ });
922
+ return transactionSignature;
923
+ }
924
+
925
+ exports.createBlockHeightExceedencePromiseFactory = createBlockHeightExceedencePromiseFactory;
926
+ exports.createDefaultAirdropRequester = createDefaultAirdropRequester;
927
+ exports.createDefaultDurableNonceTransactionConfirmer = createDefaultDurableNonceTransactionConfirmer;
928
+ exports.createDefaultDurableNonceTransactionSender = createDefaultDurableNonceTransactionSender;
929
+ exports.createDefaultRecentTransactionConfirmer = createDefaultRecentTransactionConfirmer;
930
+ exports.createDefaultRpcSubscriptionsTransport = createDefaultRpcSubscriptionsTransport;
143
931
  exports.createDefaultRpcTransport = createDefaultRpcTransport;
932
+ exports.createDefaultTransactionSender = createDefaultTransactionSender;
933
+ exports.createNonceInvalidationPromiseFactory = createNonceInvalidationPromiseFactory;
934
+ exports.createRecentSignatureConfirmationPromiseFactory = createRecentSignatureConfirmationPromiseFactory;
144
935
  exports.createSolanaRpc = createSolanaRpc;
936
+ exports.createSolanaRpcSubscriptions = createSolanaRpcSubscriptions;
937
+ exports.createSolanaRpcSubscriptions_UNSTABLE = createSolanaRpcSubscriptions_UNSTABLE;
938
+ exports.requestAndConfirmAirdrop = requestAndConfirmAirdrop;
939
+ exports.sendAndConfirmDurableNonceTransaction = sendAndConfirmDurableNonceTransaction;
940
+ exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
941
+ exports.waitForDurableNonceTransactionConfirmation = waitForDurableNonceTransactionConfirmation;
942
+ exports.waitForRecentTransactionConfirmation = waitForRecentTransactionConfirmation;
943
+ Object.keys(addresses).forEach(function (k) {
944
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
945
+ enumerable: true,
946
+ get: function () { return addresses[k]; }
947
+ });
948
+ });
949
+ Object.keys(functional).forEach(function (k) {
950
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
951
+ enumerable: true,
952
+ get: function () { return functional[k]; }
953
+ });
954
+ });
145
955
  Object.keys(instructions).forEach(function (k) {
146
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
956
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
147
957
  enumerable: true,
148
958
  get: function () { return instructions[k]; }
149
959
  });
150
960
  });
151
961
  Object.keys(keys).forEach(function (k) {
152
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
962
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
153
963
  enumerable: true,
154
964
  get: function () { return keys[k]; }
155
965
  });
156
966
  });
967
+ Object.keys(rpcTypes).forEach(function (k) {
968
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
969
+ enumerable: true,
970
+ get: function () { return rpcTypes[k]; }
971
+ });
972
+ });
973
+ Object.keys(transactions).forEach(function (k) {
974
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
975
+ enumerable: true,
976
+ get: function () { return transactions[k]; }
977
+ });
978
+ });
157
979
  //# sourceMappingURL=out.js.map
158
980
  //# sourceMappingURL=index.browser.cjs.map