@solana/web3.js 2.0.0-experimental.b463a7a → 2.0.0-experimental.b755749

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.
@@ -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.options) || input.options.endian === 0;
338
251
  defaultDescription += littleEndian ? "(le)" : "(be)";
339
252
  }
340
253
  return {
341
254
  description: input.options.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 = {}) => ({
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 = (options = {}) => ({
401
296
  description: options.description ?? "shortU16",
402
- fixedSize: null,
403
- maxSize: 3,
404
- serialize: (value) => {
405
- assertRange("shortU16", 0, 65535, value);
406
- const bytes2 = [0];
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 = (options = {}) => ({
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,224 +327,201 @@ this.globalThis.solanaWeb3 = (function (exports) {
430
327
  }
431
328
  }
432
329
  return [value, offset + byteCount];
433
- }
330
+ },
331
+ description: options.description ?? "shortU16",
332
+ fixedSize: null,
333
+ maxSize: 3
334
+ });
335
+ var getU32Encoder = (options = {}) => numberEncoderFactory({
336
+ name: "u32",
337
+ options,
338
+ range: [0, Number("0xffffffff")],
339
+ set: (view, value, le) => view.setUint32(0, value, le),
340
+ size: 4
341
+ });
342
+ var getU32Decoder = (options = {}) => numberDecoderFactory({
343
+ get: (view, le) => view.getUint32(0, le),
344
+ name: "u32",
345
+ options,
346
+ size: 4
347
+ });
348
+ var getU8Encoder = (options = {}) => numberEncoderFactory({
349
+ name: "u8",
350
+ options,
351
+ range: [0, Number("0xff")],
352
+ set: (view, value) => view.setUint8(0, value),
353
+ size: 1
354
+ });
355
+ var getU8Decoder = (options = {}) => numberDecoderFactory({
356
+ get: (view) => view.getUint8(0),
357
+ name: "u8",
358
+ options,
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) {
447
+ var removeNullCharacters = (value) => (
448
+ // eslint-disable-next-line no-control-regex
449
+ value.replace(/\u0000/g, "")
450
+ );
451
+ var e = globalThis.TextDecoder;
452
+ var o = globalThis.TextEncoder;
453
+ var getUtf8Encoder = () => {
454
+ let textEncoder;
455
+ return {
456
+ description: "utf8",
457
+ encode: (value) => new Uint8Array((textEncoder || (textEncoder = new o())).encode(value)),
458
+ fixedSize: null,
459
+ maxSize: null
460
+ };
461
+ };
462
+ var getUtf8Decoder = () => {
463
+ let textDecoder;
464
+ return {
465
+ decode(bytes, offset = 0) {
466
+ const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));
467
+ return [removeNullCharacters(value), bytes.length];
468
+ },
469
+ description: "utf8",
470
+ fixedSize: null,
471
+ maxSize: null
472
+ };
473
+ };
474
+ var getStringEncoder = (options = {}) => {
475
+ const size = options.size ?? getU32Encoder();
476
+ const encoding = options.encoding ?? getUtf8Encoder();
477
+ const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
478
+ if (size === "variable") {
479
+ return { ...encoding, description };
480
+ }
471
481
  if (typeof size === "number") {
472
- return [size, offset];
482
+ return fixEncoder(encoding, size, description);
473
483
  }
474
- if (typeof size === "object") {
475
- return size.deserialize(bytes2, offset);
484
+ return {
485
+ description,
486
+ encode: (value) => {
487
+ const contentBytes = encoding.encode(value);
488
+ const lengthBytes = size.encode(contentBytes.length);
489
+ return mergeBytes([lengthBytes, contentBytes]);
490
+ },
491
+ fixedSize: null,
492
+ maxSize: null
493
+ };
494
+ };
495
+ var getStringDecoder = (options = {}) => {
496
+ const size = options.size ?? getU32Decoder();
497
+ const encoding = options.encoding ?? getUtf8Decoder();
498
+ const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
499
+ if (size === "variable") {
500
+ return { ...encoding, description };
476
501
  }
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];
502
+ if (typeof size === "number") {
503
+ return fixDecoder(encoding, size, description);
487
504
  }
488
- throw new UnrecognizedArrayLikeSerializerSizeError(size);
489
- }
505
+ return {
506
+ decode: (bytes, offset = 0) => {
507
+ assertByteArrayIsNotEmptyForCodec("string", bytes, offset);
508
+ const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);
509
+ const length = Number(lengthBigInt);
510
+ offset = lengthOffset;
511
+ const contentBytes = bytes.slice(offset, offset + length);
512
+ assertByteArrayHasEnoughBytesForCodec("string", length, contentBytes);
513
+ const [value, contentOffset] = encoding.decode(contentBytes);
514
+ offset += contentOffset;
515
+ return [value, offset];
516
+ },
517
+ description,
518
+ fixedSize: null,
519
+ maxSize: null
520
+ };
521
+ };
490
522
  function getSizeDescription(size) {
491
523
  return typeof size === "object" ? size.description : `${size}`;
492
524
  }
493
- function getSizeFromChildren(size, childrenSizes) {
494
- if (typeof size !== "number")
495
- return null;
496
- if (size === 0)
497
- return 0;
498
- const childrenSize = sumSerializerSizes(childrenSizes);
499
- return childrenSize === null ? null : childrenSize * size;
500
- }
501
- function getSizePrefix(size, realSize) {
502
- return typeof size === "object" ? size.serialize(realSize) : new Uint8Array();
503
- }
504
-
505
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs
506
- function array(item, options = {}) {
507
- const size = options.size ?? u32();
508
- if (size === "remainder" && item.fixedSize === null) {
509
- throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.');
510
- }
511
- return {
512
- description: options.description ?? `array(${item.description}; ${getSizeDescription(size)})`,
513
- fixedSize: getSizeFromChildren(size, [item.fixedSize]),
514
- maxSize: getSizeFromChildren(size, [item.maxSize]),
515
- serialize: (value) => {
516
- if (typeof size === "number" && value.length !== size) {
517
- throw new InvalidNumberOfItemsError("array", size, value.length);
518
- }
519
- return mergeBytes([getSizePrefix(size, value.length), ...value.map((v) => item.serialize(v))]);
520
- },
521
- deserialize: (bytes2, offset = 0) => {
522
- if (typeof size === "object" && bytes2.slice(offset).length === 0) {
523
- return [[], offset];
524
- }
525
- const [resolvedSize, newOffset] = getResolvedSize(size, [item.fixedSize], bytes2, offset);
526
- offset = newOffset;
527
- const values = [];
528
- for (let i = 0; i < resolvedSize; i += 1) {
529
- const [value, newOffset2] = item.deserialize(bytes2, offset);
530
- values.push(value);
531
- offset = newOffset2;
532
- }
533
- return [values, offset];
534
- }
535
- };
536
- }
537
-
538
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/bytes.mjs
539
- init_env_shim();
540
- function bytes(options = {}) {
541
- const size = options.size ?? "variable";
542
- const description = options.description ?? `bytes(${getSizeDescription(size)})`;
543
- const byteSerializer = {
544
- description,
545
- fixedSize: null,
546
- maxSize: null,
547
- serialize: (value) => new Uint8Array(value),
548
- deserialize: (bytes2, offset = 0) => {
549
- const slice = bytes2.slice(offset);
550
- return [slice, offset + slice.length];
551
- }
552
- };
553
- if (size === "variable") {
554
- return byteSerializer;
555
- }
556
- if (typeof size === "number") {
557
- return fixSerializer(byteSerializer, size, description);
558
- }
559
- return {
560
- description,
561
- fixedSize: null,
562
- maxSize: null,
563
- serialize: (value) => {
564
- const contentBytes = byteSerializer.serialize(value);
565
- const lengthBytes = size.serialize(contentBytes.length);
566
- return mergeBytes([lengthBytes, contentBytes]);
567
- },
568
- deserialize: (buffer, offset = 0) => {
569
- if (buffer.slice(offset).length === 0) {
570
- throw new DeserializingEmptyBufferError("bytes");
571
- }
572
- const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
573
- const length = Number(lengthBigInt);
574
- offset = lengthOffset;
575
- const contentBuffer = buffer.slice(offset, offset + length);
576
- if (contentBuffer.length < length) {
577
- throw new NotEnoughBytesError("bytes", length, contentBuffer.length);
578
- }
579
- const [value, contentOffset] = byteSerializer.deserialize(contentBuffer);
580
- offset += contentOffset;
581
- return [value, offset];
582
- }
583
- };
584
- }
585
-
586
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs
587
- init_env_shim();
588
- function string(options = {}) {
589
- const size = options.size ?? u32();
590
- const encoding = options.encoding ?? utf8;
591
- const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
592
- if (size === "variable") {
593
- return {
594
- ...encoding,
595
- description
596
- };
597
- }
598
- if (typeof size === "number") {
599
- return fixSerializer(encoding, size, description);
600
- }
601
- return {
602
- description,
603
- fixedSize: null,
604
- maxSize: null,
605
- serialize: (value) => {
606
- const contentBytes = encoding.serialize(value);
607
- const lengthBytes = size.serialize(contentBytes.length);
608
- return mergeBytes([lengthBytes, contentBytes]);
609
- },
610
- deserialize: (buffer, offset = 0) => {
611
- if (buffer.slice(offset).length === 0) {
612
- throw new DeserializingEmptyBufferError("string");
613
- }
614
- const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
615
- const length = Number(lengthBigInt);
616
- offset = lengthOffset;
617
- const contentBuffer = buffer.slice(offset, offset + length);
618
- if (contentBuffer.length < length) {
619
- throw new NotEnoughBytesError("string", length, contentBuffer.length);
620
- }
621
- const [value, contentOffset] = encoding.deserialize(contentBuffer);
622
- offset += contentOffset;
623
- return [value, offset];
624
- }
625
- };
626
- }
627
-
628
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.9/node_modules/@metaplex-foundation/umi-serializers/dist/esm/struct.mjs
629
- init_env_shim();
630
- function struct(fields, options = {}) {
631
- const fieldDescriptions = fields.map(([name, serializer]) => `${String(name)}: ${serializer.description}`).join(", ");
632
- return {
633
- description: options.description ?? `struct(${fieldDescriptions})`,
634
- fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)),
635
- maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)),
636
- serialize: (struct2) => {
637
- const fieldBytes = fields.map(([key, serializer]) => serializer.serialize(struct2[key]));
638
- return mergeBytes(fieldBytes);
639
- },
640
- deserialize: (bytes2, offset = 0) => {
641
- const struct2 = {};
642
- fields.forEach(([key, serializer]) => {
643
- const [value, newOffset] = serializer.deserialize(bytes2, offset);
644
- offset = newOffset;
645
- struct2[key] = value;
646
- });
647
- return [struct2, offset];
648
- }
649
- };
650
- }
651
525
 
652
526
  // ../assertions/dist/index.browser.js
653
527
  init_env_shim();
@@ -715,7 +589,37 @@ this.globalThis.solanaWeb3 = (function (exports) {
715
589
  throw new Error("No signature verification implementation could be found");
716
590
  }
717
591
  }
