@meshsdk/core-cst 1.9.0-beta.5 → 1.9.0-beta.52

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.cjs CHANGED
@@ -3498,7 +3498,8 @@ __export(index_exports, {
3498
3498
  Bip32PrivateKeyHex: () => Bip32PrivateKeyHex2,
3499
3499
  Bip32PublicKey: () => Bip32PublicKey2,
3500
3500
  Bip32PublicKeyHex: () => Bip32PublicKeyHex2,
3501
- Cardano: () => import_core8.Cardano,
3501
+ BootstrapWitness: () => BootstrapWitness,
3502
+ Cardano: () => import_core9.Cardano,
3502
3503
  CardanoSDK: () => CardanoSDK,
3503
3504
  CardanoSDKSerializer: () => CardanoSDKSerializer,
3504
3505
  CardanoSDKUtil: () => CardanoSDKUtil,
@@ -3565,7 +3566,7 @@ __export(index_exports, {
3565
3566
  Script: () => Script,
3566
3567
  ScriptHash: () => ScriptHash,
3567
3568
  ScriptPubkey: () => ScriptPubkey,
3568
- Serialization: () => import_core8.Serialization,
3569
+ Serialization: () => import_core9.Serialization,
3569
3570
  Slot: () => Slot,
3570
3571
  StakeCredentialStatus: () => StakeCredentialStatus,
3571
3572
  StakeDelegation: () => StakeDelegation,
@@ -3600,6 +3601,7 @@ __export(index_exports, {
3600
3601
  buildRewardAddress: () => buildRewardAddress,
3601
3602
  buildScriptPubkey: () => buildScriptPubkey,
3602
3603
  bytesToHex: () => bytesToHex,
3604
+ calculateFees: () => calculateFees,
3603
3605
  checkSignature: () => checkSignature,
3604
3606
  clampScalar: () => clampScalar,
3605
3607
  computeAuxiliaryDataHash: () => computeAuxiliaryDataHash,
@@ -3674,7 +3676,7 @@ __export(index_exports, {
3674
3676
  v2ScriptToBech32: () => v2ScriptToBech32
3675
3677
  });
3676
3678
  module.exports = __toCommonJS(index_exports);
3677
- var import_core8 = require("@cardano-sdk/core");
3679
+ var import_core9 = require("@cardano-sdk/core");
3678
3680
 
3679
3681
  // src/types/cardano-sdk.ts
3680
3682
  var import_core = require("@cardano-sdk/core");
@@ -3683,7 +3685,9 @@ var import_util = require("@cardano-sdk/util");
3683
3685
  var Slot = import_core.Cardano.Slot;
3684
3686
  var Value = import_core.Serialization.Value;
3685
3687
  var Transaction = import_core.Serialization.Transaction;
3686
- var TransactionId = import_core.Cardano.TransactionId;
3688
+ var TransactionId = (value) => {
3689
+ return import_core.Cardano.TransactionId(value);
3690
+ };
3687
3691
  var TransactionBody = import_core.Serialization.TransactionBody;
3688
3692
  var TransactionWitnessSet = import_core.Serialization.TransactionWitnessSet;
3689
3693
  var AuxilliaryData = import_core.Serialization.AuxiliaryData;
@@ -3719,7 +3723,9 @@ var Ed25519PrivateExtendedKeyHex = (value) => (0, import_util.typedHex)(value, 1
3719
3723
  var Ed25519KeyHash2 = Crypto.Ed25519KeyHash;
3720
3724
  var Ed25519KeyHashHex2 = Crypto.Ed25519KeyHashHex;
3721
3725
  var Hash28ByteBase162 = Crypto.Hash28ByteBase16;
3722
- var Hash32ByteBase162 = Crypto.Hash32ByteBase16;
3726
+ var Hash32ByteBase162 = (value) => {
3727
+ return Crypto.Hash32ByteBase16(value);
3728
+ };
3723
3729
  var CredentialType = import_core.Cardano.CredentialType;
3724
3730
  var Certificate = import_core.Serialization.Certificate;
3725
3731
  var PoolId = import_core.Cardano.PoolId;
@@ -3749,7 +3755,9 @@ var CborWriter = import_core.Serialization.CborWriter;
3749
3755
  var ConstrPlutusData = import_core.Serialization.ConstrPlutusData;
3750
3756
  var RewardAccount = import_core.Cardano.RewardAccount;
3751
3757
  var Hash = import_core.Serialization.Hash;
3752
- var DatumHash = Crypto.Hash32ByteBase16;
3758
+ var DatumHash = (value) => {
3759
+ return Crypto.Hash32ByteBase16(value);
3760
+ };
3753
3761
  var Datum = import_core.Serialization.Datum;
3754
3762
  var ExUnits = import_core.Serialization.ExUnits;
3755
3763
  var NetworkId = import_core.Cardano.NetworkId;
@@ -3771,6 +3779,7 @@ var TxCBOR = import_core.Serialization.TxCBOR;
3771
3779
  var Ed25519PrivateKey2 = Crypto.Ed25519PrivateKey;
3772
3780
  var computeAuxiliaryDataHash = import_core.Cardano.computeAuxiliaryDataHash;
3773
3781
  var blake2b2 = Crypto.blake2b;
3782
+ var BootstrapWitness = import_core.Serialization.BootstrapWitness;
3774
3783
 
3775
3784
  // src/message-signing/check-signature.ts
3776
3785
  var import_crypto = require("@cardano-sdk/crypto");
@@ -4091,10 +4100,10 @@ var import_bech323 = require("bech32");
4091
4100
  var import_common7 = require("@meshsdk/common");
4092
4101
 
4093
4102
  // src/utils/builder.ts
4094
- var import_crypto3 = require("@cardano-sdk/crypto");
4103
+ var import_crypto3 = require("crypto");
4104
+ var import_crypto4 = require("@cardano-sdk/crypto");
4095
4105
  var import_util2 = require("@cardano-sdk/util");
4096
4106
  var import_hash = __toESM(require_hash(), 1);
4097
- var import_crypto4 = require("crypto");
4098
4107
  var import_common2 = require("@meshsdk/common");
4099
4108
  var buildBaseAddress = (networkId, paymentKeyHash, stakeKeyHash) => {
4100
4109
  return BaseAddress.fromCredentials(
@@ -4130,7 +4139,7 @@ var buildBip32PrivateKey = (entropy, password = "") => {
4130
4139
  const PBKDF2_KEY_SIZE = 96;
4131
4140
  const PBKDF2_DIGEST_ALGORITHM = "sha512";
4132
4141
  const _entropy = Buffer.from(entropy, "hex");
4133
- const xprv = (0, import_crypto4.pbkdf2Sync)(
4142
+ const xprv = (0, import_crypto3.pbkdf2Sync)(
4134
4143
  password,
4135
4144
  _entropy,
4136
4145
  PBKDF2_ITERATIONS,
@@ -4164,8 +4173,12 @@ var buildKeys = (privateKeyHex, accountIndex, keyIndex = 0) => {
4164
4173
  const dRepKey = accountKey.derive([3, keyIndex]).toRawKey();
4165
4174
  return { paymentKey, stakeKey, dRepKey };
4166
4175
  } else {
4167
- const paymentKey = buildEd25519PrivateKeyFromSecretKey(privateKeyHex[0]);
4168
- const stakeKey = buildEd25519PrivateKeyFromSecretKey(privateKeyHex[1]);
4176
+ const paymentKey = Ed25519PrivateKey2.fromNormalHex(
4177
+ Ed25519PrivateNormalKeyHex(privateKeyHex[0])
4178
+ );
4179
+ const stakeKey = Ed25519PrivateKey2.fromNormalHex(
4180
+ Ed25519PrivateNormalKeyHex(privateKeyHex[1])
4181
+ );
4169
4182
  return { paymentKey, stakeKey };
4170
4183
  }
4171
4184
  };
@@ -4186,7 +4199,7 @@ var buildScriptPubkey = (keyHash) => {
4186
4199
  };
4187
4200
  var buildDRepID = (dRepKey, networkId = NetworkId.Testnet, addressType = AddressType.EnterpriseKey) => {
4188
4201
  const dRepKeyBytes = Buffer.from(dRepKey, "hex");
4189
- const dRepIdHex = (0, import_crypto3.blake2b)(28).update(dRepKeyBytes).digest("hex");
4202
+ const dRepIdHex = (0, import_crypto4.blake2b)(28).update(dRepKeyBytes).digest("hex");
4190
4203
  const paymentAddress = EnterpriseAddress.packParts({
4191
4204
  networkId,
4192
4205
  paymentPart: {
@@ -4335,7 +4348,7 @@ var fromBuilderToPlutusData = (data) => {
4335
4348
  var fromPlutusDataToJson = (data) => {
4336
4349
  if (data.getKind() === PlutusDataKind.ConstrPlutusData) {
4337
4350
  const plutusData = data.asConstrPlutusData();
4338
- if (plutusData) {
4351
+ if (plutusData !== void 0) {
4339
4352
  const fields = plutusData.getData();
4340
4353
  const list = [];
4341
4354
  for (let i = 0; i < fields.getLength(); i++) {
@@ -4352,7 +4365,7 @@ var fromPlutusDataToJson = (data) => {
4352
4365
  } else if (data.getKind() === PlutusDataKind.Map) {
4353
4366
  const plutusMap = data.asMap();
4354
4367
  const mapList = [];
4355
- if (plutusMap) {
4368
+ if (plutusMap !== void 0) {
4356
4369
  const keys = plutusMap.getKeys();
4357
4370
  for (let i = 0; i < keys.getLength(); i++) {
4358
4371
  const key = keys.get(i);
@@ -4372,7 +4385,7 @@ var fromPlutusDataToJson = (data) => {
4372
4385
  }
4373
4386
  } else if (data.getKind() === PlutusDataKind.List) {
4374
4387
  const plutusList = data.asList();
4375
- if (plutusList) {
4388
+ if (plutusList !== void 0) {
4376
4389
  const list = [];
4377
4390
  for (let i = 0; i < plutusList.getLength(); i++) {
4378
4391
  const element = plutusList.get(i);
@@ -4384,16 +4397,16 @@ var fromPlutusDataToJson = (data) => {
4384
4397
  }
4385
4398
  } else if (data.getKind() === PlutusDataKind.Integer) {
4386
4399
  const plutusInt = data.asInteger();
4387
- if (plutusInt) {
4400
+ if (plutusInt !== void 0) {
4388
4401
  return {
4389
- int: BigInt(plutusInt.toString())
4402
+ int: plutusInt
4390
4403
  };
4391
4404
  } else {
4392
4405
  throw new Error("Invalid integer data found");
4393
4406
  }
4394
4407
  } else if (data.getKind() === PlutusDataKind.Bytes) {
4395
4408
  const plutusBytes = data.asBoundedBytes();
4396
- if (plutusBytes) {
4409
+ if (plutusBytes !== void 0) {
4397
4410
  return {
4398
4411
  bytes: Buffer.from(plutusBytes).toString("hex")
4399
4412
  };
@@ -4415,7 +4428,7 @@ var parseInlineDatum = (utxo) => {
4415
4428
  const datumCbor = utxo.inline_datum || "";
4416
4429
  return datumCborToJson(datumCbor);
4417
4430
  };
4418
- var deserializeDataHash = (dataHash) => DatumHash.fromHexBlob((0, import_util3.HexBlob)(dataHash));
4431
+ var deserializeDataHash = (dataHash) => DatumHash(dataHash);
4419
4432
  var deserializePlutusData = (plutusData) => PlutusData.fromCbor((0, import_util3.HexBlob)(plutusData));
4420
4433
 
4421
4434
  // src/utils/deserializer.ts
@@ -4442,7 +4455,7 @@ var deserializeScriptRef = (scriptRef) => Script.fromCbor((0, import_util4.HexBl
4442
4455
  var deserializeTxUnspentOutput = (txUnspentOutput) => TransactionUnspentOutput.fromCbor((0, import_util4.HexBlob)(txUnspentOutput));
4443
4456
  var deserializeValue = (value) => Value.fromCbor((0, import_util4.HexBlob)(value));
4444
4457
  var deserializeTx = (tx) => Transaction.fromCbor(import_core2.Serialization.TxCBOR(tx));
4445
- var deserializeTxHash = (txHash) => TransactionId.fromHexBlob((0, import_util4.HexBlob)(txHash));
4458
+ var deserializeTxHash = (txHash) => TransactionId(txHash);
4446
4459
 
4447
4460
  // src/utils/converter.ts
4448
4461
  var toAddress = (bech325) => Address.fromBech32(bech325);
@@ -4676,10 +4689,10 @@ var toNativeScript = (script) => {
4676
4689
  };
4677
4690
  var toValue = (assets) => {
4678
4691
  const multiAsset = /* @__PURE__ */ new Map();
4679
- assets.filter((asset) => asset.unit !== "lovelace").forEach((asset) => {
4692
+ assets.filter((asset) => asset.unit !== "lovelace" && asset.unit !== "").forEach((asset) => {
4680
4693
  multiAsset.set(AssetId(asset.unit), BigInt(asset.quantity));
4681
4694
  });
4682
- const lovelace = assets.find((asset) => asset.unit === "lovelace");
4695
+ const lovelace = assets.find((asset) => asset.unit === "lovelace" || asset.unit === "");
4683
4696
  const value = new Value(BigInt(lovelace ? lovelace.quantity : 0));
4684
4697
  if (assets.length > 1 || !lovelace) {
4685
4698
  value.setMultiasset(multiAsset);
@@ -4970,7 +4983,7 @@ var plutusDataToAddrBech32 = (plutusData, networkId = 0) => {
4970
4983
  }
4971
4984
  const cardanoPaymentCredential = {
4972
4985
  hash: Hash28ByteBase162(Buffer.from(paymentBytes).toString("hex")),
4973
- type: paymentConstrData.getAlternative() === BigInt(0) ? 0 : 1
4986
+ type: Number(paymentConstrData.getAlternative())
4974
4987
  };
4975
4988
  const delegationData = plutusDataList.get(1);
4976
4989
  const delegationConstrData = delegationData.asConstrPlutusData();
@@ -5005,15 +5018,27 @@ var plutusDataToAddrBech32 = (plutusData, networkId = 0) => {
5005
5018
  "Error: serializeAddressObj: Delegation inner part must contain 1 element"
5006
5019
  );
5007
5020
  }
5008
- const delegationBytes = delegationDataInnerList.get(0).asBoundedBytes();
5021
+ const delegationCredential = delegationDataInnerList.get(0).asConstrPlutusData();
5022
+ if (!delegationCredential) {
5023
+ throw new Error(
5024
+ "Error: serializeAddressObj: Delegation inner part must be a constructor"
5025
+ );
5026
+ }
5027
+ const delegationBytesList = delegationCredential.getData();
5028
+ if (delegationBytesList.getLength() !== 1) {
5029
+ throw new Error(
5030
+ "Error: serializeAddressObj: Delegation bytes part must contain 1 element"
5031
+ );
5032
+ }
5033
+ const delegationBytes = delegationBytesList.get(0).asBoundedBytes();
5009
5034
  if (!delegationBytes) {
5010
5035
  throw new Error(
5011
- "Error: serializeAddressObj: Delegation inner part must be bytes"
5036
+ "Error: serializeAddressObj: Delegation bytes part must be of type bytes"
5012
5037
  );
5013
5038
  }
5014
5039
  const cardanoStakeCredential = {
5015
5040
  hash: Hash28ByteBase162(Buffer.from(delegationBytes).toString("hex")),
5016
- type: delegationDataInnerConstrData.getAlternative() === BigInt(0) ? 0 : 1
5041
+ type: Number(delegationCredential.getAlternative())
5017
5042
  };
5018
5043
  return BaseAddress.fromCredentials(
5019
5044
  networkId,
@@ -5160,9 +5185,60 @@ var addVKeyWitnessSetToTransaction = (txHex, vkeyWitnessSet) => {
5160
5185
  return tx.toCbor();
5161
5186
  };
5162
5187
 
5188
+ // src/utils/fee.ts
5189
+ var calculateFees = (minFeeA, minFeeB, minFeeRefScriptCostPerByte, priceMem, priceStep, tx, refScriptSize) => {
5190
+ let fee = minFeeB + tx.toCbor().length / 2 * minFeeA;
5191
+ fee += calculateRefScriptFees(refScriptSize, minFeeRefScriptCostPerByte);
5192
+ let scriptFee = BigInt(0);
5193
+ let priceMemNumerator = priceMem;
5194
+ let priceMemDenominator = 1;
5195
+ while (priceMemNumerator % 1) {
5196
+ priceMemNumerator *= 10;
5197
+ priceMemDenominator *= 10;
5198
+ }
5199
+ let priceStepNumerator = priceStep;
5200
+ let priceStepDenominator = 1;
5201
+ while (priceStepNumerator % 1) {
5202
+ priceStepNumerator *= 10;
5203
+ priceStepDenominator *= 10;
5204
+ }
5205
+ if (tx.witnessSet().redeemers()) {
5206
+ for (const redeemer of tx.witnessSet().redeemers().values()) {
5207
+ scriptFee += redeemer.exUnits().mem() * BigInt(priceMemNumerator.toString()) / BigInt(priceMemDenominator.toString());
5208
+ scriptFee += redeemer.exUnits().steps() * BigInt(priceStepNumerator.toString()) / BigInt(priceStepDenominator.toString());
5209
+ if (priceMemNumerator % priceMemDenominator !== 0) {
5210
+ scriptFee += BigInt(1);
5211
+ }
5212
+ if (priceStepNumerator % priceStepDenominator !== 0) {
5213
+ scriptFee += BigInt(1);
5214
+ }
5215
+ }
5216
+ }
5217
+ return BigInt(fee) + scriptFee;
5218
+ };
5219
+ var calculateRefScriptFees = (refScriptSize, minFeeRefScriptCostPerByte, tierMultiplier = 1.2) => {
5220
+ let fee = 0;
5221
+ const tierSize = 25600;
5222
+ let currentRefScriptSize = refScriptSize;
5223
+ let multiplier = 1;
5224
+ while (currentRefScriptSize >= tierSize) {
5225
+ fee += tierSize * multiplier * minFeeRefScriptCostPerByte;
5226
+ currentRefScriptSize -= tierSize;
5227
+ multiplier *= tierMultiplier;
5228
+ }
5229
+ if (currentRefScriptSize > 0) {
5230
+ fee += currentRefScriptSize * multiplier * minFeeRefScriptCostPerByte;
5231
+ }
5232
+ fee = Math.ceil(fee);
5233
+ return fee;
5234
+ };
5235
+
5163
5236
  // src/resolvers/index.ts
5164
- var resolveDataHash = (data) => {
5165
- const plutusData = toPlutusData(data);
5237
+ var resolveDataHash = (rawData, type = "Mesh") => {
5238
+ const plutusData = fromBuilderToPlutusData({
5239
+ content: rawData,
5240
+ type
5241
+ });
5166
5242
  return plutusData.hash().toString();
5167
5243
  };
5168
5244
  var resolveNativeScriptAddress = (script, networkId = 0) => {
@@ -5280,7 +5356,8 @@ var resolveEd25519KeyHash = (bech325) => {
5280
5356
  };
5281
5357
 
5282
5358
  // src/serializer/index.ts
5283
- var import_core7 = require("@cardano-sdk/core");
5359
+ var import_buffer2 = require("buffer");
5360
+ var import_core8 = require("@cardano-sdk/core");
5284
5361
  var import_util9 = require("@cardano-sdk/util");
5285
5362
  var import_cbor3 = require("@harmoniclabs/cbor");
5286
5363
  var import_base32_encoding4 = __toESM(require("base32-encoding"), 1);
@@ -5391,7 +5468,7 @@ var toCardanoCert = (cert) => {
5391
5468
  return Certificate.newStakeDelegation(
5392
5469
  new import_core5.Serialization.StakeDelegation(
5393
5470
  rewardAddress.getPaymentCredential(),
5394
- Ed25519KeyHashHex2(cert.poolId)
5471
+ cert.poolId.startsWith("pool1") ? import_core5.Cardano.PoolId.toKeyHash(import_core5.Cardano.PoolId(cert.poolId)) : Ed25519KeyHashHex2(cert.poolId)
5395
5472
  )
5396
5473
  );
5397
5474
  }
@@ -5413,7 +5490,7 @@ var toCardanoCert = (cert) => {
5413
5490
  case "RetirePool": {
5414
5491
  return Certificate.newPoolRetirement(
5415
5492
  new import_core5.Serialization.PoolRetirement(
5416
- Ed25519KeyHashHex2(cert.poolId),
5493
+ cert.poolId.startsWith("pool1") ? import_core5.Cardano.PoolId.toKeyHash(import_core5.Cardano.PoolId(cert.poolId)) : Ed25519KeyHashHex2(cert.poolId),
5417
5494
  import_core5.Cardano.EpochNo(cert.epoch)
5418
5495
  )
5419
5496
  );
@@ -5666,48 +5743,6 @@ var toCardanoCert = (cert) => {
5666
5743
  }
5667
5744
  };
5668
5745
 
5669
- // src/utils/fee.ts
5670
- var calculateFees = (minFeeA, minFeeB, minFeeRefScriptCostPerByte, priceMem, priceStep, tx, refScriptSize) => {
5671
- let fee = minFeeB + tx.toCbor().length / 2 * minFeeA;
5672
- const tierSize = 25600;
5673
- let currentRefScriptSize = refScriptSize;
5674
- let multiplier = 1.2;
5675
- while (currentRefScriptSize >= tierSize) {
5676
- fee += tierSize * multiplier * minFeeRefScriptCostPerByte;
5677
- currentRefScriptSize -= tierSize;
5678
- multiplier *= multiplier;
5679
- }
5680
- if (currentRefScriptSize > 0) {
5681
- fee += currentRefScriptSize * multiplier * minFeeRefScriptCostPerByte;
5682
- }
5683
- let scriptFee = BigInt(0);
5684
- let priceMemNumerator = priceMem;
5685
- let priceMemDenominator = 1;
5686
- while (priceMemNumerator % 1) {
5687
- priceMemNumerator *= 10;
5688
- priceMemDenominator *= 10;
5689
- }
5690
- let priceStepNumerator = priceStep;
5691
- let priceStepDenominator = 1;
5692
- while (priceStepNumerator % 1) {
5693
- priceStepNumerator *= 10;
5694
- priceStepDenominator *= 10;
5695
- }
5696
- if (tx.witnessSet().redeemers()) {
5697
- for (const redeemer of tx.witnessSet().redeemers().values()) {
5698
- scriptFee += redeemer.exUnits().mem() * BigInt(priceMemNumerator.toString()) / BigInt(priceMemDenominator.toString());
5699
- scriptFee += redeemer.exUnits().steps() * BigInt(priceStepNumerator.toString()) / BigInt(priceStepDenominator.toString());
5700
- if (priceMemNumerator % priceMemDenominator !== 0) {
5701
- scriptFee += BigInt(1);
5702
- }
5703
- if (priceStepNumerator % priceStepDenominator !== 0) {
5704
- scriptFee += BigInt(1);
5705
- }
5706
- }
5707
- }
5708
- return BigInt(fee) + scriptFee;
5709
- };
5710
-
5711
5746
  // src/utils/metadata.ts
5712
5747
  var toCardanoMetadataMap = (metadata) => {
5713
5748
  let cardanoMetadataMap = /* @__PURE__ */ new Map();
@@ -5747,27 +5782,19 @@ var import_core6 = require("@cardano-sdk/core");
5747
5782
  var Crypto3 = __toESM(require("@cardano-sdk/crypto"), 1);
5748
5783
  var import_crypto8 = require("@cardano-sdk/crypto");
5749
5784
  var import_util8 = require("@cardano-sdk/util");
5750
- var CBOR_EMPTY_LIST = new Uint8Array([128]);
5751
5785
  var CBOR_EMPTY_MAP = new Uint8Array([160]);
5752
- var getCborEncodedArray = (items) => {
5753
- const writer = new import_core6.Serialization.CborWriter();
5754
- writer.writeStartArray(items.length);
5755
- for (const item of items) {
5756
- writer.writeEncodedValue(Buffer.from(item.toCbor(), "hex"));
5757
- }
5758
- return writer.encode();
5759
- };
5760
5786
  var hashScriptData = (costModels, redemeers, datums) => {
5761
5787
  const writer = new import_core6.Serialization.CborWriter();
5762
- if (datums && datums.length > 0 && (!redemeers || redemeers.length === 0)) {
5763
- writer.writeEncodedValue(CBOR_EMPTY_LIST);
5764
- writer.writeEncodedValue(getCborEncodedArray(datums));
5788
+ if (datums && datums.size() > 0 && (!redemeers || redemeers.size() === 0)) {
5789
+ writer.writeEncodedValue(CBOR_EMPTY_MAP);
5790
+ writer.writeEncodedValue(Buffer.from(datums.toCbor(), "hex"));
5765
5791
  writer.writeEncodedValue(CBOR_EMPTY_MAP);
5766
5792
  } else {
5767
- if (!redemeers || redemeers.length === 0) return void 0;
5768
- writer.writeEncodedValue(getCborEncodedArray(redemeers));
5769
- if (datums && datums.length > 0)
5770
- writer.writeEncodedValue(getCborEncodedArray(datums));
5793
+ if (!redemeers || redemeers.size() === 0) return void 0;
5794
+ writer.writeEncodedValue(Buffer.from(redemeers.toCbor(), "hex"));
5795
+ if (datums && datums.size() > 0) {
5796
+ writer.writeEncodedValue(Buffer.from(datums.toCbor(), "hex"));
5797
+ }
5771
5798
  writer.writeEncodedValue(
5772
5799
  Buffer.from(costModels.languageViewsEncoding(), "hex")
5773
5800
  );
@@ -5779,13 +5806,90 @@ var hashScriptData = (costModels, redemeers, datums) => {
5779
5806
  );
5780
5807
  };
5781
5808
 
5809
+ // src/utils/vote.ts
5810
+ var import_core7 = require("@cardano-sdk/core");
5811
+ var toCardanoVoter = (voter) => {
5812
+ switch (voter.type) {
5813
+ case "ConstitutionalCommittee": {
5814
+ switch (voter.hotCred.type) {
5815
+ case "KeyHash": {
5816
+ return import_core7.Serialization.Voter.newConstitutionalCommitteeHotKey({
5817
+ type: 0,
5818
+ hash: Hash28ByteBase162(voter.hotCred.keyHash)
5819
+ });
5820
+ }
5821
+ case "ScriptHash": {
5822
+ return import_core7.Serialization.Voter.newConstitutionalCommitteeHotKey({
5823
+ type: 1,
5824
+ hash: Hash28ByteBase162(voter.hotCred.scriptHash)
5825
+ });
5826
+ }
5827
+ }
5828
+ }
5829
+ case "DRep": {
5830
+ const cardanoDrep = toDRep(voter.drepId);
5831
+ if (cardanoDrep.toKeyHash() !== void 0) {
5832
+ return import_core7.Serialization.Voter.newDrep({
5833
+ type: 0,
5834
+ hash: Hash28ByteBase162(cardanoDrep.toKeyHash())
5835
+ });
5836
+ } else if (cardanoDrep.toScriptHash() !== void 0) {
5837
+ return import_core7.Serialization.Voter.newDrep({
5838
+ type: 1,
5839
+ hash: Hash28ByteBase162(cardanoDrep.toScriptHash())
5840
+ });
5841
+ } else {
5842
+ throw new Error("Invalid DRep provided");
5843
+ }
5844
+ }
5845
+ case "StakingPool": {
5846
+ return import_core7.Serialization.Voter.newStakingPool(
5847
+ Ed25519KeyHashHex2(voter.keyHash)
5848
+ );
5849
+ }
5850
+ }
5851
+ };
5852
+ var toCardanoVotingProcedure = (votingProcedure) => {
5853
+ return new import_core7.Serialization.VotingProcedure(
5854
+ toCardanoVoteKind(votingProcedure.voteKind),
5855
+ votingProcedure.anchor ? toCardanoAnchor(votingProcedure.anchor) : void 0
5856
+ );
5857
+ };
5858
+ var toCardanoAnchor = (anchor) => {
5859
+ return new import_core7.Serialization.Anchor(
5860
+ anchor.anchorUrl,
5861
+ Hash32ByteBase162(anchor.anchorDataHash)
5862
+ );
5863
+ };
5864
+ var toCardanoVoteKind = (voteType) => {
5865
+ switch (voteType) {
5866
+ case "Yes": {
5867
+ return 1;
5868
+ }
5869
+ case "No": {
5870
+ return 0;
5871
+ }
5872
+ case "Abstain": {
5873
+ return 2;
5874
+ }
5875
+ }
5876
+ };
5877
+ var toCardanoGovernanceActionId = (govActionId) => {
5878
+ return new import_core7.Serialization.GovernanceActionId(
5879
+ import_core7.Cardano.TransactionId(govActionId.txHash),
5880
+ BigInt(govActionId.txIndex)
5881
+ );
5882
+ };
5883
+
5782
5884
  // src/serializer/index.ts
5885
+ var VKEY_PUBKEY_SIZE_BYTES = 32;
5886
+ var VKEY_SIGNATURE_SIZE_BYTES = 64;
5887
+ var CHAIN_CODE_SIZE_BYTES = 32;
5783
5888
  var CardanoSDKSerializer = class {
5784
- verbose;
5785
5889
  protocolParams;
5786
- constructor(protocolParams, verbose = false) {
5890
+ constructor(protocolParams) {
5891
+ (0, import_core8.setInConwayEra)(true);
5787
5892
  this.protocolParams = protocolParams || import_common8.DEFAULT_PROTOCOL_PARAMETERS;
5788
- this.verbose = verbose;
5789
5893
  }
5790
5894
  serializeRewardAddress(stakeKeyHash, isScriptHash, network_id) {
5791
5895
  return RewardAddress.fromCredentials(network_id ?? 0, {
@@ -5915,7 +6019,7 @@ var CardanoSDKSerializer = class {
5915
6019
  resolvePrivateKey: function(words) {
5916
6020
  const buildBip32PrivateKey2 = (entropy2, password = "") => {
5917
6021
  return Bip32PrivateKey2.fromBip39Entropy(
5918
- Buffer.from((0, import_common8.toBytes)(entropy2)),
6022
+ import_buffer2.Buffer.from((0, import_common8.toBytes)(entropy2)),
5919
6023
  (0, import_common8.fromUTF8)(password)
5920
6024
  );
5921
6025
  };
@@ -5947,12 +6051,12 @@ var CardanoSDKSerializer = class {
5947
6051
  },
5948
6052
  tx: {
5949
6053
  resolveTxHash: function(txHex) {
5950
- return Transaction.fromCbor(import_core7.Serialization.TxCBOR(txHex)).getId();
6054
+ return Transaction.fromCbor(import_core8.Serialization.TxCBOR(txHex)).getId();
5951
6055
  }
5952
6056
  },
5953
6057
  data: {
5954
- resolveDataHash: function(data) {
5955
- return fromBuilderToPlutusData({ type: "Mesh", content: data }).hash();
6058
+ resolveDataHash: function(rawData, type = "Mesh") {
6059
+ return resolveDataHash(rawData, type);
5956
6060
  }
5957
6061
  },
5958
6062
  script: {
@@ -6011,24 +6115,18 @@ var CardanoSDKSerializer = class {
6011
6115
  }
6012
6116
  }
6013
6117
  };
6014
- serializeTxBody = (txBuilderBody, protocolParams, balanced = true) => {
6015
- if (this.verbose) {
6016
- console.log(
6017
- "txBodyJson",
6018
- JSON.stringify(txBuilderBody, (key, val) => {
6019
- if (key === "extraInputs") return void 0;
6020
- if (key === "selectionConfig") return void 0;
6021
- return val;
6022
- })
6023
- );
6024
- }
6118
+ serializeTxBody = (txBuilderBody, protocolParams) => {
6025
6119
  const serializerCore = new CardanoSDKSerializerCore(
6026
6120
  protocolParams ?? this.protocolParams
6027
6121
  );
6028
- return serializerCore.coreSerializeTxBody(txBuilderBody, balanced);
6122
+ return serializerCore.coreSerializeTx(txBuilderBody);
6029
6123
  };
6124
+ serializeTxBodyWithMockSignatures(txBuilderBody, protocolParams) {
6125
+ const serializerCore = new CardanoSDKSerializerCore(protocolParams);
6126
+ return serializerCore.coreSerializeTxWithMockSignatures(txBuilderBody);
6127
+ }
6030
6128
  addSigningKeys = (txHex, signingKeys) => {
6031
- let cardanoTx = Transaction.fromCbor(import_core7.Serialization.TxCBOR(txHex));
6129
+ let cardanoTx = Transaction.fromCbor(import_core8.Serialization.TxCBOR(txHex));
6032
6130
  let currentWitnessSet = cardanoTx.witnessSet();
6033
6131
  let currentWitnessSetVkeys = currentWitnessSet.vkeys();
6034
6132
  let currentWitnessSetVkeysValues = currentWitnessSetVkeys ? [...currentWitnessSetVkeys.values()] : [];
@@ -6049,7 +6147,7 @@ var CardanoSDKSerializer = class {
6049
6147
  }
6050
6148
  }
6051
6149
  currentWitnessSet.setVkeys(
6052
- import_core7.Serialization.CborSet.fromCore(
6150
+ import_core8.Serialization.CborSet.fromCore(
6053
6151
  currentWitnessSetVkeysValues.map((vkw) => vkw.toCore()),
6054
6152
  VkeyWitness.fromCore
6055
6153
  )
@@ -6057,6 +6155,63 @@ var CardanoSDKSerializer = class {
6057
6155
  cardanoTx.setWitnessSet(currentWitnessSet);
6058
6156
  return cardanoTx.toCbor();
6059
6157
  };
6158
+ serializeValue(value) {
6159
+ return toValue(value).toCbor();
6160
+ }
6161
+ serializeOutput(output) {
6162
+ let cardanoOutput = new TransactionOutput(
6163
+ toCardanoAddress(output.address),
6164
+ toValue(output.amount)
6165
+ );
6166
+ if (output.datum?.type === "Hash") {
6167
+ cardanoOutput.setDatum(
6168
+ Datum.newDataHash(fromBuilderToPlutusData(output.datum.data).hash())
6169
+ );
6170
+ } else if (output.datum?.type === "Inline") {
6171
+ cardanoOutput.setDatum(
6172
+ Datum.newInlineData(fromBuilderToPlutusData(output.datum.data))
6173
+ );
6174
+ } else if (output.datum?.type === "Embedded") {
6175
+ throw new Error("Embedded datum not supported");
6176
+ }
6177
+ if (output.referenceScript) {
6178
+ switch (output.referenceScript.version) {
6179
+ case "V1": {
6180
+ cardanoOutput.setScriptRef(
6181
+ Script.newPlutusV1Script(
6182
+ PlutusV1Script.fromCbor((0, import_util9.HexBlob)(output.referenceScript.code))
6183
+ )
6184
+ );
6185
+ break;
6186
+ }
6187
+ case "V2": {
6188
+ cardanoOutput.setScriptRef(
6189
+ Script.newPlutusV2Script(
6190
+ PlutusV2Script.fromCbor((0, import_util9.HexBlob)(output.referenceScript.code))
6191
+ )
6192
+ );
6193
+ break;
6194
+ }
6195
+ case "V3": {
6196
+ cardanoOutput.setScriptRef(
6197
+ Script.newPlutusV3Script(
6198
+ PlutusV3Script.fromCbor((0, import_util9.HexBlob)(output.referenceScript.code))
6199
+ )
6200
+ );
6201
+ break;
6202
+ }
6203
+ default: {
6204
+ cardanoOutput.setScriptRef(
6205
+ Script.newNativeScript(
6206
+ NativeScript.fromCbor((0, import_util9.HexBlob)(output.referenceScript.code))
6207
+ )
6208
+ );
6209
+ break;
6210
+ }
6211
+ }
6212
+ }
6213
+ return cardanoOutput.toCbor();
6214
+ }
6060
6215
  };
6061
6216
  var CardanoSDKSerializerCore = class {
6062
6217
  txBody;
@@ -6076,7 +6231,7 @@ var CardanoSDKSerializerCore = class {
6076
6231
  constructor(protocolParams) {
6077
6232
  this.protocolParams = protocolParams || import_common8.DEFAULT_PROTOCOL_PARAMETERS;
6078
6233
  this.txBody = new TransactionBody(
6079
- import_core7.Serialization.CborSet.fromCore([], TransactionInput.fromCore),
6234
+ import_core8.Serialization.CborSet.fromCore([], TransactionInput.fromCore),
6080
6235
  [],
6081
6236
  BigInt(0),
6082
6237
  void 0
@@ -6085,7 +6240,7 @@ var CardanoSDKSerializerCore = class {
6085
6240
  this.txWitnessSet = new TransactionWitnessSet();
6086
6241
  this.txAuxilliaryData = new AuxilliaryData();
6087
6242
  }
6088
- coreSerializeTxBody = (txBuilderBody, balanced) => {
6243
+ coreSerializeTxBody = (txBuilderBody) => {
6089
6244
  const {
6090
6245
  inputs,
6091
6246
  outputs,
@@ -6093,36 +6248,128 @@ var CardanoSDKSerializerCore = class {
6093
6248
  requiredSignatures,
6094
6249
  referenceInputs,
6095
6250
  mints,
6096
- changeAddress,
6097
6251
  metadata,
6098
6252
  validityRange,
6099
6253
  certificates,
6100
- withdrawals
6254
+ withdrawals,
6255
+ votes,
6256
+ totalCollateral,
6257
+ collateralReturnAddress,
6258
+ changeAddress
6101
6259
  } = txBuilderBody;
6102
- this.addAllInputs(inputs);
6103
- this.sanitizeOutputs(outputs);
6104
- this.addAllOutputs(outputs);
6105
- this.addAllMints(mints);
6106
- this.addAllCerts(certificates);
6107
- this.addAllWithdrawals(withdrawals);
6108
- this.addAllCollateralInputs(collaterals);
6109
- this.addAllReferenceInputs(referenceInputs);
6260
+ const uniqueRefInputs = this.removeBodyInputRefInputOverlap(
6261
+ inputs,
6262
+ referenceInputs
6263
+ );
6264
+ try {
6265
+ this.addAllInputs(inputs);
6266
+ } catch (e) {
6267
+ throwErrorWithOrigin("Error serializing inputs", e);
6268
+ }
6269
+ try {
6270
+ this.setFee(txBuilderBody.fee ?? "0");
6271
+ } catch (e) {
6272
+ throwErrorWithOrigin("Error serializing fee", e);
6273
+ }
6274
+ try {
6275
+ this.sanitizeOutputs(outputs);
6276
+ } catch (e) {
6277
+ throwErrorWithOrigin("Error calculating min utxo values for outputs", e);
6278
+ }
6279
+ try {
6280
+ this.addAllOutputs(outputs);
6281
+ } catch (e) {
6282
+ throwErrorWithOrigin("Error serializing outputs", e);
6283
+ }
6284
+ try {
6285
+ this.addAllMints(mints);
6286
+ } catch (e) {
6287
+ throwErrorWithOrigin("Error serializing mints", e);
6288
+ }
6289
+ try {
6290
+ this.addAllCerts(certificates);
6291
+ } catch (e) {
6292
+ throwErrorWithOrigin("Error serializing certificates", e);
6293
+ }
6294
+ try {
6295
+ this.addAllWithdrawals(withdrawals);
6296
+ } catch (e) {
6297
+ throwErrorWithOrigin("Error serializing withdrawals", e);
6298
+ }
6299
+ try {
6300
+ this.addAllVotes(votes);
6301
+ } catch (e) {
6302
+ throwErrorWithOrigin("Error serializing votes", e);
6303
+ }
6304
+ try {
6305
+ this.addAllCollateralInputs(collaterals);
6306
+ } catch (e) {
6307
+ throwErrorWithOrigin("Error serializing collateral inputs", e);
6308
+ }
6309
+ if (totalCollateral) {
6310
+ try {
6311
+ this.txBody.setTotalCollateral(BigInt(totalCollateral));
6312
+ this.addCollateralReturn(
6313
+ totalCollateral,
6314
+ collaterals,
6315
+ collateralReturnAddress ?? changeAddress
6316
+ );
6317
+ } catch (e) {
6318
+ throwErrorWithOrigin(
6319
+ "Error serializing total collateral and collateral return",
6320
+ e
6321
+ );
6322
+ }
6323
+ }
6324
+ try {
6325
+ this.addAllReferenceInputs(uniqueRefInputs);
6326
+ } catch (e) {
6327
+ throwErrorWithOrigin("Error serializing reference inputs", e);
6328
+ }
6110
6329
  this.removeInputRefInputOverlap();
6111
- this.setValidityInterval(validityRange);
6112
- this.addAllRequiredSignatures(requiredSignatures);
6330
+ try {
6331
+ this.setValidityInterval(validityRange);
6332
+ } catch (e) {
6333
+ throwErrorWithOrigin("Error serializing validity interval", e);
6334
+ }
6335
+ try {
6336
+ this.addAllRequiredSignatures(requiredSignatures);
6337
+ } catch (e) {
6338
+ throwErrorWithOrigin("Error serializing required signatures", e);
6339
+ }
6113
6340
  if (metadata.size > 0) {
6114
- this.addMetadata(metadata);
6341
+ try {
6342
+ this.addMetadata(metadata);
6343
+ } catch (e) {
6344
+ throwErrorWithOrigin("Error serializing metadata", e);
6345
+ }
6115
6346
  }
6116
- this.buildWitnessSet();
6117
- if (balanced) {
6118
- this.balanceTx(changeAddress);
6347
+ return this.txBody;
6348
+ };
6349
+ coreSerializeTx(txBuilderBody) {
6350
+ const bodyCore = this.coreSerializeTxBody(txBuilderBody);
6351
+ if (txBuilderBody.fee !== void 0) {
6352
+ this.txBody.setFee(BigInt(txBuilderBody.fee));
6119
6353
  }
6354
+ this.buildWitnessSet();
6120
6355
  return new Transaction(
6121
- this.txBody,
6356
+ bodyCore,
6122
6357
  this.txWitnessSet,
6123
6358
  this.txAuxilliaryData
6124
6359
  ).toCbor();
6125
- };
6360
+ }
6361
+ coreSerializeTxWithMockSignatures(txBuilderBody) {
6362
+ const bodyCore = this.coreSerializeTxBody(txBuilderBody);
6363
+ const mockWitSet = this.createMockedWitnessSet(
6364
+ txBuilderBody.expectedNumberKeyWitnesses,
6365
+ txBuilderBody.expectedByronAddressWitnesses
6366
+ );
6367
+ return new Transaction(
6368
+ bodyCore,
6369
+ mockWitSet,
6370
+ this.txAuxilliaryData
6371
+ ).toCbor();
6372
+ }
6126
6373
  sanitizeOutputs = (outputs) => {
6127
6374
  for (let i = 0; i < outputs.length; i++) {
6128
6375
  let currentOutput = outputs[i];
@@ -6153,6 +6400,18 @@ var CardanoSDKSerializerCore = class {
6153
6400
  );
6154
6401
  let minUtxoValue = (160 + dummyCardanoOutput.toCbor().length / 2 + 1) * this.protocolParams.coinsPerUtxoSize;
6155
6402
  currentAmount.quantity = minUtxoValue.toString();
6403
+ if (!lovelaceFound) {
6404
+ let currentAmount2 = {
6405
+ unit: "lovelace",
6406
+ quantity: "10000000"
6407
+ };
6408
+ currentOutput.amount.push(currentAmount2);
6409
+ let dummyCardanoOutput2 = this.toCardanoOutput(
6410
+ currentOutput
6411
+ );
6412
+ let minUtxoValue2 = (160 + dummyCardanoOutput2.toCbor().length / 2 + 1) * this.protocolParams.coinsPerUtxoSize;
6413
+ currentAmount2.quantity = minUtxoValue2.toString();
6414
+ }
6156
6415
  }
6157
6416
  }
6158
6417
  };
@@ -6197,6 +6456,9 @@ var CardanoSDKSerializerCore = class {
6197
6456
  );
6198
6457
  this.utxoContext.set(cardanoTxIn, cardanoTxOut);
6199
6458
  this.txBody.setInputs(inputs);
6459
+ if (currentTxIn.txIn.scriptSize) {
6460
+ this.refScriptSize += currentTxIn.txIn.scriptSize;
6461
+ }
6200
6462
  };
6201
6463
  addScriptTxIn = (currentTxIn, index) => {
6202
6464
  this.addTxIn({
@@ -6222,16 +6484,10 @@ var CardanoSDKSerializerCore = class {
6222
6484
  fromBuilderToPlutusData(currentTxIn.scriptTxIn.datumSource.data)
6223
6485
  );
6224
6486
  } else if (currentTxIn.scriptTxIn.datumSource.type === "Inline") {
6225
- let referenceInputs = this.txBody.referenceInputs() ?? import_core7.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6226
- let referenceInputsList = [...referenceInputs.values()];
6227
- referenceInputsList.push(
6228
- new TransactionInput(
6229
- TransactionId(currentTxIn.txIn.txHash),
6230
- BigInt(currentTxIn.txIn.txIndex)
6231
- )
6232
- );
6233
- referenceInputs.setValues(referenceInputsList);
6234
- this.txBody.setReferenceInputs(referenceInputs);
6487
+ this.addReferenceInput({
6488
+ txHash: currentTxIn.txIn.txHash,
6489
+ txIndex: currentTxIn.txIn.txIndex
6490
+ });
6235
6491
  }
6236
6492
  let exUnits = currentTxIn.scriptTxIn.redeemer.exUnits;
6237
6493
  let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
@@ -6285,9 +6541,7 @@ var CardanoSDKSerializerCore = class {
6285
6541
  if (output.datum?.type === "Hash") {
6286
6542
  cardanoOutput.setDatum(
6287
6543
  Datum.newDataHash(
6288
- DatumHash.fromHexBlob(
6289
- (0, import_util9.HexBlob)(fromBuilderToPlutusData(output.datum.data).hash())
6290
- )
6544
+ DatumHash(fromBuilderToPlutusData(output.datum.data).hash())
6291
6545
  )
6292
6546
  );
6293
6547
  } else if (output.datum?.type === "Inline") {
@@ -6295,7 +6549,7 @@ var CardanoSDKSerializerCore = class {
6295
6549
  Datum.newInlineData(fromBuilderToPlutusData(output.datum.data))
6296
6550
  );
6297
6551
  } else if (output.datum?.type === "Embedded") {
6298
- const currentWitnessDatum = this.txWitnessSet.plutusData() ?? import_core7.Serialization.CborSet.fromCore([], import_core7.Serialization.PlutusData.fromCore);
6552
+ const currentWitnessDatum = this.txWitnessSet.plutusData() ?? import_core8.Serialization.CborSet.fromCore([], import_core8.Serialization.PlutusData.fromCore);
6299
6553
  const currentWitnessDatumValues = [...currentWitnessDatum.values()];
6300
6554
  currentWitnessDatumValues.push(
6301
6555
  fromBuilderToPlutusData(output.datum.data)
@@ -6339,15 +6593,22 @@ var CardanoSDKSerializerCore = class {
6339
6593
  }
6340
6594
  };
6341
6595
  addReferenceInput = (refInput) => {
6342
- let referenceInputs = this.txBody.referenceInputs() ?? import_core7.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6596
+ let referenceInputs = this.txBody.referenceInputs() ?? import_core8.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6343
6597
  let referenceInputsList = [...referenceInputs.values()];
6598
+ if (referenceInputsList.some(
6599
+ (input) => input.transactionId().toString() === refInput.txHash && input.index().toString() === refInput.txIndex.toString()
6600
+ ))
6601
+ return;
6344
6602
  referenceInputsList.push(
6345
6603
  new TransactionInput(
6346
- TransactionId.fromHexBlob((0, import_util9.HexBlob)(refInput.txHash)),
6604
+ TransactionId(refInput.txHash),
6347
6605
  BigInt(refInput.txIndex)
6348
6606
  )
6349
6607
  );
6350
6608
  referenceInputs.setValues(referenceInputsList);
6609
+ if (refInput.scriptSize) {
6610
+ this.refScriptSize += refInput.scriptSize;
6611
+ }
6351
6612
  this.txBody.setReferenceInputs(referenceInputs);
6352
6613
  };
6353
6614
  addAllMints = (mints) => {
@@ -6372,16 +6633,21 @@ var CardanoSDKSerializerCore = class {
6372
6633
  };
6373
6634
  addMint = (mint) => {
6374
6635
  const currentMint = this.txBody.mint() ?? /* @__PURE__ */ new Map();
6375
- const mintAssetId = mint.policyId + mint.assetName;
6376
- for (const asset of currentMint.keys()) {
6377
- if (asset.toString() == mintAssetId) {
6378
- throw new Error("The same asset is already in the mint field");
6636
+ for (const assetValue of mint.mintValue) {
6637
+ const mintAssetId = `${mint.policyId}${assetValue.assetName}`;
6638
+ for (const asset of currentMint.keys()) {
6639
+ if (asset.toString() == mintAssetId) {
6640
+ throw new Error("The same asset is already in the mint field");
6641
+ }
6379
6642
  }
6643
+ currentMint.set(
6644
+ AssetId.fromParts(
6645
+ PolicyId(mint.policyId),
6646
+ AssetName(assetValue.assetName)
6647
+ ),
6648
+ BigInt(assetValue.amount)
6649
+ );
6380
6650
  }
6381
- currentMint.set(
6382
- AssetId.fromParts(PolicyId(mint.policyId), AssetName(mint.assetName)),
6383
- BigInt(mint.amount)
6384
- );
6385
6651
  this.txBody.setMint(currentMint);
6386
6652
  if (mint.type === "Native") {
6387
6653
  if (!mint.scriptSource)
@@ -6443,7 +6709,7 @@ var CardanoSDKSerializerCore = class {
6443
6709
  }
6444
6710
  };
6445
6711
  addCert = (cert, index) => {
6446
- const currentCerts = this.txBody.certs() ?? import_core7.Serialization.CborSet.fromCore([], import_core7.Serialization.Certificate.fromCore);
6712
+ const currentCerts = this.txBody.certs() ?? import_core8.Serialization.CborSet.fromCore([], import_core8.Serialization.Certificate.fromCore);
6447
6713
  let currentCertsValues = [...currentCerts.values()];
6448
6714
  currentCertsValues.push(toCardanoCert(cert.certType));
6449
6715
  currentCerts.setValues(currentCertsValues);
@@ -6586,7 +6852,7 @@ var CardanoSDKSerializerCore = class {
6586
6852
  TransactionId(collateral.txIn.txHash),
6587
6853
  BigInt(collateral.txIn.txIndex)
6588
6854
  );
6589
- const collateralInputs = this.txBody.collateral() ?? import_core7.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6855
+ const collateralInputs = this.txBody.collateral() ?? import_core8.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6590
6856
  const collateralInputsList = [
6591
6857
  ...collateralInputs.values()
6592
6858
  ];
@@ -6604,6 +6870,22 @@ var CardanoSDKSerializerCore = class {
6604
6870
  this.utxoContext.set(cardanoTxIn, cardanoTxOut);
6605
6871
  this.txBody.setCollateral(collateralInputs);
6606
6872
  };
6873
+ addCollateralReturn = (totalCollateral, collaterals, collateralReturnAddress) => {
6874
+ let collateralReturnValue = Value.fromCore({
6875
+ coins: -BigInt(totalCollateral)
6876
+ });
6877
+ for (const collateral of collaterals) {
6878
+ collateralReturnValue = mergeValue(
6879
+ collateralReturnValue,
6880
+ toValue(collateral.txIn.amount)
6881
+ );
6882
+ }
6883
+ const collateralReturn = new TransactionOutput(
6884
+ toCardanoAddress(collateralReturnAddress),
6885
+ collateralReturnValue
6886
+ );
6887
+ this.txBody.setCollateralReturn(collateralReturn);
6888
+ };
6607
6889
  setValidityInterval = (validity) => {
6608
6890
  if (validity.invalidBefore) {
6609
6891
  this.txBody.setValidityStartInterval(Slot(validity.invalidBefore));
@@ -6612,12 +6894,15 @@ var CardanoSDKSerializerCore = class {
6612
6894
  this.txBody.setTtl(Slot(validity.invalidHereafter));
6613
6895
  }
6614
6896
  };
6897
+ setFee = (fee) => {
6898
+ this.txBody.setFee(BigInt(fee));
6899
+ };
6615
6900
  addAllRequiredSignatures = (requiredSignatures) => {
6616
- const requiredSigners = this.txBody.requiredSigners() ?? import_core7.Serialization.CborSet.fromCore([], import_core7.Serialization.Hash.fromCore);
6901
+ const requiredSigners = this.txBody.requiredSigners() ?? import_core8.Serialization.CborSet.fromCore([], import_core8.Serialization.Hash.fromCore);
6617
6902
  let requiredSignerValues = [...requiredSigners.values()];
6618
6903
  for (const requiredSigner of requiredSignatures) {
6619
6904
  requiredSignerValues.push(
6620
- import_core7.Serialization.Hash.fromCore(Ed25519KeyHashHex2(requiredSigner))
6905
+ import_core8.Serialization.Hash.fromCore(Ed25519KeyHashHex2(requiredSigner))
6621
6906
  );
6622
6907
  }
6623
6908
  requiredSigners.setValues(requiredSignerValues);
@@ -6625,16 +6910,33 @@ var CardanoSDKSerializerCore = class {
6625
6910
  };
6626
6911
  addMetadata = (metadata) => {
6627
6912
  this.txAuxilliaryData.setMetadata(
6628
- new import_core7.Serialization.GeneralTransactionMetadata(
6913
+ new import_core8.Serialization.GeneralTransactionMetadata(
6629
6914
  toCardanoMetadataMap(metadata)
6630
6915
  )
6631
6916
  );
6632
6917
  };
6918
+ createMockedWitnessSet = (requiredSignaturesCount, requiredByronSignatures) => {
6919
+ this.buildWitnessSet();
6920
+ const clonedWitnessSet = TransactionWitnessSet.fromCbor(
6921
+ this.txWitnessSet.toCbor()
6922
+ );
6923
+ const bootstrapWitnesses = this.mockBootstrapWitnesses(
6924
+ requiredByronSignatures
6925
+ );
6926
+ const vkeyWitnesses = this.mockVkeyWitnesses(requiredSignaturesCount);
6927
+ const bootstrapsSet = CborSet.fromCore([], BootstrapWitness.fromCore);
6928
+ bootstrapsSet.setValues(bootstrapWitnesses);
6929
+ clonedWitnessSet.setBootstraps(bootstrapsSet);
6930
+ const vkeysSet = CborSet.fromCore([], VkeyWitness.fromCore);
6931
+ vkeysSet.setValues(vkeyWitnesses);
6932
+ clonedWitnessSet.setVkeys(vkeysSet);
6933
+ return clonedWitnessSet;
6934
+ };
6633
6935
  buildWitnessSet = () => {
6634
- let nativeScripts = this.txWitnessSet.nativeScripts() ?? import_core7.Serialization.CborSet.fromCore([], NativeScript.fromCore);
6635
- let v1Scripts = this.txWitnessSet.plutusV1Scripts() ?? import_core7.Serialization.CborSet.fromCore([], PlutusV1Script.fromCore);
6636
- let v2Scripts = this.txWitnessSet.plutusV2Scripts() ?? import_core7.Serialization.CborSet.fromCore([], PlutusV2Script.fromCore);
6637
- let v3Scripts = this.txWitnessSet.plutusV3Scripts() ?? import_core7.Serialization.CborSet.fromCore([], PlutusV3Script.fromCore);
6936
+ let nativeScripts = this.txWitnessSet.nativeScripts() ?? import_core8.Serialization.CborSet.fromCore([], NativeScript.fromCore);
6937
+ let v1Scripts = this.txWitnessSet.plutusV1Scripts() ?? import_core8.Serialization.CborSet.fromCore([], PlutusV1Script.fromCore);
6938
+ let v2Scripts = this.txWitnessSet.plutusV2Scripts() ?? import_core8.Serialization.CborSet.fromCore([], PlutusV2Script.fromCore);
6939
+ let v3Scripts = this.txWitnessSet.plutusV3Scripts() ?? import_core8.Serialization.CborSet.fromCore([], PlutusV3Script.fromCore);
6638
6940
  this.scriptsProvided.forEach((scriptHex) => {
6639
6941
  const script = Script.fromCbor((0, import_util9.HexBlob)(scriptHex));
6640
6942
  if (script.asNative() !== void 0) {
@@ -6659,23 +6961,23 @@ var CardanoSDKSerializerCore = class {
6659
6961
  this.txWitnessSet.setPlutusV2Scripts(v2Scripts);
6660
6962
  this.txWitnessSet.setPlutusV3Scripts(v3Scripts);
6661
6963
  });
6662
- let datums = this.txWitnessSet.plutusData() ?? import_core7.Serialization.CborSet.fromCore([], PlutusData.fromCore);
6964
+ let datums = this.txWitnessSet.plutusData() ?? import_core8.Serialization.CborSet.fromCore([], PlutusData.fromCore);
6663
6965
  let datumsList = [...datums.values()];
6664
6966
  this.datumsProvided.forEach((datum) => {
6665
6967
  datumsList.push(datum);
6666
6968
  });
6667
6969
  datums.setValues(datumsList);
6668
6970
  this.txWitnessSet.setPlutusData(datums);
6669
- let costModelV1 = import_core7.Serialization.CostModel.newPlutusV1(
6971
+ let costModelV1 = import_core8.Serialization.CostModel.newPlutusV1(
6670
6972
  import_common8.DEFAULT_V1_COST_MODEL_LIST
6671
6973
  );
6672
- let costModelV2 = import_core7.Serialization.CostModel.newPlutusV2(
6974
+ let costModelV2 = import_core8.Serialization.CostModel.newPlutusV2(
6673
6975
  import_common8.DEFAULT_V2_COST_MODEL_LIST
6674
6976
  );
6675
- let costModelV3 = import_core7.Serialization.CostModel.newPlutusV3(
6977
+ let costModelV3 = import_core8.Serialization.CostModel.newPlutusV3(
6676
6978
  import_common8.DEFAULT_V3_COST_MODEL_LIST
6677
6979
  );
6678
- let costModels = new import_core7.Serialization.Costmdls();
6980
+ let costModels = new import_core8.Serialization.Costmdls();
6679
6981
  if (this.usedLanguages[PlutusLanguageVersion.V1]) {
6680
6982
  costModels.insert(costModelV1);
6681
6983
  }
@@ -6688,8 +6990,8 @@ var CardanoSDKSerializerCore = class {
6688
6990
  const redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
6689
6991
  let scriptDataHash = hashScriptData(
6690
6992
  costModels,
6691
- redeemers.size() > 0 ? [...redeemers.values()] : void 0,
6692
- datums.size() > 0 ? [...datums.values()] : void 0
6993
+ redeemers,
6994
+ datums.size() > 0 ? datums : void 0
6693
6995
  );
6694
6996
  if (scriptDataHash) {
6695
6997
  this.txBody.setScriptDataHash(scriptDataHash);
@@ -6718,206 +7020,39 @@ var CardanoSDKSerializerCore = class {
6718
7020
  }
6719
7021
  });
6720
7022
  this.txBody.setReferenceInputs(
6721
- import_core7.Serialization.CborSet.fromCore(
7023
+ import_core8.Serialization.CborSet.fromCore(
6722
7024
  refInputsValues.map((input) => input.toCore()),
6723
7025
  TransactionInput.fromCore
6724
7026
  )
6725
7027
  );
6726
7028
  }
6727
7029
  };
6728
- balanceTx = (changeAddress) => {
6729
- if (changeAddress === "") {
6730
- throw new Error("Can't balance tx without a change address");
6731
- }
6732
- const inputs = this.txBody.inputs().values();
6733
- let remainingValue = new Value(BigInt(0));
6734
- for (let i = 0; i < inputs.length; i++) {
6735
- let input = inputs[i];
6736
- if (!input) {
6737
- throw new Error("Invalid input found");
6738
- }
6739
- const output = this.utxoContext.get(input);
6740
- if (!output) {
6741
- throw new Error(`Unable to resolve input: ${input.toCbor()}`);
6742
- }
6743
- remainingValue = mergeValue(remainingValue, output.amount());
6744
- }
6745
- const withdrawals = this.txBody.withdrawals();
6746
- if (withdrawals) {
6747
- withdrawals.forEach((coin) => {
6748
- remainingValue = mergeValue(remainingValue, new Value(coin));
6749
- });
6750
- }
6751
- remainingValue = mergeValue(
6752
- remainingValue,
6753
- new Value(BigInt(0), this.txBody.mint())
6754
- );
6755
- const currentOutputs = this.txBody.outputs();
6756
- for (let i = 0; i < currentOutputs.length; i++) {
6757
- let output = currentOutputs.at(i);
6758
- if (output) {
6759
- remainingValue = subValue(remainingValue, output.amount());
6760
- }
6761
- }
6762
- const certs = this.txBody.certs();
6763
- if (certs) {
6764
- certs.values().forEach((cert) => {
6765
- switch (cert.toCore().__typename) {
6766
- case CertificateType.StakeRegistration: {
6767
- remainingValue = subValue(
6768
- remainingValue,
6769
- new Value(BigInt(this.protocolParams.keyDeposit))
6770
- );
6771
- break;
6772
- }
6773
- case CertificateType.StakeDeregistration: {
6774
- remainingValue = mergeValue(
6775
- remainingValue,
6776
- new Value(BigInt(this.protocolParams.keyDeposit))
6777
- );
6778
- break;
6779
- }
6780
- case CertificateType.Registration: {
6781
- remainingValue = subValue(
6782
- remainingValue,
6783
- new Value(BigInt(cert.asRegistrationCert()?.deposit() ?? 0))
6784
- );
6785
- break;
6786
- }
6787
- case CertificateType.Unregistration: {
6788
- remainingValue = mergeValue(
6789
- remainingValue,
6790
- new Value(BigInt(cert.asUnregistrationCert()?.deposit() ?? 0))
6791
- );
6792
- break;
6793
- }
6794
- case CertificateType.PoolRegistration: {
6795
- remainingValue = subValue(
6796
- remainingValue,
6797
- new Value(BigInt(this.protocolParams.poolDeposit))
6798
- );
6799
- break;
6800
- }
6801
- case CertificateType.PoolRetirement: {
6802
- remainingValue = mergeValue(
6803
- remainingValue,
6804
- new Value(BigInt(this.protocolParams.poolDeposit))
6805
- );
6806
- break;
6807
- }
6808
- case CertificateType.RegisterDelegateRepresentative: {
6809
- remainingValue = subValue(
6810
- remainingValue,
6811
- new Value(
6812
- BigInt(
6813
- cert.asRegisterDelegateRepresentativeCert()?.deposit() ?? 0
6814
- )
6815
- )
6816
- );
6817
- break;
6818
- }
6819
- case CertificateType.UnregisterDelegateRepresentative: {
6820
- remainingValue = mergeValue(
6821
- remainingValue,
6822
- new Value(
6823
- BigInt(
6824
- cert.asUnregisterDelegateRepresentativeCert()?.deposit() ?? 0
6825
- )
6826
- )
6827
- );
6828
- break;
6829
- }
6830
- case CertificateType.StakeRegistrationDelegation: {
6831
- remainingValue = subValue(
6832
- remainingValue,
6833
- new Value(
6834
- BigInt(
6835
- cert.asStakeRegistrationDelegationCert()?.deposit() ?? 0
6836
- )
6837
- )
6838
- );
6839
- break;
6840
- }
6841
- case CertificateType.StakeVoteRegistrationDelegation: {
6842
- remainingValue = subValue(
6843
- remainingValue,
6844
- new Value(
6845
- BigInt(
6846
- cert.asStakeVoteRegistrationDelegationCert()?.deposit() ?? 0
6847
- )
6848
- )
6849
- );
6850
- break;
6851
- }
6852
- }
6853
- });
6854
- }
6855
- if (remainingValue.coin() < 0 || !empty(negatives(remainingValue))) {
6856
- throw new Error(`Not enough funds to satisfy outputs`);
6857
- }
6858
- const dummyChangeOutput = new TransactionOutput(
6859
- toCardanoAddress(changeAddress),
6860
- remainingValue
6861
- );
6862
- let minUtxoValue = (160 + dummyChangeOutput.toCbor().length / 2 + 1) * this.protocolParams.coinsPerUtxoSize;
6863
- this.txBody.setFee(BigInt("10000000"));
6864
- const numberOfRequiredWitnesses = this.countNumberOfRequiredWitnesses();
6865
- const dummyTx = this.createDummyTx(numberOfRequiredWitnesses);
6866
- let fee = calculateFees(
6867
- this.protocolParams.minFeeA,
6868
- this.protocolParams.minFeeB,
6869
- this.protocolParams.minFeeRefScriptCostPerByte,
6870
- this.protocolParams.priceMem,
6871
- this.protocolParams.priceStep,
6872
- dummyTx,
6873
- this.refScriptSize
6874
- );
6875
- if (remainingValue.coin() >= fee + BigInt(minUtxoValue)) {
6876
- dummyChangeOutput.amount().setCoin(dummyChangeOutput.amount().coin() - fee);
6877
- currentOutputs.push(dummyChangeOutput);
6878
- this.txBody.setOutputs(currentOutputs);
6879
- remainingValue = new Value(BigInt(0));
6880
- } else if (remainingValue.coin() >= fee) {
6881
- if (remainingValue.multiasset() && remainingValue.multiasset().size > 0) {
6882
- throw new Error(
6883
- "Insufficient funds to create change output with tokens"
6884
- );
6885
- } else {
6886
- fee = remainingValue.coin();
7030
+ removeBodyInputRefInputOverlap = (inputs, refInputs) => {
7031
+ let finalRefInputs = [];
7032
+ for (let i = 0; i < refInputs.length; i++) {
7033
+ let refInput = refInputs[i];
7034
+ if (!inputs.some(
7035
+ (input) => input.txIn.txHash === refInput.txHash && input.txIn.txIndex === refInput.txIndex
7036
+ )) {
7037
+ finalRefInputs.push(refInput);
6887
7038
  }
6888
7039
  }
6889
- this.txBody.setFee(fee);
6890
- };
6891
- createDummyTx = (numberOfRequiredWitnesses) => {
6892
- let dummyWitnessSet = TransactionWitnessSet.fromCbor(
6893
- (0, import_util9.HexBlob)(this.txWitnessSet.toCbor())
6894
- );
6895
- const dummyVkeyWitnesses = [];
6896
- for (let i = 0; i < numberOfRequiredWitnesses; i++) {
6897
- dummyVkeyWitnesses.push([
6898
- Ed25519PublicKeyHex2(String(i).repeat(64)),
6899
- Ed25519SignatureHex2(String(i).repeat(128))
6900
- ]);
6901
- }
6902
- dummyWitnessSet.setVkeys(
6903
- import_core7.Serialization.CborSet.fromCore(dummyVkeyWitnesses, VkeyWitness.fromCore)
6904
- );
6905
- return new Transaction(this.txBody, dummyWitnessSet, this.txAuxilliaryData);
7040
+ return finalRefInputs;
6906
7041
  };
6907
7042
  addScriptRef = (scriptSource) => {
6908
7043
  if (scriptSource.type !== "Inline") {
6909
7044
  return;
6910
7045
  }
6911
- let referenceInputs = this.txBody.referenceInputs() ?? import_core7.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6912
- let referenceInputsList = [...referenceInputs.values()];
6913
- referenceInputsList.push(
6914
- new TransactionInput(
6915
- TransactionId(scriptSource.txHash),
6916
- BigInt(scriptSource.txIndex)
6917
- )
6918
- );
6919
- referenceInputs.setValues(referenceInputsList);
6920
- this.txBody.setReferenceInputs(referenceInputs);
7046
+ if (!scriptSource.scriptSize) {
7047
+ throw new Error(
7048
+ "A reference script was used without providing its size, this must be provided as fee calculations are based on it"
7049
+ );
7050
+ }
7051
+ this.addReferenceInput({
7052
+ txHash: scriptSource.txHash,
7053
+ txIndex: scriptSource.txIndex,
7054
+ scriptSize: Number(scriptSource.scriptSize)
7055
+ });
6921
7056
  switch (scriptSource.version) {
6922
7057
  case "V1": {
6923
7058
  this.usedLanguages[PlutusLanguageVersion.V1] = true;
@@ -6932,205 +7067,22 @@ var CardanoSDKSerializerCore = class {
6932
7067
  break;
6933
7068
  }
6934
7069
  }
6935
- if (scriptSource.scriptSize) {
6936
- this.refScriptSize += Number(scriptSource.scriptSize);
6937
- } else {
6938
- throw new Error(
6939
- "A reference script was used without providing its size, this must be provided as fee calculations are based on it"
6940
- );
6941
- }
6942
7070
  };
6943
7071
  addSimpleScriptRef = (simpleScriptSource) => {
6944
7072
  if (simpleScriptSource.type !== "Inline") {
6945
7073
  return;
6946
7074
  }
6947
- let referenceInputs = this.txBody.referenceInputs() ?? import_core7.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
6948
- let referenceInputsList = [...referenceInputs.values()];
6949
- referenceInputsList.push(
6950
- new TransactionInput(
6951
- TransactionId(simpleScriptSource.txHash),
6952
- BigInt(simpleScriptSource.txIndex)
6953
- )
6954
- );
6955
- if (simpleScriptSource.scriptSize) {
6956
- this.refScriptSize += Number(simpleScriptSource.scriptSize);
6957
- } else {
7075
+ if (!simpleScriptSource.scriptSize) {
6958
7076
  throw new Error(
6959
7077
  "A reference script was used without providing its size, this must be provided as fee calculations are based on it"
6960
7078
  );
6961
7079
  }
6962
- referenceInputs.setValues(referenceInputsList);
6963
- this.txBody.setReferenceInputs(referenceInputs);
7080
+ this.addReferenceInput({
7081
+ txHash: simpleScriptSource.txHash,
7082
+ txIndex: simpleScriptSource.txIndex,
7083
+ scriptSize: Number(simpleScriptSource.scriptSize)
7084
+ });
6964
7085
  };
6965
- countNumberOfRequiredWitnesses() {
6966
- let requiredWitnesses = /* @__PURE__ */ new Set();
6967
- const inputs = this.txBody.inputs().values();
6968
- for (let i = 0; i < inputs.length; i++) {
6969
- const input = inputs[i];
6970
- const addressPaymentPart = this.utxoContext.get(input)?.address().getProps().paymentPart;
6971
- if (addressPaymentPart?.type === 0) {
6972
- requiredWitnesses.add(addressPaymentPart.hash);
6973
- }
6974
- }
6975
- const collateralInputs = this.txBody.collateral()?.values();
6976
- if (collateralInputs) {
6977
- for (let i = 0; i < collateralInputs?.length; i++) {
6978
- const collateralInput = collateralInputs[i];
6979
- const addressPaymentPart = this.utxoContext.get(collateralInput)?.address().getProps().paymentPart;
6980
- if (addressPaymentPart?.type === 0) {
6981
- requiredWitnesses.add(addressPaymentPart.hash);
6982
- }
6983
- }
6984
- }
6985
- const withdrawalKeys = this.txBody.withdrawals()?.keys();
6986
- if (withdrawalKeys) {
6987
- for (let withdrawalKey of withdrawalKeys) {
6988
- requiredWitnesses.add(RewardAccount.toHash(withdrawalKey));
6989
- }
6990
- }
6991
- const certs = this.txBody.certs()?.values();
6992
- if (certs) {
6993
- for (let cert of certs) {
6994
- const coreCert = cert.toCore();
6995
- switch (coreCert.__typename) {
6996
- case CertificateType.StakeRegistration: {
6997
- requiredWitnesses.add(coreCert.stakeCredential.hash);
6998
- break;
6999
- }
7000
- case CertificateType.StakeDeregistration: {
7001
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7002
- break;
7003
- }
7004
- case CertificateType.PoolRegistration: {
7005
- for (let owner of coreCert.poolParameters.owners) {
7006
- requiredWitnesses.add(RewardAccount.toHash(owner));
7007
- }
7008
- requiredWitnesses.add(PoolId.toKeyHash(coreCert.poolParameters.id));
7009
- break;
7010
- }
7011
- case CertificateType.PoolRetirement: {
7012
- requiredWitnesses.add(PoolId.toKeyHash(coreCert.poolId));
7013
- break;
7014
- }
7015
- case CertificateType.StakeDelegation: {
7016
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7017
- break;
7018
- }
7019
- case CertificateType.MIR:
7020
- break;
7021
- case CertificateType.GenesisKeyDelegation: {
7022
- requiredWitnesses.add(coreCert.genesisDelegateHash);
7023
- break;
7024
- }
7025
- case CertificateType.Registration: {
7026
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7027
- break;
7028
- }
7029
- case CertificateType.Unregistration: {
7030
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7031
- break;
7032
- }
7033
- case CertificateType.VoteDelegation: {
7034
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7035
- break;
7036
- }
7037
- case CertificateType.StakeVoteDelegation: {
7038
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7039
- break;
7040
- }
7041
- case CertificateType.StakeRegistrationDelegation: {
7042
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7043
- break;
7044
- }
7045
- case CertificateType.VoteRegistrationDelegation: {
7046
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7047
- break;
7048
- }
7049
- case CertificateType.StakeVoteRegistrationDelegation: {
7050
- requiredWitnesses.add(coreCert.stakeCredential.hash);
7051
- break;
7052
- }
7053
- case CertificateType.AuthorizeCommitteeHot: {
7054
- requiredWitnesses.add(coreCert.hotCredential.hash);
7055
- break;
7056
- }
7057
- case CertificateType.ResignCommitteeCold: {
7058
- requiredWitnesses.add(coreCert.coldCredential.hash);
7059
- break;
7060
- }
7061
- case CertificateType.RegisterDelegateRepresentative: {
7062
- requiredWitnesses.add(coreCert.dRepCredential.hash);
7063
- break;
7064
- }
7065
- case CertificateType.UnregisterDelegateRepresentative: {
7066
- requiredWitnesses.add(coreCert.dRepCredential.hash);
7067
- break;
7068
- }
7069
- case CertificateType.UpdateDelegateRepresentative: {
7070
- requiredWitnesses.add(coreCert.dRepCredential.hash);
7071
- break;
7072
- }
7073
- }
7074
- }
7075
- }
7076
- for (const scriptHex of this.scriptsProvided) {
7077
- const script = Script.fromCbor((0, import_util9.HexBlob)(scriptHex));
7078
- let nativeScript = script.asNative();
7079
- if (nativeScript) {
7080
- this.addKeyHashesFromNativeScript(nativeScript, requiredWitnesses);
7081
- }
7082
- }
7083
- const requiredSigners = this.txBody.requiredSigners()?.values();
7084
- if (requiredSigners) {
7085
- for (let i = 0; i < requiredSigners.length; i++) {
7086
- requiredWitnesses.add(requiredSigners[i].toCbor());
7087
- }
7088
- }
7089
- return requiredWitnesses.size;
7090
- }
7091
- addKeyHashesFromNativeScript(script, keyHashes) {
7092
- const scriptCore = script.toCore();
7093
- switch (scriptCore.kind) {
7094
- case RequireSignature: {
7095
- keyHashes.add(scriptCore.keyHash);
7096
- break;
7097
- }
7098
- case RequireTimeAfter: {
7099
- break;
7100
- }
7101
- case RequireTimeBefore: {
7102
- break;
7103
- }
7104
- case RequireAllOf: {
7105
- for (const innerScript of scriptCore.scripts) {
7106
- this.addKeyHashesFromNativeScript(
7107
- NativeScript.fromCore(innerScript),
7108
- keyHashes
7109
- );
7110
- }
7111
- break;
7112
- }
7113
- case RequireAnyOf: {
7114
- for (const innerScript of scriptCore.scripts) {
7115
- this.addKeyHashesFromNativeScript(
7116
- NativeScript.fromCore(innerScript),
7117
- keyHashes
7118
- );
7119
- }
7120
- break;
7121
- }
7122
- case RequireNOf: {
7123
- for (const innerScript of scriptCore.scripts) {
7124
- this.addKeyHashesFromNativeScript(
7125
- NativeScript.fromCore(innerScript),
7126
- keyHashes
7127
- );
7128
- }
7129
- break;
7130
- }
7131
- }
7132
- return keyHashes;
7133
- }
7134
7086
  addProvidedPlutusScript = (script) => {
7135
7087
  switch (script.version) {
7136
7088
  case "V1": {
@@ -7162,6 +7114,170 @@ var CardanoSDKSerializerCore = class {
7162
7114
  }
7163
7115
  }
7164
7116
  };
7117
+ addAllVotes = (votes) => {
7118
+ for (let i = 0; i < votes.length; i++) {
7119
+ const vote = votes[i];
7120
+ switch (vote.type) {
7121
+ case "BasicVote": {
7122
+ this.addBasicVote(vote);
7123
+ break;
7124
+ }
7125
+ case "ScriptVote": {
7126
+ this.addScriptVote(vote, i);
7127
+ break;
7128
+ }
7129
+ case "SimpleScriptVote": {
7130
+ this.addSimpleScriptVote(vote);
7131
+ break;
7132
+ }
7133
+ }
7134
+ }
7135
+ };
7136
+ addBasicVote = (basicVote) => {
7137
+ const votes = this.txBody.votingProcedures() ?? import_core8.Serialization.VotingProcedures.fromCore([]);
7138
+ votes.insert(
7139
+ toCardanoVoter(basicVote.vote.voter),
7140
+ toCardanoGovernanceActionId(basicVote.vote.govActionId),
7141
+ toCardanoVotingProcedure(basicVote.vote.votingProcedure)
7142
+ );
7143
+ this.txBody.setVotingProcedures(votes);
7144
+ };
7145
+ addScriptVote = (vote, index) => {
7146
+ if (!vote.scriptSource)
7147
+ throw new Error("Script source not provided for plutus script vote");
7148
+ const plutusScriptSource = vote.scriptSource;
7149
+ if (!plutusScriptSource) {
7150
+ throw new Error(
7151
+ "A script source for a plutus certificate was not plutus script somehow"
7152
+ );
7153
+ }
7154
+ if (!vote.redeemer) {
7155
+ throw new Error("A redeemer was not provided for a plutus vote");
7156
+ }
7157
+ let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
7158
+ let redeemersList = [...redeemers.values()];
7159
+ redeemersList.push(
7160
+ new Redeemer(
7161
+ RedeemerTag.Voting,
7162
+ BigInt(index),
7163
+ fromBuilderToPlutusData(vote.redeemer.data),
7164
+ new ExUnits(
7165
+ BigInt(vote.redeemer.exUnits.mem),
7166
+ BigInt(vote.redeemer.exUnits.steps)
7167
+ )
7168
+ )
7169
+ );
7170
+ redeemers.setValues(redeemersList);
7171
+ this.txWitnessSet.setRedeemers(redeemers);
7172
+ if (plutusScriptSource.type === "Provided") {
7173
+ this.addProvidedPlutusScript(plutusScriptSource.script);
7174
+ } else if (plutusScriptSource.type === "Inline") {
7175
+ this.addScriptRef(plutusScriptSource);
7176
+ }
7177
+ this.addBasicVote({ type: "BasicVote", vote: vote.vote });
7178
+ };
7179
+ addSimpleScriptVote = (vote) => {
7180
+ if (!vote.simpleScriptSource)
7181
+ throw new Error("Script source not provided for native script vote");
7182
+ const nativeScriptSource = vote.simpleScriptSource;
7183
+ if (!nativeScriptSource)
7184
+ throw new Error(
7185
+ "A script source for a native script was not a native script somehow"
7186
+ );
7187
+ if (nativeScriptSource.type === "Provided") {
7188
+ this.scriptsProvided.add(
7189
+ Script.newNativeScript(
7190
+ NativeScript.fromCbor((0, import_util9.HexBlob)(nativeScriptSource.scriptCode))
7191
+ ).toCbor()
7192
+ );
7193
+ } else if (nativeScriptSource.type === "Inline") {
7194
+ this.addSimpleScriptRef(nativeScriptSource);
7195
+ }
7196
+ this.addBasicVote({ type: "BasicVote", vote: vote.vote });
7197
+ };
7198
+ mockVkeyWitnesses = (numberOfRequiredWitnesses) => {
7199
+ let vkeyWitnesses = [];
7200
+ for (let i = 0; i < numberOfRequiredWitnesses; i++) {
7201
+ const numberInHex = this.numberToIntegerHex(i);
7202
+ const pubKeyHex = this.mockPubkey(numberInHex);
7203
+ const signature = this.mockSignature(numberInHex);
7204
+ vkeyWitnesses.push(
7205
+ new VkeyWitness(
7206
+ Ed25519PublicKeyHex2(pubKeyHex),
7207
+ Ed25519SignatureHex2(signature)
7208
+ )
7209
+ );
7210
+ }
7211
+ return vkeyWitnesses;
7212
+ };
7213
+ mockPubkey(numberInHex) {
7214
+ return "0".repeat(VKEY_PUBKEY_SIZE_BYTES * 2 - numberInHex.length).concat(numberInHex);
7215
+ }
7216
+ mockSignature(numberInHex) {
7217
+ return "0".repeat(VKEY_SIGNATURE_SIZE_BYTES * 2 - numberInHex.length).concat(numberInHex);
7218
+ }
7219
+ mockChainCode = (numberInHex) => {
7220
+ return "0".repeat(CHAIN_CODE_SIZE_BYTES * 2 - numberInHex.length).concat(numberInHex);
7221
+ };
7222
+ numberToIntegerHex = (number) => {
7223
+ return BigInt(number).toString(16);
7224
+ };
7225
+ mockBootstrapWitnesses = (byronAddresses) => {
7226
+ let bootstrapWitnesses = [];
7227
+ for (let i = 0; i < byronAddresses.length; i++) {
7228
+ const address = Address.fromBytes(byronAddresses[i]).asByron();
7229
+ if (!address) {
7230
+ throw new Error(`Failed to parse byron address: ${byronAddresses[i]}`);
7231
+ }
7232
+ const numberInHex = this.numberToIntegerHex(i);
7233
+ const pubKeyHex = this.mockPubkey(numberInHex);
7234
+ const signature = this.mockSignature(numberInHex);
7235
+ const chainCode = this.mockChainCode(numberInHex);
7236
+ const attributes = address.getAttributes();
7237
+ bootstrapWitnesses.push(
7238
+ new BootstrapWitness(
7239
+ Ed25519PublicKeyHex2(pubKeyHex),
7240
+ Ed25519SignatureHex2(signature),
7241
+ (0, import_util9.HexBlob)(chainCode),
7242
+ this.serializeByronAttributes(attributes)
7243
+ )
7244
+ );
7245
+ }
7246
+ return bootstrapWitnesses;
7247
+ };
7248
+ serializeByronAttributes = (attributes) => {
7249
+ const writer = new CborWriter();
7250
+ let mapSize = 0;
7251
+ if (attributes.magic) {
7252
+ mapSize++;
7253
+ }
7254
+ if (attributes.derivationPath) {
7255
+ mapSize++;
7256
+ }
7257
+ writer.writeStartMap(mapSize);
7258
+ if (attributes.derivationPath) {
7259
+ writer.writeInt(1);
7260
+ const encodedPathCbor = new CborWriter().writeByteString(import_buffer2.Buffer.from(attributes.derivationPath, "hex")).encode();
7261
+ writer.writeByteString(encodedPathCbor);
7262
+ }
7263
+ if (attributes.magic) {
7264
+ writer.writeInt(2);
7265
+ const encodedMagicCbor = new CborWriter().writeInt(attributes.magic).encode();
7266
+ writer.writeByteString(encodedMagicCbor);
7267
+ }
7268
+ return writer.encodeAsHex();
7269
+ };
7270
+ };
7271
+ var throwErrorWithOrigin = (origin, error) => {
7272
+ if (error instanceof Error) {
7273
+ throw new Error(`${origin}: ${error.message}`);
7274
+ } else if (typeof error === "string") {
7275
+ throw new Error(`${origin}: ${error}`);
7276
+ } else if (typeof error === "object") {
7277
+ throw new Error(`${origin}: ${JSON.stringify(error)}`);
7278
+ } else {
7279
+ throw new Error(`${origin}: ${String(error)}`);
7280
+ }
7165
7281
  };
7166
7282
 
7167
7283
  // src/plutus-tools/index.ts
@@ -7309,6 +7425,7 @@ var CardanoSDK = __toESM(require("@cardano-sdk/core"), 1);
7309
7425
  Bip32PrivateKeyHex,
7310
7426
  Bip32PublicKey,
7311
7427
  Bip32PublicKeyHex,
7428
+ BootstrapWitness,
7312
7429
  Cardano,
7313
7430
  CardanoSDK,
7314
7431
  CardanoSDKSerializer,
@@ -7411,6 +7528,7 @@ var CardanoSDK = __toESM(require("@cardano-sdk/core"), 1);
7411
7528
  buildRewardAddress,
7412
7529
  buildScriptPubkey,
7413
7530
  bytesToHex,
7531
+ calculateFees,
7414
7532
  checkSignature,
7415
7533
  clampScalar,
7416
7534
  computeAuxiliaryDataHash,