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