@solana/web3.js 2.0.0-experimental.a8f1f88 → 2.0.0-experimental.aa4a701

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