@solana/web3.js 2.0.0-experimental.f8229ef → 2.0.0-experimental.f8c941c

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