@lucid-evolution/provider 0.2.6 → 0.4.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
@@ -89,7 +89,7 @@ var OgmiosJsonRpcError = class extends KupmiosError {
89
89
  var toKupmiosError = (cause, protocol, operation) => cause instanceof KupmiosError ? cause : new KupmiosError({ cause, protocol, operation });
90
90
 
91
91
  // src/core.ts
92
- import * as CML from "@anastasia-labs/cardano-multiplatform-lib-nodejs";
92
+ import * as CML from "@lucid-evolution/cml";
93
93
 
94
94
  // src/blockfrost.ts
95
95
  import { fromHex, sleep } from "@lucid-evolution/core-utils";
@@ -101,7 +101,7 @@ import {
101
101
  // package.json
102
102
  var package_default = {
103
103
  name: "@lucid-evolution/provider",
104
- version: "0.2.6",
104
+ version: "0.4.0",
105
105
  description: "",
106
106
  main: "./dist/index.js",
107
107
  types: "./dist/index.d.ts",
@@ -127,14 +127,10 @@ var package_default = {
127
127
  keywords: [],
128
128
  author: "",
129
129
  license: "MIT",
130
- browser: {
131
- "@anastasia-labs/cardano-multiplatform-lib-nodejs": "@anastasia-labs/cardano-multiplatform-lib-browser"
132
- },
133
130
  dependencies: {
134
- "@anastasia-labs/cardano-multiplatform-lib-browser": "6.2.0-1",
135
- "@anastasia-labs/cardano-multiplatform-lib-nodejs": "6.2.0-1",
136
131
  "@effect/platform": "^0.71.3",
137
132
  "@effect/schema": "^0.68.26",
133
+ "@lucid-evolution/cml": "workspace:*",
138
134
  "@lucid-evolution/core-types": "workspace:*",
139
135
  "@lucid-evolution/core-utils": "workspace:*",
140
136
  "@lucid-evolution/utils": "workspace:*",
@@ -562,7 +558,15 @@ var lucid = package_default.version;
562
558
  // src/kupmios.ts
563
559
  import { applyDoubleCborEncoding as applyDoubleCborEncoding2, fromUnit as fromUnit2 } from "@lucid-evolution/utils";
564
560
  import { Schema as S3 } from "effect";
565
- import { Cause, Effect as Effect2, Exit, pipe as pipe3, Array as _Array, Schedule } from "effect";
561
+ import {
562
+ Cause,
563
+ Effect as Effect2,
564
+ Exit,
565
+ Layer,
566
+ pipe as pipe3,
567
+ Array as _Array,
568
+ Schedule
569
+ } from "effect";
566
570
 
567
571
  // src/internal/ogmios.ts
568
572
  import { Schema as S } from "effect";
@@ -1029,6 +1033,7 @@ var Kupmios = class {
1029
1033
  options;
1030
1034
  requestTimeoutMs;
1031
1035
  awaitTxTimeoutMs;
1036
+ httpLayer;
1032
1037
  constructor(kupoUrl, ogmiosUrl, options = {}) {
1033
1038
  this.kupoUrl = kupoUrl;
1034
1039
  this.ogmiosUrl = ogmiosUrl;
@@ -1041,6 +1046,10 @@ var Kupmios = class {
1041
1046
  "awaitTxTimeoutMs",
1042
1047
  options.awaitTxTimeoutMs ?? DEFAULT_AWAIT_TX_TIMEOUT_MS
1043
1048
  );
1049
+ this.httpLayer = options.fetchImpl === void 0 ? FetchHttpClient.layer : Layer.provide(
1050
+ FetchHttpClient.layer,
1051
+ Layer.succeed(FetchHttpClient.Fetch, options.fetchImpl)
1052
+ );
1044
1053
  }
1045
1054
  async getProtocolParameters() {
1046
1055
  const data = {
@@ -1062,7 +1071,7 @@ var Kupmios = class {
1062
1071
  ),
1063
1072
  Effect2.timeout(this.requestTimeoutMs),
1064
1073
  catchProviderError("ogmios", "queryLedgerState/protocolParameters"),
1065
- Effect2.provide(FetchHttpClient.layer)
1074
+ Effect2.provide(this.httpLayer)
1066
1075
  ),
1067
1076
  "ogmios",
1068
1077
  "queryLedgerState/protocolParameters"
@@ -1097,7 +1106,7 @@ var Kupmios = class {
1097
1106
  ),
1098
1107
  Effect2.timeout(this.requestTimeoutMs),
1099
1108
  catchProviderError("ogmios", "queryLedgerState/treasuryAndReserves"),
1100
- Effect2.provide(FetchHttpClient.layer)
1109
+ Effect2.provide(this.httpLayer)
1101
1110
  ),
1102
1111
  "ogmios",
1103
1112
  "queryLedgerState/treasuryAndReserves"
@@ -1120,7 +1129,7 @@ var Kupmios = class {
1120
1129
  Effect2.map(kupmiosUtxosToUtxos),
1121
1130
  Effect2.timeout(this.requestTimeoutMs),
1122
1131
  catchProviderError("kupo", "getUtxos"),
1123
- Effect2.provide(FetchHttpClient.layer)
1132
+ Effect2.provide(this.httpLayer)
1124
1133
  ),
1125
1134
  "kupo",
1126
1135
  "getUtxos"
@@ -1139,7 +1148,7 @@ var Kupmios = class {
1139
1148
  Effect2.map(kupmiosUtxosToUtxos),
1140
1149
  Effect2.timeout(this.requestTimeoutMs),
1141
1150
  catchProviderError("kupo", "getUtxosWithUnit"),
1142
- Effect2.provide(FetchHttpClient.layer)
1151
+ Effect2.provide(this.httpLayer)
1143
1152
  ),
1144
1153
  "kupo",
1145
1154
  "getUtxosWithUnit"
@@ -1163,7 +1172,7 @@ var Kupmios = class {
1163
1172
  Effect2.map(kupmiosUtxosToUtxos),
1164
1173
  Effect2.timeout(this.requestTimeoutMs),
1165
1174
  catchProviderError("kupo", "getUtxosWithPolicy"),
1166
- Effect2.provide(FetchHttpClient.layer)
1175
+ Effect2.provide(this.httpLayer)
1167
1176
  ),
1168
1177
  "kupo",
1169
1178
  "getUtxosWithPolicy"
@@ -1179,7 +1188,7 @@ var Kupmios = class {
1179
1188
  Effect2.map(kupmiosUtxosToUtxos),
1180
1189
  Effect2.timeout(this.requestTimeoutMs),
1181
1190
  catchProviderError("kupo", "getUtxoByUnit"),
1182
- Effect2.provide(FetchHttpClient.layer)
1191
+ Effect2.provide(this.httpLayer)
1183
1192
  ),
1184
1193
  "kupo",
1185
1194
  "getUtxoByUnit"
@@ -1208,7 +1217,7 @@ var Kupmios = class {
1208
1217
  )
1209
1218
  );
1210
1219
  const utxos = await runProviderEffect(
1211
- pipe3(program, Effect2.provide(FetchHttpClient.layer)),
1220
+ pipe3(program, Effect2.provide(this.httpLayer)),
1212
1221
  "kupo",
1213
1222
  "getUtxosByOutRef"
1214
1223
  );
@@ -1234,7 +1243,7 @@ var Kupmios = class {
1234
1243
  schema,
1235
1244
  this.options.ogmiosHeader
1236
1245
  ),
1237
- Effect2.provide(FetchHttpClient.layer),
1246
+ Effect2.provide(this.httpLayer),
1238
1247
  Effect2.timeout(this.requestTimeoutMs),
1239
1248
  catchProviderError("ogmios", "queryLedgerState/rewardAccountSummaries")
1240
1249
  ),
@@ -1258,7 +1267,7 @@ var Kupmios = class {
1258
1267
  const result = await runProviderEffect(
1259
1268
  pipe3(
1260
1269
  makeGet(pattern, schema, this.options.kupoHeader),
1261
- Effect2.provide(FetchHttpClient.layer),
1270
+ Effect2.provide(this.httpLayer),
1262
1271
  Effect2.timeout(this.requestTimeoutMs),
1263
1272
  Effect2.flatMap(Effect2.fromNullable),
1264
1273
  catchProviderError("kupo", "getDatum")
@@ -1278,7 +1287,7 @@ var Kupmios = class {
1278
1287
  makeGet(pattern, schema, this.options.kupoHeader),
1279
1288
  Effect2.timeout(this.requestTimeoutMs),
1280
1289
  catchProviderError("kupo", "getTransactionStatus"),
1281
- Effect2.provide(FetchHttpClient.layer)
1290
+ Effect2.provide(this.httpLayer)
1282
1291
  ),
1283
1292
  "kupo",
1284
1293
  "getTransactionStatus",
@@ -1304,7 +1313,7 @@ var Kupmios = class {
1304
1313
  const result = await runProviderEffect(
1305
1314
  pipe3(
1306
1315
  makeGet(pattern, schema, this.options.kupoHeader),
1307
- Effect2.provide(FetchHttpClient.layer),
1316
+ Effect2.provide(this.httpLayer),
1308
1317
  Effect2.repeat({
1309
1318
  schedule: Schedule.exponential(checkInterval),
1310
1319
  until: (result2) => result2.length > 0
@@ -1342,7 +1351,7 @@ var Kupmios = class {
1342
1351
  schema,
1343
1352
  this.options.ogmiosHeader
1344
1353
  ),
1345
- Effect2.provide(FetchHttpClient.layer),
1354
+ Effect2.provide(this.httpLayer),
1346
1355
  Effect2.timeout(this.requestTimeoutMs),
1347
1356
  catchProviderError("ogmios", "submitTransaction")
1348
1357
  ),
@@ -1375,7 +1384,7 @@ var Kupmios = class {
1375
1384
  schema,
1376
1385
  this.options.ogmiosHeader
1377
1386
  ),
1378
- Effect2.provide(FetchHttpClient.layer),
1387
+ Effect2.provide(this.httpLayer),
1379
1388
  Effect2.timeout(this.requestTimeoutMs),
1380
1389
  catchProviderError("ogmios", "evaluateTransaction")
1381
1390
  ),
@@ -1486,9 +1495,210 @@ import {
1486
1495
  generateSeedPhrase,
1487
1496
  PROTOCOL_PARAMETERS_DEFAULT
1488
1497
  } from "@lucid-evolution/utils";
1489
- import { coreToUtxo, getAddressDetails } from "@lucid-evolution/utils";
1490
- import { freeCML, fromHex as fromHex2, withCMLScope } from "@lucid-evolution/core-utils";
1498
+ import {
1499
+ coreToUtxo,
1500
+ getAddressDetails as getAddressDetails2,
1501
+ ScriptCache,
1502
+ valueToAssets
1503
+ } from "@lucid-evolution/utils";
1504
+ import { fromHex as fromHex2, withCMLScope } from "@lucid-evolution/core-utils";
1491
1505
  import { walletFromSeed } from "@lucid-evolution/wallet";
1506
+
1507
+ // src/internal/emulator-ledger.ts
1508
+ import { getAddressDetails } from "@lucid-evolution/utils";
1509
+ var isUnorderedKey = (key) => {
1510
+ if (key === "__proto__") return true;
1511
+ if (key.length > 10) return false;
1512
+ const index = Number(key);
1513
+ return Number.isInteger(index) && index < 2 ** 32 - 1 && String(index) === key;
1514
+ };
1515
+ var EmulatorLedger = class {
1516
+ #record = {};
1517
+ #exposed = false;
1518
+ /** Record keys in record order; `undefined` marks a deleted slot. */
1519
+ #keys = [];
1520
+ /** Record entries, parallel to `#keys`. */
1521
+ #entries = [];
1522
+ #slots = /* @__PURE__ */ new Map();
1523
+ #holes = 0;
1524
+ /** Per slot, the address whose payment hash `#slotHashes` holds. */
1525
+ #slotHashAddresses = [];
1526
+ #slotHashes = [];
1527
+ #paymentHashes = /* @__PURE__ */ new Map();
1528
+ /** The record, for internal reads that do not let it escape. */
1529
+ get record() {
1530
+ return this.#record;
1531
+ }
1532
+ /** Returns the record to a caller, who may then change it at any time. */
1533
+ expose() {
1534
+ this.#dropMirror();
1535
+ return this.#record;
1536
+ }
1537
+ /** Adopts a record supplied by a caller. */
1538
+ replace(record) {
1539
+ this.#record = record;
1540
+ this.#dropMirror();
1541
+ }
1542
+ get(outRef) {
1543
+ return this.#record[outRef];
1544
+ }
1545
+ set(outRef, entry) {
1546
+ this.#record[outRef] = entry;
1547
+ if (this.#exposed) return;
1548
+ if (isUnorderedKey(outRef)) {
1549
+ this.#dropMirror();
1550
+ return;
1551
+ }
1552
+ const slot = this.#slots.get(outRef);
1553
+ if (slot === void 0) {
1554
+ this.#slots.set(outRef, this.#keys.length);
1555
+ this.#keys.push(outRef);
1556
+ this.#entries.push(entry);
1557
+ this.#slotHashAddresses.push(void 0);
1558
+ this.#slotHashes.push(void 0);
1559
+ } else {
1560
+ this.#entries[slot] = entry;
1561
+ }
1562
+ }
1563
+ /**
1564
+ * Moves the mempool into the record, then deletes every entry marked
1565
+ * spent, as the emulator always has.
1566
+ */
1567
+ applyMempool(mempool) {
1568
+ for (const [outRef, { utxo, spent }] of Object.entries(mempool)) {
1569
+ this.set(outRef, { utxo, spent });
1570
+ }
1571
+ const record = this.#record;
1572
+ if (this.#exposed) {
1573
+ for (const [outRef, { spent }] of Object.entries(record)) {
1574
+ if (spent) delete record[outRef];
1575
+ }
1576
+ return;
1577
+ }
1578
+ const keys = this.#keys;
1579
+ const entries = this.#entries;
1580
+ for (let slot = 0; slot < entries.length; slot++) {
1581
+ const entry = entries[slot];
1582
+ if (entry === void 0 || !entry.spent) continue;
1583
+ const outRef = keys[slot];
1584
+ delete record[outRef];
1585
+ this.#slots.delete(outRef);
1586
+ keys[slot] = void 0;
1587
+ entries[slot] = void 0;
1588
+ this.#holes++;
1589
+ }
1590
+ if (this.#holes > 64 && this.#holes * 2 > entries.length) this.#compact();
1591
+ }
1592
+ /**
1593
+ * Unspent UTxOs at an address or payment credential, optionally holding
1594
+ * `unit`, in record order.
1595
+ */
1596
+ utxosAt(addressOrCredential, unit) {
1597
+ const utxos = [];
1598
+ const entries = this.#inOrder();
1599
+ if (typeof addressOrCredential === "string") {
1600
+ for (let i = 0; i < entries.length; i++) {
1601
+ const entry = entries[i];
1602
+ if (entry === void 0 && !this.#exposed) continue;
1603
+ const { utxo, spent } = entry;
1604
+ if (!spent && utxo.address === addressOrCredential && (unit === void 0 || utxo.assets[unit] > 0n)) {
1605
+ utxos.push(utxo);
1606
+ }
1607
+ }
1608
+ return utxos;
1609
+ }
1610
+ const hash = addressOrCredential.hash;
1611
+ const hashAddresses = this.#slotHashAddresses;
1612
+ const hashes = this.#slotHashes;
1613
+ for (let i = 0; i < entries.length; i++) {
1614
+ const entry = entries[i];
1615
+ if (entry === void 0 && !this.#exposed) continue;
1616
+ const { utxo, spent } = entry;
1617
+ if (spent) continue;
1618
+ const address = utxo.address;
1619
+ let paymentHash;
1620
+ if (this.#exposed) {
1621
+ paymentHash = this.#paymentHashOf(address);
1622
+ } else if (hashAddresses[i] === address) {
1623
+ paymentHash = hashes[i];
1624
+ } else {
1625
+ paymentHash = this.#paymentHashOf(address);
1626
+ hashAddresses[i] = address;
1627
+ hashes[i] = paymentHash;
1628
+ }
1629
+ if (paymentHash === hash && (unit === void 0 || utxo.assets[unit] > 0n)) {
1630
+ utxos.push(utxo);
1631
+ }
1632
+ }
1633
+ return utxos;
1634
+ }
1635
+ /** Unspent UTxOs holding `unit`, in record order. */
1636
+ utxosWithUnit(unit) {
1637
+ const utxos = [];
1638
+ const entries = this.#inOrder();
1639
+ for (let i = 0; i < entries.length; i++) {
1640
+ const entry = entries[i];
1641
+ if (entry === void 0 && !this.#exposed) continue;
1642
+ const { utxo, spent } = entry;
1643
+ if (!spent && utxo.assets[unit] > 0n) utxos.push(utxo);
1644
+ }
1645
+ return utxos;
1646
+ }
1647
+ /**
1648
+ * The record's entries in record order. From the mirror, deleted slots
1649
+ * are `undefined`; from an exposed record, every value is as stored, so a
1650
+ * malformed entry fails a query just as a scan of the record would.
1651
+ */
1652
+ #inOrder() {
1653
+ if (!this.#exposed) return this.#entries;
1654
+ const record = this.#record;
1655
+ const keys = Object.keys(record);
1656
+ const entries = new Array(keys.length);
1657
+ for (let i = 0; i < keys.length; i++) entries[i] = record[keys[i]];
1658
+ return entries;
1659
+ }
1660
+ /** Payment credential hash of an address; parse errors propagate. */
1661
+ #paymentHashOf(address) {
1662
+ if (this.#paymentHashes.has(address))
1663
+ return this.#paymentHashes.get(address);
1664
+ const hash = getAddressDetails(address).paymentCredential?.hash;
1665
+ this.#paymentHashes.set(address, hash);
1666
+ return hash;
1667
+ }
1668
+ #compact() {
1669
+ const keys = [];
1670
+ const entries = [];
1671
+ const hashAddresses = [];
1672
+ const hashes = [];
1673
+ this.#slots.clear();
1674
+ for (let slot = 0; slot < this.#entries.length; slot++) {
1675
+ const entry = this.#entries[slot];
1676
+ if (entry === void 0) continue;
1677
+ const outRef = this.#keys[slot];
1678
+ this.#slots.set(outRef, keys.length);
1679
+ keys.push(outRef);
1680
+ entries.push(entry);
1681
+ hashAddresses.push(this.#slotHashAddresses[slot]);
1682
+ hashes.push(this.#slotHashes[slot]);
1683
+ }
1684
+ this.#keys = keys;
1685
+ this.#entries = entries;
1686
+ this.#slotHashAddresses = hashAddresses;
1687
+ this.#slotHashes = hashes;
1688
+ this.#holes = 0;
1689
+ }
1690
+ #dropMirror() {
1691
+ this.#exposed = true;
1692
+ this.#keys = [];
1693
+ this.#entries = [];
1694
+ this.#slots.clear();
1695
+ this.#slotHashAddresses = [];
1696
+ this.#slotHashes = [];
1697
+ this.#holes = 0;
1698
+ }
1699
+ };
1700
+
1701
+ // src/emulator.ts
1492
1702
  var EMULATOR_PROVIDER_BRAND = Symbol.for(
1493
1703
  "@lucid-evolution/provider/Emulator"
1494
1704
  );
@@ -1526,7 +1736,13 @@ function generateEmulatorAccount(assets) {
1526
1736
  var DEFAULT_PROTOCOL_MAJOR_VERSION = 11;
1527
1737
  var Emulator = class {
1528
1738
  [EMULATOR_PROVIDER_BRAND] = true;
1529
- ledger;
1739
+ #confirmed = new EmulatorLedger();
1740
+ #ledgerProperty = Object.defineProperty(this, "ledger", {
1741
+ configurable: true,
1742
+ enumerable: true,
1743
+ get: () => this.#confirmed.expose(),
1744
+ set: (entries) => this.#confirmed.replace(entries)
1745
+ });
1530
1746
  mempool = {};
1531
1747
  /**
1532
1748
  * Only stake key registrations/delegations and rewards are tracked.
@@ -1539,13 +1755,37 @@ var Emulator = class {
1539
1755
  protocolParameters;
1540
1756
  datumTable = {};
1541
1757
  treasury;
1542
- transactionHistory = {};
1758
+ #history = {};
1759
+ /** Whether a caller holds `transactionHistory`, and may edit it. */
1760
+ #historyExposed = false;
1761
+ #historyProperty = Object.defineProperty(this, "transactionHistory", {
1762
+ configurable: true,
1763
+ enumerable: true,
1764
+ get: () => {
1765
+ this.#historyExposed = true;
1766
+ return this.#history;
1767
+ },
1768
+ set: (history) => {
1769
+ this.#historyExposed = true;
1770
+ this.#history = history;
1771
+ }
1772
+ });
1773
+ /**
1774
+ * Transactions submitted since the last block. While no caller holds
1775
+ * `transactionHistory`, these are its only pending entries.
1776
+ */
1777
+ #pendingTxHashes = [];
1778
+ /**
1779
+ * Script hashes of reference scripts, keyed by type and CBOR. A plain Map
1780
+ * keyed by long script text puts every script of the same length in one
1781
+ * hash bucket; `ScriptCache` keys a fingerprint and is bounded.
1782
+ */
1783
+ #scriptRefHashes = new ScriptCache(4096, 64 * 1024 * 1024);
1543
1784
  constructor(accounts, protocolParameters = PROTOCOL_PARAMETERS_DEFAULT, treasury = 0n) {
1544
1785
  const GENESIS_HASH = "00".repeat(32);
1545
1786
  this.blockHeight = 0;
1546
1787
  this.slot = 0;
1547
1788
  this.time = Date.now();
1548
- this.ledger = {};
1549
1789
  accounts.forEach(({ address, assets, outputData }, index) => {
1550
1790
  if ([outputData?.hash, outputData?.asHash, outputData?.inline].filter(
1551
1791
  (b) => b
@@ -1554,7 +1794,7 @@ var Emulator = class {
1554
1794
  "Not allowed to set hash, asHash and inline at the same time."
1555
1795
  );
1556
1796
  }
1557
- this.ledger[GENESIS_HASH + index] = {
1797
+ this.#confirmed.set(GENESIS_HASH + index, {
1558
1798
  utxo: {
1559
1799
  txHash: GENESIS_HASH,
1560
1800
  outputIndex: index,
@@ -1567,7 +1807,7 @@ var Emulator = class {
1567
1807
  scriptRef: outputData?.scriptRef
1568
1808
  },
1569
1809
  spent: false
1570
- };
1810
+ });
1571
1811
  });
1572
1812
  this.protocolParameters = protocolParameters;
1573
1813
  this.treasury = treasury;
@@ -1575,16 +1815,28 @@ var Emulator = class {
1575
1815
  now() {
1576
1816
  return this.time;
1577
1817
  }
1818
+ /** Confirms every pending transaction in `transactionHistory`. */
1578
1819
  confirmPendingTransactions(blockHeight, slot) {
1579
- for (const [txHash, status] of Object.entries(this.transactionHistory)) {
1580
- if (status.status === "pending") {
1581
- this.transactionHistory[txHash] = {
1582
- status: "confirmed",
1583
- blockHeight,
1584
- slot
1585
- };
1820
+ const history = this.#history;
1821
+ if (this.#historyExposed) {
1822
+ for (const [txHash, { status }] of Object.entries(history)) {
1823
+ if (status === "pending") {
1824
+ history[txHash] = { status: "confirmed", blockHeight, slot };
1825
+ }
1826
+ }
1827
+ } else {
1828
+ for (const txHash of this.#pendingTxHashes) {
1829
+ if (history[txHash].status === "pending") {
1830
+ history[txHash] = { status: "confirmed", blockHeight, slot };
1831
+ }
1586
1832
  }
1587
1833
  }
1834
+ this.#pendingTxHashes = [];
1835
+ }
1836
+ /** Moves the mempool into the ledger and drops spent entries. */
1837
+ applyMempool() {
1838
+ this.#confirmed.applyMempool(this.mempool);
1839
+ this.mempool = {};
1588
1840
  }
1589
1841
  awaitSlot(length = 1) {
1590
1842
  this.slot += length;
@@ -1596,13 +1848,7 @@ var Emulator = class {
1596
1848
  currentHeight + 1,
1597
1849
  (currentHeight + 1) * 20
1598
1850
  );
1599
- for (const [outRef, { utxo, spent }] of Object.entries(this.mempool)) {
1600
- this.ledger[outRef] = { utxo, spent };
1601
- }
1602
- for (const [outRef, { spent }] of Object.entries(this.ledger)) {
1603
- if (spent) delete this.ledger[outRef];
1604
- }
1605
- this.mempool = {};
1851
+ this.applyMempool();
1606
1852
  }
1607
1853
  }
1608
1854
  awaitBlock(height = 1) {
@@ -1614,27 +1860,10 @@ var Emulator = class {
1614
1860
  if (height > 0) {
1615
1861
  this.confirmPendingTransactions(previousHeight + 1, previousSlot + 20);
1616
1862
  }
1617
- for (const [outRef, { utxo, spent }] of Object.entries(this.mempool)) {
1618
- this.ledger[outRef] = { utxo, spent };
1619
- }
1620
- for (const [outRef, { spent }] of Object.entries(this.ledger)) {
1621
- if (spent) delete this.ledger[outRef];
1622
- }
1623
- this.mempool = {};
1863
+ this.applyMempool();
1624
1864
  }
1625
1865
  getUtxos(addressOrCredential) {
1626
- const utxos = Object.values(this.ledger).flatMap(
1627
- ({ utxo, spent }) => {
1628
- if (spent) return [];
1629
- if (typeof addressOrCredential === "string") {
1630
- return addressOrCredential === utxo.address ? utxo : [];
1631
- } else {
1632
- const { paymentCredential } = getAddressDetails(utxo.address);
1633
- return paymentCredential?.hash === addressOrCredential.hash ? utxo : [];
1634
- }
1635
- }
1636
- );
1637
- return Promise.resolve(utxos);
1866
+ return Promise.resolve(this.#confirmed.utxosAt(addressOrCredential));
1638
1867
  }
1639
1868
  getProtocolParameters() {
1640
1869
  return Promise.resolve(this.protocolParameters);
@@ -1646,31 +1875,18 @@ var Emulator = class {
1646
1875
  return Promise.resolve(this.datumTable[datumHash]);
1647
1876
  }
1648
1877
  getUtxosWithUnit(addressOrCredential, unit) {
1649
- const utxos = Object.values(this.ledger).flatMap(
1650
- ({ utxo, spent }) => {
1651
- if (spent) return [];
1652
- if (typeof addressOrCredential === "string") {
1653
- return addressOrCredential === utxo.address && utxo.assets[unit] > 0n ? utxo : [];
1654
- } else {
1655
- const { paymentCredential } = getAddressDetails(utxo.address);
1656
- return paymentCredential?.hash === addressOrCredential.hash && utxo.assets[unit] > 0n ? utxo : [];
1657
- }
1658
- }
1659
- );
1660
- return Promise.resolve(utxos);
1878
+ return Promise.resolve(this.#confirmed.utxosAt(addressOrCredential, unit));
1661
1879
  }
1662
1880
  getUtxosByOutRef(outRefs) {
1663
1881
  return Promise.resolve(
1664
1882
  outRefs.flatMap((outRef) => {
1665
- const entry = this.ledger[outRef.txHash + outRef.outputIndex];
1883
+ const entry = this.#confirmed.get(outRef.txHash + outRef.outputIndex);
1666
1884
  return entry && !entry.spent ? entry.utxo : [];
1667
1885
  })
1668
1886
  );
1669
1887
  }
1670
1888
  getUtxoByUnit(unit) {
1671
- const utxos = Object.values(this.ledger).flatMap(
1672
- ({ utxo, spent }) => !spent && utxo.assets[unit] > 0n ? utxo : []
1673
- );
1889
+ const utxos = this.#confirmed.utxosWithUnit(unit);
1674
1890
  if (utxos.length > 1) {
1675
1891
  throw new Error("Unit needs to be an NFT or only held by one address.");
1676
1892
  }
@@ -1691,7 +1907,7 @@ var Emulator = class {
1691
1907
  });
1692
1908
  }
1693
1909
  awaitTx(txHash) {
1694
- if (this.transactionHistory[txHash]?.status === "pending") {
1910
+ if (this.#history[txHash]?.status === "pending") {
1695
1911
  this.awaitBlock();
1696
1912
  return Promise.resolve(true);
1697
1913
  }
@@ -1703,7 +1919,7 @@ var Emulator = class {
1703
1919
  options.signal.reason instanceof Error ? options.signal.reason : new DOMException("The operation was aborted.", "AbortError")
1704
1920
  );
1705
1921
  }
1706
- const status = this.transactionHistory[txHash];
1922
+ const status = this.#history[txHash];
1707
1923
  if (!status) return Promise.resolve({ status: "not_found", txHash });
1708
1924
  if (status.status === "pending") {
1709
1925
  return Promise.resolve({ status: "pending", txHash });
@@ -1741,10 +1957,14 @@ var Emulator = class {
1741
1957
  this.awaitBlock();
1742
1958
  }
1743
1959
  submitTx(tx) {
1744
- const desTx = CML.Transaction.from_cbor_hex(tx);
1745
- const body = desTx.body();
1746
- const witnesses = desTx.witness_set();
1747
- const datums = witnesses.plutus_datums();
1960
+ return withCMLScope((own) => Promise.resolve(this.applyTx(tx, own)));
1961
+ }
1962
+ /** Validates `tx` and applies it to the mempool; returns its hash. */
1963
+ applyTx(tx, own) {
1964
+ const desTx = own(CML.Transaction.from_cbor_hex(tx));
1965
+ const body = own(desTx.body());
1966
+ const witnesses = own(desTx.witness_set());
1967
+ const datums = own(witnesses.plutus_datums());
1748
1968
  const txHash = CML.hash_transaction(body).to_hex();
1749
1969
  const lowerBound = body.validity_interval_start() ? parseInt(body.validity_interval_start().toString()) : null;
1750
1970
  const upperBound = body.ttl() ? parseInt(body.ttl().toString()) : null;
@@ -1778,24 +1998,24 @@ var Emulator = class {
1778
1998
  const datumTable = (() => {
1779
1999
  const table = {};
1780
2000
  for (let i = 0; i < (datums?.len() || 0); i++) {
1781
- withCMLScope((own) => {
1782
- const datum = own(datums.get(i));
1783
- const datumHash = own(CML.hash_plutus_data(datum)).to_hex();
2001
+ withCMLScope((own2) => {
2002
+ const datum = own2(datums.get(i));
2003
+ const datumHash = own2(CML.hash_plutus_data(datum)).to_hex();
1784
2004
  table[datumHash] = datum.to_cbor_hex();
1785
2005
  });
1786
2006
  }
1787
2007
  return table;
1788
2008
  })();
1789
2009
  const consumedHashes = /* @__PURE__ */ new Set();
1790
- const keyHashes = withCMLScope((own) => {
2010
+ const keyHashList = withCMLScope((own2) => {
1791
2011
  const keyHashes2 = [];
1792
- const vkeyWitnesses = own(witnesses.vkeywitnesses());
2012
+ const vkeyWitnesses = own2(witnesses.vkeywitnesses());
1793
2013
  for (let i = 0; i < (vkeyWitnesses?.len() || 0); i++) {
1794
- withCMLScope((own2) => {
1795
- const witness = own2(vkeyWitnesses.get(i));
1796
- const publicKey = own2(witness.vkey());
1797
- const keyHash = own2(publicKey.hash()).to_hex();
1798
- if (!publicKey.verify(fromHex2(txHash), own2(witness.ed25519_signature()))) {
2014
+ withCMLScope((own3) => {
2015
+ const witness = own3(vkeyWitnesses.get(i));
2016
+ const publicKey = own3(witness.vkey());
2017
+ const keyHash = own3(publicKey.hash()).to_hex();
2018
+ if (!publicKey.verify(fromHex2(txHash), own3(witness.ed25519_signature()))) {
1799
2019
  throw new Error(`Invalid vkey witness. Key hash: ${keyHash}`);
1800
2020
  }
1801
2021
  keyHashes2.push(keyHash);
@@ -1803,19 +2023,20 @@ var Emulator = class {
1803
2023
  }
1804
2024
  return keyHashes2;
1805
2025
  });
1806
- const edKeyHashes = CML.Ed25519KeyHashList.new();
1807
- keyHashes.forEach(
2026
+ const keyHashes = new Set(keyHashList);
2027
+ const edKeyHashes = own(CML.Ed25519KeyHashList.new());
2028
+ keyHashList.forEach(
1808
2029
  (keyHash) => withCMLScope(
1809
- (own) => edKeyHashes.add(own(CML.Ed25519KeyHash.from_hex(keyHash)))
2030
+ (own2) => edKeyHashes.add(own2(CML.Ed25519KeyHash.from_hex(keyHash)))
1810
2031
  )
1811
2032
  );
1812
- const nativeHashes = withCMLScope((own) => {
2033
+ const nativeHashList = withCMLScope((own2) => {
1813
2034
  const scriptHashes = [];
1814
- const nativeScripts = own(witnesses.native_scripts());
2035
+ const nativeScripts = own2(witnesses.native_scripts());
1815
2036
  for (let i = 0; i < (nativeScripts?.len() || 0); i++) {
1816
- withCMLScope((own2) => {
1817
- const witness = own2(nativeScripts.get(i));
1818
- const scriptHash = own2(witness.hash()).to_hex();
2037
+ withCMLScope((own3) => {
2038
+ const witness = own3(nativeScripts.get(i));
2039
+ const scriptHash = own3(witness.hash()).to_hex();
1819
2040
  if (!witness.verify(
1820
2041
  Number.isInteger(lowerBound) ? BigInt(lowerBound) : void 0,
1821
2042
  Number.isInteger(upperBound) ? BigInt(upperBound) : void 0,
@@ -1825,9 +2046,9 @@ var Emulator = class {
1825
2046
  `Invalid native script witness. Script hash: ${scriptHash}`
1826
2047
  );
1827
2048
  }
1828
- const requiredSigners = own2(witness.get_required_signers());
1829
- for (let j = 0; j < requiredSigners.len(); j++) {
1830
- const keyHash = own2(requiredSigners.get(j)).to_hex();
2049
+ const requiredSigners2 = own3(witness.get_required_signers());
2050
+ for (let j = 0; j < requiredSigners2.len(); j++) {
2051
+ const keyHash = own3(requiredSigners2.get(j)).to_hex();
1831
2052
  consumedHashes.add(keyHash);
1832
2053
  }
1833
2054
  scriptHashes.push(scriptHash);
@@ -1835,18 +2056,18 @@ var Emulator = class {
1835
2056
  }
1836
2057
  return scriptHashes;
1837
2058
  });
1838
- edKeyHashes.free();
2059
+ const nativeHashes = new Set(nativeHashList);
1839
2060
  const nativeHashesOptional = {};
1840
- const plutusHashesOptional = [];
2061
+ const plutusHashesOptional = /* @__PURE__ */ new Set();
1841
2062
  const plutusV3Hashes = /* @__PURE__ */ new Set();
1842
- const plutusHashes = withCMLScope((own) => {
2063
+ const plutusHashList = withCMLScope((own2) => {
1843
2064
  const scriptHashes = [];
1844
2065
  const collectHashes = (scripts, isPlutusV3 = false) => {
1845
- own(scripts);
2066
+ own2(scripts);
1846
2067
  for (let i = 0; i < (scripts?.len() || 0); i++) {
1847
- withCMLScope((own2) => {
1848
- const script = own2(scripts.get(i));
1849
- const scriptHash = own2(script.hash()).to_hex();
2068
+ withCMLScope((own3) => {
2069
+ const script = own3(scripts.get(i));
2070
+ const scriptHash = own3(script.hash()).to_hex();
1850
2071
  scriptHashes.push(scriptHash);
1851
2072
  if (isPlutusV3) plutusV3Hashes.add(scriptHash);
1852
2073
  });
@@ -1857,16 +2078,26 @@ var Emulator = class {
1857
2078
  collectHashes(witnesses.plutus_v3_scripts(), true);
1858
2079
  return scriptHashes;
1859
2080
  });
1860
- const inputs = body.inputs();
2081
+ const plutusHashes = new Set(plutusHashList);
2082
+ const collectScriptRef = (scriptRef) => {
2083
+ const scriptHash = this.scriptRefHash(scriptRef);
2084
+ if (scriptRef.type === "Native") {
2085
+ nativeHashesOptional[scriptHash] = scriptRef.script;
2086
+ return;
2087
+ }
2088
+ plutusHashesOptional.add(scriptHash);
2089
+ if (scriptRef.type === "PlutusV3") plutusV3Hashes.add(scriptHash);
2090
+ };
2091
+ const inputs = own(body.inputs());
1861
2092
  const resolvedInputs = [];
1862
2093
  const inputOutRefs = /* @__PURE__ */ new Set();
1863
2094
  for (let i = 0; i < inputs.len(); i++) {
1864
- const outRef = withCMLScope((own) => {
1865
- const input = own(inputs.get(i));
1866
- return own(input.transaction_id()).to_hex() + input.index().toString();
2095
+ const outRef = withCMLScope((own2) => {
2096
+ const input = own2(inputs.get(i));
2097
+ return own2(input.transaction_id()).to_hex() + input.index().toString();
1867
2098
  });
1868
2099
  inputOutRefs.add(outRef);
1869
- const entryLedger = this.ledger[outRef];
2100
+ const entryLedger = this.#confirmed.get(outRef);
1870
2101
  const { entry, type } = !entryLedger ? { entry: this.mempool[outRef], type: "Mempool" } : { entry: entryLedger, type: "Ledger" };
1871
2102
  if (!entry || entry.spent) {
1872
2103
  throw new Error(
@@ -1878,52 +2109,18 @@ It does not exist or was already spent.`
1878
2109
  );
1879
2110
  }
1880
2111
  const scriptRef = entry.utxo.scriptRef;
1881
- if (scriptRef) {
1882
- switch (scriptRef.type) {
1883
- case "Native": {
1884
- const script = CML.NativeScript.from_cbor_bytes(
1885
- fromHex2(scriptRef.script)
1886
- );
1887
- nativeHashesOptional[script.hash().to_hex()] = script;
1888
- break;
1889
- }
1890
- case "PlutusV1": {
1891
- const script = CML.PlutusScript.from_v1(
1892
- CML.PlutusV1Script.from_cbor_bytes(fromHex2(scriptRef.script))
1893
- );
1894
- plutusHashesOptional.push(script.hash().to_hex());
1895
- break;
1896
- }
1897
- case "PlutusV2": {
1898
- const script = CML.PlutusScript.from_v2(
1899
- CML.PlutusV2Script.from_cbor_bytes(fromHex2(scriptRef.script))
1900
- );
1901
- plutusHashesOptional.push(script.hash().to_hex());
1902
- break;
1903
- }
1904
- case "PlutusV3": {
1905
- const script = CML.PlutusScript.from_v3(
1906
- CML.PlutusV3Script.from_cbor_bytes(fromHex2(scriptRef.script))
1907
- );
1908
- const scriptHash = script.hash().to_hex();
1909
- plutusHashesOptional.push(scriptHash);
1910
- plutusV3Hashes.add(scriptHash);
1911
- break;
1912
- }
1913
- }
1914
- }
2112
+ if (scriptRef) collectScriptRef(scriptRef);
1915
2113
  if (entry.utxo.datumHash) consumedHashes.add(entry.utxo.datumHash);
1916
2114
  resolvedInputs.push({ entry, type });
1917
2115
  }
1918
- inputs.free();
1919
- const referenceInputs = body.reference_inputs();
2116
+ const referenceInputs = own(body.reference_inputs());
1920
2117
  const nonDisjointRefInputs = [];
1921
2118
  for (let i = 0; i < (referenceInputs?.len() || 0); i++) {
1922
- const outRef = withCMLScope((own) => {
1923
- const input = own(referenceInputs.get(i));
1924
- return own(input.transaction_id()).to_hex() + input.index().toString();
2119
+ const outRef = withCMLScope((own2) => {
2120
+ const input = own2(referenceInputs.get(i));
2121
+ return own2(input.transaction_id()).to_hex() + input.index().toString();
1925
2122
  });
1926
- const entry = this.ledger[outRef] || this.mempool[outRef];
2123
+ const entry = this.#confirmed.get(outRef) || this.mempool[outRef];
1927
2124
  if (!entry || entry.spent) {
1928
2125
  throw new Error(
1929
2126
  `Could not read UTxO: ${JSON.stringify({
@@ -1939,44 +2136,11 @@ It does not exist or was already spent.`
1939
2136
  );
1940
2137
  }
1941
2138
  const scriptRef = entry.utxo.scriptRef;
1942
- if (scriptRef) {
1943
- switch (scriptRef.type) {
1944
- case "Native": {
1945
- const script = CML.NativeScript.from_cbor_bytes(
1946
- fromHex2(scriptRef.script)
1947
- );
1948
- nativeHashesOptional[script.hash().to_hex()] = script;
1949
- break;
1950
- }
1951
- case "PlutusV1": {
1952
- const script = CML.PlutusScript.from_v1(
1953
- CML.PlutusV1Script.from_cbor_bytes(fromHex2(scriptRef.script))
1954
- );
1955
- plutusHashesOptional.push(script.hash().to_hex());
1956
- break;
1957
- }
1958
- case "PlutusV2": {
1959
- const script = CML.PlutusScript.from_v2(
1960
- CML.PlutusV2Script.from_cbor_bytes(fromHex2(scriptRef.script))
1961
- );
1962
- plutusHashesOptional.push(script.hash().to_hex());
1963
- break;
1964
- }
1965
- case "PlutusV3": {
1966
- const script = CML.PlutusScript.from_v3(
1967
- CML.PlutusV3Script.from_cbor_bytes(fromHex2(scriptRef.script))
1968
- );
1969
- const scriptHash = script.hash().to_hex();
1970
- plutusHashesOptional.push(scriptHash);
1971
- plutusV3Hashes.add(scriptHash);
1972
- break;
1973
- }
1974
- }
1975
- }
2139
+ if (scriptRef) collectScriptRef(scriptRef);
1976
2140
  if (entry.utxo.datumHash) consumedHashes.add(entry.utxo.datumHash);
1977
2141
  }
1978
- referenceInputs?.free();
1979
- const redeemers = (() => {
2142
+ const redeemerKey = (tag, index) => `${tag}:${index}`;
2143
+ const redeemers = withCMLScope((own2) => {
1980
2144
  const tagMap = {
1981
2145
  0: "Spend",
1982
2146
  1: "Mint",
@@ -1985,35 +2149,33 @@ It does not exist or was already spent.`
1985
2149
  4: "Proposing",
1986
2150
  5: "Voting"
1987
2151
  };
1988
- const collected = [];
1989
- const redeemers2 = witnesses.redeemers();
1990
- const arrLegacyRedeemer = redeemers2?.as_arr_legacy_redeemer();
2152
+ const collected = /* @__PURE__ */ new Set();
2153
+ const redeemers2 = own2(witnesses.redeemers());
2154
+ const arrLegacyRedeemer = own2(redeemers2?.as_arr_legacy_redeemer());
1991
2155
  if (arrLegacyRedeemer) {
1992
2156
  for (let i = 0; i < (arrLegacyRedeemer.len() || 0); i++) {
1993
- const redeemer = arrLegacyRedeemer.get(i);
1994
- collected.push({
1995
- tag: tagMap[redeemer.tag()],
1996
- index: Number(redeemer.index())
1997
- });
2157
+ const redeemer = own2(arrLegacyRedeemer.get(i));
2158
+ collected.add(
2159
+ redeemerKey(tagMap[redeemer.tag()], Number(redeemer.index()))
2160
+ );
1998
2161
  }
1999
2162
  }
2000
- const mapRedeemerKeyToRedeemerVal = redeemers2?.as_map_redeemer_key_to_redeemer_val();
2163
+ const mapRedeemerKeyToRedeemerVal = own2(
2164
+ redeemers2?.as_map_redeemer_key_to_redeemer_val()
2165
+ );
2001
2166
  if (mapRedeemerKeyToRedeemerVal) {
2002
- const keys = mapRedeemerKeyToRedeemerVal.keys();
2167
+ const keys = own2(mapRedeemerKeyToRedeemerVal.keys());
2003
2168
  for (let i = 0; i < (keys.len() || 0); i++) {
2004
- const key = keys.get(i);
2005
- collected.push({
2006
- tag: tagMap[key.tag()],
2007
- index: Number(key.index())
2008
- });
2169
+ const key = own2(keys.get(i));
2170
+ collected.add(redeemerKey(tagMap[key.tag()], Number(key.index())));
2009
2171
  }
2010
2172
  }
2011
2173
  return collected;
2012
- })();
2174
+ });
2013
2175
  function checkAndConsumeHash(credential, tag, index) {
2014
2176
  switch (credential.type) {
2015
2177
  case "Key": {
2016
- if (!keyHashes.includes(credential.hash)) {
2178
+ if (!keyHashes.has(credential.hash)) {
2017
2179
  throw new Error(
2018
2180
  `Missing vkey witness. Key hash: ${credential.hash}`
2019
2181
  );
@@ -2022,28 +2184,29 @@ It does not exist or was already spent.`
2022
2184
  break;
2023
2185
  }
2024
2186
  case "Script": {
2025
- if (nativeHashes.includes(credential.hash)) {
2187
+ if (nativeHashes.has(credential.hash)) {
2026
2188
  consumedHashes.add(credential.hash);
2027
2189
  break;
2028
2190
  } else if (nativeHashesOptional[credential.hash]) {
2029
- if (!nativeHashesOptional[credential.hash].verify(
2030
- Number.isInteger(lowerBound) ? CML.BigInteger.from_str(
2031
- lowerBound.toString()
2032
- ).to_js_value() : void 0,
2033
- Number.isInteger(upperBound) ? CML.BigInteger.from_str(
2034
- upperBound.toString()
2035
- ).to_js_value() : void 0,
2036
- edKeyHashes
2037
- )) {
2191
+ const valid = withCMLScope(
2192
+ (own2) => own2(
2193
+ CML.NativeScript.from_cbor_hex(
2194
+ nativeHashesOptional[credential.hash]
2195
+ )
2196
+ ).verify(
2197
+ Number.isInteger(lowerBound) ? BigInt(lowerBound) : void 0,
2198
+ Number.isInteger(upperBound) ? BigInt(upperBound) : void 0,
2199
+ edKeyHashes
2200
+ )
2201
+ );
2202
+ if (!valid) {
2038
2203
  throw new Error(
2039
2204
  `Invalid native script witness. Script hash: ${credential.hash}`
2040
2205
  );
2041
2206
  }
2042
2207
  break;
2043
- } else if (plutusHashes.includes(credential.hash) || plutusHashesOptional.includes(credential.hash)) {
2044
- if (redeemers.find(
2045
- (redeemer) => redeemer.tag === tag && redeemer.index === index
2046
- )) {
2208
+ } else if (plutusHashes.has(credential.hash) || plutusHashesOptional.has(credential.hash)) {
2209
+ if (redeemers.has(redeemerKey(tag, index))) {
2047
2210
  consumedHashes.add(credential.hash);
2048
2211
  break;
2049
2212
  }
@@ -2054,13 +2217,14 @@ It does not exist or was already spent.`
2054
2217
  }
2055
2218
  }
2056
2219
  }
2057
- const collateralInputs = body.collateral_inputs();
2220
+ const collateralInputs = own(body.collateral_inputs());
2221
+ const collateralBalance = {};
2058
2222
  for (let i = 0; i < (collateralInputs?.len() || 0); i++) {
2059
- const outRef = withCMLScope((own) => {
2060
- const input = own(collateralInputs.get(i));
2061
- return own(input.transaction_id()).to_hex() + input.index().toString();
2223
+ const outRef = withCMLScope((own2) => {
2224
+ const input = own2(collateralInputs.get(i));
2225
+ return own2(input.transaction_id()).to_hex() + input.index().toString();
2062
2226
  });
2063
- const entry = this.ledger[outRef] || this.mempool[outRef];
2227
+ const entry = this.#confirmed.get(outRef) || this.mempool[outRef];
2064
2228
  if (!entry || entry.spent) {
2065
2229
  throw new Error(
2066
2230
  `Could not read UTxO: ${JSON.stringify({
@@ -2070,19 +2234,27 @@ It does not exist or was already spent.`
2070
2234
  It does not exist or was already spent.`
2071
2235
  );
2072
2236
  }
2073
- const { paymentCredential } = getAddressDetails(entry.utxo.address);
2237
+ const { paymentCredential } = getAddressDetails2(entry.utxo.address);
2074
2238
  if (paymentCredential?.type === "Script") {
2075
2239
  throw new Error("Collateral inputs can only contain vkeys.");
2076
2240
  }
2077
2241
  checkAndConsumeHash(paymentCredential, null, null);
2242
+ for (const [unit, amount] of Object.entries(entry.utxo.assets)) {
2243
+ collateralBalance[unit] = (collateralBalance[unit] ?? 0n) + amount;
2244
+ }
2078
2245
  }
2079
- collateralInputs?.free();
2080
- for (let i = 0; i < (body.required_signers()?.len() || 0); i++) {
2081
- const signer = body.required_signers().get(i);
2246
+ if (redeemers.size > 0) {
2247
+ this.checkCollateral(body, collateralBalance, own);
2248
+ }
2249
+ const requiredSigners = own(body.required_signers());
2250
+ for (let i = 0; i < (requiredSigners?.len() || 0); i++) {
2251
+ const signer = own(requiredSigners.get(i));
2082
2252
  checkAndConsumeHash({ type: "Key", hash: signer.to_hex() }, null, null);
2083
2253
  }
2084
- for (let index = 0; index < (body.mint()?.keys().len() || 0); index++) {
2085
- const policyId = body.mint().keys().get(index).to_hex();
2254
+ const mint = own(body.mint());
2255
+ const policyIds = own(mint?.keys());
2256
+ for (let index = 0; index < (policyIds?.len() || 0); index++) {
2257
+ const policyId = own(policyIds.get(index)).to_hex();
2086
2258
  checkAndConsumeHash({ type: "Script", hash: policyId }, "Mint", index);
2087
2259
  }
2088
2260
  const withdrawalRequests = [];
@@ -2092,7 +2264,7 @@ It does not exist or was already spent.`
2092
2264
  body.withdrawals().get(rawAddress).toString()
2093
2265
  );
2094
2266
  const rewardAddress = rawAddress.to_address().to_bech32(void 0);
2095
- const { stakeCredential } = getAddressDetails(rewardAddress);
2267
+ const { stakeCredential } = getAddressDetails2(rewardAddress);
2096
2268
  checkAndConsumeHash(stakeCredential, "Reward", index);
2097
2269
  if (this.chain[rewardAddress]?.delegation.rewards !== withdrawal) {
2098
2270
  throw new Error(
@@ -2131,7 +2303,7 @@ It does not exist or was already spent.`
2131
2303
  CML.NetworkInfo.testnet().network_id(),
2132
2304
  registration.stake_credential()
2133
2305
  ).to_address().to_bech32(void 0);
2134
- const { stakeCredential } = getAddressDetails(rewardAddress);
2306
+ const { stakeCredential } = getAddressDetails2(rewardAddress);
2135
2307
  checkAndConsumeHash(stakeCredential, "Cert", index);
2136
2308
  if (this.chain[rewardAddress]?.registeredStake) {
2137
2309
  throw new Error(
@@ -2147,7 +2319,7 @@ It does not exist or was already spent.`
2147
2319
  CML.NetworkInfo.testnet().network_id(),
2148
2320
  deregistration.stake_credential()
2149
2321
  ).to_address().to_bech32(void 0);
2150
- const { stakeCredential } = getAddressDetails(rewardAddress);
2322
+ const { stakeCredential } = getAddressDetails2(rewardAddress);
2151
2323
  checkAndConsumeHash(stakeCredential, "Cert", index);
2152
2324
  if (!this.chain[rewardAddress]?.registeredStake) {
2153
2325
  throw new Error(
@@ -2164,7 +2336,7 @@ It does not exist or was already spent.`
2164
2336
  delegation.stake_credential()
2165
2337
  ).to_address().to_bech32(void 0);
2166
2338
  const poolId = delegation.pool().to_bech32("pool");
2167
- const { stakeCredential } = getAddressDetails(rewardAddress);
2339
+ const { stakeCredential } = getAddressDetails2(rewardAddress);
2168
2340
  checkAndConsumeHash(stakeCredential, "Cert", index);
2169
2341
  if (!this.chain[rewardAddress]?.registeredStake && !certRequests.find(
2170
2342
  (request) => request.type === "Registration" && request.rewardAddress === rewardAddress
@@ -2339,19 +2511,19 @@ It does not exist or was already spent.`
2339
2511
  }
2340
2512
  }
2341
2513
  resolvedInputs.forEach(({ entry: { utxo } }, index) => {
2342
- const { paymentCredential } = getAddressDetails(utxo.address);
2514
+ const { paymentCredential } = getAddressDetails2(utxo.address);
2343
2515
  checkAndConsumeHash(paymentCredential, "Spend", index);
2344
2516
  });
2345
- const outputs = withCMLScope((own) => {
2517
+ const outputs = withCMLScope((own2) => {
2346
2518
  const collected = [];
2347
- const bodyOutputs = own(body.outputs());
2519
+ const bodyOutputs = own2(body.outputs());
2348
2520
  for (let i = 0; i < bodyOutputs.len(); i++) {
2349
- const output = own(bodyOutputs.get(i));
2350
- const unspentOutput = own(
2521
+ const output = own2(bodyOutputs.get(i));
2522
+ const unspentOutput = own2(
2351
2523
  CML.TransactionUnspentOutput.new(
2352
- own(
2524
+ own2(
2353
2525
  CML.TransactionInput.new(
2354
- own(CML.TransactionHash.from_hex(txHash)),
2526
+ own2(CML.TransactionHash.from_hex(txHash)),
2355
2527
  BigInt(i)
2356
2528
  )
2357
2529
  ),
@@ -2367,13 +2539,13 @@ It does not exist or was already spent.`
2367
2539
  }
2368
2540
  return collected;
2369
2541
  });
2370
- const [extraKeyHash] = keyHashes.filter(
2542
+ const [extraKeyHash] = keyHashList.filter(
2371
2543
  (keyHash) => !consumedHashes.has(keyHash)
2372
2544
  );
2373
2545
  if (extraKeyHash) {
2374
2546
  throw new Error(`Extraneous vkey witness. Key hash: ${extraKeyHash}`);
2375
2547
  }
2376
- const [extraNativeHash] = nativeHashes.filter(
2548
+ const [extraNativeHash] = nativeHashList.filter(
2377
2549
  (scriptHash) => !consumedHashes.has(scriptHash)
2378
2550
  );
2379
2551
  if (extraNativeHash) {
@@ -2381,7 +2553,7 @@ It does not exist or was already spent.`
2381
2553
  `Extraneous native script. Script hash: ${extraNativeHash}`
2382
2554
  );
2383
2555
  }
2384
- const [extraPlutusHash] = plutusHashes.filter(
2556
+ const [extraPlutusHash] = plutusHashList.filter(
2385
2557
  (scriptHash) => !consumedHashes.has(scriptHash)
2386
2558
  );
2387
2559
  if (extraPlutusHash) {
@@ -2412,11 +2584,8 @@ It does not exist or was already spent.`
2412
2584
  );
2413
2585
  }
2414
2586
  }
2415
- resolvedInputs.forEach(({ entry, type }) => {
2416
- const outRef = entry.utxo.txHash + entry.utxo.outputIndex;
2587
+ resolvedInputs.forEach(({ entry }) => {
2417
2588
  entry.spent = true;
2418
- if (type === "Ledger") this.ledger[outRef] = entry;
2419
- else if (type === "Mempool") this.mempool[outRef] = entry;
2420
2589
  });
2421
2590
  withdrawalRequests.forEach(({ rewardAddress, withdrawal }) => {
2422
2591
  this.chain[rewardAddress].delegation.rewards -= withdrawal;
@@ -2456,9 +2625,115 @@ It does not exist or was already spent.`
2456
2625
  for (const [datumHash, datum] of Object.entries(datumTable)) {
2457
2626
  this.datumTable[datumHash] = datum;
2458
2627
  }
2459
- this.transactionHistory[txHash] = { status: "pending" };
2460
- freeCML(datums, witnesses, body, desTx);
2461
- return Promise.resolve(txHash);
2628
+ this.#history[txHash] = { status: "pending" };
2629
+ this.#pendingTxHashes.push(txHash);
2630
+ return txHash;
2631
+ }
2632
+ /**
2633
+ * The ledger's collateral rules for a transaction with redeemers: at least
2634
+ * one and at most `maxCollateralInputs` collateral inputs, a balance (inputs
2635
+ * minus the collateral return) of ADA only that covers
2636
+ * `collateralPercentage` of the fee, a `total_collateral` field, when
2637
+ * present, equal to that balance, and a collateral return holding at least
2638
+ * its minimum ADA.
2639
+ */
2640
+ checkCollateral(body, collateralBalance, own) {
2641
+ const inputCount = own(body.collateral_inputs())?.len() ?? 0;
2642
+ if (inputCount === 0) {
2643
+ throw new Error(
2644
+ "NoCollateralInputs: a transaction that runs scripts needs collateral inputs."
2645
+ );
2646
+ }
2647
+ const { maxCollateralInputs, collateralPercentage } = this.protocolParameters;
2648
+ if (inputCount > maxCollateralInputs) {
2649
+ throw new Error(
2650
+ `TooManyCollateralInputs: ${inputCount} collateral inputs, but at most ${maxCollateralInputs} are allowed.`
2651
+ );
2652
+ }
2653
+ const balance = { ...collateralBalance };
2654
+ const collateralReturn = own(body.collateral_return());
2655
+ if (collateralReturn) {
2656
+ const minLovelace = CML.min_ada_required(
2657
+ collateralReturn,
2658
+ this.protocolParameters.coinsPerUtxoByte
2659
+ );
2660
+ const returnedLovelace = own(collateralReturn.amount()).coin();
2661
+ if (returnedLovelace < minLovelace) {
2662
+ throw new Error(
2663
+ `BabbageOutputTooSmallUTxO: collateral return holds ${returnedLovelace} Lovelace, but needs at least ${minLovelace} Lovelace.`
2664
+ );
2665
+ }
2666
+ const returned = valueToAssets(own(collateralReturn.amount()));
2667
+ for (const [unit, amount] of Object.entries(returned)) {
2668
+ balance[unit] = (balance[unit] ?? 0n) - amount;
2669
+ }
2670
+ }
2671
+ const nonAda = Object.entries(balance).filter(
2672
+ ([unit, amount]) => unit !== "lovelace" && amount !== 0n
2673
+ );
2674
+ if (nonAda.length > 0) {
2675
+ throw new Error(
2676
+ `CollateralContainsNonADA: collateral balance holds ${nonAda.map(([unit, amount]) => `${amount} ${unit}`).join(", ")}.`
2677
+ );
2678
+ }
2679
+ const collateral = balance.lovelace ?? 0n;
2680
+ const fee = body.fee();
2681
+ if (collateral * 100n < fee * BigInt(collateralPercentage)) {
2682
+ const required = (fee * BigInt(collateralPercentage) + 99n) / 100n;
2683
+ throw new Error(
2684
+ `InsufficientCollateral: collateral balance is ${collateral} Lovelace, but the fee of ${fee} requires ${required} Lovelace (${collateralPercentage}%).`
2685
+ );
2686
+ }
2687
+ const totalCollateral = body.total_collateral();
2688
+ if (totalCollateral !== void 0 && totalCollateral !== collateral) {
2689
+ throw new Error(
2690
+ `IncorrectTotalCollateralField: total collateral is ${totalCollateral} Lovelace, but the collateral balance is ${collateral} Lovelace.`
2691
+ );
2692
+ }
2693
+ }
2694
+ /** Hash of a reference script, computed once per distinct script. */
2695
+ scriptRefHash(scriptRef) {
2696
+ let scriptHash = this.#scriptRefHashes.get(
2697
+ scriptRef.type,
2698
+ scriptRef.script
2699
+ );
2700
+ if (scriptHash === void 0) {
2701
+ scriptHash = withCMLScope((own) => {
2702
+ const bytes = fromHex2(scriptRef.script);
2703
+ switch (scriptRef.type) {
2704
+ case "Native":
2705
+ return own(
2706
+ own(CML.NativeScript.from_cbor_bytes(bytes)).hash()
2707
+ ).to_hex();
2708
+ case "PlutusV1":
2709
+ return own(
2710
+ own(
2711
+ CML.PlutusScript.from_v1(
2712
+ own(CML.PlutusV1Script.from_cbor_bytes(bytes))
2713
+ )
2714
+ ).hash()
2715
+ ).to_hex();
2716
+ case "PlutusV2":
2717
+ return own(
2718
+ own(
2719
+ CML.PlutusScript.from_v2(
2720
+ own(CML.PlutusV2Script.from_cbor_bytes(bytes))
2721
+ )
2722
+ ).hash()
2723
+ ).to_hex();
2724
+ case "PlutusV3":
2725
+ return own(
2726
+ own(
2727
+ CML.PlutusScript.from_v3(
2728
+ own(CML.PlutusV3Script.from_cbor_bytes(bytes))
2729
+ )
2730
+ ).hash()
2731
+ ).to_hex();
2732
+ }
2733
+ });
2734
+ this.#scriptRefHashes.set(scriptRef.type, scriptRef.script, scriptHash);
2735
+ }
2736
+ return scriptHash;
2462
2737
  }
2463
2738
  async evaluateTx(tx, additionalUTxOs) {
2464
2739
  return withCMLScope((own) => {
@@ -2523,7 +2798,7 @@ It does not exist or was already spent.`
2523
2798
  }
2524
2799
  const totalBalances = {};
2525
2800
  const balances = {};
2526
- for (const { utxo } of Object.values(this.ledger)) {
2801
+ for (const { utxo } of Object.values(this.#confirmed.record)) {
2527
2802
  for (const [unit, quantity] of Object.entries(utxo.assets)) {
2528
2803
  if (!balances[utxo.address]) {
2529
2804
  balances[utxo.address] = { [unit]: quantity };
@@ -2576,377 +2851,14 @@ ${"\u2581".repeat(60)}
2576
2851
  }
2577
2852
  };
2578
2853
 
2579
- // src/maestro.ts
2580
- import {
2581
- applyDoubleCborEncoding as applyDoubleCborEncoding3,
2582
- scriptFromNative as scriptFromNative2,
2583
- utxoToCore
2584
- } from "@lucid-evolution/utils";
2585
- import { fromHex as fromHex3 } from "@lucid-evolution/core-utils";
2586
- var Maestro = class {
2587
- url;
2588
- apiKey;
2589
- turboSubmit;
2590
- constructor({ network, apiKey, turboSubmit = false }) {
2591
- this.url = `https://${network}.gomaestro-api.org/v1`;
2592
- this.apiKey = apiKey;
2593
- this.turboSubmit = turboSubmit;
2594
- }
2595
- async getProtocolParameters() {
2596
- const timestampedResult = await fetch(`${this.url}/protocol-parameters`, {
2597
- headers: this.commonHeaders()
2598
- }).then((res) => res.json());
2599
- const result = timestampedResult.data;
2600
- const decimalFromRationalString = (str) => {
2601
- const forwardSlashIndex = str.indexOf("/");
2602
- return parseInt(str.slice(0, forwardSlashIndex)) / parseInt(str.slice(forwardSlashIndex + 1));
2603
- };
2604
- return {
2605
- protocolMajorVersion: result.version?.major,
2606
- protocolMinorVersion: result.version?.minor,
2607
- minFeeA: parseInt(result.min_fee_coefficient),
2608
- minFeeB: parseInt(result.min_fee_constant.ada.lovelace),
2609
- maxTxSize: parseInt(result.max_transaction_size.bytes),
2610
- maxValSize: parseInt(result.max_value_size.bytes),
2611
- keyDeposit: BigInt(result.stake_credential_deposit.ada.lovelace),
2612
- poolDeposit: BigInt(result.stake_pool_deposit.ada.lovelace),
2613
- drepDeposit: BigInt(result.delegate_representative_deposit.ada.lovelace),
2614
- govActionDeposit: BigInt(result.governance_action_deposit.ada.lovelace),
2615
- priceMem: decimalFromRationalString(
2616
- result.script_execution_prices.memory
2617
- ),
2618
- priceStep: decimalFromRationalString(result.script_execution_prices.cpu),
2619
- maxTxExMem: BigInt(result.max_execution_units_per_transaction.memory),
2620
- maxTxExSteps: BigInt(result.max_execution_units_per_transaction.cpu),
2621
- coinsPerUtxoByte: BigInt(result.min_utxo_deposit_coefficient),
2622
- collateralPercentage: parseInt(result.collateral_percentage),
2623
- maxCollateralInputs: parseInt(result.max_collateral_inputs),
2624
- minFeeRefScriptCostPerByte: parseInt(
2625
- result.min_fee_reference_scripts.base
2626
- ),
2627
- costModels: {
2628
- PlutusV1: result.plutus_cost_models.plutus_v1,
2629
- PlutusV2: result.plutus_cost_models.plutus_v2,
2630
- PlutusV3: result.plutus_cost_models.plutus_v3
2631
- }
2632
- };
2633
- }
2634
- async getTreasury() {
2635
- throw new Error(
2636
- "Maestro does not expose a current treasury query. Pass currentTreasuryValue explicitly to donateToTreasury."
2637
- );
2638
- }
2639
- async getUtxosInternal(addressOrCredential, unit) {
2640
- const queryPredicate = (() => {
2641
- if (typeof addressOrCredential === "string") {
2642
- return "/addresses/" + addressOrCredential;
2643
- }
2644
- let credentialBech32Query = "/addresses/cred/";
2645
- credentialBech32Query += addressOrCredential.type === "Key" ? CML.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32(
2646
- "addr_vkh"
2647
- ) : CML.ScriptHash.from_hex(addressOrCredential.hash).to_bech32(
2648
- "addr_shared_vkh"
2649
- );
2650
- return credentialBech32Query;
2651
- })();
2652
- const qparams = new URLSearchParams({
2653
- count: "100",
2654
- ...unit && { asset: unit }
2655
- });
2656
- const result = await this.getAllPagesData(
2657
- async (qry) => await fetch(qry, {
2658
- headers: this.requireAmountsAsStrings(this.commonHeaders())
2659
- }),
2660
- `${this.url}${queryPredicate}/utxos`,
2661
- qparams,
2662
- "Location: getUtxosInternal. Error: Could not fetch UTxOs from Maestro"
2663
- );
2664
- return result.map(this.maestroUtxoToUtxo);
2665
- }
2666
- getUtxos(addressOrCredential) {
2667
- return this.getUtxosInternal(addressOrCredential);
2668
- }
2669
- getUtxosWithUnit(addressOrCredential, unit) {
2670
- return this.getUtxosInternal(addressOrCredential, unit);
2671
- }
2672
- async getUtxoByUnit(unit) {
2673
- const timestampedAddressesResponse = await fetch(
2674
- `${this.url}/assets/${unit}/addresses?count=2`,
2675
- { headers: this.commonHeaders() }
2676
- );
2677
- const timestampedAddresses = await timestampedAddressesResponse.json();
2678
- if (!timestampedAddressesResponse.ok) {
2679
- if (timestampedAddresses.message) {
2680
- throw new Error(timestampedAddresses.message);
2681
- }
2682
- throw new Error(
2683
- "Location: getUtxoByUnit. Error: Couldn't perform query. Received status code: " + timestampedAddressesResponse.status
2684
- );
2685
- }
2686
- const addressesWithAmount = timestampedAddresses.data;
2687
- if (addressesWithAmount.length === 0) {
2688
- throw new Error("Location: getUtxoByUnit. Error: Unit not found.");
2689
- }
2690
- if (addressesWithAmount.length > 1) {
2691
- throw new Error(
2692
- "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address."
2693
- );
2694
- }
2695
- const address = addressesWithAmount[0].address;
2696
- const utxos = await this.getUtxosWithUnit(address, unit);
2697
- if (utxos.length > 1) {
2698
- throw new Error(
2699
- "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address."
2700
- );
2701
- }
2702
- return utxos[0];
2703
- }
2704
- async getUtxosByOutRef(outRefs) {
2705
- const qry = `${this.url}/transactions/outputs`;
2706
- const body = JSON.stringify(
2707
- outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`)
2708
- );
2709
- const utxos = await this.getAllPagesData(
2710
- async (qry2) => await fetch(qry2, {
2711
- method: "POST",
2712
- headers: {
2713
- "Content-Type": "application/json",
2714
- ...this.requireAmountsAsStrings(this.commonHeaders())
2715
- },
2716
- body
2717
- }),
2718
- qry,
2719
- new URLSearchParams({}),
2720
- "Location: getUtxosByOutRef. Error: Could not fetch UTxOs by references from Maestro"
2721
- );
2722
- return utxos.map(this.maestroUtxoToUtxo);
2723
- }
2724
- async getRewardAccount(rewardAddress) {
2725
- const response = await fetch(`${this.url}/accounts/${rewardAddress}`, {
2726
- headers: this.requireAmountsAsStrings(this.commonHeaders())
2727
- });
2728
- if (response.status === 404) {
2729
- return { registered: false, poolId: null, rewards: 0n };
2730
- }
2731
- if (!response.ok) {
2732
- throw new Error(
2733
- `Could not fetch reward account from Maestro. Received status code: ${response.status}`
2734
- );
2735
- }
2736
- const timestampedResult = await response.json();
2737
- const result = timestampedResult.data;
2738
- return {
2739
- registered: result.registered,
2740
- poolId: result.delegated_pool || null,
2741
- rewards: BigInt(result.rewards_available)
2742
- };
2743
- }
2744
- async getDelegation(rewardAddress) {
2745
- const { poolId, rewards } = await this.getRewardAccount(rewardAddress);
2746
- return { poolId, rewards };
2747
- }
2748
- async getDatum(datumHash) {
2749
- const timestampedResultResponse = await fetch(
2750
- `${this.url}/datums/${datumHash}`,
2751
- {
2752
- headers: this.commonHeaders()
2753
- }
2754
- );
2755
- if (!timestampedResultResponse.ok) {
2756
- if (timestampedResultResponse.status === 404) {
2757
- throw new Error(`No datum found for datum hash: ${datumHash}`);
2758
- } else {
2759
- throw new Error(
2760
- "Location: getDatum. Error: Couldn't successfully perform query. Received status code: " + timestampedResultResponse.status
2761
- );
2762
- }
2763
- }
2764
- const timestampedResult = await timestampedResultResponse.json();
2765
- return timestampedResult.data.bytes;
2766
- }
2767
- awaitTx(txHash, checkInterval = 3e3) {
2768
- return new Promise((res) => {
2769
- const confirmation = setInterval(async () => {
2770
- const isConfirmedResponse = await fetch(
2771
- `${this.url}/transactions/${txHash}/cbor`,
2772
- {
2773
- headers: this.commonHeaders()
2774
- }
2775
- );
2776
- if (isConfirmedResponse.ok) {
2777
- await isConfirmedResponse.json();
2778
- clearInterval(confirmation);
2779
- await new Promise((res2) => setTimeout(() => res2(1), 1e3));
2780
- return res(true);
2781
- }
2782
- }, checkInterval);
2783
- });
2784
- }
2785
- async getTransactionStatus(txHash, options = {}) {
2786
- const response = await fetch(`${this.url}/txmanager/${txHash}/state`, {
2787
- headers: this.commonHeaders(),
2788
- signal: options.signal
2789
- });
2790
- if (response.status === 404) return { status: "not_found", txHash };
2791
- if (!response.ok) {
2792
- throw new Error(
2793
- `Could not fetch transaction status from Maestro. Received status code: ${response.status}`
2794
- );
2795
- }
2796
- const result = await response.json();
2797
- switch (result.status) {
2798
- case "pending":
2799
- return { status: "pending", txHash };
2800
- case "confirmed":
2801
- return {
2802
- status: "confirmed",
2803
- txHash,
2804
- confirmation: {
2805
- txHash,
2806
- confirmations: result.confirmations
2807
- }
2808
- };
2809
- case "failed":
2810
- return {
2811
- status: "failed",
2812
- txHash,
2813
- reason: result.reason ?? result.error
2814
- };
2815
- default:
2816
- throw new Error(
2817
- `Maestro returned an unknown transaction status: ${String(result.status)}`
2818
- );
2819
- }
2820
- }
2821
- async submitTx(tx) {
2822
- let queryUrl = `${this.url}/txmanager`;
2823
- queryUrl += this.turboSubmit ? "/turbosubmit" : "";
2824
- const response = await fetch(queryUrl, {
2825
- method: "POST",
2826
- headers: {
2827
- "Content-Type": "application/cbor",
2828
- Accept: "text/plain",
2829
- ...this.commonHeaders()
2830
- },
2831
- body: fromHex3(tx)
2832
- });
2833
- const result = await response.text();
2834
- if (!response.ok) {
2835
- if (response.status === 400) throw new Error(result);
2836
- else {
2837
- throw new Error(
2838
- "Could not submit transaction. Received status code: " + response.status
2839
- );
2840
- }
2841
- }
2842
- return result;
2843
- }
2844
- commonHeaders() {
2845
- return { "api-key": this.apiKey, lucid: lucid2 };
2846
- }
2847
- requireAmountsAsStrings(obj) {
2848
- return { ...obj, "amounts-as-strings": "true" };
2849
- }
2850
- maestroUtxoToUtxo(result) {
2851
- return {
2852
- txHash: result.tx_hash,
2853
- outputIndex: result.index,
2854
- assets: (() => {
2855
- const a = {};
2856
- result.assets.forEach((am) => {
2857
- a[am.unit] = BigInt(am.amount);
2858
- });
2859
- return a;
2860
- })(),
2861
- address: result.address,
2862
- datumHash: result.datum ? result.datum.type == "inline" ? void 0 : result.datum.hash : void 0,
2863
- datum: result.datum?.bytes,
2864
- scriptRef: toScriptRef2(result.reference_script)
2865
- };
2866
- }
2867
- async getAllPagesData(getResponse, qry, paramsGiven, errorMsg) {
2868
- let nextCursor = null;
2869
- let result = [];
2870
- while (true) {
2871
- if (nextCursor !== null) {
2872
- paramsGiven.set("cursor", nextCursor);
2873
- }
2874
- const response = await getResponse(`${qry}?` + paramsGiven);
2875
- const pageResult = await response.json();
2876
- if (!response.ok) {
2877
- throw new Error(
2878
- `${errorMsg}. Received status code: ${response.status}`
2879
- );
2880
- }
2881
- nextCursor = pageResult.next_cursor;
2882
- result = result.concat(pageResult.data);
2883
- if (nextCursor == null) break;
2884
- }
2885
- return result;
2886
- }
2887
- async evaluateTx(tx, additionalUTxOs) {
2888
- const additionalMaestroUTxOs = (additionalUTxOs || []).map((utxo) => ({
2889
- tx_hash: utxo.txHash,
2890
- index: utxo.outputIndex,
2891
- txout_cbor: utxoToCore(utxo).output().to_cbor_hex()
2892
- }));
2893
- const payload = {
2894
- cbor: tx,
2895
- additional_utxos: additionalMaestroUTxOs
2896
- };
2897
- const res = await fetch(`${this.url}/transactions/evaluate`, {
2898
- method: "POST",
2899
- headers: {
2900
- "Content-Type": "application/json",
2901
- Accept: "application/json",
2902
- "api-key": this.apiKey
2903
- },
2904
- body: JSON.stringify(payload)
2905
- });
2906
- if (!res.ok) {
2907
- const body = await res.text();
2908
- console.error("Response error:", JSON.stringify(res));
2909
- throw new Error(`Evaluate transaction failed: ${body}`);
2910
- }
2911
- const result = await res.json();
2912
- return result;
2913
- }
2914
- };
2915
- var toScriptRef2 = (reference_script) => {
2916
- if (reference_script && reference_script.bytes) {
2917
- switch (reference_script.type) {
2918
- case "native":
2919
- return scriptFromNative2(reference_script.json);
2920
- case "plutusv1":
2921
- return {
2922
- type: "PlutusV1",
2923
- script: applyDoubleCborEncoding3(reference_script.bytes)
2924
- };
2925
- case "plutusv2":
2926
- return {
2927
- type: "PlutusV2",
2928
- script: applyDoubleCborEncoding3(reference_script.bytes)
2929
- };
2930
- case "plutusv3":
2931
- return {
2932
- type: "PlutusV3",
2933
- script: applyDoubleCborEncoding3(reference_script.bytes)
2934
- };
2935
- default:
2936
- return void 0;
2937
- }
2938
- }
2939
- };
2940
- var lucid2 = package_default.version;
2941
-
2942
2854
  // src/koios.ts
2943
- import { fromHex as fromHex4 } from "@lucid-evolution/core-utils";
2855
+ import { fromHex as fromHex3 } from "@lucid-evolution/core-utils";
2944
2856
  import { fromUnit as fromUnit3 } from "@lucid-evolution/utils";
2945
2857
 
2946
2858
  // src/internal/koios.ts
2947
2859
  import { FetchHttpClient as FetchHttpClient2 } from "@effect/platform";
2948
2860
  import { Effect as Effect3, pipe as pipe4, Schema as S4 } from "effect";
2949
- import { applyDoubleCborEncoding as applyDoubleCborEncoding4 } from "@lucid-evolution/utils";
2861
+ import { applyDoubleCborEncoding as applyDoubleCborEncoding3 } from "@lucid-evolution/utils";
2950
2862
  var ProtocolParametersSchema2 = S4.Struct({
2951
2863
  pvt_motion_no_confidence: S4.Number,
2952
2864
  pvt_committee_normal: S4.Number,
@@ -3194,25 +3106,25 @@ var toUTxO = (koiosUTxO, address) => ({
3194
3106
  address,
3195
3107
  datumHash: koiosUTxO.inline_datum ? void 0 : koiosUTxO.datum_hash || void 0,
3196
3108
  datum: koiosUTxO.inline_datum ? koiosUTxO.inline_datum.bytes : void 0,
3197
- scriptRef: toScriptRef3(koiosUTxO.reference_script)
3109
+ scriptRef: toScriptRef2(koiosUTxO.reference_script)
3198
3110
  });
3199
- var toScriptRef3 = (reference_script) => {
3111
+ var toScriptRef2 = (reference_script) => {
3200
3112
  if (reference_script && reference_script.bytes && reference_script.type) {
3201
3113
  switch (reference_script.type) {
3202
3114
  case "plutusV1":
3203
3115
  return {
3204
3116
  type: "PlutusV1",
3205
- script: applyDoubleCborEncoding4(reference_script.bytes)
3117
+ script: applyDoubleCborEncoding3(reference_script.bytes)
3206
3118
  };
3207
3119
  case "plutusV2":
3208
3120
  return {
3209
3121
  type: "PlutusV2",
3210
- script: applyDoubleCborEncoding4(reference_script.bytes)
3122
+ script: applyDoubleCborEncoding3(reference_script.bytes)
3211
3123
  };
3212
3124
  case "plutusV3":
3213
3125
  return {
3214
3126
  type: "PlutusV3",
3215
- script: applyDoubleCborEncoding4(reference_script.bytes)
3127
+ script: applyDoubleCborEncoding3(reference_script.bytes)
3216
3128
  };
3217
3129
  default:
3218
3130
  return void 0;
@@ -3525,7 +3437,7 @@ var Koios = class {
3525
3437
  }
3526
3438
  async submitTx(tx) {
3527
3439
  const url = `${this.baseUrl}/submittx`;
3528
- const body = fromHex4(tx);
3440
+ const body = fromHex3(tx);
3529
3441
  const schema = TxHashSchema;
3530
3442
  const bearerToken = this.token ? { Authorization: `Bearer ${this.token}` } : void 0;
3531
3443
  const result = await pipe5(
@@ -3577,7 +3489,6 @@ export {
3577
3489
  KoiosError,
3578
3490
  Kupmios,
3579
3491
  KupmiosError,
3580
- Maestro,
3581
3492
  OgmiosJsonRpcError,
3582
3493
  generateEmulatorAccount,
3583
3494
  generateEmulatorAccountFromPrivateKey,