@rialo/ts-cdk 0.2.0-alpha.0 → 0.2.0-alpha.1

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.
package/dist/index.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ import { Chacha20Poly1305 } from '@hpke/chacha20poly1305';
2
+ import { CipherSuite, HkdfSha256, DhkemX25519HkdfSha256 } from '@hpke/core';
3
+
1
4
  var __create = Object.create;
2
5
  var __defProp = Object.defineProperty;
3
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -5478,6 +5481,302 @@ var RialoError = class _RialoError extends Error {
5478
5481
  }
5479
5482
  };
5480
5483
 
5484
+ // src/rex/errors.ts
5485
+ var HpkeErrorCode = /* @__PURE__ */ ((HpkeErrorCode2) => {
5486
+ HpkeErrorCode2["INVALID_KEY_LENGTH"] = "INVALID_KEY_LENGTH";
5487
+ HpkeErrorCode2["CIPHERTEXT_TOO_SHORT"] = "CIPHERTEXT_TOO_SHORT";
5488
+ HpkeErrorCode2["ENCRYPTION_FAILED"] = "ENCRYPTION_FAILED";
5489
+ HpkeErrorCode2["BORSH_DESERIALIZE_FAILED"] = "BORSH_DESERIALIZE_FAILED";
5490
+ HpkeErrorCode2["INVALID_ORACLE_VALUE"] = "INVALID_ORACLE_VALUE";
5491
+ return HpkeErrorCode2;
5492
+ })(HpkeErrorCode || {});
5493
+ var HpkeError = class _HpkeError extends Error {
5494
+ code;
5495
+ cause;
5496
+ constructor(code, message, cause) {
5497
+ super(message);
5498
+ this.name = "HpkeError";
5499
+ this.code = code;
5500
+ this.cause = cause;
5501
+ if (Error.captureStackTrace) {
5502
+ Error.captureStackTrace(this, _HpkeError);
5503
+ }
5504
+ }
5505
+ /**
5506
+ * Create an error for invalid key length.
5507
+ *
5508
+ * @param expected - Expected key length in bytes
5509
+ * @param actual - Actual key length in bytes
5510
+ * @param keyType - Description of the key type (e.g., "REX public key")
5511
+ */
5512
+ static invalidKeyLength(expected, actual, keyType) {
5513
+ return new _HpkeError(
5514
+ "INVALID_KEY_LENGTH" /* INVALID_KEY_LENGTH */,
5515
+ `Invalid ${keyType} length: expected ${expected} bytes, got ${actual}`
5516
+ );
5517
+ }
5518
+ /**
5519
+ * Create an error for ciphertext that is too short.
5520
+ *
5521
+ * @param minLength - Minimum required length
5522
+ * @param actual - Actual length
5523
+ */
5524
+ static ciphertextTooShort(minLength, actual) {
5525
+ return new _HpkeError(
5526
+ "CIPHERTEXT_TOO_SHORT" /* CIPHERTEXT_TOO_SHORT */,
5527
+ `Ciphertext too short: minimum ${minLength} bytes required, got ${actual}`
5528
+ );
5529
+ }
5530
+ /**
5531
+ * Create an error for encryption failure.
5532
+ *
5533
+ * @param cause - The underlying error
5534
+ */
5535
+ static encryptionFailed(cause) {
5536
+ return new _HpkeError(
5537
+ "ENCRYPTION_FAILED" /* ENCRYPTION_FAILED */,
5538
+ `HPKE encryption failed: ${cause.message}`,
5539
+ cause
5540
+ );
5541
+ }
5542
+ /**
5543
+ * Create an error for Borsh deserialization failure.
5544
+ *
5545
+ * @param cause - The underlying error
5546
+ */
5547
+ static borshDeserializeFailed(cause) {
5548
+ return new _HpkeError(
5549
+ "BORSH_DESERIALIZE_FAILED" /* BORSH_DESERIALIZE_FAILED */,
5550
+ `Borsh deserialization failed: ${cause.message}`,
5551
+ cause
5552
+ );
5553
+ }
5554
+ /**
5555
+ * Create an error for invalid RexValue variant.
5556
+ *
5557
+ * @param variant - The invalid variant byte
5558
+ */
5559
+ static invalidRexValue(variant) {
5560
+ return new _HpkeError(
5561
+ "INVALID_ORACLE_VALUE" /* INVALID_ORACLE_VALUE */,
5562
+ `Invalid RexValue variant: ${variant}`
5563
+ );
5564
+ }
5565
+ };
5566
+
5567
+ // src/rex/constants.ts
5568
+ var USER_SECRET_AAD = new TextEncoder().encode("rex-secret-v1");
5569
+ var SECRET_SHARING_HPKE_INFO = new TextEncoder().encode(
5570
+ "rialo/tee/secret-sharing-hpke/v1"
5571
+ );
5572
+ var X25519_PUBLIC_KEY_LENGTH = 32;
5573
+ var ED25519_PUBLIC_KEY_LENGTH = 32;
5574
+ var HPKE_ENC_LENGTH = 32;
5575
+ var CHACHA20_POLY1305_TAG_LENGTH = 16;
5576
+ var HPKE_OVERHEAD_LENGTH = HPKE_ENC_LENGTH + CHACHA20_POLY1305_TAG_LENGTH;
5577
+
5578
+ // src/rex/rex-value.ts
5579
+ var RexValueVariant = /* @__PURE__ */ ((RexValueVariant2) => {
5580
+ RexValueVariant2[RexValueVariant2["Plain"] = 0] = "Plain";
5581
+ RexValueVariant2[RexValueVariant2["Encrypted"] = 1] = "Encrypted";
5582
+ return RexValueVariant2;
5583
+ })(RexValueVariant || {});
5584
+ var RexValue = class _RexValue {
5585
+ variant;
5586
+ data;
5587
+ constructor(variant, data) {
5588
+ this.variant = variant;
5589
+ this.data = data;
5590
+ }
5591
+ /**
5592
+ * Create a plain (unencrypted) RexValue from raw bytes.
5593
+ *
5594
+ * @param data - The raw byte data
5595
+ * @returns A new RexValue with Plain variant
5596
+ */
5597
+ static plain(data) {
5598
+ return new _RexValue(0 /* Plain */, data);
5599
+ }
5600
+ /**
5601
+ * Create a plain (unencrypted) RexValue from a UTF-8 string.
5602
+ *
5603
+ * @param s - The string to encode
5604
+ * @returns A new RexValue with Plain variant
5605
+ */
5606
+ static plainString(s) {
5607
+ return new _RexValue(
5608
+ 0 /* Plain */,
5609
+ new TextEncoder().encode(s)
5610
+ );
5611
+ }
5612
+ /**
5613
+ * Create an encrypted RexValue from HPKE ciphertext.
5614
+ *
5615
+ * @param ciphertext - The HPKE-encrypted ciphertext (enc || ct || tag)
5616
+ * @returns A new RexValue with Encrypted variant
5617
+ */
5618
+ static encrypted(ciphertext) {
5619
+ return new _RexValue(1 /* Encrypted */, ciphertext);
5620
+ }
5621
+ /**
5622
+ * Check if this is a plain (unencrypted) value.
5623
+ */
5624
+ isPlain() {
5625
+ return this.variant === 0 /* Plain */;
5626
+ }
5627
+ /**
5628
+ * Check if this is an encrypted value.
5629
+ */
5630
+ isEncrypted() {
5631
+ return this.variant === 1 /* Encrypted */;
5632
+ }
5633
+ /**
5634
+ * Get the variant type.
5635
+ */
5636
+ getVariant() {
5637
+ return this.variant;
5638
+ }
5639
+ /**
5640
+ * Get the raw bytes (plaintext or ciphertext).
5641
+ *
5642
+ * For Plain values, returns the plaintext.
5643
+ * For Encrypted values, returns the ciphertext.
5644
+ */
5645
+ asBytes() {
5646
+ return this.data;
5647
+ }
5648
+ /**
5649
+ * Try to decode the plain value as a UTF-8 string.
5650
+ *
5651
+ * @returns The decoded string, or null if encrypted or not valid UTF-8
5652
+ */
5653
+ asString() {
5654
+ if (!this.isPlain()) {
5655
+ return null;
5656
+ }
5657
+ try {
5658
+ return new TextDecoder("utf-8", { fatal: true }).decode(this.data);
5659
+ } catch {
5660
+ return null;
5661
+ }
5662
+ }
5663
+ /**
5664
+ * Serialize to Borsh format.
5665
+ *
5666
+ * Format: `[variant: u8] [length: u32 LE] [data bytes]`
5667
+ *
5668
+ * @returns The Borsh-serialized bytes
5669
+ */
5670
+ toBorsh() {
5671
+ const result = new Uint8Array(1 + 4 + this.data.length);
5672
+ result[0] = this.variant;
5673
+ const dataView = new DataView(result.buffer);
5674
+ dataView.setUint32(1, this.data.length, true);
5675
+ result.set(this.data, 5);
5676
+ return result;
5677
+ }
5678
+ /**
5679
+ * Deserialize from Borsh format.
5680
+ *
5681
+ * @param data - The Borsh-serialized bytes
5682
+ * @returns A new RexValue
5683
+ * @throws {HpkeError} If deserialization fails
5684
+ */
5685
+ static fromBorsh(data) {
5686
+ if (data.length < 5) {
5687
+ throw HpkeError.borshDeserializeFailed(
5688
+ new Error(`Buffer too short: expected at least 5 bytes, got ${data.length}`)
5689
+ );
5690
+ }
5691
+ const variant = data[0];
5692
+ if (variant !== 0 /* Plain */ && variant !== 1 /* Encrypted */) {
5693
+ throw HpkeError.invalidRexValue(variant);
5694
+ }
5695
+ const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
5696
+ const length = dataView.getUint32(1, true);
5697
+ if (data.length < 5 + length) {
5698
+ throw HpkeError.borshDeserializeFailed(
5699
+ new Error(`Buffer too short: expected ${5 + length} bytes, got ${data.length}`)
5700
+ );
5701
+ }
5702
+ const payload = data.slice(5, 5 + length);
5703
+ return new _RexValue(variant, payload);
5704
+ }
5705
+ };
5706
+ var hpkeSuite = new CipherSuite({
5707
+ kem: new DhkemX25519HkdfSha256(),
5708
+ kdf: new HkdfSha256(),
5709
+ aead: new Chacha20Poly1305()
5710
+ });
5711
+ function buildAad(senderPubkey) {
5712
+ const aad = new Uint8Array(USER_SECRET_AAD.length + senderPubkey.length);
5713
+ aad.set(USER_SECRET_AAD, 0);
5714
+ aad.set(senderPubkey, USER_SECRET_AAD.length);
5715
+ return aad;
5716
+ }
5717
+ async function hpkeEncrypt(rexPubkey, data, senderPubkey) {
5718
+ if (rexPubkey.length !== X25519_PUBLIC_KEY_LENGTH) {
5719
+ throw HpkeError.invalidKeyLength(
5720
+ X25519_PUBLIC_KEY_LENGTH,
5721
+ rexPubkey.length,
5722
+ "REX public key"
5723
+ );
5724
+ }
5725
+ if (senderPubkey.length !== ED25519_PUBLIC_KEY_LENGTH) {
5726
+ throw HpkeError.invalidKeyLength(
5727
+ ED25519_PUBLIC_KEY_LENGTH,
5728
+ senderPubkey.length,
5729
+ "sender public key"
5730
+ );
5731
+ }
5732
+ try {
5733
+ const recipientKey = await hpkeSuite.kem.importKey(
5734
+ "raw",
5735
+ rexPubkey.buffer.slice(
5736
+ rexPubkey.byteOffset,
5737
+ rexPubkey.byteOffset + rexPubkey.byteLength
5738
+ )
5739
+ );
5740
+ const sender = await hpkeSuite.createSenderContext({
5741
+ recipientPublicKey: recipientKey,
5742
+ info: SECRET_SHARING_HPKE_INFO.buffer.slice(
5743
+ SECRET_SHARING_HPKE_INFO.byteOffset,
5744
+ SECRET_SHARING_HPKE_INFO.byteOffset + SECRET_SHARING_HPKE_INFO.byteLength
5745
+ )
5746
+ });
5747
+ const aad = buildAad(senderPubkey);
5748
+ const ciphertext = await sender.seal(
5749
+ data.buffer.slice(
5750
+ data.byteOffset,
5751
+ data.byteOffset + data.byteLength
5752
+ ),
5753
+ aad.buffer.slice(
5754
+ aad.byteOffset,
5755
+ aad.byteOffset + aad.byteLength
5756
+ )
5757
+ );
5758
+ const enc = new Uint8Array(sender.enc);
5759
+ const result = new Uint8Array(enc.length + ciphertext.byteLength);
5760
+ result.set(enc, 0);
5761
+ result.set(new Uint8Array(ciphertext), enc.length);
5762
+ return result;
5763
+ } catch (error) {
5764
+ throw HpkeError.encryptionFailed(
5765
+ error instanceof Error ? error : new Error(String(error))
5766
+ );
5767
+ }
5768
+ }
5769
+ async function encryptForRex(rexPubkey, data, senderPubkey) {
5770
+ const ciphertext = await hpkeEncrypt(rexPubkey, data, senderPubkey);
5771
+ return RexValue.encrypted(ciphertext);
5772
+ }
5773
+ function getCiphertextLength(plaintextLength) {
5774
+ return HPKE_OVERHEAD_LENGTH + plaintextLength;
5775
+ }
5776
+ function isValidCiphertextLength(ciphertext) {
5777
+ return ciphertext.length >= HPKE_OVERHEAD_LENGTH;
5778
+ }
5779
+
5481
5780
  // src/rpc/errors.ts
