@solana/web3.js 2.0.0-experimental.24998c4 → 2.0.0-experimental.24d71d6

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 (56) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1151 -43
  3. package/dist/index.browser.cjs +844 -22
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +808 -23
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +3794 -513
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +797 -23
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +833 -22
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +797 -23
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +83 -19
  16. package/dist/types/airdrop-confirmer.d.ts +19 -0
  17. package/dist/types/airdrop-confirmer.d.ts.map +1 -0
  18. package/dist/types/airdrop.d.ts +21 -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 +13 -2
  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 +3 -2
  26. package/dist/types/rpc-integer-overflow-error.d.ts.map +1 -0
  27. package/dist/types/rpc-request-coalescer.d.ts +1 -1
  28. package/dist/types/rpc-request-coalescer.d.ts.map +1 -0
  29. package/dist/types/rpc-request-deduplication.d.ts.map +1 -0
  30. package/dist/types/rpc-subscription-coalescer.d.ts +10 -0
  31. package/dist/types/rpc-subscription-coalescer.d.ts.map +1 -0
  32. package/dist/types/rpc-transport.d.ts +1 -2
  33. package/dist/types/rpc-transport.d.ts.map +1 -0
  34. package/dist/types/rpc-websocket-autopinger.d.ts +8 -0
  35. package/dist/types/rpc-websocket-autopinger.d.ts.map +1 -0
  36. package/dist/types/rpc-websocket-connection-sharding.d.ts +13 -0
  37. package/dist/types/rpc-websocket-connection-sharding.d.ts.map +1 -0
  38. package/dist/types/rpc-websocket-transport.d.ts +12 -0
  39. package/dist/types/rpc-websocket-transport.d.ts.map +1 -0
  40. package/dist/types/rpc.d.ts +4 -3
  41. package/dist/types/rpc.d.ts.map +1 -0
  42. package/dist/types/send-transaction.d.ts +38 -0
  43. package/dist/types/send-transaction.d.ts.map +1 -0
  44. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts +14 -0
  45. package/dist/types/transaction-confirmation-strategy-blockheight.d.ts.map +1 -0
  46. package/dist/types/transaction-confirmation-strategy-nonce.d.ts +14 -0
  47. package/dist/types/transaction-confirmation-strategy-nonce.d.ts.map +1 -0
  48. package/dist/types/transaction-confirmation-strategy-racer.d.ts +14 -0
  49. package/dist/types/transaction-confirmation-strategy-racer.d.ts.map +1 -0
  50. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts +12 -0
  51. package/dist/types/transaction-confirmation-strategy-recent-signature.d.ts.map +1 -0
  52. package/dist/types/transaction-confirmation-strategy-timeout.d.ts +8 -0
  53. package/dist/types/transaction-confirmation-strategy-timeout.d.ts.map +1 -0
  54. package/dist/types/transaction-confirmation.d.ts +32 -0
  55. package/dist/types/transaction-confirmation.d.ts.map +1 -0
  56. package/package.json +25 -23
@@ -12,8 +12,8 @@ this.globalThis.solanaWeb3 = (function (exports) {
12
12
  var __esm = (fn, res) => function __init() {
13
13
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
14
  };
15
- var __commonJS = (cb, mod) => function __require() {
16
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ var __commonJS = (cb, mod2) => function __require() {
16
+ return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
17
17
  };
18
18
  var __copyProps = (to, from, except, desc) => {
19
19
  if (from && typeof from === "object" || typeof from === "function") {
@@ -23,13 +23,13 @@ this.globalThis.solanaWeb3 = (function (exports) {
23
23
  }
24
24
  return to;
25
25
  };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
27
27
  // If the importer is in node compatibility mode or this is not an ESM
28
28
  // file that has been converted to a CommonJS file using a Babel-
29
29
  // compatible transform (i.e. "__esModule" has not been set), then set
30
30
  // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
31
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
32
+ mod2
33
33
  ));
34
34
  var __publicField = (obj, key, value) => {
35
35
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
@@ -122,64 +122,22 @@ this.globalThis.solanaWeb3 = (function (exports) {
122
122
  // src/index.ts
123
123
  init_env_shim();
124
124
 
125
- // ../instructions/dist/index.browser.js
126
- init_env_shim();
127
- var AccountRole = /* @__PURE__ */ ((AccountRole2) => {
128
- AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */
129
- 3] = "WRITABLE_SIGNER";
130
- AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */
131
- 2] = "READONLY_SIGNER";
132
- AccountRole2[AccountRole2["WRITABLE"] = /* 1 */
133
- 1] = "WRITABLE";
134
- AccountRole2[AccountRole2["READONLY"] = /* 0 */
135
- 0] = "READONLY";
136
- return AccountRole2;
137
- })(AccountRole || {});
138
- var IS_SIGNER_BITMASK = 2;
139
- var IS_WRITABLE_BITMASK = 1;
140
- function downgradeRoleToNonSigner(role) {
141
- return role & ~IS_SIGNER_BITMASK;
142
- }
143
- function downgradeRoleToReadonly(role) {
144
- return role & ~IS_WRITABLE_BITMASK;
145
- }
146
- function isSignerRole(role) {
147
- return role >= 2;
148
- }
149
- function isWritableRole(role) {
150
- return (role & IS_WRITABLE_BITMASK) !== 0;
151
- }
152
- function mergeRoles(roleA, roleB) {
153
- return roleA | roleB;
154
- }
155
- function upgradeRoleToSigner(role) {
156
- return role | IS_SIGNER_BITMASK;
157
- }
158
- function upgradeRoleToWritable(role) {
159
- return role | IS_WRITABLE_BITMASK;
160
- }
161
-
162
- // ../keys/dist/index.browser.js
125
+ // ../addresses/dist/index.browser.js
163
126
  init_env_shim();
164
127
 
165
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/index.mjs
128
+ // ../codecs-core/dist/index.browser.js
166
129
  init_env_shim();
167
-
168
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/index.mjs
169
- init_env_shim();
170
-
171
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/bytes.mjs
172
- init_env_shim();
173
- var mergeBytes = (bytesArr) => {
174
- const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);
175
- const result = new Uint8Array(totalLength);
176
- let offset = 0;
177
- bytesArr.forEach((arr) => {
178
- result.set(arr, offset);
179
- offset += arr.length;
180
- });
181
- return result;
182
- };
130
+ function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
131
+ if (bytes.length - offset <= 0) {
132
+ throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);
133
+ }
134
+ }
135
+ function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
136
+ const bytesLength = bytes.length - offset;
137
+ if (bytesLength < expected) {
138
+ throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
139
+ }
140
+ }
183
141
  var padBytes = (bytes, length) => {
184
142
  if (bytes.length >= length)
185
143
  return bytes;
@@ -187,302 +145,398 @@ this.globalThis.solanaWeb3 = (function (exports) {
187
145
  paddedBytes.set(bytes);
188
146
  return paddedBytes;
189
147
  };
190
- var fixBytes = (bytes, length) => padBytes(bytes.slice(0, length), length);
191
-
192
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/errors.mjs
193
- init_env_shim();
194
- var DeserializingEmptyBufferError = class extends Error {
195
- constructor(serializer) {
196
- super(`Serializer [${serializer}] cannot deserialize empty buffers.`);
197
- __publicField(this, "name", "DeserializingEmptyBufferError");
148
+ var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
149
+ function getEncodedSize(value, encoder) {
150
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
151
+ }
152
+ function createEncoder(encoder) {
153
+ return Object.freeze({
154
+ ...encoder,
155
+ encode: (value) => {
156
+ const bytes = new Uint8Array(getEncodedSize(value, encoder));
157
+ encoder.write(value, bytes, 0);
158
+ return bytes;
159
+ }
160
+ });
161
+ }
162
+ function createDecoder(decoder) {
163
+ return Object.freeze({
164
+ ...decoder,
165
+ decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
166
+ });
167
+ }
168
+ function isFixedSize(codec) {
169
+ return "fixedSize" in codec && typeof codec.fixedSize === "number";
170
+ }
171
+ function assertIsFixedSize(codec, message) {
172
+ if (!isFixedSize(codec)) {
173
+ throw new Error(message != null ? message : "Expected a fixed-size codec, got a variable-size one.");
198
174
  }
199
- };
200
- var NotEnoughBytesError = class extends Error {
201
- constructor(serializer, expected, actual) {
202
- super(`Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`);
203
- __publicField(this, "name", "NotEnoughBytesError");
175
+ }
176
+ function isVariableSize(codec) {
177
+ return !isFixedSize(codec);
178
+ }
179
+ function combineCodec(encoder, decoder) {
180
+ if (isFixedSize(encoder) !== isFixedSize(decoder)) {
181
+ throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);
182
+ }
183
+ if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {
184
+ throw new Error(
185
+ `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
186
+ );
187
+ }
188
+ if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {
189
+ throw new Error(
190
+ `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
191
+ );
204
192
  }
205
- };
206
-
207
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/fixSerializer.mjs
208
- init_env_shim();
209
- function fixSerializer(serializer, fixedBytes, description) {
210
193
  return {
211
- description: description ?? `fixed(${fixedBytes}, ${serializer.description})`,
194
+ ...decoder,
195
+ ...encoder,
196
+ decode: decoder.decode,
197
+ encode: encoder.encode,
198
+ read: decoder.read,
199
+ write: encoder.write
200
+ };
201
+ }
202
+ function fixEncoder(encoder, fixedBytes) {
203
+ return createEncoder({
204
+ fixedSize: fixedBytes,
205
+ write: (value, bytes, offset) => {
206
+ const variableByteArray = encoder.encode(value);
207
+ const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
208
+ bytes.set(fixedByteArray, offset);
209
+ return offset + fixedBytes;
210
+ }
211
+ });
212
+ }
213
+ function fixDecoder(decoder, fixedBytes) {
214
+ return createDecoder({
212
215
  fixedSize: fixedBytes,
213
- maxSize: fixedBytes,
214
- serialize: (value) => fixBytes(serializer.serialize(value), fixedBytes),
215
- deserialize: (buffer, offset = 0) => {
216
- buffer = buffer.slice(offset, offset + fixedBytes);
217
- if (buffer.length < fixedBytes) {
218
- throw new NotEnoughBytesError("fixSerializer", fixedBytes, buffer.length);
216
+ read: (bytes, offset) => {
217
+ assertByteArrayHasEnoughBytesForCodec("fixCodec", fixedBytes, bytes, offset);
218
+ if (offset > 0 || bytes.length > fixedBytes) {
219
+ bytes = bytes.slice(offset, offset + fixedBytes);
219
220
  }
220
- if (serializer.fixedSize !== null) {
221
- buffer = fixBytes(buffer, serializer.fixedSize);
221
+ if (isFixedSize(decoder)) {
222
+ bytes = fixBytes(bytes, decoder.fixedSize);
222
223
  }
223
- const [value] = serializer.deserialize(buffer, 0);
224
+ const [value] = decoder.read(bytes, 0);
224
225
  return [value, offset + fixedBytes];
225
226
  }
226
- };
227
+ });
228
+ }
229
+ function mapEncoder(encoder, unmap) {
230
+ return createEncoder({
231
+ ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,
232
+ write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)
233
+ });
234
+ }
235
+ function mapDecoder(decoder, map) {
236
+ return createDecoder({
237
+ ...decoder,
238
+ read: (bytes, offset) => {
239
+ const [value, newOffset] = decoder.read(bytes, offset);
240
+ return [map(value, bytes, offset), newOffset];
241
+ }
242
+ });
227
243
  }
228
244
 
229
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/index.mjs
230
- init_env_shim();
231
-
232
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
245
+ // ../codecs-strings/dist/index.browser.js
233
246
  init_env_shim();
234
247
 
235
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/errors.mjs
248
+ // ../codecs-numbers/dist/index.browser.js
236
249
  init_env_shim();
237
- var InvalidBaseStringError = class extends Error {
238
- constructor(value, base, cause) {
239
- const message = `Expected a string of base ${base}, got [${value}].`;
240
- super(message);
241
- __publicField(this, "name", "InvalidBaseStringError");
242
- this.cause = cause;
250
+ function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
251
+ if (value < min || value > max) {
252
+ throw new Error(
253
+ `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`
254
+ );
243
255
  }
244
- };
245
-
246
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
247
- var baseX = (alphabet) => {
248
- const base = alphabet.length;
249
- const baseBigInt = BigInt(base);
250
- return {
251
- description: `base${base}`,
252
- fixedSize: null,
253
- maxSize: null,
254
- serialize(value) {
255
- if (!value.match(new RegExp(`^[${alphabet}]*$`))) {
256
- throw new InvalidBaseStringError(value, base);
256
+ }
257
+ function isLittleEndian(config) {
258
+ return (config == null ? void 0 : config.endian) === 1 ? false : true;
259
+ }
260
+ function numberEncoderFactory(input) {
261
+ return createEncoder({
262
+ fixedSize: input.size,
263
+ write(value, bytes, offset) {
264
+ if (input.range) {
265
+ assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
266
+ }
267
+ const arrayBuffer = new ArrayBuffer(input.size);
268
+ input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));
269
+ bytes.set(new Uint8Array(arrayBuffer), offset);
270
+ return offset + input.size;
271
+ }
272
+ });
273
+ }
274
+ function numberDecoderFactory(input) {
275
+ return createDecoder({
276
+ fixedSize: input.size,
277
+ read(bytes, offset = 0) {
278
+ assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);
279
+ assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);
280
+ const view = new DataView(toArrayBuffer(bytes, offset, input.size));
281
+ return [input.get(view, isLittleEndian(input.config)), offset + input.size];
282
+ }
283
+ });
284
+ }
285
+ function toArrayBuffer(bytes, offset, length) {
286
+ const bytesOffset = bytes.byteOffset + (offset != null ? offset : 0);
287
+ const bytesLength = length != null ? length : bytes.byteLength;
288
+ return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
289
+ }
290
+ var getShortU16Encoder = () => createEncoder({
291
+ getSizeFromValue: (value) => {
292
+ if (value <= 127)
293
+ return 1;
294
+ if (value <= 16383)
295
+ return 2;
296
+ return 3;
297
+ },
298
+ maxSize: 3,
299
+ write: (value, bytes, offset) => {
300
+ assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
301
+ const shortU16Bytes = [0];
302
+ for (let ii = 0; ; ii += 1) {
303
+ const alignedValue = value >> ii * 7;
304
+ if (alignedValue === 0) {
305
+ break;
306
+ }
307
+ const nextSevenBits = 127 & alignedValue;
308
+ shortU16Bytes[ii] = nextSevenBits;
309
+ if (ii > 0) {
310
+ shortU16Bytes[ii - 1] |= 128;
311
+ }
312
+ }
313
+ bytes.set(shortU16Bytes, offset);
314
+ return offset + shortU16Bytes.length;
315
+ }
316
+ });
317
+ var getShortU16Decoder = () => createDecoder({
318
+ maxSize: 3,
319
+ read: (bytes, offset) => {
320
+ let value = 0;
321
+ let byteCount = 0;
322
+ while (++byteCount) {
323
+ const byteIndex = byteCount - 1;
324
+ const currentByte = bytes[offset + byteIndex];
325
+ const nextSevenBits = 127 & currentByte;
326
+ value |= nextSevenBits << byteIndex * 7;
327
+ if ((currentByte & 128) === 0) {
328
+ break;
257
329
  }
330
+ }
331
+ return [value, offset + byteCount];
332
+ }
333
+ });
334
+ var getU32Encoder = (config = {}) => numberEncoderFactory({
335
+ config,
336
+ name: "u32",
337
+ range: [0, Number("0xffffffff")],
338
+ set: (view, value, le) => view.setUint32(0, value, le),
339
+ size: 4
340
+ });
341
+ var getU32Decoder = (config = {}) => numberDecoderFactory({
342
+ config,
343
+ get: (view, le) => view.getUint32(0, le),
344
+ name: "u32",
345
+ size: 4
346
+ });
347
+ var getU8Encoder = () => numberEncoderFactory({
348
+ name: "u8",
349
+ range: [0, Number("0xff")],
350
+ set: (view, value) => view.setUint8(0, value),
351
+ size: 1
352
+ });
353
+ var getU8Decoder = () => numberDecoderFactory({
354
+ get: (view) => view.getUint8(0),
355
+ name: "u8",
356
+ size: 1
357
+ });
358
+
359
+ // ../codecs-strings/dist/index.browser.js
360
+ function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
361
+ if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
362
+ throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
363
+ }
364
+ }
365
+ var getBaseXEncoder = (alphabet4) => {
366
+ return createEncoder({
367
+ getSizeFromValue: (value) => {
368
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
369
+ if (tailChars === "")
370
+ return value.length;
371
+ const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
372
+ return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
373
+ },
374
+ write(value, bytes, offset) {
375
+ assertValidBaseString(alphabet4, value);
258
376
  if (value === "")
259
- return new Uint8Array();
260
- const chars = [...value];
261
- let trailIndex = chars.findIndex((c) => c !== alphabet[0]);
262
- trailIndex = trailIndex === -1 ? chars.length : trailIndex;
263
- const leadingZeroes = Array(trailIndex).fill(0);
264
- if (trailIndex === chars.length)
265
- return Uint8Array.from(leadingZeroes);
266
- const tailChars = chars.slice(trailIndex);
267
- let base10Number = 0n;
268
- let baseXPower = 1n;
269
- for (let i = tailChars.length - 1; i >= 0; i -= 1) {
270
- base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));
271
- baseXPower *= baseBigInt;
377
+ return offset;
378
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
379
+ if (tailChars === "") {
380
+ bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
381
+ return offset + leadingZeroes.length;
272
382
  }
383
+ let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
273
384
  const tailBytes = [];
274
385
  while (base10Number > 0n) {
275
386
  tailBytes.unshift(Number(base10Number % 256n));
276
387
  base10Number /= 256n;
277
388
  }
278
- return Uint8Array.from(leadingZeroes.concat(tailBytes));
279
- },
280
- deserialize(buffer, offset = 0) {
281
- if (buffer.length === 0)
389
+ const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
390
+ bytes.set(bytesToAdd, offset);
391
+ return offset + bytesToAdd.length;
392
+ }
393
+ });
394
+ };
395
+ var getBaseXDecoder = (alphabet4) => {
396
+ return createDecoder({
397
+ read(rawBytes, offset) {
398
+ const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
399
+ if (bytes.length === 0)
282
400
  return ["", 0];
283
- const bytes = buffer.slice(offset);
284
401
  let trailIndex = bytes.findIndex((n) => n !== 0);
285
402
  trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
286
- const leadingZeroes = alphabet[0].repeat(trailIndex);
403
+ const leadingZeroes = alphabet4[0].repeat(trailIndex);
287
404
  if (trailIndex === bytes.length)
288
- return [leadingZeroes, buffer.length];
289
- let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
290
- const tailChars = [];
291
- while (base10Number > 0n) {
292
- tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);
293
- base10Number /= baseBigInt;
294
- }
295
- return [leadingZeroes + tailChars.join(""), buffer.length];
405
+ return [leadingZeroes, rawBytes.length];
406
+ const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
407
+ const tailChars = getBaseXFromBigInt(base10Number, alphabet4);
408
+ return [leadingZeroes + tailChars, rawBytes.length];
296
409
  }
297
- };
410
+ });
411
+ };
412
+ function partitionLeadingZeroes(value, zeroCharacter) {
413
+ const leadingZeroIndex = [...value].findIndex((c) => c !== zeroCharacter);
414
+ return leadingZeroIndex === -1 ? [value, ""] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];
415
+ }
416
+ function getBigIntFromBaseX(value, alphabet4) {
417
+ const base = BigInt(alphabet4.length);
418
+ return [...value].reduce((sum, char) => sum * base + BigInt(alphabet4.indexOf(char)), 0n);
419
+ }
420
+ function getBaseXFromBigInt(value, alphabet4) {
421
+ const base = BigInt(alphabet4.length);
422
+ const tailChars = [];
423
+ while (value > 0n) {
424
+ tailChars.unshift(alphabet4[Number(value % base)]);
425
+ value /= base;
426
+ }
427
+ return tailChars.join("");
428
+ }
429
+ var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
430
+ var getBase58Encoder = () => getBaseXEncoder(alphabet2);
431
+ var getBase58Decoder = () => getBaseXDecoder(alphabet2);
432
+ var getBase64Encoder = () => {
433
+ {
434
+ return createEncoder({
435
+ getSizeFromValue: (value) => {
436
+ try {
437
+ return atob(value).length;
438
+ } catch (e23) {
439
+ throw new Error(`Expected a string of base 64, got [${value}].`);
440
+ }
441
+ },
442
+ write(value, bytes, offset) {
443
+ try {
444
+ const bytesToAdd = atob(value).split("").map((c) => c.charCodeAt(0));
445
+ bytes.set(bytesToAdd, offset);
446
+ return bytesToAdd.length + offset;
447
+ } catch (e23) {
448
+ throw new Error(`Expected a string of base 64, got [${value}].`);
449
+ }
450
+ }
451
+ });
452
+ }
453
+ };
454
+ var getBase64Decoder = () => {
455
+ {
456
+ return createDecoder({
457
+ read(bytes, offset = 0) {
458
+ const slice = bytes.slice(offset);
459
+ const value = btoa(String.fromCharCode(...slice));
460
+ return [value, bytes.length];
461
+ }
462
+ });
463
+ }
298
464
  };
299
-
300
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base58.mjs
301
- init_env_shim();
302
- var base58 = baseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
303
-
304
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/nullCharacters.mjs
305
- init_env_shim();
306
465
  var removeNullCharacters = (value) => (
307
466
  // eslint-disable-next-line no-control-regex
308
467
  value.replace(/\u0000/g, "")
309
468
  );