718
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
592
+
593
+ // ../addresses/dist/index.browser.js
594
+ var memoizedBase58Encoder;
595
+ var memoizedBase58Decoder;
596
+ function getMemoizedBase58Encoder() {
597
+ if (!memoizedBase58Encoder)
598
+ memoizedBase58Encoder = getBase58Encoder();
599
+ return memoizedBase58Encoder;
600
+ }
601
+ function getMemoizedBase58Decoder() {
602
+ if (!memoizedBase58Decoder)
603
+ memoizedBase58Decoder = getBase58Decoder();
604
+ return memoizedBase58Decoder;
605
+ }
606
+ function isAddress(putativeBase58EncodedAddress) {
607
+ if (
608
+ // Lowest address (32 bytes of zeroes)
609
+ putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
610
+ putativeBase58EncodedAddress.length > 44
611
+ ) {
612
+ return false;
613
+ }
614
+ const base58Encoder3 = getMemoizedBase58Encoder();
615
+ const bytes = base58Encoder3.encode(putativeBase58EncodedAddress);
616
+ const numBytes = bytes.byteLength;
617
+ if (numBytes !== 32) {
618
+ return false;
619
+ }
620
+ return true;
621
+ }
622
+ function assertIsAddress(putativeBase58EncodedAddress) {
719
623
  try {
720
624
  if (
721
625
  // Lowest address (32 bytes of zeroes)
@@ -724,8 +628,9 @@ this.globalThis.solanaWeb3 = (function (exports) {
724
628
  ) {
725
629
  throw new Error("Expected input string to decode to a byte array of length 32.");
726
630
  }
727
- const bytes2 = base58.serialize(putativeBase58EncodedAddress);
728
- const numBytes = bytes2.byteLength;
631
+ const base58Encoder3 = getMemoizedBase58Encoder();
632
+ const bytes = base58Encoder3.encode(putativeBase58EncodedAddress);
633
+ const numBytes = bytes.byteLength;
729
634
  if (numBytes !== 32) {
730
635
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
731
636
  }
@@ -735,14 +640,31 @@ this.globalThis.solanaWeb3 = (function (exports) {
735
640
  });
736
641
  }
737
642
  }
738
- function getBase58EncodedAddressCodec(config) {
739
- return string({
740
- description: config?.description ?? ("A 32-byte account address" ),
741
- encoding: base58,
643
+ function address(putativeBase58EncodedAddress) {
644
+ assertIsAddress(putativeBase58EncodedAddress);
645
+ return putativeBase58EncodedAddress;
646
+ }
647
+ function getAddressEncoder(config) {
648
+ return mapEncoder(
649
+ getStringEncoder({
650
+ description: config?.description ?? "Base58EncodedAddress",
651
+ encoding: getMemoizedBase58Encoder(),
652
+ size: 32
653
+ }),
654
+ (putativeAddress) => address(putativeAddress)
655
+ );
656
+ }
657
+ function getAddressDecoder(config) {
658
+ return getStringDecoder({
659
+ description: config?.description ?? "Base58EncodedAddress",
660
+ encoding: getMemoizedBase58Decoder(),
742
661
  size: 32
743
662
  });
744
663
  }
745
- function getBase58EncodedAddressComparator() {
664
+ function getAddressCodec(config) {
665
+ return combineCodec(getAddressEncoder(config), getAddressDecoder(config));
666
+ }
667
+ function getAddressComparator() {
746
668
  return new Intl.Collator("en", {
747
669
  caseFirst: "lower",
748
670
  ignorePunctuation: false,
@@ -826,17 +748,32 @@ this.globalThis.solanaWeb3 = (function (exports) {
826
748
  return hexString;
827
749
  }
828
750
  }
829
- function decompressPointBytes(bytes2) {
830
- const hexString = bytes2.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
751
+ function decompressPointBytes(bytes) {
752
+ const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
831
753
  const integerLiteralString = `0x${hexString}`;
832
754
  return BigInt(integerLiteralString);
833
755
  }
834
- async function compressedPointBytesAreOnCurve(bytes2) {
835
- if (bytes2.byteLength !== 32) {
756
+ async function compressedPointBytesAreOnCurve(bytes) {
757
+ if (bytes.byteLength !== 32) {
836
758
  return false;
837
759
  }
838
- const y = decompressPointBytes(bytes2);
839
- return pointIsOnCurve(y, bytes2[31]);
760
+ const y = decompressPointBytes(bytes);
761
+ return pointIsOnCurve(y, bytes[31]);
762
+ }
763
+ function isProgramDerivedAddress(value) {
764
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
765
+ }
766
+ function assertIsProgramDerivedAddress(value) {
767
+ const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
768
+ if (!validFormat) {
769
+ throw new Error(
770
+ `Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].`
771
+ );
772
+ }
773
+ if (value[1] < 0 || value[1] > 255) {
774
+ throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);
775
+ }
776
+ assertIsAddress(value[0]);
840
777
  }
841
778
  var MAX_SEED_LENGTH = 32;
842
779
  var MAX_SEEDS = 16;
@@ -866,22 +803,25 @@ this.globalThis.solanaWeb3 = (function (exports) {
866
803
  ];
867
804
  var PointOnCurveError = class extends Error {
868
805
  };
869
- async function createProgramDerivedAddress({ programAddress, seeds }) {
806
+ async function createProgramDerivedAddress({
807
+ programAddress,
808
+ seeds
809
+ }) {
870
810
  await assertDigestCapabilityIsAvailable();
871
811
  if (seeds.length > MAX_SEEDS) {
872
812
  throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);
873
813
  }
874
814
  let textEncoder;
875
815
  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) {
816
+ const bytes = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
817
+ if (bytes.byteLength > MAX_SEED_LENGTH) {
878
818
  throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);
879
819
  }
880
- acc.push(...bytes2);
820
+ acc.push(...bytes);
881
821
  return acc;
882
822
  }, []);
883
- const base58EncodedAddressCodec = getBase58EncodedAddressCodec();
884
- const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);
823
+ const base58EncodedAddressCodec = getAddressCodec();
824
+ const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
885
825
  const addressBytesBuffer = await crypto.subtle.digest(
886
826
  "SHA-256",
887
827
  new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
@@ -890,19 +830,20 @@ this.globalThis.solanaWeb3 = (function (exports) {
890
830
  if (await compressedPointBytesAreOnCurve(addressBytes)) {
891
831
  throw new PointOnCurveError("Invalid seeds; point must fall off the Ed25519 curve");
892
832
  }
893
- return base58EncodedAddressCodec.deserialize(addressBytes)[0];
833
+ return base58EncodedAddressCodec.decode(addressBytes)[0];
894
834
  }
895
- async function getProgramDerivedAddress({ programAddress, seeds }) {
835
+ async function getProgramDerivedAddress({
836
+ programAddress,
837
+ seeds
838
+ }) {
896
839
  let bumpSeed = 255;
897
840
  while (bumpSeed > 0) {
898
841
  try {
899
- return {
900
- bumpSeed,
901
- pda: await createProgramDerivedAddress({
902
- programAddress,
903
- seeds: [...seeds, new Uint8Array([bumpSeed])]
904
- })
905
- };
842
+ const address2 = await createProgramDerivedAddress({
843
+ programAddress,
844
+ seeds: [...seeds, new Uint8Array([bumpSeed])]
845
+ });
846
+ return [address2, bumpSeed];
906
847
  } catch (e3) {
907
848
  if (e3 instanceof PointOnCurveError) {
908
849
  bumpSeed--;
@@ -918,21 +859,21 @@ this.globalThis.solanaWeb3 = (function (exports) {
918
859
  programAddress,
919
860
  seed
920
861
  }) {
921
- const { serialize: serialize4, deserialize: deserialize2 } = getBase58EncodedAddressCodec();
862
+ const { encode: encode2, decode: decode2 } = getAddressCodec();
922
863
  const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
923
864
  if (seedBytes.byteLength > MAX_SEED_LENGTH) {
924
865
  throw new Error(`The seed exceeds the maximum length of 32 bytes`);
925
866
  }
926
- const programAddressBytes = serialize4(programAddress);
867
+ const programAddressBytes = encode2(programAddress);
927
868
  if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
928
869
  throw new Error(`programAddress cannot end with the PDA marker`);
929
870
  }
930
871
  const addressBytesBuffer = await crypto.subtle.digest(
931
872
  "SHA-256",
932
- new Uint8Array([...serialize4(baseAddress), ...seedBytes, ...programAddressBytes])
873
+ new Uint8Array([...encode2(baseAddress), ...seedBytes, ...programAddressBytes])
933
874
  );
934
875
  const addressBytes = new Uint8Array(addressBytesBuffer);
935
- return deserialize2(addressBytes)[0];
876
+ return decode2(addressBytes)[0];
936
877
  }
937
878
  async function getAddressFromPublicKey(publicKey) {
938
879
  await assertKeyExporterIsAvailable();
@@ -940,7 +881,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
940
881
  throw new Error("The `CryptoKey` must be an `Ed25519` public key");
941
882
  }
942
883
  const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
943
- const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
884
+ const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
944
885
  return base58EncodedAddress;
945
886
  }
946
887
 
@@ -1007,8 +948,286 @@ this.globalThis.solanaWeb3 = (function (exports) {
1007
948
  return await crypto.subtle.verify("Ed25519", key, signature, data);
1008
949
  }
1009
950
 
951
+ // ../rpc-types/dist/index.browser.js
952
+ init_env_shim();
953
+ function getCommitmentScore(commitment) {
954
+ switch (commitment) {
955
+ case "finalized":
956
+ return 2;
957
+ case "confirmed":
958
+ return 1;
959
+ case "processed":
960
+ return 0;
961
+ default:
962
+ return ((_) => {
963
+ throw new Error(`Unrecognized commitment \`${commitment}\`.`);
964
+ })();
965
+ }
966
+ }
967
+ function commitmentComparator(a, b) {
968
+ if (a === b) {
969
+ return 0;
970
+ }
971
+ return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;
972
+ }
973
+ var maxU64Value = 18446744073709551615n;
974
+ function isLamports(putativeLamports) {
975
+ return putativeLamports >= 0 && putativeLamports <= maxU64Value;
976
+ }
977
+ function assertIsLamports(putativeLamports) {
978
+ if (putativeLamports < 0) {
979
+ throw new Error("Input for 64-bit unsigned integer cannot be negative");
980
+ }
981
+ if (putativeLamports > maxU64Value) {
982
+ throw new Error("Input number is too large to be represented as a 64-bit unsigned integer");
983
+ }
984
+ }
985
+ function lamports(putativeLamports) {
986
+ assertIsLamports(putativeLamports);
987
+ return putativeLamports;
988
+ }
989
+ function isStringifiedBigInt(putativeBigInt) {
990
+ try {
991
+ BigInt(putativeBigInt);
992
+ return true;
993
+ } catch (_) {
994
+ return false;
995
+ }
996
+ }
997
+ function assertIsStringifiedBigInt(putativeBigInt) {
998
+ try {
999
+ BigInt(putativeBigInt);
1000
+ } catch (e3) {
1001
+ throw new Error(`\`${putativeBigInt}\` cannot be parsed as a BigInt`, {
1002
+ cause: e3
1003
+ });
1004
+ }
1005
+ }
1006
+ function stringifiedBigInt(putativeBigInt) {
1007
+ assertIsStringifiedBigInt(putativeBigInt);
1008
+ return putativeBigInt;
1009
+ }
1010
+ function isStringifiedNumber(putativeNumber) {
1011
+ return !Number.isNaN(Number(putativeNumber));
1012
+ }
1013
+ function assertIsStringifiedNumber(putativeNumber) {
1014
+ if (Number.isNaN(Number(putativeNumber))) {
1015
+ throw new Error(`\`${putativeNumber}\` cannot be parsed as a Number`);
1016
+ }
1017
+ }
1018
+ function stringifiedNumber(putativeNumber) {
1019
+ assertIsStringifiedNumber(putativeNumber);
1020
+ return putativeNumber;
1021
+ }
1022
+ function isUnixTimestamp(putativeTimestamp) {
1023
+ if (putativeTimestamp > 864e13 || putativeTimestamp < -864e13) {
1024
+ return false;
1025
+ }
1026
+ return true;
1027
+ }
1028
+ function assertIsUnixTimestamp(putativeTimestamp) {
1029
+ try {
1030
+ if (putativeTimestamp > 864e13 || putativeTimestamp < -864e13) {
1031
+ throw new Error("Expected input number to be in the range [-8.64e15, 8.64e15]");
1032
+ }
1033
+ } catch (e3) {
1034
+ throw new Error(`\`${putativeTimestamp}\` is not a timestamp`, {
1035
+ cause: e3
1036
+ });
1037
+ }
1038
+ }
1039
+ function unixTimestamp(putativeTimestamp) {
1040
+ assertIsUnixTimestamp(putativeTimestamp);
1041
+ return putativeTimestamp;
1042
+ }
1043
+
1010
1044
  // ../transactions/dist/index.browser.js
1011
1045
  init_env_shim();
1046
+
1047
+ // ../codecs-data-structures/dist/index.browser.js
1048
+ init_env_shim();
1049
+ function sumCodecSizes(sizes) {
1050
+ return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
1051
+ }
1052
+ function decodeArrayLikeCodecSize(size, childrenSizes, bytes, offset) {
1053
+ if (typeof size === "number") {
1054
+ return [size, offset];
1055
+ }
1056
+ if (typeof size === "object") {
1057
+ return size.decode(bytes, offset);
1058
+ }
1059
+ if (size === "remainder") {
1060
+ const childrenSize = sumCodecSizes(childrenSizes);
1061
+ if (childrenSize === null) {
1062
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
1063
+ }
1064
+ const remainder = bytes.slice(offset).length;
1065
+ if (remainder % childrenSize !== 0) {
1066
+ throw new Error(
1067
+ `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.`
1068
+ );
1069
+ }
1070
+ return [remainder / childrenSize, offset];
1071
+ }
1072
+ throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);
1073
+ }
1074
+ function getArrayLikeCodecSizeDescription(size) {
1075
+ return typeof size === "object" ? size.description : `${size}`;
1076
+ }
1077
+ function getArrayLikeCodecSizeFromChildren(size, childrenSizes) {
1078
+ if (typeof size !== "number")
1079
+ return null;
1080
+ if (size === 0)
1081
+ return 0;
1082
+ const childrenSize = sumCodecSizes(childrenSizes);
1083
+ return childrenSize === null ? null : childrenSize * size;
1084
+ }
1085
+ function getArrayLikeCodecSizePrefix(size, realSize) {
1086
+ return typeof size === "object" ? size.encode(realSize) : new Uint8Array();
1087
+ }
1088
+ function assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {
1089
+ if (expected !== actual) {
1090
+ throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);
1091
+ }
1092
+ }
1093
+ function arrayCodecHelper(item, size, description) {
1094
+ if (size === "remainder" && item.fixedSize === null) {
1095
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
1096
+ }
1097
+ return {
1098
+ description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,
1099
+ fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),
1100
+ maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])
1101
+ };
1102
+ }
1103
+ function getArrayEncoder(item, options = {}) {
1104
+ const size = options.size ?? getU32Encoder();
1105
+ return {
1106
+ ...arrayCodecHelper(item, size, options.description),
1107
+ encode: (value) => {
1108
+ if (typeof size === "number") {
1109
+ assertValidNumberOfItemsForCodec("array", size, value.length);
1110
+ }
1111
+ return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map((v) => item.encode(v))]);
1112
+ }
1113
+ };
1114
+ }
1115
+ function getArrayDecoder(item, options = {}) {
1116
+ const size = options.size ?? getU32Decoder();
1117
+ return {
1118
+ ...arrayCodecHelper(item, size, options.description),
1119
+ decode: (bytes, offset = 0) => {
1120
+ if (typeof size === "object" && bytes.slice(offset).length === 0) {
1121
+ return [[], offset];
1122
+ }
1123
+ const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);
1124
+ offset = newOffset;
1125
+ const values = [];
1126
+ for (let i = 0; i < resolvedSize; i += 1) {
1127
+ const [value, newOffset2] = item.decode(bytes, offset);
1128
+ values.push(value);
1129
+ offset = newOffset2;
1130
+ }
1131
+ return [values, offset];
1132
+ }
1133
+ };
1134
+ }
1135
+ function getBytesEncoder(options = {}) {
1136
+ const size = options.size ?? "variable";
1137
+ const sizeDescription = typeof size === "object" ? size.description : `${size}`;
1138
+ const description = options.description ?? `bytes(${sizeDescription})`;
1139
+ const byteEncoder = {
1140
+ description,
1141
+ encode: (value) => value,
1142
+ fixedSize: null,
1143
+ maxSize: null
1144
+ };
1145
+ if (size === "variable") {
1146
+ return byteEncoder;
1147
+ }
1148
+ if (typeof size === "number") {
1149
+ return fixEncoder(byteEncoder, size, description);
1150
+ }
1151
+ return {
1152
+ ...byteEncoder,
1153
+ encode: (value) => {
1154
+ const contentBytes = byteEncoder.encode(value);
1155
+ const lengthBytes = size.encode(contentBytes.length);
1156
+ return mergeBytes([lengthBytes, contentBytes]);
1157
+ }
1158
+ };
1159
+ }
1160
+ function getBytesDecoder(options = {}) {
1161
+ const size = options.size ?? "variable";
1162
+ const sizeDescription = typeof size === "object" ? size.description : `${size}`;
1163
+ const description = options.description ?? `bytes(${sizeDescription})`;
1164
+ const byteDecoder = {
1165
+ decode: (bytes, offset = 0) => {
1166
+ const slice = bytes.slice(offset);
1167
+ return [slice, offset + slice.length];
1168
+ },
1169
+ description,
1170
+ fixedSize: null,
1171
+ maxSize: null
1172
+ };
1173
+ if (size === "variable") {
1174
+ return byteDecoder;
1175
+ }
1176
+ if (typeof size === "number") {
1177
+ return fixDecoder(byteDecoder, size, description);
1178
+ }
1179
+ return {
1180
+ ...byteDecoder,
1181
+ decode: (bytes, offset = 0) => {
1182
+ assertByteArrayIsNotEmptyForCodec("bytes", bytes, offset);
1183
+ const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);
1184
+ const length = Number(lengthBigInt);
1185
+ offset = lengthOffset;
1186
+ const contentBytes = bytes.slice(offset, offset + length);
1187
+ assertByteArrayHasEnoughBytesForCodec("bytes", length, contentBytes);
1188
+ const [value, contentOffset] = byteDecoder.decode(contentBytes);
1189
+ offset += contentOffset;
1190
+ return [value, offset];
1191
+ }
1192
+ };
1193
+ }
1194
+ function structCodecHelper(fields, description) {
1195
+ const fieldDescriptions = fields.map(([name, codec]) => `${String(name)}: ${codec.description}`).join(", ");
1196
+ return {
1197
+ description: description ?? `struct(${fieldDescriptions})`,
1198
+ fixedSize: sumCodecSizes(fields.map(([, field]) => field.fixedSize)),
1199
+ maxSize: sumCodecSizes(fields.map(([, field]) => field.maxSize))
1200
+ };
1201
+ }
1202
+ function getStructEncoder(fields, options = {}) {
1203
+ return {
1204
+ ...structCodecHelper(fields, options.description),
1205
+ encode: (struct) => {
1206
+ const fieldBytes = fields.map(([key, codec]) => codec.encode(struct[key]));
1207
+ return mergeBytes(fieldBytes);
1208
+ }
1209
+ };
1210
+ }
1211
+ function getStructDecoder(fields, options = {}) {
1212
+ return {
1213
+ ...structCodecHelper(fields, options.description),
1214
+ decode: (bytes, offset = 0) => {
1215
+ const struct = {};
1216
+ fields.forEach(([key, codec]) => {
1217
+ const [value, newOffset] = codec.decode(bytes, offset);
1218
+ offset = newOffset;
1219
+ struct[key] = value;
1220
+ });
1221
+ return [struct, offset];
1222
+ }
1223
+ };
1224
+ }
1225
+
1226
+ // ../functional/dist/index.browser.js
1227
+ init_env_shim();
1228
+ function pipe(init, ...fns) {
1229
+ return fns.reduce((acc, fn) => fn(acc), init);
1230
+ }
1012
1231
  function getUnsignedTransaction(transaction) {
1013
1232
  if ("signatures" in transaction) {
1014
1233
  const {
@@ -1021,7 +1240,10 @@ this.globalThis.solanaWeb3 = (function (exports) {
1021
1240
  return transaction;
1022
1241
  }
1023
1242
  }
1243
+ var base58Encoder;
1024
1244
  function assertIsBlockhash(putativeBlockhash) {
1245
+ if (!base58Encoder)
1246
+ base58Encoder = getBase58Encoder();
1025
1247
  try {
1026
1248
  if (
1027
1249
  // Lowest value (32 bytes of zeroes)
@@ -1030,8 +1252,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
1030
1252
  ) {
1031
1253
  throw new Error("Expected input string to decode to a byte array of length 32.");
1032
1254
  }
1033
- const bytes3 = base58.serialize(putativeBlockhash);
1034
- const numBytes = bytes3.byteLength;
1255
+ const bytes = base58Encoder.encode(putativeBlockhash);
1256
+ const numBytes = bytes.byteLength;
1035
1257
  if (numBytes !== 32) {
1036
1258
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
1037
1259
  }
@@ -1110,7 +1332,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1110
1332
  instruction.accounts?.length === 3 && // First account is nonce account address
1111
1333
  instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole2.WRITABLE && // Second account is recent blockhashes sysvar
1112
1334
  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;
1335
+ instruction.accounts[2].address != null && isSignerRole2(instruction.accounts[2].role);
1114
1336
  }
1115
1337
  function isAdvanceNonceAccountInstructionData(data) {
1116
1338
  return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
@@ -1118,21 +1340,38 @@ this.globalThis.solanaWeb3 = (function (exports) {
1118
1340
  function isDurableNonceTransaction(transaction) {
1119
1341
  return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
1120
1342
  }
1343
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
1344
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
1345
+ }
1121
1346
  function setTransactionLifetimeUsingDurableNonce({
1122
1347
  nonce,
1123
1348
  nonceAccountAddress,
1124
1349
  nonceAuthorityAddress
1125
1350
  }, 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;
1351
+ let newInstructions;
1352
+ const firstInstruction = transaction.instructions[0];
1353
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
1354
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
1355
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
1356
+ return transaction;
1357
+ } else {
1358
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
1359
+ }
1360
+ } else {
1361
+ newInstructions = [
1362
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1363
+ ...transaction.instructions.slice(1)
1364
+ ];
1365
+ }
1366
+ } else {
1367
+ newInstructions = [
1368
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1369
+ ...transaction.instructions
1370
+ ];
1129
1371
  }
1130
1372
  const out = {
1131
1373
  ...getUnsignedTransaction(transaction),
1132
- instructions: [
1133
- createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1134
- ...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions
1135
- ],
1374
+ instructions: newInstructions,
1136
1375
  lifetimeConstraint: {
1137
1376
  nonce
1138
1377
  }
@@ -1167,8 +1406,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
1167
1406
  Object.freeze(out);
1168
1407
  return out;
1169
1408
  }
1170
- function upsert(addressMap, address, update) {
1171
- addressMap[address] = update(addressMap[address] ?? { role: AccountRole2.READONLY });
1409
+ function upsert(addressMap, address2, update) {
1410
+ addressMap[address2] = update(addressMap[address2] ?? { role: AccountRole2.READONLY });
1172
1411
  }
1173
1412
  var TYPE = Symbol("AddressMapTypeProperty");
1174
1413
  function getAddressMapFromInstructions(feePayer, instructions) {
@@ -1219,7 +1458,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1219
1458
  const shouldReplaceEntry = (
1220
1459
  // Consider using the new LOOKUP_TABLE if its address is different...
1221
1460
  entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
1222
- (addressComparator || (addressComparator = getBase58EncodedAddressComparator()))(
1461
+ (addressComparator || (addressComparator = getAddressComparator()))(
1223
1462
  accountMeta.lookupTableAddress,
1224
1463
  entry.lookupTableAddress
1225
1464
  ) < 0
@@ -1327,14 +1566,14 @@ this.globalThis.solanaWeb3 = (function (exports) {
1327
1566
  if (leftIsWritable !== isWritableRole2(rightEntry.role)) {
1328
1567
  return leftIsWritable ? -1 : 1;
1329
1568
  }
1330
- addressComparator || (addressComparator = getBase58EncodedAddressComparator());
1569
+ addressComparator || (addressComparator = getAddressComparator());
1331
1570
  if (leftEntry[TYPE] === 1 && rightEntry[TYPE] === 1 && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
1332
1571
  return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
1333
1572
  } else {
1334
1573
  return addressComparator(leftAddress, rightAddress);
1335
1574
  }
1336
- }).map(([address, addressMeta]) => ({
1337
- address,
1575
+ }).map(([address2, addressMeta]) => ({
1576
+ address: address2,
1338
1577
  ...addressMeta
1339
1578
  }));
1340
1579
  return orderedAccounts;
@@ -1356,7 +1595,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1356
1595
  entry.readableIndices.push(account.addressIndex);
1357
1596
  }
1358
1597
  }
1359
- return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
1598
+ return Object.keys(index).sort(getAddressComparator()).map((lookupTableAddress) => ({
1360
1599
  lookupTableAddress,
1361
1600
  ...index[lookupTableAddress]
1362
1601
  }));
@@ -1397,7 +1636,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1397
1636
  return instructions.map(({ accounts, data, programAddress }) => {
1398
1637
  return {
1399
1638
  programAddressIndex: accountIndex[programAddress],
1400
- ...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null,
1639
+ ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
1401
1640
  ...data ? { data } : null
1402
1641
  };
1403
1642
  });
@@ -1411,7 +1650,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1411
1650
  function getCompiledStaticAccounts(orderedAccounts) {
1412
1651
  const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
1413
1652
  const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
1414
- return orderedStaticAccounts.map(({ address }) => address);
1653
+ return orderedStaticAccounts.map(({ address: address2 }) => address2);
1415
1654
  }
1416
1655
  function compileMessage(transaction) {
1417
1656
  const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
@@ -1425,138 +1664,306 @@ this.globalThis.solanaWeb3 = (function (exports) {
1425
1664
  version: transaction.version
1426
1665
  };
1427
1666
  }
1428
- function getAddressTableLookupCodec() {
1429
- return struct(
1430
- [
1431
- [
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
- )
1438
- ],
1439
- [
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
- })
1447
- ],
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
- ]
1457
- ],
1458
- {
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
- }
1667
+ function getCompiledTransaction(transaction) {
1668
+ const compiledMessage = compileMessage(transaction);
1669
+ let signatures;
1670
+ if ("signatures" in transaction) {
1671
+ signatures = [];
1672
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
1673
+ signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
1674
+ }
1675
+ } else {
1676
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
1677
+ }
1678
+ return {
1679
+ compiledMessage,
1680
+ signatures
1681
+ };
1682
+ }
1683
+ function getAccountMetas(message) {
1684
+ const { header } = message;
1685
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
1686
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
1687
+ const accountMetas = [];
1688
+ let accountIndex = 0;
1689
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
1690
+ accountMetas.push({
1691
+ address: message.staticAccounts[accountIndex],
1692
+ role: AccountRole2.WRITABLE_SIGNER
1693
+ });
1694
+ accountIndex++;
1695
+ }
1696
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
1697
+ accountMetas.push({
1698
+ address: message.staticAccounts[accountIndex],
1699
+ role: AccountRole2.READONLY_SIGNER
1700
+ });
1701
+ accountIndex++;
1702
+ }
1703
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
1704
+ accountMetas.push({
1705
+ address: message.staticAccounts[accountIndex],
1706
+ role: AccountRole2.WRITABLE
1707
+ });
1708
+ accountIndex++;
1709
+ }
1710
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
1711
+ accountMetas.push({
1712
+ address: message.staticAccounts[accountIndex],
1713
+ role: AccountRole2.READONLY
1714
+ });
1715
+ accountIndex++;
1716
+ }
1717
+ return accountMetas;
1718
+ }
1719
+ function convertInstruction(instruction, accountMetas) {
1720
+ const programAddress = accountMetas[instruction.programAddressIndex]?.address;
1721
+ if (!programAddress) {
1722
+ throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);
1723
+ }
1724
+ const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
1725
+ const { data } = instruction;
1726
+ return {
1727
+ programAddress,
1728
+ ...accounts && accounts.length ? { accounts } : {},
1729
+ ...data && data.length ? { data } : {}
1730
+ };
1731
+ }
1732
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
1733
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
1734
+ return {
1735
+ blockhash: messageLifetimeToken,
1736
+ lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
1737
+ // U64 MAX
1738
+ };
1739
+ } else {
1740
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
1741
+ assertIsAddress(nonceAccountAddress);
1742
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
1743
+ assertIsAddress(nonceAuthorityAddress);
1744
+ return {
1745
+ nonce: messageLifetimeToken,
1746
+ nonceAccountAddress,
1747
+ nonceAuthorityAddress
1748
+ };
1749
+ }
1750
+ }
1751
+ function convertSignatures(compiledTransaction) {
1752
+ const {
1753
+ compiledMessage: { staticAccounts },
1754
+ signatures
1755
+ } = compiledTransaction;
1756
+ return signatures.reduce((acc, sig, index) => {
1757
+ const allZeros = sig.every((byte) => byte === 0);
1758
+ if (allZeros)
1759
+ return acc;
1760
+ const address2 = staticAccounts[index];
1761
+ return { ...acc, [address2]: sig };
1762
+ }, {});
1763
+ }
1764
+ function decompileTransaction(compiledTransaction, lastValidBlockHeight) {
1765
+ const { compiledMessage } = compiledTransaction;
1766
+ if ("addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {
1767
+ throw new Error("Cannot convert transaction with addressTableLookups");
1768
+ }
1769
+ const feePayer = compiledMessage.staticAccounts[0];
1770
+ if (!feePayer)
1771
+ throw new Error("No fee payer set in CompiledTransaction");
1772
+ const accountMetas = getAccountMetas(compiledMessage);
1773
+ const instructions = compiledMessage.instructions.map(
1774
+ (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)
1775
+ );
1776
+ const firstInstruction = instructions[0];
1777
+ const lifetimeConstraint = getLifetimeConstraint(
1778
+ compiledMessage.lifetimeToken,
1779
+ firstInstruction,
1780
+ lastValidBlockHeight
1781
+ );
1782
+ const signatures = convertSignatures(compiledTransaction);
1783
+ return pipe(
1784
+ createTransaction({ version: compiledMessage.version }),
1785
+ (tx) => setTransactionFeePayer(feePayer, tx),
1786
+ (tx) => instructions.reduce((acc, instruction) => {
1787
+ return appendTransactionInstruction(instruction, acc);
1788
+ }, tx),
1789
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
1790
+ (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx
1461
1791
  );
1462
1792
  }
1463
- function getMessageHeaderCodec() {
1464
- return struct(
1465
- [
1793
+ var lookupTableAddressDescription = "The address of the address lookup table account from which instruction addresses should be looked up" ;
1794
+ var writableIndicesDescription = "The indices of the accounts in the lookup table that should be loaded as writeable" ;
1795
+ var readableIndicesDescription = "The indices of the accounts in the lookup table that should be loaded as read-only" ;
1796
+ 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" ;
1797
+ var memoizedAddressTableLookupEncoder;
1798
+ function getAddressTableLookupEncoder() {
1799
+ if (!memoizedAddressTableLookupEncoder) {
1800
+ memoizedAddressTableLookupEncoder = getStructEncoder(
1466
1801
  [
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
- )
1802
+ ["lookupTableAddress", getAddressEncoder({ description: lookupTableAddressDescription })],
1803
+ [
1804
+ "writableIndices",
1805
+ getArrayEncoder(getU8Encoder(), {
1806
+ description: writableIndicesDescription,
1807
+ size: getShortU16Encoder()
1808
+ })
1809
+ ],
1810
+ [
1811
+ "readableIndices",
1812
+ getArrayEncoder(getU8Encoder(), {
1813
+ description: readableIndicesDescription,
1814
+ size: getShortU16Encoder()
1815
+ })
1816
+ ]
1473
1817
  ],
1818
+ { description: addressTableLookupDescription }
1819
+ );
1820
+ }
1821
+ return memoizedAddressTableLookupEncoder;
1822
+ }
1823
+ var memoizedAddressTableLookupDecoder;
1824
+ function getAddressTableLookupDecoder() {
1825
+ if (!memoizedAddressTableLookupDecoder) {
1826
+ memoizedAddressTableLookupDecoder = getStructDecoder(
1474
1827
  [
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
- )
1828
+ ["lookupTableAddress", getAddressDecoder({ description: lookupTableAddressDescription })],
1829
+ [
1830
+ "writableIndices",
1831
+ getArrayDecoder(getU8Decoder(), {
1832
+ description: writableIndicesDescription,
1833
+ size: getShortU16Decoder()
1834
+ })
1835
+ ],
1836
+ [
1837
+ "readableIndices",
1838
+ getArrayDecoder(getU8Decoder(), {
1839
+ description: readableIndicesDescription,
1840
+ size: getShortU16Decoder()
1841
+ })
1842
+ ]
1481
1843
  ],
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
- ]
1844
+ { description: addressTableLookupDescription }
1845
+ );
1846
+ }
1847
+ return memoizedAddressTableLookupDecoder;
1848
+ }
1849
+ var memoizedU8Encoder;
1850
+ function getMemoizedU8Encoder() {
1851
+ if (!memoizedU8Encoder)
1852
+ memoizedU8Encoder = getU8Encoder();
1853
+ return memoizedU8Encoder;
1854
+ }
1855
+ function getMemoizedU8EncoderDescription(description) {
1856
+ const encoder = getMemoizedU8Encoder();
1857
+ return {
1858
+ ...encoder,
1859
+ description: description ?? encoder.description
1860
+ };
1861
+ }
1862
+ var memoizedU8Decoder;
1863
+ function getMemoizedU8Decoder() {
1864
+ if (!memoizedU8Decoder)
1865
+ memoizedU8Decoder = getU8Decoder();
1866
+ return memoizedU8Decoder;
1867
+ }
1868
+ function getMemoizedU8DecoderDescription(description) {
1869
+ const decoder = getMemoizedU8Decoder();
1870
+ return {
1871
+ ...decoder,
1872
+ description: description ?? decoder.description
1873
+ };
1874
+ }
1875
+ var numSignerAccountsDescription = "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" ;
1876
+ 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" ;
1877
+ var numReadonlyNonSignerAccountsDescription = "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" ;
1878
+ var messageHeaderDescription = "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" ;
1879
+ function getMessageHeaderEncoder() {
1880
+ return getStructEncoder(
1881
+ [
1882
+ ["numSignerAccounts", getMemoizedU8EncoderDescription(numSignerAccountsDescription)],
1883
+ ["numReadonlySignerAccounts", getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],
1884
+ ["numReadonlyNonSignerAccounts", getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)]
1490
1885
  ],
1491
1886
  {
1492
- description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
1493
- }
1887
+ description: messageHeaderDescription
1888
+ }
1494
1889
  );
1495
1890
  }
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
- };
1891
+ function getMessageHeaderDecoder() {
1892
+ return getStructDecoder(
1893
+ [
1894
+ ["numSignerAccounts", getMemoizedU8DecoderDescription(numSignerAccountsDescription)],
1895
+ ["numReadonlySignerAccounts", getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],
1896
+ ["numReadonlyNonSignerAccounts", getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)]
1897
+ ],
1898
+ {
1899
+ description: messageHeaderDescription
1547
1900
  }
1548
1901
  );
1549
1902
  }
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
- );
1903
+ var programAddressIndexDescription = "The index of the program being called, according to the well-ordered accounts list for this transaction" ;
1904
+ var accountIndexDescription = "The index of an account, according to the well-ordered accounts list for this transaction" ;
1905
+ 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" ;
1906
+ var dataDescription = "An optional buffer of data passed to the instruction" ;
1907
+ var memoizedGetInstructionEncoder;
1908
+ function getInstructionEncoder() {
1909
+ if (!memoizedGetInstructionEncoder) {
1910
+ memoizedGetInstructionEncoder = mapEncoder(
1911
+ getStructEncoder([
1912
+ ["programAddressIndex", getU8Encoder({ description: programAddressIndexDescription })],
1913
+ [
1914
+ "accountIndices",
1915
+ getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {
1916
+ description: accountIndicesDescription,
1917
+ size: getShortU16Encoder()
1918
+ })
1919
+ ],
1920
+ ["data", getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })]
1921
+ ]),
1922
+ // Convert an instruction to have all fields defined
1923
+ (instruction) => {
1924
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
1925
+ return instruction;
1926
+ }
1927
+ return {
1928
+ ...instruction,
1929
+ accountIndices: instruction.accountIndices ?? [],
1930
+ data: instruction.data ?? new Uint8Array(0)
1931
+ };
1932
+ }
1933
+ );
1934
+ }
1935
+ return memoizedGetInstructionEncoder;
1555
1936
  }
