@solana/web3.js 2.0.0-experimental.d6c5c0e → 2.0.0-experimental.da22638

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 (33) hide show
  1. package/README.md +14 -13
  2. package/dist/index.browser.cjs +297 -9
  3. package/dist/index.browser.cjs.map +1 -1
  4. package/dist/index.browser.js +277 -11
  5. package/dist/index.browser.js.map +1 -1
  6. package/dist/index.development.js +2567 -195
  7. package/dist/index.development.js.map +1 -1
  8. package/dist/index.native.js +264 -11
  9. package/dist/index.native.js.map +1 -1
  10. package/dist/index.node.cjs +288 -9
  11. package/dist/index.node.cjs.map +1 -1
  12. package/dist/index.node.js +266 -11
  13. package/dist/index.node.js.map +1 -1
  14. package/dist/index.production.min.js +38 -4
  15. package/dist/types/cached-abortable-iterable.d.ts +11 -0
  16. package/dist/types/cached-abortable-iterable.d.ts.map +1 -0
  17. package/dist/types/index.d.ts +4 -0
  18. package/dist/types/index.d.ts.map +1 -1
  19. package/dist/types/rpc-default-config.d.ts.map +1 -1
  20. package/dist/types/rpc-request-coalescer.d.ts +5 -0
  21. package/dist/types/rpc-request-coalescer.d.ts.map +1 -0
  22. package/dist/types/rpc-request-deduplication.d.ts +3 -0
  23. package/dist/types/rpc-request-deduplication.d.ts.map +1 -0
  24. package/dist/types/rpc-transport.d.ts.map +1 -1
  25. package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
  26. package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
  27. package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
  28. package/dist/types/rpc-websocket-connection-sharding.d.ts.map +1 -0
  29. package/dist/types/rpc-websocket-transport.d.ts +13 -0
  30. package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
  31. package/dist/types/rpc.d.ts +4 -3
  32. package/dist/types/rpc.d.ts.map +1 -1
  33. package/package.json +23 -21
@@ -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,14 +23,18 @@ 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
+ };
33
38
 
34
39
  // ../build-scripts/env-shim.ts
35
40
  var init_env_shim = __esm({
@@ -37,153 +42,694 @@ this.globalThis.solanaWeb3 = (function (exports) {
37
42
  }
38
43
  });
39
44
 
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) {
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) {
43
48
  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");
96
- }
97
- length = i2;
98
- pbegin++;
99
- }
100
- var it2 = size - length;
101
- while (it2 !== size && b58[it2] === 0) {
102
- it2++;
103
- }
104
- var str = LEADER.repeat(zeroes);
105
- for (; it2 < size; ++it2) {
106
- str += ALPHABET.charAt(b58[it2]);
107
- }
108
- return str;
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);
109
54
  }
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");
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
+ }
139
103
  }
140
- length = i2;
141
- psz++;
142
- }
143
- var it4 = size - length;
144
- while (it4 !== size && b256[it4] === 0) {
145
- it4++;
146
- }
147
- var vch = new Uint8Array(zeroes + (size - it4));
148
- var j2 = zeroes;
149
- while (it4 !== size) {
150
- vch[j2++] = b256[it4++];
151
- }
152
- return vch;
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;
153
111
  }
154
- function decode(string) {
155
- var buffer = decodeUnsafe(string);
156
- if (buffer) {
157
- return buffer;
158
- }
159
- throw new Error("Non-base" + BASE + " character");
112
+ }
113
+ module.exports = function(val) {
114
+ var returnVal = stringify(val, false);
115
+ if (returnVal !== void 0) {
116
+ return "" + returnVal;
160
117
  }
161
- return {
162
- encode,
163
- decodeUnsafe,
164
- decode
165
- };
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];
166
281
  }
167
- module.exports = base;
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/nullCharacters.mjs
290
+ init_env_shim();
291
+ var removeNullCharacters = (value) => (
292
+ // eslint-disable-next-line no-control-regex
293
+ value.replace(/\u0000/g, "")
294
+ );
295
+
296
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/utf8.mjs
297
+ init_env_shim();
298
+ var utf8 = {
299
+ description: "utf8",
300
+ fixedSize: null,
301
+ maxSize: null,
302
+ serialize(value) {
303
+ return new TextEncoder().encode(value);
304
+ },
305
+ deserialize(buffer, offset = 0) {
306
+ const value = new TextDecoder().decode(buffer.slice(offset));
307
+ return [removeNullCharacters(value), buffer.length];
308
+ }
309
+ };
310
+
311
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/index.mjs
312
+ init_env_shim();
313
+
314
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs
315
+ init_env_shim();
316
+ var Endian;
317
+ (function(Endian2) {
318
+ Endian2["Little"] = "le";
319
+ Endian2["Big"] = "be";
320
+ })(Endian || (Endian = {}));
321
+
322
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs
323
+ init_env_shim();
324
+ var NumberOutOfRangeError = class extends RangeError {
325
+ constructor(serializer, min, max, actual) {
326
+ super(`Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`);
327
+ __publicField(this, "name", "NumberOutOfRangeError");
168
328
  }
329
+ };
330
+
331
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/utils.mjs
332
+ init_env_shim();
333
+ function numberFactory(input) {
334
+ let littleEndian;
335
+ let defaultDescription = input.name;
336
+ if (input.size > 1) {
337
+ littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little;
338
+ defaultDescription += littleEndian ? "(le)" : "(be)";
339
+ }
340
+ return {
341
+ description: input.options.description ?? defaultDescription,
342
+ fixedSize: input.size,
343
+ maxSize: input.size,
344
+ serialize(value) {
345
+ if (input.range) {
346
+ assertRange(input.name, input.range[0], input.range[1], value);
347
+ }
348
+ const buffer = new ArrayBuffer(input.size);
349
+ input.set(new DataView(buffer), value, littleEndian);
350
+ return new Uint8Array(buffer);
351
+ },
352
+ deserialize(bytes2, offset = 0) {
353
+ const slice = bytes2.slice(offset, offset + input.size);
354
+ assertEnoughBytes("i8", slice, input.size);
355
+ const view = toDataView(slice);
356
+ return [input.get(view, littleEndian), offset + input.size];
357
+ }
358
+ };
359
+ }
360
+ var toArrayBuffer = (array2) => array2.buffer.slice(array2.byteOffset, array2.byteLength + array2.byteOffset);
361
+ var toDataView = (array2) => new DataView(toArrayBuffer(array2));
362
+ var assertRange = (serializer, min, max, value) => {
363
+ if (value < min || value > max) {
364
+ throw new NumberOutOfRangeError(serializer, min, max, value);
365
+ }
366
+ };
367
+ var assertEnoughBytes = (serializer, bytes2, expected) => {
368
+ if (bytes2.length === 0) {
369
+ throw new DeserializingEmptyBufferError(serializer);
370
+ }
371
+ if (bytes2.length < expected) {
372
+ throw new NotEnoughBytesError(serializer, expected, bytes2.length);
373
+ }
374
+ };
375
+
376
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u8.mjs
377
+ init_env_shim();
378
+ var u8 = (options = {}) => numberFactory({
379
+ name: "u8",
380
+ size: 1,
381
+ range: [0, Number("0xff")],
382
+ set: (view, value) => view.setUint8(0, Number(value)),
383
+ get: (view) => view.getUint8(0),
384
+ options
169
385
  });
170
386
 
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);
387
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u32.mjs
388
+ init_env_shim();
389
+ var u32 = (options = {}) => numberFactory({
390
+ name: "u32",
391
+ size: 4,
392
+ range: [0, Number("0xffffffff")],
393
+ set: (view, value, le) => view.setUint32(0, Number(value), le),
394
+ get: (view, le) => view.getUint32(0, le),
395
+ options
396
+ });
397
+
398
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/shortU16.mjs
399
+ init_env_shim();
400
+ var shortU16 = (options = {}) => ({
401
+ description: options.description ?? "shortU16",
402
+ fixedSize: null,
403
+ maxSize: 3,
404
+ serialize: (value) => {
405
+ assertRange("shortU16", 0, 65535, value);
406
+ const bytes2 = [0];
407
+ for (let ii = 0; ; ii += 1) {
408
+ const alignedValue = value >> ii * 7;
409
+ if (alignedValue === 0) {
410
+ break;
411
+ }
412
+ const nextSevenBits = 127 & alignedValue;
413
+ bytes2[ii] = nextSevenBits;
414
+ if (ii > 0) {
415
+ bytes2[ii - 1] |= 128;
416
+ }
417
+ }
418
+ return new Uint8Array(bytes2);
419
+ },
420
+ deserialize: (bytes2, offset = 0) => {
421
+ let value = 0;
422
+ let byteCount = 0;
423
+ while (++byteCount) {
424
+ const byteIndex = byteCount - 1;
425
+ const currentByte = bytes2[offset + byteIndex];
426
+ const nextSevenBits = 127 & currentByte;
427
+ value |= nextSevenBits << byteIndex * 7;
428
+ if ((currentByte & 128) === 0) {
429
+ break;
430
+ }
431
+ }
432
+ return [value, offset + byteCount];
178
433
  }
179
434
  });
180
435
 
181
- // src/index.ts
436
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs
182
437
  init_env_shim();
183
438
 
184
- // ../keys/dist/index.browser.js
439
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/errors.mjs
440
+ init_env_shim();
441
+ var InvalidNumberOfItemsError = class extends Error {
442
+ constructor(serializer, expected, actual) {
443
+ super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`);
444
+ __publicField(this, "name", "InvalidNumberOfItemsError");
445
+ }
446
+ };
447
+ var InvalidArrayLikeRemainderSizeError = class extends Error {
448
+ constructor(remainderSize, itemSize) {
449
+ 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.`);
450
+ __publicField(this, "name", "InvalidArrayLikeRemainderSizeError");
451
+ }
452
+ };
453
+ var UnrecognizedArrayLikeSerializerSizeError = class extends Error {
454
+ constructor(size) {
455
+ super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);
456
+ __publicField(this, "name", "UnrecognizedArrayLikeSerializerSizeError");
457
+ }
458
+ };
459
+
460
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
185
461
  init_env_shim();
