@solana/web3.js 2.0.0-experimental.ed7c7b8 → 2.0.0-experimental.ee4214c

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 (34) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +4 -4
  3. package/dist/index.browser.cjs +624 -9
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +595 -11
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +3223 -209
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +584 -11
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +613 -11
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +584 -13
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +53 -4
  16. package/dist/types/cached-abortable-iterable.d.ts +11 -0
  17. package/dist/types/index.d.ts +8 -0
  18. package/dist/types/rpc-request-coalescer.d.ts +5 -0
  19. package/dist/types/rpc-request-deduplication.d.ts +2 -0
  20. package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
  21. package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
  22. package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
  23. package/dist/types/rpc-websocket-transport.d.ts +13 -0
  24. package/dist/types/rpc.d.ts +5 -3
  25. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +10 -0
  26. package/dist/types/transaction-confirmation-strategy-nonce.d.ts +15 -0
  27. package/dist/types/transaction-confirmation-strategy-signature.d.ts +13 -0
  28. package/dist/types/transaction-confirmation.d.ts +39 -0
  29. package/package.json +26 -23
  30. package/dist/types/index.d.ts.map +0 -1
  31. package/dist/types/rpc-default-config.d.ts.map +0 -1
  32. package/dist/types/rpc-integer-overflow-error.d.ts.map +0 -1
  33. package/dist/types/rpc-transport.d.ts.map +0 -1
  34. package/dist/types/rpc.d.ts.map +0 -1
