@solana/web3.js 2.0.0-experimental.3536b48 → 2.0.0-experimental.3690b65

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 (50) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1155 -43
  3. package/dist/index.browser.cjs +763 -8
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +746 -13
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +2617 -819
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +735 -11
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +752 -8
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +735 -13
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +76 -31
  16. package/dist/types/airdrop-confirmer.d.ts +20 -0
  17. package/dist/types/airdrop-confirmer.d.ts.map +1 -0
  18. package/dist/types/airdrop.d.ts +23 -0
  19. package/dist/types/airdrop.d.ts.map +1 -0
  20. package/dist/types/cached-abortable-iterable.d.ts +11 -0
  21. package/dist/types/cached-abortable-iterable.d.ts.map +1 -0
  22. package/dist/types/index.d.ts +8 -0
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/rpc-request-deduplication.d.ts.map +1 -1
  25. package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
  26. package/dist/types/rpc-subscription-coalescer.d.ts.map +1 -0
  27. package/dist/types/rpc-transport.d.ts.map +1 -1
  28. package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
  29. package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
  30. package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
  31. package/dist/types/rpc-websocket-connection-sharding.d.ts.map +1 -0
  32. package/dist/types/rpc-websocket-transport.d.ts +13 -0
  33. package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
  34. package/dist/types/rpc.d.ts +5 -3
  35. package/dist/types/rpc.d.ts.map +1 -1
  36. package/dist/types/send-transaction.d.ts +38 -0
  37. package/dist/types/send-transaction.d.ts.map +1 -0
  38. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +10 -0
  39. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts.map +1 -0
  40. package/dist/types/transaction-confirmation-strategy-nonce.d.ts +15 -0
  41. package/dist/types/transaction-confirmation-strategy-nonce.d.ts.map +1 -0
  42. package/dist/types/transaction-confirmation-strategy-racer.d.ts +14 -0
  43. package/dist/types/transaction-confirmation-strategy-racer.d.ts.map +1 -0
  44. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +13 -0
  45. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts.map +1 -0
  46. package/dist/types/transaction-confirmation-strategy-timeout.d.ts +8 -0
  47. package/dist/types/transaction-confirmation-strategy-timeout.d.ts.map +1 -0
  48. package/dist/types/transaction-confirmation.d.ts +37 -0
  49. package/dist/types/transaction-confirmation.d.ts.map +1 -0
  50. package/package.json +21 -18
@@ -8,7 +8,6 @@ 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;
12
11
  var __esm = (fn, res) => function __init() {
13
12
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
13
  };
@@ -31,10 +30,6 @@ this.globalThis.solanaWeb3 = (function (exports) {
31
30
  isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
32
31
  mod2
33
32
  ));
34
- var __publicField = (obj, key, value) => {
35
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
36
- return value;
37
- };
38
33
 
39
34
  // ../build-scripts/env-shim.ts
40
35
  var init_env_shim = __esm({
@@ -125,304 +120,206 @@ this.globalThis.solanaWeb3 = (function (exports) {
125
120
  // ../addresses/dist/index.browser.js
126
121
  init_env_shim();
127
122
 
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
123
+ // ../codecs-core/dist/index.browser.js
135
124
  init_env_shim();
136
- var mergeBytes = (bytesArr) => {
137
- const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);
125
+ function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
126
+ if (bytes.length - offset <= 0) {
127
+ throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);
128
+ }
129
+ }
130
+ function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
131
+ const bytesLength = bytes.length - offset;
132
+ if (bytesLength < expected) {
133
+ throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
134
+ }
135
+ }
136
+ var mergeBytes = (byteArrays) => {
137
+ const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);
138
+ if (nonEmptyByteArrays.length === 0) {
139
+ return byteArrays.length ? byteArrays[0] : new Uint8Array();
140
+ }
141
+ if (nonEmptyByteArrays.length === 1) {
142
+ return nonEmptyByteArrays[0];
143
+ }
144
+ const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);
138
145
  const result = new Uint8Array(totalLength);
139
146
  let offset = 0;
140
- bytesArr.forEach((arr) => {
147
+ nonEmptyByteArrays.forEach((arr) => {
141
148
  result.set(arr, offset);
142
149
  offset += arr.length;
143
150
  });
144
151
  return result;
145
152
  };
146
- var padBytes = (bytes2, length) => {
147
- if (bytes2.length >= length)
148
- return bytes2;
153
+ var padBytes = (bytes, length) => {
154
+ if (bytes.length >= length)
155
+ return bytes;
149
156
  const paddedBytes = new Uint8Array(length).fill(0);
150
- paddedBytes.set(bytes2);
157
+ paddedBytes.set(bytes);
151
158
  return paddedBytes;
152
159
  };
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");
160
+ var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
161
+ function combineCodec(encoder, decoder, description) {
162
+ if (encoder.fixedSize !== decoder.fixedSize) {
163
+ throw new Error(
164
+ `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
165
+ );
161
166
  }
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
+ if (encoder.maxSize !== decoder.maxSize) {
168
+ throw new Error(
169
+ `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
170
+ );
167
171
  }
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");
172
+ if (description === void 0 && encoder.description !== decoder.description) {
173
+ throw new Error(
174
+ `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`
175
+ );
174
176
  }
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
177
  return {
181
- description: description ?? `fixed(${fixedBytes}, ${serializer.description})`,
178
+ decode: decoder.decode,
179
+ description: description ?? encoder.description,
180
+ encode: encoder.encode,
181
+ fixedSize: encoder.fixedSize,
182
+ maxSize: encoder.maxSize
183
+ };
184
+ }
185
+ function fixCodecHelper(data, fixedBytes, description) {
186
+ return {
187
+ description: description ?? `fixed(${fixedBytes}, ${data.description})`,
182
188
  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
+ maxSize: fixedBytes
190
+ };
191
+ }
192
+ function fixEncoder(encoder, fixedBytes, description) {
193
+ return {
194
+ ...fixCodecHelper(encoder, fixedBytes, description),
195
+ encode: (value) => fixBytes(encoder.encode(value), fixedBytes)
196
+ };
197
+ }
198
+ function fixDecoder(decoder, fixedBytes, description) {
199
+ return {
200
+ ...fixCodecHelper(decoder, fixedBytes, description),
201
+ decode: (bytes, offset = 0) => {
202
+ assertByteArrayHasEnoughBytesForCodec("fixCodec", fixedBytes, bytes, offset);
203
+ if (offset > 0 || bytes.length > fixedBytes) {
204
+ bytes = bytes.slice(offset, offset + fixedBytes);
189
205
  }
190
- if (serializer.fixedSize !== null) {
191
- buffer = fixBytes(buffer, serializer.fixedSize);
206
+ if (decoder.fixedSize !== null) {
207
+ bytes = fixBytes(bytes, decoder.fixedSize);
192
208
  }
193
- const [value] = serializer.deserialize(buffer, 0);
209
+ const [value] = decoder.decode(bytes, 0);
194
210
  return [value, offset + fixedBytes];
195
211
  }
196
212
  };
197
213
  }
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) {
214
+ function mapEncoder(encoder, unmap) {
202
215
  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
- }
216
+ description: encoder.description,
217
+ encode: (value) => encoder.encode(unmap(value)),
218
+ fixedSize: encoder.fixedSize,
219
+ maxSize: encoder.maxSize
211
220
  };
212
221
  }
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);
222
+ function mapDecoder(decoder, map) {
235
223
  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));
224
+ decode: (bytes, offset = 0) => {
225
+ const [value, length] = decoder.decode(bytes, offset);
226
+ return [map(value, bytes, offset), length];
264
227
  },
265
- deserialize(buffer, offset = 0) {
266
- if (buffer.length === 0)
267
- return ["", 0];
268
- const bytes2 = buffer.slice(offset);
269
- let trailIndex = bytes2.findIndex((n) => n !== 0);
270
- trailIndex = trailIndex === -1 ? bytes2.length : trailIndex;
271
- const leadingZeroes = alphabet[0].repeat(trailIndex);
272
- if (trailIndex === bytes2.length)
273
- return [leadingZeroes, buffer.length];
274
- let base10Number = bytes2.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
275
- const tailChars = [];
276
- while (base10Number > 0n) {
277
- tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);
278
- base10Number /= baseBigInt;
279
- }
280
- return [leadingZeroes + tailChars.join(""), buffer.length];
281
- }
228
+ description: decoder.description,
229
+ fixedSize: decoder.fixedSize,
230
+ maxSize: decoder.maxSize
282
231
  };
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();
232
+ }
313
233
 
314
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs
234
+ // ../codecs-strings/dist/index.browser.js
315
235
  init_env_shim();
316
- var Endian;
317
- (function(Endian2) {
318
- Endian2["Little"] = "le";
319
- Endian2["Big"] = "be";
320
- })(Endian || (Endian = {}));
321
236
 
322
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.9/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs
237
+ // ../codecs-numbers/dist/index.browser.js
323
238
  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");
239
+ function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
240
+ if (value < min || value > max) {
241
+ throw new Error(
242
+ `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`
243
+ );
328
244
  }
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) {
245
+ }
246
+ function sharedNumberFactory(input) {
334
247
  let littleEndian;
335
248
  let defaultDescription = input.name;
336
249
  if (input.size > 1) {
337
- littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little;
250
+ littleEndian = !("endian" in input.config) || input.config.endian === 0;
338
251
  defaultDescription += littleEndian ? "(le)" : "(be)";
339
252
  }
340
253
  return {
341
- description: input.options.description ?? defaultDescription,
254
+ description: input.config.description ?? defaultDescription,
342
255
  fixedSize: input.size,
343
- maxSize: input.size,
344
- serialize(value) {
256
+ littleEndian,
257
+ maxSize: input.size
258
+ };
259
+ }
260
+ function numberEncoderFactory(input) {
261
+ const codecData = sharedNumberFactory(input);
262
+ return {
263
+ description: codecData.description,
264
+ encode(value) {
345
265
  if (input.range) {
346
- assertRange(input.name, input.range[0], input.range[1], value);
266
+ assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
347
267
  }
348
- const buffer = new ArrayBuffer(input.size);
349
- input.set(new DataView(buffer), value, littleEndian);
350
- return new Uint8Array(buffer);
268
+ const arrayBuffer = new ArrayBuffer(input.size);
269
+ input.set(new DataView(arrayBuffer), value, codecData.littleEndian);
270
+ return new Uint8Array(arrayBuffer);
351
271
  },
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
- }
272
+ fixedSize: codecData.fixedSize,
273
+ maxSize: codecData.maxSize
358
274
  };
359
275
  }
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
385
- });
386
-
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];
276
+ function numberDecoderFactory(input) {
277
+ const codecData = sharedNumberFactory(input);
278
+ return {
279
+ decode(bytes, offset = 0) {
280
+ assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);
281
+ assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);
282
+ const view = new DataView(toArrayBuffer(bytes, offset, input.size));
283
+ return [input.get(view, codecData.littleEndian), offset + input.size];
284
+ },
285
+ description: codecData.description,
286
+ fixedSize: codecData.fixedSize,
287
+ maxSize: codecData.maxSize
288
+ };
289
+ }
290
+ function toArrayBuffer(bytes, offset, length) {
291
+ const bytesOffset = bytes.byteOffset + (offset ?? 0);
292
+ const bytesLength = length ?? bytes.byteLength;
293
+ return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
294
+ }
295
+ var getShortU16Encoder = (config = {}) => ({
296
+ description: config.description ?? "shortU16",
297
+ encode: (value) => {
298
+ assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
299
+ const bytes = [0];
407
300
  for (let ii = 0; ; ii += 1) {
408
301
  const alignedValue = value >> ii * 7;
409
302
  if (alignedValue === 0) {
410
303
  break;
411
304
  }
412
305
  const nextSevenBits = 127 & alignedValue;
413
- bytes2[ii] = nextSevenBits;
306
+ bytes[ii] = nextSevenBits;
414
307
  if (ii > 0) {
415
- bytes2[ii - 1] |= 128;
308
+ bytes[ii - 1] |= 128;
416
309
  }
417
310
  }
418
- return new Uint8Array(bytes2);
311
+ return new Uint8Array(bytes);
419
312
  },
420
- deserialize: (bytes2, offset = 0) => {
313
+ fixedSize: null,
314
+ maxSize: 3
315
+ });
316
+ var getShortU16Decoder = (config = {}) => ({
317
+ decode: (bytes, offset = 0) => {
421
318
  let value = 0;
422
319
  let byteCount = 0;
423
320
  while (++byteCount) {
424
321
  const byteIndex = byteCount - 1;
425
- const currentByte = bytes2[offset + byteIndex];
322
+ const currentByte = bytes[offset + byteIndex];
426
323
  const nextSevenBits = 127 & currentByte;
427
324
  value |= nextSevenBits << byteIndex * 7;
428
325
  if ((currentByte & 128) === 0) {
@@ -430,223 +327,214 @@ this.globalThis.solanaWeb3 = (function (exports) {
430
327
  }
431
328
  }
432
329
  return [value, offset + byteCount];
433
- }
330
+ },
331
+ description: config.description ?? "shortU16",
332
+ fixedSize: null,
333
+ maxSize: 3
334
+ });
335
+ var getU32Encoder = (config = {}) => numberEncoderFactory({
336
+ config,
337
+ name: "u32",
338
+ range: [0, Number("0xffffffff")],
339
+ set: (view, value, le) => view.setUint32(0, value, le),
340
+ size: 4
341
+ });
342
+ var getU32Decoder = (config = {}) => numberDecoderFactory({
343
+ config,
344
+ get: (view, le) => view.getUint32(0, le),
345
+ name: "u32",
346
+ size: 4
347
+ });
348
+ var getU8Encoder = (config = {}) => numberEncoderFactory({
349
+ config,
350
+ name: "u8",
351
+ range: [0, Number("0xff")],
352
+ set: (view, value) => view.setUint8(0, value),
353
+ size: 1
354
+ });
355
+ var getU8Decoder = (config = {}) => numberDecoderFactory({
356
+ config,
357
+ get: (view) => view.getUint8(0),
358
+ name: "u8",
359
+ size: 1
434
360
  });
435
361
 
436
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs
437
- init_env_shim();
438
-
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");
362
+ // ../codecs-strings/dist/index.browser.js
363
+ function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
364
+ if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
365
+ throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
445
366
  }
367
+ }
368
+ var getBaseXEncoder = (alphabet4) => {
369
+ const base = alphabet4.length;
370
+ const baseBigInt = BigInt(base);
371
+ return {
372
+ description: `base${base}`,
373
+ encode(value) {
374
+ assertValidBaseString(alphabet4, value);
375
+ if (value === "")
376
+ return new Uint8Array();
377
+ const chars = [...value];
378
+ let trailIndex = chars.findIndex((c) => c !== alphabet4[0]);
379
+ trailIndex = trailIndex === -1 ? chars.length : trailIndex;
380
+ const leadingZeroes = Array(trailIndex).fill(0);
381
+ if (trailIndex === chars.length)
382
+ return Uint8Array.from(leadingZeroes);
383
+ const tailChars = chars.slice(trailIndex);
384
+ let base10Number = 0n;
385
+ let baseXPower = 1n;
386
+ for (let i = tailChars.length - 1; i >= 0; i -= 1) {
387
+ base10Number += baseXPower * BigInt(alphabet4.indexOf(tailChars[i]));
388
+ baseXPower *= baseBigInt;
389
+ }
390
+ const tailBytes = [];
391
+ while (base10Number > 0n) {
392
+ tailBytes.unshift(Number(base10Number % 256n));
393
+ base10Number /= 256n;
394
+ }
395
+ return Uint8Array.from(leadingZeroes.concat(tailBytes));
396
+ },
397
+ fixedSize: null,
398
+ maxSize: null
399
+ };
446
400
  };
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
- }
401
+ var getBaseXDecoder = (alphabet4) => {
402
+ const base = alphabet4.length;
403
+ const baseBigInt = BigInt(base);
404
+ return {
405
+ decode(rawBytes, offset = 0) {
406
+ const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
407
+ if (bytes.length === 0)
408
+ return ["", 0];
409
+ let trailIndex = bytes.findIndex((n) => n !== 0);
410
+ trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
411
+ const leadingZeroes = alphabet4[0].repeat(trailIndex);
412
+ if (trailIndex === bytes.length)
413
+ return [leadingZeroes, rawBytes.length];
414
+ let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
415
+ const tailChars = [];
416
+ while (base10Number > 0n) {
417
+ tailChars.unshift(alphabet4[Number(base10Number % baseBigInt)]);
418
+ base10Number /= baseBigInt;
419
+ }
420
+ return [leadingZeroes + tailChars.join(""), rawBytes.length];
421
+ },
422
+ description: `base${base}`,
423
+ fixedSize: null,
424
+ maxSize: null
425
+ };
452
426
  };