186
- var import_bs58 = __toESM(require_bs58(), 1);
462
+
463
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/sumSerializerSizes.mjs
464
+ init_env_shim();
465
+ function sumSerializerSizes(sizes) {
466
+ return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
467
+ }
468
+
469
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
470
+ function getResolvedSize(size, childrenSizes, bytes2, offset) {
471
+ if (typeof size === "number") {
472
+ return [size, offset];
473
+ }
474
+ if (typeof size === "object") {
475
+ return size.deserialize(bytes2, offset);
476
+ }
477
+ if (size === "remainder") {
478
+ const childrenSize = sumSerializerSizes(childrenSizes);
479
+ if (childrenSize === null) {
480
+ throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.');
481
+ }
482
+ const remainder = bytes2.slice(offset).length;
483
+ if (remainder % childrenSize !== 0) {
484
+ throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);
485
+ }
486
+ return [remainder / childrenSize, offset];
487
+ }
488
+ throw new UnrecognizedArrayLikeSerializerSizeError(size);
489
+ }
490
+ function getSizeDescription(size) {
491
+ return typeof size === "object" ? size.description : `${size}`;
492
+ }
493
+ function getSizeFromChildren(size, childrenSizes) {
494
+ if (typeof size !== "number")
495
+ return null;
496
+ if (size === 0)
497
+ return 0;
498
+ const childrenSize = sumSerializerSizes(childrenSizes);
499
+ return childrenSize === null ? null : childrenSize * size;
500
+ }
501
+ function getSizePrefix(size, realSize) {
502
+ return typeof size === "object" ? size.serialize(realSize) : new Uint8Array();
503
+ }
504
+
505
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs
506
+ function array(item, options = {}) {
507
+ const size = options.size ?? u32();
508
+ if (size === "remainder" && item.fixedSize === null) {
509
+ throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.');
510
+ }
511
+ return {
512
+ description: options.description ?? `array(${item.description}; ${getSizeDescription(size)})`,
513
+ fixedSize: getSizeFromChildren(size, [item.fixedSize]),
514
+ maxSize: getSizeFromChildren(size, [item.maxSize]),
515
+ serialize: (value) => {
516
+ if (typeof size === "number" && value.length !== size) {
517
+ throw new InvalidNumberOfItemsError("array", size, value.length);
518
+ }
519
+ return mergeBytes([getSizePrefix(size, value.length), ...value.map((v) => item.serialize(v))]);
520
+ },
521
+ deserialize: (bytes2, offset = 0) => {
522
+ if (typeof size === "object" && bytes2.slice(offset).length === 0) {
523
+ return [[], offset];
524
+ }
525
+ const [resolvedSize, newOffset] = getResolvedSize(size, [item.fixedSize], bytes2, offset);
526
+ offset = newOffset;
527
+ const values = [];
528
+ for (let i = 0; i < resolvedSize; i += 1) {
529
+ const [value, newOffset2] = item.deserialize(bytes2, offset);
530
+ values.push(value);
531
+ offset = newOffset2;
532
+ }
533
+ return [values, offset];
534
+ }
535
+ };
536
+ }
537
+
538
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/bytes.mjs
539
+ init_env_shim();
540
+ function bytes(options = {}) {
541
+ const size = options.size ?? "variable";
542
+ const description = options.description ?? `bytes(${getSizeDescription(size)})`;
543
+ const byteSerializer = {
544
+ description,
545
+ fixedSize: null,
546
+ maxSize: null,
547
+ serialize: (value) => new Uint8Array(value),
548
+ deserialize: (bytes2, offset = 0) => {
549
+ const slice = bytes2.slice(offset);
550
+ return [slice, offset + slice.length];
551
+ }
552
+ };
553
+ if (size === "variable") {
554
+ return byteSerializer;
555
+ }
556
+ if (typeof size === "number") {
557
+ return fixSerializer(byteSerializer, size, description);
558
+ }
559
+ return {
560
+ description,
561
+ fixedSize: null,
562
+ maxSize: null,
563
+ serialize: (value) => {
564
+ const contentBytes = byteSerializer.serialize(value);
565
+ const lengthBytes = size.serialize(contentBytes.length);
566
+ return mergeBytes([lengthBytes, contentBytes]);
567
+ },
568
+ deserialize: (buffer, offset = 0) => {
569
+ if (buffer.slice(offset).length === 0) {
570
+ throw new DeserializingEmptyBufferError("bytes");
571
+ }
572
+ const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
573
+ const length = Number(lengthBigInt);
574
+ offset = lengthOffset;
575
+ const contentBuffer = buffer.slice(offset, offset + length);
576
+ if (contentBuffer.length < length) {
577
+ throw new NotEnoughBytesError("bytes", length, contentBuffer.length);
578
+ }
579
+ const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);
580
+ offset += contentOffset;
581
+ return [value, offset];
582
+ }
583
+ };
584
+ }
585
+
586
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs
587
+ init_env_shim();
588
+ function string(options = {}) {
589
+ const size = options.size ?? u32();
590
+ const encoding = options.encoding ?? utf8;
591
+ const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
592
+ if (size === "variable") {
593
+ return {
594
+ ...encoding,
595
+ description
596
+ };
597
+ }
598
+ if (typeof size === "number") {
599
+ return fixSerializer(encoding, size, description);
600
+ }
601
+ return {
602
+ description,
603
+ fixedSize: null,
604
+ maxSize: null,
605
+ serialize: (value) => {
606
+ const contentBytes = encoding.serialize(value);
607
+ const lengthBytes = size.serialize(contentBytes.length);
608
+ return mergeBytes([lengthBytes, contentBytes]);
609
+ },
610
+ deserialize: (buffer, offset = 0) => {
611
+ if (buffer.slice(offset).length === 0) {
612
+ throw new DeserializingEmptyBufferError("string");
613
+ }
614
+ const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
615
+ const length = Number(lengthBigInt);
616
+ offset = lengthOffset;
617
+ const contentBuffer = buffer.slice(offset, offset + length);
618
+ if (contentBuffer.length < length) {
619
+ throw new NotEnoughBytesError("string", length, contentBuffer.length);
620
+ }
621
+ const [value, contentOffset] = encoding.deserialize(contentBuffer);
622
+ offset += contentOffset;
623
+ return [value, offset];
624
+ }
625
+ };
626
+ }
627
+
628
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/struct.mjs
629
+ init_env_shim();
630
+ function struct(fields, options = {}) {
631
+ const fieldDescriptions = fields.map(([name, serializer]) => `${String(name)}: ${serializer.description}`).join(", ");
632
+ return {
633
+ description: options.description ?? `struct(${fieldDescriptions})`,
634
+ fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),
635
+ maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),
636
+ serialize: (struct2) => {
637
+ const fieldBytes = fields.map(([key, serializer]) => serializer.serialize(struct2[key]));
638
+ return mergeBytes(fieldBytes);
639
+ },
640
+ deserialize: (bytes2, offset = 0) => {
641
+ const struct2 = {};
642
+ fields.forEach(([key, serializer]) => {
643
+ const [value, newOffset] = serializer.deserialize(bytes2, offset);
644
+ offset = newOffset;
645
+ struct2[key] = value;
646
+ });
647
+ return [struct2, offset];
648
+ }
649
+ };
650
+ }
651
+
652
+ // ../assertions/dist/index.browser.js
653
+ init_env_shim();
654
+ function assertIsSecureContext() {
655
+ if (!globalThis.isSecureContext) {
656
+ throw new Error(
657
+ "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
658
+ );
659
+ }
660
+ }
661
+ var cachedEd25519Decision;
662
+ async function isEd25519CurveSupported(subtle) {
663
+ if (cachedEd25519Decision === void 0) {
664
+ cachedEd25519Decision = new Promise((resolve) => {
665
+ subtle.generateKey(
666
+ "Ed25519",
667
+ /* extractable */
668
+ false,
669
+ ["sign", "verify"]
670
+ ).catch(() => {
671
+ resolve(cachedEd25519Decision = false);
672
+ }).then(() => {
673
+ resolve(cachedEd25519Decision = true);
674
+ });
675
+ });
676
+ }
677
+ if (typeof cachedEd25519Decision === "boolean") {
678
+ return cachedEd25519Decision;
679
+ } else {
680
+ return await cachedEd25519Decision;
681
+ }
682
+ }
683
+ async function assertDigestCapabilityIsAvailable() {
684
+ assertIsSecureContext();
685
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.digest !== "function") {
686
+ throw new Error("No digest implementation could be found");
687
+ }
688
+ }
689
+ async function assertKeyGenerationIsAvailable() {
690
+ assertIsSecureContext();
691
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
692
+ throw new Error("No key generation implementation could be found");
693
+ }
694
+ if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
695
+ throw new Error(
696
+ "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"
697
+ );
698
+ }
699
+ }
700
+ async function assertKeyExporterIsAvailable() {
701
+ assertIsSecureContext();
702
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
703
+ throw new Error("No key export implementation could be found");
704
+ }
705
+ }
706
+ async function assertSigningCapabilityIsAvailable() {
707
+ assertIsSecureContext();
708
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
709
+ throw new Error("No signing implementation could be found");
710
+ }
711
+ }
712
+ async function assertVerificationCapabilityIsAvailable() {
713
+ assertIsSecureContext();
714
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
715
+ throw new Error("No signature verification implementation could be found");
716
+ }
717
+ }
718
+ function isBase58EncodedAddress(putativeBase58EncodedAddress) {
719
+ if (
720
+ // Lowest address (32 bytes of zeroes)
721
+ putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
722
+ putativeBase58EncodedAddress.length > 44
723
+ ) {
724
+ return false;
725
+ }
726
+ const bytes2 = base58.serialize(putativeBase58EncodedAddress);
727
+ const numBytes = bytes2.byteLength;
728
+ if (numBytes !== 32) {
729
+ return false;
730
+ }
731
+ return true;
732
+ }
187
733
  function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