310
-
311
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/utf8.mjs
312
- init_env_shim();
313
- var utf8 = {
314
- description: "utf8",
315
- fixedSize: null,
316
- maxSize: null,
317
- serialize(value) {
318
- return new TextEncoder().encode(value);
319
- },
320
- deserialize(buffer, offset = 0) {
321
- const value = new TextDecoder().decode(buffer.slice(offset));
322
- return [removeNullCharacters(value), buffer.length];
323
- }
324
- };
325
-
326
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/index.mjs
327
- init_env_shim();
328
-
329
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs
330
- init_env_shim();
331
- var Endian;
332
- (function(Endian2) {
333
- Endian2["Little"] = "le";
334
- Endian2["Big"] = "be";
335
- })(Endian || (Endian = {}));
336
-
337
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs
338
- init_env_shim();
339
- var NumberOutOfRangeError = class extends RangeError {
340
- constructor(serializer, min, max, actual) {
341
- super(`Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`);
342
- __publicField(this, "name", "NumberOutOfRangeError");
343
- }
469
+ var e = globalThis.TextDecoder;
470
+ var o = globalThis.TextEncoder;
471
+ var getUtf8Encoder = () => {
472
+ let textEncoder;
473
+ return createEncoder({
474
+ getSizeFromValue: (value) => (textEncoder || (textEncoder = new o())).encode(value).length,
475
+ write: (value, bytes, offset) => {
476
+ const bytesToAdd = (textEncoder || (textEncoder = new o())).encode(value);
477
+ bytes.set(bytesToAdd, offset);
478
+ return offset + bytesToAdd.length;
479
+ }
480
+ });
344
481
  };
345
-
346
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/utils.mjs
347
- init_env_shim();
348
- function numberFactory(input) {
349
- let littleEndian;
350
- let defaultDescription = input.name;
351
- if (input.size > 1) {
352
- littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little;
353
- defaultDescription += littleEndian ? "(le)" : "(be)";
354
- }
355
- return {
356
- description: input.options.description ?? defaultDescription,
357
- fixedSize: input.size,
358
- maxSize: input.size,
359
- serialize(value) {
360
- if (input.range) {
361
- assertRange(input.name, input.range[0], input.range[1], value);
362
- }
363
- const buffer = new ArrayBuffer(input.size);
364
- input.set(new DataView(buffer), value, littleEndian);
365
- return new Uint8Array(buffer);
366
- },
367
- deserialize(bytes, offset = 0) {
368
- const slice = bytes.slice(offset, offset + input.size);
369
- assertEnoughBytes("i8", slice, input.size);
370
- const view = toDataView(slice);
371
- return [input.get(view, littleEndian), offset + input.size];
482
+ var getUtf8Decoder = () => {
483
+ let textDecoder;
484
+ return createDecoder({
485
+ read(bytes, offset) {
486
+ const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));
487
+ return [removeNullCharacters(value), bytes.length];
372
488
  }
373
- };
374
- }
375
- var toArrayBuffer = (array) => array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
376
- var toDataView = (array) => new DataView(toArrayBuffer(array));
377
- var assertRange = (serializer, min, max, value) => {
378
- if (value < min || value > max) {
379
- throw new NumberOutOfRangeError(serializer, min, max, value);
380
- }
489
+ });
381
490
  };
382
- var assertEnoughBytes = (serializer, bytes, expected) => {
383
- if (bytes.length === 0) {
384
- throw new DeserializingEmptyBufferError(serializer);
491
+ function getStringEncoder(config = {}) {
492
+ var _a, _b;
493
+ const size = (_a = config.size) != null ? _a : getU32Encoder();
494
+ const encoding = (_b = config.encoding) != null ? _b : getUtf8Encoder();
495
+ if (size === "variable") {
496
+ return encoding;
385
497
  }
386
- if (bytes.length < expected) {
387
- throw new NotEnoughBytesError(serializer, expected, bytes.length);
498
+ if (typeof size === "number") {
499
+ return fixEncoder(encoding, size);
388
500
  }
389
- };
390
-
391
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u32.mjs
392
- init_env_shim();
393
- var u32 = (options = {}) => numberFactory({
394
- name: "u32",
395
- size: 4,
396
- range: [0, Number("0xffffffff")],
397
- set: (view, value, le) => view.setUint32(0, Number(value), le),
398
- get: (view, le) => view.getUint32(0, le),
399
- options
400
- });
401
-
402
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
403
- init_env_shim();
404
- function getSizeDescription(size) {
405
- return typeof size === "object" ? size.description : `${size}`;
501
+ return createEncoder({
502
+ getSizeFromValue: (value) => {
503
+ const contentSize = getEncodedSize(value, encoding);
504
+ return getEncodedSize(contentSize, size) + contentSize;
505
+ },
506
+ write: (value, bytes, offset) => {
507
+ const contentSize = getEncodedSize(value, encoding);
508
+ offset = size.write(contentSize, bytes, offset);
509
+ return encoding.write(value, bytes, offset);
510
+ }
511
+ });
406
512
  }
407
-
408
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs
409
- init_env_shim();
410
- function string(options = {}) {
411
- const size = options.size ?? u32();
412
- const encoding = options.encoding ?? utf8;
413
- const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
513
+ function getStringDecoder(config = {}) {
514
+ var _a, _b;
515
+ const size = (_a = config.size) != null ? _a : getU32Decoder();
516
+ const encoding = (_b = config.encoding) != null ? _b : getUtf8Decoder();
414
517
  if (size === "variable") {
415
- return {
416
- ...encoding,
417
- description
418
- };
518
+ return encoding;
419
519
  }
420
520
  if (typeof size === "number") {
421
- return fixSerializer(encoding, size, description);
521
+ return fixDecoder(encoding, size);
422
522
  }
423
- return {
424
- description,
425
- fixedSize: null,
426
- maxSize: null,
427
- serialize: (value) => {
428
- const contentBytes = encoding.serialize(value);
429
- const lengthBytes = size.serialize(contentBytes.length);
430
- return mergeBytes([lengthBytes, contentBytes]);
431
- },
432
- deserialize: (buffer, offset = 0) => {
433
- if (buffer.slice(offset).length === 0) {
434
- throw new DeserializingEmptyBufferError("string");
435
- }
436
- const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
523
+ return createDecoder({
524
+ read: (bytes, offset = 0) => {
525
+ assertByteArrayIsNotEmptyForCodec("string", bytes, offset);
526
+ const [lengthBigInt, lengthOffset] = size.read(bytes, offset);
437
527
  const length = Number(lengthBigInt);
438
528
  offset = lengthOffset;
439
- const contentBuffer = buffer.slice(offset, offset + length);
440
- if (contentBuffer.length < length) {
441
- throw new NotEnoughBytesError("string", length, contentBuffer.length);
442
- }
443
- const [value, contentOffset] = encoding.deserialize(contentBuffer);
529
+ const contentBytes = bytes.slice(offset, offset + length);
530
+ assertByteArrayHasEnoughBytesForCodec("string", length, contentBytes);
531
+ const [value, contentOffset] = encoding.read(contentBytes, 0);
444
532
  offset += contentOffset;
445
533
  return [value, offset];
446
534
  }
447
- };
448
- }
449
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
450
- try {
451
- if (
452
- // Lowest address (32 bytes of zeroes)
453
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
454
- putativeBase58EncodedAddress.length > 44
455
- ) {
456
- throw new Error("Expected input string to decode to a byte array of length 32.");
457
- }
458
- const bytes = base58.serialize(putativeBase58EncodedAddress);
459
- const numBytes = bytes.byteLength;
460
- if (numBytes !== 32) {
461
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
462
- }
463
- } catch (e2) {
464
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
465
- cause: e2
466
- });
467
- }
468
- }
469
- function getBase58EncodedAddressCodec(config) {
470
- return string({
471
- description: config?.description ?? ("A 32-byte account address" ),
472
- encoding: base58,
473
- size: 32
474
535
  });
475
536
  }
476
- function getBase58EncodedAddressComparator() {
477
- return new Intl.Collator("en", {
478
- caseFirst: "lower",
479
- ignorePunctuation: false,
480
- localeMatcher: "best fit",
481
- numeric: false,
482
- sensitivity: "variant",
483
- usage: "sort"
484
- }).compare;
485
- }
537
+
538
+ // ../assertions/dist/index.browser.js
539
+ init_env_shim();
486
540
  function assertIsSecureContext() {
487
541
  if (!globalThis.isSecureContext) {
488
542
  throw new Error(
@@ -512,9 +566,17 @@ this.globalThis.solanaWeb3 = (function (exports) {
512
566
  return await cachedEd25519Decision;
513
567
  }
514
568
  }
569
+ async function assertDigestCapabilityIsAvailable() {
570
+ var _a;
571
+ assertIsSecureContext();
572
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.digest) !== "function") {
573
+ throw new Error("No digest implementation could be found");
574
+ }
575
+ }
515
576
  async function assertKeyGenerationIsAvailable() {
577
+ var _a;
516
578
  assertIsSecureContext();
517
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
579
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.generateKey) !== "function") {
518
580
  throw new Error("No key generation implementation could be found");
519
581
  }
520
582
  if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
@@ -524,196 +586,1809 @@ this.globalThis.solanaWeb3 = (function (exports) {
524
586
  }
525
587
  }
526
588
  async function assertKeyExporterIsAvailable() {
589
+ var _a;
527
590
  assertIsSecureContext();
528
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
591
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.exportKey) !== "function") {
529
592
  throw new Error("No key export implementation could be found");
530
593
  }
531
594
  }
532
595
  async function assertSigningCapabilityIsAvailable() {
596
+ var _a;
533
597
  assertIsSecureContext();
534
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
598
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.sign) !== "function") {
535
599
  throw new Error("No signing implementation could be found");
536
600
  }
537
601
  }
538
602
  async function assertVerificationCapabilityIsAvailable() {
603
+ var _a;
539
604
  assertIsSecureContext();
540
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
605
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.verify) !== "function") {
541
606
  throw new Error("No signature verification implementation could be found");
542
607
  }
543
608
  }
544
- async function generateKeyPair() {
545
- await assertKeyGenerationIsAvailable();
546
- const keyPair = await crypto.subtle.generateKey(
547
- /* algorithm */
548
- "Ed25519",
549
- // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
550
- /* extractable */
551
- false,
552
- // Prevents the bytes of the private key from being visible to JS.
553
- /* allowed uses */
554
- ["sign", "verify"]
555
- );
556
- return keyPair;
557
- }
558
- async function getBase58EncodedAddressFromPublicKey(publicKey) {
559
- await assertKeyExporterIsAvailable();
560
- if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
561
- throw new Error("The `CryptoKey` must be an `Ed25519` public key");
562
- }
563
- const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
564
- const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
565
- return base58EncodedAddress;
609
+
610
+ // ../addresses/dist/index.browser.js
611
+ var memoizedBase58Encoder;
612
+ var memoizedBase58Decoder;
613
+ function getMemoizedBase58Encoder() {
614
+ if (!memoizedBase58Encoder)
615
+ memoizedBase58Encoder = getBase58Encoder();
616
+ return memoizedBase58Encoder;
566
617
  }