1556
- function getUnimplementedDecoder(name) {
1557
- return () => {
1558
- throw getError("decoder", name);
1559
- };
1937
+ var memoizedGetInstructionDecoder;
1938
+ function getInstructionDecoder() {
1939
+ if (!memoizedGetInstructionDecoder) {
1940
+ memoizedGetInstructionDecoder = mapDecoder(
1941
+ getStructDecoder([
1942
+ ["programAddressIndex", getU8Decoder({ description: programAddressIndexDescription })],
1943
+ [
1944
+ "accountIndices",
1945
+ getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {
1946
+ description: accountIndicesDescription,
1947
+ size: getShortU16Decoder()
1948
+ })
1949
+ ],
1950
+ ["data", getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })]
1951
+ ]),
1952
+ // Convert an instruction to exclude optional fields if they are empty
1953
+ (instruction) => {
1954
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
1955
+ return instruction;
1956
+ }
1957
+ const { accountIndices, data, ...rest } = instruction;
1958
+ return {
1959
+ ...rest,
1960
+ ...accountIndices.length ? { accountIndices } : null,
1961
+ ...data.byteLength ? { data } : null
1962
+ };
1963
+ }
1964
+ );
1965
+ }
1966
+ return memoizedGetInstructionDecoder;
1560
1967
  }