@@ -8,11 +8,12 @@ this.globalThis.solanaWeb3 = (function (exports) {
8
8
  var __getOwnPropNames = Object.getOwnPropertyNames;
9
9
  var __getProtoOf = Object.getPrototypeOf;
10
10
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
12
  var __esm = (fn, res) => function __init() {
12
13
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
14
  };
14
- var __commonJS = (cb, mod) => function __require() {
15
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ var __commonJS = (cb, mod2) => function __require() {
16
+ return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
16
17
  };
17
18
  var __copyProps = (to, from, except, desc) => {
18
19
  if (from && typeof from === "object" || typeof from === "function") {
@@ -22,194 +23,1882 @@ this.globalThis.solanaWeb3 = (function (exports) {
22
23
  }
23
24
  return to;
24
25
  };
25
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
26
27
  // If the importer is in node compatibility mode or this is not an ESM
27
28
  // file that has been converted to a CommonJS file using a Babel-
28
29
  // compatible transform (i.e. "__esModule" has not been set), then set
29
30
  // "default" to the CommonJS "module.exports" for node compatibility.
30
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
- mod
31
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
32
+ mod2
32
33
  ));
34
+ var __publicField = (obj, key, value) => {
35
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
36
+ return value;
37
+ };
38
+
39
+ // ../build-scripts/env-shim.ts
40
+ var init_env_shim = __esm({
41
+ "../build-scripts/env-shim.ts"() {
42
+ }
43
+ });
44
+
45
+ // ../../node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js
46
+ var require_fast_stable_stringify = __commonJS({
47
+ "../../node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js"(exports, module) {
48
+ init_env_shim();
49
+ var objToString = Object.prototype.toString;
50
+ var objKeys = Object.keys || function(obj) {
51
+ var keys = [];
52
+ for (var name in obj) {
53
+ keys.push(name);
54
+ }
55
+ return keys;
56
+ };
57
+ function stringify(val, isArrayProp) {
58
+ var i, max, str, keys, key, propVal, toStr;
59
+ if (val === true) {
60
+ return "true";
61
+ }
62
+ if (val === false) {
63
+ return "false";
64
+ }
65
+ switch (typeof val) {
66
+ case "object":
67
+ if (val === null) {
68
+ return null;
69
+ } else if (val.toJSON && typeof val.toJSON === "function") {
70
+ return stringify(val.toJSON(), isArrayProp);
71
+ } else {
72
+ toStr = objToString.call(val);
73
+ if (toStr === "[object Array]") {
74
+ str = "[";
75
+ max = val.length - 1;
76
+ for (i = 0; i < max; i++) {
77
+ str += stringify(val[i], true) + ",";
78
+ }
79
+ if (max > -1) {
80
+ str += stringify(val[i], true);
81
+ }
82
+ return str + "]";
83
+ } else if (toStr === "[object Object]") {
84
+ keys = objKeys(val).sort();
85
+ max = keys.length;
86
+ str = "";
87
+ i = 0;
88
+ while (i < max) {
89
+ key = keys[i];
90
+ propVal = stringify(val[key], false);
91
+ if (propVal !== void 0) {
92
+ if (str) {
93
+ str += ",";
94
+ }
95
+ str += JSON.stringify(key) + ":" + propVal;
96
+ }
97
+ i++;
98
+ }
99
+ return "{" + str + "}";
100
+ } else {
101
+ return JSON.stringify(val);
102
+ }
103
+ }
104
+ case "function":
105
+ case "undefined":
106
+ return isArrayProp ? null : void 0;
107
+ case "string":
108
+ return JSON.stringify(val);
109
+ default:
110
+ return isFinite(val) ? val : null;
111
+ }
112
+ }
113
+ module.exports = function(val) {
114
+ var returnVal = stringify(val, false);
115
+ if (returnVal !== void 0) {
116
+ return "" + returnVal;
117
+ }
118
+ };
119
+ }
120
+ });
121
+
122
+ // src/index.ts
123
+ init_env_shim();
124
+
125
+ // ../addresses/dist/index.browser.js
126
+ init_env_shim();
127
+
128
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/index.mjs
129
+ init_env_shim();
130
+
131
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/index.mjs
132
+ init_env_shim();
133
+
134
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/bytes.mjs
135
+ init_env_shim();
136
+ var mergeBytes = (bytesArr) => {
137
+ const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);
138
+ const result = new Uint8Array(totalLength);
139
+ let offset = 0;
140
+ bytesArr.forEach((arr) => {
141
+ result.set(arr, offset);
142
+ offset += arr.length;
143
+ });
144
+ return result;
145
+ };
146
+ var padBytes = (bytes2, length) => {
147
+ if (bytes2.length >= length)
148
+ return bytes2;
149
+ const paddedBytes = new Uint8Array(length).fill(0);
150
+ paddedBytes.set(bytes2);
151
+ return paddedBytes;
152
+ };
153
+ var fixBytes = (bytes2, length) => padBytes(bytes2.slice(0, length), length);
154
+
155
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/errors.mjs
156
+ init_env_shim();
157
+ var DeserializingEmptyBufferError = class extends Error {
158
+ constructor(serializer) {
159
+ super(`Serializer [${serializer}] cannot deserialize empty buffers.`);
160
+ __publicField(this, "name", "DeserializingEmptyBufferError");
161
+ }
162
+ };
163
+ var NotEnoughBytesError = class extends Error {
164
+ constructor(serializer, expected, actual) {
165
+ super(`Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`);
166
+ __publicField(this, "name", "NotEnoughBytesError");
167
+ }
168
+ };
169
+ var ExpectedFixedSizeSerializerError = class extends Error {
170
+ constructor(message) {
171
+ message ?? (message = "Expected a fixed-size serializer, got a variable-size one.");
172
+ super(message);
173
+ __publicField(this, "name", "ExpectedFixedSizeSerializerError");
174
+ }
175
+ };
176
+
177
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/fixSerializer.mjs
178
+ init_env_shim();
179
+ function fixSerializer(serializer, fixedBytes, description) {
180
+ return {
181
+ description: description ?? `fixed(${fixedBytes}, ${serializer.description})`,
182
+ fixedSize: fixedBytes,
183
+ maxSize: fixedBytes,
184
+ serialize: (value) => fixBytes(serializer.serialize(value), fixedBytes),
185
+ deserialize: (buffer, offset = 0) => {
186
+ buffer = buffer.slice(offset, offset + fixedBytes);
187
+ if (buffer.length < fixedBytes) {
188
+ throw new NotEnoughBytesError("fixSerializer", fixedBytes, buffer.length);
189
+ }
190
+ if (serializer.fixedSize !== null) {
191
+ buffer = fixBytes(buffer, serializer.fixedSize);
192
+ }
193
+ const [value] = serializer.deserialize(buffer, 0);
194
+ return [value, offset + fixedBytes];
195
+ }
196
+ };
197
+ }
198
+
199
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.9/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/mapSerializer.mjs
200
+ init_env_shim();
201
+ function mapSerializer(serializer, unmap, map) {
202
+ return {
203
+ description: serializer.description,
204
+ fixedSize: serializer.fixedSize,
205
+ maxSize: serializer.maxSize,
206
+ serialize: (value) => serializer.serialize(unmap(value)),
207
+ deserialize: (buffer, offset = 0) => {
208
+ const [value, length] = serializer.deserialize(buffer, offset);
209
+ return map ? [map(value, buffer, offset), length] : [value, length];
210
+ }
211
+ };
212
+ }
213
+
214
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/index.mjs
215
+ init_env_shim();
216
+
217
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
218
+ init_env_shim();
219
+
220
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/errors.mjs
221
+ init_env_shim();
222
+ var InvalidBaseStringError = class extends Error {
223
+ constructor(value, base, cause) {
224
+ const message = `Expected a string of base ${base}, got [${value}].`;
225
+ super(message);
226
+ __publicField(this, "name", "InvalidBaseStringError");
227
+ this.cause = cause;
228
+ }
229
+ };
230
+
231
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
232
+ var baseX = (alphabet) => {
233
+ const base = alphabet.length;
234
+ const baseBigInt = BigInt(base);
235
+ return {
236
+ description: `base${base}`,
237
+ fixedSize: null,
238
+ maxSize: null,
239
+ serialize(value) {
240
+ if (!value.match(new RegExp(`^[${alphabet}]*$`))) {
241
+ throw new InvalidBaseStringError(value, base);
242
+ }
243
+ if (value === "")
244
+ return new Uint8Array();
245
+ const chars = [...value];
246
+ let trailIndex = chars.findIndex((c) => c !== alphabet[0]);
247
+ trailIndex = trailIndex === -1 ? chars.length : trailIndex;
248
+ const leadingZeroes = Array(trailIndex).fill(0);
249
+ if (trailIndex === chars.length)
250
+ return Uint8Array.from(leadingZeroes);
251
+ const tailChars = chars.slice(trailIndex);
252
+ let base10Number = 0n;
253
+ let baseXPower = 1n;
254
+ for (let i = tailChars.length - 1; i >= 0; i -= 1) {
255
+ base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));
256
+ baseXPower *= baseBigInt;
257
+ }
258
+ const tailBytes = [];
259
+ while (base10Number > 0n) {
260
+ tailBytes.unshift(Number(base10Number % 256n));
261
+ base10Number /= 256n;
262
+ }
263
+ return Uint8Array.from(leadingZeroes.concat(tailBytes));
264
+ },
265
+ deserialize(buffer, offset = 0) {
266
+ if (buffer.length === 0)
267
+ return ["", 0];
268
+ const bytes2 = buffer.slice(offset);
269
+ let trailIndex = bytes2.findIndex((n) => n !== 0);
270
+ trailIndex = trailIndex === -1 ? bytes2.length : trailIndex;
271
+ const leadingZeroes = alphabet[0].repeat(trailIndex);
272
+ if (trailIndex === bytes2.length)
273
+ return [leadingZeroes, buffer.length];
274
+ let base10Number = bytes2.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
275
+ const tailChars = [];
276
+ while (base10Number > 0n) {
277
+ tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);
278
+ base10Number /= baseBigInt;
279
+ }
280
+ return [leadingZeroes + tailChars.join(""), buffer.length];
281
+ }
282
+ };
283
+ };
284
+
285
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base58.mjs
286
+ init_env_shim();
287
+ var base58 = baseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
288
+
289
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base64.mjs
290
+ init_env_shim();
291
+
292
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseXReslice.mjs
293
+ init_env_shim();
294
+ var baseXReslice = (alphabet, bits) => {
295
+ const base = alphabet.length;
296
+ const reslice = (input, inputBits, outputBits, useRemainder) => {
297
+ const output = [];
298
+ let accumulator = 0;
299
+ let bitsInAccumulator = 0;
300
+ const mask = (1 << outputBits) - 1;
301
+ for (const value of input) {
302
+ accumulator = accumulator << inputBits | value;
303
+ bitsInAccumulator += inputBits;
304
+ while (bitsInAccumulator >= outputBits) {
305
+ bitsInAccumulator -= outputBits;
306
+ output.push(accumulator >> bitsInAccumulator & mask);
307
+ }
308
+ }
309
+ if (useRemainder && bitsInAccumulator > 0) {
310
+ output.push(accumulator << outputBits - bitsInAccumulator & mask);
311
+ }
312
+ return output;
313
+ };
314
+ return {
315
+ description: `base${base}`,
316
+ fixedSize: null,
317
+ maxSize: null,
318
+ serialize(value) {
319
+ if (!value.match(new RegExp(`^[${alphabet}]*$`))) {
320
+ throw new InvalidBaseStringError(value, base);
321
+ }
322
+ if (value === "")
323
+ return new Uint8Array();
324
+ const charIndices = [...value].map((c) => alphabet.indexOf(c));
325
+ const bytes2 = reslice(charIndices, bits, 8, false);
326
+ return Uint8Array.from(bytes2);
327
+ },
328
+ deserialize(buffer, offset = 0) {
329
+ if (buffer.length === 0)
330
+ return ["", 0];
331
+ const bytes2 = [...buffer.slice(offset)];
332
+ const charIndices = reslice(bytes2, 8, bits, true);
333
+ return [charIndices.map((i) => alphabet[i]).join(""), buffer.length];
334
+ }
335
+ };
336
+ };
337
+
338
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base64.mjs
339
+ var base64 = mapSerializer(baseXReslice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 6), (value) => value.replace(/=/g, ""), (value) => value.padEnd(Math.ceil(value.length / 4) * 4, "="));
340
+
341
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/nullCharacters.mjs
342
+ init_env_shim();
343
+ var removeNullCharacters = (value) => (
344
+ // eslint-disable-next-line no-control-regex
345
+ value.replace(/\u0000/g, "")
346
+ );
347
+
348
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/utf8.mjs
349
+ init_env_shim();
350
+ var utf8 = {
351
+ description: "utf8",
352
+ fixedSize: null,
353
+ maxSize: null,
354
+ serialize(value) {
355
+ return new TextEncoder().encode(value);
356
+ },
357
+ deserialize(buffer, offset = 0) {
358
+ const value = new TextDecoder().decode(buffer.slice(offset));
359
+ return [removeNullCharacters(value), buffer.length];
360
+ }
361
+ };
362
+
363
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/index.mjs
364
+ init_env_shim();
365
+
366
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs
367
+ init_env_shim();
368
+ var Endian;
369
+ (function(Endian2) {
370
+ Endian2["Little"] = "le";
371
+ Endian2["Big"] = "be";
372
+ })(Endian || (Endian = {}));
373
+
374
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs
375
+ init_env_shim();
376
+ var NumberOutOfRangeError = class extends RangeError {
377
+ constructor(serializer, min, max, actual) {
378
+ super(`Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`);
379
+ __publicField(this, "name", "NumberOutOfRangeError");
380
+ }
381
+ };
382
+
383
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/utils.mjs
384
+ init_env_shim();
385
+ function numberFactory(input) {
386
+ let littleEndian;
387
+ let defaultDescription = input.name;
388
+ if (input.size > 1) {
389
+ littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little;
390
+ defaultDescription += littleEndian ? "(le)" : "(be)";
391
+ }
392
+ return {
393
+ description: input.options.description ?? defaultDescription,
394
+ fixedSize: input.size,
395
+ maxSize: input.size,
396
+ serialize(value) {
397
+ if (input.range) {
398
+ assertRange(input.name, input.range[0], input.range[1], value);
399
+ }
400
+ const buffer = new ArrayBuffer(input.size);
401
+ input.set(new DataView(buffer), value, littleEndian);
402
+ return new Uint8Array(buffer);
403
+ },
404
+ deserialize(bytes2, offset = 0) {
405
+ const slice = bytes2.slice(offset, offset + input.size);
406
+ assertEnoughBytes("i8", slice, input.size);
407
+ const view = toDataView(slice);
408
+ return [input.get(view, littleEndian), offset + input.size];
409
+ }
410
+ };
411
+ }
412
+ var toArrayBuffer = (array2) => array2.buffer.slice(array2.byteOffset, array2.byteLength + array2.byteOffset);
413
+ var toDataView = (array2) => new DataView(toArrayBuffer(array2));
414
+ var assertRange = (serializer, min, max, value) => {
415
+ if (value < min || value > max) {
416
+ throw new NumberOutOfRangeError(serializer, min, max, value);
417
+ }
418
+ };
419
+ var assertEnoughBytes = (serializer, bytes2, expected) => {
420
+ if (bytes2.length === 0) {
421
+ throw new DeserializingEmptyBufferError(serializer);
422
+ }
423
+ if (bytes2.length < expected) {
424
+ throw new NotEnoughBytesError(serializer, expected, bytes2.length);
425
+ }
426
+ };
427
+
428
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u8.mjs
429
+ init_env_shim();
430
+ var u8 = (options = {}) => numberFactory({
431
+ name: "u8",
432
+ size: 1,
433
+ range: [0, Number("0xff")],
434
+ set: (view, value) => view.setUint8(0, Number(value)),
435
+ get: (view) => view.getUint8(0),
436
+ options
437
+ });
438
+
439
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u32.mjs
440
+ init_env_shim();
441
+ var u32 = (options = {}) => numberFactory({
442
+ name: "u32",
443
+ size: 4,
444
+ range: [0, Number("0xffffffff")],
445
+ set: (view, value, le) => view.setUint32(0, Number(value), le),
446
+ get: (view, le) => view.getUint32(0, le),
447
+ options
448
+ });
449
+
450
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/shortU16.mjs
451
+ init_env_shim();
452
+ var shortU16 = (options = {}) => ({
453
+ description: options.description ?? "shortU16",
454
+ fixedSize: null,
455
+ maxSize: 3,
456
+ serialize: (value) => {
457
+ assertRange("shortU16", 0, 65535, value);
458
+ const bytes2 = [0];
459
+ for (let ii = 0; ; ii += 1) {
460
+ const alignedValue = value >> ii * 7;
461
+ if (alignedValue === 0) {
462
+ break;
463
+ }
464
+ const nextSevenBits = 127 & alignedValue;
465
+ bytes2[ii] = nextSevenBits;
466
+ if (ii > 0) {
467
+ bytes2[ii - 1] |= 128;
468
+ }
469
+ }
470
+ return new Uint8Array(bytes2);
471
+ },
472
+ deserialize: (bytes2, offset = 0) => {
473
+ let value = 0;
474
+ let byteCount = 0;
475
+ while (++byteCount) {
476
+ const byteIndex = byteCount - 1;
477
+ const currentByte = bytes2[offset + byteIndex];
478
+ const nextSevenBits = 127 & currentByte;
479
+ value |= nextSevenBits << byteIndex * 7;
480
+ if ((currentByte & 128) === 0) {
481
+ break;
482
+ }
483
+ }
484
+ return [value, offset + byteCount];
485
+ }
486
+ });
487
+
488
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs
489
+ init_env_shim();
490
+
491
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/errors.mjs
492
+ init_env_shim();
493
+ var InvalidNumberOfItemsError = class extends Error {
494
+ constructor(serializer, expected, actual) {
495
+ super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);
496
+ __publicField(this, "name", "InvalidNumberOfItemsError");
497
+ }
498
+ };
499
+ var InvalidArrayLikeRemainderSizeError = class extends Error {
500
+ constructor(remainderSize, itemSize) {
501
+ super(`The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. Serializers of "remainder" size must have a remainder that is a multiple of its item size. In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`);
502
+ __publicField(this, "name", "InvalidArrayLikeRemainderSizeError");
503
+ }
504
+ };
505
+ var UnrecognizedArrayLikeSerializerSizeError = class extends Error {
506
+ constructor(size) {
507
+ super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);
508
+ __publicField(this, "name", "UnrecognizedArrayLikeSerializerSizeError");
509
+ }
510
+ };
511
+
512
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
513
+ init_env_shim();
514
+
515
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/sumSerializerSizes.mjs
516
+ init_env_shim();
517
+ function sumSerializerSizes(sizes) {
518
+ return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
519
+ }
520
+
521
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
522
+ function getResolvedSize(size, childrenSizes, bytes2, offset) {
523
+ if (typeof size === "number") {
524
+ return [size, offset];
525
+ }
526
+ if (typeof size === "object") {
527
+ return size.deserialize(bytes2, offset);
528
+ }
529
+ if (size === "remainder") {
530
+ const childrenSize = sumSerializerSizes(childrenSizes);
531
+ if (childrenSize === null) {
532
+ throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.');
533
+ }
534
+ const remainder = bytes2.slice(offset).length;
535
+ if (remainder % childrenSize !== 0) {
536
+ throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);
537
+ }
538
+ return [remainder / childrenSize, offset];
539
+ }
540
+ throw new UnrecognizedArrayLikeSerializerSizeError(size);
541
+ }
542
+ function getSizeDescription(size) {
543
+ return typeof size === "object" ? size.description : `${size}`;
544
+ }
545
+ function getSizeFromChildren(size, childrenSizes) {
546
+ if (typeof size !== "number")
547
+ return null;
548
+ if (size === 0)
549
+ return 0;
550
+ const childrenSize = sumSerializerSizes(childrenSizes);
551
+ return childrenSize === null ? null : childrenSize * size;
552
+ }
553
+ function getSizePrefix(size, realSize) {
554
+ return typeof size === "object" ? size.serialize(realSize) : new Uint8Array();
555
+ }
556
+
557
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs
558
+ function array(item, options = {}) {
559
+ const size = options.size ?? u32();
560
+ if (size === "remainder" && item.fixedSize === null) {
561
+ throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.');
562
+ }
563
+ return {
564
+ description: options.description ?? `array(${item.description}; ${getSizeDescription(size)})`,
565
+ fixedSize: getSizeFromChildren(size, [item.fixedSize]),
566
+ maxSize: getSizeFromChildren(size, [item.maxSize]),
567
+ serialize: (value) => {
568
+ if (typeof size === "number" && value.length !== size) {
569
+ throw new InvalidNumberOfItemsError("array", size, value.length);
570
+ }
571
+ return mergeBytes([getSizePrefix(size, value.length), ...value.map((v) => item.serialize(v))]);
572
+ },
573
+ deserialize: (bytes2, offset = 0) => {
574
+ if (typeof size === "object" && bytes2.slice(offset).length === 0) {
575
+ return [[], offset];
576
+ }
577
+ const [resolvedSize, newOffset] = getResolvedSize(size, [item.fixedSize], bytes2, offset);
578
+ offset = newOffset;
579
+ const values = [];
580
+ for (let i = 0; i < resolvedSize; i += 1) {
581
+ const [value, newOffset2] = item.deserialize(bytes2, offset);
582
+ values.push(value);
583
+ offset = newOffset2;
584
+ }
585
+ return [values, offset];
586
+ }
587
+ };
588
+ }
589
+
590
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/bytes.mjs
591
+ init_env_shim();
592
+ function bytes(options = {}) {
593
+ const size = options.size ?? "variable";
594
+ const description = options.description ?? `bytes(${getSizeDescription(size)})`;
595
+ const byteSerializer = {
596
+ description,
597
+ fixedSize: null,
598
+ maxSize: null,
599
+ serialize: (value) => new Uint8Array(value),
600
+ deserialize: (bytes2, offset = 0) => {
601
+ const slice = bytes2.slice(offset);
602
+ return [slice, offset + slice.length];
603
+ }
604
+ };
605
+ if (size === "variable") {
606
+ return byteSerializer;
607
+ }
608
+ if (typeof size === "number") {
609
+ return fixSerializer(byteSerializer, size, description);
610
+ }
611
+ return {
612
+ description,
613
+ fixedSize: null,
614
+ maxSize: null,
615
+ serialize: (value) => {
616
+ const contentBytes = byteSerializer.serialize(value);
617
+ const lengthBytes = size.serialize(contentBytes.length);
618
+ return mergeBytes([lengthBytes, contentBytes]);
619
+ },
620
+ deserialize: (buffer, offset = 0) => {
621
+ if (buffer.slice(offset).length === 0) {
622
+ throw new DeserializingEmptyBufferError("bytes");
623
+ }
624
+ const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
625
+ const length = Number(lengthBigInt);
626
+ offset = lengthOffset;
627
+ const contentBuffer = buffer.slice(offset, offset + length);
628
+ if (contentBuffer.length < length) {
629
+ throw new NotEnoughBytesError("bytes", length, contentBuffer.length);
630
+ }
631
+ const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);
632
+ offset += contentOffset;
633
+ return [value, offset];
634
+ }
635
+ };
636
+ }
637
+
638
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs
639
+ init_env_shim();
640
+ function string(options = {}) {
641
+ const size = options.size ?? u32();
642
+ const encoding = options.encoding ?? utf8;
643
+ const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
644
+ if (size === "variable") {
645
+ return {
646
+ ...encoding,
647
+ description
648
+ };
649
+ }
650
+ if (typeof size === "number") {
651
+ return fixSerializer(encoding, size, description);
652
+ }
653
+ return {
654
+ description,
655
+ fixedSize: null,
656
+ maxSize: null,
657
+ serialize: (value) => {
658
+ const contentBytes = encoding.serialize(value);
659
+ const lengthBytes = size.serialize(contentBytes.length);
660
+ return mergeBytes([lengthBytes, contentBytes]);
661
+ },
662
+ deserialize: (buffer, offset = 0) => {
663
+ if (buffer.slice(offset).length === 0) {
664
+ throw new DeserializingEmptyBufferError("string");
665
+ }
666
+ const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
667
+ const length = Number(lengthBigInt);
668
+ offset = lengthOffset;
669
+ const contentBuffer = buffer.slice(offset, offset + length);
670
+ if (contentBuffer.length < length) {
671
+ throw new NotEnoughBytesError("string", length, contentBuffer.length);
672
+ }
673
+ const [value, contentOffset] = encoding.deserialize(contentBuffer);
674
+ offset += contentOffset;
675
+ return [value, offset];
676
+ }
677
+ };
678
+ }
679
+
680
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/struct.mjs
681
+ init_env_shim();
682
+ function struct(fields, options = {}) {
683
+ const fieldDescriptions = fields.map(([name, serializer]) => `${String(name)}: ${serializer.description}`).join(", ");
684
+ return {
685
+ description: options.description ?? `struct(${fieldDescriptions})`,
686
+ fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),
687
+ maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),
688
+ serialize: (struct2) => {
689
+ const fieldBytes = fields.map(([key, serializer]) => serializer.serialize(struct2[key]));
690
+ return mergeBytes(fieldBytes);
691
+ },
692
+ deserialize: (bytes2, offset = 0) => {
693
+ const struct2 = {};
694
+ fields.forEach(([key, serializer]) => {
695
+ const [value, newOffset] = serializer.deserialize(bytes2, offset);
696
+ offset = newOffset;
697
+ struct2[key] = value;
698
+ });
699
+ return [struct2, offset];
700
+ }
701
+ };
702
+ }
703
+
704
+ // ../assertions/dist/index.browser.js
705
+ init_env_shim();
706
+ function assertIsSecureContext() {
707
+ if (!globalThis.isSecureContext) {
708
+ throw new Error(
709
+ "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
710
+ );
711
+ }
712
+ }
713
+ var cachedEd25519Decision;
714
+ async function isEd25519CurveSupported(subtle) {
715
+ if (cachedEd25519Decision === void 0) {
716
+ cachedEd25519Decision = new Promise((resolve) => {
717
+ subtle.generateKey(
718
+ "Ed25519",
719
+ /* extractable */
720
+ false,
721
+ ["sign", "verify"]
722
+ ).catch(() => {
723
+ resolve(cachedEd25519Decision = false);
724
+ }).then(() => {
725
+ resolve(cachedEd25519Decision = true);
726
+ });
727
+ });
728
+ }
729
+ if (typeof cachedEd25519Decision === "boolean") {
730
+ return cachedEd25519Decision;
731
+ } else {
732
+ return await cachedEd25519Decision;
733
+ }
734
+ }
735
+ async function assertDigestCapabilityIsAvailable() {
736
+ assertIsSecureContext();
737
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.digest !== "function") {
738
+ throw new Error("No digest implementation could be found");
739
+ }
740
+ }
741
+ async function assertKeyGenerationIsAvailable() {
742
+ assertIsSecureContext();
743
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
744
+ throw new Error("No key generation implementation could be found");
745
+ }
746
+ if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
747
+ throw new Error(
748
+ "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall and import `@solana/webcrypto-ed25519-polyfill` before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20"
749
+ );
750
+ }
751
+ }
752
+ async function assertKeyExporterIsAvailable() {
753
+ assertIsSecureContext();
754
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
755
+ throw new Error("No key export implementation could be found");
756
+ }
757
+ }
758
+ async function assertSigningCapabilityIsAvailable() {
759
+ assertIsSecureContext();
760
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
761
+ throw new Error("No signing implementation could be found");
762
+ }
763
+ }
764
+ async function assertVerificationCapabilityIsAvailable() {
765
+ assertIsSecureContext();
766
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
767
+ throw new Error("No signature verification implementation could be found");
768
+ }
769
+ }
770
+ function isAddress(putativeBase58EncodedAddress) {
771
+ if (
772
+ // Lowest address (32 bytes of zeroes)
773
+ putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
774
+ putativeBase58EncodedAddress.length > 44
775
+ ) {
776
+ return false;
777
+ }
778
+ const bytes2 = base58.serialize(putativeBase58EncodedAddress);
779
+ const numBytes = bytes2.byteLength;
780
+ if (numBytes !== 32) {
781
+ return false;
782
+ }
783
+ return true;
784
+ }
785
+ function assertIsAddress(putativeBase58EncodedAddress) {
786
+ try {
787
+ if (
788
+ // Lowest address (32 bytes of zeroes)
789
+ putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
790
+ putativeBase58EncodedAddress.length > 44
791
+ ) {
792
+ throw new Error("Expected input string to decode to a byte array of length 32.");
793
+ }
794
+ const bytes2 = base58.serialize(putativeBase58EncodedAddress);
795
+ const numBytes = bytes2.byteLength;
796
+ if (numBytes !== 32) {
797
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
798
+ }
799
+ } catch (e3) {
800
+ throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
801
+ cause: e3
802
+ });
803
+ }
804
+ }
805
+ function address(putativeBase58EncodedAddress) {
806
+ assertIsAddress(putativeBase58EncodedAddress);
807
+ return putativeBase58EncodedAddress;
808
+ }
809
+ function getAddressCodec(config) {
810
+ return string({
811
+ description: config?.description ?? ("A 32-byte account address" ),
812
+ encoding: base58,
813
+ size: 32
814
+ });
815
+ }
816
+ function getAddressComparator() {
817
+ return new Intl.Collator("en", {
818
+ caseFirst: "lower",
819
+ ignorePunctuation: false,
820
+ localeMatcher: "best fit",
821
+ numeric: false,
822
+ sensitivity: "variant",
823
+ usage: "sort"
824
+ }).compare;
825
+ }
826
+ var D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
827
+ var P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;
828
+ var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
829
+ function mod(a) {
830
+ const r = a % P;
831
+ return r >= 0n ? r : P + r;
832
+ }
833
+ function pow2(x, power) {
834
+ let r = x;
835
+ while (power-- > 0n) {
836
+ r *= r;
837
+ r %= P;
838
+ }
839
+ return r;
840
+ }
841
+ function pow_2_252_3(x) {
842
+ const x2 = x * x % P;
843
+ const b2 = x2 * x % P;
844
+ const b4 = pow2(b2, 2n) * b2 % P;
845
+ const b5 = pow2(b4, 1n) * x % P;
846
+ const b10 = pow2(b5, 5n) * b5 % P;
847
+ const b20 = pow2(b10, 10n) * b10 % P;
848
+ const b40 = pow2(b20, 20n) * b20 % P;
849
+ const b80 = pow2(b40, 40n) * b40 % P;
850
+ const b160 = pow2(b80, 80n) * b80 % P;
851
+ const b240 = pow2(b160, 80n) * b80 % P;
852
+ const b250 = pow2(b240, 10n) * b10 % P;
853
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
854
+ return pow_p_5_8;
855
+ }
856
+ function uvRatio(u, v) {
857
+ const v3 = mod(v * v * v);
858
+ const v7 = mod(v3 * v3 * v);
859
+ const pow = pow_2_252_3(u * v7);
860
+ let x = mod(u * v3 * pow);
861
+ const vx2 = mod(v * x * x);
862
+ const root1 = x;
863
+ const root2 = mod(x * RM1);
864
+ const useRoot1 = vx2 === u;
865
+ const useRoot2 = vx2 === mod(-u);
866
+ const noRoot = vx2 === mod(-u * RM1);
867
+ if (useRoot1)
868
+ x = root1;
869
+ if (useRoot2 || noRoot)
870
+ x = root2;
871
+ if ((mod(x) & 1n) === 1n)
872
+ x = mod(-x);
873
+ if (!useRoot1 && !useRoot2) {
874
+ return null;
875
+ }
876
+ return x;
877
+ }
878
+ function pointIsOnCurve(y, lastByte) {
879
+ const y2 = mod(y * y);
880
+ const u = mod(y2 - 1n);
881
+ const v = mod(D * y2 + 1n);
882
+ const x = uvRatio(u, v);
883
+ if (x === null) {
884
+ return false;
885
+ }
886
+ const isLastByteOdd = (lastByte & 128) !== 0;
887
+ if (x === 0n && isLastByteOdd) {
888
+ return false;
889
+ }
890
+ return true;
891
+ }
892
+ function byteToHex(byte) {
893
+ const hexString = byte.toString(16);
894
+ if (hexString.length === 1) {
895
+ return `0${hexString}`;
896
+ } else {
897
+ return hexString;
898
+ }
899
+ }
900
+ function decompressPointBytes(bytes2) {
901
+ const hexString = bytes2.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
902
+ const integerLiteralString = `0x${hexString}`;
903
+ return BigInt(integerLiteralString);
904
+ }
905
+ async function compressedPointBytesAreOnCurve(bytes2) {
906
+ if (bytes2.byteLength !== 32) {
907
+ return false;
908
+ }
909
+ const y = decompressPointBytes(bytes2);
910
+ return pointIsOnCurve(y, bytes2[31]);
911
+ }
912
+ function isProgramDerivedAddress(value) {
913
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
914
+ }
915
+ function assertIsProgramDerivedAddress(value) {
916
+ const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
917
+ if (!validFormat) {
918
+ throw new Error(
919
+ `Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].`
920
+ );
921
+ }
922
+ if (value[1] < 0 || value[1] > 255) {
923
+ throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);
924
+ }
925
+ assertIsAddress(value[0]);
926
+ }
927
+ var MAX_SEED_LENGTH = 32;
928
+ var MAX_SEEDS = 16;
929
+ var PDA_MARKER_BYTES = [
930
+ // The string 'ProgramDerivedAddress'
931
+ 80,
932
+ 114,
933
+ 111,
934
+ 103,
935
+ 114,
936
+ 97,
937
+ 109,
938
+ 68,
939
+ 101,
940
+ 114,
941
+ 105,
942
+ 118,
943
+ 101,
944
+ 100,
945
+ 65,
946
+ 100,
947
+ 100,
948
+ 114,
949
+ 101,
950
+ 115,
951
+ 115
952
+ ];
953
+ var PointOnCurveError = class extends Error {
954
+ };
955
+ async function createProgramDerivedAddress({
956
+ programAddress,
957
+ seeds
958
+ }) {
959
+ await assertDigestCapabilityIsAvailable();
960
+ if (seeds.length > MAX_SEEDS) {
961
+ throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);
962
+ }
963
+ let textEncoder;
964
+ const seedBytes = seeds.reduce((acc, seed, ii) => {
965
+ const bytes2 = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
966
+ if (bytes2.byteLength > MAX_SEED_LENGTH) {
967
+ throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);
968
+ }
969
+ acc.push(...bytes2);
970
+ return acc;
971
+ }, []);
972
+ const base58EncodedAddressCodec = getAddressCodec();
973
+ const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);
974
+ const addressBytesBuffer = await crypto.subtle.digest(
975
+ "SHA-256",
976
+ new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
977
+ );
978
+ const addressBytes = new Uint8Array(addressBytesBuffer);
979
+ if (await compressedPointBytesAreOnCurve(addressBytes)) {
980
+ throw new PointOnCurveError("Invalid seeds; point must fall off the Ed25519 curve");
981
+ }
982
+ return base58EncodedAddressCodec.deserialize(addressBytes)[0];
983
+ }
984
+ async function getProgramDerivedAddress({
985
+ programAddress,
986
+ seeds
987
+ }) {
988
+ let bumpSeed = 255;
989
+ while (bumpSeed > 0) {
990
+ try {
991
+ const address2 = await createProgramDerivedAddress({
992
+ programAddress,
993
+ seeds: [...seeds, new Uint8Array([bumpSeed])]
994
+ });
995
+ return [address2, bumpSeed];
996
+ } catch (e3) {
997
+ if (e3 instanceof PointOnCurveError) {
998
+ bumpSeed--;
999
+ } else {
1000
+ throw e3;
1001
+ }
1002
+ }
1003
+ }
1004
+ throw new Error("Unable to find a viable program address bump seed");
1005
+ }
1006
+ async function createAddressWithSeed({
1007
+ baseAddress,
1008
+ programAddress,
1009
+ seed
1010
+ }) {
1011
+ const { serialize: serialize4, deserialize: deserialize2 } = getAddressCodec();
1012
+ const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
1013
+ if (seedBytes.byteLength > MAX_SEED_LENGTH) {
1014
+ throw new Error(`The seed exceeds the maximum length of 32 bytes`);
1015
+ }
1016
+ const programAddressBytes = serialize4(programAddress);
1017
+ if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
1018
+ throw new Error(`programAddress cannot end with the PDA marker`);
1019
+ }
1020
+ const addressBytesBuffer = await crypto.subtle.digest(
1021
+ "SHA-256",
1022
+ new Uint8Array([...serialize4(baseAddress), ...seedBytes, ...programAddressBytes])
1023
+ );
1024
+ const addressBytes = new Uint8Array(addressBytesBuffer);
1025
+ return deserialize2(addressBytes)[0];
1026
+ }
1027
+ async function getAddressFromPublicKey(publicKey) {
1028
+ await assertKeyExporterIsAvailable();
1029
+ if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
1030
+ throw new Error("The `CryptoKey` must be an `Ed25519` public key");
1031
+ }
1032
+ const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
1033
+ const [base58EncodedAddress] = getAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
1034
+ return base58EncodedAddress;
1035
+ }
1036
+
1037
+ // ../instructions/dist/index.browser.js
1038
+ init_env_shim();
1039
+ var AccountRole = /* @__PURE__ */ ((AccountRole22) => {
1040
+ AccountRole22[AccountRole22["WRITABLE_SIGNER"] = /* 3 */
1041
+ 3] = "WRITABLE_SIGNER";
1042
+ AccountRole22[AccountRole22["READONLY_SIGNER"] = /* 2 */
1043
+ 2] = "READONLY_SIGNER";
1044
+ AccountRole22[AccountRole22["WRITABLE"] = /* 1 */
1045
+ 1] = "WRITABLE";
1046
+ AccountRole22[AccountRole22["READONLY"] = /* 0 */
1047
+ 0] = "READONLY";
1048
+ return AccountRole22;
1049
+ })(AccountRole || {});
1050
+ var IS_SIGNER_BITMASK = 2;
1051
+ var IS_WRITABLE_BITMASK = 1;
1052
+ function downgradeRoleToNonSigner(role) {
1053
+ return role & ~IS_SIGNER_BITMASK;
1054
+ }
1055
+ function downgradeRoleToReadonly(role) {
1056
+ return role & ~IS_WRITABLE_BITMASK;
1057
+ }
1058
+ function isSignerRole(role) {
1059
+ return role >= 2;
1060
+ }
1061
+ function isWritableRole(role) {
1062
+ return (role & IS_WRITABLE_BITMASK) !== 0;
1063
+ }
1064
+ function mergeRoles(roleA, roleB) {
1065
+ return roleA | roleB;
1066
+ }
1067
+ function upgradeRoleToSigner(role) {
1068
+ return role | IS_SIGNER_BITMASK;
1069
+ }
1070
+ function upgradeRoleToWritable(role) {
1071
+ return role | IS_WRITABLE_BITMASK;
1072
+ }
1073
+
1074
+ // ../keys/dist/index.browser.js
1075
+ init_env_shim();
1076
+ async function generateKeyPair() {
1077
+ await assertKeyGenerationIsAvailable();
1078
+ const keyPair = await crypto.subtle.generateKey(
1079
+ /* algorithm */
1080
+ "Ed25519",
1081
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
1082
+ /* extractable */
1083
+ false,
1084
+ // Prevents the bytes of the private key from being visible to JS.
1085
+ /* allowed uses */
1086
+ ["sign", "verify"]
1087
+ );
1088
+ return keyPair;
1089
+ }
1090
+ async function signBytes(key, data) {
1091
+ await assertSigningCapabilityIsAvailable();
1092
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
1093
+ return new Uint8Array(signedData);
1094
+ }
1095
+ async function verifySignature(key, signature, data) {
1096
+ await assertVerificationCapabilityIsAvailable();
1097
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
1098
+ }
33
1099
 
