@meshsdk/core-cst 1.8.13 → 1.9.0-beta.0

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
@@ -545,7 +545,7 @@ var require_blake2b = __commonJS({
545
545
  }
546
546
  return out;
547
547
  }
548
- function blake2b5(input, key, outlen, salt, personal) {
548
+ function blake2b7(input, key, outlen, salt, personal) {
549
549
  outlen = outlen || 64;
550
550
  input = util.normalizeInput(input);
551
551
  if (salt) {
@@ -559,11 +559,11 @@ var require_blake2b = __commonJS({
559
559
  return blake2bFinal(ctx);
560
560
  }
561
561
  function blake2bHex(input, key, outlen, salt, personal) {
562
- const output = blake2b5(input, key, outlen, salt, personal);
562
+ const output = blake2b7(input, key, outlen, salt, personal);
563
563
  return util.toHex(output);
564
564
  }
565
565
  module.exports = {
566
- blake2b: blake2b5,
566
+ blake2b: blake2b7,
567
567
  blake2bHex,
568
568
  blake2bInit,
569
569
  blake2bUpdate,
@@ -887,7 +887,7 @@ var require_blakejs = __commonJS({
887
887
  });
888
888
 
889
889
  // src/index.ts
890
- import { Cardano as Cardano4, Serialization as Serialization5 } from "@cardano-sdk/core";
890
+ import { Cardano as Cardano5, Serialization as Serialization7 } from "@cardano-sdk/core";
891
891
 
892
892
  // src/types/cardano-sdk.ts
893
893
  import { Cardano, Serialization } from "@cardano-sdk/core";
@@ -899,6 +899,10 @@ var Transaction = Serialization.Transaction;
899
899
  var TransactionId = Cardano.TransactionId;
900
900
  var TransactionBody = Serialization.TransactionBody;
901
901
  var TransactionWitnessSet = Serialization.TransactionWitnessSet;
902
+ var AuxilliaryData = Serialization.AuxiliaryData;
903
+ var TransactionMetadatum = Serialization.TransactionMetadatum;
904
+ var MetadatumMap = Serialization.MetadatumMap;
905
+ var MetadatumList = Serialization.MetadatumList;
902
906
  var TransactionUnspentOutput = Serialization.TransactionUnspentOutput;
903
907
  var TransactionInput = Serialization.TransactionInput;
904
908
  var TransactionOutput = Serialization.TransactionOutput;
@@ -946,6 +950,10 @@ var NativeScript = Serialization.NativeScript;
946
950
  var PlutusV1Script = Serialization.PlutusV1Script;
947
951
  var PlutusV2Script = Serialization.PlutusV2Script;
948
952
  var PlutusV3Script = Serialization.PlutusV3Script;
953
+ var PlutusDataKind = Serialization.PlutusDataKind;
954
+ var PointerAddress = Cardano.PointerAddress;
955
+ var CertIndex = Cardano.CertIndex;
956
+ var TxIndex = Cardano.TxIndex;
949
957
  var Costmdls = Serialization.Costmdls;
950
958
  var CostModel = Serialization.CostModel;
951
959
  var CborWriter = Serialization.CborWriter;
@@ -969,6 +977,8 @@ var ScriptPubkey = Serialization.ScriptPubkey;
969
977
  var DRepID = Cardano.DRepID;
970
978
  var DRep = Serialization.DRep;
971
979
  var StakeCredentialStatus = Cardano.StakeCredentialStatus;
980
+ var computeAuxiliaryDataHash = Cardano.computeAuxiliaryDataHash;
981
+ var blake2b2 = Crypto.blake2b;
972
982
 
973
983
  // src/stricahq/bip32ed25519/wrapper.ts
974
984
  import * as cjsBip32ed25519 from "@stricahq/bip32ed25519";
@@ -1256,11 +1266,18 @@ var signData = (data, signer) => {
1256
1266
 
1257
1267
  // src/resolvers/index.ts
1258
1268
  import { Cardano as Cardano2 } from "@cardano-sdk/core";
1259
- import { blake2b as blake2b3 } from "@cardano-sdk/crypto";
1260
- import { HexBlob as HexBlob4 } from "@cardano-sdk/util";
1269
+ import { blake2b as blake2b5 } from "@cardano-sdk/crypto";
1270
+ import { HexBlob as HexBlob6 } from "@cardano-sdk/util";
1271
+ import base323 from "base32-encoding";
1272
+ import { bech32 as bech323 } from "bech32";
1273
+ import {
1274
+ fromUTF8,
1275
+ mnemonicToEntropy,
1276
+ toBytes as toBytes4
1277
+ } from "@meshsdk/common";
1261
1278
 
1262
1279
  // src/utils/builder.ts
1263
- import { blake2b as blake2b2 } from "@cardano-sdk/crypto";
1280
+ import { blake2b as blake2b4 } from "@cardano-sdk/crypto";
1264
1281
  import { HexBlob } from "@cardano-sdk/util";
1265
1282
  import { pbkdf2Sync } from "pbkdf2";
1266
1283
  import { HARDENED_KEY_START } from "@meshsdk/common";
@@ -1338,7 +1355,7 @@ var buildScriptPubkey = (keyHash) => {
1338
1355
  };
1339
1356
  var buildDRepID = (dRepKey, networkId = NetworkId.Testnet, addressType = AddressType.EnterpriseKey) => {
1340
1357
  const dRepKeyBytes = Buffer.from(dRepKey, "hex");
1341
- const dRepIdHex = blake2b2(28).update(dRepKeyBytes).digest("hex");
1358
+ const dRepIdHex = blake2b4(28).update(dRepKeyBytes).digest("hex");
1342
1359
  const paymentAddress = EnterpriseAddress.packParts({
1343
1360
  networkId,
1344
1361
  paymentPart: {
@@ -1354,55 +1371,265 @@ var buildDRepID = (dRepKey, networkId = NetworkId.Testnet, addressType = Address
1354
1371
  };
1355
1372
 
1356
1373
  // src/utils/converter.ts
1357
- import { Serialization as Serialization2 } from "@cardano-sdk/core";
1374
+ import { Serialization as Serialization3 } from "@cardano-sdk/core";
1358
1375
  import { Ed25519KeyHash as Ed25519KeyHash4 } from "@cardano-sdk/crypto";
1359
- import { HexBlob as HexBlob3 } from "@cardano-sdk/util";
1376
+ import { HexBlob as HexBlob4 } from "@cardano-sdk/util";
1377
+ import base32 from "base32-encoding";
1378
+ import { bech32 } from "bech32";
1360
1379
  import {
1361
- toBytes as toBytes2
1380
+ toBytes as toBytes3
1362
1381
  } from "@meshsdk/common";
1363
1382
 
1364
- // src/utils/deserializer.ts
1365
- import { TxCBOR } from "@cardano-sdk/core";
1366
- import { Ed25519KeyHashHex as Ed25519KeyHashHex3 } from "@cardano-sdk/crypto";
1383
+ // src/utils/data.ts
1367
1384
  import { HexBlob as HexBlob2 } from "@cardano-sdk/util";
1368
1385
  import { toBytes } from "@meshsdk/common";
1369
- var deserializeAddress = (address) => {
1370
- const _address = Address.fromString(address);
1371
- if (_address === null) throw new Error("Invalid address");
1372
- return _address;
1386
+ var toPlutusData = (data) => {
1387
+ const toPlutusList = (data2) => {
1388
+ const plutusList = new PlutusList();
1389
+ data2.forEach((element) => {
1390
+ plutusList.add(toPlutusData(element));
1391
+ });
1392
+ return plutusList;
1393
+ };
1394
+ switch (typeof data) {
1395
+ case "string":
1396
+ return PlutusData.newBytes(toBytes(data));
1397
+ case "number":
1398
+ return PlutusData.newInteger(BigInt(data));
1399
+ case "bigint":
1400
+ return PlutusData.newInteger(BigInt(data));
1401
+ case "object":
1402
+ if (data instanceof Array) {
1403
+ const plutusList = toPlutusList(data);
1404
+ return PlutusData.newList(plutusList);
1405
+ } else if (data instanceof Map) {
1406
+ const plutusMap = new PlutusMap();
1407
+ data.forEach((value, key) => {
1408
+ plutusMap.insert(toPlutusData(key), toPlutusData(value));
1409
+ });
1410
+ return PlutusData.newMap(plutusMap);
1411
+ } else {
1412
+ return PlutusData.newConstrPlutusData(
1413
+ new ConstrPlutusData(
1414
+ BigInt(data.alternative),
1415
+ toPlutusList(data.fields)
1416
+ )
1417
+ );
1418
+ }
1419
+ }
1420
+ };
1421
+ var isConstrPlutusDataJson = (data) => {
1422
+ return typeof data === "object" && "constructor" in data && (typeof data.constructor === "number" || typeof data.constructor === "bigint" || typeof data.constructor === "string") && "fields" in data && Array.isArray(data.fields);
1423
+ };
1424
+ function isMapPlutusDataJson(data) {
1425
+ return typeof data === "object" && Array.isArray(data);
1426
+ }
1427
+ function isKeyValuePlutusDataJson(data) {
1428
+ return typeof data === "object" && "k" in data && typeof data.k === "object" && "v" in data && typeof data.v === "object";
1429
+ }
1430
+ var fromJsonToPlutusData = (data) => {
1431
+ if (isConstrPlutusDataJson(data)) {
1432
+ const plutusList = new PlutusList();
1433
+ data.fields.map((val) => {
1434
+ plutusList.add(fromJsonToPlutusData(val));
1435
+ });
1436
+ const plutusConstrData = new ConstrPlutusData(
1437
+ BigInt(data.constructor),
1438
+ plutusList
1439
+ );
1440
+ return PlutusData.newConstrPlutusData(plutusConstrData);
1441
+ } else if ("int" in data && Object.keys(data).length === 1) {
1442
+ if (typeof data.int === "bigint" || typeof data.int === "number" || typeof data.int === "string") {
1443
+ return PlutusData.newInteger(BigInt(data.int));
1444
+ } else {
1445
+ throw new Error(
1446
+ "Malformed int field in Plutus data, expected one of bigint, number or string"
1447
+ );
1448
+ }
1449
+ } else if ("bytes" in data && Object.keys(data).length === 1) {
1450
+ if (typeof data.bytes === "string") {
1451
+ return PlutusData.newBytes(Buffer.from(data.bytes, "hex"));
1452
+ } else {
1453
+ throw new Error("Malformed bytes field in Plutus data, expected string");
1454
+ }
1455
+ } else if ("list" in data && Object.keys(data).length === 1) {
1456
+ if (Array.isArray(data.list)) {
1457
+ const plutusList = new PlutusList();
1458
+ data.list.map((val) => {
1459
+ plutusList.add(fromJsonToPlutusData(val));
1460
+ });
1461
+ return PlutusData.newList(plutusList);
1462
+ } else {
1463
+ throw new Error("Malformed list field in Plutus data, expected list");
1464
+ }
1465
+ } else if ("map" in data && Object.keys(data).length === 1) {
1466
+ if (isMapPlutusDataJson(data.map)) {
1467
+ const plutusMap = new PlutusMap();
1468
+ data.map.forEach((val) => {
1469
+ if (isKeyValuePlutusDataJson(val)) {
1470
+ plutusMap.insert(
1471
+ fromJsonToPlutusData(val.k),
1472
+ fromJsonToPlutusData(val.v)
1473
+ );
1474
+ } else {
1475
+ throw new Error("Malformed key value pair in Plutus data map");
1476
+ }
1477
+ });
1478
+ return PlutusData.newMap(plutusMap);
1479
+ } else {
1480
+ console.log(data);
1481
+ throw new Error("Malformed map field in Plutus data");
1482
+ }
1483
+ } else {
1484
+ throw new Error("Malformed Plutus data json");
1485
+ }
1486
+ };
1487
+ var fromBuilderToPlutusData = (data) => {
1488
+ if (data.type === "Mesh") {
1489
+ return toPlutusData(data.content);
1490
+ } else if (data.type === "CBOR") {
1491
+ return PlutusData.fromCbor(HexBlob2(data.content));
1492
+ } else if (data.type === "JSON") {
1493
+ let content;
1494
+ if (typeof data.content === "string") {
1495
+ content = JSON.parse(data.content);
1496
+ } else {
1497
+ content = data.content;
1498
+ }
1499
+ return fromJsonToPlutusData(content);
1500
+ } else {
1501
+ throw new Error(
1502
+ "Malformed builder data, expected types of, Mesh, CBOR or JSON"
1503
+ );
1504
+ }
1505
+ };
1506
+ var fromPlutusDataToJson = (data) => {
1507
+ if (data.getKind() === PlutusDataKind.ConstrPlutusData) {
1508
+ const plutusData = data.asConstrPlutusData();
1509
+ if (plutusData) {
1510
+ const fields = plutusData.getData();
1511
+ return {
1512
+ constructor: plutusData.getAlternative(),
1513
+ fields: fromPlutusDataToJson(PlutusData.newList(fields))
1514
+ };
1515
+ } else {
1516
+ throw new Error("Invalid constructor data found");
1517
+ }
1518
+ } else if (data.getKind() === PlutusDataKind.Map) {
1519
+ const plutusMap = data.asMap();
1520
+ const mapList = [];
1521
+ if (plutusMap) {
1522
+ const keys = plutusMap.getKeys();
1523
+ for (let i = 0; i < keys.getLength(); i++) {
1524
+ const key = keys.get(i);
1525
+ const value = plutusMap.get(key);
1526
+ if (value) {
1527
+ mapList.push({
1528
+ k: fromPlutusDataToJson(key),
1529
+ v: fromPlutusDataToJson(value)
1530
+ });
1531
+ }
1532
+ }
1533
+ return {
1534
+ map: mapList
1535
+ };
1536
+ } else {
1537
+ throw new Error("Invalid map data found");
1538
+ }
1539
+ } else if (data.getKind() === PlutusDataKind.List) {
1540
+ const plutusList = data.asList();
1541
+ if (plutusList) {
1542
+ const list = [];
1543
+ for (let i = 0; i < plutusList.getLength(); i++) {
1544
+ const element = plutusList.get(i);
1545
+ list.push(fromPlutusDataToJson(element));
1546
+ }
1547
+ return list;
1548
+ } else {
1549
+ throw new Error("Invalid list data found");
1550
+ }
1551
+ } else if (data.getKind() === PlutusDataKind.Integer) {
1552
+ const plutusInt = data.asInteger();
1553
+ if (plutusInt) {
1554
+ return {
1555
+ int: BigInt(plutusInt.toString())
1556
+ };
1557
+ } else {
1558
+ throw new Error("Invalid integer data found");
1559
+ }
1560
+ } else if (data.getKind() === PlutusDataKind.Bytes) {
1561
+ const plutusBytes = data.asBoundedBytes();
1562
+ if (plutusBytes) {
1563
+ return {
1564
+ bytes: Buffer.from(plutusBytes).toString("hex")
1565
+ };
1566
+ } else {
1567
+ throw new Error("Invalid bytes data found");
1568
+ }
1569
+ } else {
1570
+ throw new Error("Invalid Plutus data found");
1571
+ }
1572
+ };
1573
+ var datumCborToJson = (datumCbor) => {
1574
+ const parsedDatum = PlutusData.fromCbor(HexBlob2(datumCbor));
1575
+ return fromPlutusDataToJson(parsedDatum);
1576
+ };
1577
+ var parseDatumCbor = (datumCbor) => {
1578
+ return datumCborToJson(datumCbor);
1579
+ };
1580
+ var parseInlineDatum = (utxo) => {
1581
+ const datumCbor = utxo.inline_datum || "";
1582
+ return datumCborToJson(datumCbor);
1373
1583
  };
1374
- var deserializeEd25519KeyHash = (ed25519KeyHash) => Ed25519KeyHash2.fromBytes(toBytes(ed25519KeyHash));
1375
1584
  var deserializeDataHash = (dataHash) => DatumHash.fromHexBlob(HexBlob2(dataHash));
1376
1585
  var deserializePlutusData = (plutusData) => PlutusData.fromCbor(HexBlob2(plutusData));
1586
+
1587
+ // src/utils/deserializer.ts
1588
+ import { Serialization as Serialization2 } from "@cardano-sdk/core";
1589
+ import { Ed25519KeyHashHex as Ed25519KeyHashHex3 } from "@cardano-sdk/crypto";
1590
+ import { HexBlob as HexBlob3 } from "@cardano-sdk/util";
1591
+ import { toBytes as toBytes2 } from "@meshsdk/common";
1592
+ var deserializeEd25519KeyHash = (ed25519KeyHash) => Ed25519KeyHash2.fromBytes(toBytes2(ed25519KeyHash));
1377
1593
  var deserializePlutusScript = (plutusScript, version) => {
1378
1594
  switch (version) {
1379
1595
  case "V1":
1380
- return PlutusV1Script.fromCbor(HexBlob2(plutusScript));
1596
+ return PlutusV1Script.fromCbor(HexBlob3(plutusScript));
1381
1597
  case "V2":
1382
- return PlutusV2Script.fromCbor(HexBlob2(plutusScript));
1598
+ return PlutusV2Script.fromCbor(HexBlob3(plutusScript));
1383
1599
  case "V3":
1384
- return PlutusV3Script.fromCbor(HexBlob2(plutusScript));
1600
+ return PlutusV3Script.fromCbor(HexBlob3(plutusScript));
1385
1601
  default:
1386
1602
  throw new Error("Invalid Plutus script version");
1387
1603
  }
1388
1604
  };
1389
- var deserializeNativeScript = (nativeScript) => NativeScript.fromCbor(HexBlob2(nativeScript));
1605
+ var deserializeNativeScript = (nativeScript) => NativeScript.fromCbor(HexBlob3(nativeScript));
1390
1606
  var deserializeScriptHash = (scriptHash) => ScriptHash.fromEd25519KeyHashHex(Ed25519KeyHashHex3(scriptHash));
1391
- var deserializeScriptRef = (scriptRef) => Script.fromCbor(HexBlob2(scriptRef));
1392
- var deserializeTxUnspentOutput = (txUnspentOutput) => TransactionUnspentOutput.fromCbor(HexBlob2(txUnspentOutput));
1393
- var deserializeValue = (value) => Value.fromCbor(HexBlob2(value));
1394
- var deserializeTx = (tx) => Transaction.fromCbor(TxCBOR(tx));
1395
- var deserializeTxHash = (txHash) => TransactionId.fromHexBlob(HexBlob2(txHash));
1607
+ var deserializeScriptRef = (scriptRef) => Script.fromCbor(HexBlob3(scriptRef));
1608
+ var deserializeTxUnspentOutput = (txUnspentOutput) => TransactionUnspentOutput.fromCbor(HexBlob3(txUnspentOutput));
1609
+ var deserializeValue = (value) => Value.fromCbor(HexBlob3(value));
1610
+ var deserializeTx = (tx) => Transaction.fromCbor(Serialization2.TxCBOR(tx));
1611
+ var deserializeTxHash = (txHash) => TransactionId.fromHexBlob(HexBlob3(txHash));
1396
1612
 
1397
1613
  // src/utils/converter.ts
1398
- var toAddress = (bech32) => Address.fromBech32(bech32);
1399
- var toBaseAddress = (bech32) => {
1400
- return BaseAddress.fromAddress(toAddress(bech32));
1614
+ var toAddress = (bech325) => Address.fromBech32(bech325);
1615
+ var toCardanoAddress = (address) => {
1616
+ try {
1617
+ return Address.fromBech32(address);
1618
+ } catch {
1619
+ try {
1620
+ return Address.fromBase58(address);
1621
+ } catch {
1622
+ throw new Error("Invalid address format");
1623
+ }
1624
+ }
1401
1625
  };
1402
- var toEnterpriseAddress = (bech32) => {
1403
- return EnterpriseAddress.fromAddress(toAddress(bech32));
1626
+ var toBaseAddress = (bech325) => {
1627
+ return BaseAddress.fromAddress(toAddress(bech325));
1404
1628
  };
1405
- var toRewardAddress = (bech32) => RewardAddress.fromAddress(toAddress(bech32));
1629
+ var toEnterpriseAddress = (bech325) => {
1630
+ return EnterpriseAddress.fromAddress(toAddress(bech325));
1631
+ };
1632
+ var toRewardAddress = (bech325) => RewardAddress.fromAddress(toAddress(bech325));
1406
1633
  var fromTxUnspentOutput = (txUnspentOutput) => {
1407
1634
  const dataHash = txUnspentOutput.output().datum() ? txUnspentOutput.output().datum()?.toCbor().toString() : void 0;
1408
1635
  const scriptRef = txUnspentOutput.output().scriptRef() ? txUnspentOutput.output().scriptRef()?.toCbor().toString() : void 0;
@@ -1440,7 +1667,7 @@ var toTxUnspentOutput = (utxo) => {
1440
1667
  }
1441
1668
  if (utxo.output.plutusData !== void 0) {
1442
1669
  const plutusData = deserializePlutusData(utxo.output.plutusData);
1443
- const datum = new Serialization2.Datum(void 0, plutusData);
1670
+ const datum = new Serialization3.Datum(void 0, plutusData);
1444
1671
  txOutput.setDatum(datum);
1445
1672
  }
1446
1673
  if (utxo.output.scriptRef !== void 0) {
@@ -1486,7 +1713,7 @@ var toScriptRef = (script) => {
1486
1713
  return Script.newNativeScript(toNativeScript(script));
1487
1714
  };
1488
1715
  var fromScriptRef = (scriptRef) => {
1489
- const script = Script.fromCbor(HexBlob3(scriptRef));
1716
+ const script = Script.fromCbor(HexBlob4(scriptRef));
1490
1717
  const plutusScriptCodeV3 = script.asPlutusV3()?.toCbor().toString();
1491
1718
  if (plutusScriptCodeV3) {
1492
1719
  return {
@@ -1584,70 +1811,35 @@ var toNativeScript = (script) => {
1584
1811
  switch (script.type) {
1585
1812
  case "all":
1586
1813
  return NativeScript.newScriptAll(
1587
- new Serialization2.ScriptAll(toNativeScripts(script.scripts))
1814
+ new Serialization3.ScriptAll(toNativeScripts(script.scripts))
1588
1815
  );
1589
1816
  case "any":
1590
1817
  return NativeScript.newScriptAny(
1591
- new Serialization2.ScriptAny(toNativeScripts(script.scripts))
1818
+ new Serialization3.ScriptAny(toNativeScripts(script.scripts))
1592
1819
  );
1593
1820
  case "atLeast":
1594
1821
  return NativeScript.newScriptNOfK(
1595
- new Serialization2.ScriptNOfK(
1822
+ new Serialization3.ScriptNOfK(
1596
1823
  toNativeScripts(script.scripts),
1597
1824
  script.required
1598
1825
  )
1599
1826
  );
1600
1827
  case "after":
1601
1828
  return NativeScript.newTimelockStart(
1602
- new Serialization2.TimelockStart(Slot(parseInt(script.slot)))
1829
+ new Serialization3.TimelockStart(Slot(parseInt(script.slot)))
1603
1830
  );
1604
1831
  case "before":
1605
1832
  return NativeScript.newTimelockExpiry(
1606
- new Serialization2.TimelockExpiry(Slot(parseInt(script.slot)))
1833
+ new Serialization3.TimelockExpiry(Slot(parseInt(script.slot)))
1607
1834
  );
1608
1835
  case "sig":
1609
1836
  return NativeScript.newScriptPubkey(
1610
- new Serialization2.ScriptPubkey(
1611
- Ed25519KeyHash4.fromBytes(toBytes2(script.keyHash)).hex()
1837
+ new Serialization3.ScriptPubkey(
1838
+ Ed25519KeyHash4.fromBytes(toBytes3(script.keyHash)).hex()
1612
1839
  )
1613
1840
  );
1614
1841
  }
1615
1842
  };
1616
- var toPlutusData = (data) => {
1617
- const toPlutusList = (data2) => {
1618
- const plutusList = new PlutusList();
1619
- data2.forEach((element) => {
1620
- plutusList.add(toPlutusData(element));
1621
- });
1622
- return plutusList;
1623
- };
1624
- switch (typeof data) {
1625
- case "string":
1626
- return PlutusData.newBytes(toBytes2(data));
1627
- case "number":
1628
- return PlutusData.newInteger(BigInt(data));
1629
- case "bigint":
1630
- return PlutusData.newInteger(BigInt(data));
1631
- case "object":
1632
- if (data instanceof Array) {
1633
- const plutusList = toPlutusList(data);
1634
- return PlutusData.newList(plutusList);
1635
- } else if (data instanceof Map) {
1636
- const plutusMap = new PlutusMap();
1637
- data.forEach((value, key) => {
1638
- plutusMap.insert(toPlutusData(key), toPlutusData(value));
1639
- });
1640
- return PlutusData.newMap(plutusMap);
1641
- } else {
1642
- return PlutusData.newConstrPlutusData(
1643
- new ConstrPlutusData(
1644
- BigInt(data.alternative),
1645
- toPlutusList(data.fields)
1646
- )
1647
- );
1648
- }
1649
- }
1650
- };
1651
1843
  var toValue = (assets) => {
1652
1844
  const multiAsset = /* @__PURE__ */ new Map();
1653
1845
  assets.filter((asset) => asset.unit !== "lovelace").forEach((asset) => {
@@ -1660,6 +1852,102 @@ var toValue = (assets) => {
1660
1852
  }
1661
1853
  return value;
1662
1854
  };
1855
+ var toDRep = (dRepId) => {
1856
+ if (dRepId.length === 58) {
1857
+ const { prefix, words } = bech32.decode(dRepId);
1858
+ if (prefix !== "drep") {
1859
+ throw new Error("Invalid DRepId prefix");
1860
+ }
1861
+ const bytes = base32.decode(new Uint8Array(words));
1862
+ if (bytes[0] === 34) {
1863
+ return Serialization3.DRep.newKeyHash(
1864
+ Ed25519KeyHashHex2(bytes.subarray(1).toString("hex"))
1865
+ );
1866
+ } else if (bytes[0] === 35) {
1867
+ return Serialization3.DRep.newScriptHash(
1868
+ Hash28ByteBase162(bytes.subarray(1).toString("hex"))
1869
+ );
1870
+ } else {
1871
+ throw new Error("Malformed CIP129 DRepId");
1872
+ }
1873
+ } else {
1874
+ const { prefix, words } = bech32.decode(dRepId);
1875
+ switch (prefix) {
1876
+ case "drep": {
1877
+ return Serialization3.DRep.newKeyHash(
1878
+ Ed25519KeyHashHex2(
1879
+ base32.decode(new Uint8Array(words)).toString("hex")
1880
+ )
1881
+ );
1882
+ }
1883
+ case "drep_script": {
1884
+ return Serialization3.DRep.newScriptHash(
1885
+ Hash28ByteBase162(
1886
+ base32.decode(new Uint8Array(words)).toString("hex")
1887
+ )
1888
+ );
1889
+ }
1890
+ default: {
1891
+ throw new Error("Malformed DRepId prefix");
1892
+ }
1893
+ }
1894
+ }
1895
+ };
1896
+ var getDRepIds = (dRepId) => {
1897
+ let result = {
1898
+ cip105: "",
1899
+ cip129: ""
1900
+ };
1901
+ if (dRepId.length === 58) {
1902
+ result.cip129 = dRepId;
1903
+ const { prefix, words } = bech32.decode(dRepId);
1904
+ if (prefix !== "drep") {
1905
+ throw new Error("Malformed CIP129 DRepId");
1906
+ }
1907
+ const bytes = base32.decode(new Uint8Array(words));
1908
+ if (bytes[0] === 34) {
1909
+ result.cip105 = bech32.encode("drep", base32.encode(bytes.subarray(1)));
1910
+ } else if (bytes[0] === 35) {
1911
+ result.cip105 = bech32.encode(
1912
+ "drep_script",
1913
+ base32.encode(bytes.subarray(1))
1914
+ );
1915
+ } else {
1916
+ throw new Error("Malformed CIP129 DRepId");
1917
+ }
1918
+ } else {
1919
+ result.cip105 = dRepId;
1920
+ try {
1921
+ const { prefix, words } = bech32.decode(dRepId);
1922
+ let rawBytes = base32.decode(new Uint8Array(words));
1923
+ if (prefix === "drep") {
1924
+ if (!rawBytes) {
1925
+ throw new Error("Malformed key hash in DRepId");
1926
+ }
1927
+ let rawBytesWithPrefix = new Uint8Array(rawBytes.length + 1);
1928
+ rawBytesWithPrefix.set([34]);
1929
+ rawBytesWithPrefix.set(rawBytes, 1);
1930
+ let base32RawBytes = base32.encode(rawBytesWithPrefix);
1931
+ result.cip129 = bech32.encode("drep", base32RawBytes);
1932
+ } else if (prefix === "drep_script") {
1933
+ if (!rawBytes) {
1934
+ throw new Error("Malformed script hash in DRepId");
1935
+ }
1936
+ let rawBytesWithPrefix = new Uint8Array(rawBytes.length + 1);
1937
+ rawBytesWithPrefix.set([35]);
1938
+ rawBytesWithPrefix.set(rawBytes, 1);
1939
+ let base32RawBytes = base32.encode(rawBytesWithPrefix);
1940
+ result.cip129 = bech32.encode("drep", base32RawBytes);
1941
+ } else {
1942
+ throw new Error("Can only calculate DRepIds for script/key DReps");
1943
+ }
1944
+ } catch (e) {
1945
+ console.error(e);
1946
+ throw new Error("Malformed DRepId");
1947
+ }
1948
+ }
1949
+ return result;
1950
+ };
1663
1951
 
1664
1952
  // src/utils/value.ts
1665
1953
  function mergeValue(a, b) {
@@ -1717,115 +2005,907 @@ function empty(v) {
1717
2005
  return assetTypes(v) == 0;
1718
2006
  }
1719
2007
 
1720
- // src/utils/encoding.ts
1721
- var hexToBytes = (hex) => Buffer.from(hex, "hex");
1722
-
1723
- // src/resolvers/index.ts
1724
- var resolveDataHash = (data) => {
1725
- const plutusData = toPlutusData(data);
1726
- return plutusData.hash().toString();
1727
- };
1728
- var resolveNativeScriptAddress = (script, networkId = 0) => {
1729
- const nativeScript = toNativeScript(script);
1730
- const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
1731
- hash: nativeScript.hash(),
1732
- type: Cardano2.CredentialType.ScriptHash
1733
- });
1734
- return enterpriseAddress.toAddress().toBech32();
1735
- };
1736
- var resolveNativeScriptHash = (script) => {
1737
- return toNativeScript(script).hash().toString();
1738
- };
1739
- var resolvePaymentKeyHash = (bech32) => {
1740
- try {
1741
- const paymentKeyHash = [
1742
- toBaseAddress(bech32)?.getPaymentCredential().hash,
1743
- toEnterpriseAddress(bech32)?.getPaymentCredential().hash
1744
- ].find((kh) => kh !== void 0);
1745
- if (paymentKeyHash !== void 0) return paymentKeyHash.toString();
2008
+ // src/utils/address.ts
2009
+ import { HexBlob as HexBlob5 } from "@cardano-sdk/util";
2010
+ import {
2011
+ pubKeyAddress,
2012
+ scriptAddress
2013
+ } from "@meshsdk/common";
2014
+ var serialzeAddress = (deserializedAddress, networkId = 0) => {
2015
+ const {
2016
+ pubKeyHash,
2017
+ scriptHash,
2018
+ stakeCredentialHash,
2019
+ stakeScriptCredentialHash
2020
+ } = deserializedAddress;
2021
+ const isPaymentScript = !pubKeyHash;
2022
+ const isStakeScript = !stakeCredentialHash;
2023
+ const paymentHash = isPaymentScript ? scriptHash : pubKeyHash;
2024
+ const stakeHash = isStakeScript ? stakeScriptCredentialHash : stakeCredentialHash;
2025
+ if (!paymentHash)
1746
2026
  throw new Error(
1747
- `Couldn't resolve payment key hash from address: ${bech32}`
2027
+ "Error: serializeAddress: Address must contain a payment part"
1748
2028
  );
1749
- } catch (error) {
2029
+ const addressObj = isPaymentScript ? scriptAddress(paymentHash, stakeHash, isStakeScript) : pubKeyAddress(paymentHash, stakeHash, isStakeScript);
2030
+ return serializeAddressObj(addressObj, networkId);
2031
+ };
2032
+ var addrBech32ToPlutusData = (bech325) => {
2033
+ const cardanoAddress = Address.fromBech32(bech325);
2034
+ const cardanoAddressProps = cardanoAddress.getProps();
2035
+ const paymentPartList = new PlutusList();
2036
+ if (!cardanoAddressProps.paymentPart) {
1750
2037
  throw new Error(
1751
- `An error occurred during resolvePaymentKeyHash: ${error}.`
2038
+ "Error: addrBech32ToPlutusDataHex: Address must contain a payment part"
1752
2039
  );
1753
2040
  }
1754
- };
1755
- var resolvePlutusScriptAddress = (script, networkId = 0) => {
1756
- const plutusScript = deserializePlutusScript(script.code, script.version);
1757
- const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
1758
- hash: plutusScript.hash(),
1759
- type: Cardano2.CredentialType.ScriptHash
1760
- });
1761
- return enterpriseAddress.toAddress().toBech32();
1762
- };
1763
- var resolvePlutusScriptHash = (bech32) => {
1764
- try {
1765
- const enterpriseAddress = toEnterpriseAddress(bech32);
1766
- const scriptHash = enterpriseAddress?.getPaymentCredential().hash;
1767
- if (scriptHash !== void 0) return scriptHash.toString();
1768
- throw new Error(`Couldn't resolve script hash from address: ${bech32}`);
1769
- } catch (error) {
1770
- throw new Error(`An error occurred during resolveScriptHash: ${error}.`);
2041
+ paymentPartList.add(
2042
+ PlutusData.newBytes(
2043
+ Buffer.from(cardanoAddressProps.paymentPart.hash, "hex")
2044
+ )
2045
+ );
2046
+ const paymentPart = PlutusData.newConstrPlutusData(
2047
+ new ConstrPlutusData(
2048
+ BigInt(cardanoAddressProps.paymentPart.type),
2049
+ paymentPartList
2050
+ )
2051
+ );
2052
+ const delegationPartList = new PlutusList();
2053
+ let delegationPart;
2054
+ if (cardanoAddressProps.delegationPart) {
2055
+ delegationPartList.add(
2056
+ PlutusData.newBytes(
2057
+ Buffer.from(cardanoAddressProps.delegationPart.hash, "hex")
2058
+ )
2059
+ );
2060
+ const inlineDelegationPart = PlutusData.newConstrPlutusData(
2061
+ new ConstrPlutusData(BigInt(0), delegationPartList)
2062
+ );
2063
+ const someList = new PlutusList();
2064
+ someList.add(inlineDelegationPart);
2065
+ delegationPart = PlutusData.newConstrPlutusData(
2066
+ new ConstrPlutusData(BigInt(0), someList)
2067
+ );
2068
+ } else if (cardanoAddressProps.pointer) {
2069
+ const pointerList = new PlutusList();
2070
+ pointerList.add(
2071
+ PlutusData.newInteger(BigInt(cardanoAddressProps.pointer.slot))
2072
+ );
2073
+ pointerList.add(
2074
+ PlutusData.newInteger(BigInt(cardanoAddressProps.pointer.txIndex))
2075
+ );
2076
+ pointerList.add(
2077
+ PlutusData.newInteger(BigInt(cardanoAddressProps.pointer.certIndex))
2078
+ );
2079
+ const pointer = PlutusData.newConstrPlutusData(
2080
+ new ConstrPlutusData(BigInt(1), pointerList)
2081
+ );
2082
+ const someList = new PlutusList();
2083
+ someList.add(pointer);
2084
+ delegationPart = PlutusData.newConstrPlutusData(
2085
+ new ConstrPlutusData(BigInt(0), someList)
2086
+ );
2087
+ } else {
2088
+ delegationPart = PlutusData.newConstrPlutusData(
2089
+ new ConstrPlutusData(BigInt(1), new PlutusList())
2090
+ );
1771
2091
  }
2092
+ const addressList = new PlutusList();
2093
+ addressList.add(paymentPart);
2094
+ addressList.add(delegationPart);
2095
+ return PlutusData.newConstrPlutusData(
2096
+ new ConstrPlutusData(BigInt(0), addressList)
2097
+ );
1772
2098
  };
1773
- var resolvePoolId = (hash) => {
1774
- return Ed25519KeyHashHex2(hash).toString();
1775
- };
1776
- var resolvePrivateKey = (words) => {
1777
- return "not implemented";
2099
+ var addrBech32ToPlutusDataHex = (bech325) => {
2100
+ return addrBech32ToPlutusData(bech325).toCbor();
1778
2101
  };
1779
- var resolveScriptRef = (script) => {
1780
- return toScriptRef(script).toCbor().toString();
2102
+ var addrBech32ToPlutusDataObj = (bech325) => {
2103
+ return fromPlutusDataToJson(addrBech32ToPlutusData(bech325));
1781
2104
  };
1782
- var resolveRewardAddress = (bech32) => {
1783
- try {
1784
- const address = toAddress(bech32);
1785
- const baseAddress = toBaseAddress(bech32);
1786
- const stakeKeyHash = baseAddress?.getStakeCredential().hash;
1787
- if (stakeKeyHash !== void 0)
1788
- return buildRewardAddress(address.getNetworkId(), stakeKeyHash).toAddress().toBech32();
1789
- throw new Error(`Couldn't resolve reward address from address: ${bech32}`);
1790
- } catch (error) {
1791
- throw new Error(`An error occurred during resolveRewardAddress: ${error}.`);
2105
+ var plutusDataToAddrBech32 = (plutusData, networkId = 0) => {
2106
+ const constrPlutusData = plutusData.asConstrPlutusData();
2107
+ if (!constrPlutusData || constrPlutusData.getAlternative() !== BigInt(0)) {
2108
+ throw new Error(
2109
+ "Error: serializeAddressObj: Address must contain a constructor 0"
2110
+ );
1792
2111
  }
1793
- };
1794
- var resolveStakeKeyHash = (bech32) => {
1795
- try {
1796
- const stakeKeyHash = [
1797
- toBaseAddress(bech32)?.getStakeCredential().hash,
1798
- toRewardAddress(bech32)?.getPaymentCredential().hash
1799
- ].find((kh) => kh !== void 0);
1800
- if (stakeKeyHash !== void 0) return stakeKeyHash.toString();
1801
- throw new Error(`Couldn't resolve stake key hash from address: ${bech32}`);
1802
- } catch (error) {
1803
- throw new Error(`An error occurred during resolveStakeKeyHash: ${error}.`);
2112
+ const plutusDataList = constrPlutusData.getData();
2113
+ if (plutusDataList.getLength() !== 2) {
2114
+ throw new Error("Error: serializeAddressObj: Address must contain 2 parts");
1804
2115
  }
1805
- };
2116
+ const paymentData = plutusDataList.get(0);
2117
+ const paymentConstrData = paymentData.asConstrPlutusData();
2118
+ if (!paymentConstrData) {
2119
+ throw new Error(
2120
+ "Error: serializeAddressObj: Payment part must be a constructor"
2121
+ );
2122
+ }
2123
+ const paymentConstrDataList = paymentConstrData.getData();
2124
+ if (paymentConstrDataList.getLength() !== 1) {
2125
+ throw new Error(
2126
+ "Error: serializeAddressObj: Payment part must contain 1 element"
2127
+ );
2128
+ }
2129
+ const paymentBytes = paymentConstrDataList.get(0).asBoundedBytes();
2130
+ if (!paymentBytes) {
2131
+ throw new Error(
2132
+ "Error: serializeAddressObj: Payment inner part must be bytes"
2133
+ );
2134
+ }
2135
+ if (paymentConstrData.getAlternative() !== BigInt(0) && paymentConstrData.getAlternative() !== BigInt(1)) {
2136
+ throw new Error(
2137
+ "Error: serializeAddressObj: Payment part must be alternative 0 or 1"
2138
+ );
2139
+ }
2140
+ const cardanoPaymentCredential = {
2141
+ hash: Hash28ByteBase162(Buffer.from(paymentBytes).toString("hex")),
2142
+ type: paymentConstrData.getAlternative() === BigInt(0) ? 0 : 1
2143
+ };
2144
+ const delegationData = plutusDataList.get(1);
2145
+ const delegationConstrData = delegationData.asConstrPlutusData();
2146
+ if (!delegationConstrData) {
2147
+ throw new Error(
2148
+ "Error: serializeAddressObj: Delegation part must be a constructor"
2149
+ );
2150
+ }
2151
+ if (delegationConstrData.getAlternative() === BigInt(1)) {
2152
+ return EnterpriseAddress.fromCredentials(
2153
+ networkId,
2154
+ cardanoPaymentCredential
2155
+ ).toAddress().toBech32();
2156
+ } else if (delegationConstrData.getAlternative() === BigInt(0)) {
2157
+ const delegationDataList = delegationConstrData.getData();
2158
+ if (delegationDataList.getLength() !== 1) {
2159
+ throw new Error(
2160
+ "Error: serializeAddressObj: Delegation part must contain 1 element"
2161
+ );
2162
+ }
2163
+ const delegationDataInner = delegationDataList.get(0);
2164
+ const delegationDataInnerConstrData = delegationDataInner.asConstrPlutusData();
2165
+ if (!delegationDataInnerConstrData) {
2166
+ throw new Error(
2167
+ "Error: serializeAddressObj: Delegation inner part must be a constructor"
2168
+ );
2169
+ }
2170
+ if (delegationDataInnerConstrData.getAlternative() === BigInt(0)) {
2171
+ const delegationDataInnerList = delegationDataInnerConstrData.getData();
2172
+ if (delegationDataInnerList.getLength() !== 1) {
2173
+ throw new Error(
2174
+ "Error: serializeAddressObj: Delegation inner part must contain 1 element"
2175
+ );
2176
+ }
2177
+ const delegationBytes = delegationDataInnerList.get(0).asBoundedBytes();
2178
+ if (!delegationBytes) {
2179
+ throw new Error(
2180
+ "Error: serializeAddressObj: Delegation inner part must be bytes"
2181
+ );
2182
+ }
2183
+ const cardanoStakeCredential = {
2184
+ hash: Hash28ByteBase162(Buffer.from(delegationBytes).toString("hex")),
2185
+ type: delegationDataInnerConstrData.getAlternative() === BigInt(0) ? 0 : 1
2186
+ };
2187
+ return BaseAddress.fromCredentials(
2188
+ networkId,
2189
+ cardanoPaymentCredential,
2190
+ cardanoStakeCredential
2191
+ ).toAddress().toBech32();
2192
+ } else if (delegationDataInnerConstrData.getAlternative() === BigInt(1)) {
2193
+ const delegationDataInnerList = delegationDataInnerConstrData.getData();
2194
+ if (delegationDataInnerList.getLength() !== 3) {
2195
+ throw new Error(
2196
+ "Error: serializeAddressObj: Delegation inner part must contain 3 elements"
2197
+ );
2198
+ }
2199
+ const slot = delegationDataInnerList.get(0).asInteger();
2200
+ if (!slot) {
2201
+ throw new Error(
2202
+ "Error: serializeAddressObj: Delegation inner part slot must be integer"
2203
+ );
2204
+ }
2205
+ const txIndex = delegationDataInnerList.get(1).asInteger();
2206
+ if (!txIndex) {
2207
+ throw new Error(
2208
+ "Error: serializeAddressObj: Delegation inner part txIndex must be integer"
2209
+ );
2210
+ }
2211
+ const certIndex = delegationDataInnerList.get(2).asInteger();
2212
+ if (!certIndex) {
2213
+ throw new Error(
2214
+ "Error: serializeAddressObj: Delegation inner part certIndex must be integer"
2215
+ );
2216
+ }
2217
+ const cardanoPointer = {
2218
+ slot,
2219
+ txIndex: TxIndex(Number(txIndex)),
2220
+ certIndex: CertIndex(Number(certIndex))
2221
+ };
2222
+ return PointerAddress.fromCredentials(
2223
+ networkId,
2224
+ cardanoPaymentCredential,
2225
+ cardanoPointer
2226
+ ).toAddress().toBech32();
2227
+ } else {
2228
+ throw new Error(
2229
+ "Error: serializeAddressObj: Delegation inner part must be alternative 0 or 1"
2230
+ );
2231
+ }
2232
+ } else {
2233
+ throw new Error(
2234
+ "Error: serializeAddressObj: Delegation part must be alternative 0 or 1"
2235
+ );
2236
+ }
2237
+ };
2238
+ var serializeAddressObj = (plutusDataAddressObject, networkId = 0) => {
2239
+ const cardanoPlutusData = fromJsonToPlutusData(plutusDataAddressObject);
2240
+ return plutusDataToAddrBech32(cardanoPlutusData, networkId);
2241
+ };
2242
+ var serializePlutusAddressToBech32 = (plutusHex, networkId = 0) => {
2243
+ const cardanoPlutusData = PlutusData.fromCbor(HexBlob5(plutusHex));
2244
+ return plutusDataToAddrBech32(cardanoPlutusData, networkId);
2245
+ };
2246
+ var deserializeBech32Address = (bech32Addr) => {
2247
+ const deserializedAddress = Address.fromBech32(bech32Addr).getProps();
2248
+ return {
2249
+ pubKeyHash: deserializedAddress.paymentPart?.type === CredentialType.KeyHash ? deserializedAddress.paymentPart?.hash : "",
2250
+ scriptHash: deserializedAddress.paymentPart?.type === CredentialType.ScriptHash ? deserializedAddress.paymentPart?.hash : "",
2251
+ stakeCredentialHash: deserializedAddress.delegationPart?.type === CredentialType.KeyHash ? deserializedAddress.delegationPart?.hash : "",
2252
+ stakeScriptCredentialHash: deserializedAddress.delegationPart?.type === CredentialType.ScriptHash ? deserializedAddress.delegationPart?.hash : ""
2253
+ };
2254
+ };
2255
+ var deserializeAddress = (address) => {
2256
+ const _address = Address.fromString(address);
2257
+ if (_address === null) throw new Error("Invalid address");
2258
+ return _address;
2259
+ };
2260
+ var scriptHashToBech32 = (scriptHash, stakeCredentialHash, networkId = 0, isScriptStakeCredentialHash = false) => {
2261
+ if (stakeCredentialHash) {
2262
+ return BaseAddress.fromCredentials(
2263
+ networkId,
2264
+ { hash: Hash28ByteBase162(scriptHash), type: CredentialType.ScriptHash },
2265
+ {
2266
+ hash: Hash28ByteBase162(stakeCredentialHash),
2267
+ type: isScriptStakeCredentialHash ? CredentialType.ScriptHash : CredentialType.KeyHash
2268
+ }
2269
+ ).toAddress().toBech32().toString();
2270
+ } else {
2271
+ return EnterpriseAddress.fromCredentials(networkId, {
2272
+ hash: Hash28ByteBase162(scriptHash),
2273
+ type: CredentialType.ScriptHash
2274
+ }).toAddress().toBech32().toString();
2275
+ }
2276
+ };
2277
+ var v2ScriptToBech32 = (scriptCbor, stakeCredential, networkId = 0, isScriptStakeCredential = false) => scriptHashToBech32(
2278
+ Script.fromCbor(HexBlob5(scriptCbor)).hash().toString(),
2279
+ stakeCredential,
2280
+ networkId,
2281
+ isScriptStakeCredential
2282
+ );
2283
+ var scriptHashToRewardAddress = (hash, networkId = 0) => {
2284
+ return RewardAddress.fromCredentials(networkId, {
2285
+ hash: Hash28ByteBase162(hash),
2286
+ type: CredentialType.ScriptHash
2287
+ }).toAddress().toBech32().toString();
2288
+ };
2289
+ var keyHashToRewardAddress = (hash, networkId = 0) => {
2290
+ return RewardAddress.fromCredentials(networkId, {
2291
+ hash: Hash28ByteBase162(hash),
2292
+ type: CredentialType.KeyHash
2293
+ }).toAddress().toBech32().toString();
2294
+ };
2295
+
2296
+ // src/utils/encoding.ts
2297
+ import base322 from "base32-encoding";
2298
+ import { bech32 as bech322 } from "bech32";
2299
+ var bytesToHex = (bytes) => Buffer.from(bytes).toString("hex");
2300
+ var hexToBytes = (hex) => Buffer.from(hex, "hex");
2301
+ var utf8ToBytes = (str) => Buffer.from(str, "utf8");
2302
+ var utf8ToHex = (str) => Buffer.from(str, "utf8").toString("hex");
2303
+ var hexToBech32 = (prefix, hex) => {
2304
+ const buf = Buffer.from(hex, "hex");
2305
+ const base32RawBytes = base322.encode(buf);
2306
+ return bech322.encode(prefix, base32RawBytes);
2307
+ };
2308
+
2309
+ // src/resolvers/index.ts
2310
+ var resolveDataHash = (data) => {
2311
+ const plutusData = toPlutusData(data);
2312
+ return plutusData.hash().toString();
2313
+ };
2314
+ var resolveNativeScriptAddress = (script, networkId = 0) => {
2315
+ const nativeScript = toNativeScript(script);
2316
+ const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
2317
+ hash: nativeScript.hash(),
2318
+ type: Cardano2.CredentialType.ScriptHash
2319
+ });
2320
+ return enterpriseAddress.toAddress().toBech32().toString();
2321
+ };
2322
+ var resolveNativeScriptHash = (script) => {
2323
+ return toNativeScript(script).hash().toString();
2324
+ };
2325
+ var resolvePaymentKeyHash = (bech325) => {
2326
+ try {
2327
+ const paymentKeyHash = [
2328
+ toBaseAddress(bech325)?.getPaymentCredential().hash,
2329
+ toEnterpriseAddress(bech325)?.getPaymentCredential().hash
2330
+ ].find((kh) => kh !== void 0);
2331
+ if (paymentKeyHash !== void 0) return paymentKeyHash.toString();
2332
+ throw new Error(
2333
+ `Couldn't resolve payment key hash from address: ${bech325}`
2334
+ );
2335
+ } catch (error) {
2336
+ throw new Error(
2337
+ `An error occurred during resolvePaymentKeyHash: ${error}.`
2338
+ );
2339
+ }
2340
+ };
2341
+ var resolvePlutusScriptAddress = (script, networkId = 0) => {
2342
+ const plutusScript = deserializePlutusScript(script.code, script.version);
2343
+ const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
2344
+ hash: plutusScript.hash(),
2345
+ type: Cardano2.CredentialType.ScriptHash
2346
+ });
2347
+ return enterpriseAddress.toAddress().toBech32().toString();
2348
+ };
2349
+ var resolvePlutusScriptHash = (bech325) => {
2350
+ try {
2351
+ const enterpriseAddress = toEnterpriseAddress(bech325);
2352
+ const scriptHash = enterpriseAddress?.getPaymentCredential().hash;
2353
+ if (scriptHash !== void 0) return scriptHash.toString();
2354
+ throw new Error(`Couldn't resolve script hash from address: ${bech325}`);
2355
+ } catch (error) {
2356
+ throw new Error(`An error occurred during resolveScriptHash: ${error}.`);
2357
+ }
2358
+ };
2359
+ var resolvePoolId = (hash) => {
2360
+ return PoolId.fromKeyHash(Ed25519KeyHashHex2(hash)).toString();
2361
+ };
2362
+ var resolvePrivateKey = (words) => {
2363
+ const buildBip32PrivateKey2 = (entropy2, password = "") => {
2364
+ return Bip32PrivateKey2.fromBip39Entropy(
2365
+ Buffer.from(toBytes4(entropy2)),
2366
+ fromUTF8(password)
2367
+ );
2368
+ };
2369
+ const entropy = mnemonicToEntropy(words.join(" "));
2370
+ const bip32PrivateKey = buildBip32PrivateKey2(entropy);
2371
+ const bytes = base323.encode(bip32PrivateKey.bytes());
2372
+ const bech32PrivateKey = bech323.encode("xprv", bytes, 1023);
2373
+ return bech32PrivateKey;
2374
+ };
2375
+ var resolveScriptRef = (script) => {
2376
+ return toScriptRef(script).toCbor().toString();
2377
+ };
2378
+ var resolveRewardAddress = (bech325) => {
2379
+ try {
2380
+ const address = toAddress(bech325);
2381
+ const baseAddress = toBaseAddress(bech325);
2382
+ const stakeKeyHash = baseAddress?.getStakeCredential().hash;
2383
+ if (stakeKeyHash !== void 0)
2384
+ return buildRewardAddress(address.getNetworkId(), stakeKeyHash).toAddress().toBech32().toString();
2385
+ throw new Error(`Couldn't resolve reward address from address: ${bech325}`);
2386
+ } catch (error) {
2387
+ throw new Error(`An error occurred during resolveRewardAddress: ${error}.`);
2388
+ }
2389
+ };
2390
+ var resolveStakeKeyHash = (bech325) => {
2391
+ try {
2392
+ const stakeKeyHash = [
2393
+ toBaseAddress(bech325)?.getStakeCredential().hash,
2394
+ toRewardAddress(bech325)?.getPaymentCredential().hash
2395
+ ].find((kh) => kh !== void 0);
2396
+ if (stakeKeyHash !== void 0) return stakeKeyHash.toString();
2397
+ throw new Error(`Couldn't resolve stake key hash from address: ${bech325}`);
2398
+ } catch (error) {
2399
+ throw new Error(`An error occurred during resolveStakeKeyHash: ${error}.`);
2400
+ }
2401
+ };
1806
2402
  var resolveTxHash = (txHex) => {
1807
2403
  const txBody = deserializeTx(txHex).body();
1808
- const hash = blake2b3(blake2b3.BYTES).update(hexToBytes(txBody.toCbor())).digest();
1809
- return Cardano2.TransactionId.fromHexBlob(HexBlob4.fromBytes(hash));
2404
+ const hash = blake2b5(blake2b5.BYTES).update(hexToBytes(txBody.toCbor())).digest();
2405
+ return Cardano2.TransactionId.fromHexBlob(HexBlob6.fromBytes(hash)).toString();
2406
+ };
2407
+ var resolveScriptHashDRepId = (scriptHash) => {
2408
+ return DRepID.cip129FromCredential({
2409
+ type: Cardano2.CredentialType.ScriptHash,
2410
+ hash: Hash28ByteBase162(scriptHash)
2411
+ }).toString();
2412
+ };
2413
+ var resolveEd25519KeyHash = (bech325) => {
2414
+ try {
2415
+ const keyHash = [
2416
+ toBaseAddress(bech325)?.getPaymentCredential().hash,
2417
+ toEnterpriseAddress(bech325)?.getPaymentCredential().hash
2418
+ ].find((kh) => kh !== void 0);
2419
+ if (keyHash !== void 0) return keyHash.toString();
2420
+ throw new Error(`Couldn't resolve key hash from address: ${bech325}`);
2421
+ } catch (error) {
2422
+ throw new Error(
2423
+ `An error occurred during resolveEd25519KeyHash: ${error}.`
2424
+ );
2425
+ }
1810
2426
  };
1811
2427
 
1812
2428
  // src/serializer/index.ts
1813
- import { Serialization as Serialization4, TxCBOR as TxCBOR2 } from "@cardano-sdk/core";
1814
- import { HexBlob as HexBlob6 } from "@cardano-sdk/util";
2429
+ import { Serialization as Serialization6 } from "@cardano-sdk/core";
2430
+ import { HexBlob as HexBlob8 } from "@cardano-sdk/util";
1815
2431
  import {
2432
+ Cbor,
2433
+ CborArray,
2434
+ CborBytes,
2435
+ CborString,
2436
+ CborTag,
2437
+ CborUInt
2438
+ } from "@harmoniclabs/cbor";
2439
+ import base324 from "base32-encoding";
2440
+ import { bech32 as bech324 } from "bech32";
2441
+ import {
2442
+ DEFAULT_PROTOCOL_PARAMETERS,
1816
2443
  DEFAULT_V1_COST_MODEL_LIST,
1817
- DEFAULT_V2_COST_MODEL_LIST
2444
+ DEFAULT_V2_COST_MODEL_LIST,
2445
+ DEFAULT_V3_COST_MODEL_LIST,
2446
+ fromUTF8 as fromUTF82,
2447
+ mnemonicToEntropy as mnemonicToEntropy2,
2448
+ toBytes as toBytes5
1818
2449
  } from "@meshsdk/common";
1819
2450
 
2451
+ // src/utils/certificate.ts
2452
+ import { Cardano as Cardano3, Serialization as Serialization4 } from "@cardano-sdk/core";
2453
+ var toCardanoCert = (cert) => {
2454
+ switch (cert.type) {
2455
+ case "RegisterPool": {
2456
+ let relays = [];
2457
+ for (const relay of cert.poolParams.relays) {
2458
+ switch (relay.type) {
2459
+ case "SingleHostAddr": {
2460
+ relays.push(
2461
+ Serialization4.Relay.newSingleHostAddr(
2462
+ new Serialization4.SingleHostAddr(
2463
+ relay.port,
2464
+ relay.IPV4,
2465
+ relay.IPV6
2466
+ )
2467
+ )
2468
+ );
2469
+ break;
2470
+ }
2471
+ case "SingleHostName": {
2472
+ relays.push(
2473
+ Serialization4.Relay.newSingleHostName(
2474
+ new Serialization4.SingleHostName(relay.domainName, relay.port)
2475
+ )
2476
+ );
2477
+ break;
2478
+ }
2479
+ case "MultiHostName": {
2480
+ relays.push(
2481
+ Serialization4.Relay.newMultiHostName(
2482
+ new Serialization4.MultiHostName(relay.domainName)
2483
+ )
2484
+ );
2485
+ break;
2486
+ }
2487
+ }
2488
+ }
2489
+ let poolOwners = Serialization4.CborSet.fromCore([], Serialization4.Hash.fromCore);
2490
+ let poolOwnersValues = [...poolOwners.values()];
2491
+ for (const poolOwner of cert.poolParams.owners) {
2492
+ poolOwnersValues.push(
2493
+ Serialization4.Hash.fromCore(Ed25519KeyHashHex2(poolOwner))
2494
+ );
2495
+ }
2496
+ poolOwners.setValues(poolOwnersValues);
2497
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2498
+ Cardano3.Address.fromBech32(cert.poolParams.rewardAddress)
2499
+ );
2500
+ if (rewardAddress === void 0) {
2501
+ throw new Error(
2502
+ "Error parsing reward address, it is expected to be in bech32 format"
2503
+ );
2504
+ }
2505
+ const metadata = cert.poolParams.metadata ? new Serialization4.PoolMetadata(
2506
+ cert.poolParams.metadata.URL,
2507
+ Crypto2.Hash32ByteBase16(cert.poolParams.metadata.hash)
2508
+ ) : void 0;
2509
+ return Certificate.newPoolRegistration(
2510
+ new Serialization4.PoolRegistration(
2511
+ new Serialization4.PoolParams(
2512
+ Ed25519KeyHashHex2(cert.poolParams.operator),
2513
+ Cardano3.VrfVkHex(cert.poolParams.vrfKeyHash),
2514
+ BigInt(cert.poolParams.pledge),
2515
+ BigInt(cert.poolParams.cost),
2516
+ new Serialization4.UnitInterval(
2517
+ BigInt(cert.poolParams.margin[0]),
2518
+ BigInt(cert.poolParams.margin[1])
2519
+ ),
2520
+ rewardAddress,
2521
+ poolOwners,
2522
+ relays,
2523
+ metadata
2524
+ )
2525
+ )
2526
+ );
2527
+ }
2528
+ case "RegisterStake": {
2529
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2530
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2531
+ );
2532
+ if (rewardAddress === void 0) {
2533
+ throw new Error(
2534
+ "Error parsing reward address, it is expected to be in bech32 format"
2535
+ );
2536
+ }
2537
+ return Certificate.newStakeRegistration(
2538
+ new Serialization4.StakeRegistration(
2539
+ rewardAddress.getPaymentCredential()
2540
+ )
2541
+ );
2542
+ }
2543
+ case "DelegateStake": {
2544
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2545
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2546
+ );
2547
+ if (rewardAddress === void 0) {
2548
+ throw new Error(
2549
+ "Error parsing reward address, it is expected to be in bech32 format"
2550
+ );
2551
+ }
2552
+ return Certificate.newStakeDelegation(
2553
+ new Serialization4.StakeDelegation(
2554
+ rewardAddress.getPaymentCredential(),
2555
+ Ed25519KeyHashHex2(cert.poolId)
2556
+ )
2557
+ );
2558
+ }
2559
+ case "DeregisterStake": {
2560
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2561
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2562
+ );
2563
+ if (rewardAddress === void 0) {
2564
+ throw new Error(
2565
+ "Error parsing reward address, it is expected to be in bech32 format"
2566
+ );
2567
+ }
2568
+ return Certificate.newStakeDeregistration(
2569
+ new Serialization4.StakeDeregistration(
2570
+ rewardAddress.getPaymentCredential()
2571
+ )
2572
+ );
2573
+ }
2574
+ case "RetirePool": {
2575
+ return Certificate.newPoolRetirement(
2576
+ new Serialization4.PoolRetirement(
2577
+ Ed25519KeyHashHex2(cert.poolId),
2578
+ Cardano3.EpochNo(cert.epoch)
2579
+ )
2580
+ );
2581
+ }
2582
+ case "VoteDelegation": {
2583
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2584
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2585
+ );
2586
+ if (rewardAddress === void 0) {
2587
+ throw new Error(
2588
+ "Error parsing reward address, it is expected to be in bech32 format"
2589
+ );
2590
+ }
2591
+ if (cert.drep.dRepId !== void 0) {
2592
+ return Certificate.newVoteDelegationCert(
2593
+ new Serialization4.VoteDelegation(
2594
+ rewardAddress.getPaymentCredential(),
2595
+ toDRep(cert.drep.dRepId)
2596
+ )
2597
+ );
2598
+ } else if (cert.drep.alwaysAbstain !== void 0) {
2599
+ return Certificate.newVoteDelegationCert(
2600
+ new Serialization4.VoteDelegation(
2601
+ rewardAddress.getPaymentCredential(),
2602
+ Serialization4.DRep.newAlwaysAbstain()
2603
+ )
2604
+ );
2605
+ } else if (cert.drep.alwaysNoConfidence !== void 0) {
2606
+ return Certificate.newVoteDelegationCert(
2607
+ new Serialization4.VoteDelegation(
2608
+ rewardAddress.getPaymentCredential(),
2609
+ Serialization4.DRep.newAlwaysNoConfidence()
2610
+ )
2611
+ );
2612
+ } else {
2613
+ throw new Error("Malformed DRep type");
2614
+ }
2615
+ }
2616
+ case "StakeAndVoteDelegation": {
2617
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2618
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2619
+ );
2620
+ if (rewardAddress === void 0) {
2621
+ throw new Error(
2622
+ "Error parsing reward address, it is expected to be in bech32 format"
2623
+ );
2624
+ }
2625
+ if (cert.drep.dRepId !== void 0) {
2626
+ return Certificate.newStakeVoteDelegationCert(
2627
+ new Serialization4.StakeVoteDelegation(
2628
+ rewardAddress.getPaymentCredential(),
2629
+ toDRep(cert.drep.dRepId),
2630
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2631
+ )
2632
+ );
2633
+ } else if (cert.drep.alwaysAbstain !== void 0) {
2634
+ return Certificate.newStakeVoteDelegationCert(
2635
+ new Serialization4.StakeVoteDelegation(
2636
+ rewardAddress.getPaymentCredential(),
2637
+ Serialization4.DRep.newAlwaysAbstain(),
2638
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2639
+ )
2640
+ );
2641
+ } else if (cert.drep.alwaysNoConfidence !== void 0) {
2642
+ return Certificate.newStakeVoteDelegationCert(
2643
+ new Serialization4.StakeVoteDelegation(
2644
+ rewardAddress.getPaymentCredential(),
2645
+ Serialization4.DRep.newAlwaysNoConfidence(),
2646
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2647
+ )
2648
+ );
2649
+ } else {
2650
+ throw new Error("Malformed DRep type");
2651
+ }
2652
+ }
2653
+ case "StakeRegistrationAndDelegation": {
2654
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2655
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2656
+ );
2657
+ if (rewardAddress === void 0) {
2658
+ throw new Error(
2659
+ "Error parsing reward address, it is expected to be in bech32 format"
2660
+ );
2661
+ }
2662
+ return Certificate.newStakeRegistrationDelegationCert(
2663
+ new Serialization4.StakeRegistrationDelegation(
2664
+ rewardAddress.getPaymentCredential(),
2665
+ BigInt(cert.coin),
2666
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2667
+ )
2668
+ );
2669
+ }
2670
+ case "VoteRegistrationAndDelegation": {
2671
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2672
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2673
+ );
2674
+ if (rewardAddress === void 0) {
2675
+ throw new Error(
2676
+ "Error parsing reward address, it is expected to be in bech32 format"
2677
+ );
2678
+ }
2679
+ if (cert.drep.dRepId !== void 0) {
2680
+ return Certificate.newVoteRegistrationDelegationCert(
2681
+ new Serialization4.VoteRegistrationDelegation(
2682
+ rewardAddress.getPaymentCredential(),
2683
+ BigInt(cert.coin),
2684
+ toDRep(cert.drep.dRepId)
2685
+ )
2686
+ );
2687
+ } else if (cert.drep.alwaysAbstain !== void 0) {
2688
+ return Certificate.newVoteRegistrationDelegationCert(
2689
+ new Serialization4.VoteRegistrationDelegation(
2690
+ rewardAddress.getPaymentCredential(),
2691
+ BigInt(cert.coin),
2692
+ Serialization4.DRep.newAlwaysAbstain()
2693
+ )
2694
+ );
2695
+ } else if (cert.drep.alwaysNoConfidence !== void 0) {
2696
+ return Certificate.newVoteRegistrationDelegationCert(
2697
+ new Serialization4.VoteRegistrationDelegation(
2698
+ rewardAddress.getPaymentCredential(),
2699
+ BigInt(cert.coin),
2700
+ Serialization4.DRep.newAlwaysNoConfidence()
2701
+ )
2702
+ );
2703
+ } else {
2704
+ throw new Error("Malformed DRep type");
2705
+ }
2706
+ }
2707
+ case "StakeVoteRegistrationAndDelegation": {
2708
+ const rewardAddress = Cardano3.RewardAddress.fromAddress(
2709
+ Cardano3.Address.fromBech32(cert.stakeKeyAddress)
2710
+ );
2711
+ if (rewardAddress === void 0) {
2712
+ throw new Error(
2713
+ "Error parsing reward address, it is expected to be in bech32 format"
2714
+ );
2715
+ }
2716
+ if (cert.drep.dRepId !== void 0) {
2717
+ return Certificate.newStakeVoteDelegationCert(
2718
+ new Serialization4.StakeVoteDelegation(
2719
+ rewardAddress.getPaymentCredential(),
2720
+ toDRep(cert.drep.dRepId),
2721
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2722
+ )
2723
+ );
2724
+ } else if (cert.drep.alwaysAbstain !== void 0) {
2725
+ return Certificate.newStakeVoteDelegationCert(
2726
+ new Serialization4.StakeVoteDelegation(
2727
+ rewardAddress.getPaymentCredential(),
2728
+ Serialization4.DRep.newAlwaysAbstain(),
2729
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2730
+ )
2731
+ );
2732
+ } else if (cert.drep.alwaysNoConfidence !== void 0) {
2733
+ return Certificate.newStakeVoteDelegationCert(
2734
+ new Serialization4.StakeVoteDelegation(
2735
+ rewardAddress.getPaymentCredential(),
2736
+ Serialization4.DRep.newAlwaysNoConfidence(),
2737
+ Ed25519KeyHashHex2(cert.poolKeyHash)
2738
+ )
2739
+ );
2740
+ } else {
2741
+ throw new Error("Malformed DRep type");
2742
+ }
2743
+ }
2744
+ case "CommitteeHotAuth": {
2745
+ const hotCred = Cardano3.Address.fromBech32(
2746
+ cert.committeeHotKeyAddress
2747
+ ).getProps().paymentPart;
2748
+ const coldCred = Cardano3.Address.fromBech32(
2749
+ cert.committeeColdKeyAddress
2750
+ ).getProps().paymentPart;
2751
+ if (!hotCred || !coldCred) {
2752
+ throw new Error("Malformed hot/cold credential");
2753
+ }
2754
+ return Certificate.newAuthCommitteeHotCert(
2755
+ new Serialization4.AuthCommitteeHot(coldCred, hotCred)
2756
+ );
2757
+ }
2758
+ case "CommitteeColdResign": {
2759
+ const coldCred = Cardano3.Address.fromBech32(
2760
+ cert.committeeColdKeyAddress
2761
+ ).getProps().paymentPart;
2762
+ if (!coldCred) {
2763
+ throw new Error("Malformed hot/cold credential");
2764
+ }
2765
+ let anchor = void 0;
2766
+ if (cert.anchor) {
2767
+ anchor = new Serialization4.Anchor(
2768
+ cert.anchor.anchorUrl,
2769
+ Hash32ByteBase162(cert.anchor.anchorDataHash)
2770
+ );
2771
+ }
2772
+ return Certificate.newResignCommitteeColdCert(
2773
+ new Serialization4.ResignCommitteeCold(coldCred, anchor)
2774
+ );
2775
+ }
2776
+ case "DRepRegistration": {
2777
+ let anchor = void 0;
2778
+ if (cert.anchor) {
2779
+ anchor = new Serialization4.Anchor(
2780
+ cert.anchor.anchorUrl,
2781
+ Hash32ByteBase162(cert.anchor.anchorDataHash)
2782
+ );
2783
+ }
2784
+ const coreDRep = toDRep(cert.drepId).toCore();
2785
+ if (Cardano3.isDRepCredential(coreDRep)) {
2786
+ return Certificate.newRegisterDelegateRepresentativeCert(
2787
+ new Serialization4.RegisterDelegateRepresentative(
2788
+ coreDRep,
2789
+ BigInt(cert.coin),
2790
+ anchor
2791
+ )
2792
+ );
2793
+ } else {
2794
+ throw new Error("DRepId must be a Credential");
2795
+ }
2796
+ }
2797
+ case "DRepDeregistration": {
2798
+ const coreDRep = toDRep(cert.drepId).toCore();
2799
+ if (Cardano3.isDRepCredential(coreDRep)) {
2800
+ return Certificate.newUnregisterDelegateRepresentativeCert(
2801
+ new Serialization4.UnregisterDelegateRepresentative(
2802
+ coreDRep,
2803
+ BigInt(cert.coin)
2804
+ )
2805
+ );
2806
+ } else {
2807
+ throw new Error("DRepId must be a Credential");
2808
+ }
2809
+ }
2810
+ case "DRepUpdate": {
2811
+ let anchor = void 0;
2812
+ if (cert.anchor) {
2813
+ anchor = new Serialization4.Anchor(
2814
+ cert.anchor.anchorUrl,
2815
+ Hash32ByteBase162(cert.anchor.anchorDataHash)
2816
+ );
2817
+ }
2818
+ const coreDRep = toDRep(cert.drepId).toCore();
2819
+ if (Cardano3.isDRepCredential(coreDRep)) {
2820
+ return Certificate.newUpdateDelegateRepresentativeCert(
2821
+ new Serialization4.UpdateDelegateRepresentative(coreDRep, anchor)
2822
+ );
2823
+ } else {
2824
+ throw new Error("DRepId must be a Credential");
2825
+ }
2826
+ }
2827
+ }
2828
+ };
2829
+
2830
+ // src/utils/fee.ts
2831
+ var calculateFees = (minFeeA, minFeeB, minFeeRefScriptCostPerByte, priceMem, priceStep, tx, refScriptSize) => {
2832
+ let fee = minFeeB + tx.toCbor().length / 2 * minFeeA;
2833
+ const tierSize = 25600;
2834
+ let currentRefScriptSize = refScriptSize;
2835
+ let multiplier = 1.2;
2836
+ while (currentRefScriptSize >= tierSize) {
2837
+ fee += tierSize * multiplier * minFeeRefScriptCostPerByte;
2838
+ currentRefScriptSize -= tierSize;
2839
+ multiplier *= multiplier;
2840
+ }
2841
+ if (currentRefScriptSize > 0) {
2842
+ fee += currentRefScriptSize * multiplier * minFeeRefScriptCostPerByte;
2843
+ }
2844
+ let scriptFee = BigInt(0);
2845
+ let priceMemNumerator = priceMem;
2846
+ let priceMemDenominator = 1;
2847
+ while (priceMemNumerator % 1) {
2848
+ priceMemNumerator *= 10;
2849
+ priceMemDenominator *= 10;
2850
+ }
2851
+ let priceStepNumerator = priceStep;
2852
+ let priceStepDenominator = 1;
2853
+ while (priceStepNumerator % 1) {
2854
+ priceStepNumerator *= 10;
2855
+ priceStepDenominator *= 10;
2856
+ }
2857
+ if (tx.witnessSet().redeemers()) {
2858
+ for (const redeemer of tx.witnessSet().redeemers().values()) {
2859
+ scriptFee += redeemer.exUnits().mem() * BigInt(priceMemNumerator.toString()) / BigInt(priceMemDenominator.toString()) + BigInt(1);
2860
+ scriptFee += redeemer.exUnits().steps() * BigInt(priceStepNumerator.toString()) / BigInt(priceStepDenominator.toString()) + BigInt(1);
2861
+ }
2862
+ }
2863
+ return BigInt(fee) + scriptFee;
2864
+ };
2865
+
2866
+ // src/utils/metadata.ts
2867
+ var toCardanoMetadataMap = (metadata) => {
2868
+ let cardanoMetadataMap = /* @__PURE__ */ new Map();
2869
+ metadata.forEach((val, key) => {
2870
+ cardanoMetadataMap.set(key, toCardanoMetadatum(val));
2871
+ });
2872
+ return cardanoMetadataMap;
2873
+ };
2874
+ var toCardanoMetadatum = (metadatum) => {
2875
+ if (typeof metadatum === "number") {
2876
+ return TransactionMetadatum.newInteger(BigInt(metadatum));
2877
+ } else if (typeof metadatum === "string") {
2878
+ return TransactionMetadatum.newText(metadatum);
2879
+ } else if (typeof metadatum === "bigint") {
2880
+ return TransactionMetadatum.newInteger(metadatum);
2881
+ } else if (metadatum instanceof Uint8Array) {
2882
+ return TransactionMetadatum.newBytes(metadatum);
2883
+ } else if (metadatum instanceof Map) {
2884
+ const result = new MetadatumMap();
2885
+ metadatum.forEach((value, key) => {
2886
+ result.insert(toCardanoMetadatum(key), toCardanoMetadatum(value));
2887
+ });
2888
+ return TransactionMetadatum.newMap(result);
2889
+ } else if (Array.isArray(metadatum)) {
2890
+ const result = new MetadatumList();
2891
+ metadatum.forEach((val) => {
2892
+ result.add(toCardanoMetadatum(val));
2893
+ });
2894
+ return TransactionMetadatum.newList(result);
2895
+ } else {
2896
+ throw new Error("metadatumToObj: Unsupported Metadatum type");
2897
+ }
2898
+ };
2899
+
1820
2900
  // src/utils/script-data-hash.ts
1821
- import { Serialization as Serialization3 } from "@cardano-sdk/core";
1822
- import * as Crypto2 from "@cardano-sdk/crypto";
2901
+ import { Serialization as Serialization5 } from "@cardano-sdk/core";
2902
+ import * as Crypto3 from "@cardano-sdk/crypto";
1823
2903
  import { Hash32ByteBase16 as Hash32ByteBase163 } from "@cardano-sdk/crypto";
1824
- import { HexBlob as HexBlob5 } from "@cardano-sdk/util";
2904
+ import { HexBlob as HexBlob7 } from "@cardano-sdk/util";
1825
2905
  var CBOR_EMPTY_LIST = new Uint8Array([128]);
1826
2906
  var CBOR_EMPTY_MAP = new Uint8Array([160]);
1827
2907
  var getCborEncodedArray = (items) => {
1828
- const writer = new Serialization3.CborWriter();
2908
+ const writer = new Serialization5.CborWriter();
1829
2909
  writer.writeStartArray(items.length);
1830
2910
  for (const item of items) {
1831
2911
  writer.writeEncodedValue(Buffer.from(item.toCbor(), "hex"));
@@ -1833,7 +2913,7 @@ var getCborEncodedArray = (items) => {
1833
2913
  return writer.encode();
1834
2914
  };
1835
2915
  var hashScriptData = (costModels, redemeers, datums) => {
1836
- const writer = new Serialization3.CborWriter();
2916
+ const writer = new Serialization5.CborWriter();
1837
2917
  if (datums && datums.length > 0 && (!redemeers || redemeers.length === 0)) {
1838
2918
  writer.writeEncodedValue(CBOR_EMPTY_LIST);
1839
2919
  writer.writeEncodedValue(getCborEncodedArray(datums));
@@ -1848,8 +2928,8 @@ var hashScriptData = (costModels, redemeers, datums) => {
1848
2928
  );
1849
2929
  }
1850
2930
  return Hash32ByteBase163.fromHexBlob(
1851
- HexBlob5.fromBytes(
1852
- Crypto2.blake2b(Crypto2.blake2b.BYTES).update(writer.encode()).digest()
2931
+ HexBlob7.fromBytes(
2932
+ Crypto3.blake2b(Crypto3.blake2b.BYTES).update(writer.encode()).digest()
1853
2933
  )
1854
2934
  );
1855
2935
  };
@@ -1857,148 +2937,253 @@ var hashScriptData = (costModels, redemeers, datums) => {
1857
2937
  // src/serializer/index.ts
1858
2938
  var CardanoSDKSerializer = class {
1859
2939
  verbose;
1860
- txBody;
1861
- txWitnessSet;
1862
- utxoContext = /* @__PURE__ */ new Map();
1863
- redeemerContext = /* @__PURE__ */ new Map();
1864
- scriptsProvided = /* @__PURE__ */ new Set();
1865
- datumsProvided = /* @__PURE__ */ new Set();
1866
- usedLanguages = {
1867
- [0]: false,
1868
- [1]: false,
1869
- [2]: false
1870
- };
1871
- constructor(verbose = false) {
2940
+ protocolParams;
2941
+ constructor(protocolParams, verbose = false) {
2942
+ this.protocolParams = protocolParams || DEFAULT_PROTOCOL_PARAMETERS;
1872
2943
  this.verbose = verbose;
1873
- this.txBody = new TransactionBody(
1874
- Serialization4.CborSet.fromCore([], TransactionInput.fromCore),
1875
- [],
1876
- BigInt(0),
1877
- void 0
1878
- );
1879
- this.txWitnessSet = new TransactionWitnessSet();
1880
2944
  }
1881
2945
  serializeRewardAddress(stakeKeyHash, isScriptHash, network_id) {
1882
- throw new Error("Method not implemented.");
2946
+ return RewardAddress.fromCredentials(network_id ?? 0, {
2947
+ type: isScriptHash ? CredentialType.ScriptHash : CredentialType.KeyHash,
2948
+ hash: Hash28ByteBase162(stakeKeyHash)
2949
+ }).toAddress().toBech32();
1883
2950
  }
1884
2951
  serializePoolId(hash) {
1885
- throw new Error("Method not implemented.");
2952
+ return PoolId.fromKeyHash(Ed25519KeyHashHex2(hash)).toString();
1886
2953
  }
1887
2954
  serializeAddress(address, networkId) {
1888
- throw new Error("Method not implemented.");
2955
+ let paymentCred = void 0;
2956
+ let stakeCred;
2957
+ if (address.pubKeyHash && address.pubKeyHash !== "") {
2958
+ paymentCred = {
2959
+ type: CredentialType.KeyHash,
2960
+ hash: Hash28ByteBase162(address.pubKeyHash)
2961
+ };
2962
+ } else if (address.scriptHash && address.scriptHash !== "") {
2963
+ paymentCred = {
2964
+ type: CredentialType.ScriptHash,
2965
+ hash: Hash28ByteBase162(address.scriptHash)
2966
+ };
2967
+ }
2968
+ if (address.stakeCredentialHash && address.stakeCredentialHash !== "") {
2969
+ stakeCred = {
2970
+ type: CredentialType.KeyHash,
2971
+ hash: Hash28ByteBase162(address.stakeCredentialHash)
2972
+ };
2973
+ } else if (address.stakeScriptCredentialHash) {
2974
+ stakeCred = {
2975
+ type: CredentialType.ScriptHash,
2976
+ hash: Hash28ByteBase162(address.stakeScriptCredentialHash)
2977
+ };
2978
+ }
2979
+ let type = AddressType.BasePaymentKeyStakeKey;
2980
+ if (paymentCred && stakeCred) {
2981
+ if (paymentCred.type === CredentialType.KeyHash && stakeCred.type === CredentialType.KeyHash) {
2982
+ type = AddressType.BasePaymentKeyStakeKey;
2983
+ } else if (paymentCred.type === CredentialType.KeyHash && stakeCred.type === CredentialType.ScriptHash) {
2984
+ type = AddressType.BasePaymentKeyStakeScript;
2985
+ } else if (paymentCred.type === CredentialType.ScriptHash && stakeCred.type === CredentialType.KeyHash) {
2986
+ type = AddressType.BasePaymentScriptStakeKey;
2987
+ } else if (paymentCred.type === CredentialType.ScriptHash && stakeCred.type === CredentialType.ScriptHash) {
2988
+ type = AddressType.BasePaymentScriptStakeScript;
2989
+ }
2990
+ } else if (paymentCred) {
2991
+ if (paymentCred.type === CredentialType.KeyHash) {
2992
+ type = AddressType.EnterpriseKey;
2993
+ } else if (paymentCred.type === CredentialType.ScriptHash) {
2994
+ type = AddressType.EnterpriseScript;
2995
+ }
2996
+ } else if (stakeCred) {
2997
+ if (stakeCred.type === CredentialType.KeyHash) {
2998
+ type = AddressType.RewardKey;
2999
+ } else if (stakeCred.type === CredentialType.ScriptHash) {
3000
+ type = AddressType.RewardScript;
3001
+ }
3002
+ }
3003
+ return new Address({
3004
+ type,
3005
+ networkId: networkId ?? 0,
3006
+ paymentPart: paymentCred,
3007
+ delegationPart: stakeCred
3008
+ }).toBech32();
1889
3009
  }
1890
3010
  serializeData(data) {
1891
- throw new Error("Method not implemented.");
3011
+ const plutusData = fromBuilderToPlutusData(data);
3012
+ return plutusData.toCbor().toString();
1892
3013
  }
1893
3014
  deserializer = {
1894
3015
  key: {
1895
- deserializeAddress: function(bech32) {
1896
- throw new Error("Function not implemented.");
3016
+ deserializeAddress: function(bech325) {
3017
+ const address = Address.fromBech32(bech325);
3018
+ const addressProps = address.getProps();
3019
+ return {
3020
+ pubKeyHash: addressProps.paymentPart?.type === CredentialType.KeyHash ? addressProps.paymentPart?.hash ?? "" : "",
3021
+ scriptHash: addressProps.paymentPart?.type === CredentialType.ScriptHash ? addressProps.paymentPart?.hash ?? "" : "",
3022
+ stakeCredentialHash: addressProps.delegationPart?.type === CredentialType.KeyHash ? addressProps.paymentPart?.hash ?? "" : "",
3023
+ stakeScriptCredentialHash: addressProps.delegationPart?.type === CredentialType.ScriptHash ? addressProps.paymentPart?.hash ?? "" : ""
3024
+ };
1897
3025
  }
1898
3026
  },
1899
3027
  script: {
1900
3028
  deserializeNativeScript: function(script) {
1901
- throw new Error("Function not implemented.");
3029
+ const cardanoNativeScript = toNativeScript(script);
3030
+ return {
3031
+ scriptHash: cardanoNativeScript.hash().toString(),
3032
+ scriptCbor: cardanoNativeScript.toCbor().toString()
3033
+ };
1902
3034
  },
1903
3035
  deserializePlutusScript: function(script) {
1904
- throw new Error("Function not implemented.");
3036
+ let cardanoPlutusScript;
3037
+ switch (script.version) {
3038
+ case "V1": {
3039
+ cardanoPlutusScript = new PlutusV1Script(HexBlob8(script.code));
3040
+ break;
3041
+ }
3042
+ case "V2": {
3043
+ cardanoPlutusScript = new PlutusV2Script(HexBlob8(script.code));
3044
+ break;
3045
+ }
3046
+ case "V3": {
3047
+ cardanoPlutusScript = new PlutusV3Script(HexBlob8(script.code));
3048
+ break;
3049
+ }
3050
+ }
3051
+ return {
3052
+ scriptHash: cardanoPlutusScript.hash().toString(),
3053
+ scriptCbor: cardanoPlutusScript.toCbor().toString()
3054
+ };
1905
3055
  }
1906
3056
  },
1907
3057
  cert: {
1908
3058
  deserializePoolId: function(poolId) {
1909
- throw new Error("Function not implemented.");
3059
+ const cardanoPoolId = PoolId(poolId);
3060
+ return PoolId.toKeyHash(cardanoPoolId).toString();
1910
3061
  }
1911
3062
  }
1912
3063
  };
1913
3064
  resolver = {
1914
3065
  keys: {
1915
- // resolvePaymentKeyHash: function (bech32: string): string {
1916
- // const cardanoAddress = toAddress(bech32);
1917
- // return cardanoAddress.asEnterprise()?.getPaymentCredential().type ===
1918
- // CredentialType.KeyHash
1919
- // ? cardanoAddress.asEnterprise()!.getPaymentCredential().hash
1920
- // : "";
1921
- // },
1922
- // resolvePlutusScriptHash: function (bech32: string): string {
1923
- // const cardanoAddress = toAddress(bech32);
1924
- // return cardanoAddress.asEnterprise()?.getPaymentCredential().type ===
1925
- // CredentialType.ScriptHash
1926
- // ? cardanoAddress.asEnterprise()!.getPaymentCredential().hash
1927
- // : "";
1928
- // },
1929
- resolveStakeKeyHash: function(bech32) {
1930
- const cardanoAddress = toAddress(bech32);
3066
+ resolveStakeKeyHash: function(bech325) {
3067
+ const cardanoAddress = toAddress(bech325);
1931
3068
  return cardanoAddress.asReward()?.getPaymentCredential().type === CredentialType.KeyHash ? cardanoAddress.asReward().getPaymentCredential().hash : "";
1932
3069
  },
1933
- // resolveStakeScriptHash(bech32: string): string {
1934
- // const cardanoAddress = toAddress(bech32);
1935
- // return cardanoAddress.asReward()?.getPaymentCredential().type ===
1936
- // CredentialType.ScriptHash
1937
- // ? cardanoAddress.asReward()!.getPaymentCredential().hash
1938
- // : "";
1939
- // },
1940
3070
  resolvePrivateKey: function(words) {
1941
- throw new Error("Function not implemented.");
3071
+ const buildBip32PrivateKey2 = (entropy2, password = "") => {
3072
+ return Bip32PrivateKey2.fromBip39Entropy(
3073
+ Buffer.from(toBytes5(entropy2)),
3074
+ fromUTF82(password)
3075
+ );
3076
+ };
3077
+ const entropy = mnemonicToEntropy2(words.join(" "));
3078
+ const bip32PrivateKey = buildBip32PrivateKey2(entropy);
3079
+ const bytes = base324.encode(bip32PrivateKey.bytes());
3080
+ const bech32PrivateKey = bech324.encode("xprv", bytes, 1023);
3081
+ return bech32PrivateKey;
1942
3082
  },
1943
- resolveRewardAddress: function(bech32) {
1944
- throw new Error("Function not implemented.");
3083
+ resolveRewardAddress: function(bech325) {
3084
+ const cardanoAddress = toAddress(bech325);
3085
+ const addressProps = cardanoAddress.getProps();
3086
+ if (!addressProps.delegationPart) {
3087
+ return "";
3088
+ }
3089
+ return RewardAddress.fromCredentials(
3090
+ cardanoAddress.getNetworkId(),
3091
+ addressProps.delegationPart
3092
+ ).toAddress().toBech32() ?? "";
1945
3093
  },
1946
- resolveEd25519KeyHash: function(bech32) {
1947
- throw new Error("Function not implemented.");
3094
+ resolveEd25519KeyHash: function(bech325) {
3095
+ const cardanoAddress = toAddress(bech325);
3096
+ const addressProps = cardanoAddress.getProps();
3097
+ if (!addressProps.paymentPart) {
3098
+ return "";
3099
+ }
3100
+ return addressProps.paymentPart.hash.toString();
1948
3101
  }
1949
3102
  },
1950
3103
  tx: {
1951
3104
  resolveTxHash: function(txHex) {
1952
- return Transaction.fromCbor(TxCBOR2(txHex)).getId();
3105
+ return Transaction.fromCbor(Serialization6.TxCBOR(txHex)).getId();
1953
3106
  }
1954
3107
  },
1955
3108
  data: {
1956
3109
  resolveDataHash: function(data) {
1957
- throw new Error("Function not implemented.");
3110
+ return fromBuilderToPlutusData({ type: "Mesh", content: data }).hash();
1958
3111
  }
1959
3112
  },
1960
3113
  script: {
1961
- // resolveNativeScript: function (script: CommonNativeScript): string {
1962
- // return toNativeScript(script).toCbor();
1963
- // },
1964
3114
  resolveScriptRef: function(script) {
1965
- throw new Error("Function not implemented.");
3115
+ if ("code" in script) {
3116
+ let versionByte;
3117
+ switch (script.version) {
3118
+ case "V1": {
3119
+ versionByte = 1;
3120
+ break;
3121
+ }
3122
+ case "V2": {
3123
+ versionByte = 2;
3124
+ break;
3125
+ }
3126
+ case "V3": {
3127
+ versionByte = 3;
3128
+ break;
3129
+ }
3130
+ }
3131
+ let taggedScript = new CborTag(
3132
+ 24,
3133
+ Cbor.parse(
3134
+ CborString.fromCborObj(
3135
+ new CborBytes(
3136
+ Cbor.encode(
3137
+ new CborArray([
3138
+ new CborUInt(versionByte),
3139
+ new CborString(script.code).toCborObj()
3140
+ ])
3141
+ ).toBuffer()
3142
+ )
3143
+ )
3144
+ )
3145
+ );
3146
+ return Cbor.encode(taggedScript).toString();
3147
+ } else {
3148
+ const nativeScript = toNativeScript(script);
3149
+ let taggedScript = new CborTag(
3150
+ 24,
3151
+ Cbor.parse(
3152
+ CborString.fromCborObj(
3153
+ new CborBytes(
3154
+ Cbor.encode(
3155
+ new CborArray([
3156
+ new CborUInt(0),
3157
+ new CborString(nativeScript.toCbor()).toCborObj()
3158
+ ])
3159
+ ).toBuffer()
3160
+ )
3161
+ )
3162
+ )
3163
+ );
3164
+ return Cbor.encode(taggedScript).toString();
3165
+ }
1966
3166
  }
1967
3167
  }
1968
3168
  };
1969
3169
  serializeTxBody = (txBuilderBody, protocolParams) => {
1970
- const {
1971
- inputs,
1972
- outputs,
1973
- collaterals,
1974
- referenceInputs,
1975
- mints,
1976
- changeAddress,
1977
- // certificates,
1978
- validityRange,
1979
- requiredSignatures
1980
- // metadata,
1981
- } = txBuilderBody;
1982
- mints.sort((a, b) => a.policyId.localeCompare(b.policyId));
1983
- inputs.sort((a, b) => {
1984
- if (a.txIn.txHash === b.txIn.txHash) {
1985
- return a.txIn.txIndex - b.txIn.txIndex;
1986
- } else {
1987
- return a.txIn.txHash.localeCompare(b.txIn.txHash);
1988
- }
1989
- });
1990
- this.addAllInputs(inputs);
1991
- this.addAllOutputs(outputs);
1992
- this.addAllMints(mints);
1993
- this.addAllCollateralInputs(collaterals);
1994
- this.addAllReferenceInputs(referenceInputs);
1995
- this.setValidityInterval(validityRange);
1996
- this.buildWitnessSet();
1997
- this.balanceTx(changeAddress, requiredSignatures.length, protocolParams);
1998
- return new Transaction(this.txBody, this.txWitnessSet).toCbor();
3170
+ if (this.verbose) {
3171
+ console.log(
3172
+ "txBodyJson",
3173
+ JSON.stringify(txBuilderBody, (key, val) => {
3174
+ if (key === "extraInputs") return void 0;
3175
+ if (key === "selectionConfig") return void 0;
3176
+ return val;
3177
+ })
3178
+ );
3179
+ }
3180
+ const serializerCore = new CardanoSDKSerializerCore(
3181
+ protocolParams ?? this.protocolParams
3182
+ );
3183
+ return serializerCore.coreSerializeTxBody(txBuilderBody);
1999
3184
  };
2000
3185
  addSigningKeys = (txHex, signingKeys) => {
2001
- let cardanoTx = Transaction.fromCbor(TxCBOR2(txHex));
3186
+ let cardanoTx = Transaction.fromCbor(Serialization6.TxCBOR(txHex));
2002
3187
  let currentWitnessSet = cardanoTx.witnessSet();
2003
3188
  let currentWitnessSetVkeys = currentWitnessSet.vkeys();
2004
3189
  let currentWitnessSetVkeysValues = currentWitnessSetVkeys ? [...currentWitnessSetVkeys.values()] : [];
@@ -2025,7 +3210,7 @@ var CardanoSDKSerializer = class {
2025
3210
  }
2026
3211
  }
2027
3212
  currentWitnessSet.setVkeys(
2028
- Serialization4.CborSet.fromCore(
3213
+ Serialization6.CborSet.fromCore(
2029
3214
  currentWitnessSetVkeysValues.map((vkw) => vkw.toCore()),
2030
3215
  VkeyWitness.fromCore
2031
3216
  )
@@ -2033,6 +3218,103 @@ var CardanoSDKSerializer = class {
2033
3218
  cardanoTx.setWitnessSet(currentWitnessSet);
2034
3219
  return cardanoTx.toCbor();
2035
3220
  };
3221
+ };
3222
+ var CardanoSDKSerializerCore = class {
3223
+ txBody;
3224
+ txWitnessSet;
3225
+ txAuxilliaryData;
3226
+ utxoContext = /* @__PURE__ */ new Map();
3227
+ mintRedeemers = /* @__PURE__ */ new Map();
3228
+ scriptsProvided = /* @__PURE__ */ new Set();
3229
+ datumsProvided = /* @__PURE__ */ new Set();
3230
+ usedLanguages = {
3231
+ [0]: false,
3232
+ [1]: false,
3233
+ [2]: false
3234
+ };
3235
+ protocolParams;
3236
+ refScriptSize;
3237
+ constructor(protocolParams) {
3238
+ this.protocolParams = protocolParams || DEFAULT_PROTOCOL_PARAMETERS;
3239
+ this.txBody = new TransactionBody(
3240
+ Serialization6.CborSet.fromCore([], TransactionInput.fromCore),
3241
+ [],
3242
+ BigInt(0),
3243
+ void 0
3244
+ );
3245
+ this.refScriptSize = 0;
3246
+ this.txWitnessSet = new TransactionWitnessSet();
3247
+ this.txAuxilliaryData = new AuxilliaryData();
3248
+ }
3249
+ coreSerializeTxBody = (txBuilderBody) => {
3250
+ const {
3251
+ inputs,
3252
+ outputs,
3253
+ collaterals,
3254
+ requiredSignatures,
3255
+ referenceInputs,
3256
+ mints,
3257
+ changeAddress,
3258
+ metadata,
3259
+ validityRange,
3260
+ certificates,
3261
+ withdrawals
3262
+ } = txBuilderBody;
3263
+ this.addAllInputs(inputs);
3264
+ this.addAllOutputs(this.sanitizeOutputs(outputs));
3265
+ this.addAllMints(mints);
3266
+ this.addAllCerts(certificates);
3267
+ this.addAllWithdrawals(withdrawals);
3268
+ this.addAllCollateralInputs(collaterals);
3269
+ this.addAllReferenceInputs(referenceInputs);
3270
+ this.removeInputRefInputOverlap();
3271
+ this.setValidityInterval(validityRange);
3272
+ this.addAllRequiredSignatures(requiredSignatures);
3273
+ if (metadata.size > 0) {
3274
+ this.addMetadata(metadata);
3275
+ }
3276
+ this.buildWitnessSet();
3277
+ this.balanceTx(changeAddress);
3278
+ return new Transaction(
3279
+ this.txBody,
3280
+ this.txWitnessSet,
3281
+ this.txAuxilliaryData
3282
+ ).toCbor();
3283
+ };
3284
+ sanitizeOutputs = (outputs) => {
3285
+ for (let i = 0; i < outputs.length; i++) {
3286
+ let currentOutput = outputs[i];
3287
+ let lovelaceFound = false;
3288
+ for (let j = 0; j < currentOutput.amount.length; j++) {
3289
+ let outputAmount = currentOutput.amount[j];
3290
+ if (outputAmount?.unit == "" || outputAmount?.unit == "lovelace") {
3291
+ lovelaceFound = true;
3292
+ if (outputAmount?.quantity == "0" || outputAmount?.quantity == "") {
3293
+ outputAmount.unit = "lovelace";
3294
+ outputAmount.quantity = "10000000";
3295
+ let dummyCardanoOutput = this.toCardanoOutput(
3296
+ currentOutput
3297
+ );
3298
+ let minUtxoValue = (160 + dummyCardanoOutput.toCbor().length / 2 + 1) * this.protocolParams.coinsPerUtxoSize;
3299
+ outputAmount.quantity = minUtxoValue.toString();
3300
+ }
3301
+ }
3302
+ if (!lovelaceFound) {
3303
+ let currentAmount = {
3304
+ unit: "lovelace",
3305
+ quantity: "10000000"
3306
+ };
3307
+ currentOutput.amount.push(currentAmount);
3308
+ let dummyCardanoOutput = this.toCardanoOutput(
3309
+ currentOutput
3310
+ );
3311
+ let minUtxoValue = (160 + dummyCardanoOutput.toCbor().length / 2 + 1) * this.protocolParams.coinsPerUtxoSize;
3312
+ currentAmount.quantity = minUtxoValue.toString();
3313
+ }
3314
+ }
3315
+ }
3316
+ return outputs;
3317
+ };
2036
3318
  addAllInputs = (inputs) => {
2037
3319
  for (let i = 0; i < inputs.length; i += 1) {
2038
3320
  const currentTxIn = inputs[i];
@@ -2043,7 +3325,8 @@ var CardanoSDKSerializer = class {
2043
3325
  break;
2044
3326
  case "Script":
2045
3327
  this.addScriptTxIn(
2046
- currentTxIn
3328
+ currentTxIn,
3329
+ i
2047
3330
  );
2048
3331
  break;
2049
3332
  case "SimpleScript":
@@ -2068,13 +3351,13 @@ var CardanoSDKSerializer = class {
2068
3351
  txInputsList.push(cardanoTxIn);
2069
3352
  inputs.setValues(txInputsList);
2070
3353
  const cardanoTxOut = new TransactionOutput(
2071
- Address.fromBech32(currentTxIn.txIn.address),
3354
+ toCardanoAddress(currentTxIn.txIn.address),
2072
3355
  toValue(currentTxIn.txIn.amount)
2073
3356
  );
2074
3357
  this.utxoContext.set(cardanoTxIn, cardanoTxOut);
2075
3358
  this.txBody.setInputs(inputs);
2076
3359
  };
2077
- addScriptTxIn = (currentTxIn) => {
3360
+ addScriptTxIn = (currentTxIn, index) => {
2078
3361
  this.addTxIn({
2079
3362
  type: "PubKey",
2080
3363
  txIn: currentTxIn.txIn
@@ -2089,74 +3372,16 @@ var CardanoSDKSerializer = class {
2089
3372
  throw new Error("A script input had no redeemer");
2090
3373
  }
2091
3374
  if (currentTxIn.scriptTxIn.scriptSource.type === "Provided") {
2092
- switch (currentTxIn.scriptTxIn.scriptSource.script.version) {
2093
- case "V1": {
2094
- this.scriptsProvided.add(
2095
- Script.newPlutusV1Script(
2096
- PlutusV1Script.fromCbor(
2097
- HexBlob6(currentTxIn.scriptTxIn.scriptSource.script.code)
2098
- )
2099
- )
2100
- );
2101
- this.usedLanguages[PlutusLanguageVersion.V1] = true;
2102
- break;
2103
- }
2104
- case "V2": {
2105
- this.scriptsProvided.add(
2106
- Script.newPlutusV2Script(
2107
- PlutusV2Script.fromCbor(
2108
- HexBlob6(currentTxIn.scriptTxIn.scriptSource.script.code)
2109
- )
2110
- )
2111
- );
2112
- this.usedLanguages[PlutusLanguageVersion.V2] = true;
2113
- break;
2114
- }
2115
- case "V3": {
2116
- this.scriptsProvided.add(
2117
- Script.newPlutusV3Script(
2118
- PlutusV3Script.fromCbor(
2119
- HexBlob6(currentTxIn.scriptTxIn.scriptSource.script.code)
2120
- )
2121
- )
2122
- );
2123
- this.usedLanguages[PlutusLanguageVersion.V3] = true;
2124
- break;
2125
- }
2126
- }
3375
+ this.addProvidedPlutusScript(currentTxIn.scriptTxIn.scriptSource.script);
2127
3376
  } else if (currentTxIn.scriptTxIn.scriptSource.type === "Inline") {
2128
- let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2129
- let referenceInputsList = [...referenceInputs.values()];
2130
- referenceInputsList.push(
2131
- new TransactionInput(
2132
- TransactionId(currentTxIn.scriptTxIn.scriptSource.txHash),
2133
- BigInt(currentTxIn.scriptTxIn.scriptSource.txIndex)
2134
- )
2135
- );
2136
- referenceInputs.setValues(referenceInputsList);
2137
- this.txBody.setReferenceInputs(referenceInputs);
2138
- switch (currentTxIn.scriptTxIn.scriptSource.version) {
2139
- case "V1": {
2140
- this.usedLanguages[PlutusLanguageVersion.V1] = true;
2141
- break;
2142
- }
2143
- case "V2": {
2144
- this.usedLanguages[PlutusLanguageVersion.V2] = true;
2145
- break;
2146
- }
2147
- case "V3": {
2148
- this.usedLanguages[PlutusLanguageVersion.V3] = true;
2149
- break;
2150
- }
2151
- }
3377
+ this.addScriptRef(currentTxIn.scriptTxIn.scriptSource);
2152
3378
  }
2153
3379
  if (currentTxIn.scriptTxIn.datumSource.type === "Provided") {
2154
3380
  this.datumsProvided.add(
2155
- toPlutusData(currentTxIn.scriptTxIn.datumSource.data.content)
2156
- // TODO: handle json / raw datum
3381
+ fromBuilderToPlutusData(currentTxIn.scriptTxIn.datumSource.data)
2157
3382
  );
2158
3383
  } else if (currentTxIn.scriptTxIn.datumSource.type === "Inline") {
2159
- let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
3384
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization6.CborSet.fromCore([], TransactionInput.fromCore);
2160
3385
  let referenceInputsList = [...referenceInputs.values()];
2161
3386
  referenceInputsList.push(
2162
3387
  new TransactionInput(
@@ -2167,21 +3392,19 @@ var CardanoSDKSerializer = class {
2167
3392
  referenceInputs.setValues(referenceInputsList);
2168
3393
  this.txBody.setReferenceInputs(referenceInputs);
2169
3394
  }
2170
- let cardanoTxIn = new TransactionInput(
2171
- TransactionId(currentTxIn.txIn.txHash),
2172
- BigInt(currentTxIn.txIn.txIndex)
2173
- );
2174
3395
  let exUnits = currentTxIn.scriptTxIn.redeemer.exUnits;
2175
- this.redeemerContext.set(
2176
- cardanoTxIn,
3396
+ let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
3397
+ let redeemersList = [...redeemers.values()];
3398
+ redeemersList.push(
2177
3399
  new Redeemer(
2178
3400
  RedeemerTag.Spend,
2179
- BigInt(0),
2180
- toPlutusData(currentTxIn.scriptTxIn.redeemer.data.content),
2181
- // TODO: handle json / raw datum
3401
+ BigInt(index),
3402
+ fromBuilderToPlutusData(currentTxIn.scriptTxIn.redeemer.data),
2182
3403
  new ExUnits(BigInt(exUnits.mem), BigInt(exUnits.steps))
2183
3404
  )
2184
3405
  );
3406
+ redeemers.setValues(redeemersList);
3407
+ this.txWitnessSet.setRedeemers(redeemers);
2185
3408
  };
2186
3409
  addSimpleScriptTxIn = (currentTxIn) => {
2187
3410
  this.addTxIn({
@@ -2195,21 +3418,12 @@ var CardanoSDKSerializer = class {
2195
3418
  this.scriptsProvided.add(
2196
3419
  Script.newNativeScript(
2197
3420
  NativeScript.fromCbor(
2198
- HexBlob6(currentTxIn.simpleScriptTxIn.scriptSource.scriptCode)
3421
+ HexBlob8(currentTxIn.simpleScriptTxIn.scriptSource.scriptCode)
2199
3422
  )
2200
- )
3423
+ ).toCbor()
2201
3424
  );
2202
3425
  } else if (currentTxIn.simpleScriptTxIn.scriptSource.type === "Inline") {
2203
- let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2204
- let referenceInputsList = [...referenceInputs.values()];
2205
- referenceInputsList.push(
2206
- new TransactionInput(
2207
- TransactionId(currentTxIn.simpleScriptTxIn.scriptSource.txHash),
2208
- BigInt(currentTxIn.simpleScriptTxIn.scriptSource.txIndex)
2209
- )
2210
- );
2211
- referenceInputs.setValues(referenceInputsList);
2212
- this.txBody.setReferenceInputs(referenceInputs);
3426
+ this.addSimpleScriptRef(currentTxIn.simpleScriptTxIn.scriptSource);
2213
3427
  }
2214
3428
  };
2215
3429
  addAllOutputs = (outputs) => {
@@ -2219,32 +3433,41 @@ var CardanoSDKSerializer = class {
2219
3433
  };
2220
3434
  addOutput = (output) => {
2221
3435
  const currentOutputs = this.txBody.outputs();
2222
- const cardanoOutput = new TransactionOutput(
2223
- Address.fromBech32(output.address),
3436
+ currentOutputs.push(this.toCardanoOutput(output));
3437
+ this.txBody.setOutputs(currentOutputs);
3438
+ };
3439
+ toCardanoOutput = (output) => {
3440
+ let cardanoOutput = new TransactionOutput(
3441
+ toCardanoAddress(output.address),
2224
3442
  toValue(output.amount)
2225
3443
  );
2226
3444
  if (output.datum?.type === "Hash") {
2227
3445
  cardanoOutput.setDatum(
2228
3446
  Datum.newDataHash(
2229
3447
  DatumHash.fromHexBlob(
2230
- HexBlob6(toPlutusData(output.datum.data.content).hash())
3448
+ HexBlob8(fromBuilderToPlutusData(output.datum.data).hash())
2231
3449
  )
2232
3450
  )
2233
3451
  );
2234
3452
  } else if (output.datum?.type === "Inline") {
2235
3453
  cardanoOutput.setDatum(
2236
- Datum.newInlineData(
2237
- toPlutusData(output.datum.data.content)
2238
- // TODO: handle json / raw datum
2239
- )
3454
+ Datum.newInlineData(fromBuilderToPlutusData(output.datum.data))
2240
3455
  );
3456
+ } else if (output.datum?.type === "Embedded") {
3457
+ const currentWitnessDatum = this.txWitnessSet.plutusData() ?? Serialization6.CborSet.fromCore([], Serialization6.PlutusData.fromCore);
3458
+ const currentWitnessDatumValues = [...currentWitnessDatum.values()];
3459
+ currentWitnessDatumValues.push(
3460
+ fromBuilderToPlutusData(output.datum.data)
3461
+ );
3462
+ currentWitnessDatum.setValues(currentWitnessDatumValues);
3463
+ this.txWitnessSet.setPlutusData(currentWitnessDatum);
2241
3464
  }
2242
3465
  if (output.referenceScript) {
2243
3466
  switch (output.referenceScript.version) {
2244
3467
  case "V1": {
2245
3468
  cardanoOutput.setScriptRef(
2246
3469
  Script.newPlutusV1Script(
2247
- PlutusV1Script.fromCbor(HexBlob6(output.referenceScript.code))
3470
+ PlutusV1Script.fromCbor(HexBlob8(output.referenceScript.code))
2248
3471
  )
2249
3472
  );
2250
3473
  break;
@@ -2252,7 +3475,7 @@ var CardanoSDKSerializer = class {
2252
3475
  case "V2": {
2253
3476
  cardanoOutput.setScriptRef(
2254
3477
  Script.newPlutusV2Script(
2255
- PlutusV2Script.fromCbor(HexBlob6(output.referenceScript.code))
3478
+ PlutusV2Script.fromCbor(HexBlob8(output.referenceScript.code))
2256
3479
  )
2257
3480
  );
2258
3481
  break;
@@ -2260,27 +3483,26 @@ var CardanoSDKSerializer = class {
2260
3483
  case "V3": {
2261
3484
  cardanoOutput.setScriptRef(
2262
3485
  Script.newPlutusV3Script(
2263
- PlutusV3Script.fromCbor(HexBlob6(output.referenceScript.code))
3486
+ PlutusV3Script.fromCbor(HexBlob8(output.referenceScript.code))
2264
3487
  )
2265
3488
  );
2266
3489
  break;
2267
3490
  }
2268
3491
  }
2269
3492
  }
2270
- currentOutputs.push(cardanoOutput);
2271
- this.txBody.setOutputs(currentOutputs);
3493
+ return cardanoOutput;
2272
3494
  };
2273
3495
  addAllReferenceInputs = (refInputs) => {
2274
3496
  for (let i = 0; i < refInputs.length; i++) {
2275
- this.addReferenceIput(refInputs[i]);
3497
+ this.addReferenceInput(refInputs[i]);
2276
3498
  }
2277
3499
  };
2278
- addReferenceIput = (refInput) => {
2279
- let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
3500
+ addReferenceInput = (refInput) => {
3501
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization6.CborSet.fromCore([], TransactionInput.fromCore);
2280
3502
  let referenceInputsList = [...referenceInputs.values()];
2281
3503
  referenceInputsList.push(
2282
3504
  new TransactionInput(
2283
- TransactionId.fromHexBlob(HexBlob6(refInput.txHash)),
3505
+ TransactionId.fromHexBlob(HexBlob8(refInput.txHash)),
2284
3506
  BigInt(refInput.txIndex)
2285
3507
  )
2286
3508
  );
@@ -2288,9 +3510,24 @@ var CardanoSDKSerializer = class {
2288
3510
  this.txBody.setReferenceInputs(referenceInputs);
2289
3511
  };
2290
3512
  addAllMints = (mints) => {
2291
- for (let i = 0; i < mints.length; i++) {
2292
- this.addMint(mints[i]);
3513
+ for (let i2 = 0; i2 < mints.length; i2++) {
3514
+ this.addMint(mints[i2]);
2293
3515
  }
3516
+ let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
3517
+ let redeemersList = [...redeemers.values()];
3518
+ let i = 0;
3519
+ this.mintRedeemers.forEach((redeemer) => {
3520
+ const newRedeemer = new Redeemer(
3521
+ redeemer.tag(),
3522
+ BigInt(i),
3523
+ redeemer.data(),
3524
+ redeemer.exUnits()
3525
+ );
3526
+ redeemersList.push(newRedeemer);
3527
+ redeemers.setValues(redeemersList);
3528
+ i++;
3529
+ });
3530
+ this.txWitnessSet.setRedeemers(redeemers);
2294
3531
  };
2295
3532
  addMint = (mint) => {
2296
3533
  const currentMint = this.txBody.mint() ?? /* @__PURE__ */ new Map();
@@ -2300,15 +3537,153 @@ var CardanoSDKSerializer = class {
2300
3537
  throw new Error("The same asset is already in the mint field");
2301
3538
  }
2302
3539
  }
2303
- currentMint.set(
2304
- AssetId.fromParts(PolicyId(mint.policyId), AssetName(mint.assetName)),
2305
- BigInt(mint.amount)
3540
+ currentMint.set(
3541
+ AssetId.fromParts(PolicyId(mint.policyId), AssetName(mint.assetName)),
3542
+ BigInt(mint.amount)
3543
+ );
3544
+ this.txBody.setMint(currentMint);
3545
+ if (mint.type === "Native") {
3546
+ if (!mint.scriptSource)
3547
+ throw new Error("Script source not provided for native script mint");
3548
+ const nativeScriptSource = mint.scriptSource;
3549
+ if (!nativeScriptSource)
3550
+ throw new Error(
3551
+ "A script source for a native script was not a native script somehow"
3552
+ );
3553
+ if (nativeScriptSource.type === "Provided") {
3554
+ this.scriptsProvided.add(
3555
+ Script.newNativeScript(
3556
+ NativeScript.fromCbor(HexBlob8(nativeScriptSource.scriptCode))
3557
+ ).toCbor()
3558
+ );
3559
+ } else if (nativeScriptSource.type === "Inline") {
3560
+ this.addSimpleScriptRef(nativeScriptSource);
3561
+ }
3562
+ } else if (mint.type === "Plutus") {
3563
+ if (!mint.scriptSource)
3564
+ throw new Error("Script source not provided for plutus script mint");
3565
+ const plutusScriptSource = mint.scriptSource;
3566
+ if (!plutusScriptSource) {
3567
+ throw new Error(
3568
+ "A script source for a plutus mint was not plutus script somehow"
3569
+ );
3570
+ }
3571
+ if (!mint.redeemer) {
3572
+ throw new Error("A redeemer was not provided for a plutus mint");
3573
+ }
3574
+ const currentRedeemer = new Redeemer(
3575
+ RedeemerTag.Mint,
3576
+ BigInt(0),
3577
+ fromBuilderToPlutusData(mint.redeemer.data),
3578
+ new ExUnits(
3579
+ BigInt(mint.redeemer.exUnits.mem),
3580
+ BigInt(mint.redeemer.exUnits.steps)
3581
+ )
3582
+ );
3583
+ if (this.mintRedeemers.has(mint.policyId)) {
3584
+ if (this.mintRedeemers.get(mint.policyId)?.toCbor() !== currentRedeemer.toCbor()) {
3585
+ throw new Error(
3586
+ "The same minting policy must have the same redeemer"
3587
+ );
3588
+ }
3589
+ } else {
3590
+ this.mintRedeemers.set(mint.policyId, currentRedeemer);
3591
+ }
3592
+ if (plutusScriptSource.type === "Provided") {
3593
+ this.addProvidedPlutusScript(plutusScriptSource.script);
3594
+ } else if (plutusScriptSource.type === "Inline") {
3595
+ this.addScriptRef(plutusScriptSource);
3596
+ }
3597
+ }
3598
+ };
3599
+ addAllCerts = (certs) => {
3600
+ for (let i = 0; i < certs.length; i++) {
3601
+ this.addCert(certs[i], i);
3602
+ }
3603
+ };
3604
+ addCert = (cert, index) => {
3605
+ const currentCerts = this.txBody.certs() ?? Serialization6.CborSet.fromCore([], Serialization6.Certificate.fromCore);
3606
+ let currentCertsValues = [...currentCerts.values()];
3607
+ currentCertsValues.push(toCardanoCert(cert.certType));
3608
+ currentCerts.setValues(currentCertsValues);
3609
+ this.txBody.setCerts(currentCerts);
3610
+ if (cert.type === "SimpleScriptCertificate") {
3611
+ if (!cert.simpleScriptSource)
3612
+ throw new Error("Script source not provided for native script cert");
3613
+ const nativeScriptSource = cert.simpleScriptSource;
3614
+ if (!nativeScriptSource)
3615
+ throw new Error(
3616
+ "A script source for a native script was not a native script somehow"
3617
+ );
3618
+ if (nativeScriptSource.type === "Provided") {
3619
+ this.scriptsProvided.add(
3620
+ Script.newNativeScript(
3621
+ NativeScript.fromCbor(HexBlob8(nativeScriptSource.scriptCode))
3622
+ ).toCbor()
3623
+ );
3624
+ } else if (nativeScriptSource.type === "Inline") {
3625
+ this.addSimpleScriptRef(nativeScriptSource);
3626
+ }
3627
+ } else if (cert.type === "ScriptCertificate") {
3628
+ if (!cert.scriptSource)
3629
+ throw new Error(
3630
+ "Script source not provided for plutus script certificate"
3631
+ );
3632
+ const plutusScriptSource = cert.scriptSource;
3633
+ if (!plutusScriptSource) {
3634
+ throw new Error(
3635
+ "A script source for a plutus certificate was not plutus script somehow"
3636
+ );
3637
+ }
3638
+ if (!cert.redeemer) {
3639
+ throw new Error("A redeemer was not provided for a plutus certificate");
3640
+ }
3641
+ let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
3642
+ let redeemersList = [...redeemers.values()];
3643
+ redeemersList.push(
3644
+ new Redeemer(
3645
+ RedeemerTag.Cert,
3646
+ BigInt(index),
3647
+ fromBuilderToPlutusData(cert.redeemer.data),
3648
+ new ExUnits(
3649
+ BigInt(cert.redeemer.exUnits.mem),
3650
+ BigInt(cert.redeemer.exUnits.steps)
3651
+ )
3652
+ )
3653
+ );
3654
+ redeemers.setValues(redeemersList);
3655
+ this.txWitnessSet.setRedeemers(redeemers);
3656
+ if (plutusScriptSource.type === "Provided") {
3657
+ this.addProvidedPlutusScript(plutusScriptSource.script);
3658
+ } else if (plutusScriptSource.type === "Inline") {
3659
+ this.addScriptRef(plutusScriptSource);
3660
+ }
3661
+ }
3662
+ };
3663
+ addAllWithdrawals = (withdrawals) => {
3664
+ for (let i = 0; i < withdrawals.length; i++) {
3665
+ this.addWithdrawal(withdrawals[i], i);
3666
+ }
3667
+ };
3668
+ addWithdrawal = (withdrawal, index) => {
3669
+ const currentWithdrawals = this.txBody.withdrawals() ?? /* @__PURE__ */ new Map();
3670
+ const address = toCardanoAddress(withdrawal.address);
3671
+ const rewardAddress = address.asReward();
3672
+ if (!rewardAddress) {
3673
+ throw new Error("Failed to parse reward address for withdrawal");
3674
+ }
3675
+ currentWithdrawals.set(
3676
+ RewardAccount.fromCredential(
3677
+ rewardAddress.getPaymentCredential(),
3678
+ address.getNetworkId()
3679
+ ),
3680
+ BigInt(withdrawal.coin)
2306
3681
  );
2307
- this.txBody.setMint(currentMint);
2308
- if (mint.type === "Native") {
2309
- if (!mint.scriptSource)
2310
- throw new Error("Script source not provided for native script mint");
2311
- const nativeScriptSource = mint.scriptSource;
3682
+ this.txBody.setWithdrawals(currentWithdrawals);
3683
+ if (withdrawal.type === "SimpleScriptWithdrawal") {
3684
+ if (!withdrawal.scriptSource)
3685
+ throw new Error("Script source not provided for native script cert");
3686
+ const nativeScriptSource = withdrawal.scriptSource;
2312
3687
  if (!nativeScriptSource)
2313
3688
  throw new Error(
2314
3689
  "A script source for a native script was not a native script somehow"
@@ -2316,85 +3691,45 @@ var CardanoSDKSerializer = class {
2316
3691
  if (nativeScriptSource.type === "Provided") {
2317
3692
  this.scriptsProvided.add(
2318
3693
  Script.newNativeScript(
2319
- NativeScript.fromCbor(HexBlob6(nativeScriptSource.scriptCode))
2320
- )
3694
+ NativeScript.fromCbor(HexBlob8(nativeScriptSource.scriptCode))
3695
+ ).toCbor()
2321
3696
  );
2322
3697
  } else if (nativeScriptSource.type === "Inline") {
2323
- let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2324
- let referenceInputsList = [...referenceInputs.values()];
2325
- referenceInputsList.push(
2326
- new TransactionInput(
2327
- TransactionId(nativeScriptSource.txHash),
2328
- BigInt(nativeScriptSource.txIndex)
2329
- )
2330
- );
2331
- referenceInputs.setValues(referenceInputsList);
2332
- this.txBody.setReferenceInputs(referenceInputs);
3698
+ this.addSimpleScriptRef(nativeScriptSource);
2333
3699
  }
2334
- } else if (mint.type === "Plutus") {
2335
- if (!mint.scriptSource)
2336
- throw new Error("Script source not provided for plutus script mint");
2337
- const plutusScriptSource = mint.scriptSource;
3700
+ } else if (withdrawal.type === "ScriptWithdrawal") {
3701
+ if (!withdrawal.scriptSource)
3702
+ throw new Error(
3703
+ "Script source not provided for plutus script certificate"
3704
+ );
3705
+ const plutusScriptSource = withdrawal.scriptSource;
2338
3706
  if (!plutusScriptSource) {
2339
3707
  throw new Error(
2340
- "A script source for a plutus mint was not plutus script somehow"
3708
+ "A script source for a plutus certificate was not plutus script somehow"
2341
3709
  );
2342
3710
  }
3711
+ if (!withdrawal.redeemer) {
3712
+ throw new Error("A redeemer was not provided for a plutus certificate");
3713
+ }
3714
+ let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
3715
+ let redeemersList = [...redeemers.values()];
3716
+ redeemersList.push(
3717
+ new Redeemer(
3718
+ RedeemerTag.Reward,
3719
+ BigInt(index),
3720
+ fromBuilderToPlutusData(withdrawal.redeemer.data),
3721
+ new ExUnits(
3722
+ BigInt(withdrawal.redeemer.exUnits.mem),
3723
+ BigInt(withdrawal.redeemer.exUnits.steps)
3724
+ )
3725
+ )
3726
+ );
3727
+ redeemers.setValues(redeemersList);
3728
+ this.txWitnessSet.setRedeemers(redeemers);
2343
3729
  if (plutusScriptSource.type === "Provided") {
2344
- switch (plutusScriptSource.script.version) {
2345
- case "V1":
2346
- this.scriptsProvided.add(
2347
- Script.newPlutusV1Script(
2348
- PlutusV1Script.fromCbor(
2349
- HexBlob6(plutusScriptSource.script.code)
2350
- )
2351
- )
2352
- );
2353
- break;
2354
- case "V2":
2355
- this.scriptsProvided.add(
2356
- Script.newPlutusV2Script(
2357
- PlutusV2Script.fromCbor(
2358
- HexBlob6(plutusScriptSource.script.code)
2359
- )
2360
- )
2361
- );
2362
- break;
2363
- case "V3":
2364
- this.scriptsProvided.add(
2365
- Script.newPlutusV3Script(
2366
- PlutusV3Script.fromCbor(
2367
- HexBlob6(plutusScriptSource.script.code)
2368
- )
2369
- )
2370
- );
2371
- break;
2372
- }
3730
+ this.addProvidedPlutusScript(plutusScriptSource.script);
2373
3731
  } else if (plutusScriptSource.type === "Inline") {
2374
- let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2375
- let referenceInputsList = [...referenceInputs.values()];
2376
- referenceInputsList.push(
2377
- new TransactionInput(
2378
- TransactionId(plutusScriptSource.txHash),
2379
- BigInt(plutusScriptSource.txIndex)
2380
- )
2381
- );
2382
- referenceInputs.setValues(referenceInputsList);
2383
- this.txBody.setReferenceInputs(referenceInputs);
2384
- switch (plutusScriptSource.version) {
2385
- case "V1": {
2386
- this.usedLanguages[PlutusLanguageVersion.V1] = true;
2387
- break;
2388
- }
2389
- case "V2": {
2390
- this.usedLanguages[PlutusLanguageVersion.V2] = true;
2391
- break;
2392
- }
2393
- case "V3": {
2394
- this.usedLanguages[PlutusLanguageVersion.V3] = true;
2395
- break;
2396
- }
2397
- }
3732
+ this.addScriptRef(plutusScriptSource);
2398
3733
  }
2399
3734
  }
2400
3735
  };
@@ -2410,7 +3745,7 @@ var CardanoSDKSerializer = class {
2410
3745
  TransactionId(collateral.txIn.txHash),
2411
3746
  BigInt(collateral.txIn.txIndex)
2412
3747
  );
2413
- const collateralInputs = this.txBody.collateral() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
3748
+ const collateralInputs = this.txBody.collateral() ?? Serialization6.CborSet.fromCore([], TransactionInput.fromCore);
2414
3749
  const collateralInputsList = [
2415
3750
  ...collateralInputs.values()
2416
3751
  ];
@@ -2422,7 +3757,7 @@ var CardanoSDKSerializer = class {
2422
3757
  collateralInputsList.push(cardanoTxIn);
2423
3758
  collateralInputs.setValues(collateralInputsList);
2424
3759
  const cardanoTxOut = new TransactionOutput(
2425
- Address.fromBech32(collateral.txIn.address),
3760
+ toCardanoAddress(collateral.txIn.address),
2426
3761
  toValue(collateral.txIn.amount)
2427
3762
  );
2428
3763
  this.utxoContext.set(cardanoTxIn, cardanoTxOut);
@@ -2436,29 +3771,31 @@ var CardanoSDKSerializer = class {
2436
3771
  this.txBody.setTtl(Slot(validity.invalidHereafter));
2437
3772
  }
2438
3773
  };
2439
- buildWitnessSet = () => {
2440
- const inputs = this.txBody.inputs();
2441
- for (let i = 0; i < inputs.size(); i += 1) {
2442
- const input = inputs.values().at(i);
2443
- if (input) {
2444
- let redeemer = this.redeemerContext.get(input);
2445
- if (redeemer) {
2446
- redeemer.setIndex(BigInt(i));
2447
- }
2448
- }
3774
+ addAllRequiredSignatures = (requiredSignatures) => {
3775
+ const requiredSigners = this.txBody.requiredSigners() ?? Serialization6.CborSet.fromCore([], Serialization6.Hash.fromCore);
3776
+ let requiredSignerValues = [...requiredSigners.values()];
3777
+ for (const requiredSigner of requiredSignatures) {
3778
+ requiredSignerValues.push(
3779
+ Serialization6.Hash.fromCore(Ed25519KeyHashHex2(requiredSigner))
3780
+ );
2449
3781
  }
2450
- let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
2451
- let redeemersList = [...redeemers.values()];
2452
- this.redeemerContext.forEach((redeemer) => {
2453
- redeemersList.push(redeemer);
2454
- });
2455
- redeemers.setValues(redeemersList);
2456
- this.txWitnessSet.setRedeemers(redeemers);
2457
- let nativeScripts = this.txWitnessSet.nativeScripts() ?? Serialization4.CborSet.fromCore([], NativeScript.fromCore);
2458
- let v1Scripts = this.txWitnessSet.plutusV1Scripts() ?? Serialization4.CborSet.fromCore([], PlutusV1Script.fromCore);
2459
- let v2Scripts = this.txWitnessSet.plutusV2Scripts() ?? Serialization4.CborSet.fromCore([], PlutusV2Script.fromCore);
2460
- let v3Scripts = this.txWitnessSet.plutusV3Scripts() ?? Serialization4.CborSet.fromCore([], PlutusV3Script.fromCore);
2461
- this.scriptsProvided.forEach((script) => {
3782
+ requiredSigners.setValues(requiredSignerValues);
3783
+ this.txBody.setRequiredSigners(requiredSigners);
3784
+ };
3785
+ addMetadata = (metadata) => {
3786
+ this.txAuxilliaryData.setMetadata(
3787
+ new Serialization6.GeneralTransactionMetadata(
3788
+ toCardanoMetadataMap(metadata)
3789
+ )
3790
+ );
3791
+ };
3792
+ buildWitnessSet = () => {
3793
+ let nativeScripts = this.txWitnessSet.nativeScripts() ?? Serialization6.CborSet.fromCore([], NativeScript.fromCore);
3794
+ let v1Scripts = this.txWitnessSet.plutusV1Scripts() ?? Serialization6.CborSet.fromCore([], PlutusV1Script.fromCore);
3795
+ let v2Scripts = this.txWitnessSet.plutusV2Scripts() ?? Serialization6.CborSet.fromCore([], PlutusV2Script.fromCore);
3796
+ let v3Scripts = this.txWitnessSet.plutusV3Scripts() ?? Serialization6.CborSet.fromCore([], PlutusV3Script.fromCore);
3797
+ this.scriptsProvided.forEach((scriptHex) => {
3798
+ const script = Script.fromCbor(HexBlob8(scriptHex));
2462
3799
  if (script.asNative() !== void 0) {
2463
3800
  let nativeScriptsList = [...nativeScripts.values()];
2464
3801
  nativeScriptsList.push(script.asNative());
@@ -2481,20 +3818,23 @@ var CardanoSDKSerializer = class {
2481
3818
  this.txWitnessSet.setPlutusV2Scripts(v2Scripts);
2482
3819
  this.txWitnessSet.setPlutusV3Scripts(v3Scripts);
2483
3820
  });
2484
- let datums = this.txWitnessSet.plutusData() ?? Serialization4.CborSet.fromCore([], PlutusData.fromCore);
3821
+ let datums = this.txWitnessSet.plutusData() ?? Serialization6.CborSet.fromCore([], PlutusData.fromCore);
3822
+ let datumsList = [...datums.values()];
2485
3823
  this.datumsProvided.forEach((datum) => {
2486
- let datumsList = [...datums.values()];
2487
3824
  datumsList.push(datum);
2488
- datums.setValues(datumsList);
2489
3825
  });
3826
+ datums.setValues(datumsList);
2490
3827
  this.txWitnessSet.setPlutusData(datums);
2491
- let costModelV1 = Serialization4.CostModel.newPlutusV1(
3828
+ let costModelV1 = Serialization6.CostModel.newPlutusV1(
2492
3829
  DEFAULT_V1_COST_MODEL_LIST
2493
3830
  );
2494
- let costModelV2 = Serialization4.CostModel.newPlutusV2(
3831
+ let costModelV2 = Serialization6.CostModel.newPlutusV2(
2495
3832
  DEFAULT_V2_COST_MODEL_LIST
2496
3833
  );
2497
- let costModels = new Serialization4.Costmdls();
3834
+ let costModelV3 = Serialization6.CostModel.newPlutusV3(
3835
+ DEFAULT_V3_COST_MODEL_LIST
3836
+ );
3837
+ let costModels = new Serialization6.Costmdls();
2498
3838
  if (this.usedLanguages[PlutusLanguageVersion.V1]) {
2499
3839
  costModels.insert(costModelV1);
2500
3840
  }
@@ -2502,7 +3842,9 @@ var CardanoSDKSerializer = class {
2502
3842
  costModels.insert(costModelV2);
2503
3843
  }
2504
3844
  if (this.usedLanguages[PlutusLanguageVersion.V3]) {
3845
+ costModels.insert(costModelV3);
2505
3846
  }
3847
+ const redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
2506
3848
  let scriptDataHash = hashScriptData(
2507
3849
  costModels,
2508
3850
  redeemers.size() > 0 ? [...redeemers.values()] : void 0,
@@ -2511,8 +3853,38 @@ var CardanoSDKSerializer = class {
2511
3853
  if (scriptDataHash) {
2512
3854
  this.txBody.setScriptDataHash(scriptDataHash);
2513
3855
  }
3856
+ let auxiliaryDataHash = computeAuxiliaryDataHash(
3857
+ this.txAuxilliaryData.toCore()
3858
+ );
3859
+ if (auxiliaryDataHash) {
3860
+ this.txBody.setAuxiliaryDataHash(auxiliaryDataHash);
3861
+ }
3862
+ };
3863
+ removeInputRefInputOverlap = () => {
3864
+ let refInputsValues = [];
3865
+ const inputs = this.txBody.inputs()?.values();
3866
+ if (this.txBody.referenceInputs()) {
3867
+ const currentRefInputValues = this.txBody.referenceInputs().values();
3868
+ currentRefInputValues.forEach((refInput) => {
3869
+ let found = false;
3870
+ for (let i = 0; i < inputs.length; i++) {
3871
+ if (refInput.toCbor() === inputs[i].toCbor()) {
3872
+ found = true;
3873
+ }
3874
+ }
3875
+ if (!found) {
3876
+ refInputsValues.push(refInput);
3877
+ }
3878
+ });
3879
+ this.txBody.setReferenceInputs(
3880
+ Serialization6.CborSet.fromCore(
3881
+ refInputsValues.map((input) => input.toCore()),
3882
+ TransactionInput.fromCore
3883
+ )
3884
+ );
3885
+ }
2514
3886
  };
2515
- balanceTx = (changeAddress, numberOfRequiredWitnesses, protocolParams) => {
3887
+ balanceTx = (changeAddress) => {
2516
3888
  if (changeAddress === "") {
2517
3889
  throw new Error("Can't balance tx without a change address");
2518
3890
  }
@@ -2546,47 +3918,421 @@ var CardanoSDKSerializer = class {
2546
3918
  remainingValue = subValue(remainingValue, output.amount());
2547
3919
  }
2548
3920
  }
3921
+ const certs = this.txBody.certs();
3922
+ if (certs) {
3923
+ certs.values().forEach((cert) => {
3924
+ switch (cert.toCore().__typename) {
3925
+ case CertificateType.StakeRegistration: {
3926
+ remainingValue = subValue(
3927
+ remainingValue,
3928
+ new Value(BigInt(this.protocolParams.keyDeposit))
3929
+ );
3930
+ break;
3931
+ }
3932
+ case CertificateType.StakeDeregistration: {
3933
+ remainingValue = mergeValue(
3934
+ remainingValue,
3935
+ new Value(BigInt(this.protocolParams.keyDeposit))
3936
+ );
3937
+ break;
3938
+ }
3939
+ case CertificateType.Registration: {
3940
+ remainingValue = subValue(
3941
+ remainingValue,
3942
+ new Value(BigInt(cert.asRegistrationCert()?.deposit() ?? 0))
3943
+ );
3944
+ break;
3945
+ }
3946
+ case CertificateType.Unregistration: {
3947
+ remainingValue = mergeValue(
3948
+ remainingValue,
3949
+ new Value(BigInt(cert.asUnregistrationCert()?.deposit() ?? 0))
3950
+ );
3951
+ break;
3952
+ }
3953
+ case CertificateType.PoolRegistration: {
3954
+ remainingValue = subValue(
3955
+ remainingValue,
3956
+ new Value(BigInt(this.protocolParams.poolDeposit))
3957
+ );
3958
+ break;
3959
+ }
3960
+ case CertificateType.PoolRetirement: {
3961
+ remainingValue = mergeValue(
3962
+ remainingValue,
3963
+ new Value(BigInt(this.protocolParams.poolDeposit))
3964
+ );
3965
+ break;
3966
+ }
3967
+ case CertificateType.RegisterDelegateRepresentative: {
3968
+ remainingValue = subValue(
3969
+ remainingValue,
3970
+ new Value(
3971
+ BigInt(
3972
+ cert.asRegisterDelegateRepresentativeCert()?.deposit() ?? 0
3973
+ )
3974
+ )
3975
+ );
3976
+ break;
3977
+ }
3978
+ case CertificateType.UnregisterDelegateRepresentative: {
3979
+ remainingValue = mergeValue(
3980
+ remainingValue,
3981
+ new Value(
3982
+ BigInt(
3983
+ cert.asUnregisterDelegateRepresentativeCert()?.deposit() ?? 0
3984
+ )
3985
+ )
3986
+ );
3987
+ break;
3988
+ }
3989
+ case CertificateType.StakeRegistrationDelegation: {
3990
+ remainingValue = subValue(
3991
+ remainingValue,
3992
+ new Value(
3993
+ BigInt(
3994
+ cert.asStakeRegistrationDelegationCert()?.deposit() ?? 0
3995
+ )
3996
+ )
3997
+ );
3998
+ break;
3999
+ }
4000
+ case CertificateType.StakeVoteRegistrationDelegation: {
4001
+ remainingValue = subValue(
4002
+ remainingValue,
4003
+ new Value(
4004
+ BigInt(
4005
+ cert.asStakeVoteRegistrationDelegationCert()?.deposit() ?? 0
4006
+ )
4007
+ )
4008
+ );
4009
+ break;
4010
+ }
4011
+ }
4012
+ });
4013
+ }
2549
4014
  if (remainingValue.coin() < 0 || !empty(negatives(remainingValue))) {
2550
4015
  throw new Error(`Not enough funds to satisfy outputs`);
2551
4016
  }
2552
4017
  currentOutputs.push(
2553
- new TransactionOutput(Address.fromBech32(changeAddress), remainingValue)
4018
+ new TransactionOutput(toCardanoAddress(changeAddress), remainingValue)
2554
4019
  );
2555
4020
  this.txBody.setOutputs(currentOutputs);
2556
4021
  this.txBody.setFee(BigInt("10000000"));
4022
+ const numberOfRequiredWitnesses = this.countNumberOfRequiredWitnesses();
2557
4023
  const dummyTx = this.createDummyTx(numberOfRequiredWitnesses);
2558
- const fee = protocolParams.minFeeB + dummyTx.toCbor().length / 2 * Number(protocolParams.coinsPerUtxoSize);
2559
- this.txBody.setFee(BigInt(fee));
4024
+ const fee = calculateFees(
4025
+ this.protocolParams.minFeeA,
4026
+ this.protocolParams.minFeeB,
4027
+ this.protocolParams.minFeeRefScriptCostPerByte,
4028
+ this.protocolParams.priceMem,
4029
+ this.protocolParams.priceStep,
4030
+ dummyTx,
4031
+ this.refScriptSize
4032
+ );
4033
+ this.txBody.setFee(fee);
2560
4034
  const changeOutput = currentOutputs.pop();
2561
4035
  if (!changeOutput) {
2562
4036
  throw new Error(
2563
4037
  "Somehow the output length was 0 after attempting to calculate fees"
2564
4038
  );
2565
4039
  }
2566
- changeOutput.amount().setCoin(changeOutput.amount().coin() - BigInt(fee));
2567
- currentOutputs.push(changeOutput);
4040
+ if (changeOutput.amount().coin() - fee > 0) {
4041
+ changeOutput.amount().setCoin(changeOutput.amount().coin() - fee);
4042
+ currentOutputs.push(changeOutput);
4043
+ } else if (changeOutput.amount().coin() - fee < 0) {
4044
+ throw new Error(
4045
+ "There was enough inputs to cover outputs, but not enough to cover fees"
4046
+ );
4047
+ }
2568
4048
  this.txBody.setOutputs(currentOutputs);
2569
4049
  };
2570
4050
  createDummyTx = (numberOfRequiredWitnesses) => {
2571
- let dummyWitnessSet = new TransactionWitnessSet();
4051
+ let dummyWitnessSet = TransactionWitnessSet.fromCbor(
4052
+ HexBlob8(this.txWitnessSet.toCbor())
4053
+ );
2572
4054
  const dummyVkeyWitnesses = [];
2573
4055
  for (let i = 0; i < numberOfRequiredWitnesses; i++) {
2574
4056
  dummyVkeyWitnesses.push([
2575
- Ed25519PublicKeyHex2("0".repeat(64)),
2576
- Ed25519SignatureHex2("0".repeat(128))
4057
+ Ed25519PublicKeyHex2(String(i).repeat(64)),
4058
+ Ed25519SignatureHex2(String(i).repeat(128))
2577
4059
  ]);
2578
4060
  }
2579
4061
  dummyWitnessSet.setVkeys(
2580
- Serialization4.CborSet.fromCore(dummyVkeyWitnesses, VkeyWitness.fromCore)
4062
+ Serialization6.CborSet.fromCore(dummyVkeyWitnesses, VkeyWitness.fromCore)
4063
+ );
4064
+ return new Transaction(this.txBody, dummyWitnessSet, this.txAuxilliaryData);
4065
+ };
4066
+ addScriptRef = (scriptSource) => {
4067
+ if (scriptSource.type !== "Inline") {
4068
+ return;
4069
+ }
4070
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization6.CborSet.fromCore([], TransactionInput.fromCore);
4071
+ let referenceInputsList = [...referenceInputs.values()];
4072
+ referenceInputsList.push(
4073
+ new TransactionInput(
4074
+ TransactionId(scriptSource.txHash),
4075
+ BigInt(scriptSource.txIndex)
4076
+ )
4077
+ );
4078
+ referenceInputs.setValues(referenceInputsList);
4079
+ this.txBody.setReferenceInputs(referenceInputs);
4080
+ switch (scriptSource.version) {
4081
+ case "V1": {
4082
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
4083
+ break;
4084
+ }
4085
+ case "V2": {
4086
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
4087
+ break;
4088
+ }
4089
+ case "V3": {
4090
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
4091
+ break;
4092
+ }
4093
+ }
4094
+ if (scriptSource.scriptSize) {
4095
+ this.refScriptSize += Number(scriptSource.scriptSize);
4096
+ } else {
4097
+ throw new Error(
4098
+ "A reference script was used without providing its size, this must be provided as fee calculations are based on it"
4099
+ );
4100
+ }
4101
+ };
4102
+ addSimpleScriptRef = (simpleScriptSource) => {
4103
+ if (simpleScriptSource.type !== "Inline") {
4104
+ return;
4105
+ }
4106
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization6.CborSet.fromCore([], TransactionInput.fromCore);
4107
+ let referenceInputsList = [...referenceInputs.values()];
4108
+ referenceInputsList.push(
4109
+ new TransactionInput(
4110
+ TransactionId(simpleScriptSource.txHash),
4111
+ BigInt(simpleScriptSource.txIndex)
4112
+ )
2581
4113
  );
2582
- return new Transaction(this.txBody, dummyWitnessSet);
4114
+ if (simpleScriptSource.scriptSize) {
4115
+ this.refScriptSize += Number(simpleScriptSource.scriptSize);
4116
+ } else {
4117
+ throw new Error(
4118
+ "A reference script was used without providing its size, this must be provided as fee calculations are based on it"
4119
+ );
4120
+ }
4121
+ referenceInputs.setValues(referenceInputsList);
4122
+ this.txBody.setReferenceInputs(referenceInputs);
4123
+ };
4124
+ countNumberOfRequiredWitnesses() {
4125
+ let requiredWitnesses = /* @__PURE__ */ new Set();
4126
+ const inputs = this.txBody.inputs().values();
4127
+ for (let i = 0; i < inputs.length; i++) {
4128
+ const input = inputs[i];
4129
+ const addressPaymentPart = this.utxoContext.get(input)?.address().getProps().paymentPart;
4130
+ if (addressPaymentPart?.type === 0) {
4131
+ requiredWitnesses.add(addressPaymentPart.hash);
4132
+ }
4133
+ }
4134
+ const collateralInputs = this.txBody.collateral()?.values();
4135
+ if (collateralInputs) {
4136
+ for (let i = 0; i < collateralInputs?.length; i++) {
4137
+ const collateralInput = collateralInputs[i];
4138
+ const addressPaymentPart = this.utxoContext.get(collateralInput)?.address().getProps().paymentPart;
4139
+ if (addressPaymentPart?.type === 0) {
4140
+ requiredWitnesses.add(addressPaymentPart.hash);
4141
+ }
4142
+ }
4143
+ }
4144
+ const withdrawalKeys = this.txBody.withdrawals()?.keys();
4145
+ if (withdrawalKeys) {
4146
+ for (let withdrawalKey of withdrawalKeys) {
4147
+ requiredWitnesses.add(RewardAccount.toHash(withdrawalKey));
4148
+ }
4149
+ }
4150
+ const certs = this.txBody.certs()?.values();
4151
+ if (certs) {
4152
+ for (let cert of certs) {
4153
+ const coreCert = cert.toCore();
4154
+ switch (coreCert.__typename) {
4155
+ case CertificateType.StakeRegistration: {
4156
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4157
+ break;
4158
+ }
4159
+ case CertificateType.StakeDeregistration: {
4160
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4161
+ break;
4162
+ }
4163
+ case CertificateType.PoolRegistration: {
4164
+ for (let owner of coreCert.poolParameters.owners) {
4165
+ requiredWitnesses.add(RewardAccount.toHash(owner));
4166
+ }
4167
+ requiredWitnesses.add(PoolId.toKeyHash(coreCert.poolParameters.id));
4168
+ break;
4169
+ }
4170
+ case CertificateType.PoolRetirement: {
4171
+ requiredWitnesses.add(PoolId.toKeyHash(coreCert.poolId));
4172
+ break;
4173
+ }
4174
+ case CertificateType.StakeDelegation: {
4175
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4176
+ break;
4177
+ }
4178
+ case CertificateType.MIR:
4179
+ break;
4180
+ case CertificateType.GenesisKeyDelegation: {
4181
+ requiredWitnesses.add(coreCert.genesisDelegateHash);
4182
+ break;
4183
+ }
4184
+ case CertificateType.Registration: {
4185
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4186
+ break;
4187
+ }
4188
+ case CertificateType.Unregistration: {
4189
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4190
+ break;
4191
+ }
4192
+ case CertificateType.VoteDelegation: {
4193
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4194
+ break;
4195
+ }
4196
+ case CertificateType.StakeVoteDelegation: {
4197
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4198
+ break;
4199
+ }
4200
+ case CertificateType.StakeRegistrationDelegation: {
4201
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4202
+ break;
4203
+ }
4204
+ case CertificateType.VoteRegistrationDelegation: {
4205
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4206
+ break;
4207
+ }
4208
+ case CertificateType.StakeVoteRegistrationDelegation: {
4209
+ requiredWitnesses.add(coreCert.stakeCredential.hash);
4210
+ break;
4211
+ }
4212
+ case CertificateType.AuthorizeCommitteeHot: {
4213
+ requiredWitnesses.add(coreCert.hotCredential.hash);
4214
+ break;
4215
+ }
4216
+ case CertificateType.ResignCommitteeCold: {
4217
+ requiredWitnesses.add(coreCert.coldCredential.hash);
4218
+ break;
4219
+ }
4220
+ case CertificateType.RegisterDelegateRepresentative: {
4221
+ requiredWitnesses.add(coreCert.dRepCredential.hash);
4222
+ break;
4223
+ }
4224
+ case CertificateType.UnregisterDelegateRepresentative: {
4225
+ requiredWitnesses.add(coreCert.dRepCredential.hash);
4226
+ break;
4227
+ }
4228
+ case CertificateType.UpdateDelegateRepresentative: {
4229
+ requiredWitnesses.add(coreCert.dRepCredential.hash);
4230
+ break;
4231
+ }
4232
+ }
4233
+ }
4234
+ }
4235
+ for (const scriptHex of this.scriptsProvided) {
4236
+ const script = Script.fromCbor(HexBlob8(scriptHex));
4237
+ let nativeScript = script.asNative();
4238
+ if (nativeScript) {
4239
+ this.addKeyHashesFromNativeScript(nativeScript, requiredWitnesses);
4240
+ }
4241
+ }
4242
+ const requiredSigners = this.txBody.requiredSigners()?.values();
4243
+ if (requiredSigners) {
4244
+ for (let i = 0; i < requiredSigners.length; i++) {
4245
+ requiredWitnesses.add(requiredSigners[i].toCbor());
4246
+ }
4247
+ }
4248
+ return requiredWitnesses.size;
4249
+ }
4250
+ addKeyHashesFromNativeScript(script, keyHashes) {
4251
+ const scriptCore = script.toCore();
4252
+ switch (scriptCore.kind) {
4253
+ case RequireSignature: {
4254
+ keyHashes.add(scriptCore.keyHash);
4255
+ break;
4256
+ }
4257
+ case RequireTimeAfter: {
4258
+ break;
4259
+ }
4260
+ case RequireTimeBefore: {
4261
+ break;
4262
+ }
4263
+ case RequireAllOf: {
4264
+ for (const innerScript of scriptCore.scripts) {
4265
+ this.addKeyHashesFromNativeScript(
4266
+ NativeScript.fromCore(innerScript),
4267
+ keyHashes
4268
+ );
4269
+ }
4270
+ break;
4271
+ }
4272
+ case RequireAnyOf: {
4273
+ for (const innerScript of scriptCore.scripts) {
4274
+ this.addKeyHashesFromNativeScript(
4275
+ NativeScript.fromCore(innerScript),
4276
+ keyHashes
4277
+ );
4278
+ }
4279
+ break;
4280
+ }
4281
+ case RequireNOf: {
4282
+ for (const innerScript of scriptCore.scripts) {
4283
+ this.addKeyHashesFromNativeScript(
4284
+ NativeScript.fromCore(innerScript),
4285
+ keyHashes
4286
+ );
4287
+ }
4288
+ break;
4289
+ }
4290
+ }
4291
+ return keyHashes;
4292
+ }
4293
+ addProvidedPlutusScript = (script) => {
4294
+ switch (script.version) {
4295
+ case "V1": {
4296
+ this.scriptsProvided.add(
4297
+ Script.newPlutusV1Script(
4298
+ PlutusV1Script.fromCbor(HexBlob8(script.code))
4299
+ ).toCbor()
4300
+ );
4301
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
4302
+ break;
4303
+ }
4304
+ case "V2": {
4305
+ this.scriptsProvided.add(
4306
+ Script.newPlutusV2Script(
4307
+ PlutusV2Script.fromCbor(HexBlob8(script.code))
4308
+ ).toCbor()
4309
+ );
4310
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
4311
+ break;
4312
+ }
4313
+ case "V3": {
4314
+ this.scriptsProvided.add(
4315
+ Script.newPlutusV3Script(
4316
+ PlutusV3Script.fromCbor(HexBlob8(script.code))
4317
+ ).toCbor()
4318
+ );
4319
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
4320
+ break;
4321
+ }
4322
+ }
2583
4323
  };
2584
4324
  };
2585
4325
 
2586
4326
  // src/plutus-tools/index.ts
4327
+ import { Cbor as Cbor2, CborBytes as CborBytes2 } from "@harmoniclabs/cbor";
2587
4328
  import { dataFromCbor } from "@harmoniclabs/plutus-data";
2588
- import { parseUPLC, Application, UPLCProgram, UPLCConst, encodeUPLC } from "@harmoniclabs/uplc";
2589
- import { Cbor, CborBytes } from "@harmoniclabs/cbor";
4329
+ import {
4330
+ Application,
4331
+ encodeUPLC,
4332
+ parseUPLC,
4333
+ UPLCConst,
4334
+ UPLCProgram
4335
+ } from "@harmoniclabs/uplc";
2590
4336
  var supportedPlutusCoreVersions = [
2591
4337
  {
2592
4338
  version: [1, 0, 0],
@@ -2597,6 +4343,19 @@ var supportedPlutusCoreVersions = [
2597
4343
  language: "Plutus V3"
2598
4344
  }
2599
4345
  ];
4346
+ var applyArgsToPlutusScript = (args, program, outputEncoding) => {
4347
+ const purePlutusBytes = getPurePlutusBytes(program);
4348
+ const parsedProgram = parseUPLC(purePlutusBytes, "flat");
4349
+ const decodedArgs = args.map((arg) => dataFromCbor(arg));
4350
+ let body = parsedProgram.body;
4351
+ for (const plutusData of decodedArgs) {
4352
+ const argTerm = UPLCConst.data(plutusData);
4353
+ body = new Application(body, argTerm);
4354
+ }
4355
+ const encodedProgram = new UPLCProgram(parsedProgram.version, body);
4356
+ const newPlutusScriptBytes = encodeUPLC(encodedProgram).toBuffer().buffer;
4357
+ return applyEncoding(newPlutusScriptBytes, outputEncoding);
4358
+ };
2600
4359
  var normalizePlutusScript = (plutusScript, encoding) => {
2601
4360
  const bytes = Buffer.from(plutusScript, "hex");
2602
4361
  const purePlutusBytes = getPurePlutusBytes(bytes);
@@ -2621,8 +4380,8 @@ var getPurePlutusBytes = (plutusScript) => {
2621
4380
  if (hasSupportedPlutusVersion(unwrappedScript)) {
2622
4381
  return unwrappedScript;
2623
4382
  }
2624
- const cbor = Cbor.parse(unwrappedScript);
2625
- if (cbor instanceof CborBytes) {
4383
+ const cbor = Cbor2.parse(unwrappedScript);
4384
+ if (cbor instanceof CborBytes2) {
2626
4385
  unwrappedScript = cbor.bytes;
2627
4386
  } else {
2628
4387
  break;
@@ -2637,7 +4396,7 @@ var getPurePlutusBytes = (plutusScript) => {
2637
4396
  throw new Error("Unsupported Plutus version or invalid Plutus script bytes");
2638
4397
  };
2639
4398
  var applyCborEncoding = (plutusScript) => {
2640
- return Cbor.encode(new CborBytes(plutusScript)).toBuffer();
4399
+ return Cbor2.encode(new CborBytes2(plutusScript)).toBuffer();
2641
4400
  };
2642
4401
  var applyEncoding = (plutusScript, outputEncoding) => {
2643
4402
  switch (outputEncoding) {
@@ -2651,10 +4410,56 @@ var applyEncoding = (plutusScript, outputEncoding) => {
2651
4410
  return applyCborEncoding(plutusScript);
2652
4411
  }
2653
4412
  };
4413
+ var applyParamsToScript = (rawScript, params, type = "Mesh") => {
4414
+ let plutusParams = [];
4415
+ switch (type) {
4416
+ case "JSON":
4417
+ params.forEach((param) => {
4418
+ plutusParams.push(
4419
+ fromBuilderToPlutusData({
4420
+ type: "JSON",
4421
+ content: param
4422
+ })
4423
+ );
4424
+ });
4425
+ break;
4426
+ case "CBOR":
4427
+ params.forEach((param) => {
4428
+ plutusParams.push(
4429
+ fromBuilderToPlutusData({
4430
+ type: "CBOR",
4431
+ content: param
4432
+ })
4433
+ );
4434
+ });
4435
+ break;
4436
+ case "Mesh":
4437
+ params.forEach((param) => {
4438
+ plutusParams.push(
4439
+ fromBuilderToPlutusData({
4440
+ type: "Mesh",
4441
+ content: param
4442
+ })
4443
+ );
4444
+ });
4445
+ break;
4446
+ }
4447
+ const byteParams = plutusParams.map((param) => {
4448
+ return Buffer.from(param.toCbor(), "hex");
4449
+ });
4450
+ const scriptHex = Buffer.from(
4451
+ applyArgsToPlutusScript(
4452
+ byteParams,
4453
+ Buffer.from(rawScript, "hex"),
4454
+ "DoubleCBOR"
4455
+ )
4456
+ ).toString("hex");
4457
+ return scriptHex;
4458
+ };
2654
4459
 
2655
4460
  // src/index.ts
2656
4461
  import * as CardanoSDKUtil from "@cardano-sdk/util";
2657
- import * as Crypto3 from "@cardano-sdk/crypto";
4462
+ import * as Crypto2 from "@cardano-sdk/crypto";
2658
4463
  import * as CardanoSDK from "@cardano-sdk/core";
2659
4464
  export {
2660
4465
  Address,
@@ -2662,15 +4467,17 @@ export {
2662
4467
  AssetFingerprint,
2663
4468
  AssetId,
2664
4469
  AssetName,
4470
+ AuxilliaryData,
2665
4471
  BaseAddress,
2666
4472
  Bip32PrivateKey2 as Bip32PrivateKey,
2667
4473
  Bip32PrivateKeyHex2 as Bip32PrivateKeyHex,
2668
- Cardano4 as Cardano,
4474
+ Cardano5 as Cardano,
2669
4475
  CardanoSDK,
2670
4476
  CardanoSDKSerializer,
2671
4477
  CardanoSDKUtil,
2672
4478
  CborSet,
2673
4479
  CborWriter,
4480
+ CertIndex,
2674
4481
  Certificate,
2675
4482
  CertificateType,
2676
4483
  ConstrPlutusData,
@@ -2679,7 +4486,7 @@ export {
2679
4486
  Costmdls,
2680
4487
  Credential,
2681
4488
  CredentialType,
2682
- Crypto3 as Crypto,
4489
+ Crypto2 as Crypto,
2683
4490
  DRep,
2684
4491
  DRepID,
2685
4492
  Datum,
@@ -2698,16 +4505,20 @@ export {
2698
4505
  Hash,
2699
4506
  Hash28ByteBase162 as Hash28ByteBase16,
2700
4507
  Hash32ByteBase162 as Hash32ByteBase16,
4508
+ MetadatumList,
4509
+ MetadatumMap,
2701
4510
  NativeScript,
2702
4511
  NetworkId,
2703
4512
  PaymentAddress,
2704
4513
  PlutusData,
4514
+ PlutusDataKind,
2705
4515
  PlutusLanguageVersion,
2706
4516
  PlutusList,
2707
4517
  PlutusMap,
2708
4518
  PlutusV1Script,
2709
4519
  PlutusV2Script,
2710
4520
  PlutusV3Script,
4521
+ PointerAddress,
2711
4522
  PolicyId,
2712
4523
  PoolId,
2713
4524
  Redeemer,
@@ -2725,7 +4536,7 @@ export {
2725
4536
  Script,
2726
4537
  ScriptHash,
2727
4538
  ScriptPubkey,
2728
- Serialization5 as Serialization,
4539
+ Serialization7 as Serialization,
2729
4540
  Slot,
2730
4541
  StakeCredentialStatus,
2731
4542
  StakeDelegation,
@@ -2744,14 +4555,21 @@ export {
2744
4555
  TransactionBody,
2745
4556
  TransactionId,
2746
4557
  TransactionInput,
4558
+ TransactionMetadatum,
2747
4559
  TransactionOutput,
2748
4560
  TransactionUnspentOutput,
2749
4561
  TransactionWitnessSet,
4562
+ TxIndex,
2750
4563
  Value,
2751
4564
  VkeyWitness,
2752
4565
  VrfVkBech32,
4566
+ addrBech32ToPlutusDataHex,
4567
+ addrBech32ToPlutusDataObj,
2753
4568
  addressToBech32,
4569
+ applyEncoding,
4570
+ applyParamsToScript,
2754
4571
  assetTypes,
4572
+ blake2b2 as blake2b,
2755
4573
  buildBaseAddress,
2756
4574
  buildBip32PrivateKey,
2757
4575
  buildDRepID,
@@ -2759,8 +4577,11 @@ export {
2759
4577
  buildKeys,
2760
4578
  buildRewardAddress,
2761
4579
  buildScriptPubkey,
4580
+ bytesToHex,
2762
4581
  checkSignature,
4582
+ computeAuxiliaryDataHash,
2763
4583
  deserializeAddress,
4584
+ deserializeBech32Address,
2764
4585
  deserializeDataHash,
2765
4586
  deserializeEd25519KeyHash,
2766
4587
  deserializeNativeScript,
@@ -2773,18 +4594,28 @@ export {
2773
4594
  deserializeTxUnspentOutput,
2774
4595
  deserializeValue,
2775
4596
  empty,
4597
+ fromBuilderToPlutusData,
4598
+ fromJsonToPlutusData,
2776
4599
  fromNativeScript,
4600
+ fromPlutusDataToJson,
2777
4601
  fromScriptRef,
2778
4602
  fromTxUnspentOutput,
2779
4603
  fromValue,
2780
4604
  generateNonce,
2781
4605
  getCoseKeyFromPublicKey,
4606
+ getDRepIds,
2782
4607
  getPublicKeyFromCoseKey,
4608
+ hexToBech32,
4609
+ hexToBytes,
4610
+ keyHashToRewardAddress,
2783
4611
  mergeValue,
2784
4612
  negateValue,
2785
4613
  negatives,
2786
4614
  normalizePlutusScript,
4615
+ parseDatumCbor,
4616
+ parseInlineDatum,
2787
4617
  resolveDataHash,
4618
+ resolveEd25519KeyHash,
2788
4619
  resolveNativeScriptAddress,
2789
4620
  resolveNativeScriptHash,
2790
4621
  resolvePaymentKeyHash,
@@ -2793,18 +4624,29 @@ export {
2793
4624
  resolvePoolId,
2794
4625
  resolvePrivateKey,
2795
4626
  resolveRewardAddress,
4627
+ resolveScriptHashDRepId,
2796
4628
  resolveScriptRef,
2797
4629
  resolveStakeKeyHash,
2798
4630
  resolveTxHash,
4631
+ scriptHashToBech32,
4632
+ scriptHashToRewardAddress,
4633
+ serializeAddressObj,
4634
+ serializePlutusAddressToBech32,
4635
+ serialzeAddress,
2799
4636
  signData,
2800
4637
  subValue,
2801
4638
  toAddress,
2802
4639
  toBaseAddress,
4640
+ toCardanoAddress,
4641
+ toDRep,
2803
4642
  toEnterpriseAddress,
2804
4643
  toNativeScript,
2805
4644
  toPlutusData,
2806
4645
  toRewardAddress,
2807
4646
  toScriptRef,
2808
4647
  toTxUnspentOutput,
2809
- toValue
4648
+ toValue,
4649
+ utf8ToBytes,
4650
+ utf8ToHex,
4651
+ v2ScriptToBech32
2810
4652
  };