1561
1968
  var VERSION_FLAG_MASK = 128;
1562
1969
  var BASE_CONFIG = {
@@ -1564,8 +1971,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
1564
1971
  fixedSize: null,
1565
1972
  maxSize: 1
1566
1973
  };
1567
- function deserialize(bytes3, offset = 0) {
1568
- const firstByte = bytes3[offset];
1974
+ function decode(bytes, offset = 0) {
1975
+ const firstByte = bytes[offset];
1569
1976
  if ((firstByte & VERSION_FLAG_MASK) === 0) {
1570
1977
  return ["legacy", offset];
1571
1978
  } else {
@@ -1573,7 +1980,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
1573
1980
  return [version, offset + 1];
1574
1981
  }
1575
1982
  }
1576
- function serialize(value) {
1983
+ function encode(value) {
1577
1984
  if (value === "legacy") {
1578
1985
  return new Uint8Array();
1579
1986
  }
@@ -1582,95 +1989,255 @@ this.globalThis.solanaWeb3 = (function (exports) {
1582
1989
  }
1583
1990
  return new Uint8Array([value | VERSION_FLAG_MASK]);
1584
1991
  }
1585
- function getTransactionVersionCodec() {
1992
+ function getTransactionVersionDecoder() {
1586
1993
  return {
1587
1994
  ...BASE_CONFIG,
1588
- deserialize,
1589
- serialize
1995
+ decode
1590
1996
  };
1591
1997
  }
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
- };
1998
+ function getTransactionVersionEncoder() {
1999
+ return {
2000
+ ...BASE_CONFIG,
2001
+ encode
2002
+ };
2003
+ }
2004
+ var staticAccountsDescription = "A compact-array of static account addresses belonging to this transaction" ;
2005
+ var lifetimeTokenDescription = "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" ;
2006
+ var instructionsDescription = "A compact-array of instructions belonging to this transaction" ;
2007
+ var addressTableLookupsDescription = "A compact array of address table lookups belonging to this transaction" ;
2008
+ function getCompiledMessageLegacyEncoder() {
2009
+ return getStructEncoder(getPreludeStructEncoderTuple());
2010
+ }
2011
+ function getCompiledMessageVersionedEncoder() {
2012
+ return mapEncoder(
2013
+ getStructEncoder([
2014
+ ...getPreludeStructEncoderTuple(),
2015
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
2016
+ ]),
2017
+ (value) => {
2018
+ if (value.version === "legacy") {
2019
+ return value;
1614
2020
  }
1615
- ).serialize(compiledMessage);
1616
- }
2021
+ return {
2022
+ ...value,
2023
+ addressTableLookups: value.addressTableLookups ?? []
2024
+ };
2025
+ }
2026
+ );
1617
2027
  }
1618
- function getPreludeStructSerializerTuple() {
2028
+ function getPreludeStructEncoderTuple() {
1619
2029
  return [
1620
- ["version", getTransactionVersionCodec()],
1621
- ["header", getMessageHeaderCodec()],
2030
+ ["version", getTransactionVersionEncoder()],
2031
+ ["header", getMessageHeaderEncoder()],
1622
2032
  [
1623
2033
  "staticAccounts",
1624
- array(getBase58EncodedAddressCodec(), {
1625
- description: "A compact-array of static account addresses belonging to this transaction" ,
1626
- size: shortU16()
2034
+ getArrayEncoder(getAddressEncoder(), {
2035
+ description: staticAccountsDescription,
2036
+ size: getShortU16Encoder()
1627
2037
  })
1628
2038
  ],
1629
2039
  [
1630
2040
  "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,
2041
+ getStringEncoder({
2042
+ description: lifetimeTokenDescription,
2043
+ encoding: getBase58Encoder(),
1634
2044
  size: 32
1635
2045
  })
1636
2046
  ],
1637
2047
  [
1638
2048
  "instructions",
1639
- array(getInstructionCodec(), {
1640
- description: "A compact-array of instructions belonging to this transaction" ,
1641
- size: shortU16()
2049
+ getArrayEncoder(getInstructionEncoder(), {
2050
+ description: instructionsDescription,
2051
+ size: getShortU16Encoder()
1642
2052
  })
1643
2053
  ]
1644
2054
  ];
1645
2055
  }
1646
- function getAddressTableLookupsSerializer() {
1647
- return array(getAddressTableLookupCodec(), {
1648
- ...{ description: "A compact array of address table lookups belonging to this transaction" } ,
1649
- size: shortU16()
2056
+ function getPreludeStructDecoderTuple() {
2057
+ return [
2058
+ ["version", getTransactionVersionDecoder()],
2059
+ ["header", getMessageHeaderDecoder()],
2060
+ [
2061
+ "staticAccounts",
2062
+ getArrayDecoder(getAddressDecoder(), {
2063
+ description: staticAccountsDescription,
2064
+ size: getShortU16Decoder()
2065
+ })
2066
+ ],
2067
+ [
2068
+ "lifetimeToken",
2069
+ getStringDecoder({
2070
+ description: lifetimeTokenDescription,
2071
+ encoding: getBase58Decoder(),
2072
+ size: 32
2073
+ })
2074
+ ],
2075
+ [
2076
+ "instructions",
2077
+ getArrayDecoder(getInstructionDecoder(), {
2078
+ description: instructionsDescription,
2079
+ size: getShortU16Decoder()
2080
+ })
2081
+ ],
2082
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
2083
+ ];
2084
+ }
2085
+ function getAddressTableLookupArrayEncoder() {
2086
+ return getArrayEncoder(getAddressTableLookupEncoder(), {
2087
+ description: addressTableLookupsDescription,
2088
+ size: getShortU16Encoder()
1650
2089
  });
1651
2090
  }
2091
+ function getAddressTableLookupArrayDecoder() {
2092
+ return getArrayDecoder(getAddressTableLookupDecoder(), {
2093
+ description: addressTableLookupsDescription,
2094
+ size: getShortU16Decoder()
2095
+ });
2096
+ }
2097
+ var messageDescription = "The wire format of a Solana transaction message" ;
1652
2098
  function getCompiledMessageEncoder() {
1653
2099
  return {
1654
- ...BASE_CONFIG2,
1655
- deserialize: getUnimplementedDecoder("CompiledMessage"),
1656
- serialize: serialize2
2100
+ description: messageDescription,
2101
+ encode: (compiledMessage) => {
2102
+ if (compiledMessage.version === "legacy") {
2103
+ return getCompiledMessageLegacyEncoder().encode(compiledMessage);
2104
+ } else {
2105
+ return getCompiledMessageVersionedEncoder().encode(compiledMessage);
2106
+ }
2107
+ },
2108
+ fixedSize: null,
2109
+ maxSize: null
1657
2110
  };
1658
2111
  }
1659
- async function getCompiledMessageSignature(message, secretKey) {
1660
- const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
1661
- const signature = await signBytes(secretKey, wireMessageBytes);
1662
- return signature;
2112
+ function getCompiledMessageDecoder() {
2113
+ return mapDecoder(
2114
+ getStructDecoder(getPreludeStructDecoderTuple(), {
2115
+ description: messageDescription
2116
+ }),
2117
+ ({ addressTableLookups, ...restOfMessage }) => {
2118
+ if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
2119
+ return restOfMessage;
2120
+ }
2121
+ return { ...restOfMessage, addressTableLookups };
2122
+ }
2123
+ );
2124
+ }
2125
+ var signaturesDescription = "A compact array of 64-byte, base-64 encoded Ed25519 signatures" ;
2126
+ var transactionDescription = "The wire format of a Solana transaction" ;
2127
+ function getCompiledTransactionEncoder() {
2128
+ return getStructEncoder(
2129
+ [
2130
+ [
2131
+ "signatures",
2132
+ getArrayEncoder(getBytesEncoder({ size: 64 }), {
2133
+ description: signaturesDescription,
2134
+ size: getShortU16Encoder()
2135
+ })
2136
+ ],
2137
+ ["compiledMessage", getCompiledMessageEncoder()]
2138
+ ],
2139
+ {
2140
+ description: transactionDescription
2141
+ }
2142
+ );
1663
2143
  }
1664
- async function signTransaction(keyPair, transaction) {
2144
+ function getSignatureDecoder() {
2145
+ return mapDecoder(getBytesDecoder({ size: 64 }), (bytes) => bytes);
2146
+ }
2147
+ function getCompiledTransactionDecoder() {
2148
+ return getStructDecoder(
2149
+ [
2150
+ [
2151
+ "signatures",
2152
+ getArrayDecoder(getSignatureDecoder(), {
2153
+ description: signaturesDescription,
2154
+ size: getShortU16Decoder()
2155
+ })
2156
+ ],
2157
+ ["compiledMessage", getCompiledMessageDecoder()]
2158
+ ],
2159
+ {
2160
+ description: transactionDescription
2161
+ }
2162
+ );
2163
+ }
2164
+ function getTransactionEncoder() {
2165
+ return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
2166
+ }
2167
+ function getTransactionDecoder(lastValidBlockHeight) {
2168
+ return mapDecoder(
2169
+ getCompiledTransactionDecoder(),
2170
+ (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)
2171
+ );
2172
+ }
2173
+ function getTransactionCodec(lastValidBlockHeight) {
2174
+ return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));
2175
+ }
2176
+ var base58Encoder2;
2177
+ var base58Decoder;
2178
+ function assertIsTransactionSignature(putativeTransactionSignature) {
2179
+ if (!base58Encoder2)
2180
+ base58Encoder2 = getBase58Encoder();
2181
+ try {
2182
+ if (
2183
+ // Lowest value (64 bytes of zeroes)
2184
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
2185
+ putativeTransactionSignature.length > 88
2186
+ ) {
2187
+ throw new Error("Expected input string to decode to a byte array of length 64.");
2188
+ }
2189
+ const bytes = base58Encoder2.encode(putativeTransactionSignature);
2190
+ const numBytes = bytes.byteLength;
2191
+ if (numBytes !== 64) {
2192
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
2193
+ }
2194
+ } catch (e3) {
2195
+ throw new Error(`\`${putativeTransactionSignature}\` is not a transaction signature`, {
2196
+ cause: e3
2197
+ });
2198
+ }
2199
+ }
2200
+ function isTransactionSignature(putativeTransactionSignature) {
2201
+ if (!base58Encoder2)
2202
+ base58Encoder2 = getBase58Encoder();
2203
+ if (
2204
+ // Lowest value (64 bytes of zeroes)
2205
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
2206
+ putativeTransactionSignature.length > 88
2207
+ ) {
2208
+ return false;
2209
+ }
2210
+ const bytes = base58Encoder2.encode(putativeTransactionSignature);
2211
+ const numBytes = bytes.byteLength;
2212
+ if (numBytes !== 64) {
2213
+ return false;
2214
+ }
2215
+ return true;
2216
+ }
2217
+ function getSignatureFromTransaction(transaction) {
2218
+ if (!base58Decoder)
2219
+ base58Decoder = getBase58Decoder();
2220
+ const signatureBytes = transaction.signatures[transaction.feePayer];
2221
+ if (!signatureBytes) {
2222
+ throw new Error(
2223
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
2224
+ );
2225
+ }
2226
+ const transactionSignature2 = base58Decoder.decode(signatureBytes)[0];
2227
+ return transactionSignature2;
2228
+ }
2229
+ async function signTransaction(keyPairs, transaction) {
1665
2230
  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
- };
2231
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
2232
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
2233
+ const publicKeySignaturePairs = await Promise.all(
2234
+ keyPairs.map(
2235
+ (keyPair) => Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])
2236
+ )
2237
+ );
2238
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
2239
+ nextSignatures[signerPublicKey] = signature;
2240
+ }
1674
2241
  const out = {
1675
2242
  ...transaction,
1676
2243
  signatures: nextSignatures
@@ -1678,52 +2245,190 @@ this.globalThis.solanaWeb3 = (function (exports) {
1678
2245
  Object.freeze(out);
1679
2246
  return out;
1680
2247
  }
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));
2248
+ function transactionSignature(putativeTransactionSignature) {
2249
+ assertIsTransactionSignature(putativeTransactionSignature);
2250
+ return putativeTransactionSignature;
2251
+ }
2252
+ function assertTransactionIsFullySigned(transaction) {
2253
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole2(a.role)) ?? []).map((a) => a.address);
2254
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
2255
+ requiredSigners.forEach((address2) => {
2256
+ if (!transaction.signatures[address2]) {
2257
+ throw new Error(`Transaction is missing signature for address \`${address2}\``);
1688
2258
  }
1689
- } else {
1690
- signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
2259
+ });
2260
+ }
2261
+ function getBase64EncodedWireTransaction(transaction) {
2262
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
2263
+ {
2264
+ return btoa(String.fromCharCode(...wireTransactionBytes));
1691
2265
  }
1692
- return {
1693
- compiledMessage,
1694
- signatures
2266
+ }
2267
+
2268
+ // src/airdrop.ts
2269
+ init_env_shim();
2270
+
2271
+ // src/airdrop-confirmer.ts
2272
+ init_env_shim();
2273
+
2274
+ // src/transaction-confirmation-strategy-racer.ts
2275
+ init_env_shim();
2276
+ async function raceStrategies(signature, config, getSpecificStrategiesForRace) {
2277
+ const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;
2278
+ callerAbortSignal?.throwIfAborted();
2279
+ const abortController = new AbortController();
2280
+ if (callerAbortSignal) {
2281
+ const handleAbort = () => {
2282
+ abortController.abort();
2283
+ };
2284
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
2285
+ }
2286
+ try {
2287
+ const specificStrategies = getSpecificStrategiesForRace({
2288
+ ...config,
2289
+ abortSignal: abortController.signal
2290
+ });
2291
+ return await Promise.race([
2292
+ getRecentSignatureConfirmationPromise({
2293
+ abortSignal: abortController.signal,
2294
+ commitment,
2295
+ signature
2296
+ }),
2297
+ ...specificStrategies
2298
+ ]);
2299
+ } finally {
2300
+ abortController.abort();
2301
+ }
2302
+ }
2303
+
2304
+ // src/transaction-confirmation-strategy-recent-signature.ts
2305
+ init_env_shim();
2306
+ function createRecentSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions) {
2307
+ return async function getRecentSignatureConfirmationPromise({
2308
+ abortSignal: callerAbortSignal,
2309
+ commitment,
2310
+ signature
2311
+ }) {
2312
+ const abortController = new AbortController();
2313
+ function handleAbort() {
2314
+ abortController.abort();
2315
+ }
2316
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
2317
+ const signatureStatusNotifications = await rpcSubscriptions.signatureNotifications(signature, { commitment }).subscribe({ abortSignal: abortController.signal });
2318
+ const signatureDidCommitPromise = (async () => {
2319
+ for await (const signatureStatusNotification of signatureStatusNotifications) {
2320
+ if (signatureStatusNotification.value.err) {
2321
+ throw new Error(`The transaction with signature \`${signature}\` failed.`, {
2322
+ cause: signatureStatusNotification.value.err
2323
+ });
2324
+ } else {
2325
+ return;
2326
+ }
2327
+ }
2328
+ })();
2329
+ const signatureStatusLookupPromise = (async () => {
2330
+ const { value: signatureStatusResults } = await rpc.getSignatureStatuses([signature]).send({ abortSignal: abortController.signal });
2331
+ const signatureStatus = signatureStatusResults[0];
2332
+ if (signatureStatus && signatureStatus.confirmationStatus && commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0) {
2333
+ return;
2334
+ } else {
2335
+ await new Promise(() => {
2336
+ });
2337
+ }
2338
+ })();
2339
+ try {
2340
+ return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);
2341
+ } finally {
2342
+ abortController.abort();
2343
+ }
1695
2344
  };
1696
2345
  }
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);
2346
+
2347
+ // src/transaction-confirmation-strategy-timeout.ts
2348
+ init_env_shim();
2349
+ async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }) {
2350
+ return await new Promise((_, reject) => {
2351
+ const handleAbort = (e3) => {
2352
+ clearTimeout(timeoutId);
2353
+ const abortError = new DOMException(e3.target.reason, "AbortError");
2354
+ reject(abortError);
2355
+ };
2356
+ callerAbortSignal.addEventListener("abort", handleAbort);
2357
+ const timeoutMs = commitment === "processed" ? 3e4 : 6e4;
2358
+ const startMs = performance.now();
2359
+ const timeoutId = (
2360
+ // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure
2361
+ // elapsed time instead of active time.
2362
+ // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
2363
+ setTimeout(() => {
2364
+ const elapsedMs = performance.now() - startMs;
2365
+ reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, "TimeoutError"));
2366
+ }, timeoutMs)
2367
+ );
2368
+ });
1714
2369
  }