34
- // ../build-scripts/env-shim.ts
35
- var init_env_shim = __esm({
36
- "../build-scripts/env-shim.ts"() {
1100
+ // ../transactions/dist/index.browser.js
1101
+ init_env_shim();
1102
+ function getUnsignedTransaction(transaction) {
1103
+ if ("signatures" in transaction) {
1104
+ const {
1105
+ signatures: _,
1106
+ // eslint-disable-line @typescript-eslint/no-unused-vars
1107
+ ...unsignedTransaction
1108
+ } = transaction;
1109
+ return unsignedTransaction;
1110
+ } else {
1111
+ return transaction;
37
1112
  }
38
- });
39
-
40
- // ../../node_modules/.pnpm/base-x@4.0.0/node_modules/base-x/src/index.js
41
- var require_src = __commonJS({
42
- "../../node_modules/.pnpm/base-x@4.0.0/node_modules/base-x/src/index.js"(exports, module) {
43
- init_env_shim();
44
- function base(ALPHABET) {
45
- if (ALPHABET.length >= 255) {
46
- throw new TypeError("Alphabet too long");
47
- }
48
- var BASE_MAP = new Uint8Array(256);
49
- for (var j = 0; j < BASE_MAP.length; j++) {
50
- BASE_MAP[j] = 255;
51
- }
52
- for (var i = 0; i < ALPHABET.length; i++) {
53
- var x = ALPHABET.charAt(i);
54
- var xc = x.charCodeAt(0);
55
- if (BASE_MAP[xc] !== 255) {
56
- throw new TypeError(x + " is ambiguous");
57
- }
58
- BASE_MAP[xc] = i;
59
- }
60
- var BASE = ALPHABET.length;
61
- var LEADER = ALPHABET.charAt(0);
62
- var FACTOR = Math.log(BASE) / Math.log(256);
63
- var iFACTOR = Math.log(256) / Math.log(BASE);
64
- function encode(source) {
65
- if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
66
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
67
- } else if (Array.isArray(source)) {
68
- source = Uint8Array.from(source);
69
- }
70
- if (!(source instanceof Uint8Array)) {
71
- throw new TypeError("Expected Uint8Array");
72
- }
73
- if (source.length === 0) {
74
- return "";
75
- }
76
- var zeroes = 0;
77
- var length = 0;
78
- var pbegin = 0;
79
- var pend = source.length;
80
- while (pbegin !== pend && source[pbegin] === 0) {
81
- pbegin++;
82
- zeroes++;
83
- }
84
- var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
85
- var b58 = new Uint8Array(size);
86
- while (pbegin !== pend) {
87
- var carry = source[pbegin];
88
- var i2 = 0;
89
- for (var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) {
90
- carry += 256 * b58[it1] >>> 0;
91
- b58[it1] = carry % BASE >>> 0;
92
- carry = carry / BASE >>> 0;
93
- }
94
- if (carry !== 0) {
95
- throw new Error("Non-zero carry");
1113
+ }
1114
+ function assertIsBlockhash(putativeBlockhash) {
1115
+ try {
1116
+ if (
1117
+ // Lowest value (32 bytes of zeroes)
1118
+ putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)
1119
+ putativeBlockhash.length > 44
1120
+ ) {
1121
+ throw new Error("Expected input string to decode to a byte array of length 32.");
1122
+ }
1123
+ const bytes3 = base58.serialize(putativeBlockhash);
1124
+ const numBytes = bytes3.byteLength;
1125
+ if (numBytes !== 32) {
1126
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
1127
+ }
1128
+ } catch (e3) {
1129
+ throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, {
1130
+ cause: e3
1131
+ });
1132
+ }
1133
+ }
1134
+ function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {
1135
+ if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
1136
+ return transaction;
1137
+ }
1138
+ const out = {
1139
+ ...getUnsignedTransaction(transaction),
1140
+ lifetimeConstraint: blockhashLifetimeConstraint
1141
+ };
1142
+ Object.freeze(out);
1143
+ return out;
1144
+ }
1145
+ function createTransaction({
1146
+ version
1147
+ }) {
1148
+ const out = {
1149
+ instructions: [],
1150
+ version
1151
+ };
1152
+ Object.freeze(out);
1153
+ return out;
1154
+ }
1155
+ var AccountRole2 = /* @__PURE__ */ ((AccountRole22) => {
1156
+ AccountRole22[AccountRole22["WRITABLE_SIGNER"] = /* 3 */
1157
+ 3] = "WRITABLE_SIGNER";
1158
+ AccountRole22[AccountRole22["READONLY_SIGNER"] = /* 2 */
1159
+ 2] = "READONLY_SIGNER";
1160
+ AccountRole22[AccountRole22["WRITABLE"] = /* 1 */
1161
+ 1] = "WRITABLE";
1162
+ AccountRole22[AccountRole22["READONLY"] = /* 0 */
1163
+ 0] = "READONLY";
1164
+ return AccountRole22;
1165
+ })(AccountRole2 || {});
1166
+ var IS_WRITABLE_BITMASK2 = 1;
1167
+ function isSignerRole2(role) {
1168
+ return role >= 2;
1169
+ }
1170
+ function isWritableRole2(role) {
1171
+ return (role & IS_WRITABLE_BITMASK2) !== 0;
1172
+ }
1173
+ function mergeRoles2(roleA, roleB) {
1174
+ return roleA | roleB;
1175
+ }
1176
+ var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111";
1177
+ var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
1178
+ function assertIsDurableNonceTransaction(transaction) {
1179
+ if (!isDurableNonceTransaction(transaction)) {
1180
+ throw new Error("Transaction is not a durable nonce transaction");
1181
+ }
1182
+ }
1183
+ function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {
1184
+ return {
1185
+ accounts: [
1186
+ { address: nonceAccountAddress, role: AccountRole2.WRITABLE },
1187
+ {
1188
+ address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,
1189
+ role: AccountRole2.READONLY
1190
+ },
1191
+ { address: nonceAuthorityAddress, role: AccountRole2.READONLY_SIGNER }
1192
+ ],
1193
+ data: new Uint8Array([4, 0, 0, 0]),
1194
+ programAddress: SYSTEM_PROGRAM_ADDRESS
1195
+ };
1196
+ }
1197
+ function isAdvanceNonceAccountInstruction(instruction) {
1198
+ return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data
1199
+ instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts
1200
+ instruction.accounts?.length === 3 && // First account is nonce account address
1201
+ instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole2.WRITABLE && // Second account is recent blockhashes sysvar
1202
+ instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole2.READONLY && // Third account is nonce authority account
1203
+ instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole2.READONLY_SIGNER;
1204
+ }
1205
+ function isAdvanceNonceAccountInstructionData(data) {
1206
+ return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
1207
+ }
1208
+ function isDurableNonceTransaction(transaction) {
1209
+ return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
1210
+ }
1211
+ function setTransactionLifetimeUsingDurableNonce({
1212
+ nonce,
1213
+ nonceAccountAddress,
1214
+ nonceAuthorityAddress
1215
+ }, transaction) {
1216
+ const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);
1217
+ if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) {
1218
+ return transaction;
1219
+ }
1220
+ const out = {
1221
+ ...getUnsignedTransaction(transaction),
1222
+ instructions: [
1223
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1224
+ ...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions
1225
+ ],
1226
+ lifetimeConstraint: {
1227
+ nonce
1228
+ }
1229
+ };
1230
+ Object.freeze(out);
1231
+ return out;
1232
+ }
1233
+ function setTransactionFeePayer(feePayer, transaction) {
1234
+ if ("feePayer" in transaction && feePayer === transaction.feePayer) {
1235
+ return transaction;
1236
+ }
1237
+ const out = {
1238
+ ...getUnsignedTransaction(transaction),
1239
+ feePayer
1240
+ };
1241
+ Object.freeze(out);
1242
+ return out;
1243
+ }
1244
+ function appendTransactionInstruction(instruction, transaction) {
1245
+ const out = {
1246
+ ...getUnsignedTransaction(transaction),
1247
+ instructions: [...transaction.instructions, instruction]
1248
+ };
1249
+ Object.freeze(out);
1250
+ return out;
1251
+ }
1252
+ function prependTransactionInstruction(instruction, transaction) {
1253
+ const out = {
1254
+ ...getUnsignedTransaction(transaction),
1255
+ instructions: [instruction, ...transaction.instructions]
1256
+ };
1257
+ Object.freeze(out);
1258
+ return out;
1259
+ }
1260
+ function upsert(addressMap, address2, update) {
1261
+ addressMap[address2] = update(addressMap[address2] ?? { role: AccountRole2.READONLY });
1262
+ }
1263
+ var TYPE = Symbol("AddressMapTypeProperty");
1264
+ function getAddressMapFromInstructions(feePayer, instructions) {
1265
+ const addressMap = {
1266
+ [feePayer]: { [TYPE]: 0, role: AccountRole2.WRITABLE_SIGNER }
1267
+ };
1268
+ const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();
1269
+ for (const instruction of instructions) {
1270
+ upsert(addressMap, instruction.programAddress, (entry) => {
1271
+ addressesOfInvokedPrograms.add(instruction.programAddress);
1272
+ if (TYPE in entry) {
1273
+ if (isWritableRole2(entry.role)) {
1274
+ switch (entry[TYPE]) {
1275
+ case 0:
1276
+ throw new Error(
1277
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`
1278
+ );
1279
+ default:
1280
+ throw new Error(
1281
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1282
+ );
96
1283
  }
97
- length = i2;
98
- pbegin++;
99
- }
100
- var it2 = size - length;
101
- while (it2 !== size && b58[it2] === 0) {
102
- it2++;
103
1284
  }
104
- var str = LEADER.repeat(zeroes);
105
- for (; it2 < size; ++it2) {
106
- str += ALPHABET.charAt(b58[it2]);
1285
+ if (entry[TYPE] === 2) {
1286
+ return entry;
107
1287
  }
108
- return str;
109
1288
  }
110
- function decodeUnsafe(source) {
111
- if (typeof source !== "string") {
112
- throw new TypeError("Expected String");
113
- }
114
- if (source.length === 0) {
115
- return new Uint8Array();
116
- }
117
- var psz = 0;
118
- var zeroes = 0;
119
- var length = 0;
120
- while (source[psz] === LEADER) {
121
- zeroes++;
122
- psz++;
123
- }
124
- var size = (source.length - psz) * FACTOR + 1 >>> 0;
125
- var b256 = new Uint8Array(size);
126
- while (source[psz]) {
127
- var carry = BASE_MAP[source.charCodeAt(psz)];
128
- if (carry === 255) {
129
- return;
130
- }
131
- var i2 = 0;
132
- for (var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) {
133
- carry += BASE * b256[it3] >>> 0;
134
- b256[it3] = carry % 256 >>> 0;
135
- carry = carry / 256 >>> 0;
136
- }
137
- if (carry !== 0) {
138
- throw new Error("Non-zero carry");
1289
+ return { [TYPE]: 2, role: AccountRole2.READONLY };
1290
+ });
1291
+ let addressComparator;
1292
+ if (!instruction.accounts) {
1293
+ continue;
1294
+ }
1295
+ for (const account of instruction.accounts) {
1296
+ upsert(addressMap, account.address, (entry) => {
1297
+ const {
1298
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1299
+ address: _,
1300
+ ...accountMeta
1301
+ } = account;
1302
+ if (TYPE in entry) {
1303
+ switch (entry[TYPE]) {
1304
+ case 0:
1305
+ return entry;
1306
+ case 1: {
1307
+ const nextRole = mergeRoles2(entry.role, accountMeta.role);
1308
+ if ("lookupTableAddress" in accountMeta) {
1309
+ const shouldReplaceEntry = (
1310
+ // Consider using the new LOOKUP_TABLE if its address is different...
1311
+ entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
1312
+ (addressComparator || (addressComparator = getAddressComparator()))(
1313
+ accountMeta.lookupTableAddress,
1314
+ entry.lookupTableAddress
1315
+ ) < 0
1316
+ );
1317
+ if (shouldReplaceEntry) {
1318
+ return {
1319
+ [TYPE]: 1,
1320
+ ...accountMeta,
1321
+ role: nextRole
1322
+ };
1323
+ }
1324
+ } else if (isSignerRole2(accountMeta.role)) {
1325
+ return {
1326
+ [TYPE]: 2,
1327
+ role: nextRole
1328
+ };
1329
+ }
1330
+ if (entry.role !== nextRole) {
1331
+ return {
1332
+ ...entry,
1333
+ role: nextRole
1334
+ };
1335
+ } else {
1336
+ return entry;
1337
+ }
1338
+ }
1339
+ case 2: {
1340
+ const nextRole = mergeRoles2(entry.role, accountMeta.role);
1341
+ if (
1342
+ // Check to see if this address represents a program that is invoked
1343
+ // in this transaction.
1344
+ addressesOfInvokedPrograms.has(account.address)
1345
+ ) {
1346
+ if (isWritableRole2(accountMeta.role)) {
1347
+ throw new Error(
1348
+ `This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1349
+ );
1350
+ }
1351
+ if (entry.role !== nextRole) {
1352
+ return {
1353
+ ...entry,
1354
+ role: nextRole
1355
+ };
1356
+ } else {
1357
+ return entry;
1358
+ }
1359
+ } else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as
1360
+ // long as they are not require to sign the transaction.
1361
+ !isSignerRole2(entry.role)) {
1362
+ return {
1363
+ ...accountMeta,
1364
+ [TYPE]: 1,
1365
+ role: nextRole
1366
+ };
1367
+ } else {
1368
+ if (entry.role !== nextRole) {
1369
+ return {
1370
+ ...entry,
1371
+ role: nextRole
1372
+ };
1373
+ } else {
1374
+ return entry;
1375
+ }
1376
+ }
1377
+ }
139
1378
  }
140
- length = i2;
141
- psz++;
142
- }
143
- var it4 = size - length;
144
- while (it4 !== size && b256[it4] === 0) {
145
- it4++;
146
1379
  }
147
- var vch = new Uint8Array(zeroes + (size - it4));
148
- var j2 = zeroes;
149
- while (it4 !== size) {
150
- vch[j2++] = b256[it4++];
1380
+ if ("lookupTableAddress" in accountMeta) {
1381
+ return {
1382
+ ...accountMeta,
1383
+ [TYPE]: 1
1384
+ /* LOOKUP_TABLE */
1385
+ };
1386
+ } else {
1387
+ return {
1388
+ ...accountMeta,
1389
+ [TYPE]: 2
1390
+ /* STATIC */
1391
+ };
151
1392
  }
152
- return vch;
1393
+ });
1394
+ }
1395
+ }
1396
+ return addressMap;
1397
+ }
1398
+ function getOrderedAccountsFromAddressMap(addressMap) {
1399
+ let addressComparator;
1400
+ const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {
1401
+ if (leftEntry[TYPE] !== rightEntry[TYPE]) {
1402
+ if (leftEntry[TYPE] === 0) {
1403
+ return -1;
1404
+ } else if (rightEntry[TYPE] === 0) {
1405
+ return 1;
1406
+ } else if (leftEntry[TYPE] === 2) {
1407
+ return -1;
1408
+ } else if (rightEntry[TYPE] === 2) {
1409
+ return 1;
153
1410
  }
154
- function decode(string) {
155
- var buffer = decodeUnsafe(string);
156
- if (buffer) {
157
- return buffer;
158
- }
159
- throw new Error("Non-base" + BASE + " character");
1411
+ }
1412
+ const leftIsSigner = isSignerRole2(leftEntry.role);
1413
+ if (leftIsSigner !== isSignerRole2(rightEntry.role)) {
1414
+ return leftIsSigner ? -1 : 1;
1415
+ }
1416
+ const leftIsWritable = isWritableRole2(leftEntry.role);
1417
+ if (leftIsWritable !== isWritableRole2(rightEntry.role)) {
1418
+ return leftIsWritable ? -1 : 1;
1419
+ }
1420
+ addressComparator || (addressComparator = getAddressComparator());
1421
+ if (leftEntry[TYPE] === 1 && rightEntry[TYPE] === 1 && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
1422
+ return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
1423
+ } else {
1424
+ return addressComparator(leftAddress, rightAddress);
1425
+ }
1426
+ }).map(([address2, addressMeta]) => ({
1427
+ address: address2,
1428
+ ...addressMeta
1429
+ }));
1430
+ return orderedAccounts;
1431
+ }
1432
+ function getCompiledAddressTableLookups(orderedAccounts) {
1433
+ var _a;
1434
+ const index = {};
1435
+ for (const account of orderedAccounts) {
1436
+ if (!("lookupTableAddress" in account)) {
1437
+ continue;
1438
+ }
1439
+ const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
1440
+ readableIndices: [],
1441
+ writableIndices: []
1442
+ });
1443
+ if (account.role === AccountRole2.WRITABLE) {
1444
+ entry.writableIndices.push(account.addressIndex);
1445
+ } else {
1446
+ entry.readableIndices.push(account.addressIndex);
1447
+ }
1448
+ }
1449
+ return Object.keys(index).sort(getAddressComparator()).map((lookupTableAddress) => ({
1450
+ lookupTableAddress,
1451
+ ...index[lookupTableAddress]
1452
+ }));
1453
+ }
1454
+ function getCompiledMessageHeader(orderedAccounts) {
1455
+ let numReadonlyNonSignerAccounts = 0;
1456
+ let numReadonlySignerAccounts = 0;
1457
+ let numSignerAccounts = 0;
1458
+ for (const account of orderedAccounts) {
1459
+ if ("lookupTableAddress" in account) {
1460
+ break;
1461
+ }
1462
+ const accountIsWritable = isWritableRole2(account.role);
1463
+ if (isSignerRole2(account.role)) {
1464
+ numSignerAccounts++;
1465
+ if (!accountIsWritable) {
1466
+ numReadonlySignerAccounts++;
1467
+ }
1468
+ } else if (!accountIsWritable) {
1469
+ numReadonlyNonSignerAccounts++;
1470
+ }
1471
+ }
1472
+ return {
1473
+ numReadonlyNonSignerAccounts,
1474
+ numReadonlySignerAccounts,
1475
+ numSignerAccounts
1476
+ };
1477
+ }
1478
+ function getAccountIndex(orderedAccounts) {
1479
+ const out = {};
1480
+ for (const [index, account] of orderedAccounts.entries()) {
1481
+ out[account.address] = index;
1482
+ }
1483
+ return out;
1484
+ }
1485
+ function getCompiledInstructions(instructions, orderedAccounts) {
1486
+ const accountIndex = getAccountIndex(orderedAccounts);
1487
+ return instructions.map(({ accounts, data, programAddress }) => {
1488
+ return {
1489
+ programAddressIndex: accountIndex[programAddress],
1490
+ ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
1491
+ ...data ? { data } : null
1492
+ };
1493
+ });
1494
+ }
1495
+ function getCompiledLifetimeToken(lifetimeConstraint) {
1496
+ if ("nonce" in lifetimeConstraint) {
1497
+ return lifetimeConstraint.nonce;
1498
+ }
1499
+ return lifetimeConstraint.blockhash;
1500
+ }
1501
+ function getCompiledStaticAccounts(orderedAccounts) {
1502
+ const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
1503
+ const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
1504
+ return orderedStaticAccounts.map(({ address: address2 }) => address2);
1505
+ }
1506
+ function compileMessage(transaction) {
1507
+ const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
1508
+ const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);
1509
+ return {
1510
+ ...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,
1511
+ header: getCompiledMessageHeader(orderedAccounts),
1512
+ instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),
1513
+ lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),
1514
+ staticAccounts: getCompiledStaticAccounts(orderedAccounts),
1515
+ version: transaction.version
1516
+ };
1517
+ }
1518
+ function getCompiledTransaction(transaction) {
1519
+ const compiledMessage = compileMessage(transaction);
1520
+ let signatures;
1521
+ if ("signatures" in transaction) {
1522
+ signatures = [];
1523
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
1524
+ signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
1525
+ }
1526
+ } else {
1527
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
1528
+ }
1529
+ return {
1530
+ compiledMessage,
1531
+ signatures
1532
+ };
1533
+ }
1534
+ function getAddressTableLookupCodec() {
1535
+ return struct(
1536
+ [
1537
+ [
1538
+ "lookupTableAddress",
1539
+ getAddressCodec(
1540
+ {
1541
+ description: "The address of the address lookup table account from which instruction addresses should be looked up"
1542
+ }
1543
+ )
1544
+ ],
1545
+ [
1546
+ "writableIndices",
1547
+ array(u8(), {
1548
+ ...{
1549
+ description: "The indices of the accounts in the lookup table that should be loaded as writeable"
1550
+ } ,
1551
+ size: shortU16()
1552
+ })
1553
+ ],
1554
+ [
1555
+ "readableIndices",
1556
+ array(u8(), {
1557
+ ...{
1558
+ description: "The indices of the accounts in the lookup table that should be loaded as read-only"
1559
+ } ,
1560
+ size: shortU16()
1561
+ })
1562
+ ]
1563
+ ],
1564
+ {
1565
+ description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it"
1566
+ }
1567
+ );
1568
+ }
1569
+ function getMessageHeaderCodec() {
1570
+ return struct(
1571
+ [
1572
+ [
1573
+ "numSignerAccounts",
1574
+ u8(
1575
+ {
1576
+ description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
1577
+ }
1578
+ )
1579
+ ],
1580
+ [
1581
+ "numReadonlySignerAccounts",
1582
+ u8(
1583
+ {
1584
+ description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable"
1585
+ }
1586
+ )
1587
+ ],
1588
+ [
1589
+ "numReadonlyNonSignerAccounts",
1590
+ u8(
1591
+ {
1592
+ description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
1593
+ }
1594
+ )
1595
+ ]
1596
+ ],
1597
+ {
1598
+ description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
1599
+ }
1600
+ );
1601
+ }
1602
+ function getInstructionCodec() {
1603
+ return mapSerializer(
1604
+ struct([
1605
+ [
1606
+ "programAddressIndex",
1607
+ u8(
1608
+ {
1609
+ description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
1610
+ }
1611
+ )
1612
+ ],
1613
+ [
1614
+ "accountIndices",
1615
+ array(
1616
+ u8({
1617
+ description: "The index of an account, according to the well-ordered accounts list for this transaction"
1618
+ }),
1619
+ {
1620
+ description: "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" ,
1621
+ size: shortU16()
1622
+ }
1623
+ )
1624
+ ],
1625
+ [
1626
+ "data",
1627
+ bytes({
1628
+ description: "An optional buffer of data passed to the instruction" ,
1629
+ size: shortU16()
1630
+ })
1631
+ ]
1632
+ ]),
1633
+ (value) => {
1634
+ if (value.accountIndices !== void 0 && value.data !== void 0) {
1635
+ return value;
1636
+ }
1637
+ return {
1638
+ ...value,
1639
+ accountIndices: value.accountIndices ?? [],
1640
+ data: value.data ?? new Uint8Array(0)
1641
+ };
1642
+ },
1643
+ (value) => {
1644
+ if (value.accountIndices.length && value.data.byteLength) {
1645
+ return value;
160
1646
  }
1647
+ const { accountIndices, data, ...rest } = value;
161
1648
  return {
162
- encode,
163
- decodeUnsafe,
164
- decode
1649
+ ...rest,
1650
+ ...accountIndices.length ? { accountIndices } : null,
1651
+ ...data.byteLength ? { data } : null
165
1652
  };
166
1653
  }
167
- module.exports = base;
1654
+ );
1655
+ }
1656
+ function getError(type, name) {
1657
+ const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
1658
+ return new Error(
1659
+ `No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}`
1660
+ );
1661
+ }
1662
+ function getUnimplementedDecoder(name) {
1663
+ return () => {
1664
+ throw getError("decoder", name);
1665
+ };
1666
+ }
1667
+ var VERSION_FLAG_MASK = 128;
1668
+ var BASE_CONFIG = {
1669
+ description: "A single byte that encodes the version of the transaction" ,
1670
+ fixedSize: null,
1671
+ maxSize: 1
1672
+ };
1673
+ function deserialize(bytes3, offset = 0) {
1674
+ const firstByte = bytes3[offset];
1675
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
1676
+ return ["legacy", offset];
1677
+ } else {
1678
+ const version = firstByte ^ VERSION_FLAG_MASK;
1679
+ return [version, offset + 1];
168
1680
  }