188
734
  try {
189
735
  if (
@@ -193,15 +739,1013 @@ this.globalThis.solanaWeb3 = (function (exports) {
193
739
  ) {
194
740
  throw new Error("Expected input string to decode to a byte array of length 32.");
195
741
  }
196
- const bytes = import_bs58.default.decode(putativeBase58EncodedAddress);
197
- const numBytes = bytes.byteLength;
742
+ const bytes2 = base58.serialize(putativeBase58EncodedAddress);
743
+ const numBytes = bytes2.byteLength;
744
+ if (numBytes !== 32) {
745
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
746
+ }
747
+ } catch (e3) {
748
+ throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
749
+ cause: e3
750
+ });
751
+ }
752
+ }
753
+ function address(putativeBase58EncodedAddress) {
754
+ assertIsBase58EncodedAddress(putativeBase58EncodedAddress);
755
+ return putativeBase58EncodedAddress;
756
+ }
757
+ function getBase58EncodedAddressCodec(config) {
758
+ return string({
759
+ description: config?.description ?? ("A 32-byte account address" ),
760
+ encoding: base58,
761
+ size: 32
762
+ });
763
+ }
764
+ function getBase58EncodedAddressComparator() {
765
+ return new Intl.Collator("en", {
766
+ caseFirst: "lower",
767
+ ignorePunctuation: false,
768
+ localeMatcher: "best fit",
769
+ numeric: false,
770
+ sensitivity: "variant",
771
+ usage: "sort"
772
+ }).compare;
773
+ }
774
+ var D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
775
+ var P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;
776
+ var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
777
+ function mod(a) {
778
+ const r = a % P;
779
+ return r >= 0n ? r : P + r;
780
+ }
781
+ function pow2(x, power) {
782
+ let r = x;
783
+ while (power-- > 0n) {
784
+ r *= r;
785
+ r %= P;
786
+ }
787
+ return r;
788
+ }
789
+ function pow_2_252_3(x) {
790
+ const x2 = x * x % P;
791
+ const b2 = x2 * x % P;
792
+ const b4 = pow2(b2, 2n) * b2 % P;
793
+ const b5 = pow2(b4, 1n) * x % P;
794
+ const b10 = pow2(b5, 5n) * b5 % P;
795
+ const b20 = pow2(b10, 10n) * b10 % P;
796
+ const b40 = pow2(b20, 20n) * b20 % P;
797
+ const b80 = pow2(b40, 40n) * b40 % P;
798
+ const b160 = pow2(b80, 80n) * b80 % P;
799
+ const b240 = pow2(b160, 80n) * b80 % P;
800
+ const b250 = pow2(b240, 10n) * b10 % P;
801
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
802
+ return pow_p_5_8;
803
+ }
804
+ function uvRatio(u, v) {
805
+ const v3 = mod(v * v * v);
806
+ const v7 = mod(v3 * v3 * v);
807
+ const pow = pow_2_252_3(u * v7);
808
+ let x = mod(u * v3 * pow);
809
+ const vx2 = mod(v * x * x);
810
+ const root1 = x;
811
+ const root2 = mod(x * RM1);
812
+ const useRoot1 = vx2 === u;
813
+ const useRoot2 = vx2 === mod(-u);
814
+ const noRoot = vx2 === mod(-u * RM1);
815
+ if (useRoot1)
816
+ x = root1;
817
+ if (useRoot2 || noRoot)
818
+ x = root2;
819
+ if ((mod(x) & 1n) === 1n)
820
+ x = mod(-x);
821
+ if (!useRoot1 && !useRoot2) {
822
+ return null;
823
+ }
824
+ return x;
825
+ }
826
+ function pointIsOnCurve(y, lastByte) {
827
+ const y2 = mod(y * y);
828
+ const u = mod(y2 - 1n);
829
+ const v = mod(D * y2 + 1n);
830
+ const x = uvRatio(u, v);
831
+ if (x === null) {
832
+ return false;
833
+ }
834
+ const isLastByteOdd = (lastByte & 128) !== 0;
835
+ if (x === 0n && isLastByteOdd) {
836
+ return false;
837
+ }
838
+ return true;
839
+ }
840
+ function byteToHex(byte) {
841
+ const hexString = byte.toString(16);
842
+ if (hexString.length === 1) {
843
+ return `0${hexString}`;
844
+ } else {
845
+ return hexString;
846
+ }
847
+ }
848
+ function decompressPointBytes(bytes2) {
849
+ const hexString = bytes2.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
850
+ const integerLiteralString = `0x${hexString}`;
851
+ return BigInt(integerLiteralString);
852
+ }
853
+ async function compressedPointBytesAreOnCurve(bytes2) {
854
+ if (bytes2.byteLength !== 32) {
855
+ return false;
856
+ }
857
+ const y = decompressPointBytes(bytes2);
858
+ return pointIsOnCurve(y, bytes2[31]);
859
+ }
860
+ var MAX_SEED_LENGTH = 32;
861
+ var MAX_SEEDS = 16;
862
+ var PDA_MARKER_BYTES = [
863
+ // The string 'ProgramDerivedAddress'
864
+ 80,
865
+ 114,
866
+ 111,
867
+ 103,
868
+ 114,
869
+ 97,
870
+ 109,
871
+ 68,
872
+ 101,
873
+ 114,
874
+ 105,
875
+ 118,
876
+ 101,
877
+ 100,
878
+ 65,
879
+ 100,
880
+ 100,
881
+ 114,
882
+ 101,
883
+ 115,
884
+ 115
885
+ ];
886
+ var PointOnCurveError = class extends Error {
887
+ };
888
+ async function createProgramDerivedAddress({ programAddress, seeds }) {
889
+ await assertDigestCapabilityIsAvailable();
890
+ if (seeds.length > MAX_SEEDS) {
891
+ throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);
892
+ }
893
+ let textEncoder;
894
+ const seedBytes = seeds.reduce((acc, seed, ii) => {
895
+ const bytes2 = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
896
+ if (bytes2.byteLength > MAX_SEED_LENGTH) {
897
+ throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);
898
+ }
899
+ acc.push(...bytes2);
900
+ return acc;
901
+ }, []);
902
+ const base58EncodedAddressCodec = getBase58EncodedAddressCodec();
903
+ const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);
904
+ const addressBytesBuffer = await crypto.subtle.digest(
905
+ "SHA-256",
906
+ new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
907
+ );
908
+ const addressBytes = new Uint8Array(addressBytesBuffer);
909
+ if (await compressedPointBytesAreOnCurve(addressBytes)) {
910
+ throw new PointOnCurveError("Invalid seeds; point must fall off the Ed25519 curve");
911
+ }
912
+ return base58EncodedAddressCodec.deserialize(addressBytes)[0];
913
+ }
914
+ async function getProgramDerivedAddress({ programAddress, seeds }) {
915
+ let bumpSeed = 255;
916
+ while (bumpSeed > 0) {
917
+ try {
918
+ return {
919
+ bumpSeed,
920
+ pda: await createProgramDerivedAddress({
921
+ programAddress,
922
+ seeds: [...seeds, new Uint8Array([bumpSeed])]
923
+ })
924
+ };
925
+ } catch (e3) {
926
+ if (e3 instanceof PointOnCurveError) {
927
+ bumpSeed--;
928
+ } else {
929
+ throw e3;
930
+ }
931
+ }
932
+ }
933
+ throw new Error("Unable to find a viable program address bump seed");
934
+ }
935
+ async function createAddressWithSeed({
936
+ baseAddress,
937
+ programAddress,
938
+ seed
939
+ }) {
940
+ const { serialize: serialize4, deserialize: deserialize2 } = getBase58EncodedAddressCodec();
941
+ const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
942
+ if (seedBytes.byteLength > MAX_SEED_LENGTH) {
943
+ throw new Error(`The seed exceeds the maximum length of 32 bytes`);
944
+ }
945
+ const programAddressBytes = serialize4(programAddress);
946
+ if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
947
+ throw new Error(`programAddress cannot end with the PDA marker`);
948
+ }
949
+ const addressBytesBuffer = await crypto.subtle.digest(
950
+ "SHA-256",
951
+ new Uint8Array([...serialize4(baseAddress), ...seedBytes, ...programAddressBytes])
952
+ );
953
+ const addressBytes = new Uint8Array(addressBytesBuffer);
954
+ return deserialize2(addressBytes)[0];
955
+ }
956
+ async function getAddressFromPublicKey(publicKey) {
957
+ await assertKeyExporterIsAvailable();
958
+ if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
959
+ throw new Error("The `CryptoKey` must be an `Ed25519` public key");
960
+ }
961
+ const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
962
+ const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
963
+ return base58EncodedAddress;
964
+ }
965
+
966
+ // ../instructions/dist/index.browser.js
967
+ init_env_shim();
968
+ var AccountRole = /* @__PURE__ */ ((AccountRole22) => {
969
+ AccountRole22[AccountRole22["WRITABLE_SIGNER"] = /* 3 */
970
+ 3] = "WRITABLE_SIGNER";
971
+ AccountRole22[AccountRole22["READONLY_SIGNER"] = /* 2 */
972
+ 2] = "READONLY_SIGNER";
973
+ AccountRole22[AccountRole22["WRITABLE"] = /* 1 */
974
+ 1] = "WRITABLE";
975
+ AccountRole22[AccountRole22["READONLY"] = /* 0 */
976
+ 0] = "READONLY";
977
+ return AccountRole22;
978
+ })(AccountRole || {});
979
+ var IS_SIGNER_BITMASK = 2;
980
+ var IS_WRITABLE_BITMASK = 1;
981
+ function downgradeRoleToNonSigner(role) {
982
+ return role & ~IS_SIGNER_BITMASK;
983
+ }
984
+ function downgradeRoleToReadonly(role) {
985
+ return role & ~IS_WRITABLE_BITMASK;
986
+ }
987
+ function isSignerRole(role) {
988
+ return role >= 2;
989
+ }
990
+ function isWritableRole(role) {
991
+ return (role & IS_WRITABLE_BITMASK) !== 0;
992
+ }
993
+ function mergeRoles(roleA, roleB) {
994
+ return roleA | roleB;
995
+ }
996
+ function upgradeRoleToSigner(role) {
997
+ return role | IS_SIGNER_BITMASK;
998
+ }
999
+ function upgradeRoleToWritable(role) {
1000
+ return role | IS_WRITABLE_BITMASK;
1001
+ }
1002
+
1003
+ // ../keys/dist/index.browser.js
1004
+ init_env_shim();
1005
+ async function generateKeyPair() {
1006
+ await assertKeyGenerationIsAvailable();
1007
+ const keyPair = await crypto.subtle.generateKey(
1008
+ /* algorithm */
1009
+ "Ed25519",
1010
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
1011
+ /* extractable */
1012
+ false,
1013
+ // Prevents the bytes of the private key from being visible to JS.
1014
+ /* allowed uses */
1015
+ ["sign", "verify"]
1016
+ );
1017
+ return keyPair;
1018
+ }
1019
+ async function signBytes(key, data) {
1020
+ await assertSigningCapabilityIsAvailable();
1021
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
1022
+ return new Uint8Array(signedData);
1023
+ }
1024
+ async function verifySignature(key, signature, data) {
1025
+ await assertVerificationCapabilityIsAvailable();
1026
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
1027
+ }
1028
+
1029
+ // ../transactions/dist/index.browser.js
1030
+ init_env_shim();
1031
+ function getUnsignedTransaction(transaction) {
1032
+ if ("signatures" in transaction) {
1033
+ const {
1034
+ signatures: _,
1035
+ // eslint-disable-line @typescript-eslint/no-unused-vars
1036
+ ...unsignedTransaction
1037
+ } = transaction;
1038
+ return unsignedTransaction;
1039
+ } else {
1040
+ return transaction;
1041
+ }
1042
+ }
1043
+ function assertIsBlockhash(putativeBlockhash) {
1044
+ try {
1045
+ if (
1046
+ // Lowest value (32 bytes of zeroes)
1047
+ putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)
1048
+ putativeBlockhash.length > 44
1049
+ ) {
1050
+ throw new Error("Expected input string to decode to a byte array of length 32.");
1051
+ }
1052
+ const bytes3 = base58.serialize(putativeBlockhash);
1053
+ const numBytes = bytes3.byteLength;
198
1054
  if (numBytes !== 32) {
199
1055
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
200
1056
  }
201
- } catch (e2) {
202
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
203
- cause: e2
204
- });
1057
+ } catch (e3) {
1058
+ throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, {
1059
+ cause: e3
1060
+ });
1061
+ }
1062
+ }
1063
+ function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {
1064
+ if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
1065
+ return transaction;
1066
+ }
1067
+ const out = {
1068
+ ...getUnsignedTransaction(transaction),
1069
+ lifetimeConstraint: blockhashLifetimeConstraint
1070
+ };
1071
+ Object.freeze(out);
1072
+ return out;
1073
+ }
1074
+ function createTransaction({
1075
+ version
1076
+ }) {
1077
+ const out = {
1078
+ instructions: [],
1079
+ version
1080
+ };
1081
+ Object.freeze(out);
1082
+ return out;
1083
+ }
1084
+ var AccountRole2 = /* @__PURE__ */ ((AccountRole22) => {
1085
+ AccountRole22[AccountRole22["WRITABLE_SIGNER"] = /* 3 */
1086
+ 3] = "WRITABLE_SIGNER";
1087
+ AccountRole22[AccountRole22["READONLY_SIGNER"] = /* 2 */
1088
+ 2] = "READONLY_SIGNER";
1089
+ AccountRole22[AccountRole22["WRITABLE"] = /* 1 */
1090
+ 1] = "WRITABLE";
1091
+ AccountRole22[AccountRole22["READONLY"] = /* 0 */
1092
+ 0] = "READONLY";
1093
+ return AccountRole22;
1094
+ })(AccountRole2 || {});
1095
+ var IS_WRITABLE_BITMASK2 = 1;
1096
+ function isSignerRole2(role) {
1097
+ return role >= 2;
1098
+ }
1099
+ function isWritableRole2(role) {
1100
+ return (role & IS_WRITABLE_BITMASK2) !== 0;
1101
+ }
1102
+ function mergeRoles2(roleA, roleB) {
1103
+ return roleA | roleB;
1104
+ }
1105
+ var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111";
1106
+ var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
1107
+ function assertIsDurableNonceTransaction(transaction) {
1108
+ if (!isDurableNonceTransaction(transaction)) {
1109
+ throw new Error("Transaction is not a durable nonce transaction");
1110
+ }
1111
+ }
1112
+ function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {
1113
+ return {
1114
+ accounts: [
1115
+ { address: nonceAccountAddress, role: AccountRole2.WRITABLE },
1116
+ {
1117
+ address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,
1118
+ role: AccountRole2.READONLY
1119
+ },
1120
+ { address: nonceAuthorityAddress, role: AccountRole2.READONLY_SIGNER }
1121
+ ],
1122
+ data: new Uint8Array([4, 0, 0, 0]),
1123
+ programAddress: SYSTEM_PROGRAM_ADDRESS
1124
+ };
1125
+ }
1126
+ function isAdvanceNonceAccountInstruction(instruction) {
1127
+ return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data
1128
+ instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts
1129
+ instruction.accounts?.length === 3 && // First account is nonce account address
1130
+ instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole2.WRITABLE && // Second account is recent blockhashes sysvar
1131
+ instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole2.READONLY && // Third account is nonce authority account
1132
+ instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole2.READONLY_SIGNER;
1133
+ }
1134
+ function isAdvanceNonceAccountInstructionData(data) {
1135
+ return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
1136
+ }
1137
+ function isDurableNonceTransaction(transaction) {
1138
+ return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
1139
+ }
1140
+ function setTransactionLifetimeUsingDurableNonce({
1141
+ nonce,
1142
+ nonceAccountAddress,
1143
+ nonceAuthorityAddress
1144
+ }, transaction) {
1145
+ const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);
1146
+ if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) {
1147
+ return transaction;
1148
+ }
1149
+ const out = {
1150
+ ...getUnsignedTransaction(transaction),
1151
+ instructions: [
1152
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1153
+ ...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions
1154
+ ],
1155
+ lifetimeConstraint: {
1156
+ nonce
1157
+ }
1158
+ };
1159
+ Object.freeze(out);
1160
+ return out;
1161
+ }
1162
+ function setTransactionFeePayer(feePayer, transaction) {
1163
+ if ("feePayer" in transaction && feePayer === transaction.feePayer) {
1164
+ return transaction;
1165
+ }
1166
+ const out = {
1167
+ ...getUnsignedTransaction(transaction),
1168
+ feePayer
1169
+ };
1170
+ Object.freeze(out);
1171
+ return out;
1172
+ }
1173
+ function appendTransactionInstruction(instruction, transaction) {
1174
+ const out = {
1175
+ ...getUnsignedTransaction(transaction),
1176
+ instructions: [...transaction.instructions, instruction]
1177
+ };
1178
+ Object.freeze(out);
1179
+ return out;
1180
+ }
1181
+ function prependTransactionInstruction(instruction, transaction) {
1182
+ const out = {
1183
+ ...getUnsignedTransaction(transaction),
1184
+ instructions: [instruction, ...transaction.instructions]
1185
+ };
1186
+ Object.freeze(out);
1187
+ return out;
1188
+ }
1189
+ function upsert(addressMap, address2, update) {
1190
+ addressMap[address2] = update(addressMap[address2] ?? { role: AccountRole2.READONLY });
1191
+ }
1192
+ var TYPE = Symbol("AddressMapTypeProperty");
1193
+ function getAddressMapFromInstructions(feePayer, instructions) {
1194
+ const addressMap = {
1195
+ [feePayer]: { [TYPE]: 0, role: AccountRole2.WRITABLE_SIGNER }
1196
+ };
1197
+ const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();
1198
+ for (const instruction of instructions) {
1199
+ upsert(addressMap, instruction.programAddress, (entry) => {
1200
+ addressesOfInvokedPrograms.add(instruction.programAddress);
1201
+ if (TYPE in entry) {
1202
+ if (isWritableRole2(entry.role)) {
1203
+ switch (entry[TYPE]) {
1204
+ case 0:
1205
+ throw new Error(
1206
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`
1207
+ );
1208
+ default:
1209
+ throw new Error(
1210
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1211
+ );
1212
+ }
1213
+ }
1214
+ if (entry[TYPE] === 2) {
1215
+ return entry;
1216
+ }
1217
+ }
1218
+ return { [TYPE]: 2, role: AccountRole2.READONLY };
1219
+ });
1220
+ let addressComparator;
1221
+ if (!instruction.accounts) {
1222
+ continue;
1223
+ }
1224
+ for (const account of instruction.accounts) {
1225
+ upsert(addressMap, account.address, (entry) => {
1226
+ const {
1227
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1228
+ address: _,
1229
+ ...accountMeta
1230
+ } = account;
1231
+ if (TYPE in entry) {
1232
+ switch (entry[TYPE]) {
1233
+ case 0:
1234
+ return entry;
1235
+ case 1: {
1236
+ const nextRole = mergeRoles2(entry.role, accountMeta.role);
1237
+ if ("lookupTableAddress" in accountMeta) {
1238
+ const shouldReplaceEntry = (
1239
+ // Consider using the new LOOKUP_TABLE if its address is different...
1240
+ entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
1241
+ (addressComparator || (addressComparator = getBase58EncodedAddressComparator()))(
1242
+ accountMeta.lookupTableAddress,
1243
+ entry.lookupTableAddress
1244
+ ) < 0
1245
+ );
1246
+ if (shouldReplaceEntry) {
1247
+ return {
1248
+ [TYPE]: 1,
1249
+ ...accountMeta,
1250
+ role: nextRole
1251
+ };
1252
+ }
1253
+ } else if (isSignerRole2(accountMeta.role)) {
1254
+ return {
1255
+ [TYPE]: 2,
1256
+ role: nextRole
1257
+ };
1258
+ }
1259
+ if (entry.role !== nextRole) {
1260
+ return {
1261
+ ...entry,
1262
+ role: nextRole
1263
+ };
1264
+ } else {
1265
+ return entry;
1266
+ }
1267
+ }
1268
+ case 2: {
1269
+ const nextRole = mergeRoles2(entry.role, accountMeta.role);
1270
+ if (
1271
+ // Check to see if this address represents a program that is invoked
1272
+ // in this transaction.
1273
+ addressesOfInvokedPrograms.has(account.address)
1274
+ ) {
1275
+ if (isWritableRole2(accountMeta.role)) {
1276
+ throw new Error(
1277
+ `This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1278
+ );
1279
+ }
1280
+ if (entry.role !== nextRole) {
1281
+ return {
1282
+ ...entry,
1283
+ role: nextRole
1284
+ };
1285
+ } else {
1286
+ return entry;
1287
+ }
1288
+ } else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as
1289
+ // long as they are not require to sign the transaction.
1290
+ !isSignerRole2(entry.role)) {
1291
+ return {
1292
+ ...accountMeta,
1293
+ [TYPE]: 1,
1294
+ role: nextRole
1295
+ };
1296
+ } else {
1297
+ if (entry.role !== nextRole) {
1298
+ return {
1299
+ ...entry,
1300
+ role: nextRole
1301
+ };
1302
+ } else {
1303
+ return entry;
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+ if ("lookupTableAddress" in accountMeta) {
1310
+ return {
1311
+ ...accountMeta,
1312
+ [TYPE]: 1
1313
+ /* LOOKUP_TABLE */
1314
+ };
1315
+ } else {
1316
+ return {
1317
+ ...accountMeta,
1318
+ [TYPE]: 2
1319
+ /* STATIC */
1320
+ };
1321
+ }
1322
+ });
1323
+ }
1324
+ }
1325
+ return addressMap;
1326
+ }
1327
+ function getOrderedAccountsFromAddressMap(addressMap) {
1328
+ let addressComparator;
1329
+ const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {
1330
+ if (leftEntry[TYPE] !== rightEntry[TYPE]) {
1331
+ if (leftEntry[TYPE] === 0) {
1332
+ return -1;
1333
+ } else if (rightEntry[TYPE] === 0) {
1334
+ return 1;
1335
+ } else if (leftEntry[TYPE] === 2) {
1336
+ return -1;
1337
+ } else if (rightEntry[TYPE] === 2) {
1338
+ return 1;
1339
+ }
1340
+ }
1341
+ const leftIsSigner = isSignerRole2(leftEntry.role);
1342
+ if (leftIsSigner !== isSignerRole2(rightEntry.role)) {
1343
+ return leftIsSigner ? -1 : 1;
1344
+ }
1345
+ const leftIsWritable = isWritableRole2(leftEntry.role);
1346
+ if (leftIsWritable !== isWritableRole2(rightEntry.role)) {
1347
+ return leftIsWritable ? -1 : 1;
1348
+ }
1349
+ addressComparator || (addressComparator = getBase58EncodedAddressComparator());
1350
+ if (leftEntry[TYPE] === 1 && rightEntry[TYPE] === 1 && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
1351
+ return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
1352
+ } else {
1353
+ return addressComparator(leftAddress, rightAddress);
1354
+ }
1355
+ }).map(([address2, addressMeta]) => ({
1356
+ address: address2,
1357
+ ...addressMeta
1358
+ }));
1359
+ return orderedAccounts;
1360
+ }
1361
+ function getCompiledAddressTableLookups(orderedAccounts) {
1362
+ var _a;
1363
+ const index = {};
1364
+ for (const account of orderedAccounts) {
1365
+ if (!("lookupTableAddress" in account)) {
1366
+ continue;
1367
+ }
1368
+ const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
1369
+ readableIndices: [],
1370
+ writableIndices: []
1371
+ });
1372
+ if (account.role === AccountRole2.WRITABLE) {
1373
+ entry.writableIndices.push(account.addressIndex);
1374
+ } else {
1375
+ entry.readableIndices.push(account.addressIndex);
1376
+ }
1377
+ }
1378
+ return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
1379
+ lookupTableAddress,
1380
+ ...index[lookupTableAddress]
1381
+ }));
1382
+ }
1383
+ function getCompiledMessageHeader(orderedAccounts) {
1384
+ let numReadonlyNonSignerAccounts = 0;
1385
+ let numReadonlySignerAccounts = 0;
1386
+ let numSignerAccounts = 0;
1387
+ for (const account of orderedAccounts) {
1388
+ if ("lookupTableAddress" in account) {
1389
+ break;
1390
+ }
1391
+ const accountIsWritable = isWritableRole2(account.role);
1392
+ if (isSignerRole2(account.role)) {
1393
+ numSignerAccounts++;
1394
+ if (!accountIsWritable) {
1395
+ numReadonlySignerAccounts++;
1396
+ }
1397
+ } else if (!accountIsWritable) {
1398
+ numReadonlyNonSignerAccounts++;
1399
+ }
1400
+ }
1401
+ return {
1402
+ numReadonlyNonSignerAccounts,
1403
+ numReadonlySignerAccounts,
1404
+ numSignerAccounts
1405
+ };
1406
+ }
1407
+ function getAccountIndex(orderedAccounts) {
1408
+ const out = {};
1409
+ for (const [index, account] of orderedAccounts.entries()) {
1410
+ out[account.address] = index;
1411
+ }
1412
+ return out;
1413
+ }
1414
+ function getCompiledInstructions(instructions, orderedAccounts) {
1415
+ const accountIndex = getAccountIndex(orderedAccounts);
1416
+ return instructions.map(({ accounts, data, programAddress }) => {
1417
+ return {
1418
+ programAddressIndex: accountIndex[programAddress],
1419
+ ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
1420
+ ...data ? { data } : null
1421
+ };
1422
+ });
1423
+ }
1424
+ function getCompiledLifetimeToken(lifetimeConstraint) {
1425
+ if ("nonce" in lifetimeConstraint) {
1426
+ return lifetimeConstraint.nonce;
1427
+ }
1428
+ return lifetimeConstraint.blockhash;
1429
+ }
1430
+ function getCompiledStaticAccounts(orderedAccounts) {
1431
+ const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
1432
+ const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
1433
+ return orderedStaticAccounts.map(({ address: address2 }) => address2);
1434
+ }
1435
+ function compileMessage(transaction) {
1436
+ const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
1437
+ const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);
1438
+ return {
1439
+ ...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,
1440
+ header: getCompiledMessageHeader(orderedAccounts),
1441
+ instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),
1442
+ lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),
1443
+ staticAccounts: getCompiledStaticAccounts(orderedAccounts),
1444
+ version: transaction.version
1445
+ };
1446
+ }
1447
+ function getAddressTableLookupCodec() {
1448
+ return struct(
1449
+ [
1450
+ [
1451
+ "lookupTableAddress",
1452
+ getBase58EncodedAddressCodec(
1453
+ {
1454
+ description: "The address of the address lookup table account from which instruction addresses should be looked up"
1455
+ }
1456
+ )
1457
+ ],
1458
+ [
1459
+ "writableIndices",
1460
+ array(u8(), {
1461
+ ...{
1462
+ description: "The indices of the accounts in the lookup table that should be loaded as writeable"
1463
+ } ,
1464
+ size: shortU16()
1465
+ })
1466
+ ],
1467
+ [
1468
+ "readableIndices",
1469
+ array(u8(), {
1470
+ ...{
1471
+ description: "The indices of the accounts in the lookup table that should be loaded as read-only"
1472
+ } ,
1473
+ size: shortU16()
1474
+ })
1475
+ ]
1476
+ ],
1477
+ {
1478
+ 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"
1479
+ }
1480
+ );
1481
+ }
1482
+ function getMessageHeaderCodec() {
1483
+ return struct(
1484
+ [
1485
+ [
1486
+ "numSignerAccounts",
1487
+ u8(
1488
+ {
1489
+ description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
1490
+ }
1491
+ )
1492
+ ],
1493
+ [
1494
+ "numReadonlySignerAccounts",
1495
+ u8(
1496
+ {
1497
+ 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"
1498
+ }
1499
+ )
1500
+ ],
1501
+ [
1502
+ "numReadonlyNonSignerAccounts",
1503
+ u8(
1504
+ {
1505
+ description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
1506
+ }
1507
+ )
1508
+ ]
1509
+ ],
1510
+ {
1511
+ description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
1512
+ }
1513
+ );
1514
+ }
1515
+ function getInstructionCodec() {
1516
+ return mapSerializer(
1517
+ struct([
1518
+ [
1519
+ "programAddressIndex",
1520
+ u8(
1521
+ {
1522
+ description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
1523
+ }
1524
+ )
1525
+ ],
1526
+ [
1527
+ "accountIndices",
1528
+ array(
1529
+ u8({
1530
+ description: "The index of an account, according to the well-ordered accounts list for this transaction"
1531
+ }),
1532
+ {
1533
+ 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" ,
1534
+ size: shortU16()
1535
+ }
1536
+ )
1537
+ ],
1538
+ [
1539
+ "data",
1540
+ bytes({
1541
+ description: "An optional buffer of data passed to the instruction" ,
1542
+ size: shortU16()
1543
+ })
1544
+ ]
1545
+ ]),
1546
+ (value) => {
1547
+ if (value.accountIndices !== void 0 && value.data !== void 0) {
1548
+ return value;
1549
+ }
1550
+ return {
1551
+ ...value,
1552
+ accountIndices: value.accountIndices ?? [],
1553
+ data: value.data ?? new Uint8Array(0)
1554
+ };
1555
+ },
1556
+ (value) => {
1557
+ if (value.accountIndices.length && value.data.byteLength) {
1558
+ return value;
1559
+ }
1560
+ const { accountIndices, data, ...rest } = value;
1561
+ return {
1562
+ ...rest,
1563
+ ...accountIndices.length ? { accountIndices } : null,
1564
+ ...data.byteLength ? { data } : null
1565
+ };
1566
+ }
1567
+ );
1568
+ }
1569
+ function getError(type, name) {
1570
+ const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
1571
+ return new Error(
1572
+ `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}`
1573
+ );
1574
+ }
1575
+ function getUnimplementedDecoder(name) {
1576
+ return () => {
1577
+ throw getError("decoder", name);
1578
+ };
1579
+ }
1580
+ var VERSION_FLAG_MASK = 128;
1581
+ var BASE_CONFIG = {
1582
+ description: "A single byte that encodes the version of the transaction" ,
1583
+ fixedSize: null,
1584
+ maxSize: 1
1585
+ };
1586
+ function deserialize(bytes3, offset = 0) {
1587
+ const firstByte = bytes3[offset];
1588
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
1589
+ return ["legacy", offset];
1590
+ } else {
1591
+ const version = firstByte ^ VERSION_FLAG_MASK;
1592
+ return [version, offset + 1];
1593
+ }
1594
+ }
1595
+ function serialize(value) {
1596
+ if (value === "legacy") {
1597
+ return new Uint8Array();
1598
+ }
1599
+ if (value < 0 || value > 127) {
1600
+ throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
1601
+ }
1602
+ return new Uint8Array([value | VERSION_FLAG_MASK]);
1603
+ }
1604
+ function getTransactionVersionCodec() {
1605
+ return {
1606
+ ...BASE_CONFIG,
1607
+ deserialize,
1608
+ serialize
1609
+ };
1610
+ }
1611
+ var BASE_CONFIG2 = {
1612
+ description: "The wire format of a Solana transaction message" ,
1613
+ fixedSize: null,
1614
+ maxSize: null
1615
+ };
1616
+ function serialize2(compiledMessage) {
1617
+ if (compiledMessage.version === "legacy") {
1618
+ return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
1619
+ } else {
1620
+ return mapSerializer(
1621
+ struct([
1622
+ ...getPreludeStructSerializerTuple(),
1623
+ ["addressTableLookups", getAddressTableLookupsSerializer()]
1624
+ ]),
1625
+ (value) => {
1626
+ if (value.version === "legacy") {
1627
+ return value;
1628
+ }
1629
+ return {
1630
+ ...value,
1631
+ addressTableLookups: value.addressTableLookups ?? []
1632
+ };
1633
+ }
1634
+ ).serialize(compiledMessage);
1635
+ }
1636
+ }
1637
+ function getPreludeStructSerializerTuple() {
1638
+ return [
1639
+ ["version", getTransactionVersionCodec()],
1640
+ ["header", getMessageHeaderCodec()],
1641
+ [
1642
+ "staticAccounts",
1643
+ array(getBase58EncodedAddressCodec(), {
1644
+ description: "A compact-array of static account addresses belonging to this transaction" ,
1645
+ size: shortU16()
1646
+ })
1647
+ ],
1648
+ [
1649
+ "lifetimeToken",
1650
+ string({
1651
+ description: "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" ,
1652
+ encoding: base58,
1653
+ size: 32
1654
+ })
1655
+ ],
1656
+ [
1657
+ "instructions",
1658
+ array(getInstructionCodec(), {
1659
+ description: "A compact-array of instructions belonging to this transaction" ,
1660
+ size: shortU16()
1661
+ })
1662
+ ]
1663
+ ];
1664
+ }
1665
+ function getAddressTableLookupsSerializer() {
1666
+ return array(getAddressTableLookupCodec(), {
1667
+ ...{ description: "A compact array of address table lookups belonging to this transaction" } ,
1668
+ size: shortU16()
1669
+ });
1670
+ }
1671
+ function getCompiledMessageEncoder() {
1672
+ return {
1673
+ ...BASE_CONFIG2,
1674
+ deserialize: getUnimplementedDecoder("CompiledMessage"),
1675
+ serialize: serialize2
1676
+ };
1677
+ }
1678
+ async function getCompiledMessageSignature(message, secretKey) {
1679
+ const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
1680
+ const signature = await signBytes(secretKey, wireMessageBytes);
1681
+ return signature;
1682
+ }
1683
+ async function signTransaction(keyPairs, transaction) {
1684
+ const compiledMessage = compileMessage(transaction);
1685
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
1686
+ const publicKeySignaturePairs = await Promise.all(
1687
+ keyPairs.map(
1688
+ (keyPair) => Promise.all([
1689
+ getAddressFromPublicKey(keyPair.publicKey),
1690
+ getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
1691
+ ])
1692
+ )
1693
+ );
1694
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
1695
+ nextSignatures[signerPublicKey] = signature;
1696
+ }
1697
+ const out = {
1698
+ ...transaction,
1699
+ signatures: nextSignatures
1700
+ };
1701
+ Object.freeze(out);
1702
+ return out;
1703
+ }
1704
+ function getCompiledTransaction(transaction) {
1705
+ const compiledMessage = compileMessage(transaction);
1706
+ let signatures;
1707
+ if ("signatures" in transaction) {
1708
+ signatures = [];
1709
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
1710
+ signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
1711
+ }
1712
+ } else {
1713
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
1714
+ }
1715
+ return {
1716
+ compiledMessage,
1717
+ signatures
1718
+ };
1719
+ }
1720
+ var BASE_CONFIG3 = {
1721
+ description: "The wire format of a Solana transaction" ,
1722
+ fixedSize: null,
1723
+ maxSize: null
1724
+ };
1725
+ function serialize3(transaction) {
1726
+ const compiledTransaction = getCompiledTransaction(transaction);
1727
+ return struct([
1728
+ [
1729
+ "signatures",
1730
+ array(bytes({ size: 64 }), {
1731
+ ...{ description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } ,
1732
+ size: shortU16()
1733
+ })
1734
+ ],
1735
+ ["compiledMessage", getCompiledMessageEncoder()]
1736
+ ]).serialize(compiledTransaction);
1737
+ }
1738
+ function getTransactionEncoder() {
1739
+ return {
1740
+ ...BASE_CONFIG3,
1741
+ deserialize: getUnimplementedDecoder("CompiledMessage"),
1742
+ serialize: serialize3
1743
+ };
1744
+ }
1745
+ function getBase64EncodedWireTransaction(transaction) {
1746
+ const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
1747
+ {
1748
+ return btoa(String.fromCharCode(...wireTransactionBytes));
205
1749
  }
206
1750
  }
