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

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
@@ -5736,9 +5736,7 @@ var QueryRpcClient = class extends BaseRpcClient {
5736
5736
  * ```
5737
5737
  */
5738
5738
  async getAccountInfo(pubkey) {
5739
- const result = await this.call("getAccountInfo", [
5740
- { address: pubkey.toString(), config: { encoding: "base64" } }
5741
- ]);
5739
+ const result = await this.call("getAccountInfo", [{ address: pubkey.toString() }]);
5742
5740
  if (!result.value) {
5743
5741
  return null;
5744
5742
  }
@@ -6026,10 +6024,9 @@ var QueryRpcClient = class extends BaseRpcClient {
6026
6024
  owner: owner.toString(),
6027
6025
  filter,
6028
6026
  config: config ? {
6029
- encoding: config.encoding ?? "base64",
6030
6027
  limit: config.limit,
6031
6028
  after: config.after
6032
- } : { encoding: "base64" }
6029
+ } : void 0
6033
6030
  }
6034
6031
  ]);
6035
6032
  return {
@@ -6796,189 +6793,219 @@ function getDefaultRialoClientConfig(network) {
6796
6793
  }
6797
6794
  }
6798
6795
 
6799
- // src/signer/keypair-signer.ts
6800
- var KeypairSigner = class {
6801
- constructor(keypair) {
6802
- this.keypair = keypair;
6796
+ // src/serialization/bincode/reader.ts
6797
+ var BincodeReader = class {
6798
+ view;
6799
+ offset;
6800
+ bytes;
6801
+ constructor(data) {
6802
+ this.bytes = data;
6803
+ this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
6804
+ this.offset = 0;
6805
+ }
6806
+ // ========== Position Management ==========
6807
+ getOffset() {
6808
+ return this.offset;
6809
+ }
6810
+ remaining() {
6811
+ return this.bytes.length - this.offset;
6812
+ }
6813
+ isExhausted() {
6814
+ return this.offset >= this.bytes.length;
6815
+ }
6816
+ skip(bytes) {
6817
+ this.ensureAvailable(bytes);
6818
+ this.offset += bytes;
6819
+ return this;
6803
6820
  }
6804
6821
  /**
6805
- * Returns the keypair's public key.
6822
+ * Peek at bytes without advancing the offset
6806
6823
  */
6807
- async getPublicKey() {
6808
- return this.keypair.publicKey;
6824
+ peek(length) {
6825
+ this.ensureAvailable(length);
6826
+ return this.bytes.slice(this.offset, this.offset + length);
6809
6827
  }
6810
6828
  /**
6811
- * Signs a message using the keypair's private key.
6829
+ * Reset reader to beginning
6812
6830
  */
6813
- async signMessage(message) {
6814
- return this.keypair.sign(message);
6831
+ reset() {
6832
+ this.offset = 0;
6833
+ return this;
6815
6834
  }
6816
- };
6817
-
6818
- // src/transaction/account-meta-table.ts
6819
- var AccountMetaTable = class {
6820
- accounts = /* @__PURE__ */ new Map();
6821
- accountOrder = [];
6822
6835
  /**
6823
- * Add or update an account in the table.
6824
- * If account already exists, merges signer/writable flags (OR operation).
6836
+ * Seek to specific offset
6825
6837
  */
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);
6838
+ seek(offset) {
6839
+ if (offset < 0 || offset > this.bytes.length) {
6840
+ throw new Error(
6841
+ `Invalid seek offset: ${offset}, buffer length: ${this.bytes.length}`
6842
+ );
6839
6843
  }
6844
+ this.offset = offset;
6845
+ return this;
6840
6846
  }
6841
- /**
6842
- * Add multiple accounts at once.
6843
- */
6844
- addAll(metas) {
6845
- for (const meta of metas) {
6846
- this.add(meta);
6847
+ // ========== Primitive Types ==========
6848
+ readU8() {
6849
+ this.ensureAvailable(1);
6850
+ const value = this.view.getUint8(this.offset);
6851
+ this.offset += 1;
6852
+ return value;
6853
+ }
6854
+ readU16() {
6855
+ this.ensureAvailable(2);
6856
+ const value = this.view.getUint16(this.offset, true);
6857
+ this.offset += 2;
6858
+ return value;
6859
+ }
6860
+ readU32() {
6861
+ this.ensureAvailable(4);
6862
+ const value = this.view.getUint32(this.offset, true);
6863
+ this.offset += 4;
6864
+ return value;
6865
+ }
6866
+ readU64() {
6867
+ this.ensureAvailable(8);
6868
+ const low = this.view.getUint32(this.offset, true);
6869
+ const high = this.view.getUint32(this.offset + 4, true);
6870
+ this.offset += 8;
6871
+ return BigInt(low) | BigInt(high) << 32n;
6872
+ }
6873
+ readU128() {
6874
+ this.ensureAvailable(16);
6875
+ const low = this.readU64();
6876
+ const high = this.readU64();
6877
+ return low | high << 64n;
6878
+ }
6879
+ readI8() {
6880
+ this.ensureAvailable(1);
6881
+ const value = this.view.getInt8(this.offset);
6882
+ this.offset += 1;
6883
+ return value;
6884
+ }
6885
+ readI16() {
6886
+ this.ensureAvailable(2);
6887
+ const value = this.view.getInt16(this.offset, true);
6888
+ this.offset += 2;
6889
+ return value;
6890
+ }
6891
+ readI32() {
6892
+ this.ensureAvailable(4);
6893
+ const value = this.view.getInt32(this.offset, true);
6894
+ this.offset += 4;
6895
+ return value;
6896
+ }
6897
+ readI64() {
6898
+ this.ensureAvailable(8);
6899
+ const low = this.view.getUint32(this.offset, true);
6900
+ const high = this.view.getInt32(this.offset + 4, true);
6901
+ this.offset += 8;
6902
+ return BigInt(low) | BigInt(high) << 32n;
6903
+ }
6904
+ readI128() {
6905
+ const unsigned = this.readU128();
6906
+ const signBit = 1n << 127n;
6907
+ if ((unsigned & signBit) !== 0n) {
6908
+ return unsigned - (1n << 128n);
6847
6909
  }
6910
+ return unsigned;
6848
6911
  }
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));
6912
+ readF32() {
6913
+ this.ensureAvailable(4);
6914
+ const value = this.view.getFloat32(this.offset, true);
6915
+ this.offset += 4;
6916
+ return value;
6856
6917
  }
6857
- /**
6858
- * Get sorted accounts according to transaction rules.
6859
- */
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
- });
6918
+ readF64() {
6919
+ this.ensureAvailable(8);
6920
+ const value = this.view.getFloat64(this.offset, true);
6921
+ this.offset += 8;
6922
+ return value;
6877
6923
  }
6878
- /**
6879
- * Get the message header based on sorted accounts.
6880
- */
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
- }
6924
+ readBool() {
6925
+ const value = this.readU8();
6926
+ if (value > 1) {
6927
+ throw new Error(`Invalid boolean value: ${value}`);
6895
6928
  }
6896
- return {
6897
- numRequiredSignatures,
6898
- numReadonlySignedAccounts,
6899
- numReadonlyUnsignedAccounts
6900
- };
6929
+ return value === 1;
6901
6930
  }
6902
- /**
6903
- * Get sorted public keys.
6904
- */
6905
- getPublicKeys() {
6906
- return this.getSortedAccounts().map((entry) => entry.pubkey);
6931
+ // ========== Compound Types ==========
6932
+ readBytes(length) {
6933
+ this.ensureAvailable(length);
6934
+ const bytes = this.bytes.slice(this.offset, this.offset + length);
6935
+ this.offset += length;
6936
+ return bytes;
6907
6937
  }
6908
- /**
6909
- * Get number of accounts in table.
6910
- */
6911
- size() {
6912
- return this.accounts.size;
6938
+ readFixedArray(length) {
6939
+ return this.readBytes(length);
6913
6940
  }
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
+ readVecBytes() {
6942
+ const length = this.readLength();
6943
+ return this.readBytes(length);
6941
6944
  }
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
- );
6945
+ readString() {
6946
+ const bytes = this.readVecBytes();
6947
+ return new TextDecoder().decode(bytes);
6947
6948
  }
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
- );
6949
+ readVariant() {
6950
+ return this.readU32();
6954
6951
  }
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
- );
6952
+ readOption(readValue2) {
6953
+ const hasValue = this.readU8();
6954
+ if (hasValue === 0) {
6955
+ return null;
6956
+ }
6957
+ if (hasValue !== 1) {
6958
+ throw new Error(`Invalid option discriminant: ${hasValue}`);
6959
+ }
6960
+ return readValue2();
6961
6961
  }
6962
- static simulationFailed(logs, error) {
6963
- return new _TransactionError(
6964
- "SIMULATION_FAILED" /* SIMULATION_FAILED */,
6965
- `Transaction simulation failed: ${error}`,
6966
- { logs, error }
6967
- );
6962
+ readVec(readElement) {
6963
+ const length = this.readLength();
6964
+ const result = [];
6965
+ for (let i = 0; i < length; i++) {
6966
+ result.push(readElement());
6967
+ }
6968
+ return result;
6968
6969
  }
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
- );
6970
+ /**
6971
+ * Read a tuple of fixed size with heterogeneous types
6972
+ */
6973
+ readTuple(readers) {
6974
+ return readers.map((read) => read());
6975
6975
  }
6976
- toJSON() {
6977
- return {
6978
- code: this.code,
6979
- message: this.message,
6980
- details: this.details
6981
- };
6976
+ readMap(readKey, readValue2) {
6977
+ const length = this.readLength();
6978
+ const map = /* @__PURE__ */ new Map();
6979
+ for (let i = 0; i < length; i++) {
6980
+ const key = readKey();
6981
+ const value = readValue2();
6982
+ map.set(key, value);
6983
+ }
6984
+ return map;
6985
+ }
6986
+ // ========== Helpers ==========
6987
+ /**
6988
+ * Read length as u64 but validate it's within safe integer range
6989
+ */
6990
+ readLength() {
6991
+ const length = this.readU64();
6992
+ if (length > BigInt(Number.MAX_SAFE_INTEGER)) {
6993
+ throw new Error(`Length ${length} exceeds maximum safe integer`);
6994
+ }
6995
+ const numLength = Number(length);
6996
+ if (numLength > this.remaining()) {
6997
+ throw new Error(
6998
+ `Length ${numLength} exceeds remaining bytes ${this.remaining()}`
6999
+ );
7000
+ }
7001
+ return numLength;
7002
+ }
7003
+ ensureAvailable(bytes) {
7004
+ if (this.offset + bytes > this.bytes.length) {
7005
+ throw new Error(
7006
+ `Unexpected end of data: need ${bytes} bytes at offset ${this.offset}, but only ${this.bytes.length - this.offset} available`
7007
+ );
7008
+ }
6982
7009
  }
6983
7010
  };
6984
7011
 
@@ -7140,12 +7167,12 @@ var BincodeWriter = class {
7140
7167
  writeVariant(index) {
7141
7168
  return this.writeU32(index);
7142
7169
  }
7143
- writeOption(value, writeValue) {
7170
+ writeOption(value, writeValue2) {
7144
7171
  if (value === null || value === void 0) {
7145
7172
  this.writeU8(0);
7146
7173
  } else {
7147
7174
  this.writeU8(1);
7148
- writeValue(this, value);
7175
+ writeValue2(this, value);
7149
7176
  }
7150
7177
  return this;
7151
7178
  }
@@ -7168,11 +7195,11 @@ var BincodeWriter = class {
7168
7195
  }
7169
7196
  return this;
7170
7197
  }
7171
- writeMap(map, writeKey, writeValue) {
7198
+ writeMap(map, writeKey, writeValue2) {
7172
7199
  this.writeU64(BigInt(map.size));
7173
7200
  for (const [key, value] of map) {
7174
7201
  writeKey(this, key);
7175
- writeValue(this, value);
7202
+ writeValue2(this, value);
7176
7203
  }
7177
7204
  return this;
7178
7205
  }
@@ -7225,41 +7252,396 @@ var BincodeWriter = class {
7225
7252
  }
7226
7253
  };
7227
7254
 
7228
- // node_modules/@dao-xyz/borsh/lib/esm/binary.js
7229
- var import_float = __toESM(require_float());
7230
- var import_utf8 = __toESM(require_utf8());
7231
-
7232
- // node_modules/@dao-xyz/borsh/lib/esm/bigint.js
7233
- function writeBufferLEBigInt(num, width, buffer, offset) {
7234
- const hex = num.toString(16);
7235
- const padded = hex.padStart(width * 2, "0").slice(0, width * 2);
7236
- for (const [ix, value] of padded.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)).entries()) {
7237
- buffer[offset + width - 1 - ix] = value;
7238
- }
7255
+ // src/serialization/bincode/schema.ts
7256
+ var Schema = {
7257
+ u8: () => ({ type: "u8" }),
7258
+ u16: () => ({ type: "u16" }),
7259
+ u32: () => ({ type: "u32" }),
7260
+ u64: () => ({ type: "u64" }),
7261
+ u128: () => ({ type: "u128" }),
7262
+ i8: () => ({ type: "i8" }),
7263
+ i16: () => ({ type: "i16" }),
7264
+ i32: () => ({ type: "i32" }),
7265
+ i64: () => ({ type: "i64" }),
7266
+ i128: () => ({ type: "i128" }),
7267
+ f32: () => ({ type: "f32" }),
7268
+ f64: () => ({ type: "f64" }),
7269
+ bool: () => ({ type: "bool" }),
7270
+ string: () => ({ type: "string" }),
7271
+ bytes: () => ({ type: "bytes" }),
7272
+ unit: () => ({ type: "unit" }),
7273
+ fixedArray: (length) => ({
7274
+ type: "fixedArray",
7275
+ length
7276
+ }),
7277
+ vec: (element) => ({
7278
+ type: "vec",
7279
+ element
7280
+ }),
7281
+ option: (inner) => ({
7282
+ type: "option",
7283
+ inner
7284
+ }),
7285
+ tuple: (...elements) => ({
7286
+ type: "tuple",
7287
+ elements
7288
+ }),
7289
+ /**
7290
+ * Define a struct with ordered fields
7291
+ * @example
7292
+ * Schema.struct([
7293
+ * ["id", Schema.u64()],
7294
+ * ["name", Schema.string()],
7295
+ * ["active", Schema.bool()],
7296
+ * ])
7297
+ */
7298
+ struct: (fields) => ({
7299
+ type: "struct",
7300
+ fields: fields.map(([name, schema]) => ({ name, schema }))
7301
+ }),
7302
+ /**
7303
+ * Define an enum with ordered variants
7304
+ * @example
7305
+ * Schema.enum([
7306
+ * ["None", null],
7307
+ * ["Some", Schema.u64()],
7308
+ * ["Error", Schema.string()],
7309
+ * ])
7310
+ */
7311
+ enum: (variants) => ({
7312
+ type: "enum",
7313
+ variants: variants.map(([name, schema]) => ({ name, schema }))
7314
+ }),
7315
+ map: (key, value) => ({
7316
+ type: "map",
7317
+ key,
7318
+ value
7319
+ }),
7320
+ pubkey: () => ({ type: "pubkey" })
7321
+ };
7322
+ function serialize(schema, value) {
7323
+ const writer = new BincodeWriter();
7324
+ writeValue(writer, schema, value);
7325
+ return writer.toBytes();
7239
7326
  }
7240
- function writeUInt32LE(value, buf, offset) {
7241
- checkInt(value, 0, 4294967295, 3);
7242
- buf[offset] = value;
7243
- buf[offset + 1] = value >>> 8;
7244
- buf[offset + 2] = value >>> 16;
7245
- buf[offset + 3] = value >>> 24;
7327
+ function deserialize(schema, data) {
7328
+ const reader = new BincodeReader(data);
7329
+ const result = readValue(reader, schema);
7330
+ if (!reader.isExhausted()) {
7331
+ console.warn(
7332
+ `Bincode deserialize: ${reader.remaining()} bytes remaining after parsing`
7333
+ );
7334
+ }
7335
+ return result;
7246
7336
  }
7247
- function writeUInt16LE(value, buf, offset) {
7248
- checkInt(value, 0, 65535, 1);
7249
- buf[offset] = value;
7250
- buf[offset + 1] = value >>> 8;
7337
+ function deserializeStrict(schema, data) {
7338
+ const reader = new BincodeReader(data);
7339
+ const result = readValue(reader, schema);
7340
+ if (!reader.isExhausted()) {
7341
+ throw new Error(
7342
+ `Unexpected data: ${reader.remaining()} bytes remaining after parsing`
7343
+ );
7344
+ }
7345
+ return result;
7251
7346
  }
7252
- var writeBigUint64Le = (bigIntOrNumber, buf, offset) => {
7253
- let lo, hi;
7254
- if (typeof bigIntOrNumber === "bigint") {
7255
- if (bigIntOrNumber <= Number.MAX_SAFE_INTEGER) {
7256
- if (bigIntOrNumber < 0) {
7257
- throw new Error("u64 value can not negative, got " + bigIntOrNumber);
7258
- }
7259
- bigIntOrNumber = Number(bigIntOrNumber);
7260
- lo = bigIntOrNumber >>> 0;
7261
- hi = (bigIntOrNumber - lo) / 4294967296;
7262
- } else {
7347
+ function writeValue(writer, schema, value) {
7348
+ switch (schema.type) {
7349
+ case "u8":
7350
+ writer.writeU8(value);
7351
+ break;
7352
+ case "u16":
7353
+ writer.writeU16(value);
7354
+ break;
7355
+ case "u32":
7356
+ writer.writeU32(value);
7357
+ break;
7358
+ case "u64":
7359
+ writer.writeU64(value);
7360
+ break;
7361
+ case "u128":
7362
+ writer.writeU128(value);
7363
+ break;
7364
+ case "i8":
7365
+ writer.writeI8(value);
7366
+ break;
7367
+ case "i16":
7368
+ writer.writeI16(value);
7369
+ break;
7370
+ case "i32":
7371
+ writer.writeI32(value);
7372
+ break;
7373
+ case "i64":
7374
+ writer.writeI64(value);
7375
+ break;
7376
+ case "i128":
7377
+ writer.writeI128(value);
7378
+ break;
7379
+ case "f32":
7380
+ writer.writeF32(value);
7381
+ break;
7382
+ case "f64":
7383
+ writer.writeF64(value);
7384
+ break;
7385
+ case "bool":
7386
+ writer.writeBool(value);
7387
+ break;
7388
+ case "string":
7389
+ writer.writeString(value);
7390
+ break;
7391
+ case "bytes":
7392
+ writer.writeVecBytes(value);
7393
+ break;
7394
+ case "unit":
7395
+ break;
7396
+ case "fixedArray": {
7397
+ const arr = value;
7398
+ if (arr.length !== schema.length) {
7399
+ throw new Error(
7400
+ `Fixed array length mismatch: expected ${schema.length}, got ${arr.length}`
7401
+ );
7402
+ }
7403
+ writer.writeFixedArray(arr);
7404
+ break;
7405
+ }
7406
+ case "pubkey": {
7407
+ const arr = value;
7408
+ if (arr.length !== 32) {
7409
+ throw new Error(`Pubkey must be exactly 32 bytes, got ${arr.length}`);
7410
+ }
7411
+ writer.writeFixedArray(arr);
7412
+ break;
7413
+ }
7414
+ case "vec": {
7415
+ const arr = value;
7416
+ writer.writeU64(BigInt(arr.length));
7417
+ for (const item of arr) {
7418
+ writeValue(writer, schema.element, item);
7419
+ }
7420
+ break;
7421
+ }
7422
+ case "option": {
7423
+ if (value === null || value === void 0) {
7424
+ writer.writeU8(0);
7425
+ } else {
7426
+ writer.writeU8(1);
7427
+ writeValue(writer, schema.inner, value);
7428
+ }
7429
+ break;
7430
+ }
7431
+ case "tuple": {
7432
+ const arr = value;
7433
+ if (arr.length !== schema.elements.length) {
7434
+ throw new Error(
7435
+ `Tuple length mismatch: expected ${schema.elements.length}, got ${arr.length}`
7436
+ );
7437
+ }
7438
+ for (let i = 0; i < schema.elements.length; i++) {
7439
+ writeValue(writer, schema.elements[i], arr[i]);
7440
+ }
7441
+ break;
7442
+ }
7443
+ case "struct": {
7444
+ const obj = value;
7445
+ for (const field2 of schema.fields) {
7446
+ if (!(field2.name in obj)) {
7447
+ throw new Error(`Missing struct field: ${field2.name}`);
7448
+ }
7449
+ writeValue(writer, field2.schema, obj[field2.name]);
7450
+ }
7451
+ break;
7452
+ }
7453
+ case "enum": {
7454
+ const enumValue = value;
7455
+ const variantIndex = schema.variants.findIndex(
7456
+ (v) => v.name === enumValue.variant
7457
+ );
7458
+ if (variantIndex === -1) {
7459
+ const validVariants = schema.variants.map((v) => v.name).join(", ");
7460
+ throw new Error(
7461
+ `Unknown variant: ${enumValue.variant}. Valid variants: ${validVariants}`
7462
+ );
7463
+ }
7464
+ writer.writeVariant(variantIndex);
7465
+ const variantSchema = schema.variants[variantIndex].schema;
7466
+ if (variantSchema !== null) {
7467
+ writeValue(writer, variantSchema, enumValue.value);
7468
+ }
7469
+ break;
7470
+ }
7471
+ case "map": {
7472
+ const map = value;
7473
+ writer.writeU64(BigInt(map.size));
7474
+ for (const [k, v] of map) {
7475
+ writeValue(writer, schema.key, k);
7476
+ writeValue(writer, schema.value, v);
7477
+ }
7478
+ break;
7479
+ }
7480
+ default: {
7481
+ throw new Error(`Unknown schema type: ${JSON.stringify(schema)}`);
7482
+ }
7483
+ }
7484
+ }
7485
+ function readValue(reader, schema) {
7486
+ switch (schema.type) {
7487
+ case "u8":
7488
+ return reader.readU8();
7489
+ case "u16":
7490
+ return reader.readU16();
7491
+ case "u32":
7492
+ return reader.readU32();
7493
+ case "u64":
7494
+ return reader.readU64();
7495
+ case "u128":
7496
+ return reader.readU128();
7497
+ case "i8":
7498
+ return reader.readI8();
7499
+ case "i16":
7500
+ return reader.readI16();
7501
+ case "i32":
7502
+ return reader.readI32();
7503
+ case "i64":
7504
+ return reader.readI64();
7505
+ case "i128":
7506
+ return reader.readI128();
7507
+ case "f32":
7508
+ return reader.readF32();
7509
+ case "f64":
7510
+ return reader.readF64();
7511
+ case "bool":
7512
+ return reader.readBool();
7513
+ case "string":
7514
+ return reader.readString();
7515
+ case "bytes":
7516
+ return reader.readVecBytes();
7517
+ case "unit":
7518
+ return void 0;
7519
+ case "fixedArray":
7520
+ return reader.readFixedArray(schema.length);
7521
+ case "pubkey":
7522
+ return reader.readFixedArray(32);
7523
+ case "vec": {
7524
+ const lengthBigInt = reader.readU64();
7525
+ if (lengthBigInt > BigInt(Number.MAX_SAFE_INTEGER)) {
7526
+ throw new Error(
7527
+ `Vec length ${lengthBigInt} exceeds safe integer range`
7528
+ );
7529
+ }
7530
+ const length = Number(lengthBigInt);
7531
+ const result = [];
7532
+ for (let i = 0; i < length; i++) {
7533
+ result.push(readValue(reader, schema.element));
7534
+ }
7535
+ return result;
7536
+ }
7537
+ case "option": {
7538
+ const hasValue = reader.readU8();
7539
+ if (hasValue === 0) return null;
7540
+ if (hasValue !== 1) {
7541
+ throw new Error(`Invalid option discriminant: ${hasValue}`);
7542
+ }
7543
+ return readValue(reader, schema.inner);
7544
+ }
7545
+ case "tuple": {
7546
+ const result = [];
7547
+ for (const elementSchema of schema.elements) {
7548
+ result.push(readValue(reader, elementSchema));
7549
+ }
7550
+ return result;
7551
+ }
7552
+ case "struct": {
7553
+ const result = {};
7554
+ for (const field2 of schema.fields) {
7555
+ result[field2.name] = readValue(reader, field2.schema);
7556
+ }
7557
+ return result;
7558
+ }
7559
+ case "enum": {
7560
+ const variantIndex = reader.readVariant();
7561
+ if (variantIndex >= schema.variants.length) {
7562
+ throw new Error(
7563
+ `Invalid variant index: ${variantIndex}, max: ${schema.variants.length - 1}`
7564
+ );
7565
+ }
7566
+ const variant = schema.variants[variantIndex];
7567
+ if (variant.schema === null) {
7568
+ return { variant: variant.name };
7569
+ }
7570
+ return {
7571
+ variant: variant.name,
7572
+ value: readValue(reader, variant.schema)
7573
+ };
7574
+ }
7575
+ case "map": {
7576
+ const lengthBigInt = reader.readU64();
7577
+ if (lengthBigInt > BigInt(Number.MAX_SAFE_INTEGER)) {
7578
+ throw new Error(
7579
+ `Map length ${lengthBigInt} exceeds safe integer range`
7580
+ );
7581
+ }
7582
+ const length = Number(lengthBigInt);
7583
+ const map = /* @__PURE__ */ new Map();
7584
+ for (let i = 0; i < length; i++) {
7585
+ const key = readValue(reader, schema.key);
7586
+ const value = readValue(reader, schema.value);
7587
+ map.set(key, value);
7588
+ }
7589
+ return map;
7590
+ }
7591
+ default: {
7592
+ const _exhaustive = schema;
7593
+ throw new Error(
7594
+ `Unknown schema type: ${_exhaustive.type}`
7595
+ );
7596
+ }
7597
+ }
7598
+ }
7599
+
7600
+ // node_modules/@dao-xyz/borsh/lib/esm/binary.js
7601
+ var import_float = __toESM(require_float());
7602
+ var import_utf8 = __toESM(require_utf8());
7603
+
7604
+ // node_modules/@dao-xyz/borsh/lib/esm/bigint.js
7605
+ function arrayToHex(arr, reverse = false) {
7606
+ return [...reverse ? new Uint8Array(arr).reverse() : new Uint8Array(arr)].map((b) => b.toString(16).padStart(2, "0")).join("");
7607
+ }
7608
+ function toBigIntLE(buf) {
7609
+ const hex = arrayToHex(buf, true);
7610
+ if (hex.length === 0) {
7611
+ return BigInt(0);
7612
+ }
7613
+ return BigInt(`0x${hex}`);
7614
+ }
7615
+ function writeBufferLEBigInt(num, width, buffer, offset) {
7616
+ const hex = num.toString(16);
7617
+ const padded = hex.padStart(width * 2, "0").slice(0, width * 2);
7618
+ for (const [ix, value] of padded.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)).entries()) {
7619
+ buffer[offset + width - 1 - ix] = value;
7620
+ }
7621
+ }
7622
+ function writeUInt32LE(value, buf, offset) {
7623
+ checkInt(value, 0, 4294967295, 3);
7624
+ buf[offset] = value;
7625
+ buf[offset + 1] = value >>> 8;
7626
+ buf[offset + 2] = value >>> 16;
7627
+ buf[offset + 3] = value >>> 24;
7628
+ }
7629
+ function writeUInt16LE(value, buf, offset) {
7630
+ checkInt(value, 0, 65535, 1);
7631
+ buf[offset] = value;
7632
+ buf[offset + 1] = value >>> 8;
7633
+ }
7634
+ var writeBigUint64Le = (bigIntOrNumber, buf, offset) => {
7635
+ let lo, hi;
7636
+ if (typeof bigIntOrNumber === "bigint") {
7637
+ if (bigIntOrNumber <= Number.MAX_SAFE_INTEGER) {
7638
+ if (bigIntOrNumber < 0) {
7639
+ throw new Error("u64 value can not negative, got " + bigIntOrNumber);
7640
+ }
7641
+ bigIntOrNumber = Number(bigIntOrNumber);
7642
+ lo = bigIntOrNumber >>> 0;
7643
+ hi = (bigIntOrNumber - lo) / 4294967296;
7644
+ } else {
7263
7645
  if (bigIntOrNumber > 18446744073709551615n) {
7264
7646
  throw new Error("u64 value can exceed mav value got " + bigIntOrNumber);
7265
7647
  }
@@ -7282,6 +7664,39 @@ var writeBigUint64Le = (bigIntOrNumber, buf, offset) => {
7282
7664
  buf[offset + 6] = hi >>> 16;
7283
7665
  buf[offset + 7] = hi >>> 24;
7284
7666
  };
7667
+ var readBigUInt64LE = (buf, offset) => {
7668
+ const first = buf[offset];
7669
+ const last = buf[offset + 7];
7670
+ if (first === void 0 || last === void 0)
7671
+ throw new Error("Out of bounds");
7672
+ let lo = (first | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
7673
+ let hi = (buf[offset + 4] | buf[offset + 5] << 8 | buf[offset + 6] << 16 | last << 24) >>> 0;
7674
+ if (hi > 0) {
7675
+ return BigInt(lo) + (BigInt(hi) << 32n);
7676
+ }
7677
+ return BigInt(lo);
7678
+ };
7679
+ function readUIntLE(buf, offset, width) {
7680
+ const hex = arrayToHex(buf.subarray(offset, offset + width), true);
7681
+ if (hex.length === 0) {
7682
+ return BigInt(0);
7683
+ }
7684
+ return BigInt(`0x${hex}`);
7685
+ }
7686
+ var readUInt32LE = (buffer, offset) => {
7687
+ const first = buffer[offset];
7688
+ const last = buffer[offset + 3];
7689
+ if (first === void 0 || last === void 0)
7690
+ throw new Error("Out of bounds");
7691
+ return first + buffer[offset + 1] * 2 ** 8 + buffer[offset + 2] * 2 ** 16 + last * 2 ** 24;
7692
+ };
7693
+ var readUInt16LE = (buffer, offset) => {
7694
+ const first = buffer[offset];
7695
+ const last = buffer[offset + 1];
7696
+ if (first === void 0 || last === void 0)
7697
+ throw new Error("Out of bounds");
7698
+ return first + last * 2 ** 8;
7699
+ };
7285
7700
  var checkInt = (value, min, max, byteLength) => {
7286
7701
  if (value > max || value < min) {
7287
7702
  const n = "";
@@ -7532,6 +7947,205 @@ var BinaryWriter = class _BinaryWriter {
7532
7947
  return this._buf;
7533
7948
  }
7534
7949
  };
7950
+ var BinaryReader = class _BinaryReader {
7951
+ constructor(buf) {
7952
+ this._buf = buf;
7953
+ this._offset = 0;
7954
+ }
7955
+ bool() {
7956
+ return _BinaryReader.bool(this);
7957
+ }
7958
+ static bool(reader) {
7959
+ const value = reader._buf[reader._offset];
7960
+ reader._offset += 1;
7961
+ if (value !== 1 && value !== 0) {
7962
+ throw new BorshError("Unexpected value for boolean: " + value + ". Expecting either 1 or 0 ");
7963
+ }
7964
+ return value ? true : false;
7965
+ }
7966
+ u8() {
7967
+ return _BinaryReader.u8(this);
7968
+ }
7969
+ static u8(reader) {
7970
+ if (reader._offset >= reader._buf.length) {
7971
+ throw new BorshError("Reader out of bounds");
7972
+ }
7973
+ const value = reader._buf[reader._offset];
7974
+ reader._offset += 1;
7975
+ return value;
7976
+ }
7977
+ u16() {
7978
+ return _BinaryReader.u16(this);
7979
+ }
7980
+ static u16(reader) {
7981
+ const value = readUInt16LE(reader._buf, reader._offset);
7982
+ reader._offset += 2;
7983
+ return value;
7984
+ }
7985
+ u32() {
7986
+ return _BinaryReader.u32(this);
7987
+ }
7988
+ static u32(reader) {
7989
+ const value = readUInt32LE(reader._buf, reader._offset);
7990
+ reader._offset += 4;
7991
+ return value;
7992
+ }
7993
+ u64() {
7994
+ return _BinaryReader.u64(this);
7995
+ }
7996
+ static u64(reader) {
7997
+ const value = readBigUInt64LE(reader._buf, reader._offset);
7998
+ reader._offset += 8;
7999
+ return value;
8000
+ }
8001
+ u128() {
8002
+ return _BinaryReader.u128(this);
8003
+ }
8004
+ static u128(reader) {
8005
+ const value = readUIntLE(reader._buf, reader._offset, 16);
8006
+ reader._offset += 16;
8007
+ return value;
8008
+ }
8009
+ u256() {
8010
+ return _BinaryReader.u256(this);
8011
+ }
8012
+ static u256(reader) {
8013
+ const value = readUIntLE(reader._buf, reader._offset, 32);
8014
+ reader._offset += 32;
8015
+ return value;
8016
+ }
8017
+ u512() {
8018
+ return _BinaryReader.u512(this);
8019
+ }
8020
+ static u512(reader) {
8021
+ const buf = reader.buffer(64);
8022
+ return toBigIntLE(buf);
8023
+ }
8024
+ f32() {
8025
+ return _BinaryReader.f32(this);
8026
+ }
8027
+ static f32(reader) {
8028
+ const value = (0, import_float.readFloatLE)(reader._buf, reader._offset);
8029
+ reader._offset += 4;
8030
+ if (Number.isNaN(value)) {
8031
+ throw new BorshError("Recieved NaN reading f32");
8032
+ }
8033
+ return value;
8034
+ }
8035
+ f64() {
8036
+ return _BinaryReader.f64(this);
8037
+ }
8038
+ static f64(reader) {
8039
+ const value = (0, import_float.readDoubleLE)(reader._buf, reader._offset);
8040
+ reader._offset += 8;
8041
+ if (Number.isNaN(value)) {
8042
+ throw new BorshError("Recieved NaN reading f64");
8043
+ }
8044
+ return value;
8045
+ }
8046
+ string() {
8047
+ return _BinaryReader.string(this);
8048
+ }
8049
+ static string(reader) {
8050
+ const len = reader.u32();
8051
+ const end = reader._offset + len;
8052
+ if (end > reader._buf.length) {
8053
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8054
+ }
8055
+ try {
8056
+ const string = import_utf8.default.read(reader._buf, reader._offset, end);
8057
+ reader._offset = end;
8058
+ return string;
8059
+ } catch (e) {
8060
+ throw new BorshError(`Error decoding UTF-8 string: ${e}`);
8061
+ }
8062
+ }
8063
+ static bufferString(reader) {
8064
+ const len = reader.u32();
8065
+ const end = reader._offset + len;
8066
+ if (end > reader._buf.length) {
8067
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8068
+ }
8069
+ const string = reader._buf.toString(void 0, reader._offset, end);
8070
+ reader._offset = end;
8071
+ return string;
8072
+ }
8073
+ static bufferStringCustom(reader, length) {
8074
+ const len = length(reader);
8075
+ const end = reader._offset + len;
8076
+ if (end > reader._buf.length) {
8077
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8078
+ }
8079
+ try {
8080
+ const string = reader._buf.toString(void 0, reader._offset, end);
8081
+ reader._offset = end;
8082
+ return string;
8083
+ } catch (e) {
8084
+ throw new BorshError(`Error decoding UTF-8 string: ${e}`);
8085
+ }
8086
+ }
8087
+ static stringCustom(reader, length) {
8088
+ const len = length(reader);
8089
+ const end = reader._offset + len;
8090
+ if (end > reader._buf.length) {
8091
+ throw new BorshError("Error decoding UTF-8 string: Invalid length");
8092
+ }
8093
+ try {
8094
+ const string = import_utf8.default.read(reader._buf, reader._offset, end);
8095
+ reader._offset = end;
8096
+ return string;
8097
+ } catch (e) {
8098
+ throw new BorshError(`Error decoding UTF-8 string: ${e}`);
8099
+ }
8100
+ }
8101
+ static read(encoding, fromBuffer) {
8102
+ if (encoding === "u8") {
8103
+ return _BinaryReader.u8;
8104
+ } else if (encoding === "u16") {
8105
+ return _BinaryReader.u16;
8106
+ } else if (encoding === "u32") {
8107
+ return _BinaryReader.u32;
8108
+ } else if (encoding === "u64") {
8109
+ return _BinaryReader.u64;
8110
+ } else if (encoding === "u128") {
8111
+ return _BinaryReader.u128;
8112
+ } else if (encoding === "u256") {
8113
+ return _BinaryReader.u256;
8114
+ } else if (encoding === "u512") {
8115
+ return _BinaryReader.u512;
8116
+ } else if (encoding === "string") {
8117
+ return fromBuffer ? _BinaryReader.bufferString : _BinaryReader.string;
8118
+ } else if (encoding === "bool") {
8119
+ return _BinaryReader.bool;
8120
+ } else if (encoding === "f32") {
8121
+ return _BinaryReader.f32;
8122
+ } else if (encoding === "f64") {
8123
+ return _BinaryReader.f64;
8124
+ } else {
8125
+ throw new Error("Unsupported encoding: " + encoding);
8126
+ }
8127
+ }
8128
+ buffer(len) {
8129
+ const end = this._offset + len;
8130
+ const result = this._buf.subarray(this._offset, end);
8131
+ this._offset = end;
8132
+ return result;
8133
+ }
8134
+ uint8Array() {
8135
+ return _BinaryReader.uint8Array(this);
8136
+ }
8137
+ static uint8Array(reader, size = reader.u32()) {
8138
+ return reader.buffer(size);
8139
+ }
8140
+ readArray(fn) {
8141
+ const len = this.u32();
8142
+ const result = new Array(len);
8143
+ for (let i = 0; i < len; ++i) {
8144
+ result[i] = fn();
8145
+ }
8146
+ return result;
8147
+ }
8148
+ };
7535
8149
 
7536
8150
  // node_modules/@dao-xyz/borsh/lib/esm/types.js
7537
8151
  var extendingClasses = (clazz) => {
@@ -7570,18 +8184,53 @@ var StringType = class {
7570
8184
  };
7571
8185
  var OptionKind = class extends WrappedType {
7572
8186
  };
8187
+ var option = (type) => {
8188
+ return new OptionKind(type);
8189
+ };
7573
8190
  var VecKind = class extends WrappedType {
7574
8191
  constructor(elementType, sizeEncoding) {
7575
8192
  super(elementType);
7576
8193
  this.sizeEncoding = sizeEncoding;
7577
8194
  }
7578
8195
  };
8196
+ var vec = (type, sizeEncoding = "u32") => {
8197
+ return new VecKind(type, sizeEncoding);
8198
+ };
7579
8199
  var FixedArrayKind = class extends WrappedType {
7580
8200
  constructor(type, length) {
7581
8201
  super(type);
7582
8202
  this.length = length;
7583
8203
  }
7584
8204
  };
8205
+ var fixedArray = (type, length) => {
8206
+ return new FixedArrayKind(type, length);
8207
+ };
8208
+ var StructKind = class {
8209
+ constructor(properties) {
8210
+ if (properties) {
8211
+ this.fields = properties.fields;
8212
+ this.variant = properties.variant;
8213
+ } else {
8214
+ this.fields = [];
8215
+ }
8216
+ }
8217
+ getDependencies() {
8218
+ let ret = [];
8219
+ this.fields.forEach((field2, ix) => {
8220
+ if (!field2) {
8221
+ throw new BorshError("Field: " + ix + " is missing specification");
8222
+ }
8223
+ if (field2.type instanceof WrappedType) {
8224
+ let dependency = field2.type.getDependency();
8225
+ if (dependency)
8226
+ ret.push(dependency);
8227
+ } else if (typeof field2.type === "function") {
8228
+ ret.push(field2.type);
8229
+ }
8230
+ });
8231
+ return ret;
8232
+ }
8233
+ };
7585
8234
 
7586
8235
  // node_modules/@dao-xyz/borsh/lib/esm/index.js
7587
8236
  var MAX_PROTOTYPE_SEARCH = 250;
@@ -7589,7 +8238,7 @@ var PROTOTYPE_POLLUTION_CONTEXT_RANGE = 500;
7589
8238
  var PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET = 500;
7590
8239
  var PROTOTYPE_DEPENDENCY_HANDLER_OFFSET = PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + PROTOTYPE_POLLUTION_CONTEXT_RANGE;
7591
8240
  var PROTOTYPE_SCHEMA_OFFSET = PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + PROTOTYPE_POLLUTION_CONTEXT_RANGE * 2;
7592
- function serialize(obj, writer = new BinaryWriter()) {
8241
+ function serialize2(obj, writer = new BinaryWriter()) {
7593
8242
  (obj.constructor._borsh_serialize || (obj.constructor._borsh_serialize = serializeStruct(obj.constructor, true)))(obj, writer);
7594
8243
  return writer.finalize();
7595
8244
  }
@@ -7597,6 +8246,15 @@ function recursiveSerialize(obj, writer = new BinaryWriter()) {
7597
8246
  (obj.constructor._borsh_serialize_recursive || (obj.constructor._borsh_serialize_recursive = serializeStruct(obj.constructor, false)))(obj, writer);
7598
8247
  return writer.finalize();
7599
8248
  }
8249
+ function deserialize2(buffer, classType, options) {
8250
+ const reader = new BinaryReader(buffer);
8251
+ let fromBuffer = buffer.constructor !== Uint8Array;
8252
+ const result = deserializeStruct(classType, fromBuffer)(reader, options);
8253
+ if (reader._offset !== buffer.length) {
8254
+ 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`);
8255
+ }
8256
+ return result;
8257
+ }
7600
8258
  function serializeField(fieldName, fieldType, options) {
7601
8259
  if (typeof fieldType.serialize == "function") {
7602
8260
  return (obj, writer) => fieldType.serialize(obj, writer);
@@ -7717,94 +8375,517 @@ function serializeStruct(ctor, allowCustomSerializer = true) {
7717
8375
  } : (_obj, writer) => writer.string(index);
7718
8376
  }
7719
8377
  }
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
- }
8378
+ if (allowCustomSerializer && schema.serializer) {
8379
+ let prev = handle;
8380
+ handle = prev ? (obj, writer) => {
8381
+ prev(obj, writer);
8382
+ schema.serializer(obj, writer, (obj2) => recursiveSerialize(obj2));
8383
+ } : (obj, writer) => schema.serializer(obj, writer, (obj2) => recursiveSerialize(obj2));
8384
+ } else {
8385
+ for (const field2 of schema.fields) {
8386
+ let prev = handle;
8387
+ const fieldHandle = serializeField(field2.key, field2.type);
8388
+ if (prev) {
8389
+ handle = (obj, writer) => {
8390
+ prev(obj, writer);
8391
+ fieldHandle(obj[field2.key], writer);
8392
+ };
8393
+ } else {
8394
+ handle = (obj, writer) => fieldHandle(obj[field2.key], writer);
8395
+ }
8396
+ }
8397
+ }
8398
+ } else if (once && !getDependencies(ctor, i)?.length) {
8399
+ return handle;
8400
+ }
8401
+ i++;
8402
+ if (i == MAX_PROTOTYPE_SEARCH && !once) {
8403
+ throw new BorshError(`Class ${ctor.name} is missing in schema`);
8404
+ }
8405
+ }
8406
+ }
8407
+ var MAX_ARRAY_SIZE_ALLOCATION = 1024 * 1024;
8408
+ function deserializeField(fieldName, fieldType, fromBuffer) {
8409
+ try {
8410
+ if (typeof fieldType === "string") {
8411
+ return BinaryReader.read(fieldType, fromBuffer);
8412
+ }
8413
+ if (fieldType === Uint8Array) {
8414
+ return (reader) => reader.uint8Array();
8415
+ }
8416
+ if (fieldType instanceof VecKind || fieldType instanceof FixedArrayKind) {
8417
+ if (fieldType.elementType === "u8") {
8418
+ if (fieldType instanceof FixedArrayKind) {
8419
+ return (reader) => reader.buffer(fieldType.length);
8420
+ } else {
8421
+ const sizeHandle = BinaryReader.read(fieldType.sizeEncoding, fromBuffer);
8422
+ return (reader) => BinaryReader.uint8Array(reader, sizeHandle(reader));
8423
+ }
8424
+ } else {
8425
+ let sizeHandle = fieldType instanceof VecKind ? BinaryReader.read(fieldType.sizeEncoding, fromBuffer) : () => fieldType.length;
8426
+ const fieldHandle = deserializeField(null, fieldType.elementType, fromBuffer);
8427
+ return (reader, options) => {
8428
+ const len = sizeHandle(reader);
8429
+ if (len < MAX_ARRAY_SIZE_ALLOCATION) {
8430
+ let arr = new Array(len);
8431
+ for (let i = 0; i < len; i++) {
8432
+ arr[i] = fieldHandle(reader, options);
8433
+ }
8434
+ return arr;
8435
+ } else {
8436
+ let arr = new Array(MAX_ARRAY_SIZE_ALLOCATION);
8437
+ for (let i = 0; i < len; i++) {
8438
+ arr[i] = fieldHandle(reader, options);
8439
+ }
8440
+ return arr;
8441
+ }
8442
+ };
8443
+ }
8444
+ }
8445
+ if (fieldType instanceof StringType) {
8446
+ const sizeReader = BinaryReader.read(fieldType.sizeEncoding, fromBuffer);
8447
+ return fromBuffer ? (reader) => BinaryReader.bufferStringCustom(reader, sizeReader) : (reader) => BinaryReader.stringCustom(reader, sizeReader);
8448
+ }
8449
+ if (typeof fieldType["deserialize"] == "function") {
8450
+ return (reader) => fieldType.deserialize(reader);
8451
+ }
8452
+ if (fieldType instanceof OptionKind) {
8453
+ const fieldHandle = deserializeField(fieldName, fieldType.elementType, fromBuffer);
8454
+ return (reader, options) => {
8455
+ return reader.bool() ? fieldHandle(reader, options) : void 0;
8456
+ };
8457
+ }
8458
+ return deserializeStruct(fieldType, fromBuffer);
8459
+ } catch (error) {
8460
+ if (error instanceof BorshError) {
8461
+ error.addToFieldPath(fieldName);
8462
+ }
8463
+ throw error;
8464
+ }
8465
+ }
8466
+ function deserializeStruct(targetClazz, fromBuffer) {
8467
+ const handle = getCreateDeserializationHandle(targetClazz, 0, fromBuffer);
8468
+ return (reader, options) => {
8469
+ const result = handle({}, reader, options);
8470
+ if (!options?.unchecked && !options?.object && !checkClazzesCompatible(result.constructor, targetClazz)) {
8471
+ throw new BorshError(`Deserialization of ${targetClazz?.name || targetClazz} yielded another Class: ${result.constructor?.name} which are not compatible`);
8472
+ }
8473
+ return result;
8474
+ };
8475
+ }
8476
+ var getCreateDeserializationHandle = (clazz, offset, fromBuffer) => getDeserializationHandle(clazz, offset, fromBuffer) || setDeserializationHandle(clazz, offset, fromBuffer, createDeserializeStructHandle(clazz, offset, fromBuffer));
8477
+ var getDeserializationHandle = (clazz, offset, fromBuffer) => clazz.prototype[PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + offset + (fromBuffer ? MAX_PROTOTYPE_SEARCH : 0)];
8478
+ var setDeserializationHandle = (clazz, offset, fromBuffer, handle) => clazz.prototype[PROTOTYPE_DESERIALIZATION_HANDLER_OFFSET + offset + (fromBuffer ? MAX_PROTOTYPE_SEARCH : 0)] = handle;
8479
+ var createDeserializeStructHandle = (currClazz, offset, fromBuffer) => {
8480
+ let handle = void 0;
8481
+ let endHandle = (result, reader, options) => {
8482
+ if (options?.object) {
8483
+ return result;
8484
+ }
8485
+ return Object.assign(options?.construct ? new currClazz() : Object.create(currClazz.prototype), result);
8486
+ };
8487
+ let structSchema = getSchema(currClazz, offset);
8488
+ if (structSchema) {
8489
+ if (offset === 0) {
8490
+ let index = getVariantIndex(structSchema);
8491
+ if (index != null) {
8492
+ if (typeof index === "number") {
8493
+ handle = (_, reader, __) => {
8494
+ reader._offset += 1;
8495
+ };
8496
+ } else if (Array.isArray(index)) {
8497
+ handle = (_, reader, __) => {
8498
+ reader._offset += index.length;
8499
+ };
8500
+ } else {
8501
+ handle = (_, reader, __) => {
8502
+ reader.string();
8503
+ };
8504
+ }
8505
+ }
8506
+ }
8507
+ for (const field2 of structSchema.fields) {
8508
+ const prev = handle;
8509
+ const fieldHandle = deserializeField(field2.key, field2.type, fromBuffer);
8510
+ if (prev) {
8511
+ handle = (result, reader, options) => {
8512
+ prev(result, reader, options);
8513
+ result[field2.key] = fieldHandle(reader, options);
8514
+ };
8515
+ } else
8516
+ handle = (result, reader, options) => {
8517
+ result[field2.key] = fieldHandle(reader, options);
8518
+ };
8519
+ }
8520
+ }
8521
+ let dependencies = getAllDependencies(currClazz, offset);
8522
+ if (dependencies) {
8523
+ let variantToDepndency = [];
8524
+ let variantType;
8525
+ for (const [actualClazz, dependency] of dependencies) {
8526
+ const variantIndex = getVariantIndex(dependency.schema);
8527
+ let currentVariantType = typeof variantIndex === "object" ? variantIndex.length : typeof variantIndex;
8528
+ if (!variantType) {
8529
+ variantType = currentVariantType;
8530
+ } else if (currentVariantType !== variantType) {
8531
+ 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`);
8532
+ }
8533
+ variantToDepndency.push([variantIndex, actualClazz, dependency]);
8534
+ }
8535
+ if (variantType === "undefined") {
8536
+ if (dependencies.size === 1) {
8537
+ const dep = variantToDepndency[0];
8538
+ return (result, reader, options) => {
8539
+ handle && handle(result, reader, options);
8540
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8541
+ };
8542
+ } else
8543
+ throw new BorshError(`Failed to find class to deserialize to from ${currClazz.name}: but no variants are used which makes deserialization undeterministic`);
8544
+ }
8545
+ return (result, reader, options) => {
8546
+ handle && handle(result, reader, options);
8547
+ let next = void 0;
8548
+ let nextOffset = void 0;
8549
+ if (variantType === "number") {
8550
+ let agg = reader.u8();
8551
+ for (const dep of variantToDepndency) {
8552
+ if (agg === dep[0]) {
8553
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8554
+ }
8555
+ }
8556
+ } else if (variantType === "string") {
8557
+ let variant = reader.string();
8558
+ for (const dep of variantToDepndency) {
8559
+ if (variant === dep[0]) {
8560
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8561
+ }
8562
+ }
8563
+ } else {
8564
+ let agg = [];
8565
+ for (let i = 0; i < variantType; i++) {
8566
+ agg.push(reader.u8());
8567
+ }
8568
+ for (const dep of variantToDepndency) {
8569
+ let currentVariant = dep[0];
8570
+ if (currentVariant.length === agg.length && currentVariant.every((value, index) => value === agg[index])) {
8571
+ return getCreateDeserializationHandle(dep[1], dep[2].offset, fromBuffer)(result, reader, options);
8572
+ }
8573
+ }
8574
+ }
8575
+ if (next == void 0 && dependencies) {
8576
+ if (dependencies.size == 1) {
8577
+ const n = dependencies.entries().next().value;
8578
+ next = n[0];
8579
+ nextOffset = n[1].offset;
8580
+ } else if (dependencies.size > 1) {
8581
+ const classes = [...dependencies.entries()].map(([c]) => c.name).join(", ");
8582
+ throw new BorshError(`Failed to find class to deserialize to from ${currClazz.name} found: ${classes} but no variant matches bytes read from the buffer.`);
8583
+ }
8584
+ }
8585
+ if (next != null) {
8586
+ getCreateDeserializationHandle(next, nextOffset, fromBuffer)(result, reader, options);
8587
+ } else {
8588
+ return endHandle(result, reader, options);
8589
+ }
8590
+ };
8591
+ } else {
8592
+ if (handle) {
8593
+ return (result, reader, options) => {
8594
+ handle(result, reader, options);
8595
+ return endHandle(result, reader, options);
8596
+ };
8597
+ }
8598
+ return endHandle;
8599
+ }
8600
+ };
8601
+ var getOrCreateStructMeta = (clazz, offset) => {
8602
+ let schema = getSchema(clazz, offset);
8603
+ if (!schema) {
8604
+ schema = new StructKind();
8605
+ }
8606
+ setSchema(clazz, schema, offset);
8607
+ return schema;
8608
+ };
8609
+ var setDependencyToProtoType = (ctor, offset) => {
8610
+ let proto = Object.getPrototypeOf(ctor);
8611
+ while (proto.prototype?.constructor != void 0) {
8612
+ let newOffset = --offset;
8613
+ let dependencies = getDependencies(proto, newOffset);
8614
+ if (dependencies) {
8615
+ for (const dependency of dependencies) {
8616
+ if (ctor.prototype instanceof dependency || dependency === ctor) {
8617
+ return;
8618
+ }
8619
+ }
8620
+ } else {
8621
+ dependencies = [];
8622
+ }
8623
+ dependencies.push(ctor);
8624
+ setDependencies(proto, newOffset, dependencies);
8625
+ proto = Object.getPrototypeOf(proto);
8626
+ }
8627
+ };
8628
+ var getSuperMostClass = (clazz) => {
8629
+ while (Object.getPrototypeOf(clazz).prototype != void 0) {
8630
+ clazz = Object.getPrototypeOf(clazz);
8631
+ }
8632
+ return clazz;
8633
+ };
8634
+ var checkClazzesCompatible = (clazzA, clazzB) => {
8635
+ return clazzA == clazzB || clazzA.isPrototypeOf(clazzB) || clazzB.isPrototypeOf(clazzA);
8636
+ };
8637
+ var getDependencies = (ctor, offset) => ctor.prototype[PROTOTYPE_DEPENDENCY_HANDLER_OFFSET + offset];
8638
+ var setDependencies = (ctor, offset, dependencies) => {
8639
+ ctor.prototype[PROTOTYPE_DEPENDENCY_HANDLER_OFFSET + offset] = dependencies;
8640
+ };
8641
+ var getAllDependencies = (ctor, offset) => {
8642
+ let existing = getDependencies(ctor, offset);
8643
+ if (existing) {
8644
+ let ret = /* @__PURE__ */ new Map();
8645
+ for (const v of existing) {
8646
+ let schema = getSubMostSchema(v);
8647
+ if (schema.fields.length > 0 || schema.variant != void 0) {
8648
+ ret.set(v, { schema, offset: getOffset(v) });
8649
+ } else {
8650
+ let req = getAllDependencies(v, offset);
8651
+ for (const [rv, rk] of req) {
8652
+ ret.set(rv, rk);
8653
+ }
8654
+ }
8655
+ }
8656
+ return ret;
8657
+ }
8658
+ };
8659
+ var setSchema = (ctor, schemas, offset) => {
8660
+ ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + offset] = schemas;
8661
+ };
8662
+ var getSchema = (ctor, offset = getOffset(ctor)) => ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + offset];
8663
+ var getSubMostSchema = (ctor) => {
8664
+ let last = void 0;
8665
+ for (var i = 0; i < MAX_PROTOTYPE_SEARCH; i++) {
8666
+ const curr = ctor.prototype[PROTOTYPE_SCHEMA_OFFSET + i];
8667
+ if (!curr && last && !getDependencies(ctor, i)?.length) {
8668
+ return last;
8669
+ }
8670
+ last = curr;
8671
+ }
8672
+ return;
8673
+ };
8674
+ var getVariantIndex = (schema) => {
8675
+ return schema.variant;
8676
+ };
8677
+ function field(properties) {
8678
+ return (target, name) => {
8679
+ const offset = getOffset(target.constructor);
8680
+ setDependencyToProtoType(target.constructor, offset);
8681
+ const schemas = getOrCreateStructMeta(target.constructor, offset);
8682
+ const schema = schemas;
8683
+ const key = name.toString();
8684
+ let field2 = void 0;
8685
+ if (properties["type"] != void 0) {
8686
+ field2 = {
8687
+ key,
8688
+ type: properties["type"]
8689
+ };
8690
+ } else {
8691
+ field2 = {
8692
+ key,
8693
+ type: properties
8694
+ };
8695
+ }
8696
+ if (properties.index === void 0) {
8697
+ schema.fields.push(field2);
8698
+ } else {
8699
+ if (schema.fields[properties.index]) {
8700
+ throw new BorshError("Multiple fields defined at the same index: " + properties.index + ", class: " + target.constructor.name);
8701
+ }
8702
+ if (properties.index >= schema.fields.length) {
8703
+ resize(schema.fields, properties.index + 1, void 0);
8704
+ }
8705
+ schema.fields[properties.index] = field2;
8706
+ }
8707
+ };
8708
+ }
8709
+ var resize = (arr, newSize, defaultValue) => {
8710
+ while (newSize > arr.length)
8711
+ arr.push(defaultValue);
8712
+ arr.length = newSize;
8713
+ };
8714
+
8715
+ // src/serialization/borsh.ts
8716
+ function serializeBorsh(data) {
8717
+ return serialize2(data);
8718
+ }
8719
+ function deserializeBorsh(data, type) {
8720
+ return deserialize2(data, type);
8721
+ }
8722
+
8723
+ // src/transaction/account-meta-table.ts
8724
+ var AccountMetaTable = class {
8725
+ accounts = /* @__PURE__ */ new Map();
8726
+ accountOrder = [];
8727
+ /**
8728
+ * Add or update an account in the table.
8729
+ * If account already exists, merges signer/writable flags (OR operation).
8730
+ */
8731
+ add(meta) {
8732
+ const key = meta.pubkey.toString();
8733
+ if (this.accounts.has(key)) {
8734
+ const existing = this.accounts.get(key);
8735
+ existing.isSigner ||= meta.isSigner;
8736
+ existing.isWritable ||= meta.isWritable;
8737
+ } else {
8738
+ this.accounts.set(key, {
8739
+ pubkey: meta.pubkey,
8740
+ isSigner: meta.isSigner,
8741
+ isWritable: meta.isWritable
8742
+ });
8743
+ this.accountOrder.push(key);
8744
+ }
8745
+ }
8746
+ /**
8747
+ * Add multiple accounts at once.
8748
+ */
8749
+ addAll(metas) {
8750
+ for (const meta of metas) {
8751
+ this.add(meta);
8752
+ }
8753
+ }
8754
+ /**
8755
+ * Get the index of an account in the sorted order.
8756
+ * Returns -1 if account not found.
8757
+ */
8758
+ getIndex(pubkey) {
8759
+ const sorted = this.getSortedAccounts();
8760
+ return sorted.findIndex((entry) => entry.pubkey.equals(pubkey));
8761
+ }
8762
+ /**
8763
+ * Get sorted accounts according to transaction rules.
8764
+ */
8765
+ getSortedAccounts() {
8766
+ const entries = this.accountOrder.map((key) => this.accounts.get(key));
8767
+ return entries.sort((a, b) => {
8768
+ const aPriority = a.isSigner && a.isWritable ? 0 : a.isSigner ? 1 : a.isWritable ? 2 : 3;
8769
+ const bPriority = b.isSigner && b.isWritable ? 0 : b.isSigner ? 1 : b.isWritable ? 2 : 3;
8770
+ if (aPriority !== bPriority) {
8771
+ return aPriority - bPriority;
8772
+ }
8773
+ const aBytes = a.pubkey.toBytes();
8774
+ const bBytes = b.pubkey.toBytes();
8775
+ for (let i = 0; i < 32; i++) {
8776
+ if (aBytes[i] !== bBytes[i]) {
8777
+ return aBytes[i] - bBytes[i];
8778
+ }
8779
+ }
8780
+ return 0;
8781
+ });
8782
+ }
8783
+ /**
8784
+ * Get the message header based on sorted accounts.
8785
+ */
8786
+ getHeader() {
8787
+ const sorted = this.getSortedAccounts();
8788
+ let numRequiredSignatures = 0;
8789
+ let numReadonlySignedAccounts = 0;
8790
+ let numReadonlyUnsignedAccounts = 0;
8791
+ for (const entry of sorted) {
8792
+ if (entry.isSigner) {
8793
+ numRequiredSignatures++;
8794
+ if (!entry.isWritable) {
8795
+ numReadonlySignedAccounts++;
7738
8796
  }
8797
+ } else if (!entry.isWritable) {
8798
+ numReadonlyUnsignedAccounts++;
7739
8799
  }
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
8800
  }
8801
+ return {
8802
+ numRequiredSignatures,
8803
+ numReadonlySignedAccounts,
8804
+ numReadonlyUnsignedAccounts
8805
+ };
7747
8806
  }
7748
- }
7749
- var getSuperMostClass = (clazz) => {
7750
- while (Object.getPrototypeOf(clazz).prototype != void 0) {
7751
- clazz = Object.getPrototypeOf(clazz);
8807
+ /**
8808
+ * Get sorted public keys.
8809
+ */
8810
+ getPublicKeys() {
8811
+ return this.getSortedAccounts().map((entry) => entry.pubkey);
8812
+ }
8813
+ /**
8814
+ * Get number of accounts in table.
8815
+ */
8816
+ size() {
8817
+ return this.accounts.size;
7752
8818
  }
7753
- return clazz;
7754
- };
7755
- var checkClazzesCompatible = (clazzA, clazzB) => {
7756
- return clazzA == clazzB || clazzA.isPrototypeOf(clazzB) || clazzB.isPrototypeOf(clazzA);
7757
8819
  };
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
8820
 
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"
8821
+ // src/transaction/errors.ts
8822
+ var TransactionErrorCode = /* @__PURE__ */ ((TransactionErrorCode2) => {
8823
+ TransactionErrorCode2["INVALID_INSTRUCTION"] = "INVALID_INSTRUCTION";
8824
+ TransactionErrorCode2["INVALID_ACCOUNT_META"] = "INVALID_ACCOUNT_META";
8825
+ TransactionErrorCode2["NO_INSTRUCTIONS"] = "NO_INSTRUCTIONS";
8826
+ TransactionErrorCode2["DUPLICATE_ACCOUNT"] = "DUPLICATE_ACCOUNT";
8827
+ TransactionErrorCode2["MISSING_SIGNATURE"] = "MISSING_SIGNATURE";
8828
+ TransactionErrorCode2["INVALID_SIGNATURE"] = "INVALID_SIGNATURE";
8829
+ TransactionErrorCode2["SIGNATURE_OUT_OF_BOUNDS"] = "SIGNATURE_OUT_OF_BOUNDS";
8830
+ TransactionErrorCode2["SIGNER_NOT_FOUND"] = "SIGNER_NOT_FOUND";
8831
+ TransactionErrorCode2["ALREADY_SIGNED"] = "ALREADY_SIGNED";
8832
+ TransactionErrorCode2["INVALID_MESSAGE_FORMAT"] = "INVALID_MESSAGE_FORMAT";
8833
+ TransactionErrorCode2["INSUFFICIENT_DATA"] = "INSUFFICIENT_DATA";
8834
+ TransactionErrorCode2["SERIALIZATION_FAILED"] = "SERIALIZATION_FAILED";
8835
+ TransactionErrorCode2["SIMULATION_FAILED"] = "SIMULATION_FAILED";
8836
+ TransactionErrorCode2["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
8837
+ TransactionErrorCode2["BLOCKHASH_EXPIRED"] = "BLOCKHASH_EXPIRED";
8838
+ return TransactionErrorCode2;
8839
+ })(TransactionErrorCode || {});
8840
+ var TransactionError = class _TransactionError extends Error {
8841
+ constructor(code, message, details) {
8842
+ super(message);
8843
+ this.code = code;
8844
+ this.details = details;
8845
+ this.name = "TransactionError";
8846
+ }
8847
+ static noInstructions() {
8848
+ return new _TransactionError(
8849
+ "NO_INSTRUCTIONS" /* NO_INSTRUCTIONS */,
8850
+ "Transaction must contain at least one instruction. Use addInstruction() to add instructions."
7773
8851
  );
7774
8852
  }
7775
- const firstByte = data[cursor++];
7776
- if ((firstByte & 128) === 0) {
7777
- return [firstByte, cursor];
8853
+ static signerNotFound(pubkey) {
8854
+ return new _TransactionError(
8855
+ "SIGNER_NOT_FOUND" /* SIGNER_NOT_FOUND */,
8856
+ `Public key ${pubkey} is not a required signer for this transaction. Check that the account is marked as a signer in the instruction.`,
8857
+ { pubkey }
8858
+ );
7778
8859
  }
7779
- if (cursor >= data.length) {
7780
- throw new TransactionError(
7781
- "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
7782
- "Incomplete compact-u16 encoding"
8860
+ static missingSignature(index, pubkey) {
8861
+ return new _TransactionError(
8862
+ "MISSING_SIGNATURE" /* MISSING_SIGNATURE */,
8863
+ `Missing signature for signer ${index} (${pubkey}). Transaction requires ${index + 1} signatures.`,
8864
+ { index, pubkey }
7783
8865
  );
7784
8866
  }
7785
- const secondByte = data[cursor++];
7786
- if ((secondByte & 128) === 0) {
7787
- return [firstByte & 127 | secondByte << 7, cursor];
8867
+ static simulationFailed(logs, error) {
8868
+ return new _TransactionError(
8869
+ "SIMULATION_FAILED" /* SIMULATION_FAILED */,
8870
+ `Transaction simulation failed: ${error}`,
8871
+ { logs, error }
8872
+ );
7788
8873
  }
7789
- if (cursor >= data.length) {
7790
- throw new TransactionError(
7791
- "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
7792
- "Incomplete compact-u16 encoding"
8874
+ static insufficientFunds(required, available) {
8875
+ return new _TransactionError(
8876
+ "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */,
8877
+ `Insufficient funds: need ${required}, have ${available}`,
8878
+ { required: required.toString(), available: available.toString() }
7793
8879
  );
7794
8880
  }
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;
8881
+ toJSON() {
8882
+ return {
8883
+ code: this.code,
8884
+ message: this.message,
8885
+ details: this.details
8886
+ };
7803
8887
  }
7804
- buffer[offset] = value & 127 | 128;
7805
- buffer[offset + 1] = value >> 7;
7806
- return offset + 2;
7807
- }
8888
+ };
7808
8889
 
7809
8890
  // src/transaction/instructions/borsh-instruction.ts
7810
8891
  function createBorshInstruction(params) {
@@ -7936,7 +9017,7 @@ var Message = class _Message {
7936
9017
  numReadonlySignedAccounts: data[cursor++],
7937
9018
  numReadonlyUnsignedAccounts: data[cursor++]
7938
9019
  };
7939
- const [accountKeysLength, newCursor1] = deserializeCompactU162(data, cursor);
9020
+ const [accountKeysLength, newCursor1] = deserializeCompactU16(data, cursor);
7940
9021
  cursor = newCursor1;
7941
9022
  const accountKeys = [];
7942
9023
  for (let i = 0; i < accountKeysLength; i++) {
@@ -7962,7 +9043,7 @@ var Message = class _Message {
7962
9043
  new DataView(validFromBytes.buffer).getBigUint64(0, true)
7963
9044
  );
7964
9045
  cursor += 8;
7965
- const [instructionsLength, newCursor2] = deserializeCompactU162(
9046
+ const [instructionsLength, newCursor2] = deserializeCompactU16(
7966
9047
  data,
7967
9048
  cursor
7968
9049
  );
@@ -7976,7 +9057,7 @@ var Message = class _Message {
7976
9057
  );
7977
9058
  }
7978
9059
  const programIdIndex = data[cursor++];
7979
- const [accountIndexesLength, newCursor3] = deserializeCompactU162(
9060
+ const [accountIndexesLength, newCursor3] = deserializeCompactU16(
7980
9061
  data,
7981
9062
  cursor
7982
9063
  );
@@ -7991,7 +9072,7 @@ var Message = class _Message {
7991
9072
  }
7992
9073
  accountKeyIndexes.push(data[cursor++]);
7993
9074
  }
7994
- const [dataLength, newCursor4] = deserializeCompactU162(data, cursor);
9075
+ const [dataLength, newCursor4] = deserializeCompactU16(data, cursor);
7995
9076
  cursor = newCursor4;
7996
9077
  if (data.length < cursor + dataLength) {
7997
9078
  throw new TransactionError(
@@ -8078,7 +9159,7 @@ var Message = class _Message {
8078
9159
  return this.getSigners().findIndex((signer) => signer.equals(pubkey));
8079
9160
  }
8080
9161
  };
8081
- function deserializeCompactU162(data, currentCursor) {
9162
+ function deserializeCompactU16(data, currentCursor) {
8082
9163
  let cursor = currentCursor;
8083
9164
  if (cursor >= data.length) {
8084
9165
  throw new TransactionError(
@@ -8160,7 +9241,7 @@ var Transaction = class _Transaction {
8160
9241
  );
8161
9242
  }
8162
9243
  let cursor = 0;
8163
- const [signaturesLength, newCursor] = deserializeCompactU16(data, cursor);
9244
+ const [signaturesLength, newCursor] = deserializeCompactU162(data, cursor);
8164
9245
  cursor = newCursor;
8165
9246
  const signatures = [];
8166
9247
  for (let i = 0; i < signaturesLength; i++) {
@@ -8539,6 +9620,88 @@ var TransactionBuilder = class _TransactionBuilder {
8539
9620
  return Transaction.fromMessage(message);
8540
9621
  }
8541
9622
  };
9623
+
9624
+ // src/serialization/compact-u16.ts
9625
+ function serializeCompactU16(buffer, value) {
9626
+ if (value < 0 || value > 65535) {
9627
+ throw new TransactionError(
9628
+ "SERIALIZATION_FAILED" /* SERIALIZATION_FAILED */,
9629
+ `Value out of range for compact-u16: ${value}`
9630
+ );
9631
+ }
9632
+ if (value <= 127) {
9633
+ buffer.push(value);
9634
+ return;
9635
+ }
9636
+ if (value <= 16383) {
9637
+ buffer.push(value & 127 | 128);
9638
+ buffer.push(value >> 7 & 127);
9639
+ return;
9640
+ }
9641
+ buffer.push(value & 127 | 128);
9642
+ buffer.push(value >> 7 & 127 | 128);
9643
+ buffer.push(value >> 14 & 255);
9644
+ }
9645
+ function deserializeCompactU162(data, currentCursor) {
9646
+ let cursor = currentCursor;
9647
+ if (cursor >= data.length) {
9648
+ throw new TransactionError(
9649
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
9650
+ "Insufficient data for compact-u16"
9651
+ );
9652
+ }
9653
+ const firstByte = data[cursor++];
9654
+ if ((firstByte & 128) === 0) {
9655
+ return [firstByte, cursor];
9656
+ }
9657
+ if (cursor >= data.length) {
9658
+ throw new TransactionError(
9659
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
9660
+ "Incomplete compact-u16 encoding"
9661
+ );
9662
+ }
9663
+ const secondByte = data[cursor++];
9664
+ if ((secondByte & 128) === 0) {
9665
+ return [firstByte & 127 | secondByte << 7, cursor];
9666
+ }
9667
+ if (cursor >= data.length) {
9668
+ throw new TransactionError(
9669
+ "INSUFFICIENT_DATA" /* INSUFFICIENT_DATA */,
9670
+ "Incomplete compact-u16 encoding"
9671
+ );
9672
+ }
9673
+ const thirdByte = data[cursor++];
9674
+ const value = firstByte & 127 | (secondByte & 127) << 7 | thirdByte << 14;
9675
+ return [value, cursor];
9676
+ }
9677
+ function writeCompactU16(buffer, offset, value) {
9678
+ if (value < 128) {
9679
+ buffer[offset] = value;
9680
+ return offset + 1;
9681
+ }
9682
+ buffer[offset] = value & 127 | 128;
9683
+ buffer[offset + 1] = value >> 7;
9684
+ return offset + 2;
9685
+ }
9686
+
9687
+ // src/signer/keypair-signer.ts
9688
+ var KeypairSigner = class {
9689
+ constructor(keypair) {
9690
+ this.keypair = keypair;
9691
+ }
9692
+ /**
9693
+ * Returns the keypair's public key.
9694
+ */
9695
+ async getPublicKey() {
9696
+ return this.keypair.publicKey;
9697
+ }
9698
+ /**
9699
+ * Signs a message using the keypair's private key.
9700
+ */
9701
+ async signMessage(message) {
9702
+ return this.keypair.sign(message);
9703
+ }
9704
+ };
8542
9705
  /*! Bundled license information:
8543
9706
 
8544
9707
  @noble/ed25519/index.js:
@@ -8555,6 +9718,6 @@ var TransactionBuilder = class _TransactionBuilder {
8555
9718
  (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
8556
9719
  */
8557
9720
 
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 };
9721
+ export { AccountMetaTable, BASE_DERIVATION_PATH, BaseRpcClient, BincodeReader, BincodeWriter, 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, Schema, 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, deserialize, deserializeBorsh, deserializeCompactU162 as deserializeCompactU16, deserializeStrict, encodeBorshData, field, fixedArray, fromBase64, getDefaultRialoClientConfig, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, isOnCurve, option, seedToBytes, serialize, serializeBorsh, serializeCompactU16, sleep, toBase64, transferInstruction, vec, writeCompactU16 };
8559
9722
  //# sourceMappingURL=index.mjs.map
8560
9723
  //# sourceMappingURL=index.mjs.map