169
- });
170
-
171
- // ../../node_modules/.pnpm/bs58@5.0.0/node_modules/bs58/index.js
172
- var require_bs58 = __commonJS({
173
- "../../node_modules/.pnpm/bs58@5.0.0/node_modules/bs58/index.js"(exports, module) {
174
- init_env_shim();
175
- var basex = require_src();
176
- var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
177
- module.exports = basex(ALPHABET);
1681
+ }
1682
+ function serialize(value) {
1683
+ if (value === "legacy") {
1684
+ return new Uint8Array();
178
1685
  }
179
- });
180
-
181
- // src/index.ts
182
- init_env_shim();
183
-
184
- // ../keys/dist/index.browser.js
185
- init_env_shim();
186
- var import_bs58 = __toESM(require_bs58(), 1);
187
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
1686
+ if (value < 0 || value > 127) {
1687
+ throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
1688
+ }
1689
+ return new Uint8Array([value | VERSION_FLAG_MASK]);
1690
+ }
1691
+ function getTransactionVersionCodec() {
1692
+ return {
1693
+ ...BASE_CONFIG,
1694
+ deserialize,
1695
+ serialize
1696
+ };
1697
+ }
1698
+ var BASE_CONFIG2 = {
1699
+ description: "The wire format of a Solana transaction message" ,
1700
+ fixedSize: null,
1701
+ maxSize: null
1702
+ };
1703
+ function serialize2(compiledMessage) {
1704
+ if (compiledMessage.version === "legacy") {
1705
+ return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
1706
+ } else {
1707
+ return mapSerializer(
1708
+ struct([
1709
+ ...getPreludeStructSerializerTuple(),
1710
+ ["addressTableLookups", getAddressTableLookupsSerializer()]
1711
+ ]),
1712
+ (value) => {
1713
+ if (value.version === "legacy") {
1714
+ return value;
1715
+ }
1716
+ return {
1717
+ ...value,
1718
+ addressTableLookups: value.addressTableLookups ?? []
1719
+ };
1720
+ }
1721
+ ).serialize(compiledMessage);
1722
+ }
1723
+ }
1724
+ function getPreludeStructSerializerTuple() {
1725
+ return [
1726
+ ["version", getTransactionVersionCodec()],
1727
+ ["header", getMessageHeaderCodec()],
1728
+ [
1729
+ "staticAccounts",
1730
+ array(getAddressCodec(), {
1731
+ description: "A compact-array of static account addresses belonging to this transaction" ,
1732
+ size: shortU16()
1733
+ })
1734
+ ],
1735
+ [
1736
+ "lifetimeToken",
1737
+ string({
1738
+ description: "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" ,
1739
+ encoding: base58,
1740
+ size: 32
1741
+ })
1742
+ ],
1743
+ [
1744
+ "instructions",
1745
+ array(getInstructionCodec(), {
1746
+ description: "A compact-array of instructions belonging to this transaction" ,
1747
+ size: shortU16()
1748
+ })
1749
+ ]
1750
+ ];
1751
+ }
1752
+ function getAddressTableLookupsSerializer() {
1753
+ return array(getAddressTableLookupCodec(), {
1754
+ ...{ description: "A compact array of address table lookups belonging to this transaction" } ,
1755
+ size: shortU16()
1756
+ });
1757
+ }
1758
+ function getCompiledMessageEncoder() {
1759
+ return {
1760
+ ...BASE_CONFIG2,
1761
+ deserialize: getUnimplementedDecoder("CompiledMessage"),
1762
+ serialize: serialize2
1763
+ };
1764
+ }
1765
+ var BASE_CONFIG3 = {
1766
+ description: "The wire format of a Solana transaction" ,
1767
+ fixedSize: null,
1768
+ maxSize: null
1769
+ };
1770
+ function serialize3(transaction) {
1771
+ const compiledTransaction = getCompiledTransaction(transaction);
1772
+ return struct([
1773
+ [
1774
+ "signatures",
1775
+ array(bytes({ size: 64 }), {
1776
+ ...{ description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } ,
1777
+ size: shortU16()
1778
+ })
1779
+ ],
1780
+ ["compiledMessage", getCompiledMessageEncoder()]
1781
+ ]).serialize(compiledTransaction);
1782
+ }
1783
+ function getTransactionEncoder() {
1784
+ return {
1785
+ ...BASE_CONFIG3,
1786
+ deserialize: getUnimplementedDecoder("CompiledMessage"),
1787
+ serialize: serialize3
1788
+ };
1789
+ }
1790
+ function assertIsTransactionSignature(putativeTransactionSignature) {
188
1791
  try {
189
1792
  if (
190
- // Lowest address (32 bytes of zeroes)
191
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
192
- putativeBase58EncodedAddress.length > 44
1793
+ // Lowest value (64 bytes of zeroes)
1794
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
1795
+ putativeTransactionSignature.length > 88
193
1796
  ) {
194
- throw new Error("Expected input string to decode to a byte array of length 32.");
1797
+ throw new Error("Expected input string to decode to a byte array of length 64.");
195
1798
  }
196
- const bytes = import_bs58.default.decode(putativeBase58EncodedAddress);
197
- const numBytes = bytes.byteLength;
198
- if (numBytes !== 32) {
199
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
1799
+ const bytes3 = base58.serialize(putativeTransactionSignature);
1800
+ const numBytes = bytes3.byteLength;
1801
+ if (numBytes !== 64) {
1802
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
200
1803
  }
201
- } catch (e2) {
202
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
203
- cause: e2
1804
+ } catch (e3) {
1805
+ throw new Error(`\`${putativeTransactionSignature}\` is not a transaction signature`, {
1806
+ cause: e3
204
1807
  });
205
1808
  }
206
1809
  }
1810
+ function isTransactionSignature(putativeTransactionSignature) {
1811
+ if (
1812
+ // Lowest value (64 bytes of zeroes)
1813
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
1814
+ putativeTransactionSignature.length > 88
1815
+ ) {
1816
+ return false;
1817
+ }
1818
+ const bytes3 = base58.serialize(putativeTransactionSignature);
1819
+ const numBytes = bytes3.byteLength;
1820
+ if (numBytes !== 64) {
1821
+ return false;
1822
+ }
1823
+ return true;
1824
+ }
1825
+ async function getCompiledMessageSignature(message, secretKey) {
1826
+ const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
1827
+ const signature = await signBytes(secretKey, wireMessageBytes);
1828
+ return signature;
1829
+ }
1830
+ function getSignatureFromTransaction(transaction) {
1831
+ const signature = transaction.signatures[transaction.feePayer];
1832
+ if (!signature) {
1833
+ throw new Error(
1834
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
1835
+ );
1836
+ }
1837
+ return signature;
1838
+ }
1839
+ async function signTransaction(keyPairs, transaction) {
1840
+ const compiledMessage = compileMessage(transaction);
1841
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
1842
+ const publicKeySignaturePairs = await Promise.all(
1843
+ keyPairs.map(
1844
+ (keyPair) => Promise.all([
1845
+ getAddressFromPublicKey(keyPair.publicKey),
1846
+ getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
1847
+ ])
1848
+ )
1849
+ );
1850
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
1851
+ nextSignatures[signerPublicKey] = signature;
1852
+ }
1853
+ const out = {
1854
+ ...transaction,
1855
+ signatures: nextSignatures
1856
+ };
1857
+ Object.freeze(out);
1858
+ return out;
1859
+ }
1860
+ function transactionSignature(putativeTransactionSignature) {
1861
+ assertIsTransactionSignature(putativeTransactionSignature);
1862
+ return putativeTransactionSignature;
1863
+ }
1864
+ function getBase64EncodedWireTransaction(transaction) {
1865
+ const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
1866
+ {
1867
+ return btoa(String.fromCharCode(...wireTransactionBytes));
1868
+ }
1869
+ }
207
1870
 