5482
5781
  var RpcErrorCode = /* @__PURE__ */ ((RpcErrorCode2) => {
5483
5782
  RpcErrorCode2["REQUEST_TIMEOUT"] = "REQUEST_TIMEOUT";
@@ -5736,9 +6035,7 @@ var QueryRpcClient = class extends BaseRpcClient {
5736
6035
  * ```
5737
6036
  */
5738
6037
  async getAccountInfo(pubkey) {
5739
- const result = await this.call("getAccountInfo", [
5740
- { address: pubkey.toString(), config: { encoding: "base64" } }
5741
- ]);
6038
+ const result = await this.call("getAccountInfo", [{ address: pubkey.toString() }]);
5742
6039
  if (!result.value) {
5743
6040
  return null;
5744
6041
  }
@@ -6026,10 +6323,9 @@ var QueryRpcClient = class extends BaseRpcClient {
6026
6323
  owner: owner.toString(),
6027
6324
  filter,
6028
6325
  config: config ? {
6029
- encoding: config.encoding ?? "base64",
6030
6326
  limit: config.limit,
6031
6327
  after: config.after
6032
- } : { encoding: "base64" }
6328
+ } : void 0
6033
6329
  }
6034
6330
  ]);
6035
6331
  return {
@@ -6168,6 +6464,64 @@ var QueryRpcClient = class extends BaseRpcClient {
6168
6464
  blockNumber: BigInt(tx.block_number)
6169
6465
  }));
6170
6466
  }
6467
+ /**
6468
+ * Retrieve the REX X25519 public key for secret sharing encryption.
6469
+ *
6470
+ * This key is used for HPKE encryption when sending encrypted data
6471
+ * that should only be decryptable within the REX execution environment.
6472
+ *
6473
+ * @returns The REX X25519 public key as a 32-byte Uint8Array
6474
+ *
6475
+ * @example
6476
+ * ```typescript
6477
+ * import { encryptForRex } from "@rialo/ts-cdk";
6478
+ *
6479
+ * // Get the REX public key
6480
+ * const rexPubkey = await client.getSecretSharingPubkey();
6481
+ *
6482
+ * // Use it for HPKE encryption
6483
+ * const encrypted = await encryptForRex(
6484
+ * rexPubkey,
6485
+ * new TextEncoder().encode("secret data"),
6486
+ * keypair.publicKey.toBytes()
6487
+ * );
6488
+ * ```
6489
+ */
6490
+ async getSecretSharingPubkey() {
6491
+ const result = await this.call(
6492
+ "getSecretSharingPubkey",
6493
+ []
6494
+ );
6495
+ const hexString = result.public_key;
6496
+ const bytes = new Uint8Array(hexString.length / 2);
6497
+ for (let i = 0; i < bytes.length; i++) {
6498
+ bytes[i] = Number.parseInt(hexString.slice(i * 2, i * 2 + 2), 16);
6499
+ }
6500
+ return bytes;
6501
+ }
6502
+ /**
6503
+ * Get the config hash prefix for replay protection.
6504
+ *
6505
+ * Returns the first 64 bits of the config hash, which is used
6506
+ * for transaction replay protection across chains.
6507
+ *
6508
+ * @returns The config hash prefix as a bigint
6509
+ *
6510
+ * @example
6511
+ * ```typescript
6512
+ * const configHashPrefix = await client.getConfigHashPrefix();
6513
+ * const tx = TransactionBuilder.create()
6514
+ * .setPayer(payer)
6515
+ * .setValidFrom(validFrom)
6516
+ * .setConfigHashPrefix(configHashPrefix)
6517
+ * .addInstruction(instruction)
6518
+ * .build();
6519
+ * ```
6520
+ */
6521
+ async getConfigHashPrefix() {
6522
+ const result = await this.call("getRecentValidatorConfigHash", [{}]);
6523
+ return BigInt(result.config_hash_prefix);
6524
+ }
6171
6525
  };
6172
6526
 
6173
6527
  // src/rpc/clients/transaction-client.ts
@@ -6796,189 +7150,219 @@ function getDefaultRialoClientConfig(network) {
6796
7150
  }
6797
7151
  }
6798
7152
 
6799
- // src/signer/keypair-signer.ts
6800
- var KeypairSigner = class {
6801
- constructor(keypair) {
6802
- this.keypair = keypair;
7153
+ // src/serialization/bincode/reader.ts
7154
+ var BincodeReader = class {
7155
+ view;
7156
+ offset;
7157
+ bytes;
7158
+ constructor(data) {
7159
+ this.bytes = data;
7160
+ this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
7161
+ this.offset = 0;
7162
+ }
7163
+ // ========== Position Management ==========
7164
+ getOffset() {
7165
+ return this.offset;
7166
+ }
7167
+ remaining() {
7168
+ return this.bytes.length - this.offset;
7169
+ }
7170
+ isExhausted() {
7171
+ return this.offset >= this.bytes.length;
7172
+ }
7173
+ skip(bytes) {
7174
+ this.ensureAvailable(bytes);
7175
+ this.offset += bytes;
7176
+ return this;
6803
7177
  }
6804
7178
  /**
6805
- * Returns the keypair's public key.
7179
+ * Peek at bytes without advancing the offset
6806
7180
  */
6807
- async getPublicKey() {
6808
- return this.keypair.publicKey;
7181
+ peek(length) {
7182
+ this.ensureAvailable(length);
7183
+ return this.bytes.slice(this.offset, this.offset + length);
6809
7184
  }
6810
7185
  /**
6811
- * Signs a message using the keypair's private key.
7186
+ * Reset reader to beginning
6812
7187
  */
6813
- async signMessage(message) {
6814
- return this.keypair.sign(message);
7188
+ reset() {
7189
+ this.offset = 0;
7190
+ return this;
6815
7191
  }
6816
- };
6817
-
6818
- // src/transaction/account-meta-table.ts
6819
- var AccountMetaTable = class {
6820
- accounts = /* @__PURE__ */ new Map();
6821
- accountOrder = [];
6822
7192
  /**
6823
- * Add or update an account in the table.
6824
- * If account already exists, merges signer/writable flags (OR operation).
7193
+ * Seek to specific offset
6825
7194
  */
6826
- add(meta) {
6827
- const key = meta.pubkey.toString();
6828
- if (this.accounts.has(key)) {
6829
- const existing = this.accounts.get(key);
6830
- existing.isSigner ||= meta.isSigner;
6831
- existing.isWritable ||= meta.isWritable;
6832
- } else {
6833
- this.accounts.set(key, {
6834
- pubkey: meta.pubkey,
6835
- isSigner: meta.isSigner,
6836
- isWritable: meta.isWritable
6837
- });
6838
- this.accountOrder.push(key);
7195
+ seek(offset) {
7196
+ if (offset < 0 || offset > this.bytes.length) {
7197
+ throw new Error(
7198
+ `Invalid seek offset: ${offset}, buffer length: ${this.bytes.length}`
7199
+ );
6839
7200
  }
7201
+ this.offset = offset;
7202
+ return this;
6840
7203
  }
6841
- /**
6842
- * Add multiple accounts at once.
6843
- */
6844
- addAll(metas) {
6845
- for (const meta of metas) {
6846
- this.add(meta);
7204
+ // ========== Primitive Types ==========
7205
+ readU8() {
7206
+ this.ensureAvailable(1);
7207
+ const value = this.view.getUint8(this.offset);
7208
+ this.offset += 1;
7209
+ return value;
7210
+ }
7211
+ readU16() {
7212
+ this.ensureAvailable(2);
7213
+ const value = this.view.getUint16(this.offset, true);
7214
+ this.offset += 2;
7215
+ return value;
7216
+ }
7217
+ readU32() {
7218
+ this.ensureAvailable(4);
7219
+ const value = this.view.getUint32(this.offset, true);
7220
+ this.offset += 4;
7221
+ return value;
7222
+ }
7223
+ readU64() {
7224
+ this.ensureAvailable(8);
7225
+ const low = this.view.getUint32(this.offset, true);
7226
+ const high = this.view.getUint32(this.offset + 4, true);
7227
+ this.offset += 8;
7228
+ return BigInt(low) | BigInt(high) << 32n;
7229
+ }
7230
+ readU128() {
7231
+ this.ensureAvailable(16);
7232
+ const low = this.readU64();
7233
+ const high = this.readU64();
7234
+ return low | high << 64n;
7235
+ }
7236
+ readI8() {
7237
+ this.ensureAvailable(1);
7238
+ const value = this.view.getInt8(this.offset);
7239
+ this.offset += 1;
7240
+ return value;
7241
+ }
7242
+ readI16() {
7243
+ this.ensureAvailable(2);
7244
+ const value = this.view.getInt16(this.offset, true);
7245
+ this.offset += 2;
7246
+ return value;
7247
+ }
7248
+ readI32() {
7249
+ this.ensureAvailable(4);
7250
+ const value = this.view.getInt32(this.offset, true);
7251
+ this.offset += 4;
7252
+ return value;
7253
+ }
7254
+ readI64() {
7255
+ this.ensureAvailable(8);
7256
+ const low = this.view.getUint32(this.offset, true);
7257
+ const high = this.view.getInt32(this.offset + 4, true);
7258
+ this.offset += 8;
7259
+ return BigInt(low) | BigInt(high) << 32n;
7260
+ }
7261
+ readI128() {
7262
+ const unsigned = this.readU128();
7263
+ const signBit = 1n << 127n;
7264
+ if ((unsigned & signBit) !== 0n) {
7265
+ return unsigned - (1n << 128n);
6847
7266
  }
7267
+ return unsigned;
6848
7268
  }
6849
- /**
6850
- * Get the index of an account in the sorted order.
6851
- * Returns -1 if account not found.
6852
- */
6853
- getIndex(pubkey) {
6854
- const sorted = this.getSortedAccounts();
6855
- return sorted.findIndex((entry) => entry.pubkey.equals(pubkey));
7269
+ readF32() {
7270
+ this.ensureAvailable(4);
7271
+ const value = this.view.getFloat32(this.offset, true);
7272
+ this.offset += 4;
7273
+ return value;
7274
+ }
7275
+ readF64() {
7276
+ this.ensureAvailable(8);
7277
+ const value = this.view.getFloat64(this.offset, true);
7278
+ this.offset += 8;
7279
+ return value;
7280
+ }
7281
+ readBool() {
7282
+ const value = this.readU8();
7283
+ if (value > 1) {
7284
+ throw new Error(`Invalid boolean value: ${value}`);
7285
+ }
7286
+ return value === 1;
7287
+ }
7288
+ // ========== Compound Types ==========
7289
+ readBytes(length) {
7290
+ this.ensureAvailable(length);
7291
+ const bytes = this.bytes.slice(this.offset, this.offset + length);
7292
+ this.offset += length;
7293
+ return bytes;
7294
+ }
7295
+ readFixedArray(length) {
7296
+ return this.readBytes(length);
7297
+ }
7298
+ readVecBytes() {
7299
+ const length = this.readLength();
7300
+ return this.readBytes(length);
7301
+ }
7302
+ readString() {
7303
+ const bytes = this.readVecBytes();
7304
+ return new TextDecoder().decode(bytes);
7305
+ }
7306
+ readVariant() {
7307
+ return this.readU32();
7308
+ }
7309
+ readOption(readValue2) {
7310
+ const hasValue = this.readU8();
7311
+ if (hasValue === 0) {
7312
+ return null;
7313
+ }
7314
+ if (hasValue !== 1) {
7315
+ throw new Error(`Invalid option discriminant: ${hasValue}`);
7316
+ }
7317
+ return readValue2();
7318
+ }
7319
+ readVec(readElement) {
7320
+ const length = this.readLength();
7321
+ const result = [];
7322
+ for (let i = 0; i < length; i++) {
7323
+ result.push(readElement());
7324
+ }
7325
+ return result;
6856
7326
  }
6857
7327
  /**
6858
- * Get sorted accounts according to transaction rules.
7328
+ * Read a tuple of fixed size with heterogeneous types
6859
7329
  */
6860
- getSortedAccounts() {
6861
- const entries = this.accountOrder.map((key) => this.accounts.get(key));
6862
- return entries.sort((a, b) => {
6863
- const aPriority = a.isSigner && a.isWritable ? 0 : a.isSigner ? 1 : a.isWritable ? 2 : 3;
6864
- const bPriority = b.isSigner && b.isWritable ? 0 : b.isSigner ? 1 : b.isWritable ? 2 : 3;
6865
- if (aPriority !== bPriority) {
6866
- return aPriority - bPriority;
6867
- }
6868
- const aBytes = a.pubkey.toBytes();
6869
- const bBytes = b.pubkey.toBytes();
6870
- for (let i = 0; i < 32; i++) {
6871
- if (aBytes[i] !== bBytes[i]) {
6872
- return aBytes[i] - bBytes[i];
6873
- }
6874
- }
6875
- return 0;
6876
- });
7330
+ readTuple(readers) {
7331
+ return readers.map((read) => read());
7332
+ }
7333
+ readMap(readKey, readValue2) {
7334
+ const length = this.readLength();
7335
+ const map = /* @__PURE__ */ new Map();
7336
+ for (let i = 0; i < length; i++) {
7337
+ const key = readKey();
7338
+ const value = readValue2();
7339
+ map.set(key, value);
7340
+ }
7341
+ return map;
6877
7342
  }
7343
+ // ========== Helpers ==========
6878
7344
  /**
6879
- * Get the message header based on sorted accounts.
7345
+ * Read length as u64 but validate it's within safe integer range
6880
7346
  */
6881
- getHeader() {
6882
- const sorted = this.getSortedAccounts();
6883
- let numRequiredSignatures = 0;
6884
- let numReadonlySignedAccounts = 0;
6885
- let numReadonlyUnsignedAccounts = 0;
6886
- for (const entry of sorted) {
6887
- if (entry.isSigner) {
6888
- numRequiredSignatures++;
6889
- if (!entry.isWritable) {
6890
- numReadonlySignedAccounts++;
6891
- }
6892
- } else if (!entry.isWritable) {
6893
- numReadonlyUnsignedAccounts++;
6894
- }
7347
+ readLength() {
7348
+ const length = this.readU64();
7349
+ if (length > BigInt(Number.MAX_SAFE_INTEGER)) {
7350
+ throw new Error(`Length ${length} exceeds maximum safe integer`);
6895
7351
  }
6896
- return {
6897
- numRequiredSignatures,
6898
- numReadonlySignedAccounts,
6899
- numReadonlyUnsignedAccounts
6900
- };
6901
- }
6902
- /**
6903
- * Get sorted public keys.
6904
- */
6905
- getPublicKeys() {
6906
- return this.getSortedAccounts().map((entry) => entry.pubkey);
6907
- }
6908
- /**
6909
- * Get number of accounts in table.
6910
- */
6911
- size() {
6912
- return this.accounts.size;
6913
- }
6914
- };
6915
-
6916
- // src/transaction/errors.ts
6917
- var TransactionErrorCode = /* @__PURE__ */ ((TransactionErrorCode2) => {
6918
- TransactionErrorCode2["INVALID_INSTRUCTION"] = "INVALID_INSTRUCTION";
6919
- TransactionErrorCode2["INVALID_ACCOUNT_META"] = "INVALID_ACCOUNT_META";
6920
- TransactionErrorCode2["NO_INSTRUCTIONS"] = "NO_INSTRUCTIONS";
6921
- TransactionErrorCode2["DUPLICATE_ACCOUNT"] = "DUPLICATE_ACCOUNT";
6922
- TransactionErrorCode2["MISSING_SIGNATURE"] = "MISSING_SIGNATURE";
6923
- TransactionErrorCode2["INVALID_SIGNATURE"] = "INVALID_SIGNATURE";
6924
- TransactionErrorCode2["SIGNATURE_OUT_OF_BOUNDS"] = "SIGNATURE_OUT_OF_BOUNDS";
6925
- TransactionErrorCode2["SIGNER_NOT_FOUND"] = "SIGNER_NOT_FOUND";
6926
- TransactionErrorCode2["ALREADY_SIGNED"] = "ALREADY_SIGNED";
6927
- TransactionErrorCode2["INVALID_MESSAGE_FORMAT"] = "INVALID_MESSAGE_FORMAT";
6928
- TransactionErrorCode2["INSUFFICIENT_DATA"] = "INSUFFICIENT_DATA";
6929
- TransactionErrorCode2["SERIALIZATION_FAILED"] = "SERIALIZATION_FAILED";
6930
- TransactionErrorCode2["SIMULATION_FAILED"] = "SIMULATION_FAILED";
6931
- TransactionErrorCode2["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
6932
- TransactionErrorCode2["BLOCKHASH_EXPIRED"] = "BLOCKHASH_EXPIRED";
6933
- return TransactionErrorCode2;
6934
- })(TransactionErrorCode || {});
6935
- var TransactionError = class _TransactionError extends Error {
6936
- constructor(code, message, details) {
6937
- super(message);
6938
- this.code = code;
6939
- this.details = details;
6940
- this.name = "TransactionError";
6941
- }
6942
- static noInstructions() {
6943
- return new _TransactionError(
6944
- "NO_INSTRUCTIONS" /* NO_INSTRUCTIONS */,
6945
- "Transaction must contain at least one instruction. Use addInstruction() to add instructions."
6946
- );
6947
- }
6948
- static signerNotFound(pubkey) {
6949
- return new _TransactionError(
6950
- "SIGNER_NOT_FOUND" /* SIGNER_NOT_FOUND */,
6951
- `Public key ${pubkey} is not a required signer for this transaction. Check that the account is marked as a signer in the instruction.`,
6952
- { pubkey }
6953
- );
6954
- }
6955
- static missingSignature(index, pubkey) {
6956
- return new _TransactionError(
6957
- "MISSING_SIGNATURE" /* MISSING_SIGNATURE */,
6958
- `Missing signature for signer ${index} (${pubkey}). Transaction requires ${index + 1} signatures.`,
6959
- { index, pubkey }
6960
- );
6961
- }
6962
- static simulationFailed(logs, error) {
6963
- return new _TransactionError(
6964
- "SIMULATION_FAILED" /* SIMULATION_FAILED */,
6965
- `Transaction simulation failed: ${error}`,
6966
- { logs, error }
6967
- );
6968
- }
6969
- static insufficientFunds(required, available) {
6970
- return new _TransactionError(
6971
- "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */,
6972
- `Insufficient funds: need ${required}, have ${available}`,
6973
- { required: required.toString(), available: available.toString() }
6974
- );
7352
+ const numLength = Number(length);
7353
+ if (numLength > this.remaining()) {
7354
+ throw new Error(
7355
+ `Length ${numLength} exceeds remaining bytes ${this.remaining()}`
7356
+ );
7357
+ }
7358
+ return numLength;
6975
7359
  }
6976
- toJSON() {
6977
- return {
6978
- code: this.code,
6979
- message: this.message,
6980
- details: this.details
6981
- };
7360
+ ensureAvailable(bytes) {
7361
+ if (this.offset + bytes > this.bytes.length) {
7362
+ throw new Error(
7363
+ `Unexpected end of data: need ${bytes} bytes at offset ${this.offset}, but only ${this.bytes.length - this.offset} available`
7364
+ );
7365
+ }
6982
7366
  }
6983
7367
  };
6984
7368
 
@@ -7140,12 +7524,12 @@ var BincodeWriter = class {
7140
7524
  writeVariant(index) {
7141
7525
  return this.writeU32(index);
7142
7526
  }
7143
- writeOption(value, writeValue) {
7527
+ writeOption(value, writeValue2) {
7144
7528
  if (value === null || value === void 0) {
7145
7529
  this.writeU8(0);
7146
7530
  } else {
7147
7531
  this.writeU8(1);
7148
- writeValue(this, value);
7532
+ writeValue2(this, value);
7149
7533
  }
7150
7534
  return this;
7151
7535
  }
@@ -7168,11 +7552,11 @@ var BincodeWriter = class {
7168
7552
  }
7169
7553
  return this;
7170
7554
  }
7171
- writeMap(map, writeKey, writeValue) {
7555
+ writeMap(map, writeKey, writeValue2) {
7172
7556
  this.writeU64(BigInt(map.size));
7173
7557
  for (const [key, value] of map) {
7174
7558
  writeKey(this, key);
7175
- writeValue(this, value);
7559
+ writeValue2(this, value);
7176
7560
  }
7177
7561
  return this;
7178
7562
  }
@@ -7225,11 +7609,366 @@ var BincodeWriter = class {
7225
7609
  }
7226
7610
  };
7227
7611
 
7612
+ // src/serialization/bincode/schema.ts
7613
+ var Schema = {
7614
+ u8: () => ({ type: "u8" }),
7615
+ u16: () => ({ type: "u16" }),
7616
+ u32: () => ({ type: "u32" }),
7617
+ u64: () => ({ type: "u64" }),
7618
+ u128: () => ({ type: "u128" }),
7619
+ i8: () => ({ type: "i8" }),
7620
+ i16: () => ({ type: "i16" }),
7621
+ i32: () => ({ type: "i32" }),
7622
+ i64: () => ({ type: "i64" }),
7623
+ i128: () => ({ type: "i128" }),
7624
+ f32: () => ({ type: "f32" }),
7625
+ f64: () => ({ type: "f64" }),
7626
+ bool: () => ({ type: "bool" }),
7627
+ string: () => ({ type: "string" }),
7628
+ bytes: () => ({ type: "bytes" }),
7629
+ unit: () => ({ type: "unit" }),
7630
+ fixedArray: (length) => ({
7631
+ type: "fixedArray",
7632
+ length
7633
+ }),
7634
+ vec: (element) => ({
7635
+ type: "vec",
7636
+ element
7637
+ }),
7638
+ option: (inner) => ({
7639
+ type: "option",
7640
+ inner
7641
+ }),
7642
+ tuple: (...elements) => ({
7643
+ type: "tuple",
7644
+ elements
7645
+ }),
7646
+ /**
7647
+ * Define a struct with ordered fields
7648
+ * @example
7649
+ * Schema.struct([
7650
+ * ["id", Schema.u64()],
7651
+ * ["name", Schema.string()],
7652
+ * ["active", Schema.bool()],
7653
+ * ])
7654
+ */
7655
+ struct: (fields) => ({
7656
+ type: "struct",
7657
+ fields: fields.map(([name, schema]) => ({ name, schema }))
7658
+ }),
7659
+ /**
7660
+ * Define an enum with ordered variants
7661
+ * @example
7662
+ * Schema.enum([
7663
+ * ["None", null],
7664
+ * ["Some", Schema.u64()],
7665
+ * ["Error", Schema.string()],
7666
+ * ])
7667
+ */
7668
+ enum: (variants) => ({
7669
+ type: "enum",
7670
+ variants: variants.map(([name, schema]) => ({ name, schema }))
7671
+ }),
7672
+ map: (key, value) => ({
7673
+ type: "map",
7674
+ key,
7675
+ value
7676
+ }),
7677
+ pubkey: () => ({ type: "pubkey" })
7678
+ };
7679
+ function serialize(schema, value) {
7680
+ const writer = new BincodeWriter();
7681
+ writeValue(writer, schema, value);
7682
+ return writer.toBytes();
7683
+ }
7684
+ function deserialize(schema, data) {
7685
+ const reader = new BincodeReader(data);
7686
+ const result = readValue(reader, schema);
7687
+ if (!reader.isExhausted()) {
7688
+ console.warn(
7689
+ `Bincode deserialize: ${reader.remaining()} bytes remaining after parsing`
7690
+ );
7691
+ }
7692
+ return result;
7693
+ }
7694
+ function deserializeStrict(schema, data) {
7695
+ const reader = new BincodeReader(data);
7696
+ const result = readValue(reader, schema);
7697
+ if (!reader.isExhausted()) {
7698
+ throw new Error(
7699
+ `Unexpected data: ${reader.remaining()} bytes remaining after parsing`
7700
+ );
7701
+ }
7702
+ return result;
7703
+ }
7704
+ function writeValue(writer, schema, value) {
7705
+ switch (schema.type) {
7706
+ case "u8":
7707
+ writer.writeU8(value);
7708
+ break;
7709
+ case "u16":
7710
+ writer.writeU16(value);
7711
+ break;
7712
+ case "u32":
7713
+ writer.writeU32(value);
7714
+ break;
7715
+ case "u64":
7716
+ writer.writeU64(value);
7717
+ break;
7718
+ case "u128":
7719
+ writer.writeU128(value);
7720
+ break;
7721
+ case "i8":
7722
+ writer.writeI8(value);
7723
+ break;
7724
+ case "i16":
7725
+ writer.writeI16(value);
7726
+ break;
7727
+ case "i32":
7728
+ writer.writeI32(value);
7729
+ break;
7730
+ case "i64":
7731
+ writer.writeI64(value);
7732
+ break;
7733
+ case "i128":
7734
+ writer.writeI128(value);
7735
+ break;
7736
+ case "f32":
7737
+ writer.writeF32(value);
7738
+ break;
7739
+ case "f64":
7740
+ writer.writeF64(value);
7741
+ break;
7742
+ case "bool":
7743
+ writer.writeBool(value);
7744
+ break;
7745
+ case "string":
7746
+ writer.writeString(value);
7747
+ break;
7748
+ case "bytes":
7749
+ writer.writeVecBytes(value);
7750
+ break;
7751
+ case "unit":
7752
+ break;
7753
+ case "fixedArray": {
7754
+ const arr = value;
7755
+ if (arr.length !== schema.length) {
7756
+ throw new Error(
7757
+ `Fixed array length mismatch: expected ${schema.length}, got ${arr.length}`
7758
+ );
7759
+ }
7760
+ writer.writeFixedArray(arr);
7761
+ break;
7762
+ }
7763
+ case "pubkey": {
7764
+ const arr = value;
7765
+ if (arr.length !== 32) {
7766
+ throw new Error(`Pubkey must be exactly 32 bytes, got ${arr.length}`);
7767
+ }
7768
+ writer.writeFixedArray(arr);
7769
+ break;
7770
+ }
7771
+ case "vec": {
7772
+ const arr = value;
7773
+ writer.writeU64(BigInt(arr.length));
7774
+ for (const item of arr) {
7775
+ writeValue(writer, schema.element, item);
7776
+ }
7777
+ break;
7778
+ }
7779
+ case "option": {
7780
+ if (value === null || value === void 0) {
7781
+ writer.writeU8(0);
7782
+ } else {
7783
+ writer.writeU8(1);
7784
+ writeValue(writer, schema.inner, value);
7785
+ }
7786
+ break;
7787
+ }
7788
+ case "tuple": {
7789
+ const arr = value;
7790
+ if (arr.length !== schema.elements.length) {
7791
+ throw new Error(
7792
+ `Tuple length mismatch: expected ${schema.elements.length}, got ${arr.length}`
7793
+ );
7794
+ }
7795
+ for (let i = 0; i < schema.elements.length; i++) {
7796
+ writeValue(writer, schema.elements[i], arr[i]);
7797
+ }
7798
+ break;
7799
+ }
7800
+ case "struct": {
7801
+ const obj = value;
7802
+ for (const field2 of schema.fields) {
7803
+ if (!(field2.name in obj)) {
7804
+ throw new Error(`Missing struct field: ${field2.name}`);
7805
+ }
7806
+ writeValue(writer, field2.schema, obj[field2.name]);
7807
+ }
7808
+ break;
7809
+ }
7810
+ case "enum": {
7811
+ const enumValue = value;
7812
+ const variantIndex = schema.variants.findIndex(
7813
+ (v) => v.name === enumValue.variant
7814
+ );
7815
+ if (variantIndex === -1) {
7816
+ const validVariants = schema.variants.map((v) => v.name).join(", ");
7817
+ throw new Error(
7818
+ `Unknown variant: ${enumValue.variant}. Valid variants: ${validVariants}`
7819
+ );
7820
+ }
7821
+ writer.writeVariant(variantIndex);
7822
+ const variantSchema = schema.variants[variantIndex].schema;
7823
+ if (variantSchema !== null) {
7824
+ writeValue(writer, variantSchema, enumValue.value);
7825
+ }
7826
+ break;
7827
+ }
7828
+ case "map": {
7829
+ const map = value;
7830
+ writer.writeU64(BigInt(map.size));
7831
+ for (const [k, v] of map) {
7832
+ writeValue(writer, schema.key, k);
7833
+ writeValue(writer, schema.value, v);
7834
+ }
7835
+ break;
7836
+ }
7837
+ default: {
7838
+ throw new Error(`Unknown schema type: ${JSON.stringify(schema)}`);
7839
+ }
7840
+ }
7841
+ }
7842
+ function readValue(reader, schema) {
7843
+ switch (schema.type) {
7844
+ case "u8":
7845
+ return reader.readU8();
7846
+ case "u16":
7847
+ return reader.readU16();
7848
+ case "u32":
7849
+ return reader.readU32();
7850
+ case "u64":
7851
+ return reader.readU64();
7852
+ case "u128":
7853
+ return reader.readU128();
7854
+ case "i8":
7855
+ return reader.readI8();
7856
+ case "i16":
7857
+ return reader.readI16();
7858
+ case "i32":
7859
+ return reader.readI32();
7860
+ case "i64":
7861
+ return reader.readI64();
7862
+ case "i128":
7863
+ return reader.readI128();
7864
+ case "f32":
7865
+ return reader.readF32();
7866
+ case "f64":
7867
+ return reader.readF64();
7868
+ case "bool":
7869
+ return reader.readBool();
7870
+ case "string":
7871
+ return reader.readString();
7872
+ case "bytes":
7873
+ return reader.readVecBytes();
7874
+ case "unit":
7875
+ return void 0;
7876
+ case "fixedArray":
7877
+ return reader.readFixedArray(schema.length);
7878
+ case "pubkey":
7879
+ return reader.readFixedArray(32);
7880
+ case "vec": {
7881
+ const lengthBigInt = reader.readU64();
7882
+ if (lengthBigInt > BigInt(Number.MAX_SAFE_INTEGER)) {
7883
+ throw new Error(
7884
+ `Vec length ${lengthBigInt} exceeds safe integer range`
7885
+ );
7886
+ }
7887
+ const length = Number(lengthBigInt);
7888
+ const result = [];
7889
+ for (let i = 0; i < length; i++) {
7890
+ result.push(readValue(reader, schema.element));
7891
+ }
7892
+ return result;
7893
+ }
7894
+ case "option": {
7895
+ const hasValue = reader.readU8();
7896
+ if (hasValue === 0) return null;
7897
+ if (hasValue !== 1) {
7898
+ throw new Error(`Invalid option discriminant: ${hasValue}`);
7899
+ }
7900
+ return readValue(reader, schema.inner);
7901
+ }
7902
+ case "tuple": {
7903
+ const result = [];
7904
+ for (const elementSchema of schema.elements) {
7905
+ result.push(readValue(reader, elementSchema));
7906
+ }
7907
+ return result;
7908
+ }
7909
+ case "struct": {
7910
+ const result = {};
7911
+ for (const field2 of schema.fields) {
7912
+ result[field2.name] = readValue(reader, field2.schema);
7913
+ }
7914
+ return result;
7915
+ }
7916
+ case "enum": {
7917
+ const variantIndex = reader.readVariant();
7918
+ if (variantIndex >= schema.variants.length) {
7919
+ throw new Error(
7920
+ `Invalid variant index: ${variantIndex}, max: ${schema.variants.length - 1}`
7921
+ );
7922
+ }
7923
+ const variant = schema.variants[variantIndex];
7924
+ if (variant.schema === null) {
7925
+ return { variant: variant.name };
7926
+ }
7927
+ return {
7928
+ variant: variant.name,
7929
+ value: readValue(reader, variant.schema)
7930
+ };
7931
+ }
7932
+ case "map": {
7933
+ const lengthBigInt = reader.readU64();
7934
+ if (lengthBigInt > BigInt(Number.MAX_SAFE_INTEGER)) {
7935
+ throw new Error(
7936
+ `Map length ${lengthBigInt} exceeds safe integer range`
7937
+ );
7938
+ }
7939
+ const length = Number(lengthBigInt);
7940
+ const map = /* @__PURE__ */ new Map();
7941
+ for (let i = 0; i < length; i++) {
7942
+ const key = readValue(reader, schema.key);
7943
+ const value = readValue(reader, schema.value);
7944
+ map.set(key, value);
7945
+ }
7946
+ return map;
7947
+ }
7948
+ default: {
7949
+ const _exhaustive = schema;
7950
+ throw new Error(
7951
+ `Unknown schema type: ${_exhaustive.type}`
7952
+ );
7953
+ }
7954
+ }
7955
+ }
7956
+
7228
7957
  // node_modules/@dao-xyz/borsh/lib/esm/binary.js
7229
7958
  var import_float = __toESM(require_float());
7230
7959
  var import_utf8 = __toESM(require_utf8());
7231
7960
 
7232
7961
  // node_modules/@dao-xyz/borsh/lib/esm/bigint.js
7962
+ function arrayToHex(arr, reverse = false) {
7963
+ return [...reverse ? new Uint8Array(arr).reverse() : new Uint8Array(arr)].map((b) => b.toString(16).padStart(2, "0")).join("");
7964
+ }
7965
+ function toBigIntLE(buf) {
7966
+ const hex = arrayToHex(buf, true);
7967
+ if (hex.length === 0) {
7968
+ return BigInt(0);
7969
+ }
7970
+ return BigInt(`0x${hex}`);
7971
+ }
7233
7972
  function writeBufferLEBigInt(num, width, buffer, offset) {
7234
7973
  const hex = num.toString(16);
7235
7974
  const padded = hex.padStart(width * 2, "0").slice(0, width * 2);
@@ -7282,6 +8021,39 @@ var writeBigUint64Le = (bigIntOrNumber, buf, offset) => {
7282
8021
  buf[offset + 6] = hi >>> 16;
7283
8022
  buf[offset + 7] = hi >>> 24;
7284
8023
  };
8024
+ var readBigUInt64LE = (buf, offset) => {
8025
+ const first = buf[offset];
8026
+ const last = buf[offset + 7];
8027
+ if (first === void 0 || last === void 0)
8028
+ throw new Error("Out of bounds");
8029
+ let lo = (first | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
8030
+ let hi = (buf[offset + 4] | buf[offset + 5] << 8 | buf[offset + 6] << 16 | last << 24) >>> 0;
8031
+ if (hi > 0) {
8032
+ return BigInt(lo) + (BigInt(hi) << 32n);
8033
+ }
8034
+ return BigInt(lo);
8035
+ };
8036
+ function readUIntLE(buf, offset, width) {
8037
+ const hex = arrayToHex(buf.subarray(offset, offset + width), true);
8038
+ if (hex.length === 0) {
8039
+ return BigInt(0);
8040
+ }
8041
+ return BigInt(`0x${hex}`);
8042
+ }
8043
+ var readUInt32LE = (buffer, offset) => {
8044
+ const first = buffer[offset];
8045
+ const last = buffer[offset + 3];
8046
+ if (first === void 0 || last === void 0)
8047
+ throw new Error("Out of bounds");
8048
+ return first + buffer[offset + 1] * 2 ** 8 + buffer[offset + 2] * 2 ** 16 + last * 2 ** 24;
8049
+ };
8050
+ var readUInt16LE = (buffer, offset) => {
8051
+ const first = buffer[offset];
8052
+ const last = buffer[offset + 1];
8053
+ if (first === void 0 || last === void 0)
8054
+ throw new Error("Out of bounds");
8055
+ return first + last * 2 ** 8;
8056
+ };
7285
8057
  var checkInt = (value, min, max, byteLength) => {
7286
8058
  if (value > max || value < min) {
7287
8059
  const n = "";
@@ -7532,6 +8304,205 @@ var BinaryWriter = class _BinaryWriter {
7532
8304
  return this._buf;
7533
8305
  }
7534
8306
  };
8307
+ var BinaryReader = class _BinaryReader {
8308
+ constructor(buf) {
8309
+ this._buf = buf;
8310
+ this._offset = 0;
8311
+ }
8312
+ bool() {
8313
+ return _BinaryReader.bool(this);
8314
+ }
8315
+ static bool(reader) {
8316
+ const value = reader._buf[reader._offset];
8317
+ reader._offset += 1;
8318
+ if (value !== 1 && value !== 0) {
8319
+ throw new BorshError("Unexpected value for boolean: " + value + ". Expecting either 1 or 0 ");
8320
+ }
8321
+ return value ? true : false;
8322
+ }
8323
+ u8() {
8324
+ return _BinaryReader.u8(this);
8325
+ }
8326
+ static u8(reader) {
8327
+ if (reader._offset >= reader._buf.length) {
8328
+ throw new BorshError("Reader out of bounds");
8329
+ }
8330
+ const value = reader._buf[reader._offset];
8331
+ reader._offset += 1;
8332
+ return value;
8333
+ }
8334
+ u16() {
8335
+ return _BinaryReader.u16(this);
8336
+ }
8337
+ static u16(reader) {
8338
+ const value = readUInt16LE(reader._buf, reader._offset);
8339
+ reader._offset += 2;
8340
+ return value;
8341
+ }
8342
+ u32() {
8343
+ return _BinaryReader.u32(this);
8344
+ }
8345
+ static u32(reader) {
8346
+ const value = readUInt32LE(reader._buf, reader._offset);
8347
+ reader._offset += 4;
8348
+ return value;
8349
+ }
8350
+ u64() {
8351
+ return _BinaryReader.u64(this);
8352
+ }
8353
+ static u64(reader) {
8354
+ const value = readBigUInt64LE(reader._buf, reader._offset);
8355
+ reader._offset += 8;
8356
+ return value;
8357
+ }
8358
+ u128() {
8359
+ return _BinaryReader.u128(this);
8360
+ }
8361
+ static u128(reader) {
8362
+ const value = readUIntLE(reader._buf, reader._offset, 16);
8363
+ reader._offset += 16;
8364
+ return value;
8365
+ }
8366
+ u256() {
8367
+ return _BinaryReader.u256(this);
8368
+ }
8369
+ static u256(reader) {
8370
+ const value = readUIntLE(reader._buf, reader._offset, 32);
8371
+ reader._offset += 32;
8372
+ return value;
8373
+ }
8374
+ u512() {
8375
+ return _BinaryReader.u512(this);
8376
+ }
8377
+ static u512(reader) {
8378
+ const buf = reader.buffer(64);
8379
+ return toBigIntLE(buf);
8380
+ }
8381
+ f32() {
8382
+ return _BinaryReader.f32(this);
8383
+ }
8384
+ static f32(reader) {
8385
+ const value = (0, import_float.readFloatLE)(reader._buf, reader._offset);
8386
+ reader._offset += 4;
8387
+ if (Number.isNaN(value)) {
8388
+ throw new BorshError("Recieved NaN reading f32");
8389
+ }
8390
+ return value;
8391
+ }
8392
+ f64() {
8393
+ return _BinaryReader.f64(this);
8394
+ }
8395
+ static f64(reader) {
8396
+ const value = (0, import_float.readDoubleLE)(reader._buf, reader._offset);
8397
+ reader._offset += 8;
8398
+ if (Number.isNaN(value)) {
8399
+ throw new BorshError("Recieved NaN reading f64");
8400
+ }
8401
+ return value;
8402
+ }
8403
+ string() {
8404
+ return _BinaryReader.string(this);
8405
+ }
8406
+ static string(reader) {
8407
+ const len = reader.u32();
8408
+ const end = reader._offset + len;
8409
+ if (end > reader._buf.length) {
8410
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8411
+ }
8412
+ try {
8413
+ const string = import_utf8.default.read(reader._buf, reader._offset, end);
8414
+ reader._offset = end;
8415
+ return string;
8416
+ } catch (e) {
8417
+ throw new BorshError(`Error decoding UTF-8 string: ${e}`);
8418
+ }
8419
+ }
8420
+ static bufferString(reader) {
8421
+ const len = reader.u32();
8422
+ const end = reader._offset + len;
8423
+ if (end > reader._buf.length) {
8424
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8425
+ }
8426
+ const string = reader._buf.toString(void 0, reader._offset, end);
8427
+ reader._offset = end;
8428
+ return string;
8429
+ }
8430
+ static bufferStringCustom(reader, length) {
8431
+ const len = length(reader);
8432
+ const end = reader._offset + len;
8433
+ if (end > reader._buf.length) {
8434
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8435
+ }
8436
+ try {
8437
+ const string = reader._buf.toString(void 0, reader._offset, end);
8438
+ reader._offset = end;
8439
+ return string;
8440
+ } catch (e) {
8441
+ throw new BorshError(`Error decoding UTF-8 string: ${e}`);
8442
+ }
8443
+ }
8444
+ static stringCustom(reader, length) {
8445
+ const len = length(reader);
8446
+ const end = reader._offset + len;
8447
+ if (end > reader._buf.length) {
8448
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8449
+ }
8450
+ try {
8451
+ const string = import_utf8.default.read(reader._buf, reader._offset, end);
8452
+ reader._offset = end;
8453
+ return string;
8454
+ } catch (e) {
8455
+ throw new BorshError(`Error decoding UTF-8 string: ${e}`);
8456
+ }
8457
+ }
8458
+ static read(encoding, fromBuffer) {
8459
+ if (encoding === "u8") {
8460
+ return _BinaryReader.u8;
8461
+ } else if (encoding === "u16") {
8462
+ return _BinaryReader.u16;
8463
+ } else if (encoding === "u32") {
8464
+ return _BinaryReader.u32;
8465
+ } else if (encoding === "u64") {
8466
+ return _BinaryReader.u64;
8467
+ } else if (encoding === "u128") {
8468
+ return _BinaryReader.u128;
8469
+ } else if (encoding === "u256") {
8470
+ return _BinaryReader.u256;
8471
+ } else if (encoding === "u512") {
8472
+ return _BinaryReader.u512;
8473
+ } else if (encoding === "string") {
8474
+ return fromBuffer ? _BinaryReader.bufferString : _BinaryReader.string;
8475
+ } else if (encoding === "bool") {
8476
+ return _BinaryReader.bool;
8477
+ } else if (encoding === "f32") {
8478
+ return _BinaryReader.f32;
8479
+ } else if (encoding === "f64") {
8480
+ return _BinaryReader.f64;
8481
+ } else {
8482
+ throw new Error("Unsupported encoding: " + encoding);
8483
+ }
8484
+ }
8485
+ buffer(len) {
8486
+ const end = this._offset + len;
8487
+ const result = this._buf.subarray(this._offset, end);
8488
+ this._offset = end;
8489
+ return result;
8490
+ }
8491
+ uint8Array() {
8492
+ return _BinaryReader.uint8Array(this);
8493
+ }
8494
+ static uint8Array(reader, size = reader.u32()) {
8495
+ return reader.buffer(size);
8496
+ }
8497
+ readArray(fn) {
8498
+ const len = this.u32();
8499
+ const result = new Array(len);
8500
+ for (let i = 0; i < len; ++i) {
8501
+ result[i] = fn();
8502
+ }
8503
+ return result;
8504
+ }
8505
+ };
7535
8506
 
7536
8507
  // node_modules/@dao-xyz/borsh/lib/esm/types.js
7537
8508
  var extendingClasses = (clazz) => {
@@ -7570,18 +8541,53 @@ var StringType = class {
7570
8541
  };
7571
8542
  var OptionKind = class extends WrappedType {
7572
8543
  };
8544
+ var option = (type) => {
8545
+ return new OptionKind(type);
8546
+ };
7573
8547
  var VecKind = class extends WrappedType {
7574
8548
  constructor(elementType, sizeEncoding) {
7575
8549
  super(elementType);
7576
8550
  this.sizeEncoding = sizeEncoding;
7577
8551
  }
7578
8552
  };
8553
+ var vec = (type, sizeEncoding = "u32") => {
8554
+ return new VecKind(type, sizeEncoding);
8555
+ };
7579
8556
  var FixedArrayKind = class extends WrappedType {
7580
8557
  constructor(type, length) {
7581
8558
  super(type);
7582
8559
  this.length = length;
7583
8560
  }
7584
8561
  };
8562
+ var fixedArray = (type, length) => {
8563
+ return new FixedArrayKind(type, length);
8564
+ };
8565
+ var StructKind = class {
8566
+ constructor(properties) {
8567
+ if (properties) {
8568
+ this.fields = properties.fields;
8569
+ this.variant = properties.variant;
8570
+ } else {
8571
+ this.fields = [];
8572
+ }
8573
+ }
8574
+ getDependencies() {
8575
+ let ret = [];
8576
+ this.fields.forEach((field2, ix) => {
8577
+ if (!field2) {
8578
+ throw new BorshError("Field: " + ix + " is missing specification");
8579
+ }
8580
+ if (field2.type instanceof WrappedType) {
8581
+ let dependency = field2.type.getDependency();
8582
+ if (dependency)
8583
+ ret.push(dependency);
8584
+ } else if (typeof field2.type === "function") {
8585
+ ret.push(field2.type);
8586
+ }
8587
+ });
8588
+ return ret;
8589
+ }
8590
+ };
7585
8591
 
7586
8592
  // node_modules/@dao-xyz/borsh/lib/esm/index.js
7587
8593
  var MAX_PROTOTYPE_SEARCH = 250;
@@ -7589,7 +8595,7 @@ var PROTOTYPE_POLLUTION_CONTEXT_RANGE = 500;
7589
8595
  var PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET = 500;
7590
8596
  var PROTOTYPE_DEPENDENCY_HANDLER_OFFSET = PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + PROTOTYPE_POLLUTION_CONTEXT_RANGE;
7591
8597
  var PROTOTYPE_SCHEMA_OFFSET = PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + PROTOTYPE_POLLUTION_CONTEXT_RANGE * 2;
7592
- function serialize(obj, writer = new BinaryWriter()) {
8598
+ function serialize2(obj, writer = new BinaryWriter()) {
7593
8599
  (obj.constructor._borsh_serialize || (obj.constructor._borsh_serialize = serializeStruct(obj.constructor, true)))(obj, writer);
7594
8600
  return writer.finalize();
7595
8601
  }
@@ -7597,6 +8603,15 @@ function recursiveSerialize(obj, writer = new BinaryWriter()) {
7597
8603
  (obj.constructor._borsh_serialize_recursive || (obj.constructor._borsh_serialize_recursive = serializeStruct(obj.constructor, false)))(obj, writer);
7598
8604
  return writer.finalize();
7599
8605
  }
8606
+ function deserialize2(buffer, classType, options) {
8607
+ const reader = new BinaryReader(buffer);
8608
+ let fromBuffer = buffer.constructor !== Uint8Array;
8609
+ const result = deserializeStruct(classType, fromBuffer)(reader, options);
8610
+ if (reader._offset !== buffer.length) {
8611
+ throw new BorshError(`Unexpected ${buffer.length - reader._offset} bytes after deserialized data. This is most likely due to that you are deserializing into the wrong class`);
8612
+ }
8613
+ return result;
8614
+ }
7600
8615
  function serializeField(fieldName, fieldType, options) {
7601
8616
  if (typeof fieldType.serialize == "function") {
7602
8617
  return (obj, writer) => fieldType.serialize(obj, writer);
@@ -7717,94 +8732,517 @@ function serializeStruct(ctor, allowCustomSerializer = true) {
7717
8732
  } : (_obj, writer) => writer.string(index);
7718
8733
  }
7719
8734
  }
7720
- if (allowCustomSerializer && schema.serializer) {
7721
- let prev = handle;
7722
- handle = prev ? (obj, writer) => {
7723
- prev(obj, writer);
7724
- schema.serializer(obj, writer, (obj2) => recursiveSerialize(obj2));
7725
- } : (obj, writer) => schema.serializer(obj, writer, (obj2) => recursiveSerialize(obj2));
7726
- } else {
7727
- for (const field2 of schema.fields) {
7728
- let prev = handle;
7729
- const fieldHandle = serializeField(field2.key, field2.type);
7730
- if (prev) {
7731
- handle = (obj, writer) => {
7732
- prev(obj, writer);
7733
- fieldHandle(obj[field2.key], writer);
7734
- };
7735
- } else {
7736
- handle = (obj, writer) => fieldHandle(obj[field2.key], writer);
7737
- }
8735
+ if (allowCustomSerializer && schema.serializer) {
8736
+ let prev = handle;
8737
+ handle = prev ? (obj, writer) => {
8738
+ prev(obj, writer);
8739
+ schema.serializer(obj, writer, (obj2) => recursiveSerialize(obj2));
8740
+ } : (obj, writer) => schema.serializer(obj, writer, (obj2) => recursiveSerialize(obj2));
8741
+ } else {
8742
+ for (const field2 of schema.fields) {
8743
+ let prev = handle;
8744
+ const fieldHandle = serializeField(field2.key, field2.type);
8745
+ if (prev) {
8746
+ handle = (obj, writer) => {
8747
+ prev(obj, writer);
8748
+ fieldHandle(obj[field2.key], writer);
8749
+ };
8750
+ } else {
8751
+ handle = (obj, writer) => fieldHandle(obj[field2.key], writer);
8752
+ }
8753
+ }
8754
+ }
8755
+ } else if (once && !getDependencies(ctor, i)?.length) {
8756
+ return handle;
8757
+ }
8758
+ i++;
8759
+ if (i == MAX_PROTOTYPE_SEARCH && !once) {
8760
+ throw new BorshError(`Class ${ctor.name} is missing in schema`);
8761
+ }
8762
+ }
8763
+ }
8764
+ var MAX_ARRAY_SIZE_ALLOCATION = 1024 * 1024;
8765
+ function deserializeField(fieldName, fieldType, fromBuffer) {
8766
+ try {
8767
+ if (typeof fieldType === "string") {
8768
+ return BinaryReader.read(fieldType, fromBuffer);
8769
+ }
8770
+ if (fieldType === Uint8Array) {
8771
+ return (reader) => reader.uint8Array();
8772
+ }
8773
+ if (fieldType instanceof VecKind || fieldType instanceof FixedArrayKind) {
8774
+ if (fieldType.elementType === "u8") {
8775
+ if (fieldType instanceof FixedArrayKind) {
8776
+ return (reader) => reader.buffer(fieldType.length);
8777
+ } else {
8778
+ const sizeHandle = BinaryReader.read(fieldType.sizeEncoding, fromBuffer);
8779
+ return (reader) => BinaryReader.uint8Array(reader, sizeHandle(reader));
8780
+ }
8781
+ } else {
8782
+ let sizeHandle = fieldType instanceof VecKind ? BinaryReader.read(fieldType.sizeEncoding, fromBuffer) : () => fieldType.length;
8783
+ const fieldHandle = deserializeField(null, fieldType.elementType, fromBuffer);
8784
+ return (reader, options) => {
8785
+ const len = sizeHandle(reader);
8786
+ if (len < MAX_ARRAY_SIZE_ALLOCATION) {
8787
+ let arr = new Array(len);
8788
+ for (let i = 0; i < len; i++) {
8789
+ arr[i] = fieldHandle(reader, options);
8790
+ }
8791
+ return arr;
8792
+ } else {
8793
+ let arr = new Array(MAX_ARRAY_SIZE_ALLOCATION);
8794
+ for (let i = 0; i < len; i++) {
8795
+ arr[i] = fieldHandle(reader, options);
8796
+ }
8797
+ return arr;
8798
+ }
8799
+ };
8800
+ }
8801
+ }
8802
+ if (fieldType instanceof StringType) {
8803
+ const sizeReader = BinaryReader.read(fieldType.sizeEncoding, fromBuffer);
8804
+ return fromBuffer ? (reader) => BinaryReader.bufferStringCustom(reader, sizeReader) : (reader) => BinaryReader.stringCustom(reader, sizeReader);
8805
+ }
8806
+ if (typeof fieldType["deserialize"] == "function") {
8807
+ return (reader) => fieldType.deserialize(reader);
8808
+ }
8809
+ if (fieldType instanceof OptionKind) {
8810
+ const fieldHandle = deserializeField(fieldName, fieldType.elementType, fromBuffer);
8811
+ return (reader, options) => {
8812
+ return reader.bool() ? fieldHandle(reader, options) : void 0;
8813
+ };
8814
+ }
8815
+ return deserializeStruct(fieldType, fromBuffer);
8816
+ } catch (error) {
8817
+ if (error instanceof BorshError) {
8818
+ error.addToFieldPath(fieldName);
8819
+ }
8820
+ throw error;
8821
+ }
8822
+ }
8823
+ function deserializeStruct(targetClazz, fromBuffer) {
8824
+ const handle = getCreateDeserializationHandle(targetClazz, 0, fromBuffer);
8825
+ return (reader, options) => {
8826
+ const result = handle({}, reader, options);
8827
+ if (!options?.unchecked && !options?.object && !checkClazzesCompatible(result.constructor, targetClazz)) {
8828
+ throw new BorshError(`Deserialization of ${targetClazz?.name || targetClazz} yielded another Class: ${result.constructor?.name} which are not compatible`);
8829
+ }
8830
+ return result;
8831
+ };
8832
+ }
8833
+ var getCreateDeserializationHandle = (clazz, offset, fromBuffer) => getDeserializationHandle(clazz, offset, fromBuffer) || setDeserializationHandle(clazz, offset, fromBuffer, createDeserializeStructHandle(clazz, offset, fromBuffer));
8834
+ var getDeserializationHandle = (clazz, offset, fromBuffer) => clazz.prototype[PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + offset + (fromBuffer ? MAX_PROTOTYPE_SEARCH : 0)];
8835
+ var setDeserializationHandle = (clazz, offset, fromBuffer, handle) => clazz.prototype[PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + offset + (fromBuffer ? MAX_PROTOTYPE_SEARCH : 0)] = handle;
8836
+ var createDeserializeStructHandle = (currClazz, offset, fromBuffer) => {
8837
+ let handle = void 0;
8838
+ let endHandle = (result, reader, options) => {
8839
+ if (options?.object) {
8840
+ return result;
8841
+ }
8842
+ return Object.assign(options?.construct ? new currClazz() : Object.create(currClazz.prototype), result);
8843
+ };
8844
+ let structSchema = getSchema(currClazz, offset);
8845
+ if (structSchema) {
8846
+ if (offset === 0) {
8847
+ let index = getVariantIndex(structSchema);
8848
+ if (index != null) {
8849
+ if (typeof index === "number") {
8850
+ handle = (_, reader, __) => {
8851
+ reader._offset += 1;
8852
+ };
8853
+ } else if (Array.isArray(index)) {
8854
+ handle = (_, reader, __) => {
8855
+ reader._offset += index.length;
8856
+ };
8857
+ } else {
8858
+ handle = (_, reader, __) => {
8859
+ reader.string();
8860
+ };
8861
+ }
8862
+ }
8863
+ }
8864
+ for (const field2 of structSchema.fields) {
8865
+ const prev = handle;
8866
+ const fieldHandle = deserializeField(field2.key, field2.type, fromBuffer);
8867
+ if (prev) {
8868
+ handle = (result, reader, options) => {
8869
+ prev(result, reader, options);
8870
+ result[field2.key] = fieldHandle(reader, options);
8871
+ };
8872
+ } else
8873
+ handle = (result, reader, options) => {
8874
+ result[field2.key] = fieldHandle(reader, options);
8875
+ };
8876
+ }
8877
+ }
8878
+ let dependencies = getAllDependencies(currClazz, offset);
8879
+ if (dependencies) {
8880
+ let variantToDepndency = [];
8881
+ let variantType;
8882
+ for (const [actualClazz, dependency] of dependencies) {
8883
+ const variantIndex = getVariantIndex(dependency.schema);
8884
+ let currentVariantType = typeof variantIndex === "object" ? variantIndex.length : typeof variantIndex;
8885
+ if (!variantType) {
8886
+ variantType = currentVariantType;
8887
+ } else if (currentVariantType !== variantType) {
8888
+ throw new Error(`Variant extending ${currClazz.name} have different types, expecting either number, number[] (with same sizes) or string, but not a combination of them`);
8889
+ }
8890
+ variantToDepndency.push([variantIndex, actualClazz, dependency]);
8891
+ }
8892
+ if (variantType === "undefined") {
8893
+ if (dependencies.size === 1) {
8894
+ const dep = variantToDepndency[0];
8895
+ return (result, reader, options) => {
8896
+ handle && handle(result, reader, options);
8897
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8898
+ };
8899
+ } else
8900
+ throw new BorshError(`Failed to find class to deserialize to from ${currClazz.name}: but no variants are used which makes deserialization undeterministic`);
8901
+ }
8902
+ return (result, reader, options) => {
8903
+ handle && handle(result, reader, options);
8904
+ let next = void 0;
8905
+ let nextOffset = void 0;
8906
+ if (variantType === "number") {
8907
+ let agg = reader.u8();
8908
+ for (const dep of variantToDepndency) {
8909
+ if (agg === dep[0]) {
8910
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8911
+ }
8912
+ }
8913
+ } else if (variantType === "string") {
8914
+ let variant = reader.string();
8915
+ for (const dep of variantToDepndency) {
8916
+ if (variant === dep[0]) {
8917
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8918
+ }
8919
+ }
8920
+ } else {
8921
+ let agg = [];
8922
+ for (let i = 0; i < variantType; i++) {
8923
+ agg.push(reader.u8());
8924
+ }
8925
+ for (const dep of variantToDepndency) {
8926
+ let currentVariant = dep[0];
8927
+ if (currentVariant.length === agg.length && currentVariant.every((value, index) => value === agg[index])) {
8928
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8929
+ }
8930
+ }
8931
+ }
8932
+ if (next == void 0 && dependencies) {
8933
+ if (dependencies.size == 1) {
8934
+ const n = dependencies.entries().next().value;
8935
+ next = n[0];
8936
+ nextOffset = n[1].offset;
8937
+ } else if (dependencies.size > 1) {
8938
+ const classes = [...dependencies.entries()].map(([c]) => c.name).join(", ");
8939
+ throw new BorshError(`Failed to find class to deserialize to from ${currClazz.name} found: ${classes} but no variant matches bytes read from the buffer.`);
8940
+ }
8941
+ }
8942
+ if (next != null) {
8943
+ getCreateDeserializationHandle(next, nextOffset, fromBuffer)(result, reader, options);
8944
+ } else {
8945
+ return endHandle(result, reader, options);
8946
+ }
8947
+ };
8948
+ } else {
8949
+ if (handle) {
8950
+ return (result, reader, options) => {
8951
+ handle(result, reader, options);
8952
+ return endHandle(result, reader, options);
8953
+ };
8954
+ }
8955
+ return endHandle;
8956
+ }
8957
+ };
8958
+ var getOrCreateStructMeta = (clazz, offset) => {
8959
+ let schema = getSchema(clazz, offset);
8960
+ if (!schema) {
8961
+ schema = new StructKind();
8962
+ }
8963
+ setSchema(clazz, schema, offset);
8964
+ return schema;
8965
+ };
8966
+ var setDependencyToProtoType = (ctor, offset) => {
8967
+ let proto = Object.getPrototypeOf(ctor);
8968
+ while (proto.prototype?.constructor != void 0) {
8969
+ let newOffset = --offset;
8970
+ let dependencies = getDependencies(proto, newOffset);
8971
+ if (dependencies) {
8972
+ for (const dependency of dependencies) {
8973
+ if (ctor.prototype instanceof dependency || dependency === ctor) {
8974
+ return;
8975
+ }
8976
+ }
8977
+ } else {
8978
+ dependencies = [];
8979
+ }
8980
+ dependencies.push(ctor);
8981
+ setDependencies(proto, newOffset, dependencies);
8982
+ proto = Object.getPrototypeOf(proto);
8983
+ }
8984
+ };
8985
+ var getSuperMostClass = (clazz) => {
8986
+ while (Object.getPrototypeOf(clazz).prototype != void 0) {
8987
+ clazz = Object.getPrototypeOf(clazz);
8988
+ }
8989
+ return clazz;
8990
+ };
8991
+ var checkClazzesCompatible = (clazzA, clazzB) => {
8992
+ return clazzA == clazzB || clazzA.isPrototypeOf(clazzB) || clazzB.isPrototypeOf(clazzA);
8993
+ };
8994
+ var getDependencies = (ctor, offset) => ctor.prototype[PROTOTYPE_DEPENDENCY_HANDLER_OFFSET + offset];
8995
+ var setDependencies = (ctor, offset, dependencies) => {
8996
+ ctor.prototype[PROTOTYPE_DEPENDENCY_HANDLER_OFFSET + offset] = dependencies;
8997
+ };
8998
+ var getAllDependencies = (ctor, offset) => {
8999
+ let existing = getDependencies(ctor, offset);
9000
+ if (existing) {
9001
+ let ret = /* @__PURE__ */ new Map();
9002
+ for (const v of existing) {
9003
+ let schema = getSubMostSchema(v);
9004
+ if (schema.fields.length > 0 || schema.variant != void 0) {
9005
+ ret.set(v, { schema, offset: getOffset(v) });
9006
+ } else {
9007
+ let req = getAllDependencies(v, offset);
9008
+ for (const [rv, rk] of req) {
9009
+ ret.set(rv, rk);
9010
+ }
9011
+ }
9012
+ }
9013
+ return ret;
9014
+ }
9015
+ };
9016
+ var setSchema = (ctor, schemas, offset) => {
9017
+ ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + offset] = schemas;
9018
+ };
9019
+ var getSchema = (ctor, offset = getOffset(ctor)) => ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + offset];
9020
+ var getSubMostSchema = (ctor) => {
9021
+ let last = void 0;
9022
+ for (var i = 0; i < MAX_PROTOTYPE_SEARCH; i++) {
9023
+ const curr = ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + i];
9024
+ if (!curr && last && !getDependencies(ctor, i)?.length) {
9025
+ return last;
9026
+ }
9027
+ last = curr;
9028
+ }
9029
+ return;
9030
+ };
9031
+ var getVariantIndex = (schema) => {
9032
+ return schema.variant;
9033
+ };
9034
+ function field(properties) {
9035
+ return (target, name) => {
9036
+ const offset = getOffset(target.constructor);
9037
+ setDependencyToProtoType(target.constructor, offset);
9038
+ const schemas = getOrCreateStructMeta(target.constructor, offset);
9039
+ const schema = schemas;
9040
+ const key = name.toString();
9041
+ let field2 = void 0;
9042
+ if (properties["type"] != void 0) {
9043
+ field2 = {
9044
+ key,
9045
+ type: properties["type"]
9046
+ };
9047
+ } else {
9048
+ field2 = {
9049
+ key,
9050
+ type: properties
9051
+ };
9052
+ }
9053
+ if (properties.index === void 0) {
9054
+ schema.fields.push(field2);
9055
+ } else {
9056
+ if (schema.fields[properties.index]) {
9057
+ throw new BorshError("Multiple fields defined at the same index: " + properties.index + ", class: " + target.constructor.name);
9058
+ }
9059
+ if (properties.index >= schema.fields.length) {
9060
+ resize(schema.fields, properties.index + 1, void 0);
9061
+ }
9062
+ schema.fields[properties.index] = field2;
9063
+ }
9064
+ };
9065
+ }
9066
+ var resize = (arr, newSize, defaultValue) => {
9067
+ while (newSize > arr.length)
9068
+ arr.push(defaultValue);
9069
+ arr.length = newSize;
9070
+ };
9071
+
9072
+ // src/serialization/borsh.ts
9073
+ function serializeBorsh(data) {
9074
+ return serialize2(data);
9075
+ }
9076
+ function deserializeBorsh(data, type) {
9077
+ return deserialize2(data, type);
9078
+ }
9079
+
9080
+ // src/transaction/account-meta-table.ts
9081
+ var AccountMetaTable = class {
9082
+ accounts = /* @__PURE__ */ new Map();
9083
+ accountOrder = [];
9084
+ /**
9085
+ * Add or update an account in the table.
9086
+ * If account already exists, merges signer/writable flags (OR operation).
9087
+ */
9088
+ add(meta) {
9089
+ const key = meta.pubkey.toString();
9090
+ if (this.accounts.has(key)) {
9091
+ const existing = this.accounts.get(key);
9092
+ existing.isSigner ||= meta.isSigner;
9093
+ existing.isWritable ||= meta.isWritable;
9094
+ } else {
9095
+ this.accounts.set(key, {
9096
+ pubkey: meta.pubkey,
9097
+ isSigner: meta.isSigner,
9098
+ isWritable: meta.isWritable
9099
+ });
9100
+ this.accountOrder.push(key);
9101
+ }
9102
+ }
9103
+ /**
9104
+ * Add multiple accounts at once.
9105
+ */
9106
+ addAll(metas) {
9107
+ for (const meta of metas) {
9108
+ this.add(meta);
9109
+ }
9110
+ }
9111
+ /**
9112
+ * Get the index of an account in the sorted order.
9113
+ * Returns -1 if account not found.
9114
+ */
9115
+ getIndex(pubkey) {
9116
+ const sorted = this.getSortedAccounts();
9117
+ return sorted.findIndex((entry) => entry.pubkey.equals(pubkey));
9118
+ }
9119
+ /**
9120
+ * Get sorted accounts according to transaction rules.
9121
+ */
9122
+ getSortedAccounts() {
9123
+ const entries = this.accountOrder.map((key) => this.accounts.get(key));
9124
+ return entries.sort((a, b) => {
9125
+ const aPriority = a.isSigner && a.isWritable ? 0 : a.isSigner ? 1 : a.isWritable ? 2 : 3;
9126
+ const bPriority = b.isSigner && b.isWritable ? 0 : b.isSigner ? 1 : b.isWritable ? 2 : 3;
9127
+ if (aPriority !== bPriority) {
9128
+ return aPriority - bPriority;
9129
+ }
9130
+ const aBytes = a.pubkey.toBytes();
9131
+ const bBytes = b.pubkey.toBytes();
9132
+ for (let i = 0; i < 32; i++) {
9133
+ if (aBytes[i] !== bBytes[i]) {
9134
+ return aBytes[i] - bBytes[i];
9135
+ }
9136
+ }
9137
+ return 0;
9138
+ });
9139
+ }
9140
+ /**
9141
+ * Get the message header based on sorted accounts.
9142
+ */
9143
+ getHeader() {
9144
+ const sorted = this.getSortedAccounts();
9145
+ let numRequiredSignatures = 0;
9146
+ let numReadonlySignedAccounts = 0;
9147
+ let numReadonlyUnsignedAccounts = 0;
9148
+ for (const entry of sorted) {
9149
+ if (entry.isSigner) {
9150
+ numRequiredSignatures++;
9151
+ if (!entry.isWritable) {
9152
+ numReadonlySignedAccounts++;
7738
9153
  }
9154
+ } else if (!entry.isWritable) {
9155
+ numReadonlyUnsignedAccounts++;
7739
9156
  }
7740
- } else if (once && !getDependencies(ctor, i)?.length) {
7741
- return handle;
7742
- }
7743
- i++;
7744
- if (i == MAX_PROTOTYPE_SEARCH && !once) {
7745
- throw new BorshError(`Class ${ctor.name} is missing in schema`);
7746
9157
  }
9158
+ return {
9159
+ numRequiredSignatures,
9160
+ numReadonlySignedAccounts,
9161
+ numReadonlyUnsignedAccounts
9162
+ };
7747
9163
  }
7748
- }
7749
- var getSuperMostClass = (clazz) => {
7750
- while (Object.getPrototypeOf(clazz).prototype != void 0) {
7751
- clazz = Object.getPrototypeOf(clazz);
9164
+ /**
9165
+ * Get sorted public keys.
9166
+ */
9167
+ getPublicKeys() {
9168
+ return this.getSortedAccounts().map((entry) => entry.pubkey);
9169
+ }
9170
+ /**
9171
+ * Get number of accounts in table.
9172
+ */
9173
+ size() {
9174
+ return this.accounts.size;
7752
9175
  }
7753
- return clazz;
7754
- };
7755
- var checkClazzesCompatible = (clazzA, clazzB) => {
7756
- return clazzA == clazzB || clazzA.isPrototypeOf(clazzB) || clazzB.isPrototypeOf(clazzA);
7757
9176
  };
7758
- var getDependencies = (ctor, offset) => ctor.prototype[PROTOTYPE_DEPENDENCY_HANDLER_OFFSET + offset];
7759
- var getSchema = (ctor, offset = getOffset(ctor)) => ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + offset];
7760
-
7761
- // src/serialization/borsh.ts
7762
- function serializeBorsh(data) {
7763
- return serialize(data);
7764
- }
7765
9177
 
7766
- // src/serialization/compact-u16.ts
7767
- function deserializeCompactU16(data, currentCursor) {
7768
- let cursor = currentCursor;
7769
- if (cursor >= data.length) {
7770
- throw new TransactionError(
7771
- "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
7772
- "Insufficient data for compact-u16"
9178
+ // src/transaction/errors.ts
9179
+ var TransactionErrorCode = /* @__PURE__ */ ((TransactionErrorCode2) => {
9180
+ TransactionErrorCode2["INVALID_INSTRUCTION"] = "INVALID_INSTRUCTION";
9181
+ TransactionErrorCode2["INVALID_ACCOUNT_META"] = "INVALID_ACCOUNT_META";
9182
+ TransactionErrorCode2["NO_INSTRUCTIONS"] = "NO_INSTRUCTIONS";
9183
+ TransactionErrorCode2["DUPLICATE_ACCOUNT"] = "DUPLICATE_ACCOUNT";
9184
+ TransactionErrorCode2["MISSING_SIGNATURE"] = "MISSING_SIGNATURE";
9185
+ TransactionErrorCode2["INVALID_SIGNATURE"] = "INVALID_SIGNATURE";
9186
+ TransactionErrorCode2["SIGNATURE_OUT_OF_BOUNDS"] = "SIGNATURE_OUT_OF_BOUNDS";
9187
+ TransactionErrorCode2["SIGNER_NOT_FOUND"] = "SIGNER_NOT_FOUND";
9188
+ TransactionErrorCode2["ALREADY_SIGNED"] = "ALREADY_SIGNED";
9189
+ TransactionErrorCode2["INVALID_MESSAGE_FORMAT"] = "INVALID_MESSAGE_FORMAT";
9190
+ TransactionErrorCode2["INSUFFICIENT_DATA"] = "INSUFFICIENT_DATA";
9191
+ TransactionErrorCode2["SERIALIZATION_FAILED"] = "SERIALIZATION_FAILED";
9192
+ TransactionErrorCode2["SIMULATION_FAILED"] = "SIMULATION_FAILED";
9193
+ TransactionErrorCode2["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
9194
+ TransactionErrorCode2["BLOCKHASH_EXPIRED"] = "BLOCKHASH_EXPIRED";
9195
+ return TransactionErrorCode2;
9196
+ })(TransactionErrorCode || {});
9197
+ var TransactionError = class _TransactionError extends Error {
9198
+ constructor(code, message, details) {
9199
+ super(message);
9200
+ this.code = code;
9201
+ this.details = details;
9202
+ this.name = "TransactionError";
9203
+ }
9204
+ static noInstructions() {
9205
+ return new _TransactionError(
9206
+ "NO_INSTRUCTIONS" /* NO_INSTRUCTIONS */,
9207
+ "Transaction must contain at least one instruction. Use addInstruction() to add instructions."
7773
9208
  );
7774
9209
  }
7775
- const firstByte = data[cursor++];
7776
- if ((firstByte & 128) === 0) {
7777
- return [firstByte, cursor];
9210
+ static signerNotFound(pubkey) {
9211
+ return new _TransactionError(
9212
+ "SIGNER_NOT_FOUND" /* SIGNER_NOT_FOUND */,
9213
+ `Public key ${pubkey} is not a required signer for this transaction. Check that the account is marked as a signer in the instruction.`,
9214
+ { pubkey }
9215
+ );
7778
9216
  }
7779
- if (cursor >= data.length) {
7780
- throw new TransactionError(
7781
- "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
7782
- "Incomplete compact-u16 encoding"
9217
+ static missingSignature(index, pubkey) {
9218
+ return new _TransactionError(
9219
+ "MISSING_SIGNATURE" /* MISSING_SIGNATURE */,
9220
+ `Missing signature for signer ${index} (${pubkey}). Transaction requires ${index + 1} signatures.`,
9221
+ { index, pubkey }
7783
9222
  );
7784
9223
  }
7785
- const secondByte = data[cursor++];
7786
- if ((secondByte & 128) === 0) {
7787
- return [firstByte & 127 | secondByte << 7, cursor];
9224
+ static simulationFailed(logs, error) {
9225
+ return new _TransactionError(
9226
+ "SIMULATION_FAILED" /* SIMULATION_FAILED */,
9227
+ `Transaction simulation failed: ${error}`,
9228
+ { logs, error }
9229
+ );
7788
9230
  }
7789
- if (cursor >= data.length) {
7790
- throw new TransactionError(
7791
- "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
7792
- "Incomplete compact-u16 encoding"
9231
+ static insufficientFunds(required, available) {
9232
+ return new _TransactionError(
9233
+ "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */,
9234
+ `Insufficient funds: need ${required}, have ${available}`,
9235
+ { required: required.toString(), available: available.toString() }
7793
9236
  );
7794
9237
  }
7795
- const thirdByte = data[cursor++];
7796
- const value = firstByte & 127 | (secondByte & 127) << 7 | thirdByte << 14;
7797
- return [value, cursor];
7798
- }
7799
- function writeCompactU16(buffer, offset, value) {
7800
- if (value < 128) {
7801
- buffer[offset] = value;
7802
- return offset + 1;
9238
+ toJSON() {
9239
+ return {
9240
+ code: this.code,
9241
+ message: this.message,
9242
+ details: this.details
9243
+ };
7803
9244
  }
7804
- buffer[offset] = value & 127 | 128;
7805
- buffer[offset + 1] = value >> 7;
7806
- return offset + 2;
7807
- }
9245
+ };
7808
9246
 
7809
9247
  // src/transaction/instructions/borsh-instruction.ts
7810
9248
  function createBorshInstruction(params) {
@@ -7895,14 +9333,17 @@ var Message = class _Message {
7895
9333
  accountKeys;
7896
9334
  /** Transaction valid from (milliseconds since Unix epoch) */
7897
9335
  validFrom;
9336
+ /** Config hash prefix for replay protection across chains */
9337
+ configHashPrefix;
7898
9338
  /** Compiled instructions with account indices */
7899
9339
  instructions;
7900
9340
  /** Cached serialized bytes */
7901
9341
  serializedCache;
7902
- constructor(header, accountKeys, validFrom, instructions) {
9342
+ constructor(header, accountKeys, validFrom, configHashPrefix, instructions) {
7903
9343
  this.header = Object.freeze({ ...header });
7904
9344
  this.accountKeys = Object.freeze([...accountKeys]);
7905
9345
  this.validFrom = validFrom;
9346
+ this.configHashPrefix = configHashPrefix;
7906
9347
  this.instructions = Object.freeze(
7907
9348
  instructions.map((ix) => Object.freeze({ ...ix }))
7908
9349
  );
@@ -7936,7 +9377,7 @@ var Message = class _Message {
7936
9377
  numReadonlySignedAccounts: data[cursor++],
7937
9378
  numReadonlyUnsignedAccounts: data[cursor++]
7938
9379
  };
7939
- const [accountKeysLength, newCursor1] = deserializeCompactU162(data, cursor);
9380
+ const [accountKeysLength, newCursor1] = deserializeCompactU16(data, cursor);
7940
9381
  cursor = newCursor1;
7941
9382
  const accountKeys = [];
7942
9383
  for (let i = 0; i < accountKeysLength; i++) {
@@ -7962,7 +9403,19 @@ var Message = class _Message {
7962
9403
  new DataView(validFromBytes.buffer).getBigUint64(0, true)
7963
9404
  );
7964
9405
  cursor += 8;
7965
- const [instructionsLength, newCursor2] = deserializeCompactU162(
9406
+ if (data.length < cursor + 8) {
9407
+ throw new TransactionError(
9408
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
9409
+ "Insufficient data for configHashPrefix"
9410
+ );
9411
+ }
9412
+ const configHashPrefixBytes = data.slice(cursor, cursor + 8);
9413
+ const configHashPrefix = BigInt.asUintN(
9414
+ 64,
9415
+ new DataView(configHashPrefixBytes.buffer).getBigUint64(0, true)
9416
+ );
9417
+ cursor += 8;
9418
+ const [instructionsLength, newCursor2] = deserializeCompactU16(
7966
9419
  data,
7967
9420
  cursor
7968
9421
  );
@@ -7976,7 +9429,7 @@ var Message = class _Message {
7976
9429
  );
7977
9430
  }
7978
9431
  const programIdIndex = data[cursor++];
7979
- const [accountIndexesLength, newCursor3] = deserializeCompactU162(
9432
+ const [accountIndexesLength, newCursor3] = deserializeCompactU16(
7980
9433
  data,
7981
9434
  cursor
7982
9435
  );
@@ -7991,7 +9444,7 @@ var Message = class _Message {
7991
9444
  }
7992
9445
  accountKeyIndexes.push(data[cursor++]);
7993
9446
  }
7994
- const [dataLength, newCursor4] = deserializeCompactU162(data, cursor);
9447
+ const [dataLength, newCursor4] = deserializeCompactU16(data, cursor);
7995
9448
  cursor = newCursor4;
7996
9449
  if (data.length < cursor + dataLength) {
7997
9450
  throw new TransactionError(
@@ -8007,7 +9460,7 @@ var Message = class _Message {
8007
9460
  data: instructionData
8008
9461
  });
8009
9462
  }
8010
- return new _Message(header, accountKeys, validFrom, instructions);
9463
+ return new _Message(header, accountKeys, validFrom, configHashPrefix, instructions);
8011
9464
  }
8012
9465
  serializeInternal() {
8013
9466
  const buffer = [];
@@ -8024,6 +9477,13 @@ var Message = class _Message {
8024
9477
  true
8025
9478
  );
8026
9479
  buffer.push(...new Uint8Array(validFromBuffer));
9480
+ const configHashPrefixBuffer = new ArrayBuffer(8);
9481
+ new DataView(configHashPrefixBuffer).setBigUint64(
9482
+ 0,
9483
+ this.configHashPrefix,
9484
+ true
9485
+ );
9486
+ buffer.push(...new Uint8Array(configHashPrefixBuffer));
8027
9487
  this.serializeCompactArray(buffer, this.instructions, (buf, ix) => {
8028
9488
  buf.push(ix.programIdIndex);
8029
9489
  this.serializeCompactArray(buf, ix.accountKeyIndexes, (b, idx) => {
@@ -8078,7 +9538,7 @@ var Message = class _Message {
8078
9538
  return this.getSigners().findIndex((signer) => signer.equals(pubkey));
8079
9539
  }
8080
9540
  };
8081
- function deserializeCompactU162(data, currentCursor) {
9541
+ function deserializeCompactU16(data, currentCursor) {
8082
9542
  let cursor = currentCursor;
8083
9543
  if (cursor >= data.length) {
8084
9544
  throw new TransactionError(
@@ -8160,7 +9620,7 @@ var Transaction = class _Transaction {
8160
9620
  );
8161
9621
  }
8162
9622
  let cursor = 0;
8163
- const [signaturesLength, newCursor] = deserializeCompactU16(data, cursor);
9623
+ const [signaturesLength, newCursor] = deserializeCompactU162(data, cursor);
8164
9624
  cursor = newCursor;
8165
9625
  const signatures = [];
8166
9626
  for (let i = 0; i < signaturesLength; i++) {
@@ -8408,6 +9868,7 @@ var Transaction = class _Transaction {
8408
9868
  var TransactionBuilder = class _TransactionBuilder {
8409
9869
  payer;
8410
9870
  validFrom;
9871
+ configHashPrefix;
8411
9872
  instructions = [];
8412
9873
  constructor() {
8413
9874
  }
@@ -8441,6 +9902,18 @@ var TransactionBuilder = class _TransactionBuilder {
8441
9902
  this.validFrom = validFrom;
8442
9903
  return this;
8443
9904
  }
9905
+ /**
9906
+ * Set the config hash prefix for replay protection.
9907
+ *
9908
+ * This is the first 64 bits of the config hash, used to ensure
9909
+ * transactions cannot be replayed on different chains.
9910
+ *
9911
+ * @param configHashPrefix - config hash prefix as a u64
9912
+ */
9913
+ setConfigHashPrefix(configHashPrefix) {
9914
+ this.configHashPrefix = configHashPrefix;
9915
+ return this;
9916
+ }
8444
9917
  /**
8445
9918
  * Add an instruction to the transaction.
8446
9919
  *
@@ -8486,6 +9959,12 @@ var TransactionBuilder = class _TransactionBuilder {
8486
9959
  "Transaction must have a valid from. Use setValidFrom() to set the valid from."
8487
9960
  );
8488
9961
  }
9962
+ if (this.configHashPrefix === void 0) {
9963
+ throw new TransactionError(
9964
+ "INVALID_MESSAGE_FORMAT" /* INVALID_MESSAGE_FORMAT */,
9965
+ "Transaction must have a config hash prefix. Use setConfigHashPrefix() to set the config hash prefix."
9966
+ );
9967
+ }
8489
9968
  if (this.instructions.length === 0) {
8490
9969
  throw TransactionError.noInstructions();
8491
9970
  }
@@ -8534,11 +10013,94 @@ var TransactionBuilder = class _TransactionBuilder {
8534
10013
  header,
8535
10014
  accountKeys,
8536
10015
  this.validFrom,
10016
+ this.configHashPrefix,
8537
10017
  compiledInstructions
8538
10018
  );
8539
10019
  return Transaction.fromMessage(message);
8540
10020
  }
8541
10021
  };
10022
+
10023
+ // src/serialization/compact-u16.ts
10024
+ function serializeCompactU16(buffer, value) {
10025
+ if (value < 0 || value > 65535) {
10026
+ throw new TransactionError(
10027
+ "SERIALIZATION_FAILED" /* SERIALIZATION_FAILED */,
10028
+ `Value out of range for compact-u16: ${value}`
10029
+ );
10030
+ }
10031
+ if (value <= 127) {
10032
+ buffer.push(value);
10033
+ return;
10034
+ }
10035
+ if (value <= 16383) {
10036
+ buffer.push(value & 127 | 128);
10037
+ buffer.push(value >> 7 & 127);
10038
+ return;
10039
+ }
10040
+ buffer.push(value & 127 | 128);
10041
+ buffer.push(value >> 7 & 127 | 128);
10042
+ buffer.push(value >> 14 & 255);
10043
+ }
10044
+ function deserializeCompactU162(data, currentCursor) {
10045
+ let cursor = currentCursor;
10046
+ if (cursor >= data.length) {
10047
+ throw new TransactionError(
10048
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
10049
+ "Insufficient data for compact-u16"
10050
+ );
10051
+ }
10052
+ const firstByte = data[cursor++];
10053
+ if ((firstByte & 128) === 0) {
10054
+ return [firstByte, cursor];
10055
+ }
10056
+ if (cursor >= data.length) {
10057
+ throw new TransactionError(
10058
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
10059
+ "Incomplete compact-u16 encoding"
10060
+ );
10061
+ }
10062
+ const secondByte = data[cursor++];
10063
+ if ((secondByte & 128) === 0) {
10064
+ return [firstByte & 127 | secondByte << 7, cursor];
10065
+ }
10066
+ if (cursor >= data.length) {
10067
+ throw new TransactionError(
10068
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
10069
+ "Incomplete compact-u16 encoding"
10070
+ );
10071
+ }
10072
+ const thirdByte = data[cursor++];
10073
+ const value = firstByte & 127 | (secondByte & 127) << 7 | thirdByte << 14;
10074
+ return [value, cursor];
10075
+ }
10076
+ function writeCompactU16(buffer, offset, value) {
10077
+ if (value < 128) {
10078
+ buffer[offset] = value;
10079
+ return offset + 1;
10080
+ }
10081
+ buffer[offset] = value & 127 | 128;
10082
+ buffer[offset + 1] = value >> 7;
10083
+ return offset + 2;
10084
+ }
10085
+
10086
+ // src/signer/keypair-signer.ts
10087
+ var KeypairSigner = class {
10088
+ constructor(keypair) {
10089
+ this.keypair = keypair;
10090
+ }
10091
+ /**
10092
+ * Returns the keypair's public key.
10093
+ */
10094
+ async getPublicKey() {
10095
+ return this.keypair.publicKey;
10096
+ }
10097
+ /**
10098
+ * Signs a message using the keypair's private key.
10099
+ */
10100
+ async signMessage(message) {
10101
+ return this.keypair.sign(message);
10102
+ }
10103
+ };
8542
10104
  /*! Bundled license information:
8543
10105
 
8544
10106
  @noble/ed25519/index.js:
@@ -8555,6 +10117,6 @@ var TransactionBuilder = class _TransactionBuilder {
8555
10117
  (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
8556
10118
  */
8557
10119
 
8558
- export { AccountMetaTable, BASE_DERIVATION_PATH, BaseRpcClient, CryptoError, CryptoErrorCode, DEFAULT_NUM_ACCOUNTS, HttpTransport, KELVIN_PER_RLO, Keypair, KeypairSigner, Message, Mnemonic, PUBLIC_KEY_LENGTH, PublicKey, QueryRpcClient, RIALO_DEVNET_CHAIN, RIALO_LOCALNET_CHAIN, RIALO_MAINNET_CHAIN, RIALO_SHITNET_CHAIN, RIALO_TESTNET_CHAIN, RialoClient, RialoError, RialoErrorType, RpcError, RpcErrorCode, SECRET_KEY_LENGTH, SIGNATURE_LENGTH, SYSTEM_PROGRAM_ID, Signature, SystemInstruction, Transaction, TransactionBuilder, TransactionError, TransactionErrorCode, TransactionRpcClient, URL_DEVNET, URL_LOCALNET, URL_MAINNET, URL_SHITNET, URL_TESTNET, allocateInstruction, assignInstruction, calculateBackoff, concatBytes2 as concatBytes, createAccount, createBorshInstruction, createRialoClient, encodeBorshData, fromBase64, getDefaultRialoClientConfig, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, isOnCurve, seedToBytes, sleep, toBase64, transferInstruction };
10120
+ export { AccountMetaTable, BASE_DERIVATION_PATH, BaseRpcClient, BincodeReader, BincodeWriter, CHACHA20_POLY1305_TAG_LENGTH, CryptoError, CryptoErrorCode, DEFAULT_NUM_ACCOUNTS, ED25519_PUBLIC_KEY_LENGTH, HPKE_ENC_LENGTH, HPKE_OVERHEAD_LENGTH, HpkeError, HpkeErrorCode, HttpTransport, KELVIN_PER_RLO, Keypair, KeypairSigner, Message, Mnemonic, PUBLIC_KEY_LENGTH, PublicKey, QueryRpcClient, RIALO_DEVNET_CHAIN, RIALO_LOCALNET_CHAIN, RIALO_MAINNET_CHAIN, RIALO_SHITNET_CHAIN, RIALO_TESTNET_CHAIN, RexValue, RexValueVariant, RialoClient, RialoError, RialoErrorType, RpcError, RpcErrorCode, SECRET_KEY_LENGTH, SECRET_SHARING_HPKE_INFO, SIGNATURE_LENGTH, SYSTEM_PROGRAM_ID, Schema, Signature, SystemInstruction, Transaction, TransactionBuilder, TransactionError, TransactionErrorCode, TransactionRpcClient, URL_DEVNET, URL_LOCALNET, URL_MAINNET, URL_SHITNET, URL_TESTNET, USER_SECRET_AAD, X25519_PUBLIC_KEY_LENGTH, allocateInstruction, assignInstruction, calculateBackoff, concatBytes2 as concatBytes, createAccount, createBorshInstruction, createRialoClient, deserialize, deserializeBorsh, deserializeCompactU162 as deserializeCompactU16, deserializeStrict, encodeBorshData, encryptForRex, field, fixedArray, fromBase64, getCiphertextLength, getDefaultRialoClientConfig, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, hpkeEncrypt, isOnCurve, isValidCiphertextLength, option, seedToBytes, serialize, serializeBorsh, serializeCompactU16, sleep, toBase64, transferInstruction, vec, writeCompactU16 };
8559
10121
  //# sourceMappingURL=index.mjs.map
8560
10122
  //# sourceMappingURL=index.mjs.map