567
- async function signBytes(key, data) {
568
- await assertSigningCapabilityIsAvailable();
569
- const signedData = await crypto.subtle.sign("Ed25519", key, data);
570
- return new Uint8Array(signedData);
618
+ function getMemoizedBase58Decoder() {
619
+ if (!memoizedBase58Decoder)
620
+ memoizedBase58Decoder = getBase58Decoder();
621
+ return memoizedBase58Decoder;
571
622
  }
572
- async function verifySignature(key, signature, data) {
573
- await assertVerificationCapabilityIsAvailable();
574
- return await crypto.subtle.verify("Ed25519", key, signature, data);
623
+ function isAddress(putativeAddress) {
624
+ if (
625
+ // Lowest address (32 bytes of zeroes)
626
+ putativeAddress.length < 32 || // Highest address (32 bytes of 255)
627
+ putativeAddress.length > 44
628
+ ) {
629
+ return false;
630
+ }
631
+ const base58Encoder3 = getMemoizedBase58Encoder();
632
+ const bytes = base58Encoder3.encode(putativeAddress);
633
+ const numBytes = bytes.byteLength;
634
+ if (numBytes !== 32) {
635
+ return false;
636
+ }
637
+ return true;
575
638
  }
576
-
577
- // src/rpc.ts
578
- init_env_shim();
579
-
580
- // ../rpc-core/dist/index.browser.js
581
- init_env_shim();
582
- function visitNode(value, keyPath, onIntegerOverflow) {
583
- if (Array.isArray(value)) {
584
- return value.map(
585
- (element, ii) => visitNode(element, [...keyPath, ii], onIntegerOverflow)
639
+ function assertIsAddress(putativeAddress) {
640
+ try {
641
+ if (
642
+ // Lowest address (32 bytes of zeroes)
643
+ putativeAddress.length < 32 || // Highest address (32 bytes of 255)
644
+ putativeAddress.length > 44
645
+ ) {
646
+ throw new Error("Expected input string to decode to a byte array of length 32.");
647
+ }
648
+ const base58Encoder3 = getMemoizedBase58Encoder();
649
+ const bytes = base58Encoder3.encode(putativeAddress);
650
+ const numBytes = bytes.byteLength;
651
+ if (numBytes !== 32) {
652
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
653
+ }
654
+ } catch (e3) {
655
+ throw new Error(`\`${putativeAddress}\` is not a base-58 encoded address`, {
656
+ cause: e3
657
+ });
658
+ }
659
+ }
660
+ function address(putativeAddress) {
661
+ assertIsAddress(putativeAddress);
662
+ return putativeAddress;
663
+ }
664
+ function getAddressEncoder() {
665
+ return mapEncoder(
666
+ getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }),
667
+ (putativeAddress) => address(putativeAddress)
668
+ );
669
+ }
670
+ function getAddressDecoder() {
671
+ return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 });
672
+ }
673
+ function getAddressCodec() {
674
+ return combineCodec(getAddressEncoder(), getAddressDecoder());
675
+ }
676
+ function getAddressComparator() {
677
+ return new Intl.Collator("en", {
678
+ caseFirst: "lower",
679
+ ignorePunctuation: false,
680
+ localeMatcher: "best fit",
681
+ numeric: false,
682
+ sensitivity: "variant",
683
+ usage: "sort"
684
+ }).compare;
685
+ }
686
+ var D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
687
+ var P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;
688
+ var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
689
+ function mod(a) {
690
+ const r = a % P;
691
+ return r >= 0n ? r : P + r;
692
+ }
693
+ function pow2(x, power) {
694
+ let r = x;
695
+ while (power-- > 0n) {
696
+ r *= r;
697
+ r %= P;
698
+ }
699
+ return r;
700
+ }
701
+ function pow_2_252_3(x) {
702
+ const x2 = x * x % P;
703
+ const b2 = x2 * x % P;
704
+ const b4 = pow2(b2, 2n) * b2 % P;
705
+ const b5 = pow2(b4, 1n) * x % P;
706
+ const b10 = pow2(b5, 5n) * b5 % P;
707
+ const b20 = pow2(b10, 10n) * b10 % P;
708
+ const b40 = pow2(b20, 20n) * b20 % P;
709
+ const b80 = pow2(b40, 40n) * b40 % P;
710
+ const b160 = pow2(b80, 80n) * b80 % P;
711
+ const b240 = pow2(b160, 80n) * b80 % P;
712
+ const b250 = pow2(b240, 10n) * b10 % P;
713
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
714
+ return pow_p_5_8;
715
+ }
716
+ function uvRatio(u, v) {
717
+ const v3 = mod(v * v * v);
718
+ const v7 = mod(v3 * v3 * v);
719
+ const pow = pow_2_252_3(u * v7);
720
+ let x = mod(u * v3 * pow);
721
+ const vx2 = mod(v * x * x);
722
+ const root1 = x;
723
+ const root2 = mod(x * RM1);
724
+ const useRoot1 = vx2 === u;
725
+ const useRoot2 = vx2 === mod(-u);
726
+ const noRoot = vx2 === mod(-u * RM1);
727
+ if (useRoot1)
728
+ x = root1;
729
+ if (useRoot2 || noRoot)
730
+ x = root2;
731
+ if ((mod(x) & 1n) === 1n)
732
+ x = mod(-x);
733
+ if (!useRoot1 && !useRoot2) {
734
+ return null;
735
+ }
736
+ return x;
737
+ }
738
+ function pointIsOnCurve(y, lastByte) {
739
+ const y2 = mod(y * y);
740
+ const u = mod(y2 - 1n);
741
+ const v = mod(D * y2 + 1n);
742
+ const x = uvRatio(u, v);
743
+ if (x === null) {
744
+ return false;
745
+ }
746
+ const isLastByteOdd = (lastByte & 128) !== 0;
747
+ if (x === 0n && isLastByteOdd) {
748
+ return false;
749
+ }
750
+ return true;
751
+ }
752
+ function byteToHex(byte) {
753
+ const hexString = byte.toString(16);
754
+ if (hexString.length === 1) {
755
+ return `0${hexString}`;
756
+ } else {
757
+ return hexString;
758
+ }
759
+ }
760
+ function decompressPointBytes(bytes) {
761
+ const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
762
+ const integerLiteralString = `0x${hexString}`;
763
+ return BigInt(integerLiteralString);
764
+ }
765
+ async function compressedPointBytesAreOnCurve(bytes) {
766
+ if (bytes.byteLength !== 32) {
767
+ return false;
768
+ }
769
+ const y = decompressPointBytes(bytes);
770
+ return pointIsOnCurve(y, bytes[31]);
771
+ }
772
+ function isProgramDerivedAddress(value) {
773
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
774
+ }
775
+ function assertIsProgramDerivedAddress(value) {
776
+ const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
777
+ if (!validFormat) {
778
+ throw new Error(
779
+ `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`
780
+ );
781
+ }
782
+ if (value[1] < 0 || value[1] > 255) {
783
+ throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);
784
+ }
785
+ assertIsAddress(value[0]);
786
+ }
787
+ var MAX_SEED_LENGTH = 32;
788
+ var MAX_SEEDS = 16;
789
+ var PDA_MARKER_BYTES = [
790
+ // The string 'ProgramDerivedAddress'
791
+ 80,
792
+ 114,
793
+ 111,
794
+ 103,
795
+ 114,
796
+ 97,
797
+ 109,
798
+ 68,
799
+ 101,
800
+ 114,
801
+ 105,
802
+ 118,
803
+ 101,
804
+ 100,
805
+ 65,
806
+ 100,
807
+ 100,
808
+ 114,
809
+ 101,
810
+ 115,
811
+ 115
812
+ ];
813
+ var PointOnCurveError = class extends Error {
814
+ };
815
+ async function createProgramDerivedAddress({ programAddress, seeds }) {
816
+ await assertDigestCapabilityIsAvailable();
817
+ if (seeds.length > MAX_SEEDS) {
818
+ throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);
819
+ }
820
+ let textEncoder;
821
+ const seedBytes = seeds.reduce((acc, seed, ii) => {
822
+ const bytes = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
823
+ if (bytes.byteLength > MAX_SEED_LENGTH) {
824
+ throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);
825
+ }
826
+ acc.push(...bytes);
827
+ return acc;
828
+ }, []);
829
+ const base58EncodedAddressCodec = getAddressCodec();
830
+ const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
831
+ const addressBytesBuffer = await crypto.subtle.digest(
832
+ "SHA-256",
833
+ new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
834
+ );
835
+ const addressBytes = new Uint8Array(addressBytesBuffer);
836
+ if (await compressedPointBytesAreOnCurve(addressBytes)) {
837
+ throw new PointOnCurveError("Invalid seeds; point must fall off the Ed25519 curve");
838
+ }
839
+ return base58EncodedAddressCodec.decode(addressBytes);
840
+ }
841
+ async function getProgramDerivedAddress({
842
+ programAddress,
843
+ seeds
844
+ }) {
845
+ let bumpSeed = 255;
846
+ while (bumpSeed > 0) {
847
+ try {
848
+ const address2 = await createProgramDerivedAddress({
849
+ programAddress,
850
+ seeds: [...seeds, new Uint8Array([bumpSeed])]
851
+ });
852
+ return [address2, bumpSeed];
853
+ } catch (e3) {
854
+ if (e3 instanceof PointOnCurveError) {
855
+ bumpSeed--;
856
+ } else {
857
+ throw e3;
858
+ }
859
+ }
860
+ }
861
+ throw new Error("Unable to find a viable program address bump seed");
862
+ }
863
+ async function createAddressWithSeed({ baseAddress, programAddress, seed }) {
864
+ const { encode, decode } = getAddressCodec();
865
+ const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
866
+ if (seedBytes.byteLength > MAX_SEED_LENGTH) {
867
+ throw new Error(`The seed exceeds the maximum length of 32 bytes`);
868
+ }
869
+ const programAddressBytes = encode(programAddress);
870
+ if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
871
+ throw new Error(`programAddress cannot end with the PDA marker`);
872
+ }
873
+ const addressBytesBuffer = await crypto.subtle.digest(
874
+ "SHA-256",
875
+ new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])
876
+ );
877
+ const addressBytes = new Uint8Array(addressBytesBuffer);
878
+ return decode(addressBytes);
879
+ }
880
+ async function getAddressFromPublicKey(publicKey) {
881
+ await assertKeyExporterIsAvailable();
882
+ if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
883
+ throw new Error("The `CryptoKey` must be an `Ed25519` public key");
884
+ }
885
+ const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
886
+ return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
887
+ }
888
+
889
+ // ../functional/dist/index.browser.js
890
+ init_env_shim();
891
+ function pipe(init, ...fns) {
892
+ return fns.reduce((acc, fn) => fn(acc), init);
893
+ }
894
+
895
+ // ../instructions/dist/index.browser.js
896
+ init_env_shim();
897
+ var AccountRole = /* @__PURE__ */ ((AccountRole22) => {
898
+ AccountRole22[AccountRole22["WRITABLE_SIGNER"] = /* 3 */
899
+ 3] = "WRITABLE_SIGNER";
900
+ AccountRole22[AccountRole22["READONLY_SIGNER"] = /* 2 */
901
+ 2] = "READONLY_SIGNER";
902
+ AccountRole22[AccountRole22["WRITABLE"] = /* 1 */
903
+ 1] = "WRITABLE";
904
+ AccountRole22[AccountRole22["READONLY"] = /* 0 */
905
+ 0] = "READONLY";
906
+ return AccountRole22;
907
+ })(AccountRole || {});
908
+ var IS_SIGNER_BITMASK = 2;
909
+ var IS_WRITABLE_BITMASK = 1;
910
+ function downgradeRoleToNonSigner(role) {
911
+ return role & ~IS_SIGNER_BITMASK;
912
+ }
913
+ function downgradeRoleToReadonly(role) {
914
+ return role & ~IS_WRITABLE_BITMASK;
915
+ }
916
+ function isSignerRole(role) {
917
+ return role >= 2;
918
+ }
919
+ function isWritableRole(role) {
920
+ return (role & IS_WRITABLE_BITMASK) !== 0;
921
+ }
922
+ function mergeRoles(roleA, roleB) {
923
+ return roleA | roleB;
924
+ }
925
+ function upgradeRoleToSigner(role) {
926
+ return role | IS_SIGNER_BITMASK;
927
+ }
928
+ function upgradeRoleToWritable(role) {
929
+ return role | IS_WRITABLE_BITMASK;
930
+ }
931
+
932
+ // ../keys/dist/index.browser.js
933
+ init_env_shim();
934
+ async function generateKeyPair() {
935
+ await assertKeyGenerationIsAvailable();
936
+ const keyPair = await crypto.subtle.generateKey(
937
+ /* algorithm */
938
+ "Ed25519",
939
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
940
+ /* extractable */
941
+ false,
942
+ // Prevents the bytes of the private key from being visible to JS.
943
+ /* allowed uses */
944
+ ["sign", "verify"]
945
+ );
946
+ return keyPair;
947
+ }
948
+ function addPkcs8Header(bytes) {
949
+ return new Uint8Array([
950
+ /**
951
+ * PKCS#8 header
952
+ */
953
+ 48,
954
+ // ASN.1 sequence tag
955
+ 46,
956
+ // Length of sequence (46 more bytes)
957
+ 2,
958
+ // ASN.1 integer tag
959
+ 1,
960
+ // Length of integer
961
+ 0,
962
+ // Version number
963
+ 48,
964
+ // ASN.1 sequence tag
965
+ 5,
966
+ // Length of sequence
967
+ 6,
968
+ // ASN.1 object identifier tag
969
+ 3,
970
+ // Length of object identifier
971
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
972
+ 43,
973
+ // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
974
+ 101,
975
+ // thawte(101)
976
+ // Ed25519 identifier
977
+ 112,
978
+ // id-Ed25519(112)
979
+ /**
980
+ * Private key payload
981
+ */
982
+ 4,
983
+ // ASN.1 octet string tag
984
+ 34,
985
+ // String length (34 more bytes)
986
+ // Private key bytes as octet string
987
+ 4,
988
+ // ASN.1 octet string tag
989
+ 32,
990
+ // String length (32 bytes)
991
+ ...bytes
992
+ ]);
993
+ }
994
+ async function createPrivateKeyFromBytes(bytes, extractable) {
995
+ if (bytes.byteLength !== 32) {
996
+ throw new Error("Private key bytes must be of length 32");
997
+ }
998
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
999
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable != null ? extractable : false, ["sign"]);
1000
+ }
1001
+ var base58Encoder;
1002
+ function assertIsSignature(putativeSignature) {
1003
+ if (!base58Encoder)
1004
+ base58Encoder = getBase58Encoder();
1005
+ try {
1006
+ if (
1007
+ // Lowest value (64 bytes of zeroes)
1008
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
1009
+ putativeSignature.length > 88
1010
+ ) {
1011
+ throw new Error("Expected input string to decode to a byte array of length 64.");
1012
+ }
1013
+ const bytes = base58Encoder.encode(putativeSignature);
1014
+ const numBytes = bytes.byteLength;
1015
+ if (numBytes !== 64) {
1016
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
1017
+ }
1018
+ } catch (e3) {
1019
+ throw new Error(`\`${putativeSignature}\` is not a signature`, {
1020
+ cause: e3
1021
+ });
1022
+ }
1023
+ }
1024
+ function isSignature(putativeSignature) {
1025
+ if (!base58Encoder)
1026
+ base58Encoder = getBase58Encoder();
1027
+ if (
1028
+ // Lowest value (64 bytes of zeroes)
1029
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
1030
+ putativeSignature.length > 88
1031
+ ) {
1032
+ return false;
1033
+ }
1034
+ const bytes = base58Encoder.encode(putativeSignature);
1035
+ const numBytes = bytes.byteLength;
1036
+ if (numBytes !== 64) {
1037
+ return false;
1038
+ }
1039
+ return true;
1040
+ }
1041
+ async function signBytes(key, data) {
1042
+ await assertSigningCapabilityIsAvailable();
1043
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
1044
+ return new Uint8Array(signedData);
1045
+ }
1046
+ function signature(putativeSignature) {
1047
+ assertIsSignature(putativeSignature);
1048
+ return putativeSignature;
1049
+ }
1050
+ async function verifySignature(key, signature2, data) {
1051
+ await assertVerificationCapabilityIsAvailable();
1052
+ return await crypto.subtle.verify("Ed25519", key, signature2, data);
1053
+ }
1054
+
1055
+ // ../rpc-types/dist/index.browser.js
1056
+ init_env_shim();
1057
+ function getCommitmentScore(commitment) {
1058
+ switch (commitment) {
1059
+ case "finalized":
1060
+ return 2;
1061
+ case "confirmed":
1062
+ return 1;
1063
+ case "processed":
1064
+ return 0;
1065
+ default:
1066
+ return ((_) => {
1067
+ throw new Error(`Unrecognized commitment \`${commitment}\`.`);
1068
+ })();
1069
+ }
1070
+ }
1071
+ function commitmentComparator(a, b) {
1072
+ if (a === b) {
1073
+ return 0;
1074
+ }
1075
+ return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;
1076
+ }
1077
+ var maxU64Value = 18446744073709551615n;
1078
+ function isLamports(putativeLamports) {
1079
+ return putativeLamports >= 0 && putativeLamports <= maxU64Value;
1080
+ }
1081
+ function assertIsLamports(putativeLamports) {
1082
+ if (putativeLamports < 0) {
1083
+ throw new Error("Input for 64-bit unsigned integer cannot be negative");
1084
+ }
1085
+ if (putativeLamports > maxU64Value) {
1086
+ throw new Error("Input number is too large to be represented as a 64-bit unsigned integer");
1087
+ }
1088
+ }
1089
+ function lamports(putativeLamports) {
1090
+ assertIsLamports(putativeLamports);
1091
+ return putativeLamports;
1092
+ }
1093
+ function isStringifiedBigInt(putativeBigInt) {
1094
+ try {
1095
+ BigInt(putativeBigInt);
1096
+ return true;
1097
+ } catch (_) {
1098
+ return false;
1099
+ }
1100
+ }
1101
+ function assertIsStringifiedBigInt(putativeBigInt) {
1102
+ try {
1103
+ BigInt(putativeBigInt);
1104
+ } catch (e3) {
1105
+ throw new Error(`\`${putativeBigInt}\` cannot be parsed as a BigInt`, {
1106
+ cause: e3
1107
+ });
1108
+ }
1109
+ }
1110
+ function stringifiedBigInt(putativeBigInt) {
1111
+ assertIsStringifiedBigInt(putativeBigInt);
1112
+ return putativeBigInt;
1113
+ }
1114
+ function isStringifiedNumber(putativeNumber) {
1115
+ return !Number.isNaN(Number(putativeNumber));
1116
+ }
1117
+ function assertIsStringifiedNumber(putativeNumber) {
1118
+ if (Number.isNaN(Number(putativeNumber))) {
1119
+ throw new Error(`\`${putativeNumber}\` cannot be parsed as a Number`);
1120
+ }
1121
+ }
1122
+ function stringifiedNumber(putativeNumber) {
1123
+ assertIsStringifiedNumber(putativeNumber);
1124
+ return putativeNumber;
1125
+ }
1126
+ function isUnixTimestamp(putativeTimestamp) {
1127
+ if (putativeTimestamp > 864e13 || putativeTimestamp < -864e13) {
1128
+ return false;
1129
+ }
1130
+ return true;
1131
+ }
1132
+ function assertIsUnixTimestamp(putativeTimestamp) {
1133
+ try {
1134
+ if (putativeTimestamp > 864e13 || putativeTimestamp < -864e13) {
1135
+ throw new Error("Expected input number to be in the range [-8.64e15, 8.64e15]");
1136
+ }
1137
+ } catch (e3) {
1138
+ throw new Error(`\`${putativeTimestamp}\` is not a timestamp`, {
1139
+ cause: e3
1140
+ });
1141
+ }
1142
+ }
1143
+ function unixTimestamp(putativeTimestamp) {
1144
+ assertIsUnixTimestamp(putativeTimestamp);
1145
+ return putativeTimestamp;
1146
+ }
1147
+
1148
+ // ../transactions/dist/index.browser.js
1149
+ init_env_shim();
1150
+
1151
+ // ../codecs-data-structures/dist/index.browser.js
1152
+ init_env_shim();
1153
+ function assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {
1154
+ if (expected !== actual) {
1155
+ throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);
1156
+ }
1157
+ }
1158
+ function sumCodecSizes(sizes) {
1159
+ return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
1160
+ }
1161
+ function getFixedSize(codec) {
1162
+ return isFixedSize(codec) ? codec.fixedSize : null;
1163
+ }
1164
+ function getMaxSize(codec) {
1165
+ var _a;
1166
+ return isFixedSize(codec) ? codec.fixedSize : (_a = codec.maxSize) != null ? _a : null;
1167
+ }
1168
+ function getArrayEncoder(item, config = {}) {
1169
+ var _a, _b;
1170
+ const size = (_a = config.size) != null ? _a : getU32Encoder();
1171
+ if (size === "remainder") {
1172
+ assertIsFixedSize(item, 'Codecs of "remainder" size must have fixed-size items.');
1173
+ }
1174
+ const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));
1175
+ const maxSize = (_b = computeArrayLikeCodecSize(size, getMaxSize(item))) != null ? _b : void 0;
1176
+ return createEncoder({
1177
+ ...fixedSize !== null ? { fixedSize } : {
1178
+ getSizeFromValue: (array) => {
1179
+ const prefixSize = typeof size === "object" ? getEncodedSize(array.length, size) : 0;
1180
+ return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);
1181
+ },
1182
+ maxSize
1183
+ },
1184
+ write: (array, bytes, offset) => {
1185
+ if (typeof size === "number") {
1186
+ assertValidNumberOfItemsForCodec("array", size, array.length);
1187
+ }
1188
+ if (typeof size === "object") {
1189
+ offset = size.write(array.length, bytes, offset);
1190
+ }
1191
+ array.forEach((value) => {
1192
+ offset = item.write(value, bytes, offset);
1193
+ });
1194
+ return offset;
1195
+ }
1196
+ });
1197
+ }
1198
+ function getArrayDecoder(item, config = {}) {
1199
+ var _a, _b;
1200
+ const size = (_a = config.size) != null ? _a : getU32Decoder();
1201
+ if (size === "remainder") {
1202
+ assertIsFixedSize(item, 'Codecs of "remainder" size must have fixed-size items.');
1203
+ }
1204
+ const itemSize = getFixedSize(item);
1205
+ const fixedSize = computeArrayLikeCodecSize(size, itemSize);
1206
+ const maxSize = (_b = computeArrayLikeCodecSize(size, getMaxSize(item))) != null ? _b : void 0;
1207
+ return createDecoder({
1208
+ ...fixedSize !== null ? { fixedSize } : { maxSize },
1209
+ read: (bytes, offset) => {
1210
+ const array = [];
1211
+ if (typeof size === "object" && bytes.slice(offset).length === 0) {
1212
+ return [array, offset];
1213
+ }
1214
+ const [resolvedSize, newOffset] = readArrayLikeCodecSize(size, itemSize, bytes, offset);
1215
+ offset = newOffset;
1216
+ for (let i = 0; i < resolvedSize; i += 1) {
1217
+ const [value, newOffset2] = item.read(bytes, offset);
1218
+ offset = newOffset2;
1219
+ array.push(value);
1220
+ }
1221
+ return [array, offset];
1222
+ }
1223
+ });
1224
+ }
1225
+ function readArrayLikeCodecSize(size, itemSize, bytes, offset) {
1226
+ if (typeof size === "number") {
1227
+ return [size, offset];
1228
+ }
1229
+ if (typeof size === "object") {
1230
+ return size.read(bytes, offset);
1231
+ }
1232
+ if (size === "remainder") {
1233
+ if (itemSize === null) {
1234
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
1235
+ }
1236
+ const remainder = Math.max(0, bytes.length - offset);
1237
+ if (remainder % itemSize !== 0) {
1238
+ throw new Error(
1239
+ `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${itemSize} bytes. Codecs of "remainder" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${itemSize} should be equal to zero.`
1240
+ );
1241
+ }
1242
+ return [remainder / itemSize, offset];
1243
+ }
1244
+ throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);
1245
+ }
1246
+ function computeArrayLikeCodecSize(size, itemSize) {
1247
+ if (typeof size !== "number")
1248
+ return null;
1249
+ if (size === 0)
1250
+ return 0;
1251
+ return itemSize === null ? null : itemSize * size;
1252
+ }
1253
+ function getBytesEncoder(config = {}) {
1254
+ var _a;
1255
+ const size = (_a = config.size) != null ? _a : "variable";
1256
+ const byteEncoder = createEncoder({
1257
+ getSizeFromValue: (value) => value.length,
1258
+ write: (value, bytes, offset) => {
1259
+ bytes.set(value, offset);
1260
+ return offset + value.length;
1261
+ }
1262
+ });
1263
+ if (size === "variable") {
1264
+ return byteEncoder;
1265
+ }
1266
+ if (typeof size === "number") {
1267
+ return fixEncoder(byteEncoder, size);
1268
+ }
1269
+ return createEncoder({
1270
+ getSizeFromValue: (value) => getEncodedSize(value.length, size) + value.length,
1271
+ write: (value, bytes, offset) => {
1272
+ offset = size.write(value.length, bytes, offset);
1273
+ return byteEncoder.write(value, bytes, offset);
1274
+ }
1275
+ });
1276
+ }
1277
+ function getBytesDecoder(config = {}) {
1278
+ var _a;
1279
+ const size = (_a = config.size) != null ? _a : "variable";
1280
+ const byteDecoder = createDecoder({
1281
+ read: (bytes, offset) => {
1282
+ const slice = bytes.slice(offset);
1283
+ return [slice, offset + slice.length];
1284
+ }
1285
+ });
1286
+ if (size === "variable") {
1287
+ return byteDecoder;
1288
+ }
1289
+ if (typeof size === "number") {
1290
+ return fixDecoder(byteDecoder, size);
1291
+ }
1292
+ return createDecoder({
1293
+ read: (bytes, offset) => {
1294
+ assertByteArrayIsNotEmptyForCodec("bytes", bytes, offset);
1295
+ const [lengthBigInt, lengthOffset] = size.read(bytes, offset);
1296
+ const length = Number(lengthBigInt);
1297
+ offset = lengthOffset;
1298
+ const contentBytes = bytes.slice(offset, offset + length);
1299
+ assertByteArrayHasEnoughBytesForCodec("bytes", length, contentBytes);
1300
+ const [value, contentOffset] = byteDecoder.read(contentBytes, 0);
1301
+ offset += contentOffset;
1302
+ return [value, offset];
1303
+ }
1304
+ });
1305
+ }
1306
+ function getStructEncoder(fields) {
1307
+ var _a;
1308
+ const fieldCodecs = fields.map(([, codec]) => codec);
1309
+ const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));
1310
+ const maxSize = (_a = sumCodecSizes(fieldCodecs.map(getMaxSize))) != null ? _a : void 0;
1311
+ return createEncoder({
1312
+ ...fixedSize === null ? {
1313
+ getSizeFromValue: (value) => fields.map(([key, codec]) => getEncodedSize(value[key], codec)).reduce((all, one) => all + one, 0),
1314
+ maxSize
1315
+ } : { fixedSize },
1316
+ write: (struct, bytes, offset) => {
1317
+ fields.forEach(([key, codec]) => {
1318
+ offset = codec.write(struct[key], bytes, offset);
1319
+ });
1320
+ return offset;
1321
+ }
1322
+ });
1323
+ }
1324
+ function getStructDecoder(fields) {
1325
+ var _a;
1326
+ const fieldCodecs = fields.map(([, codec]) => codec);
1327
+ const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));
1328
+ const maxSize = (_a = sumCodecSizes(fieldCodecs.map(getMaxSize))) != null ? _a : void 0;
1329
+ return createDecoder({
1330
+ ...fixedSize === null ? { maxSize } : { fixedSize },
1331
+ read: (bytes, offset) => {
1332
+ const struct = {};
1333
+ fields.forEach(([key, codec]) => {
1334
+ const [value, newOffset] = codec.read(bytes, offset);
1335
+ offset = newOffset;
1336
+ struct[key] = value;
1337
+ });
1338
+ return [struct, offset];
1339
+ }
1340
+ });
1341
+ }
1342
+
1343
+ // ../transactions/dist/index.browser.js
1344
+ function getUnsignedTransaction(transaction) {
1345
+ if ("signatures" in transaction) {
1346
+ const {
1347
+ signatures: _,
1348
+ // eslint-disable-line @typescript-eslint/no-unused-vars
1349
+ ...unsignedTransaction
1350
+ } = transaction;
1351
+ return unsignedTransaction;
1352
+ } else {
1353
+ return transaction;
1354
+ }
1355
+ }
1356
+ var base58Encoder2;
1357
+ function assertIsBlockhash(putativeBlockhash) {
1358
+ if (!base58Encoder2)
1359
+ base58Encoder2 = getBase58Encoder();
1360
+ try {
1361
+ if (
1362
+ // Lowest value (32 bytes of zeroes)
1363
+ putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)
1364
+ putativeBlockhash.length > 44
1365
+ ) {
1366
+ throw new Error("Expected input string to decode to a byte array of length 32.");
1367
+ }
1368
+ const bytes = base58Encoder2.encode(putativeBlockhash);
1369
+ const numBytes = bytes.byteLength;
1370
+ if (numBytes !== 32) {
1371
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
1372
+ }
1373
+ } catch (e3) {
1374
+ throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, {
1375
+ cause: e3
1376
+ });
1377
+ }
1378
+ }
1379
+ function isTransactionWithBlockhashLifetime(transaction) {
1380
+ const lifetimeConstraintShapeMatches = "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.blockhash === "string" && typeof transaction.lifetimeConstraint.lastValidBlockHeight === "bigint";
1381
+ if (!lifetimeConstraintShapeMatches)
1382
+ return false;
1383
+ try {
1384
+ assertIsBlockhash(transaction.lifetimeConstraint.blockhash);
1385
+ return true;
1386
+ } catch {
1387
+ return false;
1388
+ }
1389
+ }
1390
+ function assertIsTransactionWithBlockhashLifetime(transaction) {
1391
+ if (!isTransactionWithBlockhashLifetime(transaction)) {
1392
+ throw new Error("Transaction does not have a blockhash lifetime");
1393
+ }
1394
+ }
1395
+ function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {
1396
+ if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
1397
+ return transaction;
1398
+ }
1399
+ const out = {
1400
+ ...getUnsignedTransaction(transaction),
1401
+ lifetimeConstraint: blockhashLifetimeConstraint
1402
+ };
1403
+ Object.freeze(out);
1404
+ return out;
1405
+ }
1406
+ function createTransaction({
1407
+ version
1408
+ }) {
1409
+ const out = {
1410
+ instructions: [],
1411
+ version
1412
+ };
1413
+ Object.freeze(out);
1414
+ return out;
1415
+ }
1416
+ var AccountRole2 = /* @__PURE__ */ ((AccountRole22) => {
1417
+ AccountRole22[AccountRole22["WRITABLE_SIGNER"] = /* 3 */
1418
+ 3] = "WRITABLE_SIGNER";
1419
+ AccountRole22[AccountRole22["READONLY_SIGNER"] = /* 2 */
1420
+ 2] = "READONLY_SIGNER";
1421
+ AccountRole22[AccountRole22["WRITABLE"] = /* 1 */
1422
+ 1] = "WRITABLE";
1423
+ AccountRole22[AccountRole22["READONLY"] = /* 0 */
1424
+ 0] = "READONLY";
1425
+ return AccountRole22;
1426
+ })(AccountRole2 || {});
1427
+ var IS_WRITABLE_BITMASK2 = 1;
1428
+ function isSignerRole2(role) {
1429
+ return role >= 2;
1430
+ }
1431
+ function isWritableRole2(role) {
1432
+ return (role & IS_WRITABLE_BITMASK2) !== 0;
1433
+ }
1434
+ function mergeRoles2(roleA, roleB) {
1435
+ return roleA | roleB;
1436
+ }
1437
+ var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111";
1438
+ var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
1439
+ function assertIsDurableNonceTransaction(transaction) {
1440
+ if (!isDurableNonceTransaction(transaction)) {
1441
+ throw new Error("Transaction is not a durable nonce transaction");
1442
+ }
1443
+ }
1444
+ function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {
1445
+ return {
1446
+ accounts: [
1447
+ { address: nonceAccountAddress, role: AccountRole2.WRITABLE },
1448
+ {
1449
+ address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,
1450
+ role: AccountRole2.READONLY
1451
+ },
1452
+ { address: nonceAuthorityAddress, role: AccountRole2.READONLY_SIGNER }
1453
+ ],
1454
+ data: new Uint8Array([4, 0, 0, 0]),
1455
+ programAddress: SYSTEM_PROGRAM_ADDRESS
1456
+ };
1457
+ }
1458
+ function isAdvanceNonceAccountInstruction(instruction) {
1459
+ var _a;
1460
+ return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data
1461
+ instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts
1462
+ ((_a = instruction.accounts) == null ? void 0 : _a.length) === 3 && // First account is nonce account address
1463
+ instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole2.WRITABLE && // Second account is recent blockhashes sysvar
1464
+ instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole2.READONLY && // Third account is nonce authority account
1465
+ instruction.accounts[2].address != null && isSignerRole2(instruction.accounts[2].role);
1466
+ }
1467
+ function isAdvanceNonceAccountInstructionData(data) {
1468
+ return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
1469
+ }
1470
+ function isDurableNonceTransaction(transaction) {
1471
+ return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
1472
+ }
1473
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
1474
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
1475
+ }
1476
+ function setTransactionLifetimeUsingDurableNonce({
1477
+ nonce,
1478
+ nonceAccountAddress,
1479
+ nonceAuthorityAddress
1480
+ }, transaction) {
1481
+ let newInstructions;
1482
+ const firstInstruction = transaction.instructions[0];
1483
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
1484
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
1485
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
1486
+ return transaction;
1487
+ } else {
1488
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
1489
+ }
1490
+ } else {
1491
+ newInstructions = [
1492
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1493
+ ...transaction.instructions.slice(1)
1494
+ ];
1495
+ }
1496
+ } else {
1497
+ newInstructions = [
1498
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
1499
+ ...transaction.instructions
1500
+ ];
1501
+ }
1502
+ const out = {
1503
+ ...getUnsignedTransaction(transaction),
1504
+ instructions: newInstructions,
1505
+ lifetimeConstraint: {
1506
+ nonce
1507
+ }
1508
+ };
1509
+ Object.freeze(out);
1510
+ return out;
1511
+ }
1512
+ function setTransactionFeePayer(feePayer, transaction) {
1513
+ if ("feePayer" in transaction && feePayer === transaction.feePayer) {
1514
+ return transaction;
1515
+ }
1516
+ const out = {
1517
+ ...getUnsignedTransaction(transaction),
1518
+ feePayer
1519
+ };
1520
+ Object.freeze(out);
1521
+ return out;
1522
+ }
1523
+ function appendTransactionInstruction(instruction, transaction) {
1524
+ const out = {
1525
+ ...getUnsignedTransaction(transaction),
1526
+ instructions: [...transaction.instructions, instruction]
1527
+ };
1528
+ Object.freeze(out);
1529
+ return out;
1530
+ }
1531
+ function prependTransactionInstruction(instruction, transaction) {
1532
+ const out = {
1533
+ ...getUnsignedTransaction(transaction),
1534
+ instructions: [instruction, ...transaction.instructions]
1535
+ };
1536
+ Object.freeze(out);
1537
+ return out;
1538
+ }
1539
+ function upsert(addressMap, address2, update) {
1540
+ var _a;
1541
+ addressMap[address2] = update((_a = addressMap[address2]) != null ? _a : { role: AccountRole2.READONLY });
1542
+ }
1543
+ var TYPE = Symbol("AddressMapTypeProperty");
1544
+ function getAddressMapFromInstructions(feePayer, instructions) {
1545
+ const addressMap = {
1546
+ [feePayer]: { [TYPE]: 0, role: AccountRole2.WRITABLE_SIGNER }
1547
+ };
1548
+ const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();
1549
+ for (const instruction of instructions) {
1550
+ upsert(addressMap, instruction.programAddress, (entry) => {
1551
+ addressesOfInvokedPrograms.add(instruction.programAddress);
1552
+ if (TYPE in entry) {
1553
+ if (isWritableRole2(entry.role)) {
1554
+ switch (entry[TYPE]) {
1555
+ case 0:
1556
+ throw new Error(
1557
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`
1558
+ );
1559
+ default:
1560
+ throw new Error(
1561
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1562
+ );
1563
+ }
1564
+ }
1565
+ if (entry[TYPE] === 2) {
1566
+ return entry;
1567
+ }
1568
+ }
1569
+ return { [TYPE]: 2, role: AccountRole2.READONLY };
1570
+ });
1571
+ let addressComparator;
1572
+ if (!instruction.accounts) {
1573
+ continue;
1574
+ }
1575
+ for (const account of instruction.accounts) {
1576
+ upsert(addressMap, account.address, (entry) => {
1577
+ const {
1578
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1579
+ address: _,
1580
+ ...accountMeta
1581
+ } = account;
1582
+ if (TYPE in entry) {
1583
+ switch (entry[TYPE]) {
1584
+ case 0:
1585
+ return entry;
1586
+ case 1: {
1587
+ const nextRole = mergeRoles2(entry.role, accountMeta.role);
1588
+ if ("lookupTableAddress" in accountMeta) {
1589
+ const shouldReplaceEntry = (
1590
+ // Consider using the new LOOKUP_TABLE if its address is different...
1591
+ entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
1592
+ (addressComparator || (addressComparator = getAddressComparator()))(
1593
+ accountMeta.lookupTableAddress,
1594
+ entry.lookupTableAddress
1595
+ ) < 0
1596
+ );
1597
+ if (shouldReplaceEntry) {
1598
+ return {
1599
+ [TYPE]: 1,
1600
+ ...accountMeta,
1601
+ role: nextRole
1602
+ };
1603
+ }
1604
+ } else if (isSignerRole2(accountMeta.role)) {
1605
+ return {
1606
+ [TYPE]: 2,
1607
+ role: nextRole
1608
+ };
1609
+ }
1610
+ if (entry.role !== nextRole) {
1611
+ return {
1612
+ ...entry,
1613
+ role: nextRole
1614
+ };
1615
+ } else {
1616
+ return entry;
1617
+ }
1618
+ }
1619
+ case 2: {
1620
+ const nextRole = mergeRoles2(entry.role, accountMeta.role);
1621
+ if (
1622
+ // Check to see if this address represents a program that is invoked
1623
+ // in this transaction.
1624
+ addressesOfInvokedPrograms.has(account.address)
1625
+ ) {
1626
+ if (isWritableRole2(accountMeta.role)) {
1627
+ throw new Error(
1628
+ `This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1629
+ );
1630
+ }
1631
+ if (entry.role !== nextRole) {
1632
+ return {
1633
+ ...entry,
1634
+ role: nextRole
1635
+ };
1636
+ } else {
1637
+ return entry;
1638
+ }
1639
+ } else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as
1640
+ // long as they are not require to sign the transaction.
1641
+ !isSignerRole2(entry.role)) {
1642
+ return {
1643
+ ...accountMeta,
1644
+ [TYPE]: 1,
1645
+ role: nextRole
1646
+ };
1647
+ } else {
1648
+ if (entry.role !== nextRole) {
1649
+ return {
1650
+ ...entry,
1651
+ role: nextRole
1652
+ };
1653
+ } else {
1654
+ return entry;
1655
+ }
1656
+ }
1657
+ }
1658
+ }
1659
+ }
1660
+ if ("lookupTableAddress" in accountMeta) {
1661
+ return {
1662
+ ...accountMeta,
1663
+ [TYPE]: 1
1664
+ /* LOOKUP_TABLE */
1665
+ };
1666
+ } else {
1667
+ return {
1668
+ ...accountMeta,
1669
+ [TYPE]: 2
1670
+ /* STATIC */
1671
+ };
1672
+ }
1673
+ });
1674
+ }
1675
+ }
1676
+ return addressMap;
1677
+ }
1678
+ function getOrderedAccountsFromAddressMap(addressMap) {
1679
+ let addressComparator;
1680
+ const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {
1681
+ if (leftEntry[TYPE] !== rightEntry[TYPE]) {
1682
+ if (leftEntry[TYPE] === 0) {
1683
+ return -1;
1684
+ } else if (rightEntry[TYPE] === 0) {
1685
+ return 1;
1686
+ } else if (leftEntry[TYPE] === 2) {
1687
+ return -1;
1688
+ } else if (rightEntry[TYPE] === 2) {
1689
+ return 1;
1690
+ }
1691
+ }
1692
+ const leftIsSigner = isSignerRole2(leftEntry.role);
1693
+ if (leftIsSigner !== isSignerRole2(rightEntry.role)) {
1694
+ return leftIsSigner ? -1 : 1;
1695
+ }
1696
+ const leftIsWritable = isWritableRole2(leftEntry.role);
1697
+ if (leftIsWritable !== isWritableRole2(rightEntry.role)) {
1698
+ return leftIsWritable ? -1 : 1;
1699
+ }
1700
+ addressComparator || (addressComparator = getAddressComparator());
1701
+ if (leftEntry[TYPE] === 1 && rightEntry[TYPE] === 1 && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
1702
+ return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
1703
+ } else {
1704
+ return addressComparator(leftAddress, rightAddress);
1705
+ }
1706
+ }).map(([address2, addressMeta]) => ({
1707
+ address: address2,
1708
+ ...addressMeta
1709
+ }));
1710
+ return orderedAccounts;
1711
+ }
1712
+ function getCompiledAddressTableLookups(orderedAccounts) {
1713
+ var _a;
1714
+ const index = {};
1715
+ for (const account of orderedAccounts) {
1716
+ if (!("lookupTableAddress" in account)) {
1717
+ continue;
1718
+ }
1719
+ const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
1720
+ readableIndices: [],
1721
+ writableIndices: []
1722
+ });
1723
+ if (account.role === AccountRole2.WRITABLE) {
1724
+ entry.writableIndices.push(account.addressIndex);
1725
+ } else {
1726
+ entry.readableIndices.push(account.addressIndex);
1727
+ }
1728
+ }
1729
+ return Object.keys(index).sort(getAddressComparator()).map((lookupTableAddress) => ({
1730
+ lookupTableAddress,
1731
+ ...index[lookupTableAddress]
1732
+ }));
1733
+ }
1734
+ function getCompiledMessageHeader(orderedAccounts) {
1735
+ let numReadonlyNonSignerAccounts = 0;
1736
+ let numReadonlySignerAccounts = 0;
1737
+ let numSignerAccounts = 0;
1738
+ for (const account of orderedAccounts) {
1739
+ if ("lookupTableAddress" in account) {
1740
+ break;
1741
+ }
1742
+ const accountIsWritable = isWritableRole2(account.role);
1743
+ if (isSignerRole2(account.role)) {
1744
+ numSignerAccounts++;
1745
+ if (!accountIsWritable) {
1746
+ numReadonlySignerAccounts++;
1747
+ }
1748
+ } else if (!accountIsWritable) {
1749
+ numReadonlyNonSignerAccounts++;
1750
+ }
1751
+ }
1752
+ return {
1753
+ numReadonlyNonSignerAccounts,
1754
+ numReadonlySignerAccounts,
1755
+ numSignerAccounts
1756
+ };
1757
+ }
1758
+ function getAccountIndex(orderedAccounts) {
1759
+ const out = {};
1760
+ for (const [index, account] of orderedAccounts.entries()) {
1761
+ out[account.address] = index;
1762
+ }
1763
+ return out;
1764
+ }
1765
+ function getCompiledInstructions(instructions, orderedAccounts) {
1766
+ const accountIndex = getAccountIndex(orderedAccounts);
1767
+ return instructions.map(({ accounts, data, programAddress }) => {
1768
+ return {
1769
+ programAddressIndex: accountIndex[programAddress],
1770
+ ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
1771
+ ...data ? { data } : null
1772
+ };
1773
+ });
1774
+ }
1775
+ function getCompiledLifetimeToken(lifetimeConstraint) {
1776
+ if ("nonce" in lifetimeConstraint) {
1777
+ return lifetimeConstraint.nonce;
1778
+ }
1779
+ return lifetimeConstraint.blockhash;
1780
+ }
1781
+ function getCompiledStaticAccounts(orderedAccounts) {
1782
+ const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
1783
+ const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
1784
+ return orderedStaticAccounts.map(({ address: address2 }) => address2);
1785
+ }
1786
+ function compileMessage(transaction) {
1787
+ const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
1788
+ const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);
1789
+ return {
1790
+ ...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,
1791
+ header: getCompiledMessageHeader(orderedAccounts),
1792
+ instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),
1793
+ lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),
1794
+ staticAccounts: getCompiledStaticAccounts(orderedAccounts),
1795
+ version: transaction.version
1796
+ };
1797
+ }
1798
+ var memoizedAddressTableLookupEncoder;
1799
+ function getAddressTableLookupEncoder() {
1800
+ if (!memoizedAddressTableLookupEncoder) {
1801
+ memoizedAddressTableLookupEncoder = getStructEncoder([
1802
+ ["lookupTableAddress", getAddressEncoder()],
1803
+ [
1804
+ "writableIndices",
1805
+ getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })
1806
+ ],
1807
+ [
1808
+ "readableIndices",
1809
+ getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })
1810
+ ]
1811
+ ]);
1812
+ }
1813
+ return memoizedAddressTableLookupEncoder;
1814
+ }
1815
+ var memoizedAddressTableLookupDecoder;
1816
+ function getAddressTableLookupDecoder() {
1817
+ if (!memoizedAddressTableLookupDecoder) {
1818
+ memoizedAddressTableLookupDecoder = getStructDecoder([
1819
+ ["lookupTableAddress", getAddressDecoder()],
1820
+ ["writableIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],
1821
+ ["readableIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })]
1822
+ ]);
1823
+ }
1824
+ return memoizedAddressTableLookupDecoder;
1825
+ }
1826
+ var memoizedU8Encoder;
1827
+ function getMemoizedU8Encoder() {
1828
+ if (!memoizedU8Encoder)
1829
+ memoizedU8Encoder = getU8Encoder();
1830
+ return memoizedU8Encoder;
1831
+ }
1832
+ var memoizedU8Decoder;
1833
+ function getMemoizedU8Decoder() {
1834
+ if (!memoizedU8Decoder)
1835
+ memoizedU8Decoder = getU8Decoder();
1836
+ return memoizedU8Decoder;
1837
+ }
1838
+ function getMessageHeaderEncoder() {
1839
+ return getStructEncoder([
1840
+ ["numSignerAccounts", getMemoizedU8Encoder()],
1841
+ ["numReadonlySignerAccounts", getMemoizedU8Encoder()],
1842
+ ["numReadonlyNonSignerAccounts", getMemoizedU8Encoder()]
1843
+ ]);
1844
+ }
1845
+ function getMessageHeaderDecoder() {
1846
+ return getStructDecoder([
1847
+ ["numSignerAccounts", getMemoizedU8Decoder()],
1848
+ ["numReadonlySignerAccounts", getMemoizedU8Decoder()],
1849
+ ["numReadonlyNonSignerAccounts", getMemoizedU8Decoder()]
1850
+ ]);
1851
+ }
1852
+ var memoizedGetInstructionEncoder;
1853
+ function getInstructionEncoder() {
1854
+ if (!memoizedGetInstructionEncoder) {
1855
+ memoizedGetInstructionEncoder = mapEncoder(
1856
+ getStructEncoder([
1857
+ ["programAddressIndex", getU8Encoder()],
1858
+ ["accountIndices", getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],
1859
+ ["data", getBytesEncoder({ size: getShortU16Encoder() })]
1860
+ ]),
1861
+ // Convert an instruction to have all fields defined
1862
+ (instruction) => {
1863
+ var _a, _b;
1864
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
1865
+ return instruction;
1866
+ }
1867
+ return {
1868
+ ...instruction,
1869
+ accountIndices: (_a = instruction.accountIndices) != null ? _a : [],
1870
+ data: (_b = instruction.data) != null ? _b : new Uint8Array(0)
1871
+ };
1872
+ }
1873
+ );
1874
+ }
1875
+ return memoizedGetInstructionEncoder;
1876
+ }
1877
+ var memoizedGetInstructionDecoder;
1878
+ function getInstructionDecoder() {
1879
+ if (!memoizedGetInstructionDecoder) {
1880
+ memoizedGetInstructionDecoder = mapDecoder(
1881
+ getStructDecoder([
1882
+ ["programAddressIndex", getU8Decoder()],
1883
+ ["accountIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],
1884
+ ["data", getBytesDecoder({ size: getShortU16Decoder() })]
1885
+ ]),
1886
+ // Convert an instruction to exclude optional fields if they are empty
1887
+ (instruction) => {
1888
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
1889
+ return instruction;
1890
+ }
1891
+ const { accountIndices, data, ...rest } = instruction;
1892
+ return {
1893
+ ...rest,
1894
+ ...accountIndices.length ? { accountIndices } : null,
1895
+ ...data.byteLength ? { data } : null
1896
+ };
1897
+ }
586
1898
  );
587
- } else if (typeof value === "object" && value !== null) {
588
- const out = {};
589
- for (const propName in value) {
590
- if (Object.prototype.hasOwnProperty.call(value, propName)) {
591
- out[propName] = visitNode(value[propName], [...keyPath, propName], onIntegerOverflow);
1899
+ }
1900
+ return memoizedGetInstructionDecoder;
1901
+ }
1902
+ var VERSION_FLAG_MASK = 128;
1903
+ function getTransactionVersionEncoder() {
1904
+ return createEncoder({
1905
+ getSizeFromValue: (value) => value === "legacy" ? 0 : 1,
1906
+ maxSize: 1,
1907
+ write: (value, bytes, offset) => {
1908
+ if (value === "legacy") {
1909
+ return offset;
1910
+ }
1911
+ if (value < 0 || value > 127) {
1912
+ throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
1913
+ }
1914
+ bytes.set([value | VERSION_FLAG_MASK], offset);
1915
+ return offset + 1;
1916
+ }
1917
+ });
1918
+ }
1919
+ function getTransactionVersionDecoder() {
1920
+ return createDecoder({
1921
+ maxSize: 1,
1922
+ read: (bytes, offset) => {
1923
+ const firstByte = bytes[offset];
1924
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
1925
+ return ["legacy", offset];
1926
+ } else {
1927
+ const version = firstByte ^ VERSION_FLAG_MASK;
1928
+ return [version, offset + 1];
1929
+ }
1930
+ }
1931
+ });
1932
+ }
1933
+ function getCompiledMessageLegacyEncoder() {
1934
+ return getStructEncoder(getPreludeStructEncoderTuple());
1935
+ }
1936
+ function getCompiledMessageVersionedEncoder() {
1937
+ return mapEncoder(
1938
+ getStructEncoder([
1939
+ ...getPreludeStructEncoderTuple(),
1940
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
1941
+ ]),
1942
+ (value) => {
1943
+ var _a;
1944
+ if (value.version === "legacy") {
1945
+ return value;
1946
+ }
1947
+ return {
1948
+ ...value,
1949
+ addressTableLookups: (_a = value.addressTableLookups) != null ? _a : []
1950
+ };
1951
+ }
1952
+ );
1953
+ }
1954
+ function getPreludeStructEncoderTuple() {
1955
+ return [
1956
+ ["version", getTransactionVersionEncoder()],
1957
+ ["header", getMessageHeaderEncoder()],
1958
+ ["staticAccounts", getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],
1959
+ ["lifetimeToken", getStringEncoder({ encoding: getBase58Encoder(), size: 32 })],
1960
+ ["instructions", getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })]
1961
+ ];
1962
+ }
1963
+ function getPreludeStructDecoderTuple() {
1964
+ return [
1965
+ ["version", getTransactionVersionDecoder()],
1966
+ ["header", getMessageHeaderDecoder()],
1967
+ ["staticAccounts", getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],
1968
+ ["lifetimeToken", getStringDecoder({ encoding: getBase58Decoder(), size: 32 })],
1969
+ ["instructions", getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],
1970
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
1971
+ ];
1972
+ }
1973
+ function getAddressTableLookupArrayEncoder() {
1974
+ return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });
1975
+ }
1976
+ function getAddressTableLookupArrayDecoder() {
1977
+ return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });
1978
+ }
1979
+ function getCompiledMessageEncoder() {
1980
+ return createEncoder({
1981
+ getSizeFromValue: (compiledMessage) => {
1982
+ if (compiledMessage.version === "legacy") {
1983
+ return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);
1984
+ } else {
1985
+ return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);
1986
+ }
1987
+ },
1988
+ write: (compiledMessage, bytes, offset) => {
1989
+ if (compiledMessage.version === "legacy") {
1990
+ return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);
1991
+ } else {
1992
+ return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);
592
1993
  }