208
1871
  // src/rpc.ts
209
1872
  init_env_shim();
210
1873
 
1874
+ // ../functional/dist/index.browser.js
1875
+ init_env_shim();
1876
+ function pipe(init, ...fns) {
1877
+ return fns.reduce((acc, fn) => fn(acc), init);
1878
+ }
1879
+
211
1880
  // ../rpc-core/dist/index.browser.js
212
1881
  init_env_shim();
1882
+ function getCommitmentScore(commitment) {
1883
+ switch (commitment) {
1884
+ case "finalized":
1885
+ return 2;
1886
+ case "confirmed":
1887
+ return 1;
1888
+ case "processed":
1889
+ return 0;
1890
+ default:
1891
+ return ((_) => {
1892
+ throw new Error(`Unrecognized commitment \`${commitment}\`.`);
1893
+ })();
1894
+ }
1895
+ }
1896
+ function commitmentComparator(a, b) {
1897
+ if (a === b) {
1898
+ return 0;
1899
+ }
1900
+ return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;
1901
+ }
213
1902
  function visitNode(value, keyPath, onIntegerOverflow) {
214
1903
  if (Array.isArray(value)) {
215
1904
  return value.map(
@@ -236,9 +1925,393 @@ this.globalThis.solanaWeb3 = (function (exports) {
236
1925
  return visitNode(params, [], onIntegerOverflow);
237
1926
  }
238
1927
  var KEYPATH_WILDCARD = {};
239
- var ALLOWED_NUMERIC_KEYPATHS = {
240
- getInflationReward: [[KEYPATH_WILDCARD, "commission"]]
241
- };
1928
+ var jsonParsedTokenAccountsConfigs = [
1929
+ // parsed Token/Token22 token account
1930
+ ["data", "parsed", "info", "tokenAmount", "decimals"],
1931
+ ["data", "parsed", "info", "tokenAmount", "uiAmount"],
1932
+ ["data", "parsed", "info", "rentExemptReserve", "decimals"],
1933
+ ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
1934
+ ["data", "parsed", "info", "delegatedAmount", "decimals"],
1935
+ ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
1936
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "olderTransferFee", "transferFeeBasisPoints"],
1937
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "newerTransferFee", "transferFeeBasisPoints"],
1938
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
1939
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
1940
+ ];
1941
+ var jsonParsedAccountsConfigs = [
1942
+ ...jsonParsedTokenAccountsConfigs,
1943
+ // parsed AddressTableLookup account
1944
+ ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
1945
+ // parsed Config account
1946
+ ["data", "parsed", "info", "slashPenalty"],
1947
+ ["data", "parsed", "info", "warmupCooldownRate"],
1948
+ // parsed Token/Token22 mint account
1949
+ ["data", "parsed", "info", "decimals"],
1950
+ // parsed Token/Token22 multisig account
1951
+ ["data", "parsed", "info", "numRequiredSigners"],
1952
+ ["data", "parsed", "info", "numValidSigners"],
1953
+ // parsed Stake account
1954
+ ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
1955
+ // parsed Sysvar rent account
1956
+ ["data", "parsed", "info", "exemptionThreshold"],
1957
+ ["data", "parsed", "info", "burnPercent"],
1958
+ // parsed Vote account
1959
+ ["data", "parsed", "info", "commission"],
1960
+ ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
1961
+ ];
1962
+ var memoizedNotificationKeypaths;
1963
+ var memoizedResponseKeypaths;
1964
+ function getAllowedNumericKeypathsForNotification() {
1965
+ if (!memoizedNotificationKeypaths) {
1966
+ memoizedNotificationKeypaths = {
1967
+ accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
1968
+ blockNotifications: [
1969
+ ["value", "block", "blockTime"],
1970
+ [
1971
+ "value",
1972
+ "block",
1973
+ "transactions",
1974
+ KEYPATH_WILDCARD,
1975
+ "meta",
1976
+ "preTokenBalances",
1977
+ KEYPATH_WILDCARD,
1978
+ "accountIndex"
1979
+ ],
1980
+ [
1981
+ "value",
1982
+ "block",
1983
+ "transactions",
1984
+ KEYPATH_WILDCARD,
1985
+ "meta",
1986
+ "preTokenBalances",
1987
+ KEYPATH_WILDCARD,
1988
+ "uiTokenAmount",
1989
+ "decimals"
1990
+ ],
1991
+ [
1992
+ "value",
1993
+ "block",
1994
+ "transactions",
1995
+ KEYPATH_WILDCARD,
1996
+ "meta",
1997
+ "postTokenBalances",
1998
+ KEYPATH_WILDCARD,
1999
+ "accountIndex"
2000
+ ],
2001
+ [
2002
+ "value",
2003
+ "block",
2004
+ "transactions",
2005
+ KEYPATH_WILDCARD,
2006
+ "meta",
2007
+ "postTokenBalances",
2008
+ KEYPATH_WILDCARD,
2009
+ "uiTokenAmount",
2010
+ "decimals"
2011
+ ],
2012
+ ["value", "block", "transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2013
+ [
2014
+ "value",
2015
+ "block",
2016
+ "transactions",
2017
+ KEYPATH_WILDCARD,
2018
+ "meta",
2019
+ "innerInstructions",
2020
+ KEYPATH_WILDCARD,
2021
+ "index"
2022
+ ],
2023
+ [
2024
+ "value",
2025
+ "block",
2026
+ "transactions",
2027
+ KEYPATH_WILDCARD,
2028
+ "meta",
2029
+ "innerInstructions",
2030
+ KEYPATH_WILDCARD,
2031
+ "instructions",
2032
+ KEYPATH_WILDCARD,
2033
+ "programIdIndex"
2034
+ ],
2035
+ [
2036
+ "value",
2037
+ "block",
2038
+ "transactions",
2039
+ KEYPATH_WILDCARD,
2040
+ "meta",
2041
+ "innerInstructions",
2042
+ KEYPATH_WILDCARD,
2043
+ "instructions",
2044
+ KEYPATH_WILDCARD,
2045
+ "accounts",
2046
+ KEYPATH_WILDCARD
2047
+ ],
2048
+ [
2049
+ "value",
2050
+ "block",
2051
+ "transactions",
2052
+ KEYPATH_WILDCARD,
2053
+ "transaction",
2054
+ "message",
2055
+ "addressTableLookups",
2056
+ KEYPATH_WILDCARD,
2057
+ "writableIndexes",
2058
+ KEYPATH_WILDCARD
2059
+ ],
2060
+ [
2061
+ "value",
2062
+ "block",
2063
+ "transactions",
2064
+ KEYPATH_WILDCARD,
2065
+ "transaction",
2066
+ "message",
2067
+ "addressTableLookups",
2068
+ KEYPATH_WILDCARD,
2069
+ "readonlyIndexes",
2070
+ KEYPATH_WILDCARD
2071
+ ],
2072
+ [
2073
+ "value",
2074
+ "block",
2075
+ "transactions",
2076
+ KEYPATH_WILDCARD,
2077
+ "transaction",
2078
+ "message",
2079
+ "instructions",
2080
+ KEYPATH_WILDCARD,
2081
+ "programIdIndex"
2082
+ ],
2083
+ [
2084
+ "value",
2085
+ "block",
2086
+ "transactions",
2087
+ KEYPATH_WILDCARD,
2088
+ "transaction",
2089
+ "message",
2090
+ "instructions",
2091
+ KEYPATH_WILDCARD,
2092
+ "accounts",
2093
+ KEYPATH_WILDCARD
2094
+ ],
2095
+ [
2096
+ "value",
2097
+ "block",
2098
+ "transactions",
2099
+ KEYPATH_WILDCARD,
2100
+ "transaction",
2101
+ "message",
2102
+ "header",
2103
+ "numReadonlySignedAccounts"
2104
+ ],
2105
+ [
2106
+ "value",
2107
+ "block",
2108
+ "transactions",
2109
+ KEYPATH_WILDCARD,
2110
+ "transaction",
2111
+ "message",
2112
+ "header",
2113
+ "numReadonlyUnsignedAccounts"
2114
+ ],
2115
+ [
2116
+ "value",
2117
+ "block",
2118
+ "transactions",
2119
+ KEYPATH_WILDCARD,
2120
+ "transaction",
2121
+ "message",
2122
+ "header",
2123
+ "numRequiredSignatures"
2124
+ ],
2125
+ ["value", "block", "rewards", KEYPATH_WILDCARD, "commission"]
2126
+ ],
2127
+ programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [
2128
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2129
+ [KEYPATH_WILDCARD, "account", ...c]
2130
+ ])
2131
+ };
2132
+ }
2133
+ return memoizedNotificationKeypaths;
2134
+ }
2135
+ function getAllowedNumericKeypathsForResponse() {
2136
+ if (!memoizedResponseKeypaths) {
2137
+ memoizedResponseKeypaths = {
2138
+ getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
2139
+ getBlock: [
2140
+ ["blockTime"],
2141
+ ["transactions", KEYPATH_WILDCARD, "meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2142
+ [
2143
+ "transactions",
2144
+ KEYPATH_WILDCARD,
2145
+ "meta",
2146
+ "preTokenBalances",
2147
+ KEYPATH_WILDCARD,
2148
+ "uiTokenAmount",
2149
+ "decimals"
2150
+ ],
2151
+ ["transactions", KEYPATH_WILDCARD, "meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2152
+ [
2153
+ "transactions",
2154
+ KEYPATH_WILDCARD,
2155
+ "meta",
2156
+ "postTokenBalances",
2157
+ KEYPATH_WILDCARD,
2158
+ "uiTokenAmount",
2159
+ "decimals"
2160
+ ],
2161
+ ["transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2162
+ ["transactions", KEYPATH_WILDCARD, "meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
2163
+ [
2164
+ "transactions",
2165
+ KEYPATH_WILDCARD,
2166
+ "meta",
2167
+ "innerInstructions",
2168
+ KEYPATH_WILDCARD,
2169
+ "instructions",
2170
+ KEYPATH_WILDCARD,
2171
+ "programIdIndex"
2172
+ ],
2173
+ [
2174
+ "transactions",
2175
+ KEYPATH_WILDCARD,
2176
+ "meta",
2177
+ "innerInstructions",
2178
+ KEYPATH_WILDCARD,
2179
+ "instructions",
2180
+ KEYPATH_WILDCARD,
2181
+ "accounts",
2182
+ KEYPATH_WILDCARD
2183
+ ],
2184
+ [
2185
+ "transactions",
2186
+ KEYPATH_WILDCARD,
2187
+ "transaction",
2188
+ "message",
2189
+ "addressTableLookups",
2190
+ KEYPATH_WILDCARD,
2191
+ "writableIndexes",
2192
+ KEYPATH_WILDCARD
2193
+ ],
2194
+ [
2195
+ "transactions",
2196
+ KEYPATH_WILDCARD,
2197
+ "transaction",
2198
+ "message",
2199
+ "addressTableLookups",
2200
+ KEYPATH_WILDCARD,
2201
+ "readonlyIndexes",
2202
+ KEYPATH_WILDCARD
2203
+ ],
2204
+ [
2205
+ "transactions",
2206
+ KEYPATH_WILDCARD,
2207
+ "transaction",
2208
+ "message",
2209
+ "instructions",
2210
+ KEYPATH_WILDCARD,
2211
+ "programIdIndex"
2212
+ ],
2213
+ [
2214
+ "transactions",
2215
+ KEYPATH_WILDCARD,
2216
+ "transaction",
2217
+ "message",
2218
+ "instructions",
2219
+ KEYPATH_WILDCARD,
2220
+ "accounts",
2221
+ KEYPATH_WILDCARD
2222
+ ],
2223
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numReadonlySignedAccounts"],
2224
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numReadonlyUnsignedAccounts"],
2225
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numRequiredSignatures"],
2226
+ ["rewards", KEYPATH_WILDCARD, "commission"]
2227
+ ],
2228
+ getBlockTime: [[]],
2229
+ getClusterNodes: [
2230
+ [KEYPATH_WILDCARD, "featureSet"],
2231
+ [KEYPATH_WILDCARD, "shredVersion"]
2232
+ ],
2233
+ getInflationGovernor: [["initial"], ["foundation"], ["foundationTerm"], ["taper"], ["terminal"]],
2234
+ getInflationRate: [["foundation"], ["total"], ["validator"]],
2235
+ getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
2236
+ getMultipleAccounts: jsonParsedAccountsConfigs.map((c) => ["value", KEYPATH_WILDCARD, ...c]),
2237
+ getProgramAccounts: jsonParsedAccountsConfigs.flatMap((c) => [
2238
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2239
+ [KEYPATH_WILDCARD, "account", ...c]
2240
+ ]),
2241
+ getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
2242
+ getTokenAccountBalance: [
2243
+ ["value", "decimals"],
2244
+ ["value", "uiAmount"]
2245
+ ],
2246
+ getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map((c) => [
2247
+ "value",
2248
+ KEYPATH_WILDCARD,
2249
+ "account",
2250
+ ...c
2251
+ ]),
2252
+ getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map((c) => [
2253
+ "value",
2254
+ KEYPATH_WILDCARD,
2255
+ "account",
2256
+ ...c
2257
+ ]),
2258
+ getTokenLargestAccounts: [
2259
+ ["value", KEYPATH_WILDCARD, "decimals"],
2260
+ ["value", KEYPATH_WILDCARD, "uiAmount"]
2261
+ ],
2262
+ getTokenSupply: [
2263
+ ["value", "decimals"],
2264
+ ["value", "uiAmount"]
2265
+ ],
2266
+ getTransaction: [
2267
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2268
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
2269
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2270
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
2271
+ ["meta", "rewards", KEYPATH_WILDCARD, "commission"],
2272
+ ["meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
2273
+ ["meta", "innerInstructions", KEYPATH_WILDCARD, "instructions", KEYPATH_WILDCARD, "programIdIndex"],
2274
+ [
2275
+ "meta",
2276
+ "innerInstructions",
2277
+ KEYPATH_WILDCARD,
2278
+ "instructions",
2279
+ KEYPATH_WILDCARD,
2280
+ "accounts",
2281
+ KEYPATH_WILDCARD
2282
+ ],
2283
+ [
2284
+ "transaction",
2285
+ "message",
2286
+ "addressTableLookups",
2287
+ KEYPATH_WILDCARD,
2288
+ "writableIndexes",
2289
+ KEYPATH_WILDCARD
2290
+ ],
2291
+ [
2292
+ "transaction",
2293
+ "message",
2294
+ "addressTableLookups",
2295
+ KEYPATH_WILDCARD,
2296
+ "readonlyIndexes",
2297
+ KEYPATH_WILDCARD
2298
+ ],
2299
+ ["transaction", "message", "instructions", KEYPATH_WILDCARD, "programIdIndex"],
2300
+ ["transaction", "message", "instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
2301
+ ["transaction", "message", "header", "numReadonlySignedAccounts"],
2302
+ ["transaction", "message", "header", "numReadonlyUnsignedAccounts"],
2303
+ ["transaction", "message", "header", "numRequiredSignatures"]
2304
+ ],
2305
+ getVersion: [["feature-set"]],
2306
+ getVoteAccounts: [
2307
+ ["current", KEYPATH_WILDCARD, "commission"],
2308
+ ["delinquent", KEYPATH_WILDCARD, "commission"]
2309
+ ],
2310
+ simulateTransaction: jsonParsedAccountsConfigs.map((c) => ["value", "accounts", KEYPATH_WILDCARD, ...c])
2311
+ };
2312
+ }
2313
+ return memoizedResponseKeypaths;
2314
+ }
242
2315
  function getNextAllowedKeypaths(keyPaths, property) {
243
2316
  return keyPaths.filter((keyPath) => keyPath[0] === KEYPATH_WILDCARD && typeof property === "number" || keyPath[0] === property).map((keyPath) => keyPath.slice(1));
244
2317
  }
@@ -257,14 +2330,19 @@ this.globalThis.solanaWeb3 = (function (exports) {
257
2330
  return out;
258
2331
  } else if (typeof value === "number" && // The presence of an allowed keypath on the route to this value implies it's allowlisted;
259
2332
  // Upcast the value to `bigint` unless an allowed keypath is present.
260
- allowedKeypaths.length === 0) {
2333
+ allowedKeypaths.length === 0 && // Only try to upcast an Integer to `bigint`
2334
+ Number.isInteger(value)) {
261
2335
  return BigInt(value);
262
2336
  } else {
263
2337
  return value;
264
2338
  }
265
2339
  }
266
2340
  function patchResponseForSolanaLabsRpc(rawResponse, methodName) {
267
- const allowedKeypaths = methodName ? ALLOWED_NUMERIC_KEYPATHS[methodName] : void 0;
2341
+ const allowedKeypaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : void 0;
2342
+ return visitNode2(rawResponse, allowedKeypaths ?? []);
2343
+ }
2344
+ function patchResponseForSolanaLabsRpcSubscriptions(rawResponse, methodName) {
2345
+ const allowedKeypaths = methodName ? getAllowedNumericKeypathsForNotification()[methodName] : void 0;
268
2346
  return visitNode2(rawResponse, allowedKeypaths ?? []);
269
2347
  }
270
2348
  function createSolanaRpcApi(config) {
@@ -293,46 +2371,36 @@ this.globalThis.solanaWeb3 = (function (exports) {
293
2371
  }
294
2372
  });
295
2373
  }
296
-
297
- // src/rpc-default-config.ts
298
- init_env_shim();
299
-
300
- // src/rpc-integer-overflow-error.ts
301
- init_env_shim();
302
- var SolanaJsonRpcIntegerOverflowError = class extends Error {
303
- constructor(methodName, keyPath, value) {
304
- const argPosition = (typeof keyPath[0] === "number" ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;
305
- let ordinal = "";
306
- const lastDigit = argPosition % 10;
307
- const lastTwoDigits = argPosition % 100;
308
- if (lastDigit == 1 && lastTwoDigits != 11) {
309
- ordinal = argPosition + "st";
310
- } else if (lastDigit == 2 && lastTwoDigits != 12) {
311
- ordinal = argPosition + "nd";
312
- } else if (lastDigit == 3 && lastTwoDigits != 13) {
313
- ordinal = argPosition + "rd";
314
- } else {
315
- ordinal = argPosition + "th";
316
- }
317
- const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : null;
318
- super(
319
- `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\`.`
320
- );
321
- this.keyPath = keyPath;
322
- this.methodName = methodName;
323
- this.value = value;
324
- }
325
- get name() {
326
- return "SolanaJsonRpcIntegerOverflowError";
327
- }
328
- };
329
-
330
- // src/rpc-default-config.ts
331
- var DEFAULT_RPC_CONFIG = {
332
- onIntegerOverflow(methodName, keyPath, value) {
333
- throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);
334
- }
335
- };
2374
+ function createSolanaRpcSubscriptionsApi(config) {
2375
+ return new Proxy({}, {
2376
+ defineProperty() {
2377
+ return false;
2378
+ },
2379
+ deleteProperty() {
2380
+ return false;
2381
+ },
2382
+ get(...args) {
2383
+ const [_, p] = args;
2384
+ const notificationName = p.toString();
2385
+ return function(...rawParams) {
2386
+ const handleIntegerOverflow = config?.onIntegerOverflow;
2387
+ const params = patchParamsForSolanaLabsRpc(
2388
+ rawParams,
2389
+ handleIntegerOverflow ? (keyPath, value) => handleIntegerOverflow(notificationName, keyPath, value) : void 0
2390
+ );
2391
+ return {
2392
+ params,
2393
+ responseProcessor: (rawResponse) => patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName),
2394
+ subscribeMethodName: notificationName.replace(/Notifications$/, "Subscribe"),
2395
+ unsubscribeMethodName: notificationName.replace(/Notifications$/, "Unsubscribe")
2396
+ };
2397
+ };
2398
+ }
2399
+ });
2400
+ }
2401
+ function createSolanaRpcSubscriptionsApi_UNSTABLE(config) {
2402
+ return createSolanaRpcSubscriptionsApi(config);
2403
+ }
336
2404
 
337
2405
  // ../rpc-transport/dist/index.browser.js
338
2406
  init_env_shim();
@@ -399,6 +2467,101 @@ this.globalThis.solanaWeb3 = (function (exports) {
399
2467
  function createJsonRpc(rpcConfig) {
400
2468
  return makeProxy(rpcConfig);
401
2469
  }
2470
+ function registerIterableCleanup(iterable, cleanupFn) {
2471
+ (async () => {
2472
+ try {
2473
+ for await (const _ of iterable)
2474
+ ;
2475
+ } catch {
2476
+ } finally {
2477
+ cleanupFn();
2478
+ }
2479
+ })();
2480
+ }
2481
+ function createPendingRpcSubscription(rpcConfig, { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }) {
2482
+ return {
2483
+ async subscribe({ abortSignal }) {
2484
+ abortSignal.throwIfAborted();
2485
+ let subscriptionId;
2486
+ function handleCleanup() {
2487
+ if (subscriptionId !== void 0) {
2488
+ const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);
2489
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {
2490
+ connectionAbortController.abort();
2491
+ });
2492
+ } else {
2493
+ connectionAbortController.abort();
2494
+ }
2495
+ }
2496
+ abortSignal.addEventListener("abort", handleCleanup);
2497
+ const connectionAbortController = new AbortController();
2498
+ const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);
2499
+ const connection = await rpcConfig.transport({
2500
+ payload: subscribeMessage,
2501
+ signal: connectionAbortController.signal
2502
+ });
2503
+ function handleConnectionCleanup() {
2504
+ abortSignal.removeEventListener("abort", handleCleanup);
2505
+ }
2506
+ registerIterableCleanup(connection, handleConnectionCleanup);
2507
+ for await (const message of connection) {
2508
+ if ("id" in message && message.id === subscribeMessage.id) {
2509
+ if ("error" in message) {
2510
+ throw new SolanaJsonRpcError(message.error);
2511
+ } else {
2512
+ subscriptionId = message.result;
2513
+ break;
2514
+ }
2515
+ }
2516
+ }
2517
+ if (subscriptionId == null) {
2518
+ throw new Error("Failed to obtain a subscription id from the server");
2519
+ }
2520
+ return {
2521
+ async *[Symbol.asyncIterator]() {
2522
+ for await (const message of connection) {
2523
+ if (!("params" in message) || message.params.subscription !== subscriptionId) {
2524
+ continue;
2525
+ }
2526
+ const notification = message.params.result;
2527
+ yield responseProcessor ? responseProcessor(notification) : notification;
2528
+ }
2529
+ }
2530
+ };
2531
+ }
2532
+ };
2533
+ }
2534
+ function makeProxy2(rpcConfig) {
2535
+ return new Proxy(rpcConfig.api, {
2536
+ defineProperty() {
2537
+ return false;
2538
+ },
2539
+ deleteProperty() {
2540
+ return false;
2541
+ },
2542
+ get(target, p, receiver) {
2543
+ return function(...rawParams) {
2544
+ const methodName = p.toString();
2545
+ const createRpcSubscription = Reflect.get(target, methodName, receiver);
2546
+ if (p.toString().endsWith("Notifications") === false && !createRpcSubscription) {
2547
+ throw new Error(
2548
+ "Either the notification name must end in 'Notifications' or the API must supply a subscription creator function to map between the notification name and the subscribe/unsubscribe method names."
2549
+ );
2550
+ }
2551
+ const newRequest = createRpcSubscription ? createRpcSubscription(...rawParams) : {
2552
+ params: rawParams,
2553
+ subscribeMethodName: methodName.replace(/Notifications$/, "Subscribe"),
2554
+ unsubscribeMethodName: methodName.replace(/Notifications$/, "Unsubscribe")
2555
+ };
2556
+ return createPendingRpcSubscription(rpcConfig, newRequest);
2557
+ };
2558
+ }
2559
+ });
2560
+ }
2561
+ function createJsonSubscriptionRpc(rpcConfig) {
2562
+ return makeProxy2(rpcConfig);
2563
+ }
2564
+ var e = globalThis.fetch;
402
2565
  var SolanaHttpError = class extends Error {
403
2566
  constructor(details) {
404
2567
  super(`HTTP error (${details.statusCode}): ${details.message}`);
@@ -457,7 +2620,6 @@ this.globalThis.solanaWeb3 = (function (exports) {
457
2620
  }
458
2621
  return out;
459
2622
  }
460
- var e = globalThis.fetch;
461
2623
  function createHttpTransport({ httpAgentNodeOnly, headers, url }) {
462
2624
  if (headers) {
463
2625
  assertIsAllowedHttpRequestHeaders(headers);
@@ -497,6 +2659,406 @@ this.globalThis.solanaWeb3 = (function (exports) {
497
2659
  return await response.json();
498
2660
  };
499
2661
  }
2662
+ var e2 = globalThis.WebSocket;
2663
+ var EXPLICIT_ABORT_TOKEN = Symbol(
2664
+ "This symbol is thrown from a socket's iterator when the connection is explicity aborted by the user"
2665
+ );
2666
+ async function createWebSocketConnection({
2667
+ sendBufferHighWatermark,
2668
+ signal,
2669
+ url
2670
+ }) {
2671
+ return new Promise((resolve, reject) => {
2672
+ signal.addEventListener("abort", handleAbort, { once: true });
2673
+ const iteratorState = /* @__PURE__ */ new Map();
2674
+ function errorAndClearAllIteratorStates(reason) {
2675
+ const errorCallbacks = [...iteratorState.values()].filter((state) => state.__hasPolled).map(({ onError }) => onError);
2676
+ iteratorState.clear();
2677
+ errorCallbacks.forEach((cb) => {
2678
+ try {
2679
+ cb(reason);
2680
+ } catch {
2681
+ }
2682
+ });
2683
+ }
2684
+ function handleAbort() {
2685
+ errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);
2686
+ if (webSocket.readyState !== e2.CLOSED && webSocket.readyState !== e2.CLOSING) {
2687
+ webSocket.close(1e3);
2688
+ }
2689
+ }
2690
+ function handleClose(ev) {
2691
+ bufferDrainWatcher?.onCancel();
2692
+ signal.removeEventListener("abort", handleAbort);
2693
+ webSocket.removeEventListener("close", handleClose);
2694
+ webSocket.removeEventListener("error", handleError);
2695
+ webSocket.removeEventListener("open", handleOpen);
2696
+ webSocket.removeEventListener("message", handleMessage);
2697
+ errorAndClearAllIteratorStates(ev);
2698
+ }
2699
+ function handleError(ev) {
2700
+ if (!hasConnected) {
2701
+ reject(
2702
+ // TODO: Coded error
2703
+ new Error("WebSocket failed to connect", { cause: ev })
2704
+ );
2705
+ }
2706
+ }
2707
+ let hasConnected = false;
2708
+ let bufferDrainWatcher;
2709
+ function handleOpen() {
2710
+ hasConnected = true;
2711
+ resolve({
2712
+ async send(payload) {
2713
+ const message = JSON.stringify(payload);
2714
+ if (!bufferDrainWatcher && webSocket.readyState === e2.OPEN && webSocket.bufferedAmount > sendBufferHighWatermark) {
2715
+ let onCancel;
2716
+ const promise = new Promise((resolve2, reject2) => {
2717
+ const intervalId = setInterval(() => {
2718
+ if (webSocket.readyState !== e2.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
2719
+ clearInterval(intervalId);
2720
+ bufferDrainWatcher = void 0;
2721
+ resolve2();
2722
+ }
2723
+ }, 16);
2724
+ onCancel = () => {
2725
+ bufferDrainWatcher = void 0;
2726
+ clearInterval(intervalId);
2727
+ reject2(
2728
+ // TODO: Coded error
2729
+ new Error("WebSocket was closed before payload could be sent")
2730
+ );
2731
+ };
2732
+ });
2733
+ bufferDrainWatcher = {
2734
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2735
+ // @ts-ignore
2736
+ onCancel,
2737
+ promise
2738
+ };
2739
+ }
2740
+ if (bufferDrainWatcher) {
2741
+ await bufferDrainWatcher.promise;
2742
+ }
2743
+ webSocket.send(message);
2744
+ },
2745
+ async *[Symbol.asyncIterator]() {
2746
+ const iteratorKey = Symbol();
2747
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
2748
+ try {
2749
+ while (true) {
2750
+ const state = iteratorState.get(iteratorKey);
2751
+ if (!state) {
2752
+ throw new Error("Invariant: WebSocket message iterator is missing state storage");
2753
+ }
2754
+ if (state.__hasPolled) {
2755
+ throw new Error(
2756
+ "Invariant: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise"
2757
+ );
2758
+ }
2759
+ const queuedMessages = state.queuedMessages;
2760
+ if (queuedMessages.length) {
2761
+ state.queuedMessages = [];
2762
+ yield* queuedMessages;
2763
+ } else {
2764
+ try {
2765
+ yield await new Promise((resolve2, reject2) => {
2766
+ iteratorState.set(iteratorKey, {
2767
+ __hasPolled: true,
2768
+ onError: reject2,
2769
+ onMessage: resolve2
2770
+ });
2771
+ });
2772
+ } catch (e3) {
2773
+ if (e3 === EXPLICIT_ABORT_TOKEN) {
2774
+ return;
2775
+ } else {
2776
+ throw new Error("WebSocket connection closed", { cause: e3 });
2777
+ }
2778
+ }
2779
+ }
2780
+ }
2781
+ } finally {
2782
+ iteratorState.delete(iteratorKey);
2783
+ }
2784
+ }
2785
+ });
2786
+ }
2787
+ function handleMessage({ data }) {
2788
+ const message = JSON.parse(data);
2789
+ iteratorState.forEach((state, iteratorKey) => {
2790
+ if (state.__hasPolled) {
2791
+ const { onMessage } = state;
2792
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
2793
+ onMessage(message);
2794
+ } else {
2795
+ state.queuedMessages.push(message);
2796
+ }
2797
+ });
2798
+ }
2799
+ const webSocket = new e2(url);
2800
+ webSocket.addEventListener("close", handleClose);
2801
+ webSocket.addEventListener("error", handleError);
2802
+ webSocket.addEventListener("open", handleOpen);
2803
+ webSocket.addEventListener("message", handleMessage);
2804
+ });
2805
+ }
2806
+ function createWebSocketTransport({ sendBufferHighWatermark, url }) {
2807
+ if (/^wss?:/i.test(url) === false) {
2808
+ const protocolMatch = url.match(/^([^:]+):/);
2809
+ throw new DOMException(
2810
+ protocolMatch ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.` : `Failed to construct 'WebSocket': The URL '${url}' is invalid.`
2811
+ );
2812
+ }
2813
+ return async function sendWebSocketMessage({ payload, signal }) {
2814
+ signal?.throwIfAborted();
2815
+ const connection = await createWebSocketConnection({
2816
+ sendBufferHighWatermark,
2817
+ signal,
2818
+ url
2819
+ });
2820
+ signal?.throwIfAborted();
2821
+ await connection.send(payload);
2822
+ return {
2823
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
2824
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection)
2825
+ };
2826
+ };
2827
+ }
2828
+
2829
+ // src/rpc.ts
2830
+ var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
2831
+
2832
+ // src/rpc-default-config.ts
2833
+ init_env_shim();
2834
+
2835
+ // src/rpc-integer-overflow-error.ts
2836
+ init_env_shim();
2837
+ var SolanaJsonRpcIntegerOverflowError = class extends Error {
2838
+ constructor(methodName, keyPath, value) {
2839
+ const argPosition = (typeof keyPath[0] === "number" ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;
2840
+ let ordinal = "";
2841
+ const lastDigit = argPosition % 10;
2842
+ const lastTwoDigits = argPosition % 100;
2843
+ if (lastDigit == 1 && lastTwoDigits != 11) {
2844
+ ordinal = argPosition + "st";
2845
+ } else if (lastDigit == 2 && lastTwoDigits != 12) {
2846
+ ordinal = argPosition + "nd";
2847
+ } else if (lastDigit == 3 && lastTwoDigits != 13) {
2848
+ ordinal = argPosition + "rd";
2849
+ } else {
2850
+ ordinal = argPosition + "th";
2851
+ }
2852
+ const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : null;
2853
+ super(
2854
+ `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\`.`
2855
+ );
2856
+ this.keyPath = keyPath;
2857
+ this.methodName = methodName;
2858
+ this.value = value;
2859
+ }
2860
+ get name() {
2861
+ return "SolanaJsonRpcIntegerOverflowError";
2862
+ }
2863
+ };
2864
+
2865
+ // src/rpc-default-config.ts
2866
+ var DEFAULT_RPC_CONFIG = {
2867
+ onIntegerOverflow(methodName, keyPath, value) {
2868
+ throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);
2869
+ }
2870
+ };
2871
+
2872
+ // src/rpc-subscription-coalescer.ts
2873
+ init_env_shim();
2874
+
2875
+ // src/cached-abortable-iterable.ts
2876
+ init_env_shim();
2877
+ function registerIterableCleanup2(iterable, cleanupFn) {
2878
+ (async () => {
2879
+ try {
2880
+ for await (const _ of iterable)
2881
+ ;
2882
+ } catch {
2883
+ } finally {
2884
+ cleanupFn();
2885
+ }
2886
+ })();
2887
+ }
2888
+ function getCachedAbortableIterableFactory({
2889
+ getAbortSignalFromInputArgs,
2890
+ getCacheEntryMissingError,
2891
+ getCacheKeyFromInputArgs,
2892
+ onCacheHit,
2893
+ onCreateIterable
2894
+ }) {
2895
+ const cache = /* @__PURE__ */ new Map();
2896
+ function getCacheEntryOrThrow(cacheKey) {
2897
+ const currentCacheEntry = cache.get(cacheKey);
2898
+ if (!currentCacheEntry) {
2899
+ throw getCacheEntryMissingError(cacheKey);
2900
+ }
2901
+ return currentCacheEntry;
2902
+ }
2903
+ return async (...args) => {
2904
+ const cacheKey = getCacheKeyFromInputArgs(...args);
2905
+ const signal = getAbortSignalFromInputArgs(...args);
2906
+ if (cacheKey === void 0) {
2907
+ return await onCreateIterable(signal, ...args);
2908
+ }
2909
+ const cleanup = () => {
2910
+ cache.delete(cacheKey);
2911
+ signal.removeEventListener("abort", handleAbort);
2912
+ };
2913
+ const handleAbort = () => {
2914
+ const cacheEntry = getCacheEntryOrThrow(cacheKey);
2915
+ if (cacheEntry.purgeScheduled !== true) {
2916
+ cacheEntry.purgeScheduled = true;
2917
+ globalThis.queueMicrotask(() => {
2918
+ cacheEntry.purgeScheduled = false;
2919
+ if (cacheEntry.referenceCount === 0) {
2920
+ cacheEntry.abortController.abort();
2921
+ cleanup();
2922
+ }
2923
+ });
2924
+ }
2925
+ cacheEntry.referenceCount--;
2926
+ };
2927
+ signal.addEventListener("abort", handleAbort);
2928
+ try {
2929
+ const cacheEntry = cache.get(cacheKey);
2930
+ if (!cacheEntry) {
2931
+ const singletonAbortController = new AbortController();
2932
+ const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);
2933
+ const newCacheEntry = {
2934
+ abortController: singletonAbortController,
2935
+ iterable: newIterablePromise,
2936
+ purgeScheduled: false,
2937
+ referenceCount: 1
2938
+ };
2939
+ cache.set(cacheKey, newCacheEntry);
2940
+ const newIterable = await newIterablePromise;
2941
+ registerIterableCleanup2(newIterable, cleanup);
2942
+ newCacheEntry.iterable = newIterable;
2943
+ return newIterable;
2944
+ } else {
2945
+ cacheEntry.referenceCount++;
2946
+ const iterableOrIterablePromise = cacheEntry.iterable;
2947
+ const cachedIterable = "then" in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;
2948
+ await onCacheHit(cachedIterable, ...args);
2949
+ return cachedIterable;
2950
+ }
2951
+ } catch (e3) {
2952
+ cleanup();
2953
+ throw e3;
2954
+ }
2955
+ };
2956
+ }
2957
+
2958
+ // src/rpc-subscription-coalescer.ts
2959
+ var EXPLICIT_ABORT_TOKEN2 = Symbol(
2960
+ "This symbol is thrown from a subscription's iterator when the subscription is explicitly aborted by the user"
2961
+ );
2962
+ function registerIterableCleanup3(iterable, cleanupFn) {
2963
+ (async () => {
2964
+ try {
2965
+ for await (const _ of iterable)
2966
+ ;
2967
+ } catch {
2968
+ } finally {
2969
+ cleanupFn();
2970
+ }
2971
+ })();
2972
+ }
2973
+ function getRpcSubscriptionsWithSubscriptionCoalescing({
2974
+ getDeduplicationKey,
2975
+ rpcSubscriptions
2976
+ }) {
2977
+ const cache = /* @__PURE__ */ new Map();
2978
+ return new Proxy(rpcSubscriptions, {
2979
+ defineProperty() {
2980
+ return false;
2981
+ },
2982
+ deleteProperty() {
2983
+ return false;
2984
+ },
2985
+ get(target, p, receiver) {
2986
+ const subscriptionMethod = Reflect.get(target, p, receiver);
2987
+ if (typeof subscriptionMethod !== "function") {
2988
+ return subscriptionMethod;
2989
+ }
2990
+ return function(...rawParams) {
2991
+ const deduplicationKey = getDeduplicationKey(p, rawParams);
2992
+ if (deduplicationKey === void 0) {
2993
+ return subscriptionMethod(...rawParams);
2994
+ }
2995
+ if (cache.has(deduplicationKey)) {
2996
+ return cache.get(deduplicationKey);
2997
+ }
2998
+ const iterableFactory = getCachedAbortableIterableFactory({
2999
+ getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,
3000
+ getCacheEntryMissingError(deduplicationKey2) {
3001
+ return new Error(
3002
+ `Found no cache entry for subscription with deduplication key \`${deduplicationKey2?.toString()}\``
3003
+ );
3004
+ },
3005
+ getCacheKeyFromInputArgs: () => deduplicationKey,
3006
+ async onCacheHit(_iterable, _config) {
3007
+ },
3008
+ async onCreateIterable(abortSignal, config) {
3009
+ const pendingSubscription2 = subscriptionMethod(
3010
+ ...rawParams
3011
+ );
3012
+ const iterable = await pendingSubscription2.subscribe({
3013
+ ...config,
3014
+ abortSignal
3015
+ });
3016
+ registerIterableCleanup3(iterable, () => {
3017
+ cache.delete(deduplicationKey);
3018
+ });
3019
+ return iterable;
3020
+ }
3021
+ });
3022
+ const pendingSubscription = {
3023
+ async subscribe(...args) {
3024
+ const iterable = await iterableFactory(...args);
3025
+ const { abortSignal } = args[0];
3026
+ let abortPromise;
3027
+ return {
3028
+ ...iterable,
3029
+ async *[Symbol.asyncIterator]() {
3030
+ abortPromise || (abortPromise = abortSignal.aborted ? Promise.reject(EXPLICIT_ABORT_TOKEN2) : new Promise((_, reject) => {
3031
+ abortSignal.addEventListener("abort", () => {
3032
+ reject(EXPLICIT_ABORT_TOKEN2);
3033
+ });
3034
+ }));
3035
+ try {
3036
+ const iterator = iterable[Symbol.asyncIterator]();
3037
+ while (true) {
3038
+ const iteratorResult = await Promise.race([iterator.next(), abortPromise]);
3039
+ if (iteratorResult.done) {
3040
+ return;
3041
+ } else {
3042
+ yield iteratorResult.value;
3043
+ }
3044
+ }
3045
+ } catch (e3) {
3046
+ if (e3 === EXPLICIT_ABORT_TOKEN2) {
3047
+ return;
3048
+ }
3049
+ cache.delete(deduplicationKey);
3050
+ throw e3;
3051
+ }
3052
+ }
3053
+ };
3054
+ }
3055
+ };
3056
+ cache.set(deduplicationKey, pendingSubscription);
3057
+ return pendingSubscription;
3058
+ };
3059
+ }
3060
+ });
3061
+ }
500
3062
 
501
3063
  // src/rpc.ts
502
3064
  function createSolanaRpc(config) {
@@ -505,9 +3067,95 @@ this.globalThis.solanaWeb3 = (function (exports) {
505
3067
  api: createSolanaRpcApi(DEFAULT_RPC_CONFIG)
506
3068
  });
507
3069
  }
3070
+ function createSolanaRpcSubscriptions(config) {
3071
+ return pipe(
3072
+ createJsonSubscriptionRpc({
3073
+ ...config,
3074
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
3075
+ }),
3076
+ (rpcSubscriptions) => getRpcSubscriptionsWithSubscriptionCoalescing({
3077
+ getDeduplicationKey: (...args) => (0, import_fast_stable_stringify.default)(args),
3078
+ rpcSubscriptions
3079
+ })
3080
+ );
3081
+ }
3082
+ function createSolanaRpcSubscriptions_UNSTABLE(config) {
3083
+ return createJsonSubscriptionRpc({
3084
+ ...config,
3085
+ api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG)
3086
+ });
3087
+ }
508
3088
 
509
3089
  // src/rpc-transport.ts
510
3090
  init_env_shim();
3091
+
3092
+ // src/rpc-request-coalescer.ts
3093
+ init_env_shim();
3094
+ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
3095
+ let coalescedRequestsByDeduplicationKey;
3096
+ return async function makeCoalescedHttpRequest(config) {
3097
+ const { payload, signal } = config;
3098
+ const deduplicationKey = getDeduplicationKey(payload);
3099
+ if (deduplicationKey === void 0) {
3100
+ return await transport(config);
3101
+ }
3102
+ if (!coalescedRequestsByDeduplicationKey) {
3103
+ Promise.resolve().then(() => {
3104
+ coalescedRequestsByDeduplicationKey = void 0;
3105
+ });
3106
+ coalescedRequestsByDeduplicationKey = {};
3107
+ }
3108
+ if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {
3109
+ const abortController = new AbortController();
3110
+ coalescedRequestsByDeduplicationKey[deduplicationKey] = {
3111
+ abortController,
3112
+ numConsumers: 0,
3113
+ responsePromise: transport({
3114
+ ...config,
3115
+ signal: abortController.signal
3116
+ })
3117
+ };
3118
+ }
3119
+ const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];
3120
+ coalescedRequest.numConsumers++;
3121
+ if (signal) {
3122
+ const responsePromise = coalescedRequest.responsePromise;
3123
+ return await new Promise((resolve, reject) => {
3124
+ const handleAbort = (e3) => {
3125
+ signal.removeEventListener("abort", handleAbort);
3126
+ coalescedRequest.numConsumers -= 1;
3127
+ if (coalescedRequest.numConsumers === 0) {
3128
+ const abortController = coalescedRequest.abortController;
3129
+ abortController.abort();
3130
+ }
3131
+ const abortError = new DOMException(e3.target.reason, "AbortError");
3132
+ reject(abortError);
3133
+ };
3134
+ signal.addEventListener("abort", handleAbort);
3135
+ responsePromise.then(resolve).finally(() => {
3136
+ signal.removeEventListener("abort", handleAbort);
3137
+ });
3138
+ });
3139
+ } else {
3140
+ return await coalescedRequest.responsePromise;
3141
+ }
3142
+ };
3143
+ }
3144
+
3145
+ // src/rpc-request-deduplication.ts
3146
+ init_env_shim();
3147
+ var import_fast_stable_stringify2 = __toESM(require_fast_stable_stringify(), 1);
3148
+ function isJsonRpcPayload(payload) {
3149
+ if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
3150
+ return false;
3151
+ }
3152
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
3153
+ }
3154
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
3155
+ return isJsonRpcPayload(payload) ? (0, import_fast_stable_stringify2.default)([payload.method, payload.params]) : void 0;
3156
+ }
3157
+
3158
+ // src/rpc-transport.ts
511
3159
  function normalizeHeaders2(headers) {
512
3160
  const out = {};
513
3161
  for (const headerName in headers) {
@@ -516,21 +3164,387 @@ this.globalThis.solanaWeb3 = (function (exports) {
516
3164
  return out;
517
3165
  }
518
3166
  function createDefaultRpcTransport(config) {
519
- return createHttpTransport({
520
- ...config,
521
- headers: {
522
- ...config.headers ? normalizeHeaders2(config.headers) : void 0,
523
- ...{
524
- // Keep these headers lowercase so they will override any user-supplied headers above.
525
- "solana-client": `js/${"2.0.0-development"}` ?? "UNKNOWN"
3167
+ return pipe(
3168
+ createHttpTransport({
3169
+ ...config,
3170
+ headers: {
3171
+ ...config.headers ? normalizeHeaders2(config.headers) : void 0,
3172
+ ...{
3173
+ // Keep these headers lowercase so they will override any user-supplied headers above.
3174
+ "solana-client": `js/${"2.0.0-development"}` ?? "UNKNOWN"
3175
+ }
3176
+ }
3177
+ }),
3178
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
3179
+ );
3180
+ }
3181
+
3182
+ // src/rpc-websocket-transport.ts
3183
+ init_env_shim();
3184
+
3185
+ // src/rpc-websocket-autopinger.ts
3186
+ init_env_shim();
3187
+ var PING_PAYLOAD = {
3188
+ jsonrpc: "2.0",
3189
+ method: "ping"
3190
+ };
3191
+ function getWebSocketTransportWithAutoping({ intervalMs, transport }) {
3192
+ const pingableConnections = /* @__PURE__ */ new Map();
3193
+ return async (...args) => {
3194
+ const connection = await transport(...args);
3195
+ let intervalId;
3196
+ function sendPing() {
3197
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);
3198
+ }
3199
+ function restartPingTimer() {
3200
+ clearInterval(intervalId);
3201
+ intervalId = setInterval(sendPing, intervalMs);
3202
+ }
3203
+ if (pingableConnections.has(connection) === false) {
3204
+ pingableConnections.set(connection, {
3205
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
3206
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (...args2) => {
3207
+ restartPingTimer();
3208
+ return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args2);
3209
+ }
3210
+ });
3211
+ (async () => {
3212
+ try {
3213
+ for await (const _ of connection) {
3214
+ restartPingTimer();
3215
+ }
3216
+ } catch {
3217
+ } finally {
3218
+ pingableConnections.delete(connection);
3219
+ clearInterval(intervalId);
3220
+ if (handleOffline) {
3221
+ globalThis.window.removeEventListener("offline", handleOffline);
3222
+ }
3223
+ if (handleOnline) {
3224
+ globalThis.window.removeEventListener("online", handleOnline);
3225
+ }
3226
+ }
3227
+ })();
3228
+ if (globalThis.navigator.onLine) {
3229
+ restartPingTimer();
3230
+ }
3231
+ let handleOffline;
3232
+ let handleOnline;
3233
+ {
3234
+ handleOffline = () => {
3235
+ clearInterval(intervalId);
3236
+ };
3237
+ handleOnline = () => {
3238
+ sendPing();
3239
+ restartPingTimer();
3240
+ };
3241
+ globalThis.window.addEventListener("offline", handleOffline);
3242
+ globalThis.window.addEventListener("online", handleOnline);
526
3243
  }
527
3244
  }
3245
+ return pingableConnections.get(connection);
3246
+ };
3247
+ }
3248
+
3249
+ // src/rpc-websocket-connection-sharding.ts
3250
+ init_env_shim();
3251
+ var NULL_SHARD_CACHE_KEY = Symbol(
3252
+ "Cache key to use when there is no connection sharding strategy"
3253
+ );
3254
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
3255
+ return getCachedAbortableIterableFactory({
3256
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
3257
+ getCacheEntryMissingError(shardKey) {
3258
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
3259
+ },
3260
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
3261
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
3262
+ onCreateIterable: (abortSignal, config) => transport({
3263
+ ...config,
3264
+ signal: abortSignal
3265
+ })
528
3266
  });
529
3267
  }
530
3268
 
531
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
3269
+ // src/rpc-websocket-transport.ts
3270
+ function createDefaultRpcSubscriptionsTransport(config) {
3271
+ const { getShard, intervalMs, ...rest } = config;
3272
+ return pipe(
3273
+ createWebSocketTransport({
3274
+ ...rest,
3275
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
3276
+ 131072
3277
+ }),
3278
+ (transport) => getWebSocketTransportWithAutoping({
3279
+ intervalMs: intervalMs ?? 5e3,
3280
+ transport
3281
+ }),
3282
+ (transport) => getWebSocketTransportWithConnectionSharding({
3283
+ getShard,
3284
+ transport
3285
+ })
3286
+ );
3287
+ }
3288
+
3289
+ // src/transaction-confirmation.ts
3290
+ init_env_shim();
3291
+
3292
+ // src/transaction-confirmation-strategy-blockheight.ts
3293
+ init_env_shim();
3294
+ function createBlockHeightExceedencePromiseFactory(rpcSubscriptions) {
3295
+ return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {
3296
+ const abortController = new AbortController();
3297
+ function handleAbort() {
3298
+ abortController.abort();
3299
+ }
3300
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3301
+ const slotNotifications = await rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal });
3302
+ try {
3303
+ for await (const slotNotification of slotNotifications) {
3304
+ if (slotNotification.slot > lastValidBlockHeight) {
3305
+ throw new Error(
3306
+ "The network has progressed past the last block for which this transaction could have committed."
3307
+ );
3308
+ }
3309
+ }
3310
+ } finally {
3311
+ abortController.abort();
3312
+ }
3313
+ };
3314
+ }
3315
+
3316
+ // src/transaction-confirmation-strategy-nonce.ts
3317
+ init_env_shim();
3318
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
3319
+ 4 + // state(u32)
3320
+ 32;
3321
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
3322
+ return async function getNonceInvalidationPromise({
3323
+ abortSignal: callerAbortSignal,
3324
+ commitment,
3325
+ currentNonceValue,
3326
+ nonceAccountAddress
3327
+ }) {
3328
+ const abortController = new AbortController();
3329
+ function handleAbort() {
3330
+ abortController.abort();
3331
+ }
3332
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3333
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
3334
+ function getNonceFromAccountData([base64EncodedBytes]) {
3335
+ const data = base64.serialize(base64EncodedBytes);
3336
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
3337
+ return base58.deserialize(nonceValueBytes)[0];
3338
+ }
3339
+ const nonceAccountDidAdvancePromise = (async () => {
3340
+ for await (const accountNotification of accountNotifications) {
3341
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
3342
+ if (nonceValue !== currentNonceValue) {
3343
+ throw new Error(
3344
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
3345
+ );
3346
+ }
3347
+ }
3348
+ })();
3349
+ const nonceIsAlreadyInvalidPromise = (async () => {
3350
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
3351
+ commitment,
3352
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
3353
+ encoding: "base58"
3354
+ }).send({ abortSignal: abortController.signal });
3355
+ if (!nonceAccount) {
3356
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
3357
+ }
3358
+ const nonceValue = (
3359
+ // This works because we asked for the exact slice of data representing the nonce
3360
+ // value, and furthermore asked for it in `base58` encoding.
3361
+ nonceAccount.data[0]
3362
+ );
3363
+ if (nonceValue !== currentNonceValue) {
3364
+ throw new Error(
3365
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
3366
+ );
3367
+ } else {
3368
+ await new Promise(() => {
3369
+ });
3370
+ }
3371
+ })();
3372
+ try {
3373
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
3374
+ } finally {
3375
+ abortController.abort();
3376
+ }
3377
+ };
3378
+ }
3379
+
3380
+ // src/transaction-confirmation-strategy-signature.ts
3381
+ init_env_shim();
3382
+ function createSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions) {
3383
+ return async function getSignatureConfirmationPromise({ abortSignal: callerAbortSignal, commitment, signature }) {
3384
+ const abortController = new AbortController();
3385
+ function handleAbort() {
3386
+ abortController.abort();
3387
+ }
3388
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3389
+ const signatureStatusNotifications = await rpcSubscriptions.signatureNotifications(signature, { commitment }).subscribe({ abortSignal: abortController.signal });
3390
+ const signatureDidCommitPromise = (async () => {
3391
+ for await (const signatureStatusNotification of signatureStatusNotifications) {
3392
+ if (signatureStatusNotification.value.err) {
3393
+ throw new Error(`The transaction with signature \`${signature}\` failed.`, {
3394
+ cause: signatureStatusNotification.value.err
3395
+ });
3396
+ } else {
3397
+ return;
3398
+ }
3399
+ }
3400
+ })();
3401
+ const signatureStatusLookupPromise = (async () => {
3402
+ const { value: signatureStatusResults } = await rpc.getSignatureStatuses([signature]).send({ abortSignal: abortController.signal });
3403
+ const signatureStatus = signatureStatusResults[0];
3404
+ if (signatureStatus && signatureStatus.confirmationStatus && commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0) {
3405
+ return;
3406
+ } else {
3407
+ await new Promise(() => {
3408
+ });
3409
+ }
3410
+ })();
3411
+ try {
3412
+ return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);
3413
+ } finally {
3414
+ abortController.abort();
3415
+ }
3416
+ };
3417
+ }
3418
+
3419
+ // src/transaction-confirmation.ts
3420
+ async function raceStrategies(config, getSpecificStrategiesForRace) {
3421
+ const { abortSignal: callerAbortSignal, commitment, getSignatureConfirmationPromise, transaction } = config;
3422
+ callerAbortSignal.throwIfAborted();
3423
+ const signature = getSignatureFromTransaction(transaction);
3424
+ const abortController = new AbortController();
3425
+ function handleAbort() {
3426
+ abortController.abort();
3427
+ }
3428
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3429
+ try {
3430
+ const specificStrategies = getSpecificStrategiesForRace({
3431
+ ...config,
3432
+ abortSignal: abortController.signal
3433
+ });
3434
+ return await Promise.race([
3435
+ getSignatureConfirmationPromise({
3436
+ abortSignal: abortController.signal,
3437
+ commitment,
3438
+ signature
3439
+ }),
3440
+ ...specificStrategies
3441
+ ]);
3442
+ } finally {
3443
+ abortController.abort();
3444
+ }
3445
+ }
3446
+ function createDefaultDurableNonceTransactionConfirmer({
3447
+ rpc,
3448
+ rpcSubscriptions
3449
+ }) {
3450
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
3451
+ const getSignatureConfirmationPromise = createSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions);
3452
+ return async function confirmTransaction(config) {
3453
+ await waitForDurableNonceTransactionConfirmation({
3454
+ ...config,
3455
+ getNonceInvalidationPromise,
3456
+ getSignatureConfirmationPromise
3457
+ });
3458
+ };
3459
+ }
3460
+ function createDefaultTransactionConfirmer({ rpc, rpcSubscriptions }) {
3461
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);
3462
+ const getSignatureConfirmationPromise = createSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions);
3463
+ return async function confirmTransaction(config) {
3464
+ await waitForTransactionConfirmation({
3465
+ ...config,
3466
+ getBlockHeightExceedencePromise,
3467
+ getSignatureConfirmationPromise
3468
+ });
3469
+ };
3470
+ }
3471
+ async function waitForDurableNonceTransactionConfirmation(config) {
3472
+ await raceStrategies(
3473
+ config,
3474
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
3475
+ return [
3476
+ getNonceInvalidationPromise({
3477
+ abortSignal,
3478
+ commitment,
3479
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
3480
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
3481
+ })
3482
+ ];
3483
+ }
3484
+ );
3485
+ }
3486
+ async function waitForTransactionConfirmation(config) {
3487
+ await raceStrategies(
3488
+ config,
3489
+ function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {
3490
+ return [
3491
+ getBlockHeightExceedencePromise({
3492
+ abortSignal,
3493
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
3494
+ })
3495
+ ];
3496
+ }
3497
+ );
3498
+ }
3499
+
3500
+ exports.AccountRole = AccountRole;
3501
+ exports.address = address;
3502
+ exports.appendTransactionInstruction = appendTransactionInstruction;
3503
+ exports.assertIsAddress = assertIsAddress;
3504
+ exports.assertIsBlockhash = assertIsBlockhash;
3505
+ exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
3506
+ exports.assertIsProgramDerivedAddress = assertIsProgramDerivedAddress;
3507
+ exports.assertIsTransactionSignature = assertIsTransactionSignature;
3508
+ exports.createAddressWithSeed = createAddressWithSeed;
3509
+ exports.createBlockHeightExceedencePromiseFactory = createBlockHeightExceedencePromiseFactory;
3510
+ exports.createDefaultDurableNonceTransactionConfirmer = createDefaultDurableNonceTransactionConfirmer;
3511
+ exports.createDefaultRpcSubscriptionsTransport = createDefaultRpcSubscriptionsTransport;
532
3512
  exports.createDefaultRpcTransport = createDefaultRpcTransport;