1715
- function getTransactionEncoder() {
1716
- return {
1717
- ...BASE_CONFIG3,
1718
- deserialize: getUnimplementedDecoder("CompiledMessage"),
1719
- serialize: serialize3
2370
+
2371
+ // src/airdrop-confirmer.ts
2372
+ function createDefaultSignatureOnlyRecentTransactionConfirmer({
2373
+ rpc,
2374
+ rpcSubscriptions
2375
+ }) {
2376
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
2377
+ rpc,
2378
+ rpcSubscriptions
2379
+ );
2380
+ return async function confirmSignatureOnlyRecentTransaction(config) {
2381
+ await waitForRecentTransactionConfirmationUntilTimeout({
2382
+ ...config,
2383
+ getRecentSignatureConfirmationPromise,
2384
+ getTimeoutPromise
2385
+ });
1720
2386
  };
1721
2387
  }
1722
- function getBase64EncodedWireTransaction(transaction) {
1723
- const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
1724
- {
1725
- return btoa(String.fromCharCode(...wireTransactionBytes));
1726
- }
2388
+ async function waitForRecentTransactionConfirmationUntilTimeout(config) {
2389
+ await raceStrategies(
2390
+ config.signature,
2391
+ config,
2392
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise: getTimeoutPromise2 }) {
2393
+ return [
2394
+ getTimeoutPromise2({
2395
+ abortSignal,
2396
+ commitment
2397
+ })
2398
+ ];
2399
+ }
2400
+ );
2401
+ }
2402
+
2403
+ // src/airdrop.ts
2404
+ function createDefaultAirdropRequester({ rpc, rpcSubscriptions }) {
2405
+ const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({
2406
+ rpc,
2407
+ rpcSubscriptions
2408
+ });
2409
+ return async function requestAirdrop(config) {
2410
+ return await requestAndConfirmAirdrop({
2411
+ ...config,
2412
+ confirmSignatureOnlyTransaction,
2413
+ rpc
2414
+ });
2415
+ };
2416
+ }
2417
+ async function requestAndConfirmAirdrop({
2418
+ abortSignal,
2419
+ commitment,
2420
+ confirmSignatureOnlyTransaction,
2421
+ lamports: lamports2,
2422
+ recipientAddress,
2423
+ rpc
2424
+ }) {
2425
+ const airdropTransactionSignature = await rpc.requestAirdrop(recipientAddress, lamports2, { commitment }).send({ abortSignal });
2426
+ await confirmSignatureOnlyTransaction({
2427
+ abortSignal,
2428
+ commitment,
2429
+ signature: airdropTransactionSignature
2430
+ });
2431
+ return airdropTransactionSignature;
1727
2432
  }
1728
2433
 
1729
2434
  // src/rpc.ts
@@ -1757,68 +2462,215 @@ this.globalThis.solanaWeb3 = (function (exports) {
1757
2462
  return visitNode(params, [], onIntegerOverflow);
1758
2463
  }
1759
2464
  var KEYPATH_WILDCARD = {};
2465
+ var jsonParsedTokenAccountsConfigs = [
2466
+ // parsed Token/Token22 token account
2467
+ ["data", "parsed", "info", "tokenAmount", "decimals"],
2468
+ ["data", "parsed", "info", "tokenAmount", "uiAmount"],
2469
+ ["data", "parsed", "info", "rentExemptReserve", "decimals"],
2470
+ ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
2471
+ ["data", "parsed", "info", "delegatedAmount", "decimals"],
2472
+ ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
2473
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "olderTransferFee", "transferFeeBasisPoints"],
2474
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "newerTransferFee", "transferFeeBasisPoints"],
2475
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
2476
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
2477
+ ];
2478
+ var jsonParsedAccountsConfigs = [
2479
+ ...jsonParsedTokenAccountsConfigs,
2480
+ // parsed AddressTableLookup account
2481
+ ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
2482
+ // parsed Config account
2483
+ ["data", "parsed", "info", "slashPenalty"],
2484
+ ["data", "parsed", "info", "warmupCooldownRate"],
2485
+ // parsed Token/Token22 mint account
2486
+ ["data", "parsed", "info", "decimals"],
2487
+ // parsed Token/Token22 multisig account
2488
+ ["data", "parsed", "info", "numRequiredSigners"],
2489
+ ["data", "parsed", "info", "numValidSigners"],
2490
+ // parsed Stake account
2491
+ ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
2492
+ // parsed Sysvar rent account
2493
+ ["data", "parsed", "info", "exemptionThreshold"],
2494
+ ["data", "parsed", "info", "burnPercent"],
2495
+ // parsed Vote account
2496
+ ["data", "parsed", "info", "commission"],
2497
+ ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
2498
+ ];
1760
2499
  var memoizedNotificationKeypaths;
1761
2500
  var memoizedResponseKeypaths;