593
1994
  }
594
- return out;
595
- } else if (typeof value === "bigint") {
596
- if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {
597
- onIntegerOverflow(keyPath, value);
1995
+ });
1996
+ }
1997
+ function getCompiledMessageDecoder() {
1998
+ return mapDecoder(getStructDecoder(getPreludeStructDecoderTuple()), ({ addressTableLookups, ...restOfMessage }) => {
1999
+ if (restOfMessage.version === "legacy" || !(addressTableLookups == null ? void 0 : addressTableLookups.length)) {
2000
+ return restOfMessage;
2001
+ }
2002
+ return { ...restOfMessage, addressTableLookups };
2003
+ });
2004
+ }
2005
+ function getCompiledMessageCodec() {
2006
+ return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());
2007
+ }
2008
+ function getCompiledTransaction(transaction) {
2009
+ var _a;
2010
+ const compiledMessage = compileMessage(transaction);
2011
+ let signatures;
2012
+ if ("signatures" in transaction) {
2013
+ signatures = [];
2014
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
2015
+ signatures[ii] = (_a = transaction.signatures[compiledMessage.staticAccounts[ii]]) != null ? _a : new Uint8Array(Array(64).fill(0));
598
2016
  }
599
- return Number(value);
600
2017
  } else {
601
- return value;
2018
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
602
2019
  }
2020
+ return {
2021
+ compiledMessage,
2022
+ signatures
2023
+ };
603
2024
  }
604
- function patchParamsForSolanaLabsRpc(params, onIntegerOverflow) {
605
- return visitNode(params, [], onIntegerOverflow);
2025
+ function getAccountMetas(message) {
2026
+ const { header } = message;
2027
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
2028
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
2029
+ const accountMetas = [];
2030
+ let accountIndex = 0;
2031
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
2032
+ accountMetas.push({
2033
+ address: message.staticAccounts[accountIndex],
2034
+ role: AccountRole2.WRITABLE_SIGNER
2035
+ });
2036
+ accountIndex++;
2037
+ }
2038
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
2039
+ accountMetas.push({
2040
+ address: message.staticAccounts[accountIndex],
2041
+ role: AccountRole2.READONLY_SIGNER
2042
+ });
2043
+ accountIndex++;
2044
+ }
2045
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
2046
+ accountMetas.push({
2047
+ address: message.staticAccounts[accountIndex],
2048
+ role: AccountRole2.WRITABLE
2049
+ });
2050
+ accountIndex++;
2051
+ }
2052
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
2053
+ accountMetas.push({
2054
+ address: message.staticAccounts[accountIndex],
2055
+ role: AccountRole2.READONLY
2056
+ });
2057
+ accountIndex++;
2058
+ }
2059
+ return accountMetas;
606
2060
  }