207
1751
 
@@ -236,9 +1780,246 @@ this.globalThis.solanaWeb3 = (function (exports) {
236
1780
  return visitNode(params, [], onIntegerOverflow);
237
1781
  }
238
1782
  var KEYPATH_WILDCARD = {};
239
- var ALLOWED_NUMERIC_KEYPATHS = {
240
- getInflationReward: [[KEYPATH_WILDCARD, "commission"]]
241
- };
1783
+ var memoizedNotificationKeypaths;
1784
+ var memoizedResponseKeypaths;
1785
+ function getAllowedNumericKeypathsForNotification() {
1786
+ if (!memoizedNotificationKeypaths) {
1787
+ memoizedNotificationKeypaths = {};
1788
+ }
1789
+ return memoizedNotificationKeypaths;
1790
+ }
1791
+ function getAllowedNumericKeypathsForResponse() {
1792
+ if (!memoizedResponseKeypaths) {
1793
+ const jsonParsedTokenAccountsConfigs = [
1794
+ // parsed Token/Token22 token account
1795
+ ["data", "parsed", "info", "tokenAmount", "decimals"],
1796
+ ["data", "parsed", "info", "tokenAmount", "uiAmount"],
1797
+ ["data", "parsed", "info", "rentExemptReserve", "decimals"],
1798
+ ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
1799
+ ["data", "parsed", "info", "delegatedAmount", "decimals"],
1800
+ ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
1801
+ [
1802
+ "data",
1803
+ "parsed",
1804
+ "info",
1805
+ "extensions",
1806
+ KEYPATH_WILDCARD,
1807
+ "state",
1808
+ "olderTransferFee",
1809
+ "transferFeeBasisPoints"
1810
+ ],
1811
+ [
1812
+ "data",
1813
+ "parsed",
1814
+ "info",
1815
+ "extensions",
1816
+ KEYPATH_WILDCARD,
1817
+ "state",
1818
+ "newerTransferFee",
1819
+ "transferFeeBasisPoints"
1820
+ ],
1821
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
1822
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
1823
+ ];
1824
+ const jsonParsedAccountsConfigs = [
1825
+ ...jsonParsedTokenAccountsConfigs,
1826
+ // parsed AddressTableLookup account
1827
+ ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
1828
+ // parsed Config account
1829
+ ["data", "parsed", "info", "slashPenalty"],
1830
+ ["data", "parsed", "info", "warmupCooldownRate"],
1831
+ // parsed Token/Token22 mint account
1832
+ ["data", "parsed", "info", "decimals"],
1833
+ // parsed Token/Token22 multisig account
1834
+ ["data", "parsed", "info", "numRequiredSigners"],
1835
+ ["data", "parsed", "info", "numValidSigners"],
1836
+ // parsed Stake account
1837
+ ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
1838
+ // parsed Sysvar rent account
1839
+ ["data", "parsed", "info", "exemptionThreshold"],
1840
+ ["data", "parsed", "info", "burnPercent"],
1841
+ // parsed Vote account
1842
+ ["data", "parsed", "info", "commission"],
1843
+ ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
1844
+ ];
1845
+ memoizedResponseKeypaths = {
1846
+ getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
1847
+ getBlock: [
1848
+ ["blockTime"],
1849
+ ["transactions", KEYPATH_WILDCARD, "meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1850
+ [
1851
+ "transactions",
1852
+ KEYPATH_WILDCARD,
1853
+ "meta",
1854
+ "preTokenBalances",
1855
+ KEYPATH_WILDCARD,
1856
+ "uiTokenAmount",
1857
+ "decimals"
1858
+ ],
1859
+ ["transactions", KEYPATH_WILDCARD, "meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1860
+ [
1861
+ "transactions",
1862
+ KEYPATH_WILDCARD,
1863
+ "meta",
1864
+ "postTokenBalances",
1865
+ KEYPATH_WILDCARD,
1866
+ "uiTokenAmount",
1867
+ "decimals"
1868
+ ],
1869
+ ["transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
1870
+ ["transactions", KEYPATH_WILDCARD, "meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
1871
+ [
1872
+ "transactions",
1873
+ KEYPATH_WILDCARD,
1874
+ "meta",
1875
+ "innerInstructions",
1876
+ KEYPATH_WILDCARD,
1877
+ "instructions",
1878
+ KEYPATH_WILDCARD,
1879
+ "programIdIndex"
1880
+ ],
1881
+ [
1882
+ "transactions",
1883
+ KEYPATH_WILDCARD,
1884
+ "meta",
1885
+ "innerInstructions",
1886
+ KEYPATH_WILDCARD,
1887
+ "instructions",
1888
+ KEYPATH_WILDCARD,
1889
+ "accounts",
1890
+ KEYPATH_WILDCARD
1891
+ ],
1892
+ [
1893
+ "transactions",
1894
+ KEYPATH_WILDCARD,
1895
+ "transaction",
1896
+ "message",
1897
+ "addressTableLookups",
1898
+ KEYPATH_WILDCARD,
1899
+ "writableIndexes",
1900
+ KEYPATH_WILDCARD
1901
+ ],
1902
+ [
1903
+ "transactions",
1904
+ KEYPATH_WILDCARD,
1905
+ "transaction",
1906
+ "message",
1907
+ "addressTableLookups",
1908
+ KEYPATH_WILDCARD,
1909
+ "readonlyIndexes",
1910
+ KEYPATH_WILDCARD
1911
+ ],
1912
+ [
1913
+ "transactions",
1914
+ KEYPATH_WILDCARD,
1915
+ "transaction",
1916
+ "message",
1917
+ "instructions",
1918
+ KEYPATH_WILDCARD,
1919
+ "programIdIndex"
1920
+ ],
1921
+ [
1922
+ "transactions",
1923
+ KEYPATH_WILDCARD,
1924
+ "transaction",
1925
+ "message",
1926
+ "instructions",
1927
+ KEYPATH_WILDCARD,
1928
+ "accounts",
1929
+ KEYPATH_WILDCARD
1930
+ ],
1931
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numReadonlySignedAccounts"],
1932
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numReadonlyUnsignedAccounts"],
1933
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numRequiredSignatures"],
1934
+ ["rewards", KEYPATH_WILDCARD, "commission"]
1935
+ ],
1936
+ getBlockTime: [[]],
1937
+ getClusterNodes: [
1938
+ [KEYPATH_WILDCARD, "featureSet"],
1939
+ [KEYPATH_WILDCARD, "shredVersion"]
1940
+ ],
1941
+ getInflationGovernor: [["initial"], ["foundation"], ["foundationTerm"], ["taper"], ["terminal"]],
1942
+ getInflationRate: [["foundation"], ["total"], ["validator"]],
1943
+ getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
1944
+ getMultipleAccounts: jsonParsedAccountsConfigs.map((c) => ["value", KEYPATH_WILDCARD, ...c]),
1945
+ getProgramAccounts: jsonParsedAccountsConfigs.flatMap((c) => [
1946
+ ["value", KEYPATH_WILDCARD, "account", ...c],
1947
+ [KEYPATH_WILDCARD, "account", ...c]
1948
+ ]),
1949
+ getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
1950
+ getTokenAccountBalance: [
1951
+ ["value", "decimals"],
1952
+ ["value", "uiAmount"]
1953
+ ],
1954
+ getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map((c) => [
1955
+ "value",
1956
+ KEYPATH_WILDCARD,
1957
+ "account",
1958
+ ...c
1959
+ ]),
1960
+ getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map((c) => [
1961
+ "value",
1962
+ KEYPATH_WILDCARD,
1963
+ "account",
1964
+ ...c
1965
+ ]),
1966
+ getTokenLargestAccounts: [
1967
+ ["value", KEYPATH_WILDCARD, "decimals"],
1968
+ ["value", KEYPATH_WILDCARD, "uiAmount"]
1969
+ ],
1970
+ getTokenSupply: [
1971
+ ["value", "decimals"],
1972
+ ["value", "uiAmount"]
1973
+ ],
1974
+ getTransaction: [
1975
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1976
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
1977
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1978
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
1979
+ ["meta", "rewards", KEYPATH_WILDCARD, "commission"],
1980
+ ["meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
1981
+ ["meta", "innerInstructions", KEYPATH_WILDCARD, "instructions", KEYPATH_WILDCARD, "programIdIndex"],
1982
+ [
1983
+ "meta",
1984
+ "innerInstructions",
1985
+ KEYPATH_WILDCARD,
1986
+ "instructions",
1987
+ KEYPATH_WILDCARD,
1988
+ "accounts",
1989
+ KEYPATH_WILDCARD
1990
+ ],
1991
+ [
1992
+ "transaction",
1993
+ "message",
1994
+ "addressTableLookups",
1995
+ KEYPATH_WILDCARD,
1996
+ "writableIndexes",
1997
+ KEYPATH_WILDCARD
1998
+ ],
1999
+ [
2000
+ "transaction",
2001
+ "message",
2002
+ "addressTableLookups",
2003
+ KEYPATH_WILDCARD,
2004
+ "readonlyIndexes",
2005
+ KEYPATH_WILDCARD
2006
+ ],
2007
+ ["transaction", "message", "instructions", KEYPATH_WILDCARD, "programIdIndex"],
2008
+ ["transaction", "message", "instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
2009
+ ["transaction", "message", "header", "numReadonlySignedAccounts"],
2010
+ ["transaction", "message", "header", "numReadonlyUnsignedAccounts"],
2011
+ ["transaction", "message", "header", "numRequiredSignatures"]
2012
+ ],
2013
+ getVersion: [["feature-set"]],
2014
+ getVoteAccounts: [
2015
+ ["current", KEYPATH_WILDCARD, "commission"],
2016
+ ["delinquent", KEYPATH_WILDCARD, "commission"]
2017
+ ],
2018
+ simulateTransaction: jsonParsedAccountsConfigs.map((c) => ["value", "accounts", KEYPATH_WILDCARD, ...c])
2019
+ };
2020
+ }
2021
+ return memoizedResponseKeypaths;
2022
+ }
242
2023
  function getNextAllowedKeypaths(keyPaths, property) {
243
2024
  return keyPaths.filter((keyPath) => keyPath[0] === KEYPATH_WILDCARD && typeof property === "number" || keyPath[0] === property).map((keyPath) => keyPath.slice(1));
244
2025
  }
@@ -257,14 +2038,19 @@ this.globalThis.solanaWeb3 = (function (exports) {
257
2038
  return out;
258
2039
  } else if (typeof value === "number" && // The presence of an allowed keypath on the route to this value implies it's allowlisted;
259
2040
  // Upcast the value to `bigint` unless an allowed keypath is present.
260
- allowedKeypaths.length === 0) {
2041
+ allowedKeypaths.length === 0 && // Only try to upcast an Integer to `bigint`
2042
+ Number.isInteger(value)) {
261
2043
  return BigInt(value);
262
2044
  } else {
263
2045
  return value;
264
2046
  }
265
2047
  }
266
2048
  function patchResponseForSolanaLabsRpc(rawResponse, methodName) {
267
- const allowedKeypaths = methodName ? ALLOWED_NUMERIC_KEYPATHS[methodName] : void 0;
2049
+ const allowedKeypaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : void 0;
2050
+ return visitNode2(rawResponse, allowedKeypaths ?? []);
2051
+ }
2052
+ function patchResponseForSolanaLabsRpcSubscriptions(rawResponse, methodName) {
2053
+ const allowedKeypaths = methodName ? getAllowedNumericKeypathsForNotification()[methodName] : void 0;
268
2054
  return visitNode2(rawResponse, allowedKeypaths ?? []);
269
2055
  }
270
2056
  function createSolanaRpcApi(config) {
@@ -293,46 +2079,33 @@ this.globalThis.solanaWeb3 = (function (exports) {
293
2079
  }
294
2080
  });
295
2081
  }
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";
2082
+ function createSolanaRpcSubscriptionsApi(config) {
2083
+ return new Proxy({}, {
2084
+ defineProperty() {
2085
+ return false;
2086
+ },
2087
+ deleteProperty() {
2088
+ return false;
2089
+ },
2090
+ get(...args) {
2091
+ const [_, p] = args;
2092
+ const notificationName = p.toString();
2093
+ return function(...rawParams) {
2094
+ const handleIntegerOverflow = config?.onIntegerOverflow;
2095
+ const params = patchParamsForSolanaLabsRpc(
2096
+ rawParams,
2097
+ handleIntegerOverflow ? (keyPath, value) => handleIntegerOverflow(notificationName, keyPath, value) : void 0
2098
+ );
2099
+ return {
2100
+ params,
2101
+ responseProcessor: (rawResponse) => patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName),
2102
+ subscribeMethodName: notificationName.replace(/Notifications$/, "Subscribe"),
2103
+ unsubscribeMethodName: notificationName.replace(/Notifications$/, "Unsubscribe")
2104
+ };
2105
+ };
316
2106
  }
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
- };
2107
+ });
2108
+ }
336
2109
 
337
2110
  // ../rpc-transport/dist/index.browser.js
338
2111
  init_env_shim();
@@ -399,6 +2172,101 @@ this.globalThis.solanaWeb3 = (function (exports) {
399
2172
  function createJsonRpc(rpcConfig) {
400
2173
  return makeProxy(rpcConfig);
401
2174
  }
2175
+ function registerIterableCleanup(iterable, cleanupFn) {
2176
+ (async () => {
2177
+ try {
2178
+ for await (const _ of iterable)
2179
+ ;
2180
+ } catch {
2181
+ } finally {
2182
+ cleanupFn();
2183
+ }
2184
+ })();
2185
+ }
2186
+ function createPendingRpcSubscription(rpcConfig, { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }) {
2187
+ return {
2188
+ async subscribe({ abortSignal }) {
2189
+ abortSignal.throwIfAborted();
2190
+ let subscriptionId;
2191
+ function handleCleanup() {
2192
+ if (subscriptionId !== void 0) {
2193
+ const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);
2194
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {
2195
+ connectionAbortController.abort();
2196
+ });
2197
+ } else {
2198
+ connectionAbortController.abort();
2199
+ }
2200
+ }
2201
+ abortSignal.addEventListener("abort", handleCleanup);
2202
+ const connectionAbortController = new AbortController();
2203
+ const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);
2204
+ const connection = await rpcConfig.transport({
2205
+ payload: subscribeMessage,
2206
+ signal: connectionAbortController.signal
2207
+ });
2208
+ function handleConnectionCleanup() {
2209
+ abortSignal.removeEventListener("abort", handleCleanup);
2210
+ }
2211
+ registerIterableCleanup(connection, handleConnectionCleanup);
2212
+ for await (const message of connection) {
2213
+ if ("id" in message && message.id === subscribeMessage.id) {
2214
+ if ("error" in message) {
2215
+ throw new SolanaJsonRpcError(message.error);
2216
+ } else {
2217
+ subscriptionId = message.result;
2218
+ break;
2219
+ }
2220
+ }
2221
+ }
2222
+ if (subscriptionId == null) {
2223
+ throw new Error("Failed to obtain a subscription id from the server");
2224
+ }
2225
+ return {
2226
+ async *[Symbol.asyncIterator]() {
2227
+ for await (const message of connection) {
2228
+ if (!("params" in message) || message.params.subscription !== subscriptionId) {
2229
+ continue;
2230
+ }
2231
+ const notification = message.params.result;
2232
+ yield responseProcessor ? responseProcessor(notification) : notification;
2233
+ }
2234
+ }
2235
+ };
2236
+ }
2237
+ };
2238
+ }
2239
+ function makeProxy2(rpcConfig) {
2240
+ return new Proxy(rpcConfig.api, {
2241
+ defineProperty() {
2242
+ return false;
2243
+ },
2244
+ deleteProperty() {
2245
+ return false;
2246
+ },
2247
+ get(target, p, receiver) {
2248
+ return function(...rawParams) {
2249
+ const methodName = p.toString();
2250
+ const createRpcSubscription = Reflect.get(target, methodName, receiver);
2251
+ if (p.toString().endsWith("Notifications") === false && !createRpcSubscription) {
2252
+ throw new Error(
2253
+ "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."
2254
+ );
2255
+ }
2256
+ const newRequest = createRpcSubscription ? createRpcSubscription(...rawParams) : {
2257
+ params: rawParams,
2258
+ subscribeMethodName: methodName.replace(/Notifications$/, "Subscribe"),
2259
+ unsubscribeMethodName: methodName.replace(/Notifications$/, "Unsubscribe")
2260
+ };
2261
+ return createPendingRpcSubscription(rpcConfig, newRequest);
2262
+ };
2263
+ }
2264
+ });
2265
+ }
2266
+ function createJsonSubscriptionRpc(rpcConfig) {
2267
+ return makeProxy2(rpcConfig);
2268
+ }
2269
+ var e = globalThis.fetch;
402
2270
  var SolanaHttpError = class extends Error {
403
2271
  constructor(details) {
404
2272
  super(`HTTP error (${details.statusCode}): ${details.message}`);
@@ -457,7 +2325,6 @@ this.globalThis.solanaWeb3 = (function (exports) {
457
2325
  }
458
2326
  return out;
459
2327
  }
460
- var e = globalThis.fetch;
461
2328
  function createHttpTransport({ httpAgentNodeOnly, headers, url }) {
462
2329
  if (headers) {
463
2330
  assertIsAllowedHttpRequestHeaders(headers);
@@ -497,6 +2364,206 @@ this.globalThis.solanaWeb3 = (function (exports) {
497
2364
  return await response.json();
498
2365
  };
499
2366
  }
2367
+ var e2 = globalThis.WebSocket;
2368
+ async function createWebSocketConnection({
2369
+ sendBufferHighWatermark,
2370
+ signal,
2371
+ url
2372
+ }) {
2373
+ return new Promise((resolve, reject) => {
2374
+ signal.addEventListener("abort", handleAbort, { once: true });
2375
+ const iteratorState = /* @__PURE__ */ new Map();
2376
+ function handleAbort() {
2377
+ if (webSocket.readyState !== e2.CLOSED && webSocket.readyState !== e2.CLOSING) {
2378
+ webSocket.close(1e3);
2379
+ }
2380
+ }
2381
+ function handleClose(ev) {
2382
+ bufferDrainWatcher?.onCancel();
2383
+ signal.removeEventListener("abort", handleAbort);
2384
+ webSocket.removeEventListener("close", handleClose);
2385
+ webSocket.removeEventListener("error", handleError);
2386
+ webSocket.removeEventListener("open", handleOpen);
2387
+ webSocket.removeEventListener("message", handleMessage);
2388
+ iteratorState.forEach((state, iteratorKey) => {
2389
+ if (state.__hasPolled) {
2390
+ const { onError } = state;
2391
+ iteratorState.delete(iteratorKey);
2392
+ onError(ev);
2393
+ } else {
2394
+ iteratorState.delete(iteratorKey);
2395
+ }
2396
+ });
2397
+ }
2398
+ function handleError(ev) {
2399
+ if (!hasConnected) {
2400
+ reject(
2401
+ // TODO: Coded error
2402
+ new Error("WebSocket failed to connect", { cause: ev })
2403
+ );
2404
+ }
2405
+ }
2406
+ let hasConnected = false;
2407
+ let bufferDrainWatcher;
2408
+ function handleOpen() {
2409
+ hasConnected = true;
2410
+ resolve({
2411
+ async send(payload) {
2412
+ const message = JSON.stringify(payload);
2413
+ if (!bufferDrainWatcher && webSocket.readyState === e2.OPEN && webSocket.bufferedAmount > sendBufferHighWatermark) {
2414
+ let onCancel;
2415
+ const promise = new Promise((resolve2, reject2) => {
2416
+ const intervalId = setInterval(() => {
2417
+ if (webSocket.readyState !== e2.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
2418
+ clearInterval(intervalId);
2419
+ bufferDrainWatcher = void 0;
2420
+ resolve2();
2421
+ }
2422
+ }, 16);
2423
+ onCancel = () => {
2424
+ bufferDrainWatcher = void 0;
2425
+ clearInterval(intervalId);
2426
+ reject2(
2427
+ // TODO: Coded error
2428
+ new Error("WebSocket was closed before payload could be sent")
2429
+ );
2430
+ };
2431
+ });
2432
+ bufferDrainWatcher = {
2433
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2434
+ // @ts-ignore
2435
+ onCancel,
2436
+ promise
2437
+ };
2438
+ }
2439
+ if (bufferDrainWatcher) {
2440
+ await bufferDrainWatcher.promise;
2441
+ }
2442
+ webSocket.send(message);
2443
+ },
2444
+ async *[Symbol.asyncIterator]() {
2445
+ const iteratorKey = Symbol();
2446
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
2447
+ try {
2448
+ while (true) {
2449
+ const state = iteratorState.get(iteratorKey);
2450
+ if (!state) {
2451
+ throw new Error("Invariant: WebSocket message iterator is missing state storage");
2452
+ }
2453
+ if (state.__hasPolled) {
2454
+ throw new Error(
2455
+ "Invariant: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise"
2456
+ );
2457
+ }
2458
+ const queuedMessages = state.queuedMessages;
2459
+ if (queuedMessages.length) {
2460
+ state.queuedMessages = [];
2461
+ yield* queuedMessages;
2462
+ } else {
2463
+ try {
2464
+ yield await new Promise((onMessage, onError) => {
2465
+ iteratorState.set(iteratorKey, {
2466
+ __hasPolled: true,
2467
+ onError,
2468
+ onMessage
2469
+ });
2470
+ });
2471
+ } catch (e3) {
2472
+ if (e3 !== null && typeof e3 === "object" && "type" in e3 && e3.type === "close" && "wasClean" in e3 && e3.wasClean) {
2473
+ return;
2474
+ } else {
2475
+ throw new Error("WebSocket connection closed", { cause: e3 });
2476
+ }
2477
+ }
2478
+ }
2479
+ }
2480
+ } finally {
2481
+ iteratorState.delete(iteratorKey);
2482
+ }
2483
+ }
2484
+ });
2485
+ }
2486
+ function handleMessage({ data }) {
2487
+ const message = JSON.parse(data);
2488
+ iteratorState.forEach((state, iteratorKey) => {
2489
+ if (state.__hasPolled) {
2490
+ const { onMessage } = state;
2491
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
2492
+ onMessage(message);
2493
+ } else {
2494
+ state.queuedMessages.push(message);
2495
+ }
2496
+ });
2497
+ }
2498
+ const webSocket = new e2(url);
2499
+ webSocket.addEventListener("close", handleClose);
2500
+ webSocket.addEventListener("error", handleError);
2501
+ webSocket.addEventListener("open", handleOpen);
2502
+ webSocket.addEventListener("message", handleMessage);
2503
+ });
2504
+ }
2505
+ function createWebSocketTransport({ sendBufferHighWatermark, url }) {
2506
+ if (/^wss?:/i.test(url) === false) {
2507
+ const protocolMatch = url.match(/^([^:]+):/);
2508
+ throw new DOMException(
2509
+ 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.`
2510
+ );
2511
+ }
2512
+ return async function sendWebSocketMessage({ payload, signal }) {
2513
+ signal?.throwIfAborted();
2514
+ const connection = await createWebSocketConnection({
2515
+ sendBufferHighWatermark,
2516
+ signal,
2517
+ url
2518
+ });
2519
+ signal?.throwIfAborted();
2520
+ await connection.send(payload);
2521
+ return {
2522
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
2523
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection)
2524
+ };
2525
+ };
2526
+ }
2527
+
2528
+ // src/rpc-default-config.ts
2529
+ init_env_shim();
2530
+
2531
+ // src/rpc-integer-overflow-error.ts
2532
+ init_env_shim();
2533
+ var SolanaJsonRpcIntegerOverflowError = class extends Error {
2534
+ constructor(methodName, keyPath, value) {
2535
+ const argPosition = (typeof keyPath[0] === "number" ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;
2536
+ let ordinal = "";
2537
+ const lastDigit = argPosition % 10;
2538
+ const lastTwoDigits = argPosition % 100;
2539
+ if (lastDigit == 1 && lastTwoDigits != 11) {
2540
+ ordinal = argPosition + "st";
2541
+ } else if (lastDigit == 2 && lastTwoDigits != 12) {
2542
+ ordinal = argPosition + "nd";
2543
+ } else if (lastDigit == 3 && lastTwoDigits != 13) {
2544
+ ordinal = argPosition + "rd";
2545
+ } else {
2546
+ ordinal = argPosition + "th";
2547
+ }
2548
+ const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : null;
2549
+ super(
2550
+ `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\`.`
2551
+ );
2552
+ this.keyPath = keyPath;
2553
+ this.methodName = methodName;
2554
+ this.value = value;
2555
+ }
2556
+ get name() {
2557
+ return "SolanaJsonRpcIntegerOverflowError";
2558
+ }
2559
+ };
2560
+
2561
+ // src/rpc-default-config.ts
2562
+ var DEFAULT_RPC_CONFIG = {
2563
+ onIntegerOverflow(methodName, keyPath, value) {
2564
+ throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);
2565
+ }
2566
+ };
500
2567
 
501
2568
  // src/rpc.ts
502
2569
  function createSolanaRpc(config) {
@@ -505,9 +2572,89 @@ this.globalThis.solanaWeb3 = (function (exports) {
505
2572
  api: createSolanaRpcApi(DEFAULT_RPC_CONFIG)
506
2573
  });
507
2574
  }
2575
+ function createSolanaRpcSubscriptions(config) {
2576
+ return createJsonSubscriptionRpc({
2577
+ ...config,
2578
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
2579
+ });
2580
+ }
508
2581
 
509
2582
  // src/rpc-transport.ts
510
2583
  init_env_shim();
2584
+
2585
+ // ../functional/dist/index.browser.js
2586
+ init_env_shim();
2587
+ function pipe(init, ...fns) {
2588
+ return fns.reduce((acc, fn) => fn(acc), init);
2589
+ }
2590
+
2591
+ // src/rpc-request-coalescer.ts
2592
+ init_env_shim();
2593
+ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
2594
+ let coalescedRequestsByDeduplicationKey;
2595
+ return async function makeCoalescedHttpRequest(config) {
2596
+ const { payload, signal } = config;
2597
+ const deduplicationKey = getDeduplicationKey(payload);
2598
+ if (deduplicationKey === void 0) {
2599
+ return await transport(config);
2600
+ }
2601
+ if (!coalescedRequestsByDeduplicationKey) {
2602
+ Promise.resolve().then(() => {
2603
+ coalescedRequestsByDeduplicationKey = void 0;
2604
+ });
2605
+ coalescedRequestsByDeduplicationKey = {};
2606
+ }
2607
+ if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {
2608
+ const abortController = new AbortController();
2609
+ coalescedRequestsByDeduplicationKey[deduplicationKey] = {
2610
+ abortController,
2611
+ numConsumers: 0,
2612
+ responsePromise: transport({
2613
+ ...config,
2614
+ signal: abortController.signal
2615
+ })
2616
+ };
2617
+ }
2618
+ const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];
2619
+ coalescedRequest.numConsumers++;
2620
+ if (signal) {
2621
+ const responsePromise = coalescedRequest.responsePromise;
2622
+ return await new Promise((resolve, reject) => {
2623
+ const handleAbort = (e3) => {
2624
+ signal.removeEventListener("abort", handleAbort);
2625
+ coalescedRequest.numConsumers -= 1;
2626
+ if (coalescedRequest.numConsumers === 0) {
2627
+ const abortController = coalescedRequest.abortController;
2628
+ abortController.abort();
2629
+ }
2630
+ const abortError = new DOMException(e3.target.reason, "AbortError");
2631
+ reject(abortError);
2632
+ };
2633
+ signal.addEventListener("abort", handleAbort);
2634
+ responsePromise.then(resolve).finally(() => {
2635
+ signal.removeEventListener("abort", handleAbort);
2636
+ });
2637
+ });
2638
+ } else {
2639
+ return await coalescedRequest.responsePromise;
2640
+ }
2641
+ };
2642
+ }
2643
+
2644
+ // src/rpc-request-deduplication.ts
2645
+ init_env_shim();
2646
+ var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
2647
+ function isJsonRpcPayload(payload) {
2648
+ if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
2649
+ return false;
2650
+ }
2651
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
2652
+ }
2653
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
2654
+ return isJsonRpcPayload(payload) ? (0, import_fast_stable_stringify.default)([payload.method, payload.params]) : void 0;
2655
+ }
2656
+
2657
+ // src/rpc-transport.ts
511
2658
  function normalizeHeaders2(headers) {
512
2659
  const out = {};
513
2660
  for (const headerName in headers) {
@@ -516,21 +2663,246 @@ this.globalThis.solanaWeb3 = (function (exports) {
516
2663
  return out;
517
2664
  }
518
2665
  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"
2666
+ return pipe(
2667
+ createHttpTransport({
2668
+ ...config,
2669
+ headers: {
2670
+ ...config.headers ? normalizeHeaders2(config.headers) : void 0,
2671
+ ...{
2672
+ // Keep these headers lowercase so they will override any user-supplied headers above.
2673
+ "solana-client": `js/${"2.0.0-development"}` ?? "UNKNOWN"
2674
+ }
2675
+ }
2676
+ }),
2677
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
2678
+ );
2679
+ }
2680
+
2681
+ // src/rpc-websocket-transport.ts
2682
+ init_env_shim();
2683
+
2684
+ // src/rpc-websocket-autopinger.ts
2685
+ init_env_shim();
2686
+ var PING_PAYLOAD = {
2687
+ jsonrpc: "2.0",
2688
+ method: "ping"
2689
+ };
2690
+ function getWebSocketTransportWithAutoping({ intervalMs, transport }) {
2691
+ const pingableConnections = /* @__PURE__ */ new Map();
2692
+ return async (...args) => {
2693
+ const connection = await transport(...args);
2694
+ let intervalId;
2695
+ function sendPing() {
2696
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);
2697
+ }
2698
+ function restartPingTimer() {
2699
+ clearInterval(intervalId);
2700
+ intervalId = setInterval(sendPing, intervalMs);
2701
+ }
2702
+ if (pingableConnections.has(connection) === false) {
2703
+ pingableConnections.set(connection, {
2704
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
2705
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (...args2) => {
2706
+ restartPingTimer();
2707
+ return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args2);
2708
+ }
2709
+ });
2710
+ (async () => {
2711
+ try {
2712
+ for await (const _ of connection) {
2713
+ restartPingTimer();
2714
+ }
2715
+ } catch {
2716
+ } finally {
2717
+ pingableConnections.delete(connection);
2718
+ clearInterval(intervalId);
2719
+ if (handleOffline) {
2720
+ globalThis.window.removeEventListener("offline", handleOffline);
2721
+ }
2722
+ if (handleOnline) {
2723
+ globalThis.window.removeEventListener("online", handleOnline);
2724
+ }
2725
+ }
2726
+ })();
2727
+ if (globalThis.navigator.onLine) {
2728
+ restartPingTimer();
2729
+ }
2730
+ let handleOffline;
2731
+ let handleOnline;
2732
+ {
2733
+ handleOffline = () => {
2734
+ clearInterval(intervalId);
2735
+ };
2736
+ handleOnline = () => {
2737
+ sendPing();
2738
+ restartPingTimer();
2739
+ };
2740
+ globalThis.window.addEventListener("offline", handleOffline);
2741
+ globalThis.window.addEventListener("online", handleOnline);
2742
+ }
2743
+ }
2744
+ return pingableConnections.get(connection);
2745
+ };
2746
+ }
2747
+
2748
+ // src/rpc-websocket-connection-sharding.ts
2749
+ init_env_shim();
2750
+
2751
+ // src/cached-abortable-iterable.ts
2752
+ init_env_shim();
2753
+ function registerIterableCleanup2(iterable, cleanupFn) {
2754
+ (async () => {
2755
+ try {
2756
+ for await (const _ of iterable)
2757
+ ;
2758
+ } catch {
2759
+ } finally {
2760
+ cleanupFn();
2761
+ }
2762
+ })();
2763
+ }
2764
+ function getCachedAbortableIterableFactory({
2765
+ getAbortSignalFromInputArgs,
2766
+ getCacheEntryMissingError,
2767
+ getCacheKeyFromInputArgs,
2768
+ onCacheHit,
2769
+ onCreateIterable
2770
+ }) {
2771
+ const cache = /* @__PURE__ */ new Map();
2772
+ function getCacheEntryOrThrow(cacheKey) {
2773
+ const currentCacheEntry = cache.get(cacheKey);
2774
+ if (!currentCacheEntry) {
2775
+ throw getCacheEntryMissingError(cacheKey);
2776
+ }
2777
+ return currentCacheEntry;
2778
+ }
2779
+ return async (...args) => {
2780
+ const cacheKey = getCacheKeyFromInputArgs(...args);
2781
+ const signal = getAbortSignalFromInputArgs(...args);
2782
+ if (cacheKey === void 0) {
2783
+ return await onCreateIterable(signal, ...args);
2784
+ }
2785
+ const cleanup = () => {
2786
+ cache.delete(cacheKey);
2787
+ signal.removeEventListener("abort", handleAbort);
2788
+ };
2789
+ const handleAbort = () => {
2790
+ const cacheEntry = getCacheEntryOrThrow(cacheKey);
2791
+ if (cacheEntry.purgeScheduled !== true) {
2792
+ cacheEntry.purgeScheduled = true;
2793
+ globalThis.queueMicrotask(() => {
2794
+ cacheEntry.purgeScheduled = false;
2795
+ if (cacheEntry.referenceCount === 0) {
2796
+ cacheEntry.abortController.abort();
2797
+ cleanup();
2798
+ }
2799
+ });
2800
+ }
2801
+ cacheEntry.referenceCount--;
2802
+ };
2803
+ signal.addEventListener("abort", handleAbort);
2804
+ try {
2805
+ const cacheEntry = cache.get(cacheKey);
2806
+ if (!cacheEntry) {
2807
+ const singletonAbortController = new AbortController();
2808
+ const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);
2809
+ const newCacheEntry = {
2810
+ abortController: singletonAbortController,
2811
+ iterable: newIterablePromise,
2812
+ purgeScheduled: false,
2813
+ referenceCount: 1
2814
+ };
2815
+ cache.set(cacheKey, newCacheEntry);
2816
+ const newIterable = await newIterablePromise;
2817
+ registerIterableCleanup2(newIterable, cleanup);
2818
+ newCacheEntry.iterable = newIterable;
2819
+ return newIterable;
2820
+ } else {
2821
+ cacheEntry.referenceCount++;
2822
+ const iterableOrIterablePromise = cacheEntry.iterable;
2823
+ const cachedIterable = "then" in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;
2824
+ await onCacheHit(cachedIterable, ...args);
2825
+ return cachedIterable;
526
2826
  }
2827
+ } catch (e3) {
2828
+ cleanup();
2829
+ throw e3;
527
2830
  }
2831
+ };
2832
+ }
2833
+
2834
+ // src/rpc-websocket-connection-sharding.ts
2835
+ var NULL_SHARD_CACHE_KEY = Symbol(
2836
+ "Cache key to use when there is no connection sharding strategy"
2837
+ );
2838
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
2839
+ return getCachedAbortableIterableFactory({
2840
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
2841
+ getCacheEntryMissingError(shardKey) {
2842
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
2843
+ },
2844
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
2845
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
2846
+ onCreateIterable: (abortSignal, config) => transport({
2847
+ ...config,
2848
+ signal: abortSignal
2849
+ })
528
2850
  });
529
2851
  }