3513
+ exports.createDefaultTransactionConfirmer = createDefaultTransactionConfirmer;
3514
+ exports.createNonceInvalidationPromiseFactory = createNonceInvalidationPromiseFactory;
3515
+ exports.createSignatureConfirmationPromiseFactory = createSignatureConfirmationPromiseFactory;
533
3516
  exports.createSolanaRpc = createSolanaRpc;
3517
+ exports.createSolanaRpcSubscriptions = createSolanaRpcSubscriptions;
3518
+ exports.createSolanaRpcSubscriptions_UNSTABLE = createSolanaRpcSubscriptions_UNSTABLE;
3519
+ exports.createTransaction = createTransaction;
3520
+ exports.downgradeRoleToNonSigner = downgradeRoleToNonSigner;
3521
+ exports.downgradeRoleToReadonly = downgradeRoleToReadonly;
3522
+ exports.generateKeyPair = generateKeyPair;
3523
+ exports.getAddressCodec = getAddressCodec;
3524
+ exports.getAddressComparator = getAddressComparator;
3525
+ exports.getAddressFromPublicKey = getAddressFromPublicKey;
3526
+ exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
3527
+ exports.getProgramDerivedAddress = getProgramDerivedAddress;
3528
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
3529
+ exports.getTransactionEncoder = getTransactionEncoder;
3530
+ exports.isAddress = isAddress;
3531
+ exports.isProgramDerivedAddress = isProgramDerivedAddress;
3532
+ exports.isSignerRole = isSignerRole;
3533
+ exports.isTransactionSignature = isTransactionSignature;
3534
+ exports.isWritableRole = isWritableRole;
3535
+ exports.mergeRoles = mergeRoles;
3536
+ exports.prependTransactionInstruction = prependTransactionInstruction;
3537
+ exports.setTransactionFeePayer = setTransactionFeePayer;
3538
+ exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
3539
+ exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
3540
+ exports.signBytes = signBytes;
3541
+ exports.signTransaction = signTransaction;
3542
+ exports.transactionSignature = transactionSignature;
3543
+ exports.upgradeRoleToSigner = upgradeRoleToSigner;
3544
+ exports.upgradeRoleToWritable = upgradeRoleToWritable;
3545
+ exports.verifySignature = verifySignature;
3546
+ exports.waitForDurableNonceTransactionConfirmation = waitForDurableNonceTransactionConfirmation;
3547
+ exports.waitForTransactionConfirmation = waitForTransactionConfirmation;
534
3548
 
535
3549
  return exports;
536
3550