607
- var KEYPATH_WILDCARD = {};
608
- var ALLOWED_NUMERIC_KEYPATHS = {
609
- getAccountInfo: [
610
- // parsed AddressTableLookup account
611
- ["value", "data", "parsed", "info", "lastExtendedSlotStartIndex"],
612
- // parsed Config account
613
- ["value", "data", "parsed", "info", "slashPenalty"],
614
- ["value", "data", "parsed", "info", "warmupCooldownRate"],
615
- // parsed Token/Token22 token account
616
- ["value", "data", "parsed", "info", "tokenAmount", "decimals"],
617
- ["value", "data", "parsed", "info", "tokenAmount", "uiAmount"],
618
- ["value", "data", "parsed", "info", "rentExemptReserve", "decimals"],
619
- ["value", "data", "parsed", "info", "delegatedAmount", "decimals"],
620
- [
621
- "value",
622
- "data",
623
- "parsed",
624
- "info",
625
- "extensions",
626
- KEYPATH_WILDCARD,
627
- "state",
628
- "olderTransferFee",
629
- "transferFeeBasisPoints"
630
- ],
2061
+ function convertInstruction(instruction, accountMetas) {
2062
+ var _a, _b;
2063
+ const programAddress = (_a = accountMetas[instruction.programAddressIndex]) == null ? void 0 : _a.address;
2064
+ if (!programAddress) {
2065
+ throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);
2066
+ }
2067
+ const accounts = (_b = instruction.accountIndices) == null ? void 0 : _b.map((accountIndex) => accountMetas[accountIndex]);
2068
+ const { data } = instruction;
2069
+ return {
2070
+ programAddress,
2071
+ ...accounts && accounts.length ? { accounts } : {},
2072
+ ...data && data.length ? { data } : {}
2073
+ };
2074
+ }
2075
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
2076
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
2077
+ return {
2078
+ blockhash: messageLifetimeToken,
2079
+ lastValidBlockHeight: lastValidBlockHeight != null ? lastValidBlockHeight : 2n ** 64n - 1n
2080
+ // U64 MAX
2081
+ };
2082
+ } else {
2083
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
2084
+ assertIsAddress(nonceAccountAddress);
2085
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
2086
+ assertIsAddress(nonceAuthorityAddress);
2087
+ return {
2088
+ nonce: messageLifetimeToken,
2089
+ nonceAccountAddress,
2090
+ nonceAuthorityAddress
2091
+ };
2092
+ }
2093
+ }
2094
+ function convertSignatures(compiledTransaction) {
2095
+ const {
2096
+ compiledMessage: { staticAccounts },
2097
+ signatures
2098
+ } = compiledTransaction;
2099
+ return signatures.reduce((acc, sig, index) => {
2100
+ const allZeros = sig.every((byte) => byte === 0);
2101
+ if (allZeros)
2102
+ return acc;
2103
+ const address2 = staticAccounts[index];
2104
+ return { ...acc, [address2]: sig };
2105
+ }, {});
2106
+ }
2107
+ function decompileTransaction(compiledTransaction, lastValidBlockHeight) {
2108
+ const { compiledMessage } = compiledTransaction;
2109
+ if ("addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {
2110
+ throw new Error("Cannot convert transaction with addressTableLookups");
2111
+ }
2112
+ const feePayer = compiledMessage.staticAccounts[0];
2113
+ if (!feePayer)
2114
+ throw new Error("No fee payer set in CompiledTransaction");
2115
+ const accountMetas = getAccountMetas(compiledMessage);
2116
+ const instructions = compiledMessage.instructions.map(
2117
+ (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)
2118
+ );
2119
+ const firstInstruction = instructions[0];
2120
+ const lifetimeConstraint = getLifetimeConstraint(
2121
+ compiledMessage.lifetimeToken,
2122
+ firstInstruction,
2123
+ lastValidBlockHeight
2124
+ );
2125
+ const signatures = convertSignatures(compiledTransaction);
2126
+ return pipe(
2127
+ createTransaction({ version: compiledMessage.version }),
2128
+ (tx) => setTransactionFeePayer(feePayer, tx),
2129
+ (tx) => instructions.reduce((acc, instruction) => {
2130
+ return appendTransactionInstruction(instruction, acc);
2131
+ }, tx),
2132
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
2133
+ (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx
2134
+ );
2135
+ }
2136
+ function getCompiledTransactionEncoder() {
2137
+ return getStructEncoder([
2138
+ ["signatures", getArrayEncoder(getBytesEncoder({ size: 64 }), { size: getShortU16Encoder() })],
2139
+ ["compiledMessage", getCompiledMessageEncoder()]
2140
+ ]);
2141
+ }
2142
+ function getCompiledTransactionDecoder() {
2143
+ return getStructDecoder([
631
2144
  [
632
- "value",
633
- "data",
634
- "parsed",
635
- "info",
636
- "extensions",
637
- KEYPATH_WILDCARD,
638
- "state",
639
- "newerTransferFee",
640
- "transferFeeBasisPoints"
2145
+ "signatures",
2146
+ getArrayDecoder(getBytesDecoder({ size: 64 }), {
2147
+ size: getShortU16Decoder()
2148
+ })
641
2149
  ],
642
- ["value", "data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
643
- ["value", "data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"],
644
- // parsed Token/Token22 mint account
645
- ["value", "data", "parsed", "info", "decimals"],
646
- // parsed Token/Token22 multisig account
647
- ["value", "data", "parsed", "info", "numRequiredSigners"],
648
- ["value", "data", "parsed", "info", "numValidSigners"],
649
- // parsed Stake account
650
- ["value", "data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
651
- // parsed Sysvar rent account
652
- ["value", "data", "parsed", "info", "exemptionThreshold"],
653
- ["value", "data", "parsed", "info", "burnPercent"],
654
- // parsed Vote account
655
- ["value", "data", "parsed", "info", "commission"],
656
- ["value", "data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
657
- ],
658
- getBlockTime: [[]],
659
- getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
660
- getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
661
- getTokenLargestAccounts: [
662
- ["value", KEYPATH_WILDCARD, "decimals"],
663
- ["value", KEYPATH_WILDCARD, "uiAmount"]
664
- ],
665
- getTransaction: [
666
- ["meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
667
- ["meta", "preTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
668
- ["meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
669
- ["meta", "postTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
670
- ["meta", "rewards", KEYPATH_WILDCARD, "commission"],
671
- ["meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
672
- ["meta", "innerInstructions", KEYPATH_WILDCARD, "instructions", KEYPATH_WILDCARD, "programIdIndex"],
673
- ["meta", "innerInstructions", KEYPATH_WILDCARD, "instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
674
- ["transaction", "message", "addressTableLookups", KEYPATH_WILDCARD, "writableIndexes", KEYPATH_WILDCARD],
675
- ["transaction", "message", "addressTableLookups", KEYPATH_WILDCARD, "readonlyIndexes", KEYPATH_WILDCARD],
676
- ["transaction", "message", "instructions", KEYPATH_WILDCARD, "programIdIndex"],
677
- ["transaction", "message", "instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
678
- ["transaction", "message", "header", "numReadonlySignedAccounts"],
679
- ["transaction", "message", "header", "numReadonlyUnsignedAccounts"],
680
- ["transaction", "message", "header", "numRequiredSignatures"]
681
- ],
682
- getVoteAccounts: [
683
- ["current", KEYPATH_WILDCARD, "commission"],
684
- ["delinquent", KEYPATH_WILDCARD, "commission"]
685
- ]
686
- };
687
- function getNextAllowedKeypaths(keyPaths, property) {
688
- return keyPaths.filter((keyPath) => keyPath[0] === KEYPATH_WILDCARD && typeof property === "number" || keyPath[0] === property).map((keyPath) => keyPath.slice(1));
689
- }
690
- function visitNode2(value, allowedKeypaths) {
691
- if (Array.isArray(value)) {
692
- return value.map((element, ii) => {
693
- const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, ii);
694
- return visitNode2(element, nextAllowedKeypaths);
2150
+ ["compiledMessage", getCompiledMessageDecoder()]
2151
+ ]);
2152
+ }
2153
+ function getTransactionEncoder() {
2154
+ return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
2155
+ }
2156
+ function getTransactionDecoder(lastValidBlockHeight) {
2157
+ return mapDecoder(
2158
+ getCompiledTransactionDecoder(),
2159
+ (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)
2160
+ );
2161
+ }
2162
+ function getTransactionCodec(lastValidBlockHeight) {
2163
+ return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));
2164
+ }
2165
+ var base58Decoder;
2166
+ function getSignatureFromTransaction(transaction) {
2167
+ if (!base58Decoder)
2168
+ base58Decoder = getBase58Decoder();
2169
+ const signatureBytes = transaction.signatures[transaction.feePayer];
2170
+ if (!signatureBytes) {
2171
+ throw new Error(
2172
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
2173
+ );
2174
+ }
2175
+ const transactionSignature = base58Decoder.decode(signatureBytes);
2176
+ return transactionSignature;
2177
+ }
2178
+ async function partiallySignTransaction(keyPairs, transaction) {
2179
+ const compiledMessage = compileMessage(transaction);
2180
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
2181
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
2182
+ const publicKeySignaturePairs = await Promise.all(
2183
+ keyPairs.map(
2184
+ (keyPair) => Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])
2185
+ )
2186
+ );
2187
+ for (const [signerPublicKey, signature2] of publicKeySignaturePairs) {
2188
+ nextSignatures[signerPublicKey] = signature2;
2189
+ }
2190
+ const out = {
2191
+ ...transaction,
2192
+ signatures: nextSignatures
2193
+ };
2194
+ Object.freeze(out);
2195
+ return out;
2196
+ }
2197
+ async function signTransaction(keyPairs, transaction) {
2198
+ const out = await partiallySignTransaction(keyPairs, transaction);
2199
+ assertTransactionIsFullySigned(out);
2200
+ Object.freeze(out);
2201
+ return out;
2202
+ }
2203
+ function assertTransactionIsFullySigned(transaction) {
2204
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => {
2205
+ var _a, _b;
2206
+ return (_b = (_a = i.accounts) == null ? void 0 : _a.filter((a) => isSignerRole2(a.role))) != null ? _b : [];
2207
+ }).map((a) => a.address);
2208
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
2209
+ requiredSigners.forEach((address2) => {
2210
+ if (!transaction.signatures[address2]) {
2211
+ throw new Error(`Transaction is missing signature for address \`${address2}\``);
2212
+ }
2213
+ });
2214
+ }
2215
+ function getBase64EncodedWireTransaction(transaction) {
2216
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
2217
+ return getBase64Decoder().decode(wireTransactionBytes);
2218
+ }
2219
+
2220
+ // src/airdrop.ts
2221
+ init_env_shim();
2222
+
2223
+ // src/airdrop-confirmer.ts
2224
+ init_env_shim();
2225
+
2226
+ // src/transaction-confirmation-strategy-racer.ts
2227
+ init_env_shim();
2228
+ async function raceStrategies(signature2, config, getSpecificStrategiesForRace) {
2229
+ const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;
2230
+ callerAbortSignal == null ? void 0 : callerAbortSignal.throwIfAborted();
2231
+ const abortController = new AbortController();
2232
+ if (callerAbortSignal) {
2233
+ const handleAbort = () => {
2234
+ abortController.abort();
2235
+ };
2236
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
2237
+ }
2238
+ try {
2239
+ const specificStrategies = getSpecificStrategiesForRace({
2240
+ ...config,
2241
+ abortSignal: abortController.signal
695
2242
  });
696
- } else if (typeof value === "object" && value !== null) {
697
- const out = {};
698
- for (const [propName, innerValue] of Object.entries(value)) {
699
- const nextAllowedKeypaths = getNextAllowedKeypaths(allowedKeypaths, propName);
700
- out[propName] = visitNode2(innerValue, nextAllowedKeypaths);
701
- }
702
- return out;
703
- } else if (typeof value === "number" && // The presence of an allowed keypath on the route to this value implies it's allowlisted;
704
- // Upcast the value to `bigint` unless an allowed keypath is present.
705
- allowedKeypaths.length === 0 && // Only try to upcast an Integer to `bigint`
706
- Number.isInteger(value)) {
707
- return BigInt(value);
708
- } else {
709
- return value;
2243
+ return await Promise.race([
2244
+ getRecentSignatureConfirmationPromise({
2245
+ abortSignal: abortController.signal,
2246
+ commitment,
2247
+ signature: signature2
2248
+ }),
2249
+ ...specificStrategies
2250
+ ]);
2251
+ } finally {
2252
+ abortController.abort();
710
2253
  }
711
2254
  }
712
- function patchResponseForSolanaLabsRpc(rawResponse, methodName) {
713
- const allowedKeypaths = methodName ? ALLOWED_NUMERIC_KEYPATHS[methodName] : void 0;
714
- return visitNode2(rawResponse, allowedKeypaths ?? []);
2255
+
2256
+ // src/transaction-confirmation-strategy-recent-signature.ts
2257
+ init_env_shim();
2258
+ function createRecentSignatureConfirmationPromiseFactory(rpc, rpcSubscriptions) {
2259
+ return async function getRecentSignatureConfirmationPromise({
2260
+ abortSignal: callerAbortSignal,
2261
+ commitment,
2262
+ signature: signature2
2263
+ }) {
2264
+ const abortController = new AbortController();
2265
+ function handleAbort() {
2266
+ abortController.abort();
2267
+ }
2268
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
2269
+ const signatureStatusNotifications = await rpcSubscriptions.signatureNotifications(signature2, { commitment }).subscribe({ abortSignal: abortController.signal });
2270
+ const signatureDidCommitPromise = (async () => {
2271
+ for await (const signatureStatusNotification of signatureStatusNotifications) {
2272
+ if (signatureStatusNotification.value.err) {
2273
+ throw new Error(`The transaction with signature \`${signature2}\` failed.`, {
2274
+ cause: signatureStatusNotification.value.err
2275
+ });
2276
+ } else {
2277
+ return;
2278
+ }
2279
+ }
2280
+ })();
2281
+ const signatureStatusLookupPromise = (async () => {
2282
+ const { value: signatureStatusResults } = await rpc.getSignatureStatuses([signature2]).send({ abortSignal: abortController.signal });
2283
+ const signatureStatus = signatureStatusResults[0];
2284
+ if (signatureStatus && signatureStatus.confirmationStatus && commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0) {
2285
+ return;
2286
+ } else {
2287
+ await new Promise(() => {
2288
+ });
2289
+ }
2290
+ })();
2291
+ try {
2292
+ return await Promise.race([signatureDidCommitPromise, signatureStatusLookupPromise]);
2293
+ } finally {
2294
+ abortController.abort();
2295
+ }
2296
+ };
715
2297
  }
716
- function createSolanaRpcApi(config) {
2298
+
2299
+ // src/transaction-confirmation-strategy-timeout.ts
2300
+ init_env_shim();
2301
+ async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }) {
2302
+ return await new Promise((_, reject) => {
2303
+ const handleAbort = (e3) => {
2304
+ clearTimeout(timeoutId);
2305
+ const abortError = new DOMException(e3.target.reason, "AbortError");
2306
+ reject(abortError);
2307
+ };
2308
+ callerAbortSignal.addEventListener("abort", handleAbort);
2309
+ const timeoutMs = commitment === "processed" ? 3e4 : 6e4;
2310
+ const startMs = performance.now();
2311
+ const timeoutId = (
2312
+ // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure
2313
+ // elapsed time instead of active time.
2314
+ // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
2315
+ setTimeout(() => {
2316
+ const elapsedMs = performance.now() - startMs;
2317
+ reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, "TimeoutError"));
2318
+ }, timeoutMs)
2319
+ );
2320
+ });
2321
+ }
2322
+
2323
+ // src/airdrop-confirmer.ts
2324
+ function createDefaultSignatureOnlyRecentTransactionConfirmer({
2325
+ rpc,
2326
+ rpcSubscriptions
2327
+ }) {
2328
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
2329
+ rpc,
2330
+ rpcSubscriptions
2331
+ );
2332
+ return async function confirmSignatureOnlyRecentTransaction(config) {
2333
+ await waitForRecentTransactionConfirmationUntilTimeout({
2334
+ ...config,
2335
+ getRecentSignatureConfirmationPromise,
2336
+ getTimeoutPromise
2337
+ });
2338
+ };
2339
+ }
2340
+ async function waitForRecentTransactionConfirmationUntilTimeout(config) {
2341
+ await raceStrategies(
2342
+ config.signature,
2343
+ config,
2344
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise: getTimeoutPromise2 }) {
2345
+ return [
2346
+ getTimeoutPromise2({
2347
+ abortSignal,
2348
+ commitment
2349
+ })
2350
+ ];
2351
+ }
2352
+ );
2353
+ }
2354
+
2355
+ // src/airdrop.ts
2356
+ function createDefaultAirdropRequester({ rpc, rpcSubscriptions }) {
2357
+ const confirmSignatureOnlyTransaction = createDefaultSignatureOnlyRecentTransactionConfirmer({
2358
+ rpc,
2359
+ rpcSubscriptions
2360
+ });
2361
+ return async function requestAirdrop(config) {
2362
+ return await requestAndConfirmAirdrop({
2363
+ ...config,
2364
+ confirmSignatureOnlyTransaction,
2365
+ rpc
2366
+ });
2367
+ };
2368
+ }
2369
+ async function requestAndConfirmAirdrop({
2370
+ abortSignal,
2371
+ commitment,
2372
+ confirmSignatureOnlyTransaction,
2373
+ lamports: lamports2,
2374
+ recipientAddress,
2375
+ rpc
2376
+ }) {
2377
+ const airdropTransactionSignature = await rpc.requestAirdrop(recipientAddress, lamports2, { commitment }).send({ abortSignal });
2378
+ await confirmSignatureOnlyTransaction({
2379
+ abortSignal,
2380
+ commitment,
2381
+ signature: airdropTransactionSignature
2382
+ });
2383
+ return airdropTransactionSignature;
2384
+ }
2385
+
2386
+ // src/rpc.ts
2387
+ init_env_shim();
2388
+
2389
+ // ../rpc-core/dist/index.browser.js
2390
+ init_env_shim();
2391
+ function createJsonRpcApi(config) {
717
2392
  return new Proxy({}, {
718
2393
  defineProperty() {
719
2394
  return false;
@@ -725,26 +2400,667 @@ this.globalThis.solanaWeb3 = (function (exports) {
725
2400
  const [_, p] = args;
726
2401
  const methodName = p.toString();
727
2402
  return function(...rawParams) {
728
- const handleIntegerOverflow = config?.onIntegerOverflow;
729
- const params = patchParamsForSolanaLabsRpc(
730
- rawParams,
731
- handleIntegerOverflow ? (keyPath, value) => handleIntegerOverflow(methodName, keyPath, value) : void 0
732
- );
2403
+ const params = (config == null ? void 0 : config.parametersTransformer) ? config == null ? void 0 : config.parametersTransformer(rawParams, methodName) : rawParams;
2404
+ const responseTransformer = (config == null ? void 0 : config.responseTransformer) ? config == null ? void 0 : config.responseTransformer : (rawResponse) => rawResponse;
733
2405
  return {
734
2406
  methodName,
735
2407
  params,
736
- responseProcessor: (rawResponse) => patchResponseForSolanaLabsRpc(rawResponse, methodName)
2408
+ responseTransformer
2409
+ };
2410
+ };
2411
+ }
2412
+ });
2413
+ }
2414
+ function createJsonRpcSubscriptionsApi(config) {
2415
+ return new Proxy({}, {
2416
+ defineProperty() {
2417
+ return false;
2418
+ },
2419
+ deleteProperty() {
2420
+ return false;
2421
+ },
2422
+ get(...args) {
2423
+ const [_, p] = args;
2424
+ const notificationName = p.toString();
2425
+ return function(...rawParams) {
2426
+ const params = (config == null ? void 0 : config.parametersTransformer) ? config == null ? void 0 : config.parametersTransformer(rawParams, notificationName) : rawParams;
2427
+ const responseTransformer = (config == null ? void 0 : config.responseTransformer) ? config == null ? void 0 : config.responseTransformer : (rawResponse) => rawResponse;
2428
+ const subscribeMethodName = (config == null ? void 0 : config.subscribeNotificationNameTransformer) ? config == null ? void 0 : config.subscribeNotificationNameTransformer(notificationName) : notificationName;
2429
+ const unsubscribeMethodName = (config == null ? void 0 : config.unsubscribeNotificationNameTransformer) ? config == null ? void 0 : config.unsubscribeNotificationNameTransformer(notificationName) : notificationName;
2430
+ return {
2431
+ params,
2432
+ responseTransformer,
2433
+ subscribeMethodName,
2434
+ unsubscribeMethodName
737
2435
  };
738
2436
  };
739
2437
  }
740
2438
  });
741
2439
  }
2440
+ function applyDefaultCommitment({
2441
+ commitmentPropertyName,
2442
+ params,
2443
+ optionsObjectPositionInParams,
2444
+ overrideCommitment
2445
+ }) {
2446
+ const paramInTargetPosition = params[optionsObjectPositionInParams];
2447
+ if (
2448
+ // There's no config.
2449
+ paramInTargetPosition === void 0 || // There is a config object.
2450
+ paramInTargetPosition && typeof paramInTargetPosition === "object" && !Array.isArray(paramInTargetPosition)
2451
+ ) {
2452
+ if (
2453
+ // The config object already has a commitment set.
2454
+ paramInTargetPosition && commitmentPropertyName in paramInTargetPosition
2455
+ ) {
2456
+ if (!paramInTargetPosition[commitmentPropertyName] || paramInTargetPosition[commitmentPropertyName] === "finalized") {
2457
+ const nextParams = [...params];
2458
+ const {
2459
+ [commitmentPropertyName]: _,
2460
+ // eslint-disable-line @typescript-eslint/no-unused-vars
2461
+ ...rest
2462
+ } = paramInTargetPosition;
2463
+ if (Object.keys(rest).length > 0) {
2464
+ nextParams[optionsObjectPositionInParams] = rest;
2465
+ } else {
2466
+ if (optionsObjectPositionInParams === nextParams.length - 1) {
2467
+ nextParams.length--;
2468
+ } else {
2469
+ nextParams[optionsObjectPositionInParams] = void 0;
2470
+ }
2471
+ }
2472
+ return nextParams;
2473
+ }
2474
+ } else if (overrideCommitment !== "finalized") {
2475
+ const nextParams = [...params];
2476
+ nextParams[optionsObjectPositionInParams] = {
2477
+ ...paramInTargetPosition,
2478
+ [commitmentPropertyName]: overrideCommitment
2479
+ };
2480
+ return nextParams;
2481
+ }
2482
+ }
2483
+ return params;
2484
+ }
2485
+ function downcastNodeToNumberIfBigint(value) {
2486
+ return typeof value === "bigint" ? (
2487
+ // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana
2488
+ // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely
2489
+ // downcasting `bigints` to `numbers`.
2490
+ Number(value)
2491
+ ) : value;
2492
+ }
2493
+ function getIntegerOverflowNodeVisitor(onIntegerOverflow) {
2494
+ return (value, { keyPath }) => {
2495
+ if (typeof value === "bigint") {
2496
+ if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {
2497
+ onIntegerOverflow(keyPath, value);
2498
+ }
2499
+ }
2500
+ return value;
2501
+ };
2502
+ }
2503
+ var OPTIONS_OBJECT_POSITION_BY_METHOD = {
2504
+ accountNotifications: 1,
2505
+ blockNotifications: 1,
2506
+ getAccountInfo: 1,
2507
+ getBalance: 1,
2508
+ getBlock: 1,
2509
+ getBlockHeight: 0,
2510
+ getBlockProduction: 0,
2511
+ getBlocks: 2,
2512
+ getBlocksWithLimit: 2,
2513
+ getConfirmedBlock: 1,
2514
+ getConfirmedBlocks: 1,
2515
+ getConfirmedBlocksWithLimit: 2,
2516
+ getConfirmedSignaturesForAddress2: 1,
2517
+ getConfirmedTransaction: 1,
2518
+ getEpochInfo: 0,
2519
+ getFeeCalculatorForBlockhash: 1,
2520
+ getFeeForMessage: 1,
2521
+ getFees: 1,
2522
+ getInflationGovernor: 0,
2523
+ getInflationReward: 1,
2524
+ getLargestAccounts: 0,
2525
+ getLatestBlockhash: 0,
2526
+ getLeaderSchedule: 1,
2527
+ getMinimumBalanceForRentExemption: 1,
2528
+ getMultipleAccounts: 1,
2529
+ getProgramAccounts: 1,
2530
+ getRecentBlockhash: 1,
2531
+ getSignaturesForAddress: 1,
2532
+ getSlot: 0,
2533
+ getSlotLeader: 0,
2534
+ getStakeActivation: 1,
2535
+ getStakeMinimumDelegation: 0,
2536
+ getSupply: 0,
2537
+ getTokenAccountBalance: 1,
2538
+ getTokenAccountsByDelegate: 2,
2539
+ getTokenAccountsByOwner: 2,
2540
+ getTokenLargestAccounts: 1,
2541
+ getTokenSupply: 1,
2542
+ getTransaction: 1,
2543
+ getTransactionCount: 0,
2544
+ getVoteAccounts: 0,
2545
+ isBlockhashValid: 1,
2546
+ logsNotifications: 1,
2547
+ programNotifications: 1,
2548
+ requestAirdrop: 2,
2549
+ sendTransaction: 1,
2550
+ signatureNotifications: 1,
2551
+ simulateTransaction: 1
2552
+ };
2553
+ var KEYPATH_WILDCARD = {};
2554
+ function getTreeWalker(visitors) {
2555
+ return function traverse(node, state) {
2556
+ if (Array.isArray(node)) {
2557
+ return node.map((element, ii) => {
2558
+ const nextState = {
2559
+ ...state,
2560
+ keyPath: [...state.keyPath, ii]
2561
+ };
2562
+ return traverse(element, nextState);
2563
+ });
2564
+ } else if (typeof node === "object" && node !== null) {
2565
+ const out = {};
2566
+ for (const propName in node) {
2567
+ if (!Object.prototype.hasOwnProperty.call(node, propName)) {
2568
+ continue;
2569
+ }
2570
+ const nextState = {
2571
+ ...state,
2572
+ keyPath: [...state.keyPath, propName]
2573
+ };
2574
+ out[propName] = traverse(node[propName], nextState);
2575
+ }
2576
+ return out;
2577
+ } else {
2578
+ return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);
2579
+ }
2580
+ };
2581
+ }
2582
+ function getParamsPatcherForSolanaLabsRpc(config) {
2583
+ const defaultCommitment = config == null ? void 0 : config.defaultCommitment;
2584
+ const handleIntegerOverflow = config == null ? void 0 : config.onIntegerOverflow;
2585
+ return (rawParams, methodName) => {
2586
+ const traverse = getTreeWalker([
2587
+ ...handleIntegerOverflow ? [getIntegerOverflowNodeVisitor((...args) => handleIntegerOverflow(methodName, ...args))] : [],
2588
+ downcastNodeToNumberIfBigint
2589
+ ]);
2590
+ const initialState = {
2591
+ keyPath: []
2592
+ };
2593
+ const patchedParams = traverse(rawParams, initialState);
2594
+ if (!Array.isArray(patchedParams)) {
2595
+ return patchedParams;
2596
+ }
2597
+ const optionsObjectPositionInParams = OPTIONS_OBJECT_POSITION_BY_METHOD[methodName];
2598
+ if (optionsObjectPositionInParams == null) {
2599
+ return patchedParams;
2600
+ }
2601
+ return applyDefaultCommitment({
2602
+ commitmentPropertyName: methodName === "sendTransaction" ? "preflightCommitment" : "commitment",
2603
+ optionsObjectPositionInParams,
2604
+ overrideCommitment: defaultCommitment,
2605
+ params: patchedParams
2606
+ });
2607
+ };
2608
+ }
2609
+ var jsonParsedTokenAccountsConfigs = [
2610
+ // parsed Token/Token22 token account
2611
+ ["data", "parsed", "info", "tokenAmount", "decimals"],
2612
+ ["data", "parsed", "info", "tokenAmount", "uiAmount"],
2613
+ ["data", "parsed", "info", "rentExemptReserve", "decimals"],
2614
+ ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
2615
+ ["data", "parsed", "info", "delegatedAmount", "decimals"],
2616
+ ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
2617
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "olderTransferFee", "transferFeeBasisPoints"],
2618
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "newerTransferFee", "transferFeeBasisPoints"],
2619
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
2620
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
2621
+ ];
2622
+ var jsonParsedAccountsConfigs = [
2623
+ ...jsonParsedTokenAccountsConfigs,
2624
+ // parsed AddressTableLookup account
2625
+ ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
2626
+ // parsed Config account
2627
+ ["data", "parsed", "info", "slashPenalty"],
2628
+ ["data", "parsed", "info", "warmupCooldownRate"],
2629
+ // parsed Token/Token22 mint account
2630
+ ["data", "parsed", "info", "decimals"],
2631
+ // parsed Token/Token22 multisig account
2632
+ ["data", "parsed", "info", "numRequiredSigners"],
2633
+ ["data", "parsed", "info", "numValidSigners"],
2634
+ // parsed Stake account
2635
+ ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
2636
+ // parsed Sysvar rent account
2637
+ ["data", "parsed", "info", "exemptionThreshold"],
2638
+ ["data", "parsed", "info", "burnPercent"],
2639
+ // parsed Vote account
2640
+ ["data", "parsed", "info", "commission"],
2641
+ ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
2642
+ ];
2643
+ var memoizedNotificationKeypaths;
2644
+ var memoizedResponseKeypaths;
2645
+ function getAllowedNumericKeypathsForNotification() {
2646
+ if (!memoizedNotificationKeypaths) {
2647
+ memoizedNotificationKeypaths = {
2648
+ accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
2649
+ blockNotifications: [
2650
+ ["value", "block", "blockTime"],
2651
+ [
2652
+ "value",
2653
+ "block",
2654
+ "transactions",
2655
+ KEYPATH_WILDCARD,
2656
+ "meta",
2657
+ "preTokenBalances",
2658
+ KEYPATH_WILDCARD,
2659
+ "accountIndex"
2660
+ ],
2661
+ [
2662
+ "value",
2663
+ "block",
2664
+ "transactions",
2665
+ KEYPATH_WILDCARD,
2666
+ "meta",
2667
+ "preTokenBalances",
2668
+ KEYPATH_WILDCARD,
2669
+ "uiTokenAmount",
2670
+ "decimals"
2671
+ ],
2672
+ [
2673
+ "value",
2674
+ "block",
2675
+ "transactions",
2676
+ KEYPATH_WILDCARD,
2677
+ "meta",
2678
+ "postTokenBalances",
2679
+ KEYPATH_WILDCARD,
2680
+ "accountIndex"
2681
+ ],
2682
+ [
2683
+ "value",
2684
+ "block",
2685
+ "transactions",
2686
+ KEYPATH_WILDCARD,
2687
+ "meta",
2688
+ "postTokenBalances",
2689
+ KEYPATH_WILDCARD,
2690
+ "uiTokenAmount",
2691
+ "decimals"
2692
+ ],
2693
+ ["value", "block", "transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2694
+ [
2695
+ "value",
2696
+ "block",
2697
+ "transactions",
2698
+ KEYPATH_WILDCARD,
2699
+ "meta",
2700
+ "innerInstructions",
2701
+ KEYPATH_WILDCARD,
2702
+ "index"
2703
+ ],
2704
+ [
2705
+ "value",
2706
+ "block",
2707
+ "transactions",
2708
+ KEYPATH_WILDCARD,
2709
+ "meta",
2710
+ "innerInstructions",
2711
+ KEYPATH_WILDCARD,
2712
+ "instructions",
2713
+ KEYPATH_WILDCARD,
2714
+ "programIdIndex"
2715
+ ],
2716
+ [
2717
+ "value",
2718
+ "block",
2719
+ "transactions",
2720
+ KEYPATH_WILDCARD,
2721
+ "meta",
2722
+ "innerInstructions",
2723
+ KEYPATH_WILDCARD,
2724
+ "instructions",
2725
+ KEYPATH_WILDCARD,
2726
+ "accounts",
2727
+ KEYPATH_WILDCARD
2728
+ ],
2729
+ [
2730
+ "value",
2731
+ "block",
2732
+ "transactions",
2733
+ KEYPATH_WILDCARD,
2734
+ "transaction",
2735
+ "message",
2736
+ "addressTableLookups",
2737
+ KEYPATH_WILDCARD,
2738
+ "writableIndexes",
2739
+ KEYPATH_WILDCARD
2740
+ ],
2741
+ [
2742
+ "value",
2743
+ "block",
2744
+ "transactions",
2745
+ KEYPATH_WILDCARD,
2746
+ "transaction",
2747
+ "message",
2748
+ "addressTableLookups",
2749
+ KEYPATH_WILDCARD,
2750
+ "readonlyIndexes",
2751
+ KEYPATH_WILDCARD
2752
+ ],
2753
+ [
2754
+ "value",
2755
+ "block",
2756
+ "transactions",
2757
+ KEYPATH_WILDCARD,
2758
+ "transaction",
2759
+ "message",
2760
+ "instructions",
2761
+ KEYPATH_WILDCARD,
2762
+ "programIdIndex"
2763
+ ],
2764
+ [
2765
+ "value",
2766
+ "block",
2767
+ "transactions",
2768
+ KEYPATH_WILDCARD,
2769
+ "transaction",
2770
+ "message",
2771
+ "instructions",
2772
+ KEYPATH_WILDCARD,
2773
+ "accounts",
2774
+ KEYPATH_WILDCARD
2775
+ ],
2776
+ [
2777
+ "value",
2778
+ "block",
2779
+ "transactions",
2780
+ KEYPATH_WILDCARD,
2781
+ "transaction",
2782
+ "message",
2783
+ "header",
2784
+ "numReadonlySignedAccounts"
2785
+ ],
2786
+ [
2787
+ "value",
2788
+ "block",
2789
+ "transactions",
2790
+ KEYPATH_WILDCARD,
2791
+ "transaction",
2792
+ "message",
2793
+ "header",
2794
+ "numReadonlyUnsignedAccounts"
2795
+ ],
2796
+ [
2797
+ "value",
2798
+ "block",
2799
+ "transactions",
2800
+ KEYPATH_WILDCARD,
2801
+ "transaction",
2802
+ "message",
2803
+ "header",
2804
+ "numRequiredSignatures"
2805
+ ],
2806
+ ["value", "block", "rewards", KEYPATH_WILDCARD, "commission"]
2807
+ ],
2808
+ programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [
2809
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2810
+ [KEYPATH_WILDCARD, "account", ...c]
2811
+ ])
2812
+ };
2813
+ }
2814
+ return memoizedNotificationKeypaths;
2815
+ }
2816
+ function getAllowedNumericKeypathsForResponse() {
2817
+ if (!memoizedResponseKeypaths) {
2818
+ memoizedResponseKeypaths = {
2819
+ getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
2820
+ getBlock: [
2821
+ ["blockTime"],
2822
+ ["transactions", KEYPATH_WILDCARD, "meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2823
+ [
2824
+ "transactions",
2825
+ KEYPATH_WILDCARD,
2826
+ "meta",
2827
+ "preTokenBalances",
2828
+ KEYPATH_WILDCARD,
2829
+ "uiTokenAmount",
2830
+ "decimals"
2831
+ ],
2832
+ ["transactions", KEYPATH_WILDCARD, "meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2833
+ [
2834
+ "transactions",
2835
+ KEYPATH_WILDCARD,
2836
+ "meta",
2837
+ "postTokenBalances",
2838
+ KEYPATH_WILDCARD,
2839
+ "uiTokenAmount",
2840
+ "decimals"
2841
+ ],
2842
+ ["transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2843
+ ["transactions", KEYPATH_WILDCARD, "meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
2844
+ [
2845
+ "transactions",
2846
+ KEYPATH_WILDCARD,
2847
+ "meta",
2848
+ "innerInstructions",
2849
+ KEYPATH_WILDCARD,
2850
+ "instructions",
2851
+ KEYPATH_WILDCARD,
2852
+ "programIdIndex"
2853
+ ],
2854
+ [
2855
+ "transactions",
2856
+ KEYPATH_WILDCARD,
2857
+ "meta",
2858
+ "innerInstructions",
2859
+ KEYPATH_WILDCARD,
2860
+ "instructions",
2861
+ KEYPATH_WILDCARD,
2862
+ "accounts",
2863
+ KEYPATH_WILDCARD
2864
+ ],
2865
+ [
2866
+ "transactions",
2867
+ KEYPATH_WILDCARD,
2868
+ "transaction",
2869
+ "message",
2870
+ "addressTableLookups",
2871
+ KEYPATH_WILDCARD,
2872
+ "writableIndexes",
2873
+ KEYPATH_WILDCARD
2874
+ ],
2875
+ [
2876
+ "transactions",
2877
+ KEYPATH_WILDCARD,
2878
+ "transaction",
2879
+ "message",
2880
+ "addressTableLookups",
2881
+ KEYPATH_WILDCARD,
2882
+ "readonlyIndexes",
2883
+ KEYPATH_WILDCARD
2884
+ ],
2885
+ [
2886
+ "transactions",
2887
+ KEYPATH_WILDCARD,
2888
+ "transaction",
2889
+ "message",
2890
+ "instructions",
2891
+ KEYPATH_WILDCARD,
2892
+ "programIdIndex"
2893
+ ],
2894
+ [
2895
+ "transactions",
2896
+ KEYPATH_WILDCARD,
2897
+ "transaction",
2898
+ "message",
2899
+ "instructions",
2900
+ KEYPATH_WILDCARD,
2901
+ "accounts",
2902
+ KEYPATH_WILDCARD
2903
+ ],
2904
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numReadonlySignedAccounts"],
2905
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numReadonlyUnsignedAccounts"],
2906
+ ["transactions", KEYPATH_WILDCARD, "transaction", "message", "header", "numRequiredSignatures"],
2907
+ ["rewards", KEYPATH_WILDCARD, "commission"]
2908
+ ],
2909
+ getBlockTime: [[]],
2910
+ getClusterNodes: [
2911
+ [KEYPATH_WILDCARD, "featureSet"],
2912
+ [KEYPATH_WILDCARD, "shredVersion"]
2913
+ ],
2914
+ getInflationGovernor: [["initial"], ["foundation"], ["foundationTerm"], ["taper"], ["terminal"]],
2915
+ getInflationRate: [["foundation"], ["total"], ["validator"]],
2916
+ getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
2917
+ getMultipleAccounts: jsonParsedAccountsConfigs.map((c) => ["value", KEYPATH_WILDCARD, ...c]),
2918
+ getProgramAccounts: jsonParsedAccountsConfigs.flatMap((c) => [
2919
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2920
+ [KEYPATH_WILDCARD, "account", ...c]
2921
+ ]),
2922
+ getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
2923
+ getTokenAccountBalance: [
2924
+ ["value", "decimals"],
2925
+ ["value", "uiAmount"]
2926
+ ],
2927
+ getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map((c) => [
2928
+ "value",
2929
+ KEYPATH_WILDCARD,
2930
+ "account",
2931
+ ...c
2932
+ ]),
2933
+ getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map((c) => [
2934
+ "value",
2935
+ KEYPATH_WILDCARD,
2936
+ "account",
2937
+ ...c
2938
+ ]),
2939
+ getTokenLargestAccounts: [
2940
+ ["value", KEYPATH_WILDCARD, "decimals"],
2941
+ ["value", KEYPATH_WILDCARD, "uiAmount"]
2942
+ ],
2943
+ getTokenSupply: [
2944
+ ["value", "decimals"],
2945
+ ["value", "uiAmount"]
2946
+ ],
2947
+ getTransaction: [
2948
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2949
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
2950
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
2951
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
2952
+ ["meta", "rewards", KEYPATH_WILDCARD, "commission"],
2953
+ ["meta", "innerInstructions", KEYPATH_WILDCARD, "index"],
2954
+ ["meta", "innerInstructions", KEYPATH_WILDCARD, "instructions", KEYPATH_WILDCARD, "programIdIndex"],
2955
+ [
2956
+ "meta",
2957
+ "innerInstructions",
2958
+ KEYPATH_WILDCARD,
2959
+ "instructions",
2960
+ KEYPATH_WILDCARD,
2961
+ "accounts",
2962
+ KEYPATH_WILDCARD
2963
+ ],
2964
+ [
2965
+ "transaction",
2966
+ "message",
2967
+ "addressTableLookups",
2968
+ KEYPATH_WILDCARD,
2969
+ "writableIndexes",
2970
+ KEYPATH_WILDCARD
2971
+ ],
2972
+ [
2973
+ "transaction",
2974
+ "message",
2975
+ "addressTableLookups",
2976
+ KEYPATH_WILDCARD,
2977
+ "readonlyIndexes",
2978
+ KEYPATH_WILDCARD
2979
+ ],
2980
+ ["transaction", "message", "instructions", KEYPATH_WILDCARD, "programIdIndex"],
2981
+ ["transaction", "message", "instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
2982
+ ["transaction", "message", "header", "numReadonlySignedAccounts"],
2983
+ ["transaction", "message", "header", "numReadonlyUnsignedAccounts"],
2984
+ ["transaction", "message", "header", "numRequiredSignatures"]
2985
+ ],
2986
+ getVersion: [["feature-set"]],
2987
+ getVoteAccounts: [
2988
+ ["current", KEYPATH_WILDCARD, "commission"],
2989
+ ["delinquent", KEYPATH_WILDCARD, "commission"]
2990
+ ],
2991
+ simulateTransaction: jsonParsedAccountsConfigs.map((c) => ["value", "accounts", KEYPATH_WILDCARD, ...c])
2992
+ };
2993
+ }
2994
+ return memoizedResponseKeypaths;
2995
+ }
2996
+ function keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths) {
2997
+ return allowedNumericKeyPaths.some((prohibitedKeyPath) => {
2998
+ if (prohibitedKeyPath.length !== keyPath.length) {
2999
+ return false;
3000
+ }
3001
+ for (let ii = keyPath.length - 1; ii >= 0; ii--) {
3002
+ const keyPathPart = keyPath[ii];
3003
+ const prohibitedKeyPathPart = prohibitedKeyPath[ii];
3004
+ if (prohibitedKeyPathPart !== keyPathPart && (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== "number")) {
3005
+ return false;
3006
+ }
3007
+ }
3008
+ return true;
3009
+ });
3010
+ }
3011
+ function getBigIntUpcastVisitor(allowedNumericKeyPaths) {
3012
+ return function upcastNodeToBigIntIfNumber(value, { keyPath }) {
3013
+ if (typeof value === "number" && Number.isInteger(value) && !keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {
3014
+ return BigInt(value);
3015
+ } else {
3016
+ return value;
3017
+ }
3018
+ };
3019
+ }
3020
+ function patchResponseForSolanaLabsRpc(rawResponse, methodName) {
3021
+ const allowedNumericKeyPaths = methodName ? getAllowedNumericKeypathsForResponse()[methodName] : void 0;
3022
+ const traverse = getTreeWalker([getBigIntUpcastVisitor(allowedNumericKeyPaths != null ? allowedNumericKeyPaths : [])]);
3023
+ const initialState = {
3024
+ keyPath: []
3025
+ };
3026
+ return traverse(rawResponse, initialState);
3027
+ }
3028
+ function patchResponseForSolanaLabsRpcSubscriptions(rawResponse, notificationName) {
3029
+ const allowedNumericKeyPaths = notificationName ? getAllowedNumericKeypathsForNotification()[notificationName] : void 0;
3030
+ const traverse = getTreeWalker([getBigIntUpcastVisitor(allowedNumericKeyPaths != null ? allowedNumericKeyPaths : [])]);
3031
+ const initialState = {
3032
+ keyPath: []
3033
+ };
3034
+ return traverse(rawResponse, initialState);
3035
+ }
3036
+ function createSolanaRpcApi(config) {
3037
+ return createJsonRpcApi({
3038
+ parametersTransformer: getParamsPatcherForSolanaLabsRpc(config),
3039
+ responseTransformer: patchResponseForSolanaLabsRpc
3040
+ });
3041
+ }
3042
+ function createSolanaRpcSubscriptionsApi_INTERNAL(config) {
3043
+ return createJsonRpcSubscriptionsApi({
3044
+ parametersTransformer: getParamsPatcherForSolanaLabsRpc(config),
3045
+ responseTransformer: patchResponseForSolanaLabsRpcSubscriptions,
3046
+ subscribeNotificationNameTransformer: (notificationName) => notificationName.replace(/Notifications$/, "Subscribe"),
3047
+ unsubscribeNotificationNameTransformer: (notificationName) => notificationName.replace(/Notifications$/, "Unsubscribe")
3048
+ });
3049
+ }
3050
+ function createSolanaRpcSubscriptionsApi(config) {
3051
+ return createSolanaRpcSubscriptionsApi_INTERNAL(config);
3052
+ }
3053
+ function createSolanaRpcSubscriptionsApi_UNSTABLE(config) {
3054
+ return createSolanaRpcSubscriptionsApi_INTERNAL(config);
3055
+ }
742
3056
 
743
3057
  // ../rpc-transport/dist/index.browser.js
744
3058
  init_env_shim();
745
3059
  var SolanaJsonRpcError = class extends Error {
746
3060
  constructor(details) {
747
3061
  super(`JSON-RPC 2.0 error (${details.code}): ${details.message}`);
3062
+ __publicField(this, "code");
3063
+ __publicField(this, "data");
748
3064
  Error.captureStackTrace(this, this.constructor);
749
3065
  this.code = details.code;
750
3066
  this.data = details.data;
@@ -770,16 +3086,16 @@ this.globalThis.solanaWeb3 = (function (exports) {
770
3086
  function createPendingRpcRequest(rpcConfig, pendingRequest) {
771
3087
  return {
772
3088
  async send(options) {
773
- const { methodName, params, responseProcessor } = pendingRequest;
3089
+ const { methodName, params, responseTransformer } = pendingRequest;
774
3090
  const payload = createJsonRpcMessage(methodName, params);
775
3091
  const response = await rpcConfig.transport({
776
3092
  payload,
777
- signal: options?.abortSignal
3093
+ signal: options == null ? void 0 : options.abortSignal
778
3094
  });
779
3095
  if ("error" in response) {
780
3096
  throw new SolanaJsonRpcError(response.error);
781
3097
  } else {
782
- return responseProcessor ? responseProcessor(response.result) : response.result;
3098
+ return responseTransformer ? responseTransformer(response.result, methodName) : response.result;
783
3099
  }
784
3100
  }
785
3101
  };
@@ -805,10 +3121,105 @@ this.globalThis.solanaWeb3 = (function (exports) {
805
3121
  function createJsonRpc(rpcConfig) {
806
3122
  return makeProxy(rpcConfig);
807
3123
  }
808
- var e = globalThis.fetch;
3124
+ function registerIterableCleanup(iterable, cleanupFn) {
3125
+ (async () => {
3126
+ try {
3127
+ for await (const _ of iterable)
3128
+ ;
3129
+ } catch {
3130
+ } finally {
3131
+ cleanupFn();
3132
+ }
3133
+ })();
3134
+ }
3135
+ function createPendingRpcSubscription(rpcConfig, { params, subscribeMethodName, unsubscribeMethodName, responseTransformer }) {
3136
+ return {
3137
+ async subscribe({ abortSignal }) {
3138
+ abortSignal.throwIfAborted();
3139
+ let subscriptionId;
3140
+ function handleCleanup() {
3141
+ if (subscriptionId !== void 0) {
3142
+ const payload = createJsonRpcMessage(unsubscribeMethodName, [subscriptionId]);
3143
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload).finally(() => {
3144
+ connectionAbortController.abort();
3145
+ });
3146
+ } else {
3147
+ connectionAbortController.abort();
3148
+ }
3149
+ }
3150
+ abortSignal.addEventListener("abort", handleCleanup);
3151
+ const connectionAbortController = new AbortController();
3152
+ const subscribeMessage = createJsonRpcMessage(subscribeMethodName, params);
3153
+ const connection = await rpcConfig.transport({
3154
+ payload: subscribeMessage,
3155
+ signal: connectionAbortController.signal
3156
+ });
3157
+ function handleConnectionCleanup() {
3158
+ abortSignal.removeEventListener("abort", handleCleanup);
3159
+ }
3160
+ registerIterableCleanup(connection, handleConnectionCleanup);
3161
+ for await (const message of connection) {
3162
+ if ("id" in message && message.id === subscribeMessage.id) {
3163
+ if ("error" in message) {
3164
+ throw new SolanaJsonRpcError(message.error);
3165
+ } else {
3166
+ subscriptionId = message.result;
3167
+ break;
3168
+ }
3169
+ }
3170
+ }
3171
+ if (subscriptionId == null) {
3172
+ throw new Error("Failed to obtain a subscription id from the server");
3173
+ }
3174
+ return {
3175
+ async *[Symbol.asyncIterator]() {
3176
+ for await (const message of connection) {
3177
+ if (!("params" in message) || message.params.subscription !== subscriptionId) {
3178
+ continue;
3179
+ }
3180
+ const notification = message.params.result;
3181
+ yield responseTransformer ? responseTransformer(notification, subscribeMethodName) : notification;
3182
+ }
3183
+ }
3184
+ };
3185
+ }
3186
+ };
3187
+ }
3188
+ function makeProxy2(rpcConfig) {
3189
+ return new Proxy(rpcConfig.api, {
3190
+ defineProperty() {
3191
+ return false;
3192
+ },
3193
+ deleteProperty() {
3194
+ return false;
3195
+ },
3196
+ get(target, p, receiver) {
3197
+ return function(...rawParams) {
3198
+ const methodName = p.toString();
3199
+ const createRpcSubscription = Reflect.get(target, methodName, receiver);
3200
+ if (p.toString().endsWith("Notifications") === false && !createRpcSubscription) {
3201
+ throw new Error(
3202
+ "Either the notification name must end in 'Notifications' or the API must supply a subscription creator function to map between the notification name and the subscribe/unsubscribe method names."
3203
+ );
3204
+ }
3205
+ const newRequest = createRpcSubscription ? createRpcSubscription(...rawParams) : {
3206
+ params: rawParams,
3207
+ subscribeMethodName: methodName.replace(/Notifications$/, "Subscribe"),
3208
+ unsubscribeMethodName: methodName.replace(/Notifications$/, "Unsubscribe")
3209
+ };
3210
+ return createPendingRpcSubscription(rpcConfig, newRequest);
3211
+ };
3212
+ }
3213
+ });
3214
+ }
3215
+ function createJsonSubscriptionRpc(rpcConfig) {
3216
+ return makeProxy2(rpcConfig);
3217
+ }
3218
+ var e2 = globalThis.fetch;
809
3219
  var SolanaHttpError = class extends Error {
810
3220
  constructor(details) {
811
3221
  super(`HTTP error (${details.statusCode}): ${details.message}`);
3222
+ __publicField(this, "statusCode");
812
3223
  Error.captureStackTrace(this, this.constructor);
813
3224
  this.statusCode = details.statusCode;
814
3225
  }
@@ -864,16 +3275,10 @@ this.globalThis.solanaWeb3 = (function (exports) {
864
3275
  }
865
3276
  return out;
866
3277
  }
867
- function createHttpTransport({ httpAgentNodeOnly, headers, url }) {
3278
+ function createHttpTransport({ headers, url }) {
868
3279
  if (headers) {
869
3280
  assertIsAllowedHttpRequestHeaders(headers);
870
3281
  }
871
- const agent = void 0;
872
- if (httpAgentNodeOnly != null) {
873
- console.warn(
874
- "createHttpTransport(): The `httpAgentNodeOnly` config you supplied has been ignored; HTTP agents are only usable in Node environments."
875
- );
876
- }
877
3282
  const customHeaders = headers && normalizeHeaders(headers);
878
3283
  return async function makeHttpRequest({
879
3284
  payload,
@@ -881,7 +3286,6 @@ this.globalThis.solanaWeb3 = (function (exports) {
881
3286
  }) {
882
3287
  const body = JSON.stringify(payload);
883
3288
  const requestInfo = {
884
- agent,
885
3289
  body,
886
3290
  headers: {
887
3291
  ...customHeaders,
@@ -893,7 +3297,7 @@ this.globalThis.solanaWeb3 = (function (exports) {
893
3297
  method: "POST",
894
3298
  signal
895
3299
  };
896
- const response = await e(url, requestInfo);
3300
+ const response = await e2(url, requestInfo);
897
3301
  if (!response.ok) {
898
3302
  throw new SolanaHttpError({
899
3303
  message: response.statusText,
@@ -903,6 +3307,175 @@ this.globalThis.solanaWeb3 = (function (exports) {
903
3307
  return await response.json();
904
3308
  };
905
3309
  }
3310
+ var e22 = globalThis.WebSocket;
3311
+ var EXPLICIT_ABORT_TOKEN = Symbol(
3312
+ "This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user"
3313
+ );
3314
+ async function createWebSocketConnection({
3315
+ sendBufferHighWatermark,
3316
+ signal,
3317
+ url
3318
+ }) {
3319
+ return new Promise((resolve, reject) => {
3320
+ signal.addEventListener("abort", handleAbort, { once: true });
3321
+ const iteratorState = /* @__PURE__ */ new Map();
3322
+ function errorAndClearAllIteratorStates(reason) {
3323
+ const errorCallbacks = [...iteratorState.values()].filter((state) => state.__hasPolled).map(({ onError }) => onError);
3324
+ iteratorState.clear();
3325
+ errorCallbacks.forEach((cb) => {
3326
+ try {
3327
+ cb(reason);
3328
+ } catch {
3329
+ }
3330
+ });
3331
+ }
3332
+ function handleAbort() {
3333
+ errorAndClearAllIteratorStates(EXPLICIT_ABORT_TOKEN);
3334
+ if (webSocket.readyState !== e22.CLOSED && webSocket.readyState !== e22.CLOSING) {
3335
+ webSocket.close(1e3);
3336
+ }
3337
+ }
3338
+ function handleClose(ev) {
3339
+ bufferDrainWatcher == null ? void 0 : bufferDrainWatcher.onCancel();
3340
+ signal.removeEventListener("abort", handleAbort);
3341
+ webSocket.removeEventListener("close", handleClose);
3342
+ webSocket.removeEventListener("error", handleError);
3343
+ webSocket.removeEventListener("open", handleOpen);
3344
+ webSocket.removeEventListener("message", handleMessage);
3345
+ errorAndClearAllIteratorStates(ev);
3346
+ }
3347
+ function handleError(ev) {
3348
+ if (!hasConnected) {
3349
+ reject(
3350
+ // TODO: Coded error
3351
+ new Error("WebSocket failed to connect", { cause: ev })
3352
+ );
3353
+ }
3354
+ }
3355
+ let hasConnected = false;
3356
+ let bufferDrainWatcher;
3357
+ function handleOpen() {
3358
+ hasConnected = true;
3359
+ resolve({
3360
+ async send(payload) {
3361
+ const message = JSON.stringify(payload);
3362
+ if (!bufferDrainWatcher && webSocket.readyState === e22.OPEN && webSocket.bufferedAmount > sendBufferHighWatermark) {
3363
+ let onCancel;
3364
+ const promise = new Promise((resolve2, reject2) => {
3365
+ const intervalId = setInterval(() => {
3366
+ if (webSocket.readyState !== e22.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
3367
+ clearInterval(intervalId);
3368
+ bufferDrainWatcher = void 0;
3369
+ resolve2();
3370
+ }
3371
+ }, 16);
3372
+ onCancel = () => {
3373
+ bufferDrainWatcher = void 0;
3374
+ clearInterval(intervalId);
3375
+ reject2(
3376
+ // TODO: Coded error
3377
+ new Error("WebSocket was closed before payload could be sent")
3378
+ );
3379
+ };
3380
+ });
3381
+ bufferDrainWatcher = {
3382
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3383
+ // @ts-ignore
3384
+ onCancel,
3385
+ promise
3386
+ };
3387
+ }
3388
+ if (bufferDrainWatcher) {
3389
+ await bufferDrainWatcher.promise;
3390
+ }
3391
+ webSocket.send(message);
3392
+ },
3393
+ async *[Symbol.asyncIterator]() {
3394
+ const iteratorKey = Symbol();
3395
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
3396
+ try {
3397
+ while (true) {
3398
+ const state = iteratorState.get(iteratorKey);
3399
+ if (!state) {
3400
+ throw new Error("Invariant: WebSocket message iterator is missing state storage");
3401
+ }
3402
+ if (state.__hasPolled) {
3403
+ throw new Error(
3404
+ "Invariant: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise"
3405
+ );
3406
+ }
3407
+ const queuedMessages = state.queuedMessages;
3408
+ if (queuedMessages.length) {
3409
+ state.queuedMessages = [];
3410
+ yield* queuedMessages;
3411
+ } else {
3412
+ try {
3413
+ yield await new Promise((resolve2, reject2) => {
3414
+ iteratorState.set(iteratorKey, {
3415
+ __hasPolled: true,
3416
+ onError: reject2,
3417
+ onMessage: resolve2
3418
+ });
3419
+ });
3420
+ } catch (e3) {
3421
+ if (e3 === EXPLICIT_ABORT_TOKEN) {
3422
+ return;
3423
+ } else {
3424
+ throw new Error("WebSocket connection closed", { cause: e3 });
3425
+ }
3426
+ }
3427
+ }
3428
+ }
3429
+ } finally {
3430
+ iteratorState.delete(iteratorKey);
3431
+ }
3432
+ }
3433
+ });
3434
+ }
3435
+ function handleMessage({ data }) {
3436
+ const message = JSON.parse(data);
3437
+ iteratorState.forEach((state, iteratorKey) => {
3438
+ if (state.__hasPolled) {
3439
+ const { onMessage } = state;
3440
+ iteratorState.set(iteratorKey, { __hasPolled: false, queuedMessages: [] });
3441
+ onMessage(message);
3442
+ } else {
3443
+ state.queuedMessages.push(message);
3444
+ }
3445
+ });
3446
+ }
3447
+ const webSocket = new e22(url);
3448
+ webSocket.addEventListener("close", handleClose);
3449
+ webSocket.addEventListener("error", handleError);
3450
+ webSocket.addEventListener("open", handleOpen);
3451
+ webSocket.addEventListener("message", handleMessage);
3452
+ });
3453
+ }
3454
+ function createWebSocketTransport({ sendBufferHighWatermark, url }) {
3455
+ if (/^wss?:/i.test(url) === false) {
3456
+ const protocolMatch = url.match(/^([^:]+):/);
3457
+ throw new DOMException(
3458
+ protocolMatch ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.` : `Failed to construct 'WebSocket': The URL '${url}' is invalid.`
3459
+ );
3460
+ }
3461
+ return async function sendWebSocketMessage({ payload, signal }) {
3462
+ signal == null ? void 0 : signal.throwIfAborted();
3463
+ const connection = await createWebSocketConnection({
3464
+ sendBufferHighWatermark,
3465
+ signal,
3466
+ url
3467
+ });
3468
+ signal == null ? void 0 : signal.throwIfAborted();
3469
+ await connection.send(payload);
3470
+ return {
3471
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
3472
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: connection.send.bind(connection)
3473
+ };
3474
+ };
3475
+ }
3476
+
3477
+ // src/rpc.ts
3478
+ var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
906
3479
 
907
3480
  // src/rpc-default-config.ts
908
3481
  init_env_shim();
@@ -911,23 +3484,30 @@ this.globalThis.solanaWeb3 = (function (exports) {
911
3484
  init_env_shim();
912
3485
  var SolanaJsonRpcIntegerOverflowError = class extends Error {
913
3486
  constructor(methodName, keyPath, value) {
914
- const argPosition = (typeof keyPath[0] === "number" ? keyPath[0] : parseInt(keyPath[0], 10)) + 1;
915
- let ordinal = "";
916
- const lastDigit = argPosition % 10;
917
- const lastTwoDigits = argPosition % 100;
918
- if (lastDigit == 1 && lastTwoDigits != 11) {
919
- ordinal = argPosition + "st";
920
- } else if (lastDigit == 2 && lastTwoDigits != 12) {
921
- ordinal = argPosition + "nd";
922
- } else if (lastDigit == 3 && lastTwoDigits != 13) {
923
- ordinal = argPosition + "rd";
3487
+ let argumentLabel = "";
3488
+ if (typeof keyPath[0] === "number") {
3489
+ const argPosition = keyPath[0] + 1;
3490
+ const lastDigit = argPosition % 10;
3491
+ const lastTwoDigits = argPosition % 100;
3492
+ if (lastDigit == 1 && lastTwoDigits != 11) {
3493
+ argumentLabel = argPosition + "st";
3494
+ } else if (lastDigit == 2 && lastTwoDigits != 12) {
3495
+ argumentLabel = argPosition + "nd";
3496
+ } else if (lastDigit == 3 && lastTwoDigits != 13) {
3497
+ argumentLabel = argPosition + "rd";
3498
+ } else {
3499
+ argumentLabel = argPosition + "th";
3500
+ }
924
3501
  } else {
925
- ordinal = argPosition + "th";
3502
+ argumentLabel = `\`${keyPath[0].toString()}\``;
926
3503
  }
927
3504
  const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : null;
928
3505
  super(
929
- `The ${ordinal} argument to the \`${methodName}\` RPC method${path ? ` at path \`${path}\`` : ""} was \`${value}\`. This number is unsafe for use with the Solana JSON-RPC because it exceeds \`Number.MAX_SAFE_INTEGER\`.`
3506
+ `The ${argumentLabel} argument to the \`${methodName}\` RPC method${path ? ` at path \`${path}\`` : ""} was \`${value}\`. This number is unsafe for use with the Solana JSON-RPC because it exceeds \`Number.MAX_SAFE_INTEGER\`.`
930
3507
  );
3508
+ __publicField(this, "methodName");
3509
+ __publicField(this, "keyPath");
3510
+ __publicField(this, "value");
931
3511
  this.keyPath = keyPath;
932
3512
  this.methodName = methodName;
933
3513
  this.value = value;
@@ -939,11 +3519,203 @@ this.globalThis.solanaWeb3 = (function (exports) {
939
3519
 
940
3520
  // src/rpc-default-config.ts
941
3521
  var DEFAULT_RPC_CONFIG = {
3522
+ defaultCommitment: "confirmed",
942
3523
  onIntegerOverflow(methodName, keyPath, value) {
943
3524
  throw new SolanaJsonRpcIntegerOverflowError(methodName, keyPath, value);
944
3525
  }
945
3526
  };
946
3527
 
3528
+ // src/rpc-subscription-coalescer.ts
3529
+ init_env_shim();
3530
+
3531
+ // src/cached-abortable-iterable.ts
3532
+ init_env_shim();
3533
+ function registerIterableCleanup2(iterable, cleanupFn) {
3534
+ (async () => {
3535
+ try {
3536
+ for await (const _ of iterable)
3537
+ ;
3538
+ } catch {
3539
+ } finally {
3540
+ cleanupFn();
3541
+ }
3542
+ })();
3543
+ }
3544
+ function getCachedAbortableIterableFactory({
3545
+ getAbortSignalFromInputArgs,
3546
+ getCacheEntryMissingError,
3547
+ getCacheKeyFromInputArgs,
3548
+ onCacheHit,
3549
+ onCreateIterable
3550
+ }) {
3551
+ const cache = /* @__PURE__ */ new Map();
3552
+ function getCacheEntryOrThrow(cacheKey) {
3553
+ const currentCacheEntry = cache.get(cacheKey);
3554
+ if (!currentCacheEntry) {
3555
+ throw getCacheEntryMissingError(cacheKey);
3556
+ }
3557
+ return currentCacheEntry;
3558
+ }
3559
+ return async (...args) => {
3560
+ const cacheKey = getCacheKeyFromInputArgs(...args);
3561
+ const signal = getAbortSignalFromInputArgs(...args);
3562
+ if (cacheKey === void 0) {
3563
+ return await onCreateIterable(signal, ...args);
3564
+ }
3565
+ const cleanup = () => {
3566
+ cache.delete(cacheKey);
3567
+ signal.removeEventListener("abort", handleAbort);
3568
+ };
3569
+ const handleAbort = () => {
3570
+ const cacheEntry = getCacheEntryOrThrow(cacheKey);
3571
+ if (cacheEntry.purgeScheduled !== true) {
3572
+ cacheEntry.purgeScheduled = true;
3573
+ globalThis.queueMicrotask(() => {
3574
+ cacheEntry.purgeScheduled = false;
3575
+ if (cacheEntry.referenceCount === 0) {
3576
+ cacheEntry.abortController.abort();
3577
+ cleanup();
3578
+ }
3579
+ });
3580
+ }
3581
+ cacheEntry.referenceCount--;
3582
+ };
3583
+ signal.addEventListener("abort", handleAbort);
3584
+ try {
3585
+ const cacheEntry = cache.get(cacheKey);
3586
+ if (!cacheEntry) {
3587
+ const singletonAbortController = new AbortController();
3588
+ const newIterablePromise = onCreateIterable(singletonAbortController.signal, ...args);
3589
+ const newCacheEntry = {
3590
+ abortController: singletonAbortController,
3591
+ iterable: newIterablePromise,
3592
+ purgeScheduled: false,
3593
+ referenceCount: 1
3594
+ };
3595
+ cache.set(cacheKey, newCacheEntry);
3596
+ const newIterable = await newIterablePromise;
3597
+ registerIterableCleanup2(newIterable, cleanup);
3598
+ newCacheEntry.iterable = newIterable;
3599
+ return newIterable;
3600
+ } else {
3601
+ cacheEntry.referenceCount++;
3602
+ const iterableOrIterablePromise = cacheEntry.iterable;
3603
+ const cachedIterable = "then" in iterableOrIterablePromise ? await iterableOrIterablePromise : iterableOrIterablePromise;
3604
+ await onCacheHit(cachedIterable, ...args);
3605
+ return cachedIterable;
3606
+ }
3607
+ } catch (e3) {
3608
+ cleanup();
3609
+ throw e3;
3610
+ }
3611
+ };
3612
+ }
3613
+
3614
+ // src/rpc-subscription-coalescer.ts
3615
+ var EXPLICIT_ABORT_TOKEN2 = Symbol(
3616
+ "This symbol is thrown from a subscription's iterator when the subscription is explicitly aborted by the user"
3617
+ );
3618
+ function registerIterableCleanup3(iterable, cleanupFn) {
3619
+ (async () => {
3620
+ try {
3621
+ for await (const _ of iterable)
3622
+ ;
3623
+ } catch {
3624
+ } finally {
3625
+ cleanupFn();
3626
+ }
3627
+ })();
3628
+ }
3629
+ function getRpcSubscriptionsWithSubscriptionCoalescing({
3630
+ getDeduplicationKey,
3631
+ rpcSubscriptions
3632
+ }) {
3633
+ const cache = /* @__PURE__ */ new Map();
3634
+ return new Proxy(rpcSubscriptions, {
3635
+ defineProperty() {
3636
+ return false;
3637
+ },
3638
+ deleteProperty() {
3639
+ return false;
3640
+ },
3641
+ get(target, p, receiver) {
3642
+ const subscriptionMethod = Reflect.get(target, p, receiver);
3643
+ if (typeof subscriptionMethod !== "function") {
3644
+ return subscriptionMethod;
3645
+ }
3646
+ return function(...rawParams) {
3647
+ const deduplicationKey = getDeduplicationKey(p, rawParams);
3648
+ if (deduplicationKey === void 0) {
3649
+ return subscriptionMethod(...rawParams);
3650
+ }
3651
+ if (cache.has(deduplicationKey)) {
3652
+ return cache.get(deduplicationKey);
3653
+ }
3654
+ const iterableFactory = getCachedAbortableIterableFactory({
3655
+ getAbortSignalFromInputArgs: ({ abortSignal }) => abortSignal,
3656
+ getCacheEntryMissingError(deduplicationKey2) {
3657
+ return new Error(
3658
+ `Found no cache entry for subscription with deduplication key \`${deduplicationKey2 == null ? void 0 : deduplicationKey2.toString()}\``
3659
+ );
3660
+ },
3661
+ getCacheKeyFromInputArgs: () => deduplicationKey,
3662
+ async onCacheHit(_iterable, _config) {
3663
+ },
3664
+ async onCreateIterable(abortSignal, config) {
3665
+ const pendingSubscription2 = subscriptionMethod(
3666
+ ...rawParams
3667
+ );
3668
+ const iterable = await pendingSubscription2.subscribe({
3669
+ ...config,
3670
+ abortSignal
3671
+ });
3672
+ registerIterableCleanup3(iterable, () => {
3673
+ cache.delete(deduplicationKey);
3674
+ });
3675
+ return iterable;
3676
+ }
3677
+ });
3678
+ const pendingSubscription = {
3679
+ async subscribe(...args) {
3680
+ const iterable = await iterableFactory(...args);
3681
+ const { abortSignal } = args[0];
3682
+ let abortPromise;
3683
+ return {
3684
+ ...iterable,
3685
+ async *[Symbol.asyncIterator]() {
3686
+ abortPromise || (abortPromise = abortSignal.aborted ? Promise.reject(EXPLICIT_ABORT_TOKEN2) : new Promise((_, reject) => {
3687
+ abortSignal.addEventListener("abort", () => {
3688
+ reject(EXPLICIT_ABORT_TOKEN2);
3689
+ });
3690
+ }));
3691
+ try {
3692
+ const iterator = iterable[Symbol.asyncIterator]();
3693
+ while (true) {
3694
+ const iteratorResult = await Promise.race([iterator.next(), abortPromise]);
3695
+ if (iteratorResult.done) {
3696
+ return;
3697
+ } else {
3698
+ yield iteratorResult.value;
3699
+ }
3700
+ }
3701
+ } catch (e3) {
3702
+ if (e3 === EXPLICIT_ABORT_TOKEN2) {
3703
+ return;
3704
+ }
3705
+ cache.delete(deduplicationKey);
3706
+ throw e3;
3707
+ }
3708
+ }
3709
+ };
3710
+ }
3711
+ };
3712
+ cache.set(deduplicationKey, pendingSubscription);
3713
+ return pendingSubscription;
3714
+ };
3715
+ }
3716
+ });
3717
+ }
3718
+
947
3719
  // src/rpc.ts
948
3720
  function createSolanaRpc(config) {
949
3721
  return createJsonRpc({
@@ -951,6 +3723,24 @@ this.globalThis.solanaWeb3 = (function (exports) {
951
3723
  api: createSolanaRpcApi(DEFAULT_RPC_CONFIG)
952
3724
  });
953
3725
  }
3726
+ function createSolanaRpcSubscriptions(config) {
3727
+ return pipe(
3728
+ createJsonSubscriptionRpc({
3729
+ ...config,
3730
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_CONFIG)
3731
+ }),
3732
+ (rpcSubscriptions) => getRpcSubscriptionsWithSubscriptionCoalescing({
3733
+ getDeduplicationKey: (...args) => (0, import_fast_stable_stringify.default)(args),
3734
+ rpcSubscriptions
3735
+ })
3736
+ );
3737
+ }
3738
+ function createSolanaRpcSubscriptions_UNSTABLE(config) {
3739
+ return createJsonSubscriptionRpc({
3740
+ ...config,
3741
+ api: createSolanaRpcSubscriptionsApi_UNSTABLE(DEFAULT_RPC_CONFIG)
3742
+ });
3743
+ }
954
3744
 
955
3745
  // src/rpc-transport.ts
956
3746
  init_env_shim();
@@ -987,14 +3777,14 @@ this.globalThis.solanaWeb3 = (function (exports) {
987
3777
  if (signal) {
988
3778
  const responsePromise = coalescedRequest.responsePromise;
989
3779
  return await new Promise((resolve, reject) => {
990
- const handleAbort = (e2) => {
3780
+ const handleAbort = (e3) => {
991
3781
  signal.removeEventListener("abort", handleAbort);
992
3782
  coalescedRequest.numConsumers -= 1;
993
3783
  if (coalescedRequest.numConsumers === 0) {
994
3784
  const abortController = coalescedRequest.abortController;
995
3785
  abortController.abort();
996
3786
  }
997
- const abortError = new DOMException(e2.target.reason, "AbortError");
3787
+ const abortError = new DOMException(e3.target.reason, "AbortError");
998
3788
  reject(abortError);
999
3789
  };
1000
3790
  signal.addEventListener("abort", handleAbort);
@@ -1010,14 +3800,15 @@ this.globalThis.solanaWeb3 = (function (exports) {
1010
3800
 
1011
3801
  // src/rpc-request-deduplication.ts
1012
3802
  init_env_shim();
1013
- var import_fast_stable_stringify = __toESM(require_fast_stable_stringify(), 1);
1014
- function getSolanaRpcPayloadDeduplicationKey(payload) {
3803
+ var import_fast_stable_stringify2 = __toESM(require_fast_stable_stringify(), 1);
3804
+ function isJsonRpcPayload(payload) {
1015
3805
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
1016
- return;
1017
- }
1018
- if ("jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && "params" in payload) {
1019
- return (0, import_fast_stable_stringify.default)([payload.method, payload.params]);
3806
+ return false;
1020
3807
  }
3808
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
3809
+ }
3810
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
3811
+ return isJsonRpcPayload(payload) ? (0, import_fast_stable_stringify2.default)([payload.method, payload.params]) : void 0;
1021
3812
  }
1022
3813
 
1023
3814
  // src/rpc-transport.ts
@@ -1029,38 +3820,528 @@ this.globalThis.solanaWeb3 = (function (exports) {
1029
3820
  return out;
1030
3821
  }
1031
3822
  function createDefaultRpcTransport(config) {
1032
- return getRpcTransportWithRequestCoalescing(
3823
+ var _a;
3824
+ return pipe(
1033
3825
  createHttpTransport({
1034
3826
  ...config,
1035
3827
  headers: {
1036
3828
  ...config.headers ? normalizeHeaders2(config.headers) : void 0,
1037
3829
  ...{
1038
3830
  // Keep these headers lowercase so they will override any user-supplied headers above.
1039
- "solana-client": `js/${"2.0.0-development"}` ?? "UNKNOWN"
3831
+ "solana-client": (_a = `js/${"2.0.0-development"}`) != null ? _a : "UNKNOWN"
3832
+ }
3833
+ }
3834
+ }),
3835
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
3836
+ );
3837
+ }
3838
+
3839
+ // src/rpc-websocket-transport.ts
3840
+ init_env_shim();
3841
+
3842
+ // src/rpc-websocket-autopinger.ts
3843
+ init_env_shim();
3844
+ var PING_PAYLOAD = {
3845
+ jsonrpc: "2.0",
3846
+ method: "ping"
3847
+ };
3848
+ function getWebSocketTransportWithAutoping({ intervalMs, transport }) {
3849
+ const pingableConnections = /* @__PURE__ */ new Map();
3850
+ return async (...args) => {
3851
+ const connection = await transport(...args);
3852
+ let intervalId;
3853
+ function sendPing() {
3854
+ connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(PING_PAYLOAD);
3855
+ }
3856
+ function restartPingTimer() {
3857
+ clearInterval(intervalId);
3858
+ intervalId = setInterval(sendPing, intervalMs);
3859
+ }
3860
+ if (pingableConnections.has(connection) === false) {
3861
+ pingableConnections.set(connection, {
3862
+ [Symbol.asyncIterator]: connection[Symbol.asyncIterator].bind(connection),
3863
+ send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: (...args2) => {
3864
+ restartPingTimer();
3865
+ return connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(...args2);
1040
3866
  }
3867
+ });
3868
+ (async () => {
3869
+ try {
3870
+ for await (const _ of connection) {
3871
+ restartPingTimer();
3872
+ }
3873
+ } catch {
3874
+ } finally {
3875
+ pingableConnections.delete(connection);
3876
+ clearInterval(intervalId);
3877
+ if (handleOffline) {
3878
+ globalThis.window.removeEventListener("offline", handleOffline);
3879
+ }
3880
+ if (handleOnline) {
3881
+ globalThis.window.removeEventListener("online", handleOnline);
3882
+ }
3883
+ }
3884
+ })();
3885
+ if (globalThis.navigator.onLine) {
3886
+ restartPingTimer();
3887
+ }
3888
+ let handleOffline;
3889
+ let handleOnline;
3890
+ {
3891
+ handleOffline = () => {
3892
+ clearInterval(intervalId);
3893
+ };
3894
+ handleOnline = () => {
3895
+ sendPing();
3896
+ restartPingTimer();
3897
+ };
3898
+ globalThis.window.addEventListener("offline", handleOffline);
3899
+ globalThis.window.addEventListener("online", handleOnline);
1041
3900
  }
3901
+ }
3902
+ return pingableConnections.get(connection);
3903
+ };
3904
+ }
3905
+
3906
+ // src/rpc-websocket-connection-sharding.ts
3907
+ init_env_shim();
3908
+ var NULL_SHARD_CACHE_KEY = Symbol(
3909
+ "Cache key to use when there is no connection sharding strategy"
3910
+ );
3911
+ function getWebSocketTransportWithConnectionSharding({ getShard, transport }) {
3912
+ return getCachedAbortableIterableFactory({
3913
+ getAbortSignalFromInputArgs: ({ signal }) => signal,
3914
+ getCacheEntryMissingError(shardKey) {
3915
+ return new Error(`Found no cache entry for connection with shard key \`${shardKey == null ? void 0 : shardKey.toString()}\``);
3916
+ },
3917
+ getCacheKeyFromInputArgs: ({ payload }) => getShard ? getShard(payload) : NULL_SHARD_CACHE_KEY,
3918
+ onCacheHit: (connection, { payload }) => connection.send_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(payload),
3919
+ onCreateIterable: (abortSignal, config) => transport({
3920
+ ...config,
3921
+ signal: abortSignal
3922
+ })
3923
+ });
3924
+ }
3925
+
3926
+ // src/rpc-websocket-transport.ts
3927
+ function createDefaultRpcSubscriptionsTransport(config) {
3928
+ var _a;
3929
+ const { getShard, intervalMs, ...rest } = config;
3930
+ return pipe(
3931
+ createWebSocketTransport({
3932
+ ...rest,
3933
+ sendBufferHighWatermark: (_a = config.sendBufferHighWatermark) != null ? _a : (
3934
+ // Let 128KB of data into the WebSocket buffer before buffering it in the app.
3935
+ 131072
3936
+ )
3937
+ }),
3938
+ (transport) => getWebSocketTransportWithAutoping({
3939
+ intervalMs: intervalMs != null ? intervalMs : 5e3,
3940
+ transport
1042
3941
  }),
1043
- getSolanaRpcPayloadDeduplicationKey
3942
+ (transport) => getWebSocketTransportWithConnectionSharding({
3943
+ getShard,
3944
+ transport
3945
+ })
3946
+ );
3947
+ }
3948
+
3949
+ // src/send-transaction.ts
3950
+ init_env_shim();
3951
+
3952
+ // src/transaction-confirmation.ts
3953
+ init_env_shim();
3954
+
3955
+ // src/transaction-confirmation-strategy-blockheight.ts
3956
+ init_env_shim();
3957
+ function createBlockHeightExceedencePromiseFactory({
3958
+ rpc,
3959
+ rpcSubscriptions
3960
+ }) {
3961
+ return async function getBlockHeightExceedencePromise({
3962
+ abortSignal: callerAbortSignal,
3963
+ commitment,
3964
+ lastValidBlockHeight
3965
+ }) {
3966
+ const abortController = new AbortController();
3967
+ const handleAbort = () => {
3968
+ abortController.abort();
3969
+ };
3970
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
3971
+ async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {
3972
+ const { absoluteSlot, blockHeight } = await rpc.getEpochInfo({ commitment }).send({ abortSignal: abortController.signal });
3973
+ return {
3974
+ blockHeight,
3975
+ differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight
3976
+ };
3977
+ }
3978
+ try {
3979
+ const [slotNotifications, { blockHeight, differenceBetweenSlotHeightAndBlockHeight }] = await Promise.all([
3980
+ rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),
3981
+ getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight()
3982
+ ]);
3983
+ if (blockHeight <= lastValidBlockHeight) {
3984
+ let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;
3985
+ for await (const slotNotification of slotNotifications) {
3986
+ const { slot } = slotNotification;
3987
+ if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {
3988
+ const {
3989
+ blockHeight: currentBlockHeight,
3990
+ differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight
3991
+ } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();
3992
+ if (currentBlockHeight > lastValidBlockHeight) {
3993
+ break;
3994
+ } else {
3995
+ lastKnownDifferenceBetweenSlotHeightAndBlockHeight = currentDifferenceBetweenSlotHeightAndBlockHeight;
3996
+ }
3997
+ }
3998
+ }
3999
+ }
4000
+ throw new Error(
4001
+ "The network has progressed past the last block for which this transaction could have been committed."
4002
+ );
4003
+ } finally {
4004
+ abortController.abort();
4005
+ }
4006
+ };
4007
+ }
4008
+
4009
+ // src/transaction-confirmation-strategy-nonce.ts
4010
+ init_env_shim();
4011
+ var NONCE_VALUE_OFFSET = 4 + // version(u32)
4012
+ 4 + // state(u32)
4013
+ 32;
4014
+ function createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions) {
4015
+ return async function getNonceInvalidationPromise({
4016
+ abortSignal: callerAbortSignal,
4017
+ commitment,
4018
+ currentNonceValue,
4019
+ nonceAccountAddress
4020
+ }) {
4021
+ const abortController = new AbortController();
4022
+ function handleAbort() {
4023
+ abortController.abort();
4024
+ }
4025
+ callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
4026
+ const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
4027
+ const base58Decoder2 = getBase58Decoder();
4028
+ const base64Encoder = getBase64Encoder();
4029
+ function getNonceFromAccountData([base64EncodedBytes]) {
4030
+ const data = base64Encoder.encode(base64EncodedBytes);
4031
+ const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
4032
+ return base58Decoder2.decode(nonceValueBytes);
4033
+ }
4034
+ const nonceAccountDidAdvancePromise = (async () => {
4035
+ for await (const accountNotification of accountNotifications) {
4036
+ const nonceValue = getNonceFromAccountData(accountNotification.value.data);
4037
+ if (nonceValue !== currentNonceValue) {
4038
+ throw new Error(
4039
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
4040
+ );
4041
+ }
4042
+ }
4043
+ })();
4044
+ const nonceIsAlreadyInvalidPromise = (async () => {
4045
+ const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
4046
+ commitment,
4047
+ dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
4048
+ encoding: "base58"
4049
+ }).send({ abortSignal: abortController.signal });
4050
+ if (!nonceAccount) {
4051
+ throw new Error(`No nonce account could be found at address \`${nonceAccountAddress}\`.`);
4052
+ }
4053
+ const nonceValue = (
4054
+ // This works because we asked for the exact slice of data representing the nonce
4055
+ // value, and furthermore asked for it in `base58` encoding.
4056
+ nonceAccount.data[0]
4057
+ );
4058
+ if (nonceValue !== currentNonceValue) {
4059
+ throw new Error(
4060
+ `The nonce \`${currentNonceValue}\` is no longer valid. It has advanced to \`${nonceValue}\`.`
4061
+ );
4062
+ } else {
4063
+ await new Promise(() => {
4064
+ });
4065
+ }
4066
+ })();
4067
+ try {
4068
+ return await Promise.race([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
4069
+ } finally {
4070
+ abortController.abort();
4071
+ }
4072
+ };
4073
+ }
4074
+
4075
+ // src/transaction-confirmation.ts
4076
+ function createDefaultDurableNonceTransactionConfirmer({
4077
+ rpc,
4078
+ rpcSubscriptions
4079
+ }) {
4080
+ const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory(rpc, rpcSubscriptions);
4081
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
4082
+ rpc,
4083
+ rpcSubscriptions
4084
+ );
4085
+ return async function confirmDurableNonceTransaction(config) {
4086
+ await waitForDurableNonceTransactionConfirmation({
4087
+ ...config,
4088
+ getNonceInvalidationPromise,
4089
+ getRecentSignatureConfirmationPromise
4090
+ });
4091
+ };
4092
+ }
4093
+ function createDefaultRecentTransactionConfirmer({
4094
+ rpc,
4095
+ rpcSubscriptions
4096
+ }) {
4097
+ const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({
4098
+ rpc,
4099
+ rpcSubscriptions
4100
+ });
4101
+ const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory(
4102
+ rpc,
4103
+ rpcSubscriptions
4104
+ );
4105
+ return async function confirmRecentTransaction(config) {
4106
+ await waitForRecentTransactionConfirmation({
4107
+ ...config,
4108
+ getBlockHeightExceedencePromise,
4109
+ getRecentSignatureConfirmationPromise
4110
+ });
4111
+ };
4112
+ }
4113
+ async function waitForDurableNonceTransactionConfirmation(config) {
4114
+ await raceStrategies(
4115
+ getSignatureFromTransaction(config.transaction),
4116
+ config,
4117
+ function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
4118
+ return [
4119
+ getNonceInvalidationPromise({
4120
+ abortSignal,
4121
+ commitment,
4122
+ currentNonceValue: transaction.lifetimeConstraint.nonce,
4123
+ nonceAccountAddress: transaction.instructions[0].accounts[0].address
4124
+ })
4125
+ ];
4126
+ }
4127
+ );
4128
+ }
4129
+ async function waitForRecentTransactionConfirmation(config) {
4130
+ await raceStrategies(
4131
+ getSignatureFromTransaction(config.transaction),
4132
+ config,
4133
+ function getSpecificStrategiesForRace({
4134
+ abortSignal,
4135
+ commitment,
4136
+ getBlockHeightExceedencePromise,
4137
+ transaction
4138
+ }) {
4139
+ return [
4140
+ getBlockHeightExceedencePromise({
4141
+ abortSignal,
4142
+ commitment,
4143
+ lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
4144
+ })
4145
+ ];
4146
+ }
1044
4147
  );
1045
4148
  }
1046
4149
 
4150
+ // src/send-transaction.ts
4151
+ function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
4152
+ if (
4153
+ // The developer has supplied no value for `preflightCommitment`.
4154
+ !(config == null ? void 0 : config.preflightCommitment) && // The value of `commitment` is lower than the server default of `preflightCommitment`.
4155
+ commitmentComparator(
4156
+ commitment,
4157
+ "finalized"
4158
+ /* default value of `preflightCommitment` */
4159
+ ) < 0
4160
+ ) {
4161
+ return {
4162
+ ...config,
4163
+ // In the common case, it is unlikely that you want to simulate a transaction at
4164
+ // `finalized` commitment when your standard of commitment for confirming the
4165
+ // transaction is lower. Cap the simulation commitment level to the level of the
4166
+ // confirmation commitment.
4167
+ preflightCommitment: commitment
4168
+ };
4169
+ }
4170
+ return config;
4171
+ }
4172
+ async function sendTransaction_INTERNAL({
4173
+ abortSignal,
4174
+ commitment,
4175
+ rpc,
4176
+ transaction,
4177
+ ...sendTransactionConfig
4178
+ }) {
4179
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
4180
+ return await rpc.sendTransaction(base64EncodedWireTransaction, {
4181
+ ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
4182
+ encoding: "base64"
4183
+ }).send({ abortSignal });
4184
+ }
4185
+ function createDefaultDurableNonceTransactionSender({
4186
+ rpc,
4187
+ rpcSubscriptions
4188
+ }) {
4189
+ const confirmDurableNonceTransaction = createDefaultDurableNonceTransactionConfirmer({
4190
+ rpc,
4191
+ rpcSubscriptions
4192
+ });
4193
+ return async function sendDurableNonceTransaction(transaction, config) {
4194
+ await sendAndConfirmDurableNonceTransaction({
4195
+ ...config,
4196
+ confirmDurableNonceTransaction,
4197
+ rpc,
4198
+ transaction
4199
+ });
4200
+ };
4201
+ }
4202
+ function createDefaultTransactionSender({
4203
+ rpc,
4204
+ rpcSubscriptions
4205
+ }) {
4206
+ const confirmRecentTransaction = createDefaultRecentTransactionConfirmer({
4207
+ rpc,
4208
+ rpcSubscriptions
4209
+ });
4210
+ return async function sendTransaction(transaction, config) {
4211
+ await sendAndConfirmTransaction({
4212
+ ...config,
4213
+ confirmRecentTransaction,
4214
+ rpc,
4215
+ transaction
4216
+ });
4217
+ };
4218
+ }
4219
+ async function sendAndConfirmDurableNonceTransaction({
4220
+ abortSignal,
4221
+ commitment,
4222
+ confirmDurableNonceTransaction,
4223
+ rpc,
4224
+ transaction,
4225
+ ...sendTransactionConfig
4226
+ }) {
4227
+ const transactionSignature = await sendTransaction_INTERNAL({
4228
+ ...sendTransactionConfig,
4229
+ abortSignal,
4230
+ commitment,
4231
+ rpc,
4232
+ transaction
4233
+ });
4234
+ await confirmDurableNonceTransaction({
4235
+ abortSignal,
4236
+ commitment,
4237
+ transaction
4238
+ });
4239
+ return transactionSignature;
4240
+ }
4241
+ async function sendAndConfirmTransaction({
4242
+ abortSignal,
4243
+ commitment,
4244
+ confirmRecentTransaction,
4245
+ rpc,
4246
+ transaction,
4247
+ ...sendTransactionConfig
4248
+ }) {
4249
+ const transactionSignature = await sendTransaction_INTERNAL({
4250
+ ...sendTransactionConfig,
4251
+ abortSignal,
4252
+ commitment,
4253
+ rpc,
4254
+ transaction
4255
+ });
4256
+ await confirmRecentTransaction({
4257
+ abortSignal,
4258
+ commitment,
4259
+ transaction
4260
+ });
4261
+ return transactionSignature;
4262
+ }
4263
+
1047
4264
  exports.AccountRole = AccountRole;
1048
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
4265
+ exports.address = address;
4266
+ exports.appendTransactionInstruction = appendTransactionInstruction;
4267
+ exports.assertIsAddress = assertIsAddress;
4268
+ exports.assertIsBlockhash = assertIsBlockhash;
4269
+ exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
4270
+ exports.assertIsLamports = assertIsLamports;
4271
+ exports.assertIsProgramDerivedAddress = assertIsProgramDerivedAddress;
4272
+ exports.assertIsSignature = assertIsSignature;
4273
+ exports.assertIsStringifiedBigInt = assertIsStringifiedBigInt;
4274
+ exports.assertIsStringifiedNumber = assertIsStringifiedNumber;
4275
+ exports.assertIsTransactionWithBlockhashLifetime = assertIsTransactionWithBlockhashLifetime;
4276
+ exports.assertIsUnixTimestamp = assertIsUnixTimestamp;
4277
+ exports.assertTransactionIsFullySigned = assertTransactionIsFullySigned;
4278
+ exports.commitmentComparator = commitmentComparator;
4279
+ exports.compileMessage = compileMessage;
4280
+ exports.createAddressWithSeed = createAddressWithSeed;
4281
+ exports.createBlockHeightExceedencePromiseFactory = createBlockHeightExceedencePromiseFactory;
4282
+ exports.createDefaultAirdropRequester = createDefaultAirdropRequester;
4283
+ exports.createDefaultDurableNonceTransactionConfirmer = createDefaultDurableNonceTransactionConfirmer;
4284
+ exports.createDefaultDurableNonceTransactionSender = createDefaultDurableNonceTransactionSender;
4285
+ exports.createDefaultRecentTransactionConfirmer = createDefaultRecentTransactionConfirmer;
4286
+ exports.createDefaultRpcSubscriptionsTransport = createDefaultRpcSubscriptionsTransport;
1049
4287
  exports.createDefaultRpcTransport = createDefaultRpcTransport;
4288
+ exports.createDefaultTransactionSender = createDefaultTransactionSender;
4289
+ exports.createNonceInvalidationPromiseFactory = createNonceInvalidationPromiseFactory;
4290
+ exports.createPrivateKeyFromBytes = createPrivateKeyFromBytes;
4291
+ exports.createRecentSignatureConfirmationPromiseFactory = createRecentSignatureConfirmationPromiseFactory;
1050
4292
  exports.createSolanaRpc = createSolanaRpc;
4293
+ exports.createSolanaRpcSubscriptions = createSolanaRpcSubscriptions;
4294
+ exports.createSolanaRpcSubscriptions_UNSTABLE = createSolanaRpcSubscriptions_UNSTABLE;
4295
+ exports.createTransaction = createTransaction;
1051
4296
  exports.downgradeRoleToNonSigner = downgradeRoleToNonSigner;
1052
4297
  exports.downgradeRoleToReadonly = downgradeRoleToReadonly;
1053
4298
  exports.generateKeyPair = generateKeyPair;
1054
- exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
1055
- exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
1056
- exports.getBase58EncodedAddressFromPublicKey = getBase58EncodedAddressFromPublicKey;
4299
+ exports.getAddressCodec = getAddressCodec;
4300
+ exports.getAddressComparator = getAddressComparator;
4301
+ exports.getAddressDecoder = getAddressDecoder;
4302
+ exports.getAddressEncoder = getAddressEncoder;
4303
+ exports.getAddressFromPublicKey = getAddressFromPublicKey;
4304
+ exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
4305
+ exports.getCompiledMessageCodec = getCompiledMessageCodec;
4306
+ exports.getCompiledMessageDecoder = getCompiledMessageDecoder;
4307
+ exports.getCompiledMessageEncoder = getCompiledMessageEncoder;
4308
+ exports.getProgramDerivedAddress = getProgramDerivedAddress;
4309
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
4310
+ exports.getTransactionCodec = getTransactionCodec;
4311
+ exports.getTransactionDecoder = getTransactionDecoder;
4312
+ exports.getTransactionEncoder = getTransactionEncoder;
4313
+ exports.isAddress = isAddress;
4314
+ exports.isAdvanceNonceAccountInstruction = isAdvanceNonceAccountInstruction;
4315
+ exports.isLamports = isLamports;
4316
+ exports.isProgramDerivedAddress = isProgramDerivedAddress;
4317
+ exports.isSignature = isSignature;
1057
4318
  exports.isSignerRole = isSignerRole;
4319
+ exports.isStringifiedBigInt = isStringifiedBigInt;
4320
+ exports.isStringifiedNumber = isStringifiedNumber;
4321
+ exports.isUnixTimestamp = isUnixTimestamp;
1058
4322
  exports.isWritableRole = isWritableRole;
4323
+ exports.lamports = lamports;
1059
4324
  exports.mergeRoles = mergeRoles;
4325
+ exports.partiallySignTransaction = partiallySignTransaction;
4326
+ exports.pipe = pipe;
4327
+ exports.prependTransactionInstruction = prependTransactionInstruction;
4328
+ exports.requestAndConfirmAirdrop = requestAndConfirmAirdrop;
4329
+ exports.sendAndConfirmDurableNonceTransaction = sendAndConfirmDurableNonceTransaction;
4330
+ exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
4331
+ exports.setTransactionFeePayer = setTransactionFeePayer;
4332
+ exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
4333
+ exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
1060
4334
  exports.signBytes = signBytes;
4335
+ exports.signTransaction = signTransaction;
4336
+ exports.signature = signature;
4337
+ exports.stringifiedBigInt = stringifiedBigInt;
4338
+ exports.stringifiedNumber = stringifiedNumber;
4339
+ exports.unixTimestamp = unixTimestamp;
1061
4340
  exports.upgradeRoleToSigner = upgradeRoleToSigner;
1062
4341
  exports.upgradeRoleToWritable = upgradeRoleToWritable;
1063
4342
  exports.verifySignature = verifySignature;
4343
+ exports.waitForDurableNonceTransactionConfirmation = waitForDurableNonceTransactionConfirmation;
4344
+ exports.waitForRecentTransactionConfirmation = waitForRecentTransactionConfirmation;
1064
4345
 
1065
4346
  return exports;
1066
4347