530
2852
 
2853
+ // src/rpc-websocket-transport.ts
2854
+ function createDefaultRpcSubscriptionsTransport(config) {
2855
+ const { getShard, intervalMs, ...rest } = config;
2856
+ return pipe(
2857
+ createWebSocketTransport({
2858
+ ...rest,
2859
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
2860
+ 131072
2861
+ }),
2862
+ (transport) => getWebSocketTransportWithAutoping({
2863
+ intervalMs: intervalMs ?? 5e3,
2864
+ transport
2865
+ }),
2866
+ (transport) => getWebSocketTransportWithConnectionSharding({
2867
+ getShard,
2868
+ transport
2869
+ })
2870
+ );
2871
+ }
2872
+
2873
+ exports.AccountRole = AccountRole;
2874
+ exports.address = address;
2875
+ exports.appendTransactionInstruction = appendTransactionInstruction;
531
2876
  exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
2877
+ exports.assertIsBlockhash = assertIsBlockhash;
2878
+ exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
2879
+ exports.createAddressWithSeed = createAddressWithSeed;
2880
+ exports.createDefaultRpcSubscriptionsTransport = createDefaultRpcSubscriptionsTransport;
532
2881
  exports.createDefaultRpcTransport = createDefaultRpcTransport;
533
2882
  exports.createSolanaRpc = createSolanaRpc;