1762
2501
  function getAllowedNumericKeypathsForNotification() {
1763
2502
  if (!memoizedNotificationKeypaths) {
1764
- memoizedNotificationKeypaths = {};
2503
+ memoizedNotificationKeypaths = {
2504
+ accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
2505
+ blockNotifications: [
2506
+ ["value", "block", "blockTime"],
2507
+ [
2508
+ "value",
2509
+ "block",
2510
+ "transactions",
2511
+ KEYPATH_WILDCARD,
2512
+ "meta",
2513
+ "preTokenBalances",
2514
+ KEYPATH_WILDCARD,
2515
+ "accountIndex"
2516
+ ],
2517
+ [
2518
+ "value",
2519
+ "block",
2520
+ "transactions",
2521
+ KEYPATH_WILDCARD,
2522
+ "meta",
2523
+ "preTokenBalances",
2524
+ KEYPATH_WILDCARD,
2525
+ "uiTokenAmount",
2526
+ "decimals"
2527
+ ],
2528
+ [
2529
+ "value",
2530
+ "block",
2531
+ "transactions",
2532
+ KEYPATH_WILDCARD,
2533
+ "meta",
2534
+ "postTokenBalances",
2535
+ KEYPATH_WILDCARD,
2536
+ "accountIndex"
2537
+ ],
2538
+ [
2539
+ "value",
2540
+ "block",
2541
+ "transactions",
2542
+ KEYPATH_WILDCARD,
2543
+ "meta",
2544
+ "postTokenBalances",
2545
+ KEYPATH_WILDCARD,
2546
+ "uiTokenAmount",
2547
+ "decimals"
2548
+ ],
2549
+ ["value", "block", "transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2550
+ [
2551
+ "value",
2552
+ "block",
2553
+ "transactions",
2554
+ KEYPATH_WILDCARD,
2555
+ "meta",
2556
+ "innerInstructions",
2557
+ KEYPATH_WILDCARD,
2558
+ "index"
2559
+ ],
2560
+ [
2561
+ "value",
2562
+ "block",
2563
+ "transactions",
2564
+ KEYPATH_WILDCARD,
2565
+ "meta",
2566
+ "innerInstructions",
2567
+ KEYPATH_WILDCARD,
2568
+ "instructions",
2569
+ KEYPATH_WILDCARD,
2570
+ "programIdIndex"
2571
+ ],
2572
+ [
2573
+ "value",
2574
+ "block",
2575
+ "transactions",
2576
+ KEYPATH_WILDCARD,
2577
+ "meta",
2578
+ "innerInstructions",
2579
+ KEYPATH_WILDCARD,
2580
+ "instructions",
2581
+ KEYPATH_WILDCARD,
2582
+ "accounts",
2583
+ KEYPATH_WILDCARD
2584
+ ],
2585
+ [
2586
+ "value",
2587
+ "block",
2588
+ "transactions",
2589
+ KEYPATH_WILDCARD,
2590
+ "transaction",
2591
+ "message",
2592
+ "addressTableLookups",
2593
+ KEYPATH_WILDCARD,
2594
+ "writableIndexes",
2595
+ KEYPATH_WILDCARD
2596
+ ],
2597
+ [
2598
+ "value",
2599
+ "block",
2600
+ "transactions",
2601
+ KEYPATH_WILDCARD,
2602
+ "transaction",
2603
+ "message",
2604
+ "addressTableLookups",
2605
+ KEYPATH_WILDCARD,
2606
+ "readonlyIndexes",
2607
+ KEYPATH_WILDCARD
2608
+ ],
2609
+ [
2610
+ "value",
2611
+ "block",
2612
+ "transactions",
2613
+ KEYPATH_WILDCARD,
2614
+ "transaction",
2615
+ "message",
2616
+ "instructions",
2617
+ KEYPATH_WILDCARD,
2618
+ "programIdIndex"
2619
+ ],
2620
+ [
2621
+ "value",
2622
+ "block",
2623
+ "transactions",
2624
+ KEYPATH_WILDCARD,
2625
+ "transaction",
2626
+ "message",
2627
+ "instructions",
2628
+ KEYPATH_WILDCARD,
2629
+ "accounts",
2630
+ KEYPATH_WILDCARD
2631
+ ],
2632
+ [
2633
+ "value",
2634
+ "block",
2635
+ "transactions",
2636
+ KEYPATH_WILDCARD,
2637
+ "transaction",
2638
+ "message",
2639
+ "header",
2640
+ "numReadonlySignedAccounts"
2641
+ ],
2642
+ [
2643
+ "value",
2644
+ "block",
2645
+ "transactions",
2646
+ KEYPATH_WILDCARD,
2647
+ "transaction",
2648
+ "message",
2649
+ "header",
2650
+ "numReadonlyUnsignedAccounts"
2651
+ ],
2652
+ [
2653
+ "value",
2654
+ "block",
2655
+ "transactions",
2656
+ KEYPATH_WILDCARD,
2657
+ "transaction",
2658
+ "message",
2659
+ "header",
2660
+ "numRequiredSignatures"
2661
+ ],
2662
+ ["value", "block", "rewards", KEYPATH_WILDCARD, "commission"]
2663
+ ],
2664
+ programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [
2665
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2666
+ [KEYPATH_WILDCARD, "account", ...c]
2667
+ ])
2668
+ };
1765
2669
  }
1766
2670
  return memoizedNotificationKeypaths;
1767
2671
  }