453
- var UnrecognizedArrayLikeSerializerSizeError = class extends Error {
454
- constructor(size) {
455
- super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`);
456
- __publicField(this, "name", "UnrecognizedArrayLikeSerializerSizeError");
427
+ var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
428
+ var getBase58Encoder = () => getBaseXEncoder(alphabet2);
429
+ var getBase58Decoder = () => getBaseXDecoder(alphabet2);
430
+ var getBase64Encoder = () => {
431
+ {
432
+ return {
433
+ description: `base64`,
434
+ encode(value) {
435
+ try {
436
+ const bytes = atob(value).split("").map((c) => c.charCodeAt(0));
437
+ return new Uint8Array(bytes);
438
+ } catch (e23) {
439
+ throw new Error(`Expected a string of base 64, got [${value}].`);
440
+ }
441
+ },
442
+ fixedSize: null,
443
+ maxSize: null
444
+ };
457
445
  }
458
446
  };
459
-
460
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
461
- init_env_shim();
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.');
447
+ var getBase64Decoder = () => {
448
+ {
449
+ return {
450
+ decode(bytes, offset = 0) {
451
+ const slice = bytes.slice(offset);
452
+ const value = btoa(String.fromCharCode(...slice));
453
+ return [value, bytes.length];
454
+ },
455
+ description: `base64`,
456
+ fixedSize: null,
457
+ maxSize: null
458
+ };
510
459
  }
460
+ };
461
+ var removeNullCharacters = (value) => (
462
+ // eslint-disable-next-line no-control-regex
463
+ value.replace(/\u0000/g, "")
464
+ );
465
+ var e = globalThis.TextDecoder;
466
+ var o = globalThis.TextEncoder;
467
+ var getUtf8Encoder = () => {
468
+ let textEncoder;
511
469
  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
- }
470
+ description: "utf8",
471
+ encode: (value) => new Uint8Array((textEncoder || (textEncoder = new o())).encode(value)),
472
+ fixedSize: null,
473
+ maxSize: null
535
474
  };
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,
475
+ };
476
+ var getUtf8Decoder = () => {
477
+ let textDecoder;
478
+ return {
479
+ decode(bytes, offset = 0) {
480
+ const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));
481
+ return [removeNullCharacters(value), bytes.length];
482
+ },
483
+ description: "utf8",
545
484
  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
- }
485
+ maxSize: null
552
486
  };
487
+ };
488
+ var getStringEncoder = (config = {}) => {
489
+ const size = config.size ?? getU32Encoder();
490
+ const encoding = config.encoding ?? getUtf8Encoder();
491
+ const description = config.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
553
492
  if (size === "variable") {
554
- return byteSerializer;
493
+ return { ...encoding, description };
555
494
  }
556
495
  if (typeof size === "number") {
557
- return fixSerializer(byteSerializer, size, description);
496
+ return fixEncoder(encoding, size, description);
558
497
  }
559
498
  return {
560
499
  description,
561
- fixedSize: null,
562
- maxSize: null,
563
- serialize: (value) => {
564
- const contentBytes = byteSerializer.serialize(value);
565
- const lengthBytes = size.serialize(contentBytes.length);
500
+ encode: (value) => {
501
+ const contentBytes = encoding.encode(value);
502
+ const lengthBytes = size.encode(contentBytes.length);
566
503
  return mergeBytes([lengthBytes, contentBytes]);
567
504
  },
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
- }
505
+ fixedSize: null,
506
+ maxSize: null
583
507
  };
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)})`;
508
+ };
509
+ var getStringDecoder = (config = {}) => {
510
+ const size = config.size ?? getU32Decoder();
511
+ const encoding = config.encoding ?? getUtf8Decoder();
512
+ const description = config.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
592
513
  if (size === "variable") {
593
- return {
594
- ...encoding,
595
- description
596
- };
514
+ return { ...encoding, description };
597
515
  }
598
516
  if (typeof size === "number") {
599
- return fixSerializer(encoding, size, description);
517
+ return fixDecoder(encoding, size, description);
600
518
  }
601
519
  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);
520
+ decode: (bytes, offset = 0) => {
521
+ assertByteArrayIsNotEmptyForCodec("string", bytes, offset);
522
+ const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);
615
523
  const length = Number(lengthBigInt);
616
524
  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);
525
+ const contentBytes = bytes.slice(offset, offset + length);
526
+ assertByteArrayHasEnoughBytesForCodec("string", length, contentBytes);
527
+ const [value, contentOffset] = encoding.decode(contentBytes);
622
528
  offset += contentOffset;
623
529
  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
530
  },
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
- }
531
+ description,
532
+ fixedSize: null,
533
+ maxSize: null
649
534
  };
535
+ };
536
+ function getSizeDescription(size) {
537
+ return typeof size === "object" ? size.description : `${size}`;
650
538
  }
651
539
 
652
540
  // ../assertions/dist/index.browser.js
@@ -715,34 +603,82 @@ this.globalThis.solanaWeb3 = (function (exports) {
715
603
  throw new Error("No signature verification implementation could be found");
716
604
  }
717
605
  }
718
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
606
+
607
+ // ../addresses/dist/index.browser.js
608
+ var memoizedBase58Encoder;
609
+ var memoizedBase58Decoder;
610
+ function getMemoizedBase58Encoder() {
611
+ if (!memoizedBase58Encoder)
612
+ memoizedBase58Encoder = getBase58Encoder();
613
+ return memoizedBase58Encoder;
614
+ }
615
+ function getMemoizedBase58Decoder() {
616
+ if (!memoizedBase58Decoder)
617
+ memoizedBase58Decoder = getBase58Decoder();
618
+ return memoizedBase58Decoder;
619
+ }
620
+ function isAddress(putativeAddress) {
621
+ if (
622
+ // Lowest address (32 bytes of zeroes)
623
+ putativeAddress.length < 32 || // Highest address (32 bytes of 255)
624
+ putativeAddress.length > 44
625
+ ) {
626
+ return false;
627
+ }
628
+ const base58Encoder3 = getMemoizedBase58Encoder();
629
+ const bytes = base58Encoder3.encode(putativeAddress);
630
+ const numBytes = bytes.byteLength;
631
+ if (numBytes !== 32) {
632
+ return false;
633
+ }
634
+ return true;
635
+ }
636
+ function assertIsAddress(putativeAddress) {
719
637
  try {
720
638
  if (
721
639
  // Lowest address (32 bytes of zeroes)
722
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
723
- putativeBase58EncodedAddress.length > 44
640
+ putativeAddress.length < 32 || // Highest address (32 bytes of 255)
641
+ putativeAddress.length > 44
724
642
  ) {
725
643
  throw new Error("Expected input string to decode to a byte array of length 32.");
726
644
  }
727
- const bytes2 = base58.serialize(putativeBase58EncodedAddress);
728
- const numBytes = bytes2.byteLength;
645
+ const base58Encoder3 = getMemoizedBase58Encoder();
646
+ const bytes = base58Encoder3.encode(putativeAddress);
647
+ const numBytes = bytes.byteLength;
729
648
  if (numBytes !== 32) {
730
649
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
731
650
  }
732
651
  } catch (e3) {
733
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
652
+ throw new Error(`\`${putativeAddress}\` is not a base-58 encoded address`, {
734
653
  cause: e3
735
654
  });
736
655
  }
737
656
  }