2883
+ exports.createSolanaRpcSubscriptions = createSolanaRpcSubscriptions;
2884
+ exports.createTransaction = createTransaction;
2885
+ exports.downgradeRoleToNonSigner = downgradeRoleToNonSigner;
2886
+ exports.downgradeRoleToReadonly = downgradeRoleToReadonly;
2887
+ exports.generateKeyPair = generateKeyPair;
2888
+ exports.getAddressFromPublicKey = getAddressFromPublicKey;
2889
+ exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
2890
+ exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
2891
+ exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
2892
+ exports.getProgramDerivedAddress = getProgramDerivedAddress;
2893
+ exports.isBase58EncodedAddress = isBase58EncodedAddress;
2894
+ exports.isSignerRole = isSignerRole;
2895
+ exports.isWritableRole = isWritableRole;
2896
+ exports.mergeRoles = mergeRoles;
2897
+ exports.prependTransactionInstruction = prependTransactionInstruction;
2898
+ exports.setTransactionFeePayer = setTransactionFeePayer;
2899
+ exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
2900
+ exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
2901
+ exports.signBytes = signBytes;
2902
+ exports.signTransaction = signTransaction;
2903
+ exports.upgradeRoleToSigner = upgradeRoleToSigner;
2904
+ exports.upgradeRoleToWritable = upgradeRoleToWritable;
2905
+ exports.verifySignature = verifySignature;
534
2906
 
535
2907
  return exports;
536
2908