1768
2672
  function getAllowedNumericKeypathsForResponse() {
1769
2673
  if (!memoizedResponseKeypaths) {
1770
- const jsonParsedTokenAccountsConfigs = [
1771
- // parsed Token/Token22 token account
1772
- ["data", "parsed", "info", "tokenAmount", "decimals"],
1773
- ["data", "parsed", "info", "tokenAmount", "uiAmount"],
1774
- ["data", "parsed", "info", "rentExemptReserve", "decimals"],
1775
- ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
1776
- ["data", "parsed", "info", "delegatedAmount", "decimals"],
1777
- ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
1778
- [
1779
- "data",
1780
- "parsed",
1781
- "info",
1782
- "extensions",
1783
- KEYPATH_WILDCARD,
1784
- "state",
1785
- "olderTransferFee",
1786
- "transferFeeBasisPoints"
1787
- ],
1788
- [
1789
- "data",
1790
- "parsed",
1791
- "info",
1792
- "extensions",
1793
- KEYPATH_WILDCARD,
1794
- "state",
1795
- "newerTransferFee",
1796
- "transferFeeBasisPoints"
1797
- ],
1798
- ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
1799
- ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
1800
- ];
1801
- const jsonParsedAccountsConfigs = [
1802
- ...jsonParsedTokenAccountsConfigs,
1803
- // parsed AddressTableLookup account
1804
- ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
1805
- // parsed Config account
1806
- ["data", "parsed", "info", "slashPenalty"],
1807
- ["data", "parsed", "info", "warmupCooldownRate"],
1808
- // parsed Token/Token22 mint account
1809
- ["data", "parsed", "info", "decimals"],
1810
- // parsed Token/Token22 multisig account
1811
- ["data", "parsed", "info", "numRequiredSigners"],
1812
- ["data", "parsed", "info", "numValidSigners"],
1813
- // parsed Stake account
1814
- ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
1815
- // parsed Sysvar rent account
1816
- ["data", "parsed", "info", "exemptionThreshold"],
1817
- ["data", "parsed", "info", "burnPercent"],
1818
- // parsed Vote account
1819
- ["data", "parsed", "info", "commission"],
1820
- ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
1821
- ];
1822
2674
  memoizedResponseKeypaths = {
1823
2675
  getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
1824
2676
  getBlock: [
@@ -2083,6 +2935,9 @@ this.globalThis.solanaWeb3 = (function (exports) {
2083
2935
  }
2084
2936
  });
2085
2937
  }
2938
+ function createSolanaRpcSubscriptionsApi_UNSTABLE(config) {
2939
+ return createSolanaRpcSubscriptionsApi(config);
2940
+ }
2086
2941
 
2087
2942
  // ../rpc-transport/dist/index.browser.js
2088
2943
  init_env_shim();
@@ -2162,8 +3017,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
2162
3017
  }
2163
3018
  function createPendingRpcSubscription(rpcConfig, { params, subscribeMethodName, unsubscribeMethodName, responseProcessor }) {
2164
3019
  return {
2165
- async subscribe(options) {
2166
- options?.abortSignal?.throwIfAborted();
3020
+ async subscribe({ abortSignal }) {
3021
+ abortSignal.throwIfAborted();
2167
3022
  let subscriptionId;
2168
3023
  function handleCleanup() {
2169
3024
  if (subscriptionId !== void 0) {
@@ -2175,7 +3030,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2175
3030
  connectionAbortController.abort();
2176
3031
  }
2177
3032
  }
2178
- options?.abortSignal?.addEventListener("abort", handleCleanup);
3033
+ abortSignal.addEventListener("abort", handleCleanup);
2179
3034
  const connectionAbortController = new AbortController();
2180
3035
  const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);
2181
3036
  const connection = await rpcConfig.transport({
@@ -2183,7 +3038,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2183
3038
  signal: connectionAbortController.signal
2184
3039
  });
2185
3040
  function handleConnectionCleanup() {
2186
- options?.abortSignal?.removeEventListener("abort", handleCleanup);
3041
+ abortSignal.removeEventListener("abort", handleCleanup);
2187
3042
  }
2188
3043
  registerIterableCleanup(connection, handleConnectionCleanup);
2189
3044
  for await (const message of connection) {
@@ -2243,7 +3098,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2243
3098
  function createJsonSubscriptionRpc(rpcConfig) {
2244
3099
  return makeProxy2(rpcConfig);
2245
3100
  }
2246
- var e = globalThis.fetch;
3101
+ var e2 = globalThis.fetch;
2247
3102
  var SolanaHttpError = class extends Error {
2248
3103
  constructor(details) {
2249
3104
  super(`HTTP error (${details.statusCode}): ${details.message}`);
@@ -2302,16 +3157,10 @@ this.globalThis.solanaWeb3 = (function (exports) {
2302
3157
  }
2303
3158
  return out;
2304
3159
  }
2305
- function createHttpTransport({ httpAgentNodeOnly, headers, url }) {
3160
+ function createHttpTransport({ headers, url }) {
2306
3161
  if (headers) {
2307
3162
  assertIsAllowedHttpRequestHeaders(headers);
2308
3163
  }
2309
- const agent = void 0;
2310
- if (httpAgentNodeOnly != null) {
2311
- console.warn(
2312
- "createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ignored; HTTP agents are only usable in Node environments."
2313
- );
2314
- }
2315
3164
  const customHeaders = headers && normalizeHeaders(headers);
2316
3165
  return async function makeHttpRequest({
2317
3166
  payload,
@@ -2319,7 +3168,6 @@ this.globalThis.solanaWeb3 = (function (exports) {
2319
3168
  }) {
2320
3169
  const body = JSON.stringify(payload);
2321
3170
  const requestInfo = {
2322
- agent,
2323
3171
  body,
2324
3172
  headers: {
2325
3173
  ...customHeaders,
@@ -2331,7 +3179,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2331
3179
  method: "POST",
2332
3180
  signal
2333
3181
  };
2334
- const response = await e(url, requestInfo);
3182
+ const response = await e2(url, requestInfo);
2335
3183
  if (!response.ok) {
2336
3184
  throw new SolanaHttpError({
2337
3185
  message: response.statusText,
@@ -2341,7 +3189,10 @@ this.globalThis.solanaWeb3 = (function (exports) {
2341
3189
  return await response.json();
2342
3190
  };
2343
3191
  }
2344
- var e2 = globalThis.WebSocket;
3192
+ var e22 = globalThis.WebSocket;
3193
+ var EXPLICIT_ABORT_TOKEN = Symbol(
3194
+ "This symbol is thrown from a socket's iterator when the connection is explicity aborted by the user"
3195
+ );
2345
3196
  async function createWebSocketConnection({
2346
3197
  sendBufferHighWatermark,
2347
3198
  signal,
@@ -2350,8 +3201,19 @@ this.globalThis.solanaWeb3 = (function (exports) {
2350
3201
  return new Promise((resolve, reject) => {
2351
3202
  signal.addEventListener("abort", handleAbort, { once: true });
2352
3203
  const iteratorState = /* @__PURE__ */ new Map();
3204
+ function errorAndClearAllIteratorStates(reason) {
3205
+ const errorCallbacks = [...iteratorState.values()].filter((state) => state.__hasPolled).map(({ onError }) => onError);
3206
+ iteratorState.clear();
3207
+ errorCallbacks.forEach((cb) => {
3208
+ try {
3209
+ cb(reason);
3210
+ } catch {
3211
+ }
3212
+ });
3213
+ }
2353
3214
  function handleAbort() {
2354
- if (webSocket.readyState !== e2.CLOSED && webSocket.readyState !== e2.CLOSING) {
3215
+ errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);
3216
+ if (webSocket.readyState !== e22.CLOSED && webSocket.readyState !== e22.CLOSING) {
2355
3217
  webSocket.close(1e3);
2356
3218
  }
2357
3219
  }
@@ -2362,15 +3224,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2362
3224
  webSocket.removeEventListener("error", handleError);
2363
3225
  webSocket.removeEventListener("open", handleOpen);
2364
3226
  webSocket.removeEventListener("message", handleMessage);
2365
- iteratorState.forEach((state, iteratorKey) => {
2366
- if (state.__hasPolled) {
2367
- const { onError } = state;
2368
- iteratorState.delete(iteratorKey);
2369
- onError(ev);
2370
- } else {
2371
- iteratorState.delete(iteratorKey);
2372
- }
2373
- });
3227
+ errorAndClearAllIteratorStates(ev);
2374
3228
  }
2375
3229
  function handleError(ev) {
2376
3230
  if (!hasConnected) {
@@ -2387,11 +3241,11 @@ this.globalThis.solanaWeb3 = (function (exports) {
2387
3241
  resolve({
2388
3242
  async send(payload) {
2389
3243
  const message = JSON.stringify(payload);
2390
- if (!bufferDrainWatcher && webSocket.readyState === e2.OPEN && webSocket.bufferedAmount > sendBufferHighWatermark) {
3244
+ if (!bufferDrainWatcher && webSocket.readyState === e22.OPEN && webSocket.bufferedAmount > sendBufferHighWatermark) {
2391
3245
  let onCancel;
2392
3246
  const promise = new Promise((resolve2, reject2) => {
2393
3247
  const intervalId = setInterval(() => {
2394
- if (webSocket.readyState !== e2.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
3248
+ if (webSocket.readyState !== e22.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
2395
3249
  clearInterval(intervalId);
2396
3250
  bufferDrainWatcher = void 0;
2397
3251
  resolve2();
@@ -2438,15 +3292,15 @@ this.globalThis.solanaWeb3 = (function (exports) {
2438
3292
  yield* queuedMessages;
2439
3293
  } else {
2440
3294
  try {
2441
- yield await new Promise((onMessage, onError) => {
3295
+ yield await new Promise((resolve2, reject2) => {
2442
3296
  iteratorState.set(iteratorKey, {
2443
3297
  __hasPolled: true,
2444
- onError,
2445
- onMessage
3298
+ onError: reject2,
3299
+ onMessage: resolve2
2446
3300
  });
2447
3301
  });
2448
3302
  } catch (e3) {
2449
- if (e3 !== null && typeof e3 === "object" && "type" in e3 && e3.type === "close" && "wasClean" in e3 && e3.wasClean) {
3303
+ if (e3 === EXPLICIT_ABORT_TOKEN) {
2450
3304
  return;
2451
3305
  } else {
2452
3306
  throw new Error("WebSocket connection closed", { cause: e3 });
@@ -2472,7 +3326,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2472
3326
  }
2473
3327
  });
2474
3328
  }
2475
- const webSocket = new e2(url);
3329
+ const webSocket = new e22(url);
2476
3330
  webSocket.addEventListener("close", handleClose);
2477
3331
  webSocket.addEventListener("error", handleError);
2478
3332
  webSocket.addEventListener("open", handleOpen);
@@ -2502,6 +3356,9 @@ this.globalThis.solanaWeb3 = (function (exports) {
2502
3356
  };
2503
3357
  }
2504
3358
 
3359
+ // src/rpc.ts
3360
+ var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
3361
+
2505
3362
  // src/rpc-default-config.ts
2506
3363
  init_env_shim();
2507
3364
 
@@ -2542,6 +3399,197 @@ this.globalThis.solanaWeb3 = (function (exports) {
2542
3399
  }
2543
3400
  };
2544
3401
 
3402
+ // src/rpc-subscription-coalescer.ts
3403
+ init_env_shim();
3404
+
3405
+ // src/cached-abortable-iterable.ts
3406
+ init_env_shim();
3407
+ function registerIterableCleanup2(iterable, cleanupFn) {
3408
+ (async () => {
3409
+ try {
3410
+ for await (const _ of iterable)
3411
+ ;
3412
+ } catch {
3413
+ } finally {
3414
+ cleanupFn();
3415
+ }
3416
+ })();
3417
+ }
3418
+ function getCachedAbortableIterableFactory({
3419
+ getAbortSignalFromInputArgs,
3420
+ getCacheEntryMissingError,
3421
+ getCacheKeyFromInputArgs,
3422
+ onCacheHit,
3423
+ onCreateIterable
3424
+ }) {
3425
+ const cache = /* @__PURE__ */ new Map();
3426
+ function getCacheEntryOrThrow(cacheKey) {
3427
+ const currentCacheEntry = cache.get(cacheKey);
3428
+ if (!currentCacheEntry) {
3429
+ throw getCacheEntryMissingError(cacheKey);
3430
+ }
3431
+ return currentCacheEntry;
3432
+ }
3433
+ return async (...args) => {
3434
+ const cacheKey = getCacheKeyFromInputArgs(...args);
3435
+ const signal = getAbortSignalFromInputArgs(...args);
3436
+ if (cacheKey === void 0) {
3437
+ return await onCreateIterable(signal, ...args);
3438
+ }
3439
+ const cleanup = () => {
3440
+ cache.delete(cacheKey);
3441
+ signal.removeEventListener("abort", handleAbort);
3442
+ };
3443
+ const handleAbort = () => {
3444
+ const cacheEntry = getCacheEntryOrThrow(cacheKey);
3445
+ if (cacheEntry.purgeScheduled !== true) {
3446
+ cacheEntry.purgeScheduled = true;
3447
+ globalThis.queueMicrotask(() => {
3448
+ cacheEntry.purgeScheduled = false;
3449
+ if (cacheEntry.referenceCount === 0) {
3450
+ cacheEntry.abortController.abort();
3451
+ cleanup();
3452
+ }
3453
+ });
3454
+ }
3455
+ cacheEntry.referenceCount--;
3456
+ };
3457
+ signal.addEventListener("abort", handleAbort);
3458
+ try {
3459
+ const cacheEntry = cache.get(cacheKey);
3460
+ if (!cacheEntry) {
3461
+ const singletonAbortController = new AbortController();
3462
+ const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);
3463
+ const newCacheEntry = {
3464
+ abortController: singletonAbortController,
3465
+ iterable: newIterablePromise,
3466
+ purgeScheduled: false,
3467
+ referenceCount: 1
3468
+ };
3469
+ cache.set(cacheKey, newCacheEntry);
3470
+ const newIterable = await newIterablePromise;
3471
+ registerIterableCleanup2(newIterable, cleanup);
3472
+ newCacheEntry.iterable = newIterable;
3473
+ return newIterable;
3474
+ } else {
3475
+ cacheEntry.referenceCount++;
3476
+ const iterableOrIterablePromise = cacheEntry.iterable;
3477
+ const cachedIterable = "then" in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;
3478
+ await onCacheHit(cachedIterable, ...args);
3479
+ return cachedIterable;
3480
+ }
3481
+ } catch (e3) {
3482
+ cleanup();
3483
+ throw e3;
3484
+ }
3485
+ };
3486
+ }
3487
+
3488
+ // src/rpc-subscription-coalescer.ts
3489
+ var EXPLICIT_ABORT_TOKEN2 = Symbol(
3490
+ "This symbol is thrown from a subscription's iterator when the subscription is explicitly aborted by the user"
3491
+ );
3492
+ function registerIterableCleanup3(iterable, cleanupFn) {
3493
+ (async () => {
3494
+ try {
3495
+ for await (const _ of iterable)
3496
+ ;
3497
+ } catch {
3498
+ } finally {
3499
+ cleanupFn();
3500
+ }
3501
+ })();
3502
+ }
3503
+ function getRpcSubscriptionsWithSubscriptionCoalescing({
3504
+ getDeduplicationKey,
3505
+ rpcSubscriptions
3506
+ }) {
3507
+ const cache = /* @__PURE__ */ new Map();
3508
+ return new Proxy(rpcSubscriptions, {
3509
+ defineProperty() {
3510
+ return false;
3511
+ },
3512
+ deleteProperty() {
3513
+ return false;
3514
+ },
3515
+ get(target, p, receiver) {
3516
+ const subscriptionMethod = Reflect.get(target, p, receiver);
3517
+ if (typeof subscriptionMethod !== "function") {
3518
+ return subscriptionMethod;
3519
+ }
3520
+ return function(...rawParams) {
3521
+ const deduplicationKey = getDeduplicationKey(p, rawParams);
3522
+ if (deduplicationKey === void 0) {
3523
+ return subscriptionMethod(...rawParams);
3524
+ }
3525
+ if (cache.has(deduplicationKey)) {
3526
+ return cache.get(deduplicationKey);
3527
+ }
3528
+ const iterableFactory = getCachedAbortableIterableFactory({
3529
+ getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,
3530
+ getCacheEntryMissingError(deduplicationKey2) {
3531
+ return new Error(
3532
+ `Found no cache entry for subscription with deduplication key \`${deduplicationKey2?.toString()}\``
3533
+ );
3534
+ },
3535
+ getCacheKeyFromInputArgs: () => deduplicationKey,
3536
+ async onCacheHit(_iterable, _config) {
3537
+ },
3538
+ async onCreateIterable(abortSignal, config) {
3539
+ const pendingSubscription2 = subscriptionMethod(
3540
+ ...rawParams
3541
+ );
3542
+ const iterable = await pendingSubscription2.subscribe({
3543
+ ...config,
3544
+ abortSignal
3545
+ });
3546
+ registerIterableCleanup3(iterable, () => {
3547
+ cache.delete(deduplicationKey);
3548
+ });
3549
+ return iterable;
3550
+ }
3551
+ });
3552
+ const pendingSubscription = {
3553
+ async subscribe(...args) {
3554
+ const iterable = await iterableFactory(...args);
3555
+ const { abortSignal } = args[0];
3556
+ let abortPromise;
3557
+ return {
3558
+ ...iterable,
3559
+ async *[Symbol.asyncIterator]() {
3560
+ abortPromise || (abortPromise = abortSignal.aborted ? Promise.reject(EXPLICIT_ABORT_TOKEN2) : new Promise((_, reject) => {
3561
+ abortSignal.addEventListener("abort", () => {
3562
+ reject(EXPLICIT_ABORT_TOKEN2);
3563
+ });
3564
+ }));
3565
+ try {
3566
+ const iterator = iterable[Symbol.asyncIterator]();
3567
+ while (true) {
3568
+ const iteratorResult = await Promise.race([iterator.next(), abortPromise]);
3569
+ if (iteratorResult.done) {
3570
+ return;
3571
+ } else {
3572
+ yield iteratorResult.value;
3573
+ }
3574
+ }
3575
+ } catch (e3) {
3576
+ if (e3 === EXPLICIT_ABORT_TOKEN2) {
3577
+ return;
3578
+ }
3579
+ cache.delete(deduplicationKey);
3580
+ throw e3;
3581
+ }
3582
+ }
3583
+ };
3584
+ }
3585
+ };
3586
+ cache.set(deduplicationKey, pendingSubscription);
3587
+ return pendingSubscription;
3588
+ };
3589
+ }
3590
+ });
3591
+ }
3592
+
2545
3593
  // src/rpc.ts
2546
3594
  function createSolanaRpc(config) {
2547
3595
  return createJsonRpc({
@@ -2550,9 +3598,21 @@ this.globalThis.solanaWeb3 = (function (exports) {
2550
3598
  });
2551
3599
  }
2552
3600
  function createSolanaRpcSubscriptions(config) {
3601
+ return pipe(
3602
+ createJsonSubscriptionRpc({
3603
+ ...config,
3604
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
3605
+ }),
3606
+ (rpcSubscriptions) => getRpcSubscriptionsWithSubscriptionCoalescing({
3607
+ getDeduplicationKey: (...args) => (0, import_fast_stable_stringify.default)(args),
3608
+ rpcSubscriptions
3609
+ })
3610
+ );
3611
+ }
3612
+ function createSolanaRpcSubscriptions_UNSTABLE(config) {
2553
3613
  return createJsonSubscriptionRpc({
2554
3614
  ...config,
2555
- api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
3615
+ api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG)
2556
3616
  });
2557
3617
  }
2558
3618
 
@@ -2614,14 +3674,15 @@ this.globalThis.solanaWeb3 = (function (exports) {
2614
3674
 
2615
3675
  // src/rpc-request-deduplication.ts
2616
3676
  init_env_shim();
2617
- var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
2618
- function getSolanaRpcPayloadDeduplicationKey(payload) {
3677
+ var import_fast_stable_stringify2 = __toESM(require_fast_stable_stringify(), 1);
3678
+ function isJsonRpcPayload(payload) {
2619
3679
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
2620
- return;
2621
- }
2622
- if ("jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && "params" in payload) {
2623
- return (0, import_fast_stable_stringify.default)([payload.method, payload.params]);
3680
+ return false;
2624
3681
  }
3682
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
3683
+ }
3684
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
3685
+ return isJsonRpcPayload(payload) ? (0, import_fast_stable_stringify2.default)([payload.method, payload.params]) : void 0;
2625
3686
  }
2626
3687
 
2627
3688
  // src/rpc-transport.ts
@@ -2633,7 +3694,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2633
3694
  return out;
2634
3695
  }
2635
3696
  function createDefaultRpcTransport(config) {
2636
- return getRpcTransportWithRequestCoalescing(
3697
+ return pipe(
2637
3698
  createHttpTransport({
2638
3699
  ...config,
2639
3700
  headers: {
@@ -2644,7 +3705,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
2644
3705
  }
2645
3706
  }
2646
3707
  }),
2647
- getSolanaRpcPayloadDeduplicationKey
3708
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
2648
3709
  );
2649
3710
  }
2650
3711
 
@@ -2715,50 +3776,395 @@ this.globalThis.solanaWeb3 = (function (exports) {
2715
3776
  };
2716
3777
  }
2717
3778
 
3779
+ // src/rpc-websocket-connection-sharding.ts
3780
+ init_env_shim();
3781
+ var NULL_SHARD_CACHE_KEY = Symbol(
3782
+ "Cache key to use when there is no connection sharding strategy"
3783
+ );
3784
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
3785
+ return getCachedAbortableIterableFactory({
3786
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
3787
+ getCacheEntryMissingError(shardKey) {
3788
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey?.toString()}\``);
3789
+ },
3790
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
3791
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
3792
+ onCreateIterable: (abortSignal, config) => transport({
3793
+ ...config,
3794
+ signal: abortSignal
3795
+ })
3796
+ });
3797
+ }
3798
+
2718
3799
  // src/rpc-websocket-transport.ts
2719
3800
  function createDefaultRpcSubscriptionsTransport(config) {
2720
- const { intervalMs, ...rest } = config;
2721
- return getWebSocketTransportWithAutoping({
2722
- intervalMs: intervalMs ?? 5e3,
2723
- transport: createWebSocketTransport({
3801
+ const { getShard, intervalMs, ...rest } = config;
3802
+ return pipe(
3803
+ createWebSocketTransport({
2724
3804
  ...rest,
2725
3805
  sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
2726
3806
  131072
3807
+ }),
3808
+ (transport) => getWebSocketTransportWithAutoping({
3809
+ intervalMs: intervalMs ?? 5e3,
3810
+ transport
3811
+ }),
3812
+ (transport) => getWebSocketTransportWithConnectionSharding({
3813
+ getShard,
3814
+ transport
2727
3815
  })
3816
+ );
3817
+ }
3818
+
3819
+ // src/send-transaction.ts
3820
+ init_env_shim();
3821
+
3822
+ // src/transaction-confirmation.ts
3823
+ init_env_shim();
3824
+
3825
+ // src/transaction-confirmation-strategy-blockheight.ts
3826
+ init_env_shim();
3827
+ function createBlockHeightExceedencePromiseFactory(rpcSubscriptions) {
3828
+ return async function getBlockHeightExceedencePromise({ abortSignal: callerAbortSignal, lastValidBlockHeight }) {
3829
+ const abortController = new AbortController();
3830
+ function handleAbort() {
3831
+ abortController.abort();
3832
+ }
3833
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3834
+ const slotNotifications = await rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal });
3835
+ try {
3836
+ for await (const slotNotification of slotNotifications) {
3837
+ if (slotNotification.slot > lastValidBlockHeight) {
3838
+ throw new Error(
3839
+ "The network has progressed past the last block for which this transaction could have committed."
3840
+ );
3841
+ }
3842
+ }
3843
+ } finally {
3844
+ abortController.abort();
3845
+ }
3846
+ };
3847
+ }
3848
+
3849
+ // src/transaction-confirmation-strategy-nonce.ts
3850
+ init_env_shim();
3851
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
3852
+ 4 + // state(u32)
3853
+ 32;
3854
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
3855
+ return async function getNonceInvalidationPromise({
3856
+ abortSignal: callerAbortSignal,
3857
+ commitment,
3858
+ currentNonceValue,
3859
+ nonceAccountAddress
3860
+ }) {
3861
+ const abortController = new AbortController();
3862
+ function handleAbort() {
3863
+ abortController.abort();
3864
+ }
3865
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3866
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
3867
+ const base58Decoder2 = getBase58Decoder();
3868
+ const base64Encoder = getBase64Encoder();
3869
+ function getNonceFromAccountData([base64EncodedBytes]) {
3870
+ const data = base64Encoder.encode(base64EncodedBytes);
3871
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
3872
+ return base58Decoder2.decode(nonceValueBytes)[0];
3873
+ }
3874
+ const nonceAccountDidAdvancePromise = (async () => {
3875
+ for await (const accountNotification of accountNotifications) {
3876
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
3877
+ if (nonceValue !== currentNonceValue) {
3878
+ throw new Error(
3879
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
3880
+ );
3881
+ }
3882
+ }
3883
+ })();
3884
+ const nonceIsAlreadyInvalidPromise = (async () => {
3885
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
3886
+ commitment,
3887
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
3888
+ encoding: "base58"
3889
+ }).send({ abortSignal: abortController.signal });
3890
+ if (!nonceAccount) {
3891
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
3892
+ }
3893
+ const nonceValue = (
3894
+ // This works because we asked for the exact slice of data representing the nonce
3895
+ // value, and furthermore asked for it in `base58` encoding.
3896
+ nonceAccount.data[0]
3897
+ );
3898
+ if (nonceValue !== currentNonceValue) {
3899
+ throw new Error(
3900
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
3901
+ );
3902
+ } else {
3903
+ await new Promise(() => {
3904
+ });
3905
+ }
3906
+ })();
3907
+ try {
3908
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
3909
+ } finally {
3910
+ abortController.abort();
3911
+ }
3912
+ };
3913
+ }
3914
+
3915
+ // src/transaction-confirmation.ts
3916
+ function createDefaultDurableNonceTransactionConfirmer({
3917
+ rpc,
3918
+ rpcSubscriptions
3919
+ }) {
3920
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
3921
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
3922
+ rpc,
3923
+ rpcSubscriptions
3924
+ );
3925
+ return async function confirmDurableNonceTransaction(config) {
3926
+ await waitForDurableNonceTransactionConfirmation({
3927
+ ...config,
3928
+ getNonceInvalidationPromise,
3929
+ getRecentSignatureConfirmationPromise
3930
+ });
3931
+ };
3932
+ }
3933
+ function createDefaultRecentTransactionConfirmer({
3934
+ rpc,
3935
+ rpcSubscriptions
3936
+ }) {
3937
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory(rpcSubscriptions);
3938
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
3939
+ rpc,
3940
+ rpcSubscriptions
3941
+ );
3942
+ return async function confirmRecentTransaction(config) {
3943
+ await waitForRecentTransactionConfirmation({
3944
+ ...config,
3945
+ getBlockHeightExceedencePromise,
3946
+ getRecentSignatureConfirmationPromise
3947
+ });
3948
+ };
3949
+ }
3950
+ async function waitForDurableNonceTransactionConfirmation(config) {
3951
+ await raceStrategies(
3952
+ getSignatureFromTransaction(config.transaction),
3953
+ config,
3954
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
3955
+ return [
3956
+ getNonceInvalidationPromise({
3957
+ abortSignal,
3958
+ commitment,
3959
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
3960
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
3961
+ })
3962
+ ];
3963
+ }
3964
+ );
3965
+ }
3966
+ async function waitForRecentTransactionConfirmation(config) {
3967
+ await raceStrategies(
3968
+ getSignatureFromTransaction(config.transaction),
3969
+ config,
3970
+ function getSpecificStrategiesForRace({ abortSignal, getBlockHeightExceedencePromise, transaction }) {
3971
+ return [
3972
+ getBlockHeightExceedencePromise({
3973
+ abortSignal,
3974
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
3975
+ })
3976
+ ];
3977
+ }
3978
+ );
3979
+ }
3980
+
3981
+ // src/send-transaction.ts
3982
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
3983
+ if (
3984
+ // The developer has supplied no value for `preflightCommitment`.
3985
+ !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
3986
+ commitmentComparator(
3987
+ commitment,
3988
+ "finalized"
3989
+ /* default value of `preflightCommitment` */
3990
+ ) < 0
3991
+ ) {
3992
+ return {
3993
+ ...config,
3994
+ // In the common case, it is unlikely that you want to simulate a transaction at
3995
+ // `finalized` commitment when your standard of commitment for confirming the
3996
+ // transaction is lower. Cap the simulation commitment level to the level of the
3997
+ // confirmation commitment.
3998
+ preflightCommitment: commitment
3999
+ };
4000
+ }
4001
+ return config;
4002
+ }
4003
+ async function sendTransaction_INTERNAL({
4004
+ abortSignal,
4005
+ commitment,
4006
+ rpc,
4007
+ transaction,
4008
+ ...sendTransactionConfig
4009
+ }) {
4010
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
4011
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
4012
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
4013
+ encoding: "base64"
4014
+ }).send({ abortSignal });
4015
+ }
4016
+ function createDefaultDurableNonceTransactionSender({
4017
+ rpc,
4018
+ rpcSubscriptions
4019
+ }) {
4020
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
4021
+ rpc,
4022
+ rpcSubscriptions
4023
+ });
4024
+ return async function sendDurableNonceTransaction(transaction, config) {
4025
+ await sendAndConfirmDurableNonceTransaction({
4026
+ ...config,
4027
+ confirmDurableNonceTransaction,
4028
+ rpc,
4029
+ transaction
4030
+ });
4031
+ };
4032
+ }
4033
+ function createDefaultTransactionSender({
4034
+ rpc,
4035
+ rpcSubscriptions
4036
+ }) {
4037
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
4038
+ rpc,
4039
+ rpcSubscriptions
4040
+ });
4041
+ return async function sendTransaction(transaction, config) {
4042
+ await sendAndConfirmTransaction({
4043
+ ...config,
4044
+ confirmRecentTransaction,
4045
+ rpc,
4046
+ transaction
4047
+ });
4048
+ };
4049
+ }
4050
+ async function sendAndConfirmDurableNonceTransaction({
4051
+ abortSignal,
4052
+ commitment,
4053
+ confirmDurableNonceTransaction,
4054
+ rpc,
4055
+ transaction,
4056
+ ...sendTransactionConfig
4057
+ }) {
4058
+ const transactionSignature2 = await sendTransaction_INTERNAL({
4059
+ ...sendTransactionConfig,
4060
+ abortSignal,
4061
+ commitment,
4062
+ rpc,
4063
+ transaction
4064
+ });
4065
+ await confirmDurableNonceTransaction({
4066
+ abortSignal,
4067
+ commitment,
4068
+ transaction
4069
+ });
4070
+ return transactionSignature2;
4071
+ }
4072
+ async function sendAndConfirmTransaction({
4073
+ abortSignal,
4074
+ commitment,
4075
+ confirmRecentTransaction,
4076
+ rpc,
4077
+ transaction,
4078
+ ...sendTransactionConfig
4079
+ }) {
4080
+ const transactionSignature2 = await sendTransaction_INTERNAL({
4081
+ ...sendTransactionConfig,
4082
+ abortSignal,
4083
+ commitment,
4084
+ rpc,
4085
+ transaction
4086
+ });
4087
+ await confirmRecentTransaction({
4088
+ abortSignal,
4089
+ commitment,
4090
+ transaction
2728
4091
  });
4092
+ return transactionSignature2;
2729
4093
  }
2730
4094
 
2731
4095
  exports.AccountRole = AccountRole;
4096
+ exports.address = address;
2732
4097
  exports.appendTransactionInstruction = appendTransactionInstruction;
2733
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
4098
+ exports.assertIsAddress = assertIsAddress;
2734
4099
  exports.assertIsBlockhash = assertIsBlockhash;
2735
4100
  exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
4101
+ exports.assertIsLamports = assertIsLamports;
4102
+ exports.assertIsProgramDerivedAddress = assertIsProgramDerivedAddress;
4103
+ exports.assertIsStringifiedBigInt = assertIsStringifiedBigInt;
4104
+ exports.assertIsStringifiedNumber = assertIsStringifiedNumber;
4105
+ exports.assertIsTransactionSignature = assertIsTransactionSignature;
4106
+ exports.assertIsUnixTimestamp = assertIsUnixTimestamp;
4107
+ exports.assertTransactionIsFullySigned = assertTransactionIsFullySigned;
4108
+ exports.commitmentComparator = commitmentComparator;
2736
4109
  exports.createAddressWithSeed = createAddressWithSeed;
4110
+ exports.createBlockHeightExceedencePromiseFactory = createBlockHeightExceedencePromiseFactory;
4111
+ exports.createDefaultAirdropRequester = createDefaultAirdropRequester;
4112
+ exports.createDefaultDurableNonceTransactionConfirmer = createDefaultDurableNonceTransactionConfirmer;
4113
+ exports.createDefaultDurableNonceTransactionSender = createDefaultDurableNonceTransactionSender;
4114
+ exports.createDefaultRecentTransactionConfirmer = createDefaultRecentTransactionConfirmer;
2737
4115
  exports.createDefaultRpcSubscriptionsTransport = createDefaultRpcSubscriptionsTransport;
2738
4116
  exports.createDefaultRpcTransport = createDefaultRpcTransport;
4117
+ exports.createDefaultTransactionSender = createDefaultTransactionSender;
4118
+ exports.createNonceInvalidationPromiseFactory = createNonceInvalidationPromiseFactory;
4119
+ exports.createRecentSignatureConfirmationPromiseFactory = createRecentSignatureConfirmationPromiseFactory;
2739
4120
  exports.createSolanaRpc = createSolanaRpc;
2740
4121
  exports.createSolanaRpcSubscriptions = createSolanaRpcSubscriptions;
4122
+ exports.createSolanaRpcSubscriptions_UNSTABLE = createSolanaRpcSubscriptions_UNSTABLE;
2741
4123
  exports.createTransaction = createTransaction;
2742
4124
  exports.downgradeRoleToNonSigner = downgradeRoleToNonSigner;
2743
4125
  exports.downgradeRoleToReadonly = downgradeRoleToReadonly;
2744
4126
  exports.generateKeyPair = generateKeyPair;
4127
+ exports.getAddressCodec = getAddressCodec;
4128
+ exports.getAddressComparator = getAddressComparator;
4129
+ exports.getAddressDecoder = getAddressDecoder;
4130
+ exports.getAddressEncoder = getAddressEncoder;
2745
4131
  exports.getAddressFromPublicKey = getAddressFromPublicKey;
2746
- exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
2747
- exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
2748
4132
  exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
2749
4133
  exports.getProgramDerivedAddress = getProgramDerivedAddress;
4134
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
4135
+ exports.getTransactionCodec = getTransactionCodec;
4136
+ exports.getTransactionDecoder = getTransactionDecoder;
4137
+ exports.getTransactionEncoder = getTransactionEncoder;
4138
+ exports.isAddress = isAddress;
4139
+ exports.isAdvanceNonceAccountInstruction = isAdvanceNonceAccountInstruction;
4140
+ exports.isLamports = isLamports;
4141
+ exports.isProgramDerivedAddress = isProgramDerivedAddress;
2750
4142
  exports.isSignerRole = isSignerRole;
4143
+ exports.isStringifiedBigInt = isStringifiedBigInt;
4144
+ exports.isStringifiedNumber = isStringifiedNumber;
4145
+ exports.isTransactionSignature = isTransactionSignature;
4146
+ exports.isUnixTimestamp = isUnixTimestamp;
2751
4147
  exports.isWritableRole = isWritableRole;
4148
+ exports.lamports = lamports;
2752
4149
  exports.mergeRoles = mergeRoles;
2753
4150
  exports.prependTransactionInstruction = prependTransactionInstruction;
4151
+ exports.requestAndConfirmAirdrop = requestAndConfirmAirdrop;
4152
+ exports.sendAndConfirmDurableNonceTransaction = sendAndConfirmDurableNonceTransaction;
4153
+ exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
2754
4154
  exports.setTransactionFeePayer = setTransactionFeePayer;
2755
4155
  exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
2756
4156
  exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
2757
4157
  exports.signBytes = signBytes;
2758
4158
  exports.signTransaction = signTransaction;
4159
+ exports.stringifiedBigInt = stringifiedBigInt;
4160
+ exports.stringifiedNumber = stringifiedNumber;
4161
+ exports.transactionSignature = transactionSignature;
4162
+ exports.unixTimestamp = unixTimestamp;
2759
4163
  exports.upgradeRoleToSigner = upgradeRoleToSigner;
2760
4164
  exports.upgradeRoleToWritable = upgradeRoleToWritable;
2761
4165
  exports.verifySignature = verifySignature;
4166
+ exports.waitForDurableNonceTransactionConfirmation = waitForDurableNonceTransactionConfirmation;
4167
+ exports.waitForRecentTransactionConfirmation = waitForRecentTransactionConfirmation;
2762
4168
 
2763
4169
  return exports;
2764
4170