738
- function getBase58EncodedAddressCodec(config) {
739
- return string({
740
- description: config?.description ?? ("A 32-byte account address" ),
741
- encoding: base58,
657
+ function address(putativeAddress) {
658
+ assertIsAddress(putativeAddress);
659
+ return putativeAddress;
660
+ }
661
+ function getAddressEncoder(config) {
662
+ return mapEncoder(
663
+ getStringEncoder({
664
+ description: config?.description ?? "Address",
665
+ encoding: getMemoizedBase58Encoder(),
666
+ size: 32
667
+ }),
668
+ (putativeAddress) => address(putativeAddress)
669
+ );
670
+ }
671
+ function getAddressDecoder(config) {
672
+ return getStringDecoder({
673
+ description: config?.description ?? "Address",
674
+ encoding: getMemoizedBase58Decoder(),
742
675
  size: 32
743
676
  });
744
677
  }
745
- function getBase58EncodedAddressComparator() {
678
+ function getAddressCodec(config) {
679
+ return combineCodec(getAddressEncoder(config), getAddressDecoder(config));
680
+ }
681
+ function getAddressComparator() {
746
682
  return new Intl.Collator("en", {
747
683
  caseFirst: "lower",
748
684
  ignorePunctuation: false,
@@ -826,17 +762,32 @@ this.globalThis.solanaWeb3 = (function (exports) {
826
762
  return hexString;
827
763
  }
828
764
  }
829
- function decompressPointBytes(bytes2) {
830
- const hexString = bytes2.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
765
+ function decompressPointBytes(bytes) {
766
+ const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
831
767
  const integerLiteralString = `0x${hexString}`;
832
768
  return BigInt(integerLiteralString);
833
769
  }
834
- async function compressedPointBytesAreOnCurve(bytes2) {
835
- if (bytes2.byteLength !== 32) {
770
+ async function compressedPointBytesAreOnCurve(bytes) {
771
+ if (bytes.byteLength !== 32) {
836
772
  return false;
837
773
  }
838
- const y = decompressPointBytes(bytes2);
839
- return pointIsOnCurve(y, bytes2[31]);
774
+ const y = decompressPointBytes(bytes);
775
+ return pointIsOnCurve(y, bytes[31]);
776
+ }
777
+ function isProgramDerivedAddress(value) {
778
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
779
+ }
780
+ function assertIsProgramDerivedAddress(value) {
781
+ const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
782
+ if (!validFormat) {
783
+ throw new Error(
784
+ `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`
785
+ );
786
+ }
787
+ if (value[1] < 0 || value[1] > 255) {
788
+ throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);
789
+ }
790
+ assertIsAddress(value[0]);
840
791
  }
841
792
  var MAX_SEED_LENGTH = 32;
842
793
  var MAX_SEEDS = 16;
@@ -873,15 +824,15 @@ this.globalThis.solanaWeb3 = (function (exports) {
873
824
  }
874
825
  let textEncoder;
875
826
  const seedBytes = seeds.reduce((acc, seed, ii) => {
876
- const bytes2 = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
877
- if (bytes2.byteLength > MAX_SEED_LENGTH) {
827
+ const bytes = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
828
+ if (bytes.byteLength > MAX_SEED_LENGTH) {
878
829
  throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);
879
830
  }
880
- acc.push(...bytes2);
831
+ acc.push(...bytes);
881
832
  return acc;
882
833
  }, []);
883
- const base58EncodedAddressCodec = getBase58EncodedAddressCodec();
884
- const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);
834
+ const base58EncodedAddressCodec = getAddressCodec();
835
+ const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
885
836
  const addressBytesBuffer = await crypto.subtle.digest(
886
837
  "SHA-256",
887
838
  new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
@@ -890,19 +841,20 @@ this.globalThis.solanaWeb3 = (function (exports) {
890
841
  if (await compressedPointBytesAreOnCurve(addressBytes)) {
891
842
  throw new PointOnCurveError("Invalid seeds; point must fall off the Ed25519 curve");
892
843
  }
893
- return base58EncodedAddressCodec.deserialize(addressBytes)[0];
844
+ return base58EncodedAddressCodec.decode(addressBytes)[0];
894
845
  }
895
- async function getProgramDerivedAddress({ programAddress, seeds }) {
846
+ async function getProgramDerivedAddress({
847
+ programAddress,
848
+ seeds
849
+ }) {
896
850
  let bumpSeed = 255;
897
851
  while (bumpSeed > 0) {
898
852
  try {
899
- return {
900
- bumpSeed,
901
- pda: await createProgramDerivedAddress({
902
- programAddress,
903
- seeds: [...seeds, new Uint8Array([bumpSeed])]
904
- })
905
- };
853
+ const address2 = await createProgramDerivedAddress({
854
+ programAddress,
855
+ seeds: [...seeds, new Uint8Array([bumpSeed])]
856
+ });
857
+ return [address2, bumpSeed];
906
858
  } catch (e3) {
907
859
  if (e3 instanceof PointOnCurveError) {
908
860
  bumpSeed--;
@@ -913,26 +865,22 @@ this.globalThis.solanaWeb3 = (function (exports) {
913
865
  }
914
866
  throw new Error("Unable to find a viable program address bump seed");
915
867
  }
916
- async function createAddressWithSeed({
917
- baseAddress,
918
- programAddress,
919
- seed
920
- }) {
921
- const { serialize: serialize4, deserialize: deserialize2 } = getBase58EncodedAddressCodec();
868
+ async function createAddressWithSeed({ baseAddress, programAddress, seed }) {
869
+ const { encode: encode2, decode: decode2 } = getAddressCodec();
922
870
  const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
923
871
  if (seedBytes.byteLength > MAX_SEED_LENGTH) {
924
872
  throw new Error(`The seed exceeds the maximum length of 32 bytes`);
925
873
  }
926
- const programAddressBytes = serialize4(programAddress);
874
+ const programAddressBytes = encode2(programAddress);
927
875
  if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
928
876
  throw new Error(`programAddress cannot end with the PDA marker`);
929
877
  }
930
878
  const addressBytesBuffer = await crypto.subtle.digest(
931
879
  "SHA-256",
932
- new Uint8Array([...serialize4(baseAddress), ...seedBytes, ...programAddressBytes])
880
+ new Uint8Array([...encode2(baseAddress), ...seedBytes, ...programAddressBytes])
933
881
  );
934
882
  const addressBytes = new Uint8Array(addressBytesBuffer);
935
- return deserialize2(addressBytes)[0];
883
+ return decode2(addressBytes)[0];
936
884
  }
937
885
  async function getAddressFromPublicKey(publicKey) {
938
886
  await assertKeyExporterIsAvailable();
@@ -940,7 +888,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
940
888
  throw new Error("The `CryptoKey` must be an `Ed25519` public key");
941
889
  }
942
890
  const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
943
- const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
891
+ const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
944
892
  return base58EncodedAddress;
945
893
  }
946
894
 
@@ -997,18 +945,340 @@ this.globalThis.solanaWeb3 = (function (exports) {
997
945
  );
998
946
  return keyPair;
999
947
  }
1000
- async function signBytes(key, data) {
1001
- await assertSigningCapabilityIsAvailable();
1002
- const signedData = await crypto.subtle.sign("Ed25519", key, data);
1003
- return new Uint8Array(signedData);
948
+ var base58Encoder;
949
+ function assertIsSignature(putativeSignature) {
950
+ if (!base58Encoder)
951
+ base58Encoder = getBase58Encoder();
952
+ try {
953
+ if (
954
+ // Lowest value (64 bytes of zeroes)
955
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
956
+ putativeSignature.length > 88
957
+ ) {
958
+ throw new Error("Expected input string to decode to a byte array of length 64.");
959
+ }
960
+ const bytes = base58Encoder.encode(putativeSignature);
961
+ const numBytes = bytes.byteLength;
962
+ if (numBytes !== 64) {
963
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
964
+ }
965
+ } catch (e3) {
966
+ throw new Error(`\`${putativeSignature}\` is not a signature`, {
967
+ cause: e3
968
+ });
969
+ }
970
+ }
971
+ function isSignature(putativeSignature) {
972
+ if (!base58Encoder)
973
+ base58Encoder = getBase58Encoder();
974
+ if (
975
+ // Lowest value (64 bytes of zeroes)
976
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
977
+ putativeSignature.length > 88
978
+ ) {
979
+ return false;
980
+ }
981
+ const bytes = base58Encoder.encode(putativeSignature);
982
+ const numBytes = bytes.byteLength;
983
+ if (numBytes !== 64) {
984
+ return false;
985
+ }
986
+ return true;
987
+ }
988
+ async function signBytes(key, data) {
989
+ await assertSigningCapabilityIsAvailable();
990
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
991
+ return new Uint8Array(signedData);
992
+ }
993
+ function signature(putativeSignature) {
994
+ assertIsSignature(putativeSignature);
995
+ return putativeSignature;
996
+ }
997
+ async function verifySignature(key, signature2, data) {
998
+ await assertVerificationCapabilityIsAvailable();
999
+ return await crypto.subtle.verify("Ed25519", key, signature2, data);
1000
+ }
1001
+
1002
+ // ../rpc-types/dist/index.browser.js
1003
+ init_env_shim();
1004
+ function getCommitmentScore(commitment) {
1005
+ switch (commitment) {
1006
+ case "finalized":
1007
+ return 2;
1008
+ case "confirmed":
1009
+ return 1;
1010
+ case "processed":
1011
+ return 0;
1012
+ default:
1013
+ return ((_) => {
1014
+ throw new Error(`Unrecognized commitment \`${commitment}\`.`);
1015
+ })();
1016
+ }
1017
+ }
1018
+ function commitmentComparator(a, b) {
1019
+ if (a === b) {
1020
+ return 0;
1021
+ }
1022
+ return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;
1023
+ }
1024
+ var maxU64Value = 18446744073709551615n;
1025
+ function isLamports(putativeLamports) {
1026
+ return putativeLamports >= 0 && putativeLamports <= maxU64Value;
1027
+ }
1028
+ function assertIsLamports(putativeLamports) {
1029
+ if (putativeLamports < 0) {
1030
+ throw new Error("Input for 64-bit unsigned integer cannot be negative");
1031
+ }
1032
+ if (putativeLamports > maxU64Value) {
1033
+ throw new Error("Input number is too large to be represented as a 64-bit unsigned integer");
1034
+ }
1035
+ }
1036
+ function lamports(putativeLamports) {
1037
+ assertIsLamports(putativeLamports);
1038
+ return putativeLamports;
1039
+ }
1040
+ function isStringifiedBigInt(putativeBigInt) {
1041
+ try {
1042
+ BigInt(putativeBigInt);
1043
+ return true;
1044
+ } catch (_) {
1045
+ return false;
1046
+ }
1047
+ }
1048
+ function assertIsStringifiedBigInt(putativeBigInt) {
1049
+ try {
1050
+ BigInt(putativeBigInt);
1051
+ } catch (e3) {
1052
+ throw new Error(`\`${putativeBigInt}\` cannot be parsed as a BigInt`, {
1053
+ cause: e3
1054
+ });
1055
+ }
1056
+ }
1057
+ function stringifiedBigInt(putativeBigInt) {
1058
+ assertIsStringifiedBigInt(putativeBigInt);
1059
+ return putativeBigInt;
1060
+ }
1061
+ function isStringifiedNumber(putativeNumber) {
1062
+ return !Number.isNaN(Number(putativeNumber));
1063
+ }
1064
+ function assertIsStringifiedNumber(putativeNumber) {
1065
+ if (Number.isNaN(Number(putativeNumber))) {
1066
+ throw new Error(`\`${putativeNumber}\` cannot be parsed as a Number`);
1067
+ }
1068
+ }
1069
+ function stringifiedNumber(putativeNumber) {
1070
+ assertIsStringifiedNumber(putativeNumber);
1071
+ return putativeNumber;
1072
+ }
1073
+ function isUnixTimestamp(putativeTimestamp) {
1074
+ if (putativeTimestamp > 864e13 || putativeTimestamp < -864e13) {
1075
+ return false;
1076
+ }
1077
+ return true;
1078
+ }
1079
+ function assertIsUnixTimestamp(putativeTimestamp) {
1080
+ try {
1081
+ if (putativeTimestamp > 864e13 || putativeTimestamp < -864e13) {
1082
+ throw new Error("Expected input number to be in the range [-8.64e15, 8.64e15]");
1083
+ }
1084
+ } catch (e3) {
1085
+ throw new Error(`\`${putativeTimestamp}\` is not a timestamp`, {
1086
+ cause: e3
1087
+ });
1088
+ }
1089
+ }
1090
+ function unixTimestamp(putativeTimestamp) {
1091
+ assertIsUnixTimestamp(putativeTimestamp);
1092
+ return putativeTimestamp;
1093
+ }
1094
+
1095
+ // ../transactions/dist/index.browser.js
1096
+ init_env_shim();
1097
+
1098
+ // ../codecs-data-structures/dist/index.browser.js
1099
+ init_env_shim();
1100
+ function sumCodecSizes(sizes) {
1101
+ return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
1102
+ }
1103
+ function decodeArrayLikeCodecSize(size, childrenSizes, bytes, offset) {
1104
+ if (typeof size === "number") {
1105
+ return [size, offset];
1106
+ }
1107
+ if (typeof size === "object") {
1108
+ return size.decode(bytes, offset);
1109
+ }
1110
+ if (size === "remainder") {
1111
+ const childrenSize = sumCodecSizes(childrenSizes);
1112
+ if (childrenSize === null) {
1113
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
1114
+ }
1115
+ const remainder = bytes.slice(offset).length;
1116
+ if (remainder % childrenSize !== 0) {
1117
+ throw new Error(
1118
+ `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. Codecs of "remainder" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`
1119
+ );
1120
+ }
1121
+ return [remainder / childrenSize, offset];
1122
+ }
1123
+ throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);
1124
+ }
1125
+ function getArrayLikeCodecSizeDescription(size) {
1126
+ return typeof size === "object" ? size.description : `${size}`;
1127
+ }
1128
+ function getArrayLikeCodecSizeFromChildren(size, childrenSizes) {
1129
+ if (typeof size !== "number")
1130
+ return null;
1131
+ if (size === 0)
1132
+ return 0;
1133
+ const childrenSize = sumCodecSizes(childrenSizes);
1134
+ return childrenSize === null ? null : childrenSize * size;
1135
+ }
1136
+ function getArrayLikeCodecSizePrefix(size, realSize) {
1137
+ return typeof size === "object" ? size.encode(realSize) : new Uint8Array();
1138
+ }
1139
+ function assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {
1140
+ if (expected !== actual) {
1141
+ throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);
1142
+ }
1143
+ }
1144
+ function arrayCodecHelper(item, size, description) {
1145
+ if (size === "remainder" && item.fixedSize === null) {
1146
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
1147
+ }
1148
+ return {
1149
+ description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,
1150
+ fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),
1151
+ maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])
1152
+ };
1153
+ }
1154
+ function getArrayEncoder(item, config = {}) {
1155
+ const size = config.size ?? getU32Encoder();
1156
+ return {
1157
+ ...arrayCodecHelper(item, size, config.description),
1158
+ encode: (value) => {
1159
+ if (typeof size === "number") {
1160
+ assertValidNumberOfItemsForCodec("array", size, value.length);
1161
+ }
1162
+ return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map((v) => item.encode(v))]);
1163
+ }
1164
+ };
1165
+ }
1166
+ function getArrayDecoder(item, config = {}) {
1167
+ const size = config.size ?? getU32Decoder();
1168
+ return {
1169
+ ...arrayCodecHelper(item, size, config.description),
1170
+ decode: (bytes, offset = 0) => {
1171
+ if (typeof size === "object" && bytes.slice(offset).length === 0) {
1172
+ return [[], offset];
1173
+ }
1174
+ const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);
1175
+ offset = newOffset;
1176
+ const values = [];
1177
+ for (let i = 0; i < resolvedSize; i += 1) {
1178
+ const [value, newOffset2] = item.decode(bytes, offset);
1179
+ values.push(value);
1180
+ offset = newOffset2;
1181
+ }
1182
+ return [values, offset];
1183
+ }
1184
+ };
1185
+ }
1186
+ function getBytesEncoder(config = {}) {
1187
+ const size = config.size ?? "variable";
1188
+ const sizeDescription = typeof size === "object" ? size.description : `${size}`;
1189
+ const description = config.description ?? `bytes(${sizeDescription})`;
1190
+ const byteEncoder = {
1191
+ description,
1192
+ encode: (value) => value,
1193
+ fixedSize: null,
1194
+ maxSize: null
1195
+ };
1196
+ if (size === "variable") {
1197
+ return byteEncoder;
1198
+ }
1199
+ if (typeof size === "number") {
1200
+ return fixEncoder(byteEncoder, size, description);
1201
+ }
1202
+ return {
1203
+ ...byteEncoder,
1204
+ encode: (value) => {
1205
+ const contentBytes = byteEncoder.encode(value);
1206
+ const lengthBytes = size.encode(contentBytes.length);
1207
+ return mergeBytes([lengthBytes, contentBytes]);
1208
+ }
1209
+ };
1210
+ }
1211
+ function getBytesDecoder(config = {}) {
1212
+ const size = config.size ?? "variable";
1213
+ const sizeDescription = typeof size === "object" ? size.description : `${size}`;
1214
+ const description = config.description ?? `bytes(${sizeDescription})`;
1215
+ const byteDecoder = {
1216
+ decode: (bytes, offset = 0) => {
1217
+ const slice = bytes.slice(offset);
1218
+ return [slice, offset + slice.length];
1219
+ },
1220
+ description,
1221
+ fixedSize: null,
1222
+ maxSize: null
1223
+ };
1224
+ if (size === "variable") {
1225
+ return byteDecoder;
1226
+ }
1227
+ if (typeof size === "number") {
1228
+ return fixDecoder(byteDecoder, size, description);
1229
+ }
1230
+ return {
1231
+ ...byteDecoder,
1232
+ decode: (bytes, offset = 0) => {
1233
+ assertByteArrayIsNotEmptyForCodec("bytes", bytes, offset);
1234
+ const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);
1235
+ const length = Number(lengthBigInt);
1236
+ offset = lengthOffset;
1237
+ const contentBytes = bytes.slice(offset, offset + length);
1238
+ assertByteArrayHasEnoughBytesForCodec("bytes", length, contentBytes);
1239
+ const [value, contentOffset] = byteDecoder.decode(contentBytes);
1240
+ offset += contentOffset;
1241
+ return [value, offset];
1242
+ }
1243
+ };
1244
+ }
1245
+ function structCodecHelper(fields, description) {
1246
+ const fieldDescriptions = fields.map(([name, codec]) => `${String(name)}: ${codec.description}`).join(", ");
1247
+ return {
1248
+ description: description ?? `struct(${fieldDescriptions})`,
1249
+ fixedSize: sumCodecSizes(fields.map(([, field]) => field.fixedSize)),
1250
+ maxSize: sumCodecSizes(fields.map(([, field]) => field.maxSize))
1251
+ };
1004
1252
  }
1005
- async function verifySignature(key, signature, data) {
1006
- await assertVerificationCapabilityIsAvailable();
1007
- return await crypto.subtle.verify("Ed25519", key, signature, data);
1253
+ function getStructEncoder(fields, config = {}) {
1254
+ return {
1255
+ ...structCodecHelper(fields, config.description),
1256
+ encode: (struct) => {
1257
+ const fieldBytes = fields.map(([key, codec]) => codec.encode(struct[key]));
1258
+ return mergeBytes(fieldBytes);
1259
+ }
1260
+ };
1261
+ }
1262
+ function getStructDecoder(fields, config = {}) {
1263
+ return {
1264
+ ...structCodecHelper(fields, config.description),
1265
+ decode: (bytes, offset = 0) => {
1266
+ const struct = {};
1267
+ fields.forEach(([key, codec]) => {
1268
+ const [value, newOffset] = codec.decode(bytes, offset);
1269
+ offset = newOffset;
1270
+ struct[key] = value;
1271
+ });
1272
+ return [struct, offset];
1273
+ }
1274
+ };
1008
1275
  }
1009
1276
 
1010
- // ../transactions/dist/index.browser.js
1277
+ // ../functional/dist/index.browser.js
1011
1278
  init_env_shim();
1279
+ function pipe(init, ...fns) {
1280
+ return fns.reduce((acc, fn) => fn(acc), init);
1281
+ }
1012
1282
  function getUnsignedTransaction(transaction) {
1013
1283
  if ("signatures" in transaction) {
1014
1284
  const {
@@ -1021,7 +1291,10 @@ this.globalThis.solanaWeb3 = (function (exports) {
1021
1291
  return transaction;
1022
1292
  }
1023
1293
  }
1294
+ var base58Encoder2;
1024
1295
  function assertIsBlockhash(putativeBlockhash) {
1296
+ if (!base58Encoder2)
1297
+ base58Encoder2 = getBase58Encoder();
1025
1298
  try {
1026
1299
  if (
1027
1300
  // Lowest value (32 bytes of zeroes)
@@ -1030,8 +1303,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
1030
1303
  ) {
1031
1304
  throw new Error("Expected input string to decode to a byte array of length 32.");
1032
1305
  }
1033
- const bytes3 = base58.serialize(putativeBlockhash);
1034
- const numBytes = bytes3.byteLength;
1306
+ const bytes = base58Encoder2.encode(putativeBlockhash);
1307
+ const numBytes = bytes.byteLength;
1035
1308
  if (numBytes !== 32) {
1036
1309
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
1037
1310
  }
@@ -1110,7 +1383,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1110
1383
  instruction.accounts?.length === 3 && // First account is nonce account address
1111
1384
  instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole2.WRITABLE && // Second account is recent blockhashes sysvar
1112
1385
  instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole2.READONLY && // Third account is nonce authority account
1113
- instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole2.READONLY_SIGNER;
1386
+ instruction.accounts[2].address != null && isSignerRole2(instruction.accounts[2].role);
1114
1387
  }
1115
1388
  function isAdvanceNonceAccountInstructionData(data) {
1116
1389
  return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
@@ -1118,21 +1391,38 @@ this.globalThis.solanaWeb3 = (function (exports) {
1118
1391
  function isDurableNonceTransaction(transaction) {
1119
1392
  return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
1120
1393
  }
1394
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
1395
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
1396
+ }
1121
1397
  function setTransactionLifetimeUsingDurableNonce({
1122
1398
  nonce,
1123
1399
  nonceAccountAddress,
1124
1400
  nonceAuthorityAddress
1125
1401
  }, transaction) {
1126
- const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);
1127
- if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) {
1128
- return transaction;
1402
+ let newInstructions;
1403
+ const firstInstruction = transaction.instructions[0];
1404
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
1405
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
1406
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
1407
+ return transaction;
1408
+ } else {
1409
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
1410
+ }
1411
+ } else {
1412
+ newInstructions = [
1413
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1414
+ ...transaction.instructions.slice(1)
1415
+ ];
1416
+ }
1417
+ } else {
1418
+ newInstructions = [
1419
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1420
+ ...transaction.instructions
1421
+ ];
1129
1422
  }
1130
1423
  const out = {
1131
1424
  ...getUnsignedTransaction(transaction),
1132
- instructions: [
1133
- createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1134
- ...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions
1135
- ],
1425
+ instructions: newInstructions,
1136
1426
  lifetimeConstraint: {
1137
1427
  nonce
1138
1428
  }
@@ -1167,8 +1457,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
1167
1457
  Object.freeze(out);
1168
1458
  return out;
1169
1459
  }
1170
- function upsert(addressMap, address, update) {
1171
- addressMap[address] = update(addressMap[address] ?? { role: AccountRole2.READONLY });
1460
+ function upsert(addressMap, address2, update) {
1461
+ addressMap[address2] = update(addressMap[address2] ?? { role: AccountRole2.READONLY });
1172
1462
  }
1173
1463
  var TYPE = Symbol("AddressMapTypeProperty");
1174
1464
  function getAddressMapFromInstructions(feePayer, instructions) {
@@ -1219,7 +1509,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1219
1509
  const shouldReplaceEntry = (
1220
1510
  // Consider using the new LOOKUP_TABLE if its address is different...
1221
1511
  entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
1222
- (addressComparator || (addressComparator = getBase58EncodedAddressComparator()))(
1512
+ (addressComparator || (addressComparator = getAddressComparator()))(
1223
1513
  accountMeta.lookupTableAddress,
1224
1514
  entry.lookupTableAddress
1225
1515
  ) < 0
@@ -1327,14 +1617,14 @@ this.globalThis.solanaWeb3 = (function (exports) {
1327
1617
  if (leftIsWritable !== isWritableRole2(rightEntry.role)) {
1328
1618
  return leftIsWritable ? -1 : 1;
1329
1619
  }
1330
- addressComparator || (addressComparator = getBase58EncodedAddressComparator());
1620
+ addressComparator || (addressComparator = getAddressComparator());
1331
1621
  if (leftEntry[TYPE] === 1 && rightEntry[TYPE] === 1 && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
1332
1622
  return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
1333
1623
  } else {
1334
1624
  return addressComparator(leftAddress, rightAddress);
1335
1625
  }
1336
- }).map(([address, addressMeta]) => ({
1337
- address,
1626
+ }).map(([address2, addressMeta]) => ({
1627
+ address: address2,
1338
1628
  ...addressMeta
1339
1629
  }));
1340
1630
  return orderedAccounts;
@@ -1356,7 +1646,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1356
1646
  entry.readableIndices.push(account.addressIndex);
1357
1647
  }
1358
1648
  }
1359
- return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
1649
+ return Object.keys(index).sort(getAddressComparator()).map((lookupTableAddress) => ({
1360
1650
  lookupTableAddress,
1361
1651
  ...index[lookupTableAddress]
1362
1652
  }));
@@ -1397,7 +1687,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1397
1687
  return instructions.map(({ accounts, data, programAddress }) => {
1398
1688
  return {
1399
1689
  programAddressIndex: accountIndex[programAddress],
1400
- ...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null,
1690
+ ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
1401
1691
  ...data ? { data } : null
1402
1692
  };
1403
1693
  });
@@ -1411,7 +1701,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1411
1701
  function getCompiledStaticAccounts(orderedAccounts) {
1412
1702
  const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
1413
1703
  const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
1414
- return orderedStaticAccounts.map(({ address }) => address);
1704
+ return orderedStaticAccounts.map(({ address: address2 }) => address2);
1415
1705
  }
1416
1706
  function compileMessage(transaction) {
1417
1707
  const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
@@ -1425,138 +1715,306 @@ this.globalThis.solanaWeb3 = (function (exports) {
1425
1715
  version: transaction.version
1426
1716
  };
1427
1717
  }
1428
- function getAddressTableLookupCodec() {
1429
- return struct(
1430
- [
1718
+ function getCompiledTransaction(transaction) {
1719
+ const compiledMessage = compileMessage(transaction);
1720
+ let signatures;
1721
+ if ("signatures" in transaction) {
1722
+ signatures = [];
1723
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
1724
+ signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
1725
+ }
1726
+ } else {
1727
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
1728
+ }
1729
+ return {
1730
+ compiledMessage,
1731
+ signatures
1732
+ };
1733
+ }
1734
+ function getAccountMetas(message) {
1735
+ const { header } = message;
1736
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
1737
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
1738
+ const accountMetas = [];
1739
+ let accountIndex = 0;
1740
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
1741
+ accountMetas.push({
1742
+ address: message.staticAccounts[accountIndex],
1743
+ role: AccountRole2.WRITABLE_SIGNER
1744
+ });
1745
+ accountIndex++;
1746
+ }
1747
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
1748
+ accountMetas.push({
1749
+ address: message.staticAccounts[accountIndex],
1750
+ role: AccountRole2.READONLY_SIGNER
1751
+ });
1752
+ accountIndex++;
1753
+ }
1754
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
1755
+ accountMetas.push({
1756
+ address: message.staticAccounts[accountIndex],
1757
+ role: AccountRole2.WRITABLE
1758
+ });
1759
+ accountIndex++;
1760
+ }
1761
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
1762
+ accountMetas.push({
1763
+ address: message.staticAccounts[accountIndex],
1764
+ role: AccountRole2.READONLY
1765
+ });
1766
+ accountIndex++;
1767
+ }
1768
+ return accountMetas;
1769
+ }
1770
+ function convertInstruction(instruction, accountMetas) {
1771
+ const programAddress = accountMetas[instruction.programAddressIndex]?.address;
1772
+ if (!programAddress) {
1773
+ throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);
1774
+ }
1775
+ const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
1776
+ const { data } = instruction;
1777
+ return {
1778
+ programAddress,
1779
+ ...accounts && accounts.length ? { accounts } : {},
1780
+ ...data && data.length ? { data } : {}
1781
+ };
1782
+ }
1783
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
1784
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
1785
+ return {
1786
+ blockhash: messageLifetimeToken,
1787
+ lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
1788
+ // U64 MAX
1789
+ };
1790
+ } else {
1791
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
1792
+ assertIsAddress(nonceAccountAddress);
1793
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
1794
+ assertIsAddress(nonceAuthorityAddress);
1795
+ return {
1796
+ nonce: messageLifetimeToken,
1797
+ nonceAccountAddress,
1798
+ nonceAuthorityAddress
1799
+ };
1800
+ }
1801
+ }
1802
+ function convertSignatures(compiledTransaction) {
1803
+ const {
1804
+ compiledMessage: { staticAccounts },
1805
+ signatures
1806
+ } = compiledTransaction;
1807
+ return signatures.reduce((acc, sig, index) => {
1808
+ const allZeros = sig.every((byte) => byte === 0);
1809
+ if (allZeros)
1810
+ return acc;
1811
+ const address2 = staticAccounts[index];
1812
+ return { ...acc, [address2]: sig };
1813
+ }, {});
1814
+ }
1815
+ function decompileTransaction(compiledTransaction, lastValidBlockHeight) {
1816
+ const { compiledMessage } = compiledTransaction;
1817
+ if ("addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {
1818
+ throw new Error("Cannot convert transaction with addressTableLookups");
1819
+ }
1820
+ const feePayer = compiledMessage.staticAccounts[0];
1821
+ if (!feePayer)
1822
+ throw new Error("No fee payer set in CompiledTransaction");
1823
+ const accountMetas = getAccountMetas(compiledMessage);
1824
+ const instructions = compiledMessage.instructions.map(
1825
+ (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)
1826
+ );
1827
+ const firstInstruction = instructions[0];
1828
+ const lifetimeConstraint = getLifetimeConstraint(
1829
+ compiledMessage.lifetimeToken,
1830
+ firstInstruction,
1831
+ lastValidBlockHeight
1832
+ );
1833
+ const signatures = convertSignatures(compiledTransaction);
1834
+ return pipe(
1835
+ createTransaction({ version: compiledMessage.version }),
1836
+ (tx) => setTransactionFeePayer(feePayer, tx),
1837
+ (tx) => instructions.reduce((acc, instruction) => {
1838
+ return appendTransactionInstruction(instruction, acc);
1839
+ }, tx),
1840
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
1841
+ (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx
1842
+ );
1843
+ }
1844
+ var lookupTableAddressDescription = "The address of the address lookup table account from which instruction addresses should be looked up" ;
1845
+ var writableIndicesDescription = "The indices of the accounts in the lookup table that should be loaded as writeable" ;
1846
+ var readableIndicesDescription = "The indices of the accounts in the lookup table that should be loaded as read-only" ;
1847
+ var addressTableLookupDescription = "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" ;
1848
+ var memoizedAddressTableLookupEncoder;
1849
+ function getAddressTableLookupEncoder() {
1850
+ if (!memoizedAddressTableLookupEncoder) {
1851
+ memoizedAddressTableLookupEncoder = getStructEncoder(
1431
1852
  [
1432
- "lookupTableAddress",
1433
- getBase58EncodedAddressCodec(
1434
- {
1435
- description: "The address of the address lookup table account from which instruction addresses should be looked up"
1436
- }
1437
- )
1853
+ ["lookupTableAddress", getAddressEncoder({ description: lookupTableAddressDescription })],
1854
+ [
1855
+ "writableIndices",
1856
+ getArrayEncoder(getU8Encoder(), {
1857
+ description: writableIndicesDescription,
1858
+ size: getShortU16Encoder()
1859
+ })
1860
+ ],
1861
+ [
1862
+ "readableIndices",
1863
+ getArrayEncoder(getU8Encoder(), {
1864
+ description: readableIndicesDescription,
1865
+ size: getShortU16Encoder()
1866
+ })
1867
+ ]
1438
1868
  ],
1869
+ { description: addressTableLookupDescription }
1870
+ );
1871
+ }
1872
+ return memoizedAddressTableLookupEncoder;
1873
+ }
1874
+ var memoizedAddressTableLookupDecoder;
1875
+ function getAddressTableLookupDecoder() {
1876
+ if (!memoizedAddressTableLookupDecoder) {
1877
+ memoizedAddressTableLookupDecoder = getStructDecoder(
1439
1878
  [
1440
- "writableIndices",
1441
- array(u8(), {
1442
- ...{
1443
- description: "The indices of the accounts in the lookup table that should be loaded as writeable"
1444
- } ,
1445
- size: shortU16()
1446
- })
1879
+ ["lookupTableAddress", getAddressDecoder({ description: lookupTableAddressDescription })],
1880
+ [
1881
+ "writableIndices",
1882
+ getArrayDecoder(getU8Decoder(), {
1883
+ description: writableIndicesDescription,
1884
+ size: getShortU16Decoder()
1885
+ })
1886
+ ],
1887
+ [
1888
+ "readableIndices",
1889
+ getArrayDecoder(getU8Decoder(), {
1890
+ description: readableIndicesDescription,
1891
+ size: getShortU16Decoder()
1892
+ })
1893
+ ]
1447
1894
  ],
1448
- [
1449
- "readableIndices",
1450
- array(u8(), {
1451
- ...{
1452
- description: "The indices of the accounts in the lookup table that should be loaded as read-only"
1453
- } ,
1454
- size: shortU16()
1455
- })
1456
- ]
1895
+ { description: addressTableLookupDescription }
1896
+ );
1897
+ }
1898
+ return memoizedAddressTableLookupDecoder;
1899
+ }
1900
+ var memoizedU8Encoder;
1901
+ function getMemoizedU8Encoder() {
1902
+ if (!memoizedU8Encoder)
1903
+ memoizedU8Encoder = getU8Encoder();
1904
+ return memoizedU8Encoder;
1905
+ }
1906
+ function getMemoizedU8EncoderDescription(description) {
1907
+ const encoder = getMemoizedU8Encoder();
1908
+ return {
1909
+ ...encoder,
1910
+ description: description ?? encoder.description
1911
+ };
1912
+ }
1913
+ var memoizedU8Decoder;
1914
+ function getMemoizedU8Decoder() {
1915
+ if (!memoizedU8Decoder)
1916
+ memoizedU8Decoder = getU8Decoder();
1917
+ return memoizedU8Decoder;
1918
+ }
1919
+ function getMemoizedU8DecoderDescription(description) {
1920
+ const decoder = getMemoizedU8Decoder();
1921
+ return {
1922
+ ...decoder,
1923
+ description: description ?? decoder.description
1924
+ };
1925
+ }
1926
+ var numSignerAccountsDescription = "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" ;
1927
+ var numReadonlySignerAccountsDescription = "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" ;
1928
+ var numReadonlyNonSignerAccountsDescription = "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" ;
1929
+ var messageHeaderDescription = "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" ;
1930
+ function getMessageHeaderEncoder() {
1931
+ return getStructEncoder(
1932
+ [
1933
+ ["numSignerAccounts", getMemoizedU8EncoderDescription(numSignerAccountsDescription)],
1934
+ ["numReadonlySignerAccounts", getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],
1935
+ ["numReadonlyNonSignerAccounts", getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)]
1457
1936
  ],
1458
1937
  {
1459
- 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"
1460
- }
1938
+ description: messageHeaderDescription
1939
+ }
1461
1940
  );
1462
1941
  }
1463
- function getMessageHeaderCodec() {
1464
- return struct(
1942
+ function getMessageHeaderDecoder() {
1943
+ return getStructDecoder(
1465
1944
  [
1466
- [
1467
- "numSignerAccounts",
1468
- u8(
1469
- {
1470
- description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
1471
- }
1472
- )
1473
- ],
1474
- [
1475
- "numReadonlySignerAccounts",
1476
- u8(
1477
- {
1478
- 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"
1479
- }
1480
- )
1481
- ],
1482
- [
1483
- "numReadonlyNonSignerAccounts",
1484
- u8(
1485
- {
1486
- description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
1487
- }
1488
- )
1489
- ]
1945
+ ["numSignerAccounts", getMemoizedU8DecoderDescription(numSignerAccountsDescription)],
1946
+ ["numReadonlySignerAccounts", getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],
1947
+ ["numReadonlyNonSignerAccounts", getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)]
1490
1948
  ],
1491
1949
  {
1492
- description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
1493
- }
1494
- );
1495
- }
1496
- function getInstructionCodec() {
1497
- return mapSerializer(
1498
- struct([
1499
- [
1500
- "programAddressIndex",
1501
- u8(
1502
- {
1503
- description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
1504
- }
1505
- )
1506
- ],
1507
- [
1508
- "accountIndices",
1509
- array(
1510
- u8({
1511
- description: "The index of an account, according to the well-ordered accounts list for this transaction"
1512
- }),
1513
- {
1514
- 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" ,
1515
- size: shortU16()
1516
- }
1517
- )
1518
- ],
1519
- [
1520
- "data",
1521
- bytes({
1522
- description: "An optional buffer of data passed to the instruction" ,
1523
- size: shortU16()
1524
- })
1525
- ]
1526
- ]),
1527
- (value) => {
1528
- if (value.accountIndices !== void 0 && value.data !== void 0) {
1529
- return value;
1530
- }
1531
- return {
1532
- ...value,
1533
- accountIndices: value.accountIndices ?? [],
1534
- data: value.data ?? new Uint8Array(0)
1535
- };
1536
- },
1537
- (value) => {
1538
- if (value.accountIndices.length && value.data.byteLength) {
1539
- return value;
1540
- }
1541
- const { accountIndices, data, ...rest } = value;
1542
- return {
1543
- ...rest,
1544
- ...accountIndices.length ? { accountIndices } : null,
1545
- ...data.byteLength ? { data } : null
1546
- };
1950
+ description: messageHeaderDescription
1547
1951
  }
1548
1952
  );
1549
1953
  }
1550
- function getError(type, name) {
1551
- const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
1552
- return new Error(
1553
- `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}`
1554
- );
1954
+ var programAddressIndexDescription = "The index of the program being called, according to the well-ordered accounts list for this transaction" ;
1955
+ var accountIndexDescription = "The index of an account, according to the well-ordered accounts list for this transaction" ;
1956
+ var accountIndicesDescription = "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" ;
1957
+ var dataDescription = "An optional buffer of data passed to the instruction" ;
1958
+ var memoizedGetInstructionEncoder;
1959
+ function getInstructionEncoder() {
1960
+ if (!memoizedGetInstructionEncoder) {
1961
+ memoizedGetInstructionEncoder = mapEncoder(
1962
+ getStructEncoder([
1963
+ ["programAddressIndex", getU8Encoder({ description: programAddressIndexDescription })],
1964
+ [
1965
+ "accountIndices",
1966
+ getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {
1967
+ description: accountIndicesDescription,
1968
+ size: getShortU16Encoder()
1969
+ })
1970
+ ],
1971
+ ["data", getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })]
1972
+ ]),
1973
+ // Convert an instruction to have all fields defined
1974
+ (instruction) => {
1975
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
1976
+ return instruction;
1977
+ }
1978
+ return {
1979
+ ...instruction,
1980
+ accountIndices: instruction.accountIndices ?? [],
1981
+ data: instruction.data ?? new Uint8Array(0)
1982
+ };
1983
+ }
1984
+ );
1985
+ }
1986
+ return memoizedGetInstructionEncoder;
1555
1987
  }
1556
- function getUnimplementedDecoder(name) {
1557
- return () => {
1558
- throw getError("decoder", name);
1559
- };
1988
+ var memoizedGetInstructionDecoder;
1989
+ function getInstructionDecoder() {
1990
+ if (!memoizedGetInstructionDecoder) {
1991
+ memoizedGetInstructionDecoder = mapDecoder(
1992
+ getStructDecoder([
1993
+ ["programAddressIndex", getU8Decoder({ description: programAddressIndexDescription })],
1994
+ [
1995
+ "accountIndices",
1996
+ getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {
1997
+ description: accountIndicesDescription,
1998
+ size: getShortU16Decoder()
1999
+ })
2000
+ ],
2001
+ ["data", getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })]
2002
+ ]),
2003
+ // Convert an instruction to exclude optional fields if they are empty
2004
+ (instruction) => {
2005
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
2006
+ return instruction;
2007
+ }
2008
+ const { accountIndices, data, ...rest } = instruction;
2009
+ return {
2010
+ ...rest,
2011
+ ...accountIndices.length ? { accountIndices } : null,
2012
+ ...data.byteLength ? { data } : null
2013
+ };
2014
+ }
2015
+ );
2016
+ }
2017
+ return memoizedGetInstructionDecoder;
1560
2018
  }
1561
2019
  var VERSION_FLAG_MASK = 128;
1562
2020
  var BASE_CONFIG = {
@@ -1564,8 +2022,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
1564
2022
  fixedSize: null,
1565
2023
  maxSize: 1
1566
2024
  };
1567
- function deserialize(bytes3, offset = 0) {
1568
- const firstByte = bytes3[offset];
2025
+ function decode(bytes, offset = 0) {
2026
+ const firstByte = bytes[offset];
1569
2027
  if ((firstByte & VERSION_FLAG_MASK) === 0) {
1570
2028
  return ["legacy", offset];
1571
2029
  } else {
@@ -1573,7 +2031,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1573
2031
  return [version, offset + 1];
1574
2032
  }
1575
2033
  }
1576
- function serialize(value) {
2034
+ function encode(value) {
1577
2035
  if (value === "legacy") {
1578
2036
  return new Uint8Array();
1579
2037
  }
@@ -1582,148 +2040,406 @@ this.globalThis.solanaWeb3 = (function (exports) {
1582
2040
  }
1583
2041
  return new Uint8Array([value | VERSION_FLAG_MASK]);
1584
2042
  }
1585
- function getTransactionVersionCodec() {
2043
+ function getTransactionVersionDecoder() {
1586
2044
  return {
1587
2045
  ...BASE_CONFIG,
1588
- deserialize,
1589
- serialize
2046
+ decode
1590
2047
  };
1591
2048
  }
1592
- var BASE_CONFIG2 = {
1593
- description: "The wire format of a Solana transaction message" ,
1594
- fixedSize: null,
1595
- maxSize: null
1596
- };
1597
- function serialize2(compiledMessage) {
1598
- if (compiledMessage.version === "legacy") {
1599
- return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
1600
- } else {
1601
- return mapSerializer(
1602
- struct([
1603
- ...getPreludeStructSerializerTuple(),
1604
- ["addressTableLookups", getAddressTableLookupsSerializer()]
1605
- ]),
1606
- (value) => {
1607
- if (value.version === "legacy") {
1608
- return value;
1609
- }
1610
- return {
1611
- ...value,
1612
- addressTableLookups: value.addressTableLookups ?? []
1613
- };
2049
+ function getTransactionVersionEncoder() {
2050
+ return {
2051
+ ...BASE_CONFIG,
2052
+ encode
2053
+ };
2054
+ }
2055
+ var staticAccountsDescription = "A compact-array of static account addresses belonging to this transaction" ;
2056
+ var lifetimeTokenDescription = "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" ;
2057
+ var instructionsDescription = "A compact-array of instructions belonging to this transaction" ;
2058
+ var addressTableLookupsDescription = "A compact array of address table lookups belonging to this transaction" ;
2059
+ function getCompiledMessageLegacyEncoder() {
2060
+ return getStructEncoder(getPreludeStructEncoderTuple());
2061
+ }
2062
+ function getCompiledMessageVersionedEncoder() {
2063
+ return mapEncoder(
2064
+ getStructEncoder([
2065
+ ...getPreludeStructEncoderTuple(),
2066
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
2067
+ ]),
2068
+ (value) => {
2069
+ if (value.version === "legacy") {
2070
+ return value;
1614
2071
  }
1615
- ).serialize(compiledMessage);
1616
- }
2072
+ return {
2073
+ ...value,
2074
+ addressTableLookups: value.addressTableLookups ?? []
2075
+ };
2076
+ }
2077
+ );
1617
2078
  }
1618
- function getPreludeStructSerializerTuple() {
2079
+ function getPreludeStructEncoderTuple() {
1619
2080
  return [
1620
- ["version", getTransactionVersionCodec()],
1621
- ["header", getMessageHeaderCodec()],
2081
+ ["version", getTransactionVersionEncoder()],
2082
+ ["header", getMessageHeaderEncoder()],
1622
2083
  [
1623
2084
  "staticAccounts",
1624
- array(getBase58EncodedAddressCodec(), {
1625
- description: "A compact-array of static account addresses belonging to this transaction" ,
1626
- size: shortU16()
2085
+ getArrayEncoder(getAddressEncoder(), {
2086
+ description: staticAccountsDescription,
2087
+ size: getShortU16Encoder()
1627
2088
  })
1628
2089
  ],
1629
2090
  [
1630
2091
  "lifetimeToken",
1631
- string({
1632
- description: "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" ,
1633
- encoding: base58,
2092
+ getStringEncoder({
2093
+ description: lifetimeTokenDescription,
2094
+ encoding: getBase58Encoder(),
1634
2095
  size: 32
1635
2096
  })
1636
2097
  ],
1637
2098
  [
1638
2099
  "instructions",
1639
- array(getInstructionCodec(), {
1640
- description: "A compact-array of instructions belonging to this transaction" ,
1641
- size: shortU16()
2100
+ getArrayEncoder(getInstructionEncoder(), {
2101
+ description: instructionsDescription,
2102
+ size: getShortU16Encoder()
1642
2103
  })
1643
2104
  ]
1644
2105
  ];
1645
2106
  }
1646
- function getAddressTableLookupsSerializer() {
1647
- return array(getAddressTableLookupCodec(), {
1648
- ...{ description: "A compact array of address table lookups belonging to this transaction" } ,
1649
- size: shortU16()
2107
+ function getPreludeStructDecoderTuple() {
2108
+ return [
2109
+ ["version", getTransactionVersionDecoder()],
2110
+ ["header", getMessageHeaderDecoder()],
2111
+ [
2112
+ "staticAccounts",
2113
+ getArrayDecoder(getAddressDecoder(), {
2114
+ description: staticAccountsDescription,
2115
+ size: getShortU16Decoder()
2116
+ })
2117
+ ],
2118
+ [
2119
+ "lifetimeToken",
2120
+ getStringDecoder({
2121
+ description: lifetimeTokenDescription,
2122
+ encoding: getBase58Decoder(),
2123
+ size: 32
2124
+ })
2125
+ ],
2126
+ [
2127
+ "instructions",
2128
+ getArrayDecoder(getInstructionDecoder(), {
2129
+ description: instructionsDescription,
2130
+ size: getShortU16Decoder()
2131
+ })
2132
+ ],
2133
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
2134
+ ];
2135
+ }
2136
+ function getAddressTableLookupArrayEncoder() {
2137
+ return getArrayEncoder(getAddressTableLookupEncoder(), {
2138
+ description: addressTableLookupsDescription,
2139
+ size: getShortU16Encoder()
1650
2140
  });
1651
2141
  }
2142
+ function getAddressTableLookupArrayDecoder() {
2143
+ return getArrayDecoder(getAddressTableLookupDecoder(), {
2144
+ description: addressTableLookupsDescription,
2145
+ size: getShortU16Decoder()
2146
+ });
2147
+ }
2148
+ var messageDescription = "The wire format of a Solana transaction message" ;
1652
2149
  function getCompiledMessageEncoder() {
1653
2150
  return {
1654
- ...BASE_CONFIG2,
1655
- deserialize: getUnimplementedDecoder("CompiledMessage"),
1656
- serialize: serialize2
2151
+ description: messageDescription,
2152
+ encode: (compiledMessage) => {
2153
+ if (compiledMessage.version === "legacy") {
2154
+ return getCompiledMessageLegacyEncoder().encode(compiledMessage);
2155
+ } else {
2156
+ return getCompiledMessageVersionedEncoder().encode(compiledMessage);
2157
+ }
2158
+ },
2159
+ fixedSize: null,
2160
+ maxSize: null
2161
+ };
2162
+ }
2163
+ function getCompiledMessageDecoder() {
2164
+ return mapDecoder(
2165
+ getStructDecoder(getPreludeStructDecoderTuple(), {
2166
+ description: messageDescription
2167
+ }),
2168
+ ({ addressTableLookups, ...restOfMessage }) => {
2169
+ if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
2170
+ return restOfMessage;
2171
+ }
2172
+ return { ...restOfMessage, addressTableLookups };
2173
+ }
2174
+ );
2175
+ }
2176
+ var signaturesDescription = "A compact array of 64-byte, base-64 encoded Ed25519 signatures" ;
2177
+ var transactionDescription = "The wire format of a Solana transaction" ;
2178
+ function getCompiledTransactionEncoder() {
2179
+ return getStructEncoder(
2180
+ [
2181
+ [
2182
+ "signatures",
2183
+ getArrayEncoder(getBytesEncoder({ size: 64 }), {
2184
+ description: signaturesDescription,
2185
+ size: getShortU16Encoder()
2186
+ })
2187
+ ],
2188
+ ["compiledMessage", getCompiledMessageEncoder()]
2189
+ ],
2190
+ {
2191
+ description: transactionDescription
2192
+ }
2193
+ );
2194
+ }
2195
+ function getSignatureDecoder() {
2196
+ return mapDecoder(getBytesDecoder({ size: 64 }), (bytes) => bytes);
2197
+ }
2198
+ function getCompiledTransactionDecoder() {
2199
+ return getStructDecoder(
2200
+ [
2201
+ [
2202
+ "signatures",
2203
+ getArrayDecoder(getSignatureDecoder(), {
2204
+ description: signaturesDescription,
2205
+ size: getShortU16Decoder()
2206
+ })
2207
+ ],
2208
+ ["compiledMessage", getCompiledMessageDecoder()]
2209
+ ],
2210
+ {
2211
+ description: transactionDescription
2212
+ }
2213
+ );
2214
+ }
2215
+ function getTransactionEncoder() {
2216
+ return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
2217
+ }
2218
+ function getTransactionDecoder(lastValidBlockHeight) {
2219
+ return mapDecoder(
2220
+ getCompiledTransactionDecoder(),
2221
+ (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)
2222
+ );
2223
+ }
2224
+ function getTransactionCodec(lastValidBlockHeight) {
2225
+ return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));
2226
+ }
2227
+ var base58Decoder;
2228
+ function getSignatureFromTransaction(transaction) {
2229
+ if (!base58Decoder)
2230
+ base58Decoder = getBase58Decoder();
2231
+ const signatureBytes = transaction.signatures[transaction.feePayer];
2232
+ if (!signatureBytes) {
2233
+ throw new Error(
2234
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
2235
+ );
2236
+ }
2237
+ const transactionSignature = base58Decoder.decode(signatureBytes)[0];
2238
+ return transactionSignature;
2239
+ }
2240
+ async function partiallySignTransaction(keyPairs, transaction) {
2241
+ const compiledMessage = compileMessage(transaction);
2242
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
2243
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
2244
+ const publicKeySignaturePairs = await Promise.all(
2245
+ keyPairs.map(
2246
+ (keyPair) => Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])
2247
+ )
2248
+ );
2249
+ for (const [signerPublicKey, signature2] of publicKeySignaturePairs) {
2250
+ nextSignatures[signerPublicKey] = signature2;
2251
+ }
2252
+ const out = {
2253
+ ...transaction,
2254
+ signatures: nextSignatures
2255
+ };
2256
+ Object.freeze(out);
2257
+ return out;
2258
+ }
2259
+ async function signTransaction(keyPairs, transaction) {
2260
+ const out = await partiallySignTransaction(keyPairs, transaction);
2261
+ assertTransactionIsFullySigned(out);
2262
+ Object.freeze(out);
2263
+ return out;
2264
+ }
2265
+ function assertTransactionIsFullySigned(transaction) {
2266
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole2(a.role)) ?? []).map((a) => a.address);
2267
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
2268
+ requiredSigners.forEach((address2) => {
2269
+ if (!transaction.signatures[address2]) {
2270
+ throw new Error(`Transaction is missing signature for address \`${address2}\``);
2271
+ }
2272
+ });
2273
+ }
2274
+ function getBase64EncodedWireTransaction(transaction) {
2275
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
2276
+ return getBase64Decoder().decode(wireTransactionBytes)[0];
2277
+ }
2278
+
2279
+ // src/airdrop.ts
2280
+ init_env_shim();
2281
+
2282
+ // src/airdrop-confirmer.ts
2283
+ init_env_shim();
2284
+
2285
+ // src/transaction-confirmation-strategy-racer.ts
2286
+ init_env_shim();
2287
+ async function raceStrategies(signature2, config, getSpecificStrategiesForRace) {
2288
+ const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;
2289
+ callerAbortSignal?.throwIfAborted();
2290
+ const abortController = new AbortController();
2291
+ if (callerAbortSignal) {
2292
+ const handleAbort = () => {
2293
+ abortController.abort();
2294
+ };
2295
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
2296
+ }
2297
+ try {
2298
+ const specificStrategies = getSpecificStrategiesForRace({
2299
+ ...config,
2300
+ abortSignal: abortController.signal
2301
+ });
2302
+ return await Promise.race([
2303
+ getRecentSignatureConfirmationPromise({
2304
+ abortSignal: abortController.signal,
2305
+ commitment,
2306
+ signature: signature2
2307
+ }),
2308
+ ...specificStrategies
2309
+ ]);
2310
+ } finally {
2311
+ abortController.abort();
2312
+ }
2313
+ }
2314
+
2315
+ // src/transaction-confirmation-strategy-recent-signature.ts
2316
+ init_env_shim();
2317
+ function createRecentSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions) {
2318
+ return async function getRecentSignatureConfirmationPromise({
2319
+ abortSignal: callerAbortSignal,
2320
+ commitment,
2321
+ signature: signature2
2322
+ }) {
2323
+ const abortController = new AbortController();
2324
+ function handleAbort() {
2325
+ abortController.abort();
2326
+ }
2327
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
2328
+ const signatureStatusNotifications = await rpcSubscriptions.signatureNotifications(signature2, { commitment }).subscribe({ abortSignal: abortController.signal });
2329
+ const signatureDidCommitPromise = (async () => {
2330
+ for await (const signatureStatusNotification of signatureStatusNotifications) {
2331
+ if (signatureStatusNotification.value.err) {
2332
+ throw new Error(`The transaction with signature \`${signature2}\` failed.`, {
2333
+ cause: signatureStatusNotification.value.err
2334
+ });
2335
+ } else {
2336
+ return;
2337
+ }
2338
+ }
2339
+ })();
2340
+ const signatureStatusLookupPromise = (async () => {
2341
+ const { value: signatureStatusResults } = await rpc.getSignatureStatuses([signature2]).send({ abortSignal: abortController.signal });
2342
+ const signatureStatus = signatureStatusResults[0];
2343
+ if (signatureStatus && signatureStatus.confirmationStatus && commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0) {
2344
+ return;
2345
+ } else {
2346
+ await new Promise(() => {
2347
+ });
2348
+ }
2349
+ })();
2350
+ try {
2351
+ return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);
2352
+ } finally {
2353
+ abortController.abort();
2354
+ }
1657
2355
  };
1658
2356
  }
1659
- async function getCompiledMessageSignature(message, secretKey) {
1660
- const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
1661
- const signature = await signBytes(secretKey, wireMessageBytes);
1662
- return signature;
2357
+
2358
+ // src/transaction-confirmation-strategy-timeout.ts
2359
+ init_env_shim();
2360
+ async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }) {
2361
+ return await new Promise((_, reject) => {
2362
+ const handleAbort = (e3) => {
2363
+ clearTimeout(timeoutId);
2364
+ const abortError = new DOMException(e3.target.reason, "AbortError");
2365
+ reject(abortError);
2366
+ };
2367
+ callerAbortSignal.addEventListener("abort", handleAbort);
2368
+ const timeoutMs = commitment === "processed" ? 3e4 : 6e4;
2369
+ const startMs = performance.now();
2370
+ const timeoutId = (
2371
+ // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure
2372
+ // elapsed time instead of active time.
2373
+ // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
2374
+ setTimeout(() => {
2375
+ const elapsedMs = performance.now() - startMs;
2376
+ reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, "TimeoutError"));
2377
+ }, timeoutMs)
2378
+ );
2379
+ });
1663
2380
  }
1664
- async function signTransaction(keyPair, transaction) {
1665
- const compiledMessage = compileMessage(transaction);
1666
- const [signerPublicKey, signature] = await Promise.all([
1667
- getAddressFromPublicKey(keyPair.publicKey),
1668
- getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
1669
- ]);
1670
- const nextSignatures = {
1671
- ..."signatures" in transaction ? transaction.signatures : null,
1672
- ...{ [signerPublicKey]: signature }
1673
- };
1674
- const out = {
1675
- ...transaction,
1676
- signatures: nextSignatures
2381
+
2382
+ // src/airdrop-confirmer.ts
2383
+ function createDefaultSignatureOnlyRecentTransactionConfirmer({
2384
+ rpc,
2385
+ rpcSubscriptions
2386
+ }) {
2387
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
2388
+ rpc,
2389
+ rpcSubscriptions
2390
+ );
2391
+ return async function confirmSignatureOnlyRecentTransaction(config) {
2392
+ await waitForRecentTransactionConfirmationUntilTimeout({
2393
+ ...config,
2394
+ getRecentSignatureConfirmationPromise,
2395
+ getTimeoutPromise
2396
+ });
1677
2397
  };
1678
- Object.freeze(out);
1679
- return out;
1680
2398
  }
1681
- function getCompiledTransaction(transaction) {
1682
- const compiledMessage = compileMessage(transaction);
1683
- let signatures;
1684
- if ("signatures" in transaction) {
1685
- signatures = [];
1686
- for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
1687
- signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
2399
+ async function waitForRecentTransactionConfirmationUntilTimeout(config) {
2400
+ await raceStrategies(
2401
+ config.signature,
2402
+ config,
2403
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise: getTimeoutPromise2 }) {
2404
+ return [
2405
+ getTimeoutPromise2({
2406
+ abortSignal,
2407
+ commitment
2408
+ })
2409
+ ];
1688
2410
  }
1689
- } else {
1690
- signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
1691
- }
1692
- return {
1693
- compiledMessage,
1694
- signatures
1695
- };
1696
- }
1697
- var BASE_CONFIG3 = {
1698
- description: "The wire format of a Solana transaction" ,
1699
- fixedSize: null,
1700
- maxSize: null
1701
- };
1702
- function serialize3(transaction) {
1703
- const compiledTransaction = getCompiledTransaction(transaction);
1704
- return struct([
1705
- [
1706
- "signatures",
1707
- array(bytes({ size: 64 }), {
1708
- ...{ description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } ,
1709
- size: shortU16()
1710
- })
1711
- ],
1712
- ["compiledMessage", getCompiledMessageEncoder()]
1713
- ]).serialize(compiledTransaction);
2411
+ );
1714
2412
  }
1715
- function getTransactionEncoder() {
1716
- return {
1717
- ...BASE_CONFIG3,
1718
- deserialize: getUnimplementedDecoder("CompiledMessage"),
1719
- serialize: serialize3
2413
+
2414
+ // src/airdrop.ts
2415
+ function createDefaultAirdropRequester({ rpc, rpcSubscriptions }) {
2416
+ const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({
2417
+ rpc,
2418
+ rpcSubscriptions
2419
+ });
2420
+ return async function requestAirdrop(config) {
2421
+ return await requestAndConfirmAirdrop({
2422
+ ...config,
2423
+ confirmSignatureOnlyTransaction,
2424
+ rpc
2425
+ });
1720
2426
  };
1721
2427
  }
1722
- function getBase64EncodedWireTransaction(transaction) {
1723
- const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
1724
- {
1725
- return btoa(String.fromCharCode(...wireTransactionBytes));
1726
- }
2428
+ async function requestAndConfirmAirdrop({
2429
+ abortSignal,
2430
+ commitment,
2431
+ confirmSignatureOnlyTransaction,
2432
+ lamports: lamports2,
2433
+ recipientAddress,
2434
+ rpc
2435
+ }) {
2436
+ const airdropTransactionSignature = await rpc.requestAirdrop(recipientAddress, lamports2, { commitment }).send({ abortSignal });
2437
+ await confirmSignatureOnlyTransaction({
2438
+ abortSignal,
2439
+ commitment,
2440
+ signature: airdropTransactionSignature
2441
+ });
2442
+ return airdropTransactionSignature;
1727
2443
  }
1728
2444
 
1729
2445
  // src/rpc.ts
@@ -1757,62 +2473,216 @@ this.globalThis.solanaWeb3 = (function (exports) {
1757
2473
  return visitNode(params, [], onIntegerOverflow);
1758
2474
  }
1759
2475
  var KEYPATH_WILDCARD = {};
1760
- var memoizedKeypaths;
1761
- function getAllowedNumericKeypaths() {
1762
- if (!memoizedKeypaths) {
1763
- const jsonParsedTokenAccountsConfigs = [
1764
- // parsed Token/Token22 token account
1765
- ["data", "parsed", "info", "tokenAmount", "decimals"],
1766
- ["data", "parsed", "info", "tokenAmount", "uiAmount"],
1767
- ["data", "parsed", "info", "rentExemptReserve", "decimals"],
1768
- ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
1769
- ["data", "parsed", "info", "delegatedAmount", "decimals"],
1770
- ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
1771
- [
1772
- "data",
1773
- "parsed",
1774
- "info",
1775
- "extensions",
1776
- KEYPATH_WILDCARD,
1777
- "state",
1778
- "olderTransferFee",
1779
- "transferFeeBasisPoints"
1780
- ],
1781
- [
1782
- "data",
1783
- "parsed",
1784
- "info",
1785
- "extensions",
1786
- KEYPATH_WILDCARD,
1787
- "state",
1788
- "newerTransferFee",
1789
- "transferFeeBasisPoints"
2476
+ var jsonParsedTokenAccountsConfigs = [
2477
+ // parsed Token/Token22 token account
2478
+ ["data", "parsed", "info", "tokenAmount", "decimals"],
2479
+ ["data", "parsed", "info", "tokenAmount", "uiAmount"],
2480
+ ["data", "parsed", "info", "rentExemptReserve", "decimals"],
2481
+ ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
2482
+ ["data", "parsed", "info", "delegatedAmount", "decimals"],
2483
+ ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
2484
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "olderTransferFee", "transferFeeBasisPoints"],
2485
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "newerTransferFee", "transferFeeBasisPoints"],
2486
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
2487
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
2488
+ ];
2489
+ var jsonParsedAccountsConfigs = [
2490
+ ...jsonParsedTokenAccountsConfigs,
2491
+ // parsed AddressTableLookup account
2492
+ ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
2493
+ // parsed Config account
2494
+ ["data", "parsed", "info", "slashPenalty"],
2495
+ ["data", "parsed", "info", "warmupCooldownRate"],
2496
+ // parsed Token/Token22 mint account
2497
+ ["data", "parsed", "info", "decimals"],
2498
+ // parsed Token/Token22 multisig account
2499
+ ["data", "parsed", "info", "numRequiredSigners"],
2500
+ ["data", "parsed", "info", "numValidSigners"],
2501
+ // parsed Stake account
2502
+ ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
2503
+ // parsed Sysvar rent account
2504
+ ["data", "parsed", "info", "exemptionThreshold"],
2505
+ ["data", "parsed", "info", "burnPercent"],
2506
+ // parsed Vote account
2507
+ ["data", "parsed", "info", "commission"],
2508
+ ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
2509
+ ];
2510
+ var memoizedNotificationKeypaths;
2511
+ var memoizedResponseKeypaths;
2512
+ function getAllowedNumericKeypathsForNotification() {
2513
+ if (!memoizedNotificationKeypaths) {
2514
+ memoizedNotificationKeypaths = {
2515
+ accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
2516
+ blockNotifications: [
2517
+ ["value", "block", "blockTime"],
2518
+ [
2519
+ "value",
2520
+ "block",
2521
+ "transactions",
2522
+ KEYPATH_WILDCARD,
2523
+ "meta",
2524
+ "preTokenBalances",
2525
+ KEYPATH_WILDCARD,
2526
+ "accountIndex"
2527
+ ],
2528
+ [
2529
+ "value",
2530
+ "block",
2531
+ "transactions",
2532
+ KEYPATH_WILDCARD,
2533
+ "meta",
2534
+ "preTokenBalances",
2535
+ KEYPATH_WILDCARD,
2536
+ "uiTokenAmount",
2537
+ "decimals"
2538
+ ],
2539
+ [
2540
+ "value",
2541
+ "block",
2542
+ "transactions",
2543
+ KEYPATH_WILDCARD,
2544
+ "meta",
2545
+ "postTokenBalances",
2546
+ KEYPATH_WILDCARD,
2547
+ "accountIndex"
2548
+ ],
2549
+ [
2550
+ "value",
2551
+ "block",
2552
+ "transactions",
2553
+ KEYPATH_WILDCARD,
2554
+ "meta",
2555
+ "postTokenBalances",
2556
+ KEYPATH_WILDCARD,
2557
+ "uiTokenAmount",
2558
+ "decimals"
2559
+ ],
2560
+ ["value", "block", "transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2561
+ [
2562
+ "value",
2563
+ "block",
2564
+ "transactions",
2565
+ KEYPATH_WILDCARD,
2566
+ "meta",
2567
+ "innerInstructions",
2568
+ KEYPATH_WILDCARD,
2569
+ "index"
2570
+ ],
2571
+ [
2572
+ "value",
2573
+ "block",
2574
+ "transactions",
2575
+ KEYPATH_WILDCARD,
2576
+ "meta",
2577
+ "innerInstructions",
2578
+ KEYPATH_WILDCARD,
2579
+ "instructions",
2580
+ KEYPATH_WILDCARD,
2581
+ "programIdIndex"
2582
+ ],
2583
+ [
2584
+ "value",
2585
+ "block",
2586
+ "transactions",
2587
+ KEYPATH_WILDCARD,
2588
+ "meta",
2589
+ "innerInstructions",
2590
+ KEYPATH_WILDCARD,
2591
+ "instructions",
2592
+ KEYPATH_WILDCARD,
2593
+ "accounts",
2594
+ KEYPATH_WILDCARD
2595
+ ],
2596
+ [
2597
+ "value",
2598
+ "block",
2599
+ "transactions",
2600
+ KEYPATH_WILDCARD,
2601
+ "transaction",
2602
+ "message",
2603
+ "addressTableLookups",
2604
+ KEYPATH_WILDCARD,
2605
+ "writableIndexes",
2606
+ KEYPATH_WILDCARD
2607
+ ],
2608
+ [
2609
+ "value",
2610
+ "block",
2611
+ "transactions",
2612
+ KEYPATH_WILDCARD,
2613
+ "transaction",
2614
+ "message",
2615
+ "addressTableLookups",
2616
+ KEYPATH_WILDCARD,
2617
+ "readonlyIndexes",
2618
+ KEYPATH_WILDCARD
2619
+ ],
2620
+ [
2621
+ "value",
2622
+ "block",
2623
+ "transactions",
2624
+ KEYPATH_WILDCARD,
2625
+ "transaction",
2626
+ "message",
2627
+ "instructions",
2628
+ KEYPATH_WILDCARD,
2629
+ "programIdIndex"
2630
+ ],
2631
+ [
2632
+ "value",
2633
+ "block",
2634
+ "transactions",
2635
+ KEYPATH_WILDCARD,
2636
+ "transaction",
2637
+ "message",
2638
+ "instructions",
2639
+ KEYPATH_WILDCARD,
2640
+ "accounts",
2641
+ KEYPATH_WILDCARD
2642
+ ],
2643
+ [
2644
+ "value",
2645
+ "block",
2646
+ "transactions",
2647
+ KEYPATH_WILDCARD,
2648
+ "transaction",
2649
+ "message",
2650
+ "header",
2651
+ "numReadonlySignedAccounts"
2652
+ ],
2653
+ [
2654
+ "value",
2655
+ "block",
2656
+ "transactions",
2657
+ KEYPATH_WILDCARD,
2658
+ "transaction",
2659
+ "message",
2660
+ "header",
2661
+ "numReadonlyUnsignedAccounts"
2662
+ ],
2663
+ [
2664
+ "value",
2665
+ "block",
2666
+ "transactions",
2667
+ KEYPATH_WILDCARD,
2668
+ "transaction",
2669
+ "message",
2670
+ "header",
2671
+ "numRequiredSignatures"
2672
+ ],
2673
+ ["value", "block", "rewards", KEYPATH_WILDCARD, "commission"]
1790
2674
  ],
1791
- ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
1792
- ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
1793
- ];
1794
- const jsonParsedAccountsConfigs = [
1795
- ...jsonParsedTokenAccountsConfigs,
1796
- // parsed AddressTableLookup account
1797
- ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
1798
- // parsed Config account
1799
- ["data", "parsed", "info", "slashPenalty"],
1800
- ["data", "parsed", "info", "warmupCooldownRate"],
1801
- // parsed Token/Token22 mint account
1802
- ["data", "parsed", "info", "decimals"],
1803
- // parsed Token/Token22 multisig account
1804
- ["data", "parsed", "info", "numRequiredSigners"],
1805
- ["data", "parsed", "info", "numValidSigners"],
1806
- // parsed Stake account
1807
- ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
1808
- // parsed Sysvar rent account
1809
- ["data", "parsed", "info", "exemptionThreshold"],
1810
- ["data", "parsed", "info", "burnPercent"],
1811
- // parsed Vote account
1812
- ["data", "parsed", "info", "commission"],
1813
- ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
1814
- ];
1815
- memoizedKeypaths = {
2675
+ programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [
2676
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2677
+ [KEYPATH_WILDCARD, "account", ...c]
2678
+ ])
2679
+ };
2680
+ }
2681
+ return memoizedNotificationKeypaths;
2682
+ }
2683
+ function getAllowedNumericKeypathsForResponse() {
2684
+ if (!memoizedResponseKeypaths) {
2685
+ memoizedResponseKeypaths = {
1816
2686
  getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
1817
2687
  getBlock: [
1818
2688
  ["blockTime"],
@@ -1988,7 +2858,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1988
2858
  simulateTransaction: jsonParsedAccountsConfigs.map((c) => ["value", "accounts", KEYPATH_WILDCARD, ...c])
1989
2859
  };
1990
2860
  }
1991
- return memoizedKeypaths;
2861
+ return memoizedResponseKeypaths;
1992
2862
  }
1993
2863
  function getNextAllowedKeypaths(keyPaths, property) {
1994
2864
  return keyPaths.filter((keyPath) => keyPath[0] === KEYPATH_WILDCARD && typeof property === "number" || keyPath[0] === property).map((keyPath) => keyPath.slice(1));
@@ -2016,7 +2886,11 @@ this.globalThis.solanaWeb3 = (function (exports) {
2016
2886
  }
2017
2887
  }
2018
2888
  function patchResponseForSolanaLabsRpc(rawResponse, methodName) {
2019
- const allowedKeypaths = methodName ? getAllowedNumericKeypaths()[methodName] : void 0;
2889
+ const allowedKeypaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : void 0;
2890
+ return visitNode2(rawResponse, allowedKeypaths ?? []);
2891
+ }
2892
+ function patchResponseForSolanaLabsRpcSubscriptions(rawResponse, methodName) {
2893
+ const allowedKeypaths = methodName ? getAllowedNumericKeypathsForNotification()[methodName] : void 0;
2020
2894
  return visitNode2(rawResponse, allowedKeypaths ?? []);
2021
2895
  }
2022
2896
  function createSolanaRpcApi(config) {
@@ -2045,6 +2919,36 @@ this.globalThis.solanaWeb3 = (function (exports) {
2045
2919
  }
2046
2920
  });
2047
2921
  }
2922
+ function createSolanaRpcSubscriptionsApi(config) {
2923
+ return new Proxy({}, {
2924
+ defineProperty() {
2925
+ return false;
2926
+ },
2927
+ deleteProperty() {
2928
+ return false;
2929
+ },
2930
+ get(...args) {
2931
+ const [_, p] = args;
2932
+ const notificationName = p.toString();
2933
+ return function(...rawParams) {
2934
+ const handleIntegerOverflow = config?.onIntegerOverflow;
2935
+ const params = patchParamsForSolanaLabsRpc(
2936
+ rawParams,
2937
+ handleIntegerOverflow ? (keyPath, value) => handleIntegerOverflow(notificationName, keyPath, value) : void 0
2938
+ );
2939
+ return {
2940
+ params,
2941
+ responseProcessor: (rawResponse) => patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName),
2942
+ subscribeMethodName: notificationName.replace(/Notifications$/, "Subscribe"),
2943
+ unsubscribeMethodName: notificationName.replace(/Notifications$/, "Unsubscribe")
2944
+ };
2945
+ };
2946
+ }
2947
+ });
2948
+ }
2949
+ function createSolanaRpcSubscriptionsApi_UNSTABLE(config) {
2950
+ return createSolanaRpcSubscriptionsApi(config);
2951
+ }
2048
2952
 
2049
2953
  // ../rpc-transport/dist/index.browser.js
2050
2954
  init_env_shim();
@@ -2073,24 +2977,109 @@ this.globalThis.solanaWeb3 = (function (exports) {
2073
2977
  params
2074
2978
  };
2075
2979
  }
2076
- function createPendingRpcRequest(rpcConfig, pendingRequest) {
2980
+ function createPendingRpcRequest(rpcConfig, pendingRequest) {
2981
+ return {
2982
+ async send(options) {
2983
+ const { methodName, params, responseProcessor } = pendingRequest;
2984
+ const payload = createJsonRpcMessage(methodName, params);
2985
+ const response = await rpcConfig.transport({
2986
+ payload,
2987
+ signal: options?.abortSignal
2988
+ });
2989
+ if ("error" in response) {
2990
+ throw new SolanaJsonRpcError(response.error);
2991
+ } else {
2992
+ return responseProcessor ? responseProcessor(response.result) : response.result;
2993
+ }
2994
+ }
2995
+ };
2996
+ }
2997
+ function makeProxy(rpcConfig) {
2998
+ return new Proxy(rpcConfig.api, {
2999
+ defineProperty() {
3000
+ return false;
3001
+ },
3002
+ deleteProperty() {
3003
+ return false;
3004
+ },
3005
+ get(target, p, receiver) {
3006
+ return function(...rawParams) {
3007
+ const methodName = p.toString();
3008
+ const createRpcRequest = Reflect.get(target, methodName, receiver);
3009
+ const newRequest = createRpcRequest ? createRpcRequest(...rawParams) : { methodName, params: rawParams };
3010
+ return createPendingRpcRequest(rpcConfig, newRequest);
3011
+ };
3012
+ }
3013
+ });
3014
+ }
3015
+ function createJsonRpc(rpcConfig) {
3016
+ return makeProxy(rpcConfig);
3017
+ }
3018
+ function registerIterableCleanup(iterable, cleanupFn) {
3019
+ (async () => {
3020
+ try {
3021
+ for await (const _ of iterable)
3022
+ ;
3023
+ } catch {
3024
+ } finally {
3025
+ cleanupFn();
3026
+ }
3027
+ })();
3028
+ }
3029
+ function createPendingRpcSubscription(rpcConfig, { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }) {
2077
3030
  return {
2078
- async send(options) {
2079
- const { methodName, params, responseProcessor } = pendingRequest;
2080
- const payload = createJsonRpcMessage(methodName, params);
2081
- const response = await rpcConfig.transport({
2082
- payload,
2083
- signal: options?.abortSignal
3031
+ async subscribe({ abortSignal }) {
3032
+ abortSignal.throwIfAborted();
3033
+ let subscriptionId;
3034
+ function handleCleanup() {
3035
+ if (subscriptionId !== void 0) {
3036
+ const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);
3037
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {
3038
+ connectionAbortController.abort();
3039
+ });
3040
+ } else {
3041
+ connectionAbortController.abort();
3042
+ }
3043
+ }
3044
+ abortSignal.addEventListener("abort", handleCleanup);
3045
+ const connectionAbortController = new AbortController();
3046
+ const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);
3047
+ const connection = await rpcConfig.transport({
3048
+ payload: subscribeMessage,
3049
+ signal: connectionAbortController.signal
2084
3050
  });
2085
- if ("error" in response) {
2086
- throw new SolanaJsonRpcError(response.error);
2087
- } else {
2088
- return responseProcessor ? responseProcessor(response.result) : response.result;
3051
+ function handleConnectionCleanup() {
3052
+ abortSignal.removeEventListener("abort", handleCleanup);
2089
3053
  }
3054
+ registerIterableCleanup(connection, handleConnectionCleanup);
3055
+ for await (const message of connection) {
3056
+ if ("id" in message && message.id === subscribeMessage.id) {
3057
+ if ("error" in message) {
3058
+ throw new SolanaJsonRpcError(message.error);
3059
+ } else {
3060
+ subscriptionId = message.result;
3061
+ break;
3062
+ }
3063
+ }
3064
+ }
3065
+ if (subscriptionId == null) {
3066
+ throw new Error("Failed to obtain a subscription id from the server");
3067
+ }
3068
+ return {
3069
+ async *[Symbol.asyncIterator]() {
3070
+ for await (const message of connection) {
3071
+ if (!("params" in message) || message.params.subscription !== subscriptionId) {
3072
+ continue;
3073
+ }
3074
+ const notification = message.params.result;
3075
+ yield responseProcessor ? responseProcessor(notification) : notification;
3076
+ }
3077
+ }
3078
+ };
2090
3079
  }
2091
3080
  };
2092
3081
  }
2093
- function makeProxy(rpcConfig) {
3082
+ function makeProxy2(rpcConfig) {
2094
3083
  return new Proxy(rpcConfig.api, {
2095
3084
  defineProperty() {
2096
3085
  return false;
@@ -2101,17 +3090,26 @@ this.globalThis.solanaWeb3 = (function (exports) {
2101
3090
  get(target, p, receiver) {
2102
3091
  return function(...rawParams) {
2103
3092
  const methodName = p.toString();
2104
- const createRpcRequest = Reflect.get(target, methodName, receiver);
2105
- const newRequest = createRpcRequest ? createRpcRequest(...rawParams) : { methodName, params: rawParams };
2106
- return createPendingRpcRequest(rpcConfig, newRequest);
3093
+ const createRpcSubscription = Reflect.get(target, methodName, receiver);
3094
+ if (p.toString().endsWith("Notifications") === false && !createRpcSubscription) {
3095
+ throw new Error(
3096
+ "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."
3097
+ );
3098
+ }
3099
+ const newRequest = createRpcSubscription ? createRpcSubscription(...rawParams) : {
3100
+ params: rawParams,
3101
+ subscribeMethodName: methodName.replace(/Notifications$/, "Subscribe"),
3102
+ unsubscribeMethodName: methodName.replace(/Notifications$/, "Unsubscribe")
3103
+ };
3104
+ return createPendingRpcSubscription(rpcConfig, newRequest);
2107
3105
  };
2108
3106
  }
2109
3107
  });
2110
3108
  }
2111
- function createJsonRpc(rpcConfig) {
2112
- return makeProxy(rpcConfig);
3109
+ function createJsonSubscriptionRpc(rpcConfig) {
3110
+ return makeProxy2(rpcConfig);
2113
3111
  }
2114
- var e = globalThis.fetch;
3112
+ var e2 = globalThis.fetch;
2115
3113
  var SolanaHttpError = class extends Error {
2116
3114
  constructor(details) {
2117
3115
  super(`HTTP error (${details.statusCode}): ${details.message}`);
@@ -2170,16 +3168,10 @@ this.globalThis.solanaWeb3 = (function (exports) {
2170
3168
  }
2171
3169
  return out;
2172
3170
  }
2173
- function createHttpTransport({ httpAgentNodeOnly, headers, url }) {
3171
+ function createHttpTransport({ headers, url }) {
2174
3172
  if (headers) {
2175
3173
  assertIsAllowedHttpRequestHeaders(headers);
2176
3174
  }
2177
- const agent = void 0;
2178
- if (httpAgentNodeOnly != null) {
2179
- console.warn(
2180
- "createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ignored; HTTP agents are only usable in Node environments."
2181
- );
2182
- }
2183
3175
  const customHeaders = headers && normalizeHeaders(headers);
2184
3176
  return async function makeHttpRequest({
2185
3177
  payload,
@@ -2187,7 +3179,6 @@ this.globalThis.solanaWeb3 = (function (exports) {
2187
3179
  }) {
2188
3180
  const body = JSON.stringify(payload);
2189
3181
  const requestInfo = {
2190
- agent,
2191
3182
  body,
2192
3183
  headers: {
2193
3184
  ...customHeaders,
@@ -2199,7 +3190,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2199
3190
  method: "POST",
2200
3191
  signal
2201
3192
  };
2202
- const response = await e(url, requestInfo);
3193
+ const response = await e2(url, requestInfo);
2203
3194
  if (!response.ok) {
2204
3195
  throw new SolanaHttpError({
2205
3196
  message: response.statusText,
@@ -2209,6 +3200,175 @@ this.globalThis.solanaWeb3 = (function (exports) {
2209
3200
  return await response.json();
2210
3201
  };
2211
3202
  }
3203
+ var e22 = globalThis.WebSocket;
3204
+ var EXPLICIT_ABORT_TOKEN = Symbol(
3205
+ "This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user"
3206
+ );
3207
+ async function createWebSocketConnection({
3208
+ sendBufferHighWatermark,
3209
+ signal,
3210
+ url
3211
+ }) {
3212
+ return new Promise((resolve, reject) => {
3213
+ signal.addEventListener("abort", handleAbort, { once: true });
3214
+ const iteratorState = /* @__PURE__ */ new Map();
3215
+ function errorAndClearAllIteratorStates(reason) {
3216
+ const errorCallbacks = [...iteratorState.values()].filter((state) => state.__hasPolled).map(({ onError }) => onError);
3217
+ iteratorState.clear();
3218
+ errorCallbacks.forEach((cb) => {
3219
+ try {
3220
+ cb(reason);
3221
+ } catch {
3222
+ }
3223
+ });
3224
+ }
3225
+ function handleAbort() {
3226
+ errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);
3227
+ if (webSocket.readyState !== e22.CLOSED && webSocket.readyState !== e22.CLOSING) {
3228
+ webSocket.close(1e3);
3229
+ }
3230
+ }
3231
+ function handleClose(ev) {
3232
+ bufferDrainWatcher?.onCancel();
3233
+ signal.removeEventListener("abort", handleAbort);
3234
+ webSocket.removeEventListener("close", handleClose);
3235
+ webSocket.removeEventListener("error", handleError);
3236
+ webSocket.removeEventListener("open", handleOpen);
3237
+ webSocket.removeEventListener("message", handleMessage);
3238
+ errorAndClearAllIteratorStates(ev);
3239
+ }
3240
+ function handleError(ev) {
3241
+ if (!hasConnected) {
3242
+ reject(
3243
+ // TODO: Coded error
3244
+ new Error("WebSocket failed to connect", { cause: ev })
3245
+ );
3246
+ }
3247
+ }
3248
+ let hasConnected = false;
3249
+ let bufferDrainWatcher;
3250
+ function handleOpen() {
3251
+ hasConnected = true;
3252
+ resolve({
3253
+ async send(payload) {
3254
+ const message = JSON.stringify(payload);
3255
+ if (!bufferDrainWatcher && webSocket.readyState === e22.OPEN && webSocket.bufferedAmount > sendBufferHighWatermark) {
3256
+ let onCancel;
3257
+ const promise = new Promise((resolve2, reject2) => {
3258
+ const intervalId = setInterval(() => {
3259
+ if (webSocket.readyState !== e22.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
3260
+ clearInterval(intervalId);
3261
+ bufferDrainWatcher = void 0;
3262
+ resolve2();
3263
+ }
3264
+ }, 16);
3265
+ onCancel = () => {
3266
+ bufferDrainWatcher = void 0;
3267
+ clearInterval(intervalId);
3268
+ reject2(
3269
+ // TODO: Coded error
3270
+ new Error("WebSocket was closed before payload could be sent")
3271
+ );
3272
+ };
3273
+ });
3274
+ bufferDrainWatcher = {
3275
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3276
+ // @ts-ignore
3277
+ onCancel,
3278
+ promise
3279
+ };
3280
+ }
3281
+ if (bufferDrainWatcher) {
3282
+ await bufferDrainWatcher.promise;
3283
+ }
3284
+ webSocket.send(message);
3285
+ },
3286
+ async *[Symbol.asyncIterator]() {
3287
+ const iteratorKey = Symbol();
3288
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
3289
+ try {
3290
+ while (true) {
3291
+ const state = iteratorState.get(iteratorKey);
3292
+ if (!state) {
3293
+ throw new Error("Invariant: WebSocket message iterator is missing state storage");
3294
+ }
3295
+ if (state.__hasPolled) {
3296
+ throw new Error(
3297
+ "Invariant: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise"
3298
+ );
3299
+ }
3300
+ const queuedMessages = state.queuedMessages;
3301
+ if (queuedMessages.length) {
3302
+ state.queuedMessages = [];
3303
+ yield* queuedMessages;
3304
+ } else {
3305
+ try {
3306
+ yield await new Promise((resolve2, reject2) => {
3307
+ iteratorState.set(iteratorKey, {
3308
+ __hasPolled: true,
3309
+ onError: reject2,
3310
+ onMessage: resolve2
3311
+ });
3312
+ });
3313
+ } catch (e3) {
3314
+ if (e3 === EXPLICIT_ABORT_TOKEN) {
3315
+ return;
3316
+ } else {
3317
+ throw new Error("WebSocket connection closed", { cause: e3 });
3318
+ }
3319
+ }
3320
+ }
3321
+ }
3322
+ } finally {
3323
+ iteratorState.delete(iteratorKey);
3324
+ }
3325
+ }
3326
+ });
3327
+ }
3328
+ function handleMessage({ data }) {
3329
+ const message = JSON.parse(data);
3330
+ iteratorState.forEach((state, iteratorKey) => {
3331
+ if (state.__hasPolled) {
3332
+ const { onMessage } = state;
3333
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
3334
+ onMessage(message);
3335
+ } else {
3336
+ state.queuedMessages.push(message);
3337
+ }
3338
+ });
3339
+ }
3340
+ const webSocket = new e22(url);
3341
+ webSocket.addEventListener("close", handleClose);
3342
+ webSocket.addEventListener("error", handleError);
3343
+ webSocket.addEventListener("open", handleOpen);
3344
+ webSocket.addEventListener("message", handleMessage);
3345
+ });
3346
+ }
3347
+ function createWebSocketTransport({ sendBufferHighWatermark, url }) {
3348
+ if (/^wss?:/i.test(url) === false) {
3349
+ const protocolMatch = url.match(/^([^:]+):/);
3350
+ throw new DOMException(
3351
+ 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.`
3352
+ );
3353
+ }
3354
+ return async function sendWebSocketMessage({ payload, signal }) {
3355
+ signal?.throwIfAborted();
3356
+ const connection = await createWebSocketConnection({
3357
+ sendBufferHighWatermark,
3358
+ signal,
3359
+ url
3360
+ });
3361
+ signal?.throwIfAborted();
3362
+ await connection.send(payload);
3363
+ return {
3364
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
3365
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection)
3366
+ };
3367
+ };
3368
+ }
3369
+
3370
+ // src/rpc.ts
3371
+ var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
2212
3372
 
2213
3373
  // src/rpc-default-config.ts
2214
3374
  init_env_shim();
@@ -2250,6 +3410,197 @@ this.globalThis.solanaWeb3 = (function (exports) {
2250
3410
  }
2251
3411
  };
2252
3412
 
3413
+ // src/rpc-subscription-coalescer.ts
3414
+ init_env_shim();
3415
+
3416
+ // src/cached-abortable-iterable.ts
3417
+ init_env_shim();
3418
+ function registerIterableCleanup2(iterable, cleanupFn) {
3419
+ (async () => {
3420
+ try {
3421
+ for await (const _ of iterable)
3422
+ ;
3423
+ } catch {
3424
+ } finally {
3425
+ cleanupFn();
3426
+ }
3427
+ })();
3428
+ }
3429
+ function getCachedAbortableIterableFactory({
3430
+ getAbortSignalFromInputArgs,
3431
+ getCacheEntryMissingError,
3432
+ getCacheKeyFromInputArgs,
3433
+ onCacheHit,
3434
+ onCreateIterable
3435
+ }) {
3436
+ const cache = /* @__PURE__ */ new Map();
3437
+ function getCacheEntryOrThrow(cacheKey) {
3438
+ const currentCacheEntry = cache.get(cacheKey);
3439
+ if (!currentCacheEntry) {
3440
+ throw getCacheEntryMissingError(cacheKey);
3441
+ }
3442
+ return currentCacheEntry;
3443
+ }
3444
+ return async (...args) => {
3445
+ const cacheKey = getCacheKeyFromInputArgs(...args);
3446
+ const signal = getAbortSignalFromInputArgs(...args);
3447
+ if (cacheKey === void 0) {
3448
+ return await onCreateIterable(signal, ...args);
3449
+ }
3450
+ const cleanup = () => {
3451
+ cache.delete(cacheKey);
3452
+ signal.removeEventListener("abort", handleAbort);
3453
+ };
3454
+ const handleAbort = () => {
3455
+ const cacheEntry = getCacheEntryOrThrow(cacheKey);
3456
+ if (cacheEntry.purgeScheduled !== true) {
3457
+ cacheEntry.purgeScheduled = true;
3458
+ globalThis.queueMicrotask(() => {
3459
+ cacheEntry.purgeScheduled = false;
3460
+ if (cacheEntry.referenceCount === 0) {
3461
+ cacheEntry.abortController.abort();
3462
+ cleanup();
3463
+ }
3464
+ });
3465
+ }
3466
+ cacheEntry.referenceCount--;
3467
+ };
3468
+ signal.addEventListener("abort", handleAbort);
3469
+ try {
3470
+ const cacheEntry = cache.get(cacheKey);
3471
+ if (!cacheEntry) {
3472
+ const singletonAbortController = new AbortController();
3473
+ const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);
3474
+ const newCacheEntry = {
3475
+ abortController: singletonAbortController,
3476
+ iterable: newIterablePromise,
3477
+ purgeScheduled: false,
3478
+ referenceCount: 1
3479
+ };
3480
+ cache.set(cacheKey, newCacheEntry);
3481
+ const newIterable = await newIterablePromise;
3482
+ registerIterableCleanup2(newIterable, cleanup);
3483
+ newCacheEntry.iterable = newIterable;
3484
+ return newIterable;
3485
+ } else {
3486
+ cacheEntry.referenceCount++;
3487
+ const iterableOrIterablePromise = cacheEntry.iterable;
3488
+ const cachedIterable = "then" in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;
3489
+ await onCacheHit(cachedIterable, ...args);
3490
+ return cachedIterable;
3491
+ }
3492
+ } catch (e3) {
3493
+ cleanup();
3494
+ throw e3;
3495
+ }
3496
+ };
3497
+ }
3498
+
3499
+ // src/rpc-subscription-coalescer.ts
3500
+ var EXPLICIT_ABORT_TOKEN2 = Symbol(
3501
+ "This symbol is thrown from a subscription's iterator when the subscription is explicitly aborted by the user"
3502
+ );
3503
+ function registerIterableCleanup3(iterable, cleanupFn) {
3504
+ (async () => {
3505
+ try {
3506
+ for await (const _ of iterable)
3507
+ ;
3508
+ } catch {
3509
+ } finally {
3510
+ cleanupFn();
3511
+ }
3512
+ })();
3513
+ }
3514
+ function getRpcSubscriptionsWithSubscriptionCoalescing({
3515
+ getDeduplicationKey,
3516
+ rpcSubscriptions
3517
+ }) {
3518
+ const cache = /* @__PURE__ */ new Map();
3519
+ return new Proxy(rpcSubscriptions, {
3520
+ defineProperty() {
3521
+ return false;
3522
+ },
3523
+ deleteProperty() {
3524
+ return false;
3525
+ },
3526
+ get(target, p, receiver) {
3527
+ const subscriptionMethod = Reflect.get(target, p, receiver);
3528
+ if (typeof subscriptionMethod !== "function") {
3529
+ return subscriptionMethod;
3530
+ }
3531
+ return function(...rawParams) {
3532
+ const deduplicationKey = getDeduplicationKey(p, rawParams);
3533
+ if (deduplicationKey === void 0) {
3534
+ return subscriptionMethod(...rawParams);
3535
+ }
3536
+ if (cache.has(deduplicationKey)) {
3537
+ return cache.get(deduplicationKey);
3538
+ }
3539
+ const iterableFactory = getCachedAbortableIterableFactory({
3540
+ getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,
3541
+ getCacheEntryMissingError(deduplicationKey2) {
3542
+ return new Error(
3543
+ `Found no cache entry for subscription with deduplication key \`${deduplicationKey2?.toString()}\``
3544
+ );
3545
+ },
3546
+ getCacheKeyFromInputArgs: () => deduplicationKey,
3547
+ async onCacheHit(_iterable, _config) {
3548
+ },
3549
+ async onCreateIterable(abortSignal, config) {
3550
+ const pendingSubscription2 = subscriptionMethod(
3551
+ ...rawParams
3552
+ );
3553
+ const iterable = await pendingSubscription2.subscribe({
3554
+ ...config,
3555
+ abortSignal
3556
+ });
3557
+ registerIterableCleanup3(iterable, () => {
3558
+ cache.delete(deduplicationKey);
3559
+ });
3560
+ return iterable;
3561
+ }
3562
+ });
3563
+ const pendingSubscription = {
3564
+ async subscribe(...args) {
3565
+ const iterable = await iterableFactory(...args);
3566
+ const { abortSignal } = args[0];
3567
+ let abortPromise;
3568
+ return {
3569
+ ...iterable,
3570
+ async *[Symbol.asyncIterator]() {
3571
+ abortPromise || (abortPromise = abortSignal.aborted ? Promise.reject(EXPLICIT_ABORT_TOKEN2) : new Promise((_, reject) => {
3572
+ abortSignal.addEventListener("abort", () => {
3573
+ reject(EXPLICIT_ABORT_TOKEN2);
3574
+ });
3575
+ }));
3576
+ try {
3577
+ const iterator = iterable[Symbol.asyncIterator]();
3578
+ while (true) {
3579
+ const iteratorResult = await Promise.race([iterator.next(), abortPromise]);
3580
+ if (iteratorResult.done) {
3581
+ return;
3582
+ } else {
3583
+ yield iteratorResult.value;
3584
+ }
3585
+ }
3586
+ } catch (e3) {
3587
+ if (e3 === EXPLICIT_ABORT_TOKEN2) {
3588
+ return;
3589
+ }
3590
+ cache.delete(deduplicationKey);
3591
+ throw e3;
3592
+ }
3593
+ }
3594
+ };
3595
+ }
3596
+ };
3597
+ cache.set(deduplicationKey, pendingSubscription);
3598
+ return pendingSubscription;
3599
+ };
3600
+ }
3601
+ });
3602
+ }
3603
+
2253
3604
  // src/rpc.ts
2254
3605
  function createSolanaRpc(config) {
2255
3606
  return createJsonRpc({
@@ -2257,6 +3608,24 @@ this.globalThis.solanaWeb3 = (function (exports) {
2257
3608
  api: createSolanaRpcApi(DEFAULT_RPC_CONFIG)
2258
3609
  });
2259
3610
  }
3611
+ function createSolanaRpcSubscriptions(config) {
3612
+ return pipe(
3613
+ createJsonSubscriptionRpc({
3614
+ ...config,
3615
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
3616
+ }),
3617
+ (rpcSubscriptions) => getRpcSubscriptionsWithSubscriptionCoalescing({
3618
+ getDeduplicationKey: (...args) => (0, import_fast_stable_stringify.default)(args),
3619
+ rpcSubscriptions
3620
+ })
3621
+ );
3622
+ }
3623
+ function createSolanaRpcSubscriptions_UNSTABLE(config) {
3624
+ return createJsonSubscriptionRpc({
3625
+ ...config,
3626
+ api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG)
3627
+ });
3628
+ }
2260
3629
 
2261
3630
  // src/rpc-transport.ts
2262
3631
  init_env_shim();
@@ -2316,14 +3685,15 @@ this.globalThis.solanaWeb3 = (function (exports) {
2316
3685
 
2317
3686
  // src/rpc-request-deduplication.ts
2318
3687
  init_env_shim();
2319
- var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
2320
- function getSolanaRpcPayloadDeduplicationKey(payload) {
3688
+ var import_fast_stable_stringify2 = __toESM(require_fast_stable_stringify(), 1);
3689
+ function isJsonRpcPayload(payload) {
2321
3690
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
2322
- return;
2323
- }
2324
- if ("jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && "params" in payload) {
2325
- return (0, import_fast_stable_stringify.default)([payload.method, payload.params]);
3691
+ return false;
2326
3692
  }
3693
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
3694
+ }
3695
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
3696
+ return isJsonRpcPayload(payload) ? (0, import_fast_stable_stringify2.default)([payload.method, payload.params]) : void 0;
2327
3697
  }
2328
3698
 
2329
3699
  // src/rpc-transport.ts
@@ -2335,7 +3705,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2335
3705
  return out;
2336
3706
  }
2337
3707
  function createDefaultRpcTransport(config) {
2338
- return getRpcTransportWithRequestCoalescing(
3708
+ return pipe(
2339
3709
  createHttpTransport({
2340
3710
  ...config,
2341
3711
  headers: {
@@ -2346,39 +3716,467 @@ this.globalThis.solanaWeb3 = (function (exports) {
2346
3716
  }
2347
3717
  }
2348
3718
  }),
2349
- getSolanaRpcPayloadDeduplicationKey
3719
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
3720
+ );
3721
+ }
3722
+
3723
+ // src/rpc-websocket-transport.ts
3724
+ init_env_shim();
3725
+
3726
+ // src/rpc-websocket-autopinger.ts
3727
+ init_env_shim();
3728
+ var PING_PAYLOAD = {
3729
+ jsonrpc: "2.0",
3730
+ method: "ping"
3731
+ };
3732
+ function getWebSocketTransportWithAutoping({ intervalMs, transport }) {
3733
+ const pingableConnections = /* @__PURE__ */ new Map();
3734
+ return async (...args) => {
3735
+ const connection = await transport(...args);
3736
+ let intervalId;
3737
+ function sendPing() {
3738
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);
3739
+ }
3740
+ function restartPingTimer() {
3741
+ clearInterval(intervalId);
3742
+ intervalId = setInterval(sendPing, intervalMs);
3743
+ }
3744
+ if (pingableConnections.has(connection) === false) {
3745
+ pingableConnections.set(connection, {
3746
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
3747
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (...args2) => {
3748
+ restartPingTimer();
3749
+ return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args2);
3750
+ }
3751
+ });
3752
+ (async () => {
3753
+ try {
3754
+ for await (const _ of connection) {
3755
+ restartPingTimer();
3756
+ }
3757
+ } catch {
3758
+ } finally {
3759
+ pingableConnections.delete(connection);
3760
+ clearInterval(intervalId);
3761
+ if (handleOffline) {
3762
+ globalThis.window.removeEventListener("offline", handleOffline);
3763
+ }
3764
+ if (handleOnline) {
3765
+ globalThis.window.removeEventListener("online", handleOnline);
3766
+ }
3767
+ }
3768
+ })();
3769
+ if (globalThis.navigator.onLine) {
3770
+ restartPingTimer();
3771
+ }
3772
+ let handleOffline;
3773
+ let handleOnline;
3774
+ {
3775
+ handleOffline = () => {
3776
+ clearInterval(intervalId);
3777
+ };
3778
+ handleOnline = () => {
3779
+ sendPing();
3780
+ restartPingTimer();
3781
+ };
3782
+ globalThis.window.addEventListener("offline", handleOffline);
3783
+ globalThis.window.addEventListener("online", handleOnline);
3784
+ }
3785
+ }
3786
+ return pingableConnections.get(connection);
3787
+ };
3788
+ }
3789
+
3790
+ // src/rpc-websocket-connection-sharding.ts
3791
+ init_env_shim();
3792
+ var NULL_SHARD_CACHE_KEY = Symbol(
3793
+ "Cache key to use when there is no connection sharding strategy"
3794
+ );
3795
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
3796
+ return getCachedAbortableIterableFactory({
3797
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
3798
+ getCacheEntryMissingError(shardKey) {
3799
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
3800
+ },
3801
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
3802
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
3803
+ onCreateIterable: (abortSignal, config) => transport({
3804
+ ...config,
3805
+ signal: abortSignal
3806
+ })
3807
+ });
3808
+ }
3809
+
3810
+ // src/rpc-websocket-transport.ts
3811
+ function createDefaultRpcSubscriptionsTransport(config) {
3812
+ const { getShard, intervalMs, ...rest } = config;
3813
+ return pipe(
3814
+ createWebSocketTransport({
3815
+ ...rest,
3816
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
3817
+ 131072
3818
+ }),
3819
+ (transport) => getWebSocketTransportWithAutoping({
3820
+ intervalMs: intervalMs ?? 5e3,
3821
+ transport
3822
+ }),
3823
+ (transport) => getWebSocketTransportWithConnectionSharding({
3824
+ getShard,
3825
+ transport
3826
+ })
3827
+ );
3828
+ }
3829
+
3830
+ // src/send-transaction.ts
3831
+ init_env_shim();
3832
+
3833
+ // src/transaction-confirmation.ts
3834
+ init_env_shim();
3835
+
3836
+ // src/transaction-confirmation-strategy-blockheight.ts
3837
+ init_env_shim();
3838
+ function createBlockHeightExceedencePromiseFactory(rpcSubscriptions) {
3839
+ return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {
3840
+ const abortController = new AbortController();
3841
+ function handleAbort() {
3842
+ abortController.abort();
3843
+ }
3844
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3845
+ const slotNotifications = await rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal });
3846
+ try {
3847
+ for await (const slotNotification of slotNotifications) {
3848
+ if (slotNotification.slot > lastValidBlockHeight) {
3849
+ throw new Error(
3850
+ "The network has progressed past the last block for which this transaction could have committed."
3851
+ );
3852
+ }
3853
+ }
3854
+ } finally {
3855
+ abortController.abort();
3856
+ }
3857
+ };
3858
+ }
3859
+
3860
+ // src/transaction-confirmation-strategy-nonce.ts
3861
+ init_env_shim();
3862
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
3863
+ 4 + // state(u32)
3864
+ 32;
3865
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
3866
+ return async function getNonceInvalidationPromise({
3867
+ abortSignal: callerAbortSignal,
3868
+ commitment,
3869
+ currentNonceValue,
3870
+ nonceAccountAddress
3871
+ }) {
3872
+ const abortController = new AbortController();
3873
+ function handleAbort() {
3874
+ abortController.abort();
3875
+ }
3876
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3877
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
3878
+ const base58Decoder2 = getBase58Decoder();
3879
+ const base64Encoder = getBase64Encoder();
3880
+ function getNonceFromAccountData([base64EncodedBytes]) {
3881
+ const data = base64Encoder.encode(base64EncodedBytes);
3882
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
3883
+ return base58Decoder2.decode(nonceValueBytes)[0];
3884
+ }
3885
+ const nonceAccountDidAdvancePromise = (async () => {
3886
+ for await (const accountNotification of accountNotifications) {
3887
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
3888
+ if (nonceValue !== currentNonceValue) {
3889
+ throw new Error(
3890
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
3891
+ );
3892
+ }
3893
+ }
3894
+ })();
3895
+ const nonceIsAlreadyInvalidPromise = (async () => {
3896
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
3897
+ commitment,
3898
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
3899
+ encoding: "base58"
3900
+ }).send({ abortSignal: abortController.signal });
3901
+ if (!nonceAccount) {
3902
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
3903
+ }
3904
+ const nonceValue = (
3905
+ // This works because we asked for the exact slice of data representing the nonce
3906
+ // value, and furthermore asked for it in `base58` encoding.
3907
+ nonceAccount.data[0]
3908
+ );
3909
+ if (nonceValue !== currentNonceValue) {
3910
+ throw new Error(
3911
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
3912
+ );
3913
+ } else {
3914
+ await new Promise(() => {
3915
+ });
3916
+ }
3917
+ })();
3918
+ try {
3919
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
3920
+ } finally {
3921
+ abortController.abort();
3922
+ }
3923
+ };
3924
+ }
3925
+
3926
+ // src/transaction-confirmation.ts
3927
+ function createDefaultDurableNonceTransactionConfirmer({
3928
+ rpc,
3929
+ rpcSubscriptions
3930
+ }) {
3931
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
3932
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
3933
+ rpc,
3934
+ rpcSubscriptions
3935
+ );
3936
+ return async function confirmDurableNonceTransaction(config) {
3937
+ await waitForDurableNonceTransactionConfirmation({
3938
+ ...config,
3939
+ getNonceInvalidationPromise,
3940
+ getRecentSignatureConfirmationPromise
3941
+ });
3942
+ };
3943
+ }
3944
+ function createDefaultRecentTransactionConfirmer({
3945
+ rpc,
3946
+ rpcSubscriptions
3947
+ }) {
3948
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);
3949
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
3950
+ rpc,
3951
+ rpcSubscriptions
3952
+ );
3953
+ return async function confirmRecentTransaction(config) {
3954
+ await waitForRecentTransactionConfirmation({
3955
+ ...config,
3956
+ getBlockHeightExceedencePromise,
3957
+ getRecentSignatureConfirmationPromise
3958
+ });
3959
+ };
3960
+ }
3961
+ async function waitForDurableNonceTransactionConfirmation(config) {
3962
+ await raceStrategies(
3963
+ getSignatureFromTransaction(config.transaction),
3964
+ config,
3965
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
3966
+ return [
3967
+ getNonceInvalidationPromise({
3968
+ abortSignal,
3969
+ commitment,
3970
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
3971
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
3972
+ })
3973
+ ];
3974
+ }
2350
3975
  );
2351
3976
  }
3977
+ async function waitForRecentTransactionConfirmation(config) {
3978
+ await raceStrategies(
3979
+ getSignatureFromTransaction(config.transaction),
3980
+ config,
3981
+ function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {
3982
+ return [
3983
+ getBlockHeightExceedencePromise({
3984
+ abortSignal,
3985
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
3986
+ })
3987
+ ];
3988
+ }
3989
+ );
3990
+ }
3991
+
3992
+ // src/send-transaction.ts
3993
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
3994
+ if (
3995
+ // The developer has supplied no value for `preflightCommitment`.
3996
+ !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
3997
+ commitmentComparator(
3998
+ commitment,
3999
+ "finalized"
4000
+ /* default value of `preflightCommitment` */
4001
+ ) < 0
4002
+ ) {
4003
+ return {
4004
+ ...config,
4005
+ // In the common case, it is unlikely that you want to simulate a transaction at
4006
+ // `finalized` commitment when your standard of commitment for confirming the
4007
+ // transaction is lower. Cap the simulation commitment level to the level of the
4008
+ // confirmation commitment.
4009
+ preflightCommitment: commitment
4010
+ };
4011
+ }
4012
+ return config;
4013
+ }
4014
+ async function sendTransaction_INTERNAL({
4015
+ abortSignal,
4016
+ commitment,
4017
+ rpc,
4018
+ transaction,
4019
+ ...sendTransactionConfig
4020
+ }) {
4021
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
4022
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
4023
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
4024
+ encoding: "base64"
4025
+ }).send({ abortSignal });
4026
+ }
4027
+ function createDefaultDurableNonceTransactionSender({
4028
+ rpc,
4029
+ rpcSubscriptions
4030
+ }) {
4031
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
4032
+ rpc,
4033
+ rpcSubscriptions
4034
+ });
4035
+ return async function sendDurableNonceTransaction(transaction, config) {
4036
+ await sendAndConfirmDurableNonceTransaction({
4037
+ ...config,
4038
+ confirmDurableNonceTransaction,
4039
+ rpc,
4040
+ transaction
4041
+ });
4042
+ };
4043
+ }
4044
+ function createDefaultTransactionSender({
4045
+ rpc,
4046
+ rpcSubscriptions
4047
+ }) {
4048
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
4049
+ rpc,
4050
+ rpcSubscriptions
4051
+ });
4052
+ return async function sendTransaction(transaction, config) {
4053
+ await sendAndConfirmTransaction({
4054
+ ...config,
4055
+ confirmRecentTransaction,
4056
+ rpc,
4057
+ transaction
4058
+ });
4059
+ };
4060
+ }
4061
+ async function sendAndConfirmDurableNonceTransaction({
4062
+ abortSignal,
4063
+ commitment,
4064
+ confirmDurableNonceTransaction,
4065
+ rpc,
4066
+ transaction,
4067
+ ...sendTransactionConfig
4068
+ }) {
4069
+ const transactionSignature = await sendTransaction_INTERNAL({
4070
+ ...sendTransactionConfig,
4071
+ abortSignal,
4072
+ commitment,
4073
+ rpc,
4074
+ transaction
4075
+ });
4076
+ await confirmDurableNonceTransaction({
4077
+ abortSignal,
4078
+ commitment,
4079
+ transaction
4080
+ });
4081
+ return transactionSignature;
4082
+ }
4083
+ async function sendAndConfirmTransaction({
4084
+ abortSignal,
4085
+ commitment,
4086
+ confirmRecentTransaction,
4087
+ rpc,
4088
+ transaction,
4089
+ ...sendTransactionConfig
4090
+ }) {
4091
+ const transactionSignature = await sendTransaction_INTERNAL({
4092
+ ...sendTransactionConfig,
4093
+ abortSignal,
4094
+ commitment,
4095
+ rpc,
4096
+ transaction
4097
+ });
4098
+ await confirmRecentTransaction({
4099
+ abortSignal,
4100
+ commitment,
4101
+ transaction
4102
+ });
4103
+ return transactionSignature;
4104
+ }
2352
4105
 
2353
4106
  exports.AccountRole = AccountRole;
4107
+ exports.address = address;
2354
4108
  exports.appendTransactionInstruction = appendTransactionInstruction;
2355
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
4109
+ exports.assertIsAddress = assertIsAddress;
2356
4110
  exports.assertIsBlockhash = assertIsBlockhash;
2357
4111
  exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
4112
+ exports.assertIsLamports = assertIsLamports;
4113
+ exports.assertIsProgramDerivedAddress = assertIsProgramDerivedAddress;
4114
+ exports.assertIsSignature = assertIsSignature;
4115
+ exports.assertIsStringifiedBigInt = assertIsStringifiedBigInt;
4116
+ exports.assertIsStringifiedNumber = assertIsStringifiedNumber;
4117
+ exports.assertIsUnixTimestamp = assertIsUnixTimestamp;
4118
+ exports.assertTransactionIsFullySigned = assertTransactionIsFullySigned;
4119
+ exports.commitmentComparator = commitmentComparator;
2358
4120
  exports.createAddressWithSeed = createAddressWithSeed;
4121
+ exports.createBlockHeightExceedencePromiseFactory = createBlockHeightExceedencePromiseFactory;
4122
+ exports.createDefaultAirdropRequester = createDefaultAirdropRequester;
4123
+ exports.createDefaultDurableNonceTransactionConfirmer = createDefaultDurableNonceTransactionConfirmer;
4124
+ exports.createDefaultDurableNonceTransactionSender = createDefaultDurableNonceTransactionSender;
4125
+ exports.createDefaultRecentTransactionConfirmer = createDefaultRecentTransactionConfirmer;
4126
+ exports.createDefaultRpcSubscriptionsTransport = createDefaultRpcSubscriptionsTransport;
2359
4127
  exports.createDefaultRpcTransport = createDefaultRpcTransport;
4128
+ exports.createDefaultTransactionSender = createDefaultTransactionSender;
4129
+ exports.createNonceInvalidationPromiseFactory = createNonceInvalidationPromiseFactory;
4130
+ exports.createRecentSignatureConfirmationPromiseFactory = createRecentSignatureConfirmationPromiseFactory;
2360
4131
  exports.createSolanaRpc = createSolanaRpc;
4132
+ exports.createSolanaRpcSubscriptions = createSolanaRpcSubscriptions;
4133
+ exports.createSolanaRpcSubscriptions_UNSTABLE = createSolanaRpcSubscriptions_UNSTABLE;
2361
4134
  exports.createTransaction = createTransaction;
2362
4135
  exports.downgradeRoleToNonSigner = downgradeRoleToNonSigner;
2363
4136
  exports.downgradeRoleToReadonly = downgradeRoleToReadonly;
2364
4137
  exports.generateKeyPair = generateKeyPair;
4138
+ exports.getAddressCodec = getAddressCodec;
4139
+ exports.getAddressComparator = getAddressComparator;
4140
+ exports.getAddressDecoder = getAddressDecoder;
4141
+ exports.getAddressEncoder = getAddressEncoder;
2365
4142
  exports.getAddressFromPublicKey = getAddressFromPublicKey;
2366
- exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
2367
- exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
2368
4143
  exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
2369
4144
  exports.getProgramDerivedAddress = getProgramDerivedAddress;
4145
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
4146
+ exports.getTransactionCodec = getTransactionCodec;
4147
+ exports.getTransactionDecoder = getTransactionDecoder;
4148
+ exports.getTransactionEncoder = getTransactionEncoder;
4149
+ exports.isAddress = isAddress;
4150
+ exports.isAdvanceNonceAccountInstruction = isAdvanceNonceAccountInstruction;
4151
+ exports.isLamports = isLamports;
4152
+ exports.isProgramDerivedAddress = isProgramDerivedAddress;
4153
+ exports.isSignature = isSignature;
2370
4154
  exports.isSignerRole = isSignerRole;
4155
+ exports.isStringifiedBigInt = isStringifiedBigInt;
4156
+ exports.isStringifiedNumber = isStringifiedNumber;
4157
+ exports.isUnixTimestamp = isUnixTimestamp;
2371
4158
  exports.isWritableRole = isWritableRole;
4159
+ exports.lamports = lamports;
2372
4160
  exports.mergeRoles = mergeRoles;
4161
+ exports.partiallySignTransaction = partiallySignTransaction;
2373
4162
  exports.prependTransactionInstruction = prependTransactionInstruction;
4163
+ exports.requestAndConfirmAirdrop = requestAndConfirmAirdrop;
4164
+ exports.sendAndConfirmDurableNonceTransaction = sendAndConfirmDurableNonceTransaction;
4165
+ exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
2374
4166
  exports.setTransactionFeePayer = setTransactionFeePayer;
2375
4167
  exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
2376
4168
  exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
2377
4169
  exports.signBytes = signBytes;
2378
4170
  exports.signTransaction = signTransaction;
4171
+ exports.signature = signature;
4172
+ exports.stringifiedBigInt = stringifiedBigInt;
4173
+ exports.stringifiedNumber = stringifiedNumber;
4174
+ exports.unixTimestamp = unixTimestamp;
2379
4175
  exports.upgradeRoleToSigner = upgradeRoleToSigner;
2380
4176
  exports.upgradeRoleToWritable = upgradeRoleToWritable;
2381
4177
  exports.verifySignature = verifySignature;
4178
+ exports.waitForDurableNonceTransactionConfirmation = waitForDurableNonceTransactionConfirmation;
4179
+ exports.waitForRecentTransactionConfirmation = waitForRecentTransactionConfirmation;
2382
4180
 
2383
4181
  return exports;
2384
4182