@indigo-labs/indigo-sdk 0.2.1 → 0.2.4

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
@@ -56,6 +56,8 @@ __export(index_exports, {
56
56
  LRPDatumSchema: () => LRPDatumSchema,
57
57
  LRPParamsSchema: () => LRPParamsSchema,
58
58
  LRPRedeemerSchema: () => LRPRedeemerSchema,
59
+ MAX_REDEMPTIONS_WITH_CDP_OPEN: () => MAX_REDEMPTIONS_WITH_CDP_OPEN,
60
+ MIN_LRP_COLLATERAL_AMT: () => MIN_LRP_COLLATERAL_AMT,
59
61
  ONE_DAY: () => ONE_DAY,
60
62
  ONE_HOUR: () => ONE_HOUR,
61
63
  ONE_SECOND: () => ONE_SECOND,
@@ -86,12 +88,17 @@ __export(index_exports, {
86
88
  adjustSpAccount: () => adjustSpAccount,
87
89
  adjustStakingPosition: () => adjustStakingPosition,
88
90
  adjustmentHelper: () => adjustmentHelper,
91
+ approximateLeverageRedemptions: () => approximateLeverageRedemptions,
89
92
  assetClassToUnit: () => assetClassToUnit,
90
93
  assetClassValueOf: () => assetClassValueOf,
91
94
  balance: () => balance,
95
+ buildRedemptionsTx: () => buildRedemptionsTx,
92
96
  burnCdp: () => burnCdp,
97
+ calculateCollateralRatioFromLeverage: () => calculateCollateralRatioFromLeverage,
93
98
  calculateIAssetRedemptionAmt: () => calculateIAssetRedemptionAmt,
99
+ calculateLeverageFromCollateralRatio: () => calculateLeverageFromCollateralRatio,
94
100
  calculateMinCollateralCappedIAssetRedemptionAmt: () => calculateMinCollateralCappedIAssetRedemptionAmt,
101
+ calculateTotalAdaForRedemption: () => calculateTotalAdaForRedemption,
95
102
  cancelLrp: () => cancelLrp,
96
103
  castCDPCreatorParams: () => castCDPCreatorParams,
97
104
  castCdpParams: () => castCdpParams,
@@ -103,6 +110,7 @@ __export(index_exports, {
103
110
  castPollShardParams: () => castPollShardParams,
104
111
  castPriceOracleParams: () => castPriceOracleParams,
105
112
  castStabilityPoolParams: () => castStabilityPoolParams,
113
+ castStakingParams: () => castStakingParams,
106
114
  castVersionRecordTokenParams: () => castVersionRecordTokenParams,
107
115
  cdpCollateralRatioPercentage: () => cdpCollateralRatioPercentage,
108
116
  claimLrp: () => claimLrp,
@@ -115,6 +123,7 @@ __export(index_exports, {
115
123
  createShardsChunks: () => createShardsChunks,
116
124
  createSpAccount: () => createSpAccount,
117
125
  depositCdp: () => depositCdp,
126
+ distributeAda: () => distributeAda,
118
127
  endProposal: () => endProposal,
119
128
  executeProposal: () => executeProposal,
120
129
  feedInterestOracle: () => feedInterestOracle,
@@ -130,12 +139,15 @@ __export(index_exports, {
130
139
  getSumFromEpochToScaleToSum: () => getSumFromEpochToScaleToSum,
131
140
  initEpochToScaleToSumMap: () => initEpochToScaleToSumMap,
132
141
  initSpSnapshot: () => initSpSnapshot,
142
+ insertSorted: () => insertSorted,
133
143
  isAssetsZero: () => isAssetsZero,
144
+ leverageCdpWithLrp: () => leverageCdpWithLrp,
134
145
  liquidateCdp: () => liquidateCdp,
135
146
  liquidationHelper: () => liquidationHelper,
136
147
  loadSystemParamsFromFile: () => loadSystemParamsFromFile,
137
148
  loadSystemParamsFromUrl: () => loadSystemParamsFromUrl,
138
149
  lovelacesAmt: () => lovelacesAmt,
150
+ lrpRedeemableLovelacesInclReimb: () => lrpRedeemableLovelacesInclReimb,
139
151
  matchSingle: () => matchSingle,
140
152
  mergeCdps: () => mergeCdps,
141
153
  mergeShards: () => mergeShards,
@@ -175,10 +187,15 @@ __export(index_exports, {
175
187
  parseIAssetDatumOrThrow: () => parseIAssetDatumOrThrow,
176
188
  parseInterestOracleDatum: () => parseInterestOracleDatum,
177
189
  parseLrpDatum: () => parseLrpDatum,
190
+ parseLrpDatumOrThrow: () => parseLrpDatumOrThrow,
178
191
  parsePriceOracleDatum: () => parsePriceOracleDatum,
179
192
  parseSnapshotEpochToScaleToSumDatum: () => parseSnapshotEpochToScaleToSumDatum,
180
193
  parseStabilityPoolDatum: () => parseStabilityPoolDatum,
194
+ parseStakingManagerDatum: () => parseStakingManagerDatum,
195
+ parseStakingPosition: () => parseStakingPosition,
196
+ parseStakingPositionOrThrow: () => parseStakingPositionOrThrow,
181
197
  processSpRequest: () => processSpRequest,
198
+ randomLrpsSubsetSatisfyingTargetLovelaces: () => randomLrpsSubsetSatisfyingTargetLovelaces,
182
199
  redeemCdp: () => redeemCdp,
183
200
  redeemLrp: () => redeemLrp,
184
201
  runCreateScriptRefTx: () => runCreateScriptRefTx,
@@ -202,12 +219,16 @@ __export(index_exports, {
202
219
  serialisePriceOracleRedeemer: () => serialisePriceOracleRedeemer,
203
220
  serialiseStabilityPoolDatum: () => serialiseStabilityPoolDatum,
204
221
  serialiseStabilityPoolRedeemer: () => serialiseStabilityPoolRedeemer,
222
+ serialiseStakingDatum: () => serialiseStakingDatum,
223
+ serialiseStakingRedeemer: () => serialiseStakingRedeemer,
205
224
  setSumInEpochToScaleToSum: () => setSumInEpochToScaleToSum,
225
+ shuffle: () => shuffle,
206
226
  spAdd: () => spAdd,
207
227
  spDiv: () => spDiv,
208
228
  spMul: () => spMul,
209
229
  spSub: () => spSub,
210
230
  startInterestOracle: () => startInterestOracle,
231
+ summarizeActualLeverageRedemptions: () => summarizeActualLeverageRedemptions,
211
232
  toSystemParamsAsset: () => toSystemParamsAsset,
212
233
  treasuryFeeTx: () => treasuryFeeTx,
213
234
  updatePoolSnapshotWithdrawalFee: () => updatePoolSnapshotWithdrawalFee,
@@ -217,7 +238,7 @@ __export(index_exports, {
217
238
  module.exports = __toCommonJS(index_exports);
218
239
 
219
240
  // src/contracts/cdp/transactions.ts
220
- var import_lucid17 = require("@lucid-evolution/lucid");
241
+ var import_lucid18 = require("@lucid-evolution/lucid");
221
242
 
222
243
  // src/types/system-params.ts
223
244
  var import_lucid = require("@lucid-evolution/lucid");
@@ -1006,12 +1027,23 @@ function calculateMinCollateralCappedIAssetRedemptionAmt(collateralAmt, mintedAm
1006
1027
  }
1007
1028
 
1008
1029
  // src/utils/bigint-utils.ts
1030
+ var import_fp_ts3 = require("fp-ts");
1009
1031
  function bigintMax(a, b) {
1010
1032
  return a > b ? a : b;
1011
1033
  }
1012
1034
  function bigintMin(a, b) {
1013
1035
  return a < b ? a : b;
1014
1036
  }
1037
+ function sum(arr) {
1038
+ return import_fp_ts3.array.reduce(0n, (acc, val) => acc + val)(arr);
1039
+ }
1040
+ function fromDecimal(val) {
1041
+ return BigInt(val.toString());
1042
+ }
1043
+ var BigIntOrd = {
1044
+ equals: (x, y) => x === y,
1045
+ compare: (first, second) => first < second ? -1 : first > second ? 1 : 0
1046
+ };
1015
1047
 
1016
1048
  // src/contracts/stability-pool/types-new.ts
1017
1049
  var import_evolution2 = require("@evolution-sdk/evolution");
@@ -1187,14 +1219,14 @@ function getSumFromEpochToScaleToSum(e2s2s, epoch, scale) {
1187
1219
  }
1188
1220
  return void 0;
1189
1221
  }
1190
- function setSumInEpochToScaleToSum(e2s2s, epoch, scale, sum) {
1222
+ function setSumInEpochToScaleToSum(e2s2s, epoch, scale, sum2) {
1191
1223
  const map = /* @__PURE__ */ new Map();
1192
1224
  for (const [key, value] of e2s2s.entries()) {
1193
1225
  if (!(key.epoch === epoch && key.scale === scale)) {
1194
1226
  map.set(key, value);
1195
1227
  }
1196
1228
  }
1197
- map.set({ epoch, scale }, sum);
1229
+ map.set({ epoch, scale }, sum2);
1198
1230
  return map;
1199
1231
  }
1200
1232
  function getAccountReward(account, e2s2s) {
@@ -1368,10 +1400,24 @@ function liquidationHelper(spContent, iassetBurnAmt, reward) {
1368
1400
  }
1369
1401
 
1370
1402
  // src/contracts/cdp/transactions.ts
1371
- var import_fp_ts3 = require("fp-ts");
1403
+ var import_fp_ts4 = require("fp-ts");
1372
1404
 
1373
1405
  // src/contracts/collector/transactions.ts
1406
+ var import_lucid15 = require("@lucid-evolution/lucid");
1407
+
1408
+ // src/contracts/collector/types.ts
1374
1409
  var import_lucid14 = require("@lucid-evolution/lucid");
1410
+ var CollectorRedeemerSchema = import_lucid14.Data.Enum([
1411
+ import_lucid14.Data.Literal("Collect"),
1412
+ import_lucid14.Data.Literal("DistributeToStakers"),
1413
+ import_lucid14.Data.Literal("UpgradeVersion")
1414
+ ]);
1415
+ var CollectorRedeemer = CollectorRedeemerSchema;
1416
+ function serialiseCollectorRedeemer(redeemer) {
1417
+ return import_lucid14.Data.to(redeemer, CollectorRedeemer);
1418
+ }
1419
+
1420
+ // src/contracts/collector/transactions.ts
1375
1421
  async function collectorFeeTx(fee, lucid, params, tx, collectorOref) {
1376
1422
  const collectorUtxo = matchSingle(
1377
1423
  await lucid.utxosByOutRef([collectorOref]),
@@ -1383,9 +1429,9 @@ async function collectorFeeTx(fee, lucid, params, tx, collectorOref) {
1383
1429
  ]),
1384
1430
  (_) => new Error("Expected a single collector Ref Script UTXO")
1385
1431
  );
1386
- tx.collectFrom([collectorUtxo], import_lucid14.Data.to(new import_lucid14.Constr(0, []))).pay.ToContract(
1432
+ tx.collectFrom([collectorUtxo], serialiseCollectorRedeemer("Collect")).pay.ToContract(
1387
1433
  collectorUtxo.address,
1388
- { kind: "inline", value: import_lucid14.Data.to(new import_lucid14.Constr(0, [])) },
1434
+ { kind: "inline", value: import_lucid15.Data.void() },
1389
1435
  {
1390
1436
  ...collectorUtxo.assets,
1391
1437
  lovelace: collectorUtxo.assets.lovelace + fee
@@ -1394,34 +1440,34 @@ async function collectorFeeTx(fee, lucid, params, tx, collectorOref) {
1394
1440
  }
1395
1441
 
1396
1442
  // src/contracts/treasury/transactions.ts
1397
- var import_lucid16 = require("@lucid-evolution/lucid");
1443
+ var import_lucid17 = require("@lucid-evolution/lucid");
1398
1444
 
1399
1445
  // src/contracts/treasury/types.ts
1400
- var import_lucid15 = require("@lucid-evolution/lucid");
1401
- var TreasuryParamsSchema = import_lucid15.Data.Object({
1446
+ var import_lucid16 = require("@lucid-evolution/lucid");
1447
+ var TreasuryParamsSchema = import_lucid16.Data.Object({
1402
1448
  upgradeToken: AssetClassSchema,
1403
1449
  versionRecordToken: AssetClassSchema,
1404
- treasuryUtxosStakeCredential: import_lucid15.Data.Nullable(StakeCredentialSchema)
1450
+ treasuryUtxosStakeCredential: import_lucid16.Data.Nullable(StakeCredentialSchema)
1405
1451
  });
1406
- var TreasuryRedeemerSchema = import_lucid15.Data.Enum([
1407
- import_lucid15.Data.Literal("Withdraw"),
1408
- import_lucid15.Data.Literal("PrepareWithdraw"),
1409
- import_lucid15.Data.Literal("Split"),
1410
- import_lucid15.Data.Literal("Merge"),
1411
- import_lucid15.Data.Literal("CollectAda"),
1412
- import_lucid15.Data.Literal("UpgradeVersion")
1452
+ var TreasuryRedeemerSchema = import_lucid16.Data.Enum([
1453
+ import_lucid16.Data.Literal("Withdraw"),
1454
+ import_lucid16.Data.Literal("PrepareWithdraw"),
1455
+ import_lucid16.Data.Literal("Split"),
1456
+ import_lucid16.Data.Literal("Merge"),
1457
+ import_lucid16.Data.Literal("CollectAda"),
1458
+ import_lucid16.Data.Literal("UpgradeVersion")
1413
1459
  ]);
1414
1460
  var TreasuryRedeemer = TreasuryRedeemerSchema;
1415
- var WithdrawalOutputDatumSchema = import_lucid15.Data.Tuple([
1416
- import_lucid15.Data.Bytes(),
1461
+ var WithdrawalOutputDatumSchema = import_lucid16.Data.Tuple([
1462
+ import_lucid16.Data.Bytes(),
1417
1463
  OutputReferenceSchema
1418
1464
  ]);
1419
1465
  var WithdrawalOutputDatum = WithdrawalOutputDatumSchema;
1420
1466
  function serialiseWithdrawalOutputDatum(d) {
1421
- return import_lucid15.Data.to(d, WithdrawalOutputDatum);
1467
+ return import_lucid16.Data.to(d, WithdrawalOutputDatum);
1422
1468
  }
1423
1469
  function serialiseTreasuryRedeemer(redeemer) {
1424
- return import_lucid15.Data.to(redeemer, TreasuryRedeemer);
1470
+ return import_lucid16.Data.to(redeemer, TreasuryRedeemer);
1425
1471
  }
1426
1472
 
1427
1473
  // src/contracts/treasury/transactions.ts
@@ -1440,15 +1486,15 @@ async function treasuryFeeTx(fee, lucid, sysParams, tx, treasuryOref) {
1440
1486
  );
1441
1487
  tx.readFrom([treasuryRefScriptUtxo]).collectFrom([treasuryUtxo], serialiseTreasuryRedeemer("CollectAda")).pay.ToContract(
1442
1488
  treasuryUtxo.address,
1443
- { kind: "inline", value: import_lucid16.Data.void() },
1444
- (0, import_lucid16.addAssets)(treasuryUtxo.assets, mkLovelacesOf(fee))
1489
+ { kind: "inline", value: import_lucid17.Data.void() },
1490
+ (0, import_lucid17.addAssets)(treasuryUtxo.assets, mkLovelacesOf(fee))
1445
1491
  );
1446
1492
  }
1447
1493
 
1448
1494
  // src/contracts/cdp/transactions.ts
1449
1495
  async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref, iassetOref, priceOracleOref, interestOracleOref, collectorOref, lucid, currentSlot) {
1450
1496
  const network = lucid.config().network;
1451
- const currentTime = BigInt((0, import_lucid17.slotToUnixTime)(network, currentSlot));
1497
+ const currentTime = BigInt((0, import_lucid18.slotToUnixTime)(network, currentSlot));
1452
1498
  const [pkh, skh] = await addrDetails(lucid);
1453
1499
  const cdpCreatorRefScriptUtxo = matchSingle(
1454
1500
  await lucid.utxosByOutRef([
@@ -1524,7 +1570,7 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
1524
1570
  cdpCreatorRefScriptUtxo,
1525
1571
  cdpAuthTokenPolicyRefScriptUtxo,
1526
1572
  iAssetTokenPolicyRefScriptUtxo
1527
- ]).mintAssets(cdpNftVal, import_lucid17.Data.void()).mintAssets(iassetTokensVal, import_lucid17.Data.void()).collectFrom(
1573
+ ]).mintAssets(cdpNftVal, import_lucid18.Data.void()).mintAssets(iassetTokensVal, import_lucid18.Data.void()).collectFrom(
1528
1574
  [cdpCreatorUtxo],
1529
1575
  serialiseCDPCreatorRedeemer({
1530
1576
  CreateCDP: {
@@ -1553,10 +1599,10 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
1553
1599
  }
1554
1600
  })
1555
1601
  },
1556
- (0, import_lucid17.addAssets)(cdpNftVal, mkLovelacesOf(collateralAmount))
1602
+ (0, import_lucid18.addAssets)(cdpNftVal, mkLovelacesOf(collateralAmount))
1557
1603
  ).pay.ToContract(
1558
1604
  cdpCreatorUtxo.address,
1559
- { kind: "inline", value: import_lucid17.Data.void() },
1605
+ { kind: "inline", value: import_lucid18.Data.void() },
1560
1606
  cdpCreatorUtxo.assets
1561
1607
  ).readFrom([priceOracleUtxo, interestOracleUtxo, iassetUtxo]).addSignerKey(pkh.hash);
1562
1608
  const debtMintingFee = calculateFeeFromPercentage(
@@ -1570,7 +1616,7 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
1570
1616
  }
1571
1617
  async function adjustCdp(collateralAmount, mintAmount, cdpOref, iassetOref, priceOracleOref, interestOracleOref, collectorOref, govOref, treasuryOref, sysParams, lucid, currentSlot) {
1572
1618
  const network = lucid.config().network;
1573
- const currentTime = BigInt((0, import_lucid17.slotToUnixTime)(network, currentSlot));
1619
+ const currentTime = BigInt((0, import_lucid18.slotToUnixTime)(network, currentSlot));
1574
1620
  const cdpRefScriptUtxo = matchSingle(
1575
1621
  await lucid.utxosByOutRef([
1576
1622
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -1645,7 +1691,7 @@ async function adjustCdp(collateralAmount, mintAmount, cdpOref, iassetOref, pric
1645
1691
  }
1646
1692
  })
1647
1693
  },
1648
- (0, import_lucid17.addAssets)(cdpUtxo.assets, mkLovelacesOf(collateralAmount))
1694
+ (0, import_lucid18.addAssets)(cdpUtxo.assets, mkLovelacesOf(collateralAmount))
1649
1695
  );
1650
1696
  if (!cdpDatum.cdpOwner) {
1651
1697
  throw new Error("Expected active CDP");
@@ -1669,7 +1715,7 @@ async function adjustCdp(collateralAmount, mintAmount, cdpOref, iassetOref, pric
1669
1715
  );
1670
1716
  tx.readFrom([iAssetTokenPolicyRefScriptUtxo]).mintAssets(
1671
1717
  iassetTokensVal,
1672
- import_lucid17.Data.void()
1718
+ import_lucid18.Data.void()
1673
1719
  );
1674
1720
  }
1675
1721
  const interestAdaAmt = (0, import_ts_pattern7.match)(cdpDatum.cdpFees).with({ FrozenCDPAccumulatedFees: import_ts_pattern7.P.any }, () => {
@@ -1782,7 +1828,7 @@ async function burnCdp(amount, cdpOref, iassetOref, priceOracleOref, interestOra
1782
1828
  }
1783
1829
  async function closeCdp(cdpOref, iassetOref, priceOracleOref, interestOracleOref, collectorOref, govOref, treasuryOref, sysParams, lucid, currentSlot) {
1784
1830
  const network = lucid.config().network;
1785
- const currentTime = BigInt((0, import_lucid17.slotToUnixTime)(network, currentSlot));
1831
+ const currentTime = BigInt((0, import_lucid18.slotToUnixTime)(network, currentSlot));
1786
1832
  const cdpRefScriptUtxo = matchSingle(
1787
1833
  await lucid.utxosByOutRef([
1788
1834
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -1854,10 +1900,10 @@ async function closeCdp(cdpOref, iassetOref, priceOracleOref, interestOracleOref
1854
1900
  },
1855
1901
  -cdpDatum.mintedAmt
1856
1902
  ),
1857
- import_lucid17.Data.void()
1903
+ import_lucid18.Data.void()
1858
1904
  ).mintAssets(
1859
1905
  mkAssetsOf(fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken), -1n),
1860
- import_lucid17.Data.void()
1906
+ import_lucid18.Data.void()
1861
1907
  ).collectFrom(
1862
1908
  [cdpUtxo],
1863
1909
  serialiseCdpRedeemer({ CloseCdp: { currentTime } })
@@ -1903,7 +1949,7 @@ async function closeCdp(cdpOref, iassetOref, priceOracleOref, interestOracleOref
1903
1949
  }
1904
1950
  async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, priceOracleOref, interestOracleOref, collectorOref, treasuryOref, sysParams, lucid, currentSlot) {
1905
1951
  const network = lucid.config().network;
1906
- const currentTime = BigInt((0, import_lucid17.slotToUnixTime)(network, currentSlot));
1952
+ const currentTime = BigInt((0, import_lucid18.slotToUnixTime)(network, currentSlot));
1907
1953
  const cdpRefScriptUtxo = matchSingle(
1908
1954
  await lucid.utxosByOutRef([
1909
1955
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -2012,7 +2058,7 @@ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, pric
2012
2058
  },
2013
2059
  -redemptionIAssetAmt
2014
2060
  ),
2015
- import_lucid17.Data.void()
2061
+ import_lucid18.Data.void()
2016
2062
  ).pay.ToContract(
2017
2063
  cdpUtxo.address,
2018
2064
  {
@@ -2031,7 +2077,7 @@ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, pric
2031
2077
  }
2032
2078
  })
2033
2079
  },
2034
- (0, import_lucid17.addAssets)(
2080
+ (0, import_lucid18.addAssets)(
2035
2081
  cdpUtxo.assets,
2036
2082
  mkLovelacesOf(-redemptionLovelacesAmt),
2037
2083
  mkLovelacesOf(reimburstmentFee),
@@ -2056,7 +2102,7 @@ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, pric
2056
2102
  }
2057
2103
  async function freezeCdp(cdpOref, iassetOref, priceOracleOref, interestOracleOref, sysParams, lucid, currentSlot) {
2058
2104
  const network = lucid.config().network;
2059
- const currentTime = BigInt((0, import_lucid17.slotToUnixTime)(network, currentSlot));
2105
+ const currentTime = BigInt((0, import_lucid18.slotToUnixTime)(network, currentSlot));
2060
2106
  const cdpRefScriptUtxo = matchSingle(
2061
2107
  await lucid.utxosByOutRef([
2062
2108
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -2222,7 +2268,7 @@ async function liquidateCdp(cdpOref, stabilityPoolOref, collectorOref, treasuryO
2222
2268
  stabilityPoolRefScriptUtxo,
2223
2269
  iAssetTokenPolicyRefScriptUtxo,
2224
2270
  cdpAuthTokenPolicyRefScriptUtxo
2225
- ]).collectFrom([spUtxo], serialiseStabilityPoolRedeemer("LiquidateCDP")).collectFrom([cdpUtxo], serialiseCdpRedeemer("Liquidate")).mintAssets(mkAssetsOf(iassetsAc, -iassetBurnAmt), import_lucid17.Data.void()).pay.ToContract(
2271
+ ]).collectFrom([spUtxo], serialiseStabilityPoolRedeemer("LiquidateCDP")).collectFrom([cdpUtxo], serialiseCdpRedeemer("Liquidate")).mintAssets(mkAssetsOf(iassetsAc, -iassetBurnAmt), import_lucid18.Data.void()).pay.ToContract(
2226
2272
  spUtxo.address,
2227
2273
  {
2228
2274
  kind: "inline",
@@ -2234,7 +2280,7 @@ async function liquidateCdp(cdpOref, stabilityPoolOref, collectorOref, treasuryO
2234
2280
  ).newSpContent
2235
2281
  })
2236
2282
  },
2237
- (0, import_lucid17.addAssets)(
2283
+ (0, import_lucid18.addAssets)(
2238
2284
  spUtxo.assets,
2239
2285
  mkLovelacesOf(collateralAbsorbed),
2240
2286
  mkAssetsOf(iassetsAc, -iassetBurnAmt)
@@ -2256,7 +2302,7 @@ async function liquidateCdp(cdpOref, stabilityPoolOref, collectorOref, treasuryO
2256
2302
  }
2257
2303
  })
2258
2304
  },
2259
- (0, import_lucid17.addAssets)(
2305
+ (0, import_lucid18.addAssets)(
2260
2306
  mkAssetsOf(cdpNftAc, assetClassValueOf(cdpUtxo.assets, cdpNftAc)),
2261
2307
  mkLovelacesOf(collateralAvailable - collateralAbsorbed)
2262
2308
  )
@@ -2264,7 +2310,7 @@ async function liquidateCdp(cdpOref, stabilityPoolOref, collectorOref, treasuryO
2264
2310
  } else {
2265
2311
  tx.mintAssets(
2266
2312
  mkAssetsOf(cdpNftAc, -assetClassValueOf(cdpUtxo.assets, cdpNftAc)),
2267
- import_lucid17.Data.void()
2313
+ import_lucid18.Data.void()
2268
2314
  );
2269
2315
  }
2270
2316
  await collectorFeeTx(
@@ -2291,17 +2337,17 @@ async function mergeCdps(cdpsToMergeUtxos, sysParams, lucid) {
2291
2337
  if (cdpUtxos.length !== cdpsToMergeUtxos.length) {
2292
2338
  throw new Error("Expected certain number of CDPs");
2293
2339
  }
2294
- const aggregatedVal = import_fp_ts3.function.pipe(
2340
+ const aggregatedVal = import_fp_ts4.function.pipe(
2295
2341
  cdpUtxos,
2296
- import_fp_ts3.array.reduce({}, (acc, utxo) => (0, import_lucid17.addAssets)(acc, utxo.assets))
2342
+ import_fp_ts4.array.reduce({}, (acc, utxo) => (0, import_lucid18.addAssets)(acc, utxo.assets))
2297
2343
  );
2298
- const aggregatedMintedAmt = import_fp_ts3.function.pipe(
2344
+ const aggregatedMintedAmt = import_fp_ts4.function.pipe(
2299
2345
  cdpDatums,
2300
- import_fp_ts3.array.reduce(0n, (acc, cdpDat) => acc + cdpDat.mintedAmt)
2346
+ import_fp_ts4.array.reduce(0n, (acc, cdpDat) => acc + cdpDat.mintedAmt)
2301
2347
  );
2302
- const { aggregatedFeeTreasury, aggregatedFeeIndyStakers } = import_fp_ts3.function.pipe(
2348
+ const { aggregatedFeeTreasury, aggregatedFeeIndyStakers } = import_fp_ts4.function.pipe(
2303
2349
  cdpDatums,
2304
- import_fp_ts3.array.reduce(
2350
+ import_fp_ts4.array.reduce(
2305
2351
  { aggregatedFeeIndyStakers: 0n, aggregatedFeeTreasury: 0n },
2306
2352
  (acc, cdpDat) => (0, import_ts_pattern7.match)(cdpDat.cdpFees).returnType().with({ FrozenCDPAccumulatedFees: import_ts_pattern7.P.select() }, (fees) => ({
2307
2353
  aggregatedFeeIndyStakers: acc.aggregatedFeeIndyStakers + fees.lovelacesIndyStakers,
@@ -2310,7 +2356,7 @@ async function mergeCdps(cdpsToMergeUtxos, sysParams, lucid) {
2310
2356
  )
2311
2357
  );
2312
2358
  const [[mainMergeUtxo, mainCdpDatum], otherMergeUtxos] = (0, import_ts_pattern7.match)(
2313
- import_fp_ts3.array.zip(cdpUtxos, cdpDatums)
2359
+ import_fp_ts4.array.zip(cdpUtxos, cdpDatums)
2314
2360
  ).returnType().with([import_ts_pattern7.P._, ...import_ts_pattern7.P.array()], ([main, ...other]) => [
2315
2361
  main,
2316
2362
  other.map((a) => a[0])
@@ -2348,7 +2394,7 @@ async function mergeCdps(cdpsToMergeUtxos, sysParams, lucid) {
2348
2394
  }
2349
2395
 
2350
2396
  // src/contracts/cdp/scripts.ts
2351
- var import_lucid18 = require("@lucid-evolution/lucid");
2397
+ var import_lucid19 = require("@lucid-evolution/lucid");
2352
2398
 
2353
2399
  // src/validators/cdp-validator.ts
2354
2400
  var _cdpValidator = {
@@ -2361,7 +2407,7 @@ var _cdpValidator = {
2361
2407
  var mkCdpValidatorFromSP = (params) => {
2362
2408
  return {
2363
2409
  type: "PlutusV2",
2364
- script: (0, import_lucid18.applyParamsToScript)(_cdpValidator.cborHex, [
2410
+ script: (0, import_lucid19.applyParamsToScript)(_cdpValidator.cborHex, [
2365
2411
  castCdpParams({
2366
2412
  cdp_auth_token: fromSystemParamsAsset(params.cdpAuthToken),
2367
2413
  cdp_asset_symbol: params.cdpAssetSymbol.unCurrencySymbol,
@@ -2386,7 +2432,7 @@ var mkCdpValidatorFromSP = (params) => {
2386
2432
  };
2387
2433
 
2388
2434
  // src/contracts/cdp-creator/scripts.ts
2389
- var import_lucid19 = require("@lucid-evolution/lucid");
2435
+ var import_lucid20 = require("@lucid-evolution/lucid");
2390
2436
 
2391
2437
  // src/validators/cdp-creator-validator.ts
2392
2438
  var _cdpCreatorValidator = {
@@ -2399,7 +2445,7 @@ var _cdpCreatorValidator = {
2399
2445
  var mkCDPCreatorValidator = (params) => {
2400
2446
  return {
2401
2447
  type: "PlutusV2",
2402
- script: (0, import_lucid19.applyParamsToScript)(_cdpCreatorValidator.cborHex, [
2448
+ script: (0, import_lucid20.applyParamsToScript)(_cdpCreatorValidator.cborHex, [
2403
2449
  castCDPCreatorParams(params)
2404
2450
  ])
2405
2451
  };
@@ -2407,7 +2453,7 @@ var mkCDPCreatorValidator = (params) => {
2407
2453
  var mkCDPCreatorValidatorFromSP = (params) => {
2408
2454
  return {
2409
2455
  type: "PlutusV2",
2410
- script: (0, import_lucid19.applyParamsToScript)(_cdpCreatorValidator.cborHex, [
2456
+ script: (0, import_lucid20.applyParamsToScript)(_cdpCreatorValidator.cborHex, [
2411
2457
  castCDPCreatorParams({
2412
2458
  cdpCreatorNft: fromSystemParamsAsset(params.cdpCreatorNft),
2413
2459
  cdpAssetCs: params.cdpAssetCs.unCurrencySymbol,
@@ -2424,64 +2470,64 @@ var mkCDPCreatorValidatorFromSP = (params) => {
2424
2470
  };
2425
2471
 
2426
2472
  // src/contracts/poll/scripts.ts
2427
- var import_lucid22 = require("@lucid-evolution/lucid");
2473
+ var import_lucid23 = require("@lucid-evolution/lucid");
2428
2474
 
2429
2475
  // src/contracts/poll/types-poll-manager.ts
2430
- var import_lucid20 = require("@lucid-evolution/lucid");
2431
- var PollManagerParamsSchema = import_lucid20.Data.Object({
2476
+ var import_lucid21 = require("@lucid-evolution/lucid");
2477
+ var PollManagerParamsSchema = import_lucid21.Data.Object({
2432
2478
  govNFT: AssetClassSchema,
2433
2479
  pollToken: AssetClassSchema,
2434
2480
  upgradeToken: AssetClassSchema,
2435
2481
  indyAsset: AssetClassSchema,
2436
- govExecuteValHash: import_lucid20.Data.Bytes(),
2437
- pBiasTime: import_lucid20.Data.Integer(),
2438
- shardValHash: import_lucid20.Data.Bytes(),
2439
- treasuryValHash: import_lucid20.Data.Bytes(),
2440
- initialIndyDistribution: import_lucid20.Data.Integer()
2482
+ govExecuteValHash: import_lucid21.Data.Bytes(),
2483
+ pBiasTime: import_lucid21.Data.Integer(),
2484
+ shardValHash: import_lucid21.Data.Bytes(),
2485
+ treasuryValHash: import_lucid21.Data.Bytes(),
2486
+ initialIndyDistribution: import_lucid21.Data.Integer()
2441
2487
  });
2442
2488
  var PollManagerParams = PollManagerParamsSchema;
2443
- var PollManagerRedeemerSchema = import_lucid20.Data.Enum([
2444
- import_lucid20.Data.Object({
2445
- EndPoll: import_lucid20.Data.Object({ currentTime: import_lucid20.Data.Integer() })
2489
+ var PollManagerRedeemerSchema = import_lucid21.Data.Enum([
2490
+ import_lucid21.Data.Object({
2491
+ EndPoll: import_lucid21.Data.Object({ currentTime: import_lucid21.Data.Integer() })
2446
2492
  }),
2447
- import_lucid20.Data.Object({ CreateShards: import_lucid20.Data.Object({ currentTime: import_lucid20.Data.Integer() }) }),
2448
- import_lucid20.Data.Object({
2449
- MergeShardsManager: import_lucid20.Data.Object({ currentTime: import_lucid20.Data.Integer() })
2493
+ import_lucid21.Data.Object({ CreateShards: import_lucid21.Data.Object({ currentTime: import_lucid21.Data.Integer() }) }),
2494
+ import_lucid21.Data.Object({
2495
+ MergeShardsManager: import_lucid21.Data.Object({ currentTime: import_lucid21.Data.Integer() })
2450
2496
  })
2451
2497
  ]);
2452
2498
  var PollManagerRedeemer = PollManagerRedeemerSchema;
2453
2499
  function serialisePollManagerRedeemer(r) {
2454
- return import_lucid20.Data.to(r, PollManagerRedeemer);
2500
+ return import_lucid21.Data.to(r, PollManagerRedeemer);
2455
2501
  }
2456
2502
  function castPollManagerParams(params) {
2457
- return import_lucid20.Data.castTo(params, PollManagerParams);
2503
+ return import_lucid21.Data.castTo(params, PollManagerParams);
2458
2504
  }
2459
2505
 
2460
2506
  // src/contracts/poll/types-poll-shard.ts
2461
- var import_lucid21 = require("@lucid-evolution/lucid");
2462
- var PollShardParamsSchema = import_lucid21.Data.Object({
2507
+ var import_lucid22 = require("@lucid-evolution/lucid");
2508
+ var PollShardParamsSchema = import_lucid22.Data.Object({
2463
2509
  pollToken: AssetClassSchema,
2464
2510
  stakingToken: AssetClassSchema,
2465
2511
  indyAsset: AssetClassSchema,
2466
- stakingValHash: import_lucid21.Data.Bytes()
2512
+ stakingValHash: import_lucid22.Data.Bytes()
2467
2513
  });
2468
2514
  var PollShardParams = PollShardParamsSchema;
2469
- var VoteOptionSchema = import_lucid21.Data.Enum([import_lucid21.Data.Literal("Yes"), import_lucid21.Data.Literal("No")]);
2470
- var PollShardRedeemerSchema = import_lucid21.Data.Enum([
2471
- import_lucid21.Data.Object({ Vote: import_lucid21.Data.Object({ content: VoteOptionSchema }) }),
2472
- import_lucid21.Data.Object({
2473
- MergeShards: import_lucid21.Data.Object({
2474
- currentTime: import_lucid21.Data.Integer(),
2515
+ var VoteOptionSchema = import_lucid22.Data.Enum([import_lucid22.Data.Literal("Yes"), import_lucid22.Data.Literal("No")]);
2516
+ var PollShardRedeemerSchema = import_lucid22.Data.Enum([
2517
+ import_lucid22.Data.Object({ Vote: import_lucid22.Data.Object({ content: VoteOptionSchema }) }),
2518
+ import_lucid22.Data.Object({
2519
+ MergeShards: import_lucid22.Data.Object({
2520
+ currentTime: import_lucid22.Data.Integer(),
2475
2521
  pollManagerRef: OutputReferenceSchema
2476
2522
  })
2477
2523
  })
2478
2524
  ]);
2479
2525
  var PollShardRedeemer = PollShardRedeemerSchema;
2480
2526
  function serialisePollShardRedeemer(redeemer) {
2481
- return import_lucid21.Data.to(redeemer, PollShardRedeemer);
2527
+ return import_lucid22.Data.to(redeemer, PollShardRedeemer);
2482
2528
  }
2483
2529
  function castPollShardParams(params) {
2484
- return import_lucid21.Data.castTo(params, PollShardParams);
2530
+ return import_lucid22.Data.castTo(params, PollShardParams);
2485
2531
  }
2486
2532
 
2487
2533
  // src/validators/poll-manager-validator.ts
@@ -2502,7 +2548,7 @@ var _pollShardValidator = {
2502
2548
  var mkPollManagerValidator = (params) => {
2503
2549
  return {
2504
2550
  type: "PlutusV2",
2505
- script: (0, import_lucid22.applyParamsToScript)(_pollManagerValidator.cborHex, [
2551
+ script: (0, import_lucid23.applyParamsToScript)(_pollManagerValidator.cborHex, [
2506
2552
  castPollManagerParams(params)
2507
2553
  ])
2508
2554
  };
@@ -2510,7 +2556,7 @@ var mkPollManagerValidator = (params) => {
2510
2556
  var mkPollManagerValidatorFromSP = (params) => {
2511
2557
  return {
2512
2558
  type: "PlutusV2",
2513
- script: (0, import_lucid22.applyParamsToScript)(_pollManagerValidator.cborHex, [
2559
+ script: (0, import_lucid23.applyParamsToScript)(_pollManagerValidator.cborHex, [
2514
2560
  castPollManagerParams({
2515
2561
  govNFT: fromSystemParamsAsset(params.govNFT),
2516
2562
  pollToken: fromSystemParamsAsset(params.pollToken),
@@ -2528,7 +2574,7 @@ var mkPollManagerValidatorFromSP = (params) => {
2528
2574
  var mkPollShardValidator = (params) => {
2529
2575
  return {
2530
2576
  type: "PlutusV2",
2531
- script: (0, import_lucid22.applyParamsToScript)(_pollShardValidator.cborHex, [
2577
+ script: (0, import_lucid23.applyParamsToScript)(_pollShardValidator.cborHex, [
2532
2578
  castPollShardParams(params)
2533
2579
  ])
2534
2580
  };
@@ -2536,7 +2582,7 @@ var mkPollShardValidator = (params) => {
2536
2582
  var mkPollShardValidatorFromSP = (params) => {
2537
2583
  return {
2538
2584
  type: "PlutusV2",
2539
- script: (0, import_lucid22.applyParamsToScript)(_pollShardValidator.cborHex, [
2585
+ script: (0, import_lucid23.applyParamsToScript)(_pollShardValidator.cborHex, [
2540
2586
  castPollShardParams({
2541
2587
  pollToken: fromSystemParamsAsset(params.pollToken),
2542
2588
  stakingToken: fromSystemParamsAsset(params.stakingToken),
@@ -2548,119 +2594,123 @@ var mkPollShardValidatorFromSP = (params) => {
2548
2594
  };
2549
2595
 
2550
2596
  // src/contracts/gov/transactions.ts
2551
- var import_lucid29 = require("@lucid-evolution/lucid");
2597
+ var import_lucid30 = require("@lucid-evolution/lucid");
2552
2598
 
2553
2599
  // src/contracts/poll/types-poll.ts
2554
- var import_lucid23 = require("@lucid-evolution/lucid");
2555
- var import_fp_ts4 = require("fp-ts");
2600
+ var import_lucid24 = require("@lucid-evolution/lucid");
2601
+ var import_fp_ts5 = require("fp-ts");
2556
2602
  var import_ts_pattern8 = require("ts-pattern");
2557
- var PollStatusSchema = import_lucid23.Data.Object({
2558
- yesVotes: import_lucid23.Data.Integer(),
2559
- noVotes: import_lucid23.Data.Integer()
2603
+ var PollStatusSchema = import_lucid24.Data.Object({
2604
+ yesVotes: import_lucid24.Data.Integer(),
2605
+ noVotes: import_lucid24.Data.Integer()
2560
2606
  });
2561
- var PollManagerContentSchema = import_lucid23.Data.Object({
2562
- pollId: import_lucid23.Data.Integer(),
2563
- pollOwner: import_lucid23.Data.Bytes(),
2607
+ var PollManagerContentSchema = import_lucid24.Data.Object({
2608
+ pollId: import_lucid24.Data.Integer(),
2609
+ pollOwner: import_lucid24.Data.Bytes(),
2564
2610
  content: ProposalContentSchema,
2565
- treasuryWithdrawal: import_lucid23.Data.Nullable(TreasuryWithdrawalSchema),
2611
+ treasuryWithdrawal: import_lucid24.Data.Nullable(TreasuryWithdrawalSchema),
2566
2612
  status: PollStatusSchema,
2567
- votingEndTime: import_lucid23.Data.Integer(),
2568
- createdShardsCount: import_lucid23.Data.Integer(),
2569
- talliedShardsCount: import_lucid23.Data.Integer(),
2570
- totalShardsCount: import_lucid23.Data.Integer(),
2571
- proposingEndTime: import_lucid23.Data.Integer(),
2572
- expirationTime: import_lucid23.Data.Integer(),
2573
- protocolVersion: import_lucid23.Data.Integer(),
2574
- minimumQuorum: import_lucid23.Data.Integer()
2613
+ votingEndTime: import_lucid24.Data.Integer(),
2614
+ createdShardsCount: import_lucid24.Data.Integer(),
2615
+ talliedShardsCount: import_lucid24.Data.Integer(),
2616
+ totalShardsCount: import_lucid24.Data.Integer(),
2617
+ proposingEndTime: import_lucid24.Data.Integer(),
2618
+ expirationTime: import_lucid24.Data.Integer(),
2619
+ protocolVersion: import_lucid24.Data.Integer(),
2620
+ minimumQuorum: import_lucid24.Data.Integer()
2575
2621
  });
2576
- var PollShardContentSchema = import_lucid23.Data.Object({
2577
- pollId: import_lucid23.Data.Integer(),
2622
+ var PollShardContentSchema = import_lucid24.Data.Object({
2623
+ pollId: import_lucid24.Data.Integer(),
2578
2624
  status: PollStatusSchema,
2579
- votingEndTime: import_lucid23.Data.Integer(),
2625
+ votingEndTime: import_lucid24.Data.Integer(),
2580
2626
  managerAddress: AddressSchema
2581
2627
  });
2582
- var PollDatumSchema = import_lucid23.Data.Enum([
2583
- import_lucid23.Data.Object({
2584
- PollManager: import_lucid23.Data.Object({ content: PollManagerContentSchema })
2628
+ var PollDatumSchema = import_lucid24.Data.Enum([
2629
+ import_lucid24.Data.Object({
2630
+ PollManager: import_lucid24.Data.Object({ content: PollManagerContentSchema })
2585
2631
  }),
2586
- import_lucid23.Data.Object({ PollShard: import_lucid23.Data.Object({ content: PollShardContentSchema }) })
2632
+ import_lucid24.Data.Object({ PollShard: import_lucid24.Data.Object({ content: PollShardContentSchema }) })
2587
2633
  ]);
2588
2634
  var PollDatum = PollDatumSchema;
2589
2635
  function parsePollManager(datum) {
2590
2636
  try {
2591
- return (0, import_ts_pattern8.match)(import_lucid23.Data.from(datum, PollDatum)).with({ PollManager: import_ts_pattern8.P.select() }, (res) => import_fp_ts4.option.some(res.content)).otherwise(() => import_fp_ts4.option.none);
2637
+ return (0, import_ts_pattern8.match)(import_lucid24.Data.from(datum, PollDatum)).with({ PollManager: import_ts_pattern8.P.select() }, (res) => import_fp_ts5.option.some(res.content)).otherwise(() => import_fp_ts5.option.none);
2592
2638
  } catch (_) {
2593
- return import_fp_ts4.option.none;
2639
+ return import_fp_ts5.option.none;
2594
2640
  }
2595
2641
  }
2596
2642
  function parsePollManagerOrThrow(datum) {
2597
- return import_fp_ts4.function.pipe(
2643
+ return import_fp_ts5.function.pipe(
2598
2644
  parsePollManager(datum),
2599
- import_fp_ts4.option.match(() => {
2645
+ import_fp_ts5.option.match(() => {
2600
2646
  throw new Error("Expected a Poll manager datum.");
2601
- }, import_fp_ts4.function.identity)
2647
+ }, import_fp_ts5.function.identity)
2602
2648
  );
2603
2649
  }
2604
2650
  function parsePollShard(datum) {
2605
2651
  try {
2606
- return (0, import_ts_pattern8.match)(import_lucid23.Data.from(datum, PollDatum)).with({ PollShard: import_ts_pattern8.P.select() }, (res) => import_fp_ts4.option.some(res.content)).otherwise(() => import_fp_ts4.option.none);
2652
+ return (0, import_ts_pattern8.match)(import_lucid24.Data.from(datum, PollDatum)).with({ PollShard: import_ts_pattern8.P.select() }, (res) => import_fp_ts5.option.some(res.content)).otherwise(() => import_fp_ts5.option.none);
2607
2653
  } catch (_) {
2608
- return import_fp_ts4.option.none;
2654
+ return import_fp_ts5.option.none;
2609
2655
  }
2610
2656
  }
2611
2657
  function parsePollShardOrThrow(datum) {
2612
- return import_fp_ts4.function.pipe(
2658
+ return import_fp_ts5.function.pipe(
2613
2659
  parsePollShard(datum),
2614
- import_fp_ts4.option.match(() => {
2660
+ import_fp_ts5.option.match(() => {
2615
2661
  throw new Error("Expected a Poll shard datum.");
2616
- }, import_fp_ts4.function.identity)
2662
+ }, import_fp_ts5.function.identity)
2617
2663
  );
2618
2664
  }
2619
2665
  function serialisePollDatum(datum) {
2620
- return import_lucid23.Data.to(datum, PollDatum);
2666
+ return import_lucid24.Data.to(datum, PollDatum);
2621
2667
  }
2622
2668
 
2623
2669
  // src/contracts/gov/transactions.ts
2624
- var import_lucid30 = require("@lucid-evolution/lucid");
2670
+ var import_lucid31 = require("@lucid-evolution/lucid");
2625
2671
  var import_function2 = require("fp-ts/lib/function");
2626
- var import_fp_ts9 = require("fp-ts");
2672
+ var import_fp_ts10 = require("fp-ts");
2627
2673
  var import_ts_pattern11 = require("ts-pattern");
2628
2674
 
2629
2675
  // src/contracts/staking/types.ts
2630
- var import_lucid24 = require("@lucid-evolution/lucid");
2631
- var StakingParamsSchema = import_lucid24.Data.Object({
2676
+ var import_lucid25 = require("@lucid-evolution/lucid");
2677
+ var StakingParamsSchema = import_lucid25.Data.Object({
2632
2678
  stakingManagerNft: AssetClassSchema,
2633
2679
  stakingToken: AssetClassSchema,
2634
2680
  indyToken: AssetClassSchema,
2635
2681
  pollToken: AssetClassSchema,
2636
2682
  versionRecordToken: AssetClassSchema,
2637
- collectorValHash: import_lucid24.Data.Bytes()
2683
+ collectorValHash: import_lucid25.Data.Bytes()
2638
2684
  });
2639
- var StakingRedeemerSchema = import_lucid24.Data.Enum([
2640
- import_lucid24.Data.Object({
2641
- CreateStakingPosition: import_lucid24.Data.Object({
2642
- creatorPkh: import_lucid24.Data.Bytes()
2685
+ var StakingParams = StakingParamsSchema;
2686
+ var StakingRedeemerSchema = import_lucid25.Data.Enum([
2687
+ import_lucid25.Data.Object({
2688
+ CreateStakingPosition: import_lucid25.Data.Object({
2689
+ creatorPkh: import_lucid25.Data.Bytes()
2643
2690
  })
2644
2691
  }),
2645
- import_lucid24.Data.Literal("UpdateTotalStake"),
2646
- import_lucid24.Data.Literal("Distribute"),
2647
- import_lucid24.Data.Object({
2648
- AdjustStakedAmount: import_lucid24.Data.Object({
2649
- adjustAmount: import_lucid24.Data.Integer()
2692
+ import_lucid25.Data.Literal("UpdateTotalStake"),
2693
+ import_lucid25.Data.Literal("Distribute"),
2694
+ import_lucid25.Data.Object({
2695
+ AdjustStakedAmount: import_lucid25.Data.Object({
2696
+ adjustAmount: import_lucid25.Data.Integer()
2650
2697
  })
2651
2698
  }),
2652
- import_lucid24.Data.Literal("Unstake"),
2653
- import_lucid24.Data.Literal("Lock"),
2654
- import_lucid24.Data.Literal("UpgradeVersion")
2699
+ import_lucid25.Data.Literal("Unstake"),
2700
+ import_lucid25.Data.Literal("Lock"),
2701
+ import_lucid25.Data.Literal("UpgradeVersion")
2655
2702
  ]);
2656
2703
  var StakingRedeemer = StakingRedeemerSchema;
2657
2704
  function serialiseStakingRedeemer(redeemer) {
2658
- return import_lucid24.Data.to(redeemer, StakingRedeemer);
2705
+ return import_lucid25.Data.to(redeemer, StakingRedeemer);
2706
+ }
2707
+ function castStakingParams(params) {
2708
+ return import_lucid25.Data.castTo(params, StakingParams);
2659
2709
  }
2660
2710
 
2661
2711
  // src/contracts/staking/types-new.ts
2662
2712
  var import_evolution3 = require("@evolution-sdk/evolution");
2663
- var import_fp_ts5 = require("fp-ts");
2713
+ var import_fp_ts6 = require("fp-ts");
2664
2714
  var import_ts_pattern9 = require("ts-pattern");
2665
2715
  var StakingPosLockedAmtSchema = import_evolution3.Core.TSchema.Map(
2666
2716
  import_evolution3.Core.TSchema.Integer,
@@ -2692,17 +2742,17 @@ function parseStakingPosition(datum) {
2692
2742
  StakingDatumSchema,
2693
2743
  DEFAULT_SCHEMA_OPTIONS
2694
2744
  ).fromCBORHex(datum)
2695
- ).with({ owner: import_ts_pattern9.P.any }, (res) => import_fp_ts5.option.some(res)).otherwise(() => import_fp_ts5.option.none);
2745
+ ).with({ owner: import_ts_pattern9.P.any }, (res) => import_fp_ts6.option.some(res)).otherwise(() => import_fp_ts6.option.none);
2696
2746
  } catch (_) {
2697
- return import_fp_ts5.option.none;
2747
+ return import_fp_ts6.option.none;
2698
2748
  }
2699
2749
  }
2700
2750
  function parseStakingPositionOrThrow(datum) {
2701
- return import_fp_ts5.function.pipe(
2751
+ return import_fp_ts6.function.pipe(
2702
2752
  parseStakingPosition(datum),
2703
- import_fp_ts5.option.match(() => {
2753
+ import_fp_ts6.option.match(() => {
2704
2754
  throw new Error("Expected a StakingPosition datum.");
2705
- }, import_fp_ts5.function.identity)
2755
+ }, import_fp_ts6.function.identity)
2706
2756
  );
2707
2757
  }
2708
2758
  function parseStakingManagerDatum(datum) {
@@ -2723,10 +2773,10 @@ function serialiseStakingDatum(d) {
2723
2773
  }
2724
2774
 
2725
2775
  // src/contracts/staking/helpers.ts
2726
- var import_lucid26 = require("@lucid-evolution/lucid");
2776
+ var import_lucid27 = require("@lucid-evolution/lucid");
2727
2777
 
2728
2778
  // src/contracts/staking/scripts.ts
2729
- var import_lucid25 = require("@lucid-evolution/lucid");
2779
+ var import_lucid26 = require("@lucid-evolution/lucid");
2730
2780
 
2731
2781
  // src/validators/staking-validator.ts
2732
2782
  var _stakingValidator = {
@@ -2739,27 +2789,27 @@ var _stakingValidator = {
2739
2789
  var mkStakingValidatorFromSP = (params) => {
2740
2790
  return {
2741
2791
  type: "PlutusV2",
2742
- script: (0, import_lucid25.applyParamsToScript)(_stakingValidator.cborHex, [
2743
- new import_lucid25.Constr(0, [
2744
- new import_lucid25.Constr(0, [
2792
+ script: (0, import_lucid26.applyParamsToScript)(_stakingValidator.cborHex, [
2793
+ new import_lucid26.Constr(0, [
2794
+ new import_lucid26.Constr(0, [
2745
2795
  params.stakingManagerNFT[0].unCurrencySymbol,
2746
- (0, import_lucid25.fromText)(params.stakingManagerNFT[1].unTokenName)
2796
+ (0, import_lucid26.fromText)(params.stakingManagerNFT[1].unTokenName)
2747
2797
  ]),
2748
- new import_lucid25.Constr(0, [
2798
+ new import_lucid26.Constr(0, [
2749
2799
  params.stakingToken[0].unCurrencySymbol,
2750
- (0, import_lucid25.fromText)(params.stakingToken[1].unTokenName)
2800
+ (0, import_lucid26.fromText)(params.stakingToken[1].unTokenName)
2751
2801
  ]),
2752
- new import_lucid25.Constr(0, [
2802
+ new import_lucid26.Constr(0, [
2753
2803
  params.indyToken[0].unCurrencySymbol,
2754
- (0, import_lucid25.fromText)(params.indyToken[1].unTokenName)
2804
+ (0, import_lucid26.fromText)(params.indyToken[1].unTokenName)
2755
2805
  ]),
2756
- new import_lucid25.Constr(0, [
2806
+ new import_lucid26.Constr(0, [
2757
2807
  params.pollToken[0].unCurrencySymbol,
2758
- (0, import_lucid25.fromText)(params.pollToken[1].unTokenName)
2808
+ (0, import_lucid26.fromText)(params.pollToken[1].unTokenName)
2759
2809
  ]),
2760
- new import_lucid25.Constr(0, [
2810
+ new import_lucid26.Constr(0, [
2761
2811
  params.versionRecordToken[0].unCurrencySymbol,
2762
- (0, import_lucid25.fromText)(params.versionRecordToken[1].unTokenName)
2812
+ (0, import_lucid26.fromText)(params.versionRecordToken[1].unTokenName)
2763
2813
  ]),
2764
2814
  params.collectorValHash
2765
2815
  ])
@@ -2792,9 +2842,9 @@ function findStakingManager(params, lucid) {
2792
2842
  return lucid.utxosAtWithUnit(
2793
2843
  createScriptAddress(
2794
2844
  lucid.config().network,
2795
- (0, import_lucid26.validatorToScriptHash)(mkStakingValidatorFromSP(params.stakingParams))
2845
+ (0, import_lucid27.validatorToScriptHash)(mkStakingValidatorFromSP(params.stakingParams))
2796
2846
  ),
2797
- params.stakingParams.stakingManagerNFT[0].unCurrencySymbol + (0, import_lucid26.fromText)(params.stakingParams.stakingManagerNFT[1].unTokenName)
2847
+ params.stakingParams.stakingManagerNFT[0].unCurrencySymbol + (0, import_lucid27.fromText)(params.stakingParams.stakingManagerNFT[1].unTokenName)
2798
2848
  ).then(
2799
2849
  (utxos) => utxos.map((utxo) => {
2800
2850
  if (!utxo.datum) return void 0;
@@ -2824,10 +2874,14 @@ function findStakingPositionByOutRef(stakingPositionRef, lucid) {
2824
2874
  return result;
2825
2875
  });
2826
2876
  }
2877
+ var rewardSnapshotPrecision = OCD_DECIMAL_UNIT * OCD_DECIMAL_UNIT;
2878
+ function distributeReward(snapshotAda, adaReward, totalStake) {
2879
+ return snapshotAda + adaReward * rewardSnapshotPrecision / totalStake;
2880
+ }
2827
2881
 
2828
2882
  // src/contracts/vesting/helpers.ts
2829
2883
  var import_ts_pattern10 = require("ts-pattern");
2830
- var import_fp_ts6 = require("fp-ts");
2884
+ var import_fp_ts7 = require("fp-ts");
2831
2885
  var teamVestingSchedule = [
2832
2886
  {
2833
2887
  vestedAtTime: 1669067100000n,
@@ -3014,7 +3068,7 @@ var govDistributionSchedule = {
3014
3068
  ]
3015
3069
  };
3016
3070
  function calculateTotalVestedTeam(currentTime) {
3017
- return import_fp_ts6.array.reduce(0n, (acc, schedule) => {
3071
+ return import_fp_ts7.array.reduce(0n, (acc, schedule) => {
3018
3072
  if (currentTime >= schedule.vestedAtTime) {
3019
3073
  return acc + schedule.unlockAmt;
3020
3074
  } else {
@@ -3072,64 +3126,64 @@ function pollPassQuorum(initialIndyDist, pollStatus, currentTime, minQuorum, tre
3072
3126
  }
3073
3127
 
3074
3128
  // src/contracts/execute/types.ts
3075
- var import_lucid27 = require("@lucid-evolution/lucid");
3076
- var import_fp_ts7 = require("fp-ts");
3077
- var ExecuteParamsSchema = import_lucid27.Data.Object({
3129
+ var import_lucid28 = require("@lucid-evolution/lucid");
3130
+ var import_fp_ts8 = require("fp-ts");
3131
+ var ExecuteParamsSchema = import_lucid28.Data.Object({
3078
3132
  govNFT: AssetClassSchema,
3079
3133
  upgradeToken: AssetClassSchema,
3080
3134
  iAssetToken: AssetClassSchema,
3081
3135
  stabilityPoolToken: AssetClassSchema,
3082
3136
  versionRecordToken: AssetClassSchema,
3083
- cdpValHash: import_lucid27.Data.Bytes(),
3084
- sPoolValHash: import_lucid27.Data.Bytes(),
3085
- versionRegistryValHash: import_lucid27.Data.Bytes(),
3086
- treasuryValHash: import_lucid27.Data.Bytes(),
3137
+ cdpValHash: import_lucid28.Data.Bytes(),
3138
+ sPoolValHash: import_lucid28.Data.Bytes(),
3139
+ versionRegistryValHash: import_lucid28.Data.Bytes(),
3140
+ treasuryValHash: import_lucid28.Data.Bytes(),
3087
3141
  indyAsset: AssetClassSchema
3088
3142
  });
3089
3143
  var ExecuteParams = ExecuteParamsSchema;
3090
- var ExecuteDatumSchema = import_lucid27.Data.Object({
3091
- id: import_lucid27.Data.Integer(),
3144
+ var ExecuteDatumSchema = import_lucid28.Data.Object({
3145
+ id: import_lucid28.Data.Integer(),
3092
3146
  content: ProposalContentSchema,
3093
- passedTime: import_lucid27.Data.Integer(),
3094
- votingEndTime: import_lucid27.Data.Integer(),
3095
- protocolVersion: import_lucid27.Data.Integer(),
3147
+ passedTime: import_lucid28.Data.Integer(),
3148
+ votingEndTime: import_lucid28.Data.Integer(),
3149
+ protocolVersion: import_lucid28.Data.Integer(),
3096
3150
  /// Value proposed to be withdrawn from the treasury as part of the proposal.
3097
- treasuryWithdrawal: import_lucid27.Data.Nullable(TreasuryWithdrawalSchema)
3151
+ treasuryWithdrawal: import_lucid28.Data.Nullable(TreasuryWithdrawalSchema)
3098
3152
  });
3099
3153
  var ExecuteDatum = ExecuteDatumSchema;
3100
3154
  function serialiseExecuteDatum(d) {
3101
- return import_lucid27.Data.to(d, ExecuteDatum);
3155
+ return import_lucid28.Data.to(d, ExecuteDatum);
3102
3156
  }
3103
3157
  function parseExecuteDatum(d) {
3104
3158
  try {
3105
- return import_fp_ts7.option.some(import_lucid27.Data.from(d, ExecuteDatum));
3159
+ return import_fp_ts8.option.some(import_lucid28.Data.from(d, ExecuteDatum));
3106
3160
  } catch (_) {
3107
- return import_fp_ts7.option.none;
3161
+ return import_fp_ts8.option.none;
3108
3162
  }
3109
3163
  }
3110
3164
  function parseExecuteDatumOrThrow(d) {
3111
- return import_fp_ts7.function.pipe(
3165
+ return import_fp_ts8.function.pipe(
3112
3166
  parseExecuteDatum(d),
3113
- import_fp_ts7.option.match(() => {
3167
+ import_fp_ts8.option.match(() => {
3114
3168
  throw new Error("Expected an Execute datum.");
3115
- }, import_fp_ts7.function.identity)
3169
+ }, import_fp_ts8.function.identity)
3116
3170
  );
3117
3171
  }
3118
3172
  function castExecuteParams(params) {
3119
- return import_lucid27.Data.castTo(params, ExecuteParams);
3173
+ return import_lucid28.Data.castTo(params, ExecuteParams);
3120
3174
  }
3121
3175
 
3122
3176
  // src/contracts/gov/helpers.ts
3123
3177
  var import_function = require("fp-ts/lib/function");
3124
- var import_fp_ts8 = require("fp-ts");
3125
- var import_lucid28 = require("@lucid-evolution/lucid");
3178
+ var import_fp_ts9 = require("fp-ts");
3179
+ var import_lucid29 = require("@lucid-evolution/lucid");
3126
3180
  function proposalDeposit(baseDeposit, activeProposals) {
3127
3181
  return baseDeposit * 2n ** activeProposals;
3128
3182
  }
3129
3183
  function createValueFromWithdrawal(w) {
3130
- return import_fp_ts8.array.reduce(
3184
+ return import_fp_ts9.array.reduce(
3131
3185
  {},
3132
- (acc, [cs, tk, amt]) => (0, import_lucid28.addAssets)(acc, mkAssetsOf({ currencySymbol: cs, tokenName: tk }, amt))
3186
+ (acc, [cs, tk, amt]) => (0, import_lucid29.addAssets)(acc, mkAssetsOf({ currencySymbol: cs, tokenName: tk }, amt))
3133
3187
  )(w.value);
3134
3188
  }
3135
3189
  async function findRelativeIAssetForInsertion(newIAssetTokenName, allIAssetOrefs, lucid) {
@@ -3146,22 +3200,22 @@ async function findRelativeIAssetForInsertion(newIAssetTokenName, allIAssetOrefs
3146
3200
  return (0, import_function.pipe)(
3147
3201
  // Sort the asset names
3148
3202
  iassetUtxos,
3149
- import_fp_ts8.array.sort(
3150
- import_fp_ts8.ord.contramap((x) => (0, import_lucid28.toText)(x.datum.assetName))(
3151
- import_fp_ts8.string.Ord
3203
+ import_fp_ts9.array.sort(
3204
+ import_fp_ts9.ord.contramap((x) => (0, import_lucid29.toText)(x.datum.assetName))(
3205
+ import_fp_ts9.string.Ord
3152
3206
  )
3153
3207
  ),
3154
3208
  // split head and tail
3155
- import_fp_ts8.array.foldLeft(
3156
- () => import_fp_ts8.option.none,
3157
- (head, rest) => import_fp_ts8.option.some([head, rest])
3209
+ import_fp_ts9.array.foldLeft(
3210
+ () => import_fp_ts9.option.none,
3211
+ (head, rest) => import_fp_ts9.option.some([head, rest])
3158
3212
  ),
3159
3213
  // find the preceding iasset for the new token name
3160
- import_fp_ts8.option.flatMap(
3161
- ([firstIAsset, rest]) => import_fp_ts8.option.some(
3162
- import_fp_ts8.array.reduce(
3214
+ import_fp_ts9.option.flatMap(
3215
+ ([firstIAsset, rest]) => import_fp_ts9.option.some(
3216
+ import_fp_ts9.array.reduce(
3163
3217
  firstIAsset,
3164
- (acc, iasset) => (0, import_lucid28.toText)(iasset.datum.assetName) < newIAssetTokenName ? iasset : acc
3218
+ (acc, iasset) => (0, import_lucid29.toText)(iasset.datum.assetName) < newIAssetTokenName ? iasset : acc
3165
3219
  )(rest)
3166
3220
  )
3167
3221
  )
@@ -3184,22 +3238,22 @@ function iassetCreationDatumHelper(proposeAssetContent, referencedIAsset) {
3184
3238
  firstIAsset: true,
3185
3239
  nextIAsset: null
3186
3240
  };
3187
- return import_fp_ts8.function.pipe(
3241
+ return import_fp_ts9.function.pipe(
3188
3242
  referencedIAsset,
3189
- import_fp_ts8.option.match(
3243
+ import_fp_ts9.option.match(
3190
3244
  () => ({
3191
3245
  newIAsset: newContent,
3192
- newReferencedIAsset: import_fp_ts8.option.none
3246
+ newReferencedIAsset: import_fp_ts9.option.none
3193
3247
  }),
3194
3248
  (referencedIA) => {
3195
- if ((0, import_lucid28.toText)(proposeAssetContent.asset) < (0, import_lucid28.toText)(referencedIA.assetName)) {
3249
+ if ((0, import_lucid29.toText)(proposeAssetContent.asset) < (0, import_lucid29.toText)(referencedIA.assetName)) {
3196
3250
  return {
3197
3251
  newIAsset: {
3198
3252
  ...newContent,
3199
3253
  firstIAsset: true,
3200
3254
  nextIAsset: referencedIA.assetName
3201
3255
  },
3202
- newReferencedIAsset: import_fp_ts8.option.some({
3256
+ newReferencedIAsset: import_fp_ts9.option.some({
3203
3257
  ...referencedIA,
3204
3258
  firstIAsset: false
3205
3259
  })
@@ -3211,7 +3265,7 @@ function iassetCreationDatumHelper(proposeAssetContent, referencedIAsset) {
3211
3265
  firstIAsset: false,
3212
3266
  nextIAsset: referencedIA.nextIAsset
3213
3267
  },
3214
- newReferencedIAsset: import_fp_ts8.option.some({
3268
+ newReferencedIAsset: import_fp_ts9.option.some({
3215
3269
  ...referencedIA,
3216
3270
  nextIAsset: proposeAssetContent.asset
3217
3271
  })
@@ -3242,9 +3296,9 @@ function serialiseVersionRecordDatum(d) {
3242
3296
  // src/contracts/gov/transactions.ts
3243
3297
  async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lucid, currentSlot, govOref, allIAssetOrefs) {
3244
3298
  const network = lucid.config().network;
3245
- const currentTime = BigInt((0, import_lucid29.slotToUnixTime)(network, currentSlot));
3299
+ const currentTime = BigInt((0, import_lucid30.slotToUnixTime)(network, currentSlot));
3246
3300
  const ownAddr = await lucid.wallet().address();
3247
- const pkh = (0, import_lucid29.paymentCredentialOf)(ownAddr);
3301
+ const pkh = (0, import_lucid30.paymentCredentialOf)(ownAddr);
3248
3302
  const govRefScriptUtxo = matchSingle(
3249
3303
  await lucid.utxosByOutRef([
3250
3304
  fromSystemParamsScriptRef(
@@ -3277,13 +3331,13 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
3277
3331
  const tx = lucid.newTx();
3278
3332
  await (0, import_ts_pattern11.match)(proposalContent).with({ ProposeAsset: { asset: import_ts_pattern11.P.select() } }, async (newAsset) => {
3279
3333
  const relativeIAsset = await findRelativeIAssetForInsertion(
3280
- (0, import_lucid29.toText)(newAsset),
3334
+ (0, import_lucid30.toText)(newAsset),
3281
3335
  allIAssetOrefs,
3282
3336
  lucid
3283
3337
  );
3284
3338
  (0, import_function2.pipe)(
3285
3339
  relativeIAsset,
3286
- import_fp_ts9.option.match(
3340
+ import_fp_ts10.option.match(
3287
3341
  () => {
3288
3342
  if (govDatum.iassetsCount !== 0n) {
3289
3343
  throw new Error(
@@ -3299,7 +3353,7 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
3299
3353
  }).otherwise(() => {
3300
3354
  });
3301
3355
  return [
3302
- tx.mintAssets(pollNftValue, import_lucid30.Data.void()).readFrom([govRefScriptUtxo, pollAuthTokenPolicyRefScriptUtxo]).collectFrom(
3356
+ tx.mintAssets(pollNftValue, import_lucid31.Data.void()).readFrom([govRefScriptUtxo, pollAuthTokenPolicyRefScriptUtxo]).collectFrom(
3303
3357
  [govUtxo],
3304
3358
  serialiseGovRedeemer({
3305
3359
  CreatePoll: {
@@ -3344,7 +3398,7 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
3344
3398
  }
3345
3399
  })
3346
3400
  },
3347
- (0, import_lucid29.addAssets)(
3401
+ (0, import_lucid30.addAssets)(
3348
3402
  pollNftValue,
3349
3403
  mkAssetsOf(
3350
3404
  fromSystemParamsAsset(sysParams.govParams.indyAsset),
@@ -3360,7 +3414,7 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
3360
3414
  }
3361
3415
  async function createShardsChunks(chunkSize, pollManagerOref, sysParams, currentSlot, lucid) {
3362
3416
  const network = lucid.config().network;
3363
- const currentTime = BigInt((0, import_lucid29.slotToUnixTime)(network, currentSlot));
3417
+ const currentTime = BigInt((0, import_lucid30.slotToUnixTime)(network, currentSlot));
3364
3418
  const ownAddr = await lucid.wallet().address();
3365
3419
  const pollManagerUtxo = matchSingle(
3366
3420
  await lucid.utxosByOutRef([pollManagerOref]),
@@ -3397,7 +3451,7 @@ async function createShardsChunks(chunkSize, pollManagerOref, sysParams, current
3397
3451
  const pollNft = fromSystemParamsAsset(sysParams.govParams.pollToken);
3398
3452
  const tx = lucid.newTx().validFrom(Number(currentTime) - ONE_SECOND).validTo(
3399
3453
  Number(currentTime + sysParams.pollManagerParams.pBiasTime) - ONE_SECOND
3400
- ).mintAssets(mkAssetsOf(pollNft, shardsCount), import_lucid30.Data.void()).readFrom([pollAuthTokenPolicyRefScriptUtxo, pollManagerRefScriptUtxo]).collectFrom(
3454
+ ).mintAssets(mkAssetsOf(pollNft, shardsCount), import_lucid31.Data.void()).readFrom([pollAuthTokenPolicyRefScriptUtxo, pollManagerRefScriptUtxo]).collectFrom(
3401
3455
  [pollManagerUtxo],
3402
3456
  serialisePollManagerRedeemer({ CreateShards: { currentTime } })
3403
3457
  ).pay.ToContract(
@@ -3455,7 +3509,7 @@ function voteHelper(stakingPosLockedAmt, pollShard, voteOption, currentTime, ind
3455
3509
  }
3456
3510
  async function vote(voteOption, pollShardOref, stakingPositionOref, sysParams, lucid, currentSlot) {
3457
3511
  const network = lucid.config().network;
3458
- const currentTime = BigInt((0, import_lucid29.slotToUnixTime)(network, currentSlot));
3512
+ const currentTime = BigInt((0, import_lucid30.slotToUnixTime)(network, currentSlot));
3459
3513
  const ownAddr = await lucid.wallet().address();
3460
3514
  const pollShardRefScriptUtxo = matchSingle(
3461
3515
  await lucid.utxosByOutRef([
@@ -3531,7 +3585,7 @@ async function vote(voteOption, pollShardOref, stakingPositionOref, sysParams, l
3531
3585
  }
3532
3586
  async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, currentSlot) {
3533
3587
  const network = lucid.config().network;
3534
- const currentTime = BigInt((0, import_lucid29.slotToUnixTime)(network, currentSlot));
3588
+ const currentTime = BigInt((0, import_lucid30.slotToUnixTime)(network, currentSlot));
3535
3589
  const ownAddr = await lucid.wallet().address();
3536
3590
  const pollShardRefScriptUtxo = matchSingle(
3537
3591
  await lucid.utxosByOutRef([
@@ -3565,10 +3619,10 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3565
3619
  getInlineDatumOrThrow(pollManagerUtxo)
3566
3620
  );
3567
3621
  const shardUtxos = await lucid.utxosByOutRef(shardsOutRefs);
3568
- const aggregatedStatus = import_fp_ts9.function.pipe(
3622
+ const aggregatedStatus = import_fp_ts10.function.pipe(
3569
3623
  shardUtxos,
3570
- import_fp_ts9.array.map((utxo) => parsePollShardOrThrow(getInlineDatumOrThrow(utxo))),
3571
- import_fp_ts9.array.reduce(
3624
+ import_fp_ts10.array.map((utxo) => parsePollShardOrThrow(getInlineDatumOrThrow(utxo))),
3625
+ import_fp_ts10.array.reduce(
3572
3626
  pollManagerDatum.status,
3573
3627
  (acc, shard) => ({
3574
3628
  yesVotes: acc.yesVotes + shard.status.yesVotes,
@@ -3576,9 +3630,9 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3576
3630
  })
3577
3631
  )
3578
3632
  );
3579
- const shardsAggregatedAda = import_fp_ts9.array.reduce(
3633
+ const shardsAggregatedAda = import_fp_ts10.array.reduce(
3580
3634
  {},
3581
- (acc, utxo) => (0, import_lucid29.addAssets)(acc, mkLovelacesOf(lovelacesAmt(utxo.assets)))
3635
+ (acc, utxo) => (0, import_lucid30.addAssets)(acc, mkLovelacesOf(lovelacesAmt(utxo.assets)))
3582
3636
  )(shardUtxos);
3583
3637
  const pollNft = fromSystemParamsAsset(sysParams.govParams.pollToken);
3584
3638
  return lucid.newTx().validFrom(Number(currentTime) - ONE_SECOND).validTo(
@@ -3587,7 +3641,7 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3587
3641
  pollShardRefScriptUtxo,
3588
3642
  pollManagerRefScriptUtxo,
3589
3643
  pollAuthTokenPolicyRefScriptUtxo
3590
- ]).mintAssets(mkAssetsOf(pollNft, -BigInt(shardsOutRefs.length)), import_lucid30.Data.void()).collectFrom(
3644
+ ]).mintAssets(mkAssetsOf(pollNft, -BigInt(shardsOutRefs.length)), import_lucid31.Data.void()).collectFrom(
3591
3645
  [pollManagerUtxo],
3592
3646
  serialisePollManagerRedeemer({
3593
3647
  MergeShardsManager: { currentTime }
@@ -3617,12 +3671,12 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3617
3671
  }
3618
3672
  })
3619
3673
  },
3620
- (0, import_lucid29.addAssets)(pollManagerUtxo.assets, shardsAggregatedAda)
3674
+ (0, import_lucid30.addAssets)(pollManagerUtxo.assets, shardsAggregatedAda)
3621
3675
  ).addSigner(ownAddr);
3622
3676
  }
3623
3677
  async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSlot) {
3624
3678
  const network = lucid.config().network;
3625
- const currentTime = BigInt((0, import_lucid29.slotToUnixTime)(network, currentSlot));
3679
+ const currentTime = BigInt((0, import_lucid30.slotToUnixTime)(network, currentSlot));
3626
3680
  const ownAddr = await lucid.wallet().address();
3627
3681
  const pollManagerRefScriptUtxo = matchSingle(
3628
3682
  await lucid.utxosByOutRef([
@@ -3697,7 +3751,7 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3697
3751
  ).collectFrom(
3698
3752
  [govUtxo],
3699
3753
  serialiseGovRedeemer({ WitnessEndPoll: { currentTime } })
3700
- ).mintAssets(mkAssetsOf(pollNft, -1n), import_lucid30.Data.void()).pay.ToContract(
3754
+ ).mintAssets(mkAssetsOf(pollNft, -1n), import_lucid31.Data.void()).pay.ToContract(
3701
3755
  govUtxo.address,
3702
3756
  {
3703
3757
  kind: "inline",
@@ -3723,11 +3777,11 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3723
3777
  })
3724
3778
  },
3725
3779
  upgradeTokenVal
3726
- ).mintAssets(upgradeTokenVal, import_lucid30.Data.void());
3780
+ ).mintAssets(upgradeTokenVal, import_lucid31.Data.void());
3727
3781
  } else {
3728
3782
  tx.pay.ToContract(
3729
3783
  createScriptAddress(network, sysParams.validatorHashes.treasuryHash),
3730
- { kind: "inline", value: import_lucid30.Data.void() },
3784
+ { kind: "inline", value: import_lucid31.Data.void() },
3731
3785
  mkAssetsOf(
3732
3786
  indyAsset,
3733
3787
  assetClassValueOf(pollManagerUtxo.assets, indyAsset)
@@ -3738,7 +3792,7 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3738
3792
  }
3739
3793
  async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, allIAssetOrefs, modifyIAssetOref, sysParams, lucid, currentSlot) {
3740
3794
  const network = lucid.config().network;
3741
- const currentTime = BigInt((0, import_lucid29.slotToUnixTime)(network, currentSlot));
3795
+ const currentTime = BigInt((0, import_lucid30.slotToUnixTime)(network, currentSlot));
3742
3796
  const ownAddr = await lucid.wallet().address();
3743
3797
  const govUtxo = matchSingle(
3744
3798
  await lucid.utxosByOutRef([govOref]),
@@ -3784,8 +3838,8 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3784
3838
  );
3785
3839
  const tx = lucid.newTx();
3786
3840
  await (0, import_function2.pipe)(
3787
- import_fp_ts9.option.fromNullable(executeDatum.treasuryWithdrawal),
3788
- import_fp_ts9.option.match(
3841
+ import_fp_ts10.option.fromNullable(executeDatum.treasuryWithdrawal),
3842
+ import_fp_ts10.option.match(
3789
3843
  () => {
3790
3844
  if (treasuryWithdrawalOref) {
3791
3845
  throw new Error("Cannot provide withdrawal oref when no withdrawal.");
@@ -3809,7 +3863,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3809
3863
  (_) => new Error("Expected a single withdrawal UTXO")
3810
3864
  );
3811
3865
  const withdrawalVal = createValueFromWithdrawal(withdrawal);
3812
- const withdrawalChangeVal = (0, import_lucid29.addAssets)(
3866
+ const withdrawalChangeVal = (0, import_lucid30.addAssets)(
3813
3867
  treasuryWithdrawalUtxo.assets,
3814
3868
  negateAssets(withdrawalVal)
3815
3869
  );
@@ -3822,7 +3876,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3822
3876
  sysParams.treasuryParams.treasuryUtxosStakeCredential
3823
3877
  ) : void 0
3824
3878
  ),
3825
- { kind: "inline", value: import_lucid30.Data.void() },
3879
+ { kind: "inline", value: import_lucid31.Data.void() },
3826
3880
  withdrawalChangeVal
3827
3881
  );
3828
3882
  }
@@ -3834,7 +3888,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3834
3888
  {
3835
3889
  kind: "inline",
3836
3890
  value: serialiseWithdrawalOutputDatum([
3837
- (0, import_lucid29.fromText)("IndigoTreasuryWithdrawal"),
3891
+ (0, import_lucid30.fromText)("IndigoTreasuryWithdrawal"),
3838
3892
  {
3839
3893
  txHash: { hash: executeUtxo.txHash },
3840
3894
  outputIndex: BigInt(executeUtxo.outputIndex)
@@ -3875,15 +3929,15 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3875
3929
  throw new Error("Have to provide all iasset orefs when propose asset.");
3876
3930
  }
3877
3931
  const iassetToReference = await findRelativeIAssetForInsertion(
3878
- (0, import_lucid29.toText)(proposeContent.asset),
3932
+ (0, import_lucid30.toText)(proposeContent.asset),
3879
3933
  allIAssetOrefs,
3880
3934
  lucid
3881
3935
  );
3882
3936
  const { newIAsset, newReferencedIAsset } = iassetCreationDatumHelper(
3883
3937
  proposeContent,
3884
- import_fp_ts9.function.pipe(
3938
+ import_fp_ts10.function.pipe(
3885
3939
  iassetToReference,
3886
- import_fp_ts9.option.map((i) => i.datum)
3940
+ import_fp_ts10.option.map((i) => i.datum)
3887
3941
  )
3888
3942
  );
3889
3943
  const iassetAuthVal = mkAssetsOf(
@@ -3899,7 +3953,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3899
3953
  cdpRefScriptUtxo,
3900
3954
  iassetTokenPolicyRefScriptUtxo,
3901
3955
  stabilityPoolTokenPolicyRefScriptUtxo
3902
- ]).mintAssets(spAuthVal, import_lucid30.Data.void()).mintAssets(iassetAuthVal, import_lucid30.Data.void()).collectFrom([govUtxo], serialiseGovRedeemer("UpgradeGov")).pay.ToContract(
3956
+ ]).mintAssets(spAuthVal, import_lucid31.Data.void()).mintAssets(iassetAuthVal, import_lucid31.Data.void()).collectFrom([govUtxo], serialiseGovRedeemer("UpgradeGov")).pay.ToContract(
3903
3957
  govUtxo.address,
3904
3958
  {
3905
3959
  kind: "inline",
@@ -3924,7 +3978,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3924
3978
  value: serialiseStabilityPoolDatum(
3925
3979
  {
3926
3980
  StabilityPool: {
3927
- asset: (0, import_lucid29.fromHex)(proposeContent.asset),
3981
+ asset: (0, import_lucid30.fromHex)(proposeContent.asset),
3928
3982
  poolSnapshot: initSpSnapshot,
3929
3983
  epochToScaleToSum: initEpochToScaleToSumMap()
3930
3984
  }
@@ -3934,14 +3988,14 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3934
3988
  },
3935
3989
  spAuthVal
3936
3990
  );
3937
- import_fp_ts9.function.pipe(
3991
+ import_fp_ts10.function.pipe(
3938
3992
  iassetToReference,
3939
- import_fp_ts9.option.match(
3993
+ import_fp_ts10.option.match(
3940
3994
  () => {
3941
3995
  },
3942
- (i) => import_fp_ts9.function.pipe(
3996
+ (i) => import_fp_ts10.function.pipe(
3943
3997
  newReferencedIAsset,
3944
- import_fp_ts9.option.match(
3998
+ import_fp_ts10.option.match(
3945
3999
  () => {
3946
4000
  throw new Error("Expected some referenced iasset.");
3947
4001
  },
@@ -4065,7 +4119,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
4065
4119
  fromSystemParamsAsset(sysParams.executeParams.versionRecordToken),
4066
4120
  1n
4067
4121
  );
4068
- tx.readFrom([govRefScriptUtxo, versionRecordTokenPolicyRefScriptUtxo]).mintAssets(versionRecordNftVal, import_lucid30.Data.void()).pay.ToContract(
4122
+ tx.readFrom([govRefScriptUtxo, versionRecordTokenPolicyRefScriptUtxo]).mintAssets(versionRecordNftVal, import_lucid31.Data.void()).pay.ToContract(
4069
4123
  createScriptAddress(
4070
4124
  network,
4071
4125
  sysParams.validatorHashes.versionRegistryHash
@@ -4093,52 +4147,52 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
4093
4147
  govUtxo.assets
4094
4148
  );
4095
4149
  }).exhaustive();
4096
- tx.readFrom([upgradeTokenPolicyRefScriptUtxo, executeRefScriptUtxo]).validFrom(Number(currentTime) - ONE_SECOND).validTo(Number(currentTime + sysParams.govParams.gBiasTime) - ONE_SECOND).collectFrom([executeUtxo], import_lucid30.Data.void()).mintAssets(
4150
+ tx.readFrom([upgradeTokenPolicyRefScriptUtxo, executeRefScriptUtxo]).validFrom(Number(currentTime) - ONE_SECOND).validTo(Number(currentTime + sysParams.govParams.gBiasTime) - ONE_SECOND).collectFrom([executeUtxo], import_lucid31.Data.void()).mintAssets(
4097
4151
  mkAssetsOf(fromSystemParamsAsset(sysParams.govParams.upgradeToken), -1n),
4098
- import_lucid30.Data.void()
4152
+ import_lucid31.Data.void()
4099
4153
  ).addSigner(ownAddr);
4100
4154
  return tx;
4101
4155
  }
4102
4156
 
4103
4157
  // src/contracts/stability-pool/transactions.ts
4104
- var import_lucid33 = require("@lucid-evolution/lucid");
4158
+ var import_lucid34 = require("@lucid-evolution/lucid");
4105
4159
 
4106
4160
  // src/contracts/stability-pool/types.ts
4107
- var import_lucid31 = require("@lucid-evolution/lucid");
4108
- var ActionReturnDatumSchema = import_lucid31.Data.Enum([
4109
- import_lucid31.Data.Object({
4110
- IndigoStabilityPoolAccountAdjustment: import_lucid31.Data.Object({
4161
+ var import_lucid32 = require("@lucid-evolution/lucid");
4162
+ var ActionReturnDatumSchema = import_lucid32.Data.Enum([
4163
+ import_lucid32.Data.Object({
4164
+ IndigoStabilityPoolAccountAdjustment: import_lucid32.Data.Object({
4111
4165
  spent_account: OutputReferenceSchema
4112
4166
  })
4113
4167
  }),
4114
- import_lucid31.Data.Object({
4115
- IndigoStabilityPoolAccountClosure: import_lucid31.Data.Object({
4168
+ import_lucid32.Data.Object({
4169
+ IndigoStabilityPoolAccountClosure: import_lucid32.Data.Object({
4116
4170
  closed_account: OutputReferenceSchema
4117
4171
  })
4118
4172
  })
4119
4173
  ]);
4120
4174
  var ActionReturnDatum = ActionReturnDatumSchema;
4121
- var StabilityPoolParamsSchema = import_lucid31.Data.Object({
4122
- assetSymbol: import_lucid31.Data.Bytes(),
4175
+ var StabilityPoolParamsSchema = import_lucid32.Data.Object({
4176
+ assetSymbol: import_lucid32.Data.Bytes(),
4123
4177
  stabilityPoolToken: AssetClassSchema,
4124
4178
  snapshotEpochToScaleToSumToken: AssetClassSchema,
4125
4179
  accountToken: AssetClassSchema,
4126
4180
  cdpToken: AssetClassSchema,
4127
4181
  iAssetAuthToken: AssetClassSchema,
4128
4182
  versionRecordToken: AssetClassSchema,
4129
- collectorValHash: import_lucid31.Data.Bytes(),
4183
+ collectorValHash: import_lucid32.Data.Bytes(),
4130
4184
  govNFT: AssetClassSchema,
4131
- accountCreateFeeLovelaces: import_lucid31.Data.Integer(),
4132
- accountAdjustmentFeeLovelaces: import_lucid31.Data.Integer(),
4133
- requestCollateralLovelaces: import_lucid31.Data.Integer()
4185
+ accountCreateFeeLovelaces: import_lucid32.Data.Integer(),
4186
+ accountAdjustmentFeeLovelaces: import_lucid32.Data.Integer(),
4187
+ requestCollateralLovelaces: import_lucid32.Data.Integer()
4134
4188
  });
4135
4189
  var StabilityPoolParams = StabilityPoolParamsSchema;
4136
4190
  function castStabilityPoolParams(params) {
4137
- return import_lucid31.Data.castTo(params, StabilityPoolParams);
4191
+ return import_lucid32.Data.castTo(params, StabilityPoolParams);
4138
4192
  }
4139
4193
 
4140
4194
  // src/contracts/stability-pool/scripts.ts
4141
- var import_lucid32 = require("@lucid-evolution/lucid");
4195
+ var import_lucid33 = require("@lucid-evolution/lucid");
4142
4196
 
4143
4197
  // src/validators/stability-pool-validator.ts
4144
4198
  var _stabilityPoolValidator = {
@@ -4151,7 +4205,7 @@ var _stabilityPoolValidator = {
4151
4205
  var mkStabilityPoolValidatorFromSP = (params) => {
4152
4206
  return {
4153
4207
  type: "PlutusV2",
4154
- script: (0, import_lucid32.applyParamsToScript)(_stabilityPoolValidator.cborHex, [
4208
+ script: (0, import_lucid33.applyParamsToScript)(_stabilityPoolValidator.cborHex, [
4155
4209
  castStabilityPoolParams({
4156
4210
  assetSymbol: params.assetSymbol.unCurrencySymbol,
4157
4211
  stabilityPoolToken: fromSystemParamsAsset(params.stabilityPoolToken),
@@ -4182,8 +4236,8 @@ async function createSpAccount(asset, amount, params, lucid) {
4182
4236
  params.stabilityPoolParams.accountCreateFeeLovelaces + params.stabilityPoolParams.requestCollateralLovelaces
4183
4237
  );
4184
4238
  const datum = {
4185
- owner: (0, import_lucid33.fromHex)(pkh.hash),
4186
- asset: (0, import_lucid33.fromHex)((0, import_lucid33.fromText)(asset)),
4239
+ owner: (0, import_lucid34.fromHex)(pkh.hash),
4240
+ asset: (0, import_lucid34.fromHex)((0, import_lucid34.fromText)(asset)),
4187
4241
  accountSnapshot: {
4188
4242
  productVal: { value: 0n },
4189
4243
  depositVal: { value: 0n },
@@ -4194,8 +4248,8 @@ async function createSpAccount(asset, amount, params, lucid) {
4194
4248
  request: "Create"
4195
4249
  };
4196
4250
  return lucid.newTx().pay.ToContract(
4197
- (0, import_lucid33.credentialToAddress)(lucid.config().network, {
4198
- hash: (0, import_lucid33.validatorToScriptHash)(
4251
+ (0, import_lucid34.credentialToAddress)(lucid.config().network, {
4252
+ hash: (0, import_lucid34.validatorToScriptHash)(
4199
4253
  mkStabilityPoolValidatorFromSP(params.stabilityPoolParams)
4200
4254
  ),
4201
4255
  type: "Script"
@@ -4206,7 +4260,7 @@ async function createSpAccount(asset, amount, params, lucid) {
4206
4260
  },
4207
4261
  {
4208
4262
  lovelace: minLovelaces,
4209
- [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)]: amount
4263
+ [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)]: amount
4210
4264
  }
4211
4265
  ).addSignerKey(pkh.hash);
4212
4266
  }
@@ -4232,10 +4286,10 @@ async function adjustSpAccount(asset, amount, accountUtxo, params, lucid) {
4232
4286
  lovelace: BigInt(
4233
4287
  params.stabilityPoolParams.requestCollateralLovelaces + params.stabilityPoolParams.accountAdjustmentFeeLovelaces
4234
4288
  ),
4235
- [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4289
+ [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4236
4290
  };
4237
4291
  if (amount > 0n) {
4238
- value[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)] = amount;
4292
+ value[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)] = amount;
4239
4293
  }
4240
4294
  return lucid.newTx().readFrom([stabilityPoolScriptRef]).collectFrom(
4241
4295
  [accountUtxo],
@@ -4248,8 +4302,8 @@ async function adjustSpAccount(asset, amount, accountUtxo, params, lucid) {
4248
4302
  }
4249
4303
  })
4250
4304
  ).pay.ToContract(
4251
- (0, import_lucid33.credentialToAddress)(lucid.config().network, {
4252
- hash: (0, import_lucid33.validatorToScriptHash)(
4305
+ (0, import_lucid34.credentialToAddress)(lucid.config().network, {
4306
+ hash: (0, import_lucid34.validatorToScriptHash)(
4253
4307
  mkStabilityPoolValidatorFromSP(params.stabilityPoolParams)
4254
4308
  ),
4255
4309
  type: "Script"
@@ -4261,7 +4315,7 @@ async function adjustSpAccount(asset, amount, accountUtxo, params, lucid) {
4261
4315
  })
4262
4316
  },
4263
4317
  value
4264
- ).addSignerKey((0, import_lucid33.toHex)(oldAccountDatum.owner));
4318
+ ).addSignerKey((0, import_lucid34.toHex)(oldAccountDatum.owner));
4265
4319
  }
4266
4320
  async function closeSpAccount(accountUtxo, params, lucid) {
4267
4321
  const myAddress = await lucid.wallet().address();
@@ -4285,8 +4339,8 @@ async function closeSpAccount(accountUtxo, params, lucid) {
4285
4339
  [accountUtxo],
4286
4340
  serialiseStabilityPoolRedeemer({ RequestAction: request })
4287
4341
  ).pay.ToContract(
4288
- (0, import_lucid33.credentialToAddress)(lucid.config().network, {
4289
- hash: (0, import_lucid33.validatorToScriptHash)(
4342
+ (0, import_lucid34.credentialToAddress)(lucid.config().network, {
4343
+ hash: (0, import_lucid34.validatorToScriptHash)(
4290
4344
  mkStabilityPoolValidatorFromSP(params.stabilityPoolParams)
4291
4345
  ),
4292
4346
  type: "Script"
@@ -4299,14 +4353,14 @@ async function closeSpAccount(accountUtxo, params, lucid) {
4299
4353
  lovelace: BigInt(
4300
4354
  params.stabilityPoolParams.requestCollateralLovelaces + params.stabilityPoolParams.accountAdjustmentFeeLovelaces
4301
4355
  ),
4302
- [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4356
+ [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4303
4357
  }
4304
- ).addSignerKey((0, import_lucid33.toHex)(oldAccountDatum.owner));
4358
+ ).addSignerKey((0, import_lucid34.toHex)(oldAccountDatum.owner));
4305
4359
  }
4306
4360
  async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo, iAssetUtxo, newSnapshotUtxo, params, lucid, collectorOref) {
4307
4361
  const redeemer = {
4308
4362
  ProcessRequest: {
4309
- txHash: { hash: (0, import_lucid33.fromHex)(accountUtxo.txHash) },
4363
+ txHash: { hash: (0, import_lucid34.fromHex)(accountUtxo.txHash) },
4310
4364
  outputIndex: BigInt(accountUtxo.outputIndex)
4311
4365
  }
4312
4366
  };
@@ -4326,7 +4380,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4326
4380
  lucid
4327
4381
  );
4328
4382
  tx.readFrom([accountTokenScriptRef]);
4329
- const iassetUnit = params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset);
4383
+ const iassetUnit = params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset);
4330
4384
  const reqAmount = accountUtxo.assets[iassetUnit] ?? 0n;
4331
4385
  const newAccountSnapshot = {
4332
4386
  ...stabilityPoolDatum.poolSnapshot,
@@ -4367,14 +4421,14 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4367
4421
  const stabilityPoolAssetToken = stabilityPoolUtxo.assets[iassetUnit] ?? 0n;
4368
4422
  const poolOutputValue = {
4369
4423
  lovelace: stabilityPoolUtxo.assets.lovelace + BigInt(params.stabilityPoolParams.accountCreateFeeLovelaces),
4370
- [params.stabilityPoolParams.stabilityPoolToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.stabilityPoolToken[1].unTokenName)]: 1n,
4371
- [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)]: stabilityPoolAssetToken + reqAmount
4424
+ [params.stabilityPoolParams.stabilityPoolToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.stabilityPoolToken[1].unTokenName)]: 1n,
4425
+ [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)]: stabilityPoolAssetToken + reqAmount
4372
4426
  };
4373
4427
  tx.mintAssets(
4374
4428
  {
4375
- [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4429
+ [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4376
4430
  },
4377
- import_lucid33.Data.to(new import_lucid33.Constr(0, []))
4431
+ import_lucid34.Data.to(new import_lucid34.Constr(0, []))
4378
4432
  );
4379
4433
  tx.pay.ToContract(
4380
4434
  stabilityPoolUtxo.address,
@@ -4404,7 +4458,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4404
4458
  },
4405
4459
  {
4406
4460
  lovelace: accountUtxo.assets.lovelace - BigInt(params.stabilityPoolParams.accountCreateFeeLovelaces),
4407
- [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4461
+ [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4408
4462
  }
4409
4463
  );
4410
4464
  } else if ("Adjust" in accountDatum.request) {
@@ -4485,12 +4539,14 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4485
4539
  stabilityPoolDatum.poolSnapshot.scale,
4486
4540
  newPoolSum
4487
4541
  );
4488
- console.log("balanceChange", balanceChange);
4489
- console.log("withdrawalFee", withdrawalFee);
4490
- console.log("rewardLovelacesFee", rewardLovelacesFee);
4491
- console.log("reward", reward);
4492
4542
  if (rewardLovelacesFee > 0n) {
4493
- await collectorFeeTx(rewardLovelacesFee, lucid, params, tx, collectorOref);
4543
+ await collectorFeeTx(
4544
+ rewardLovelacesFee,
4545
+ lucid,
4546
+ params,
4547
+ tx,
4548
+ collectorOref
4549
+ );
4494
4550
  }
4495
4551
  tx.readFrom([govUtxo, iAssetUtxo, ...refInputs]);
4496
4552
  tx.pay.ToContract(
@@ -4507,8 +4563,8 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4507
4563
  },
4508
4564
  {
4509
4565
  lovelace: stabilityPoolUtxo.assets.lovelace + BigInt(params.stabilityPoolParams.accountAdjustmentFeeLovelaces) - reward,
4510
- [params.stabilityPoolParams.stabilityPoolToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.stabilityPoolToken[1].unTokenName)]: 1n,
4511
- [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)]: stabilityPoolUtxo.assets[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)] + balanceChange + withdrawalFee
4566
+ [params.stabilityPoolParams.stabilityPoolToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.stabilityPoolToken[1].unTokenName)]: 1n,
4567
+ [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)]: stabilityPoolUtxo.assets[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)] + balanceChange + withdrawalFee
4512
4568
  }
4513
4569
  );
4514
4570
  tx.pay.ToContract(
@@ -4525,7 +4581,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4525
4581
  },
4526
4582
  {
4527
4583
  lovelace: accountUtxo.assets.lovelace - BigInt(params.stabilityPoolParams.accountAdjustmentFeeLovelaces) - 2000000n,
4528
- [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4584
+ [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4529
4585
  }
4530
4586
  );
4531
4587
  if (myAddress !== outputAddress) {
@@ -4533,7 +4589,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4533
4589
  outputAddress,
4534
4590
  {
4535
4591
  kind: "inline",
4536
- value: import_lucid33.Data.to(
4592
+ value: import_lucid34.Data.to(
4537
4593
  {
4538
4594
  IndigoStabilityPoolAccountAdjustment: {
4539
4595
  spent_account: {
@@ -4548,7 +4604,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4548
4604
  {
4549
4605
  lovelace: reward - rewardLovelacesFee + 2000000n,
4550
4606
  ...!isDepositOrRewardWithdrawal ? {
4551
- [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)]: -balanceChange - withdrawalFee
4607
+ [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)]: -balanceChange - withdrawalFee
4552
4608
  } : {}
4553
4609
  }
4554
4610
  );
@@ -4605,11 +4661,11 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4605
4661
  tx.readFrom([govUtxo, iAssetUtxo, accountTokenRef, ...refInputs]);
4606
4662
  tx.mintAssets(
4607
4663
  {
4608
- [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: -1n
4664
+ [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.accountToken[1].unTokenName)]: -1n
4609
4665
  },
4610
- import_lucid33.Data.to(new import_lucid33.Constr(0, []))
4666
+ import_lucid34.Data.to(new import_lucid34.Constr(0, []))
4611
4667
  );
4612
- const assetOutputAmountForSP = stabilityPoolUtxo.assets[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)] - fromSPInteger(withdrawnAmt) - withdrawalFeeAmount;
4668
+ const assetOutputAmountForSP = stabilityPoolUtxo.assets[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)] - fromSPInteger(withdrawnAmt) - withdrawalFeeAmount;
4613
4669
  tx.pay.ToContract(
4614
4670
  stabilityPoolUtxo.address,
4615
4671
  {
@@ -4623,9 +4679,9 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4623
4679
  },
4624
4680
  {
4625
4681
  lovelace: stabilityPoolUtxo.assets.lovelace - reward,
4626
- [params.stabilityPoolParams.stabilityPoolToken[0].unCurrencySymbol + (0, import_lucid33.fromText)(params.stabilityPoolParams.stabilityPoolToken[1].unTokenName)]: 1n,
4682
+ [params.stabilityPoolParams.stabilityPoolToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stabilityPoolParams.stabilityPoolToken[1].unTokenName)]: 1n,
4627
4683
  ...assetOutputAmountForSP > 0n ? {
4628
- [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)]: assetOutputAmountForSP
4684
+ [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)]: assetOutputAmountForSP
4629
4685
  } : {}
4630
4686
  }
4631
4687
  );
@@ -4634,7 +4690,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4634
4690
  outputAddress,
4635
4691
  {
4636
4692
  kind: "inline",
4637
- value: import_lucid33.Data.to(
4693
+ value: import_lucid34.Data.to(
4638
4694
  {
4639
4695
  IndigoStabilityPoolAccountClosure: {
4640
4696
  closed_account: {
@@ -4648,7 +4704,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4648
4704
  },
4649
4705
  {
4650
4706
  lovelace: accountUtxo.assets.lovelace + reward - rewardLovelacesFee,
4651
- [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid33.fromText)(asset)]: fromSPInteger(withdrawnAmt) - withdrawalFeeAmount
4707
+ [params.stabilityPoolParams.assetSymbol.unCurrencySymbol + (0, import_lucid34.fromText)(asset)]: fromSPInteger(withdrawnAmt) - withdrawalFeeAmount
4652
4708
  }
4653
4709
  );
4654
4710
  }
@@ -4657,7 +4713,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4657
4713
  }
4658
4714
 
4659
4715
  // src/contracts/staking/transactions.ts
4660
- var import_lucid34 = require("@lucid-evolution/lucid");
4716
+ var import_lucid35 = require("@lucid-evolution/lucid");
4661
4717
  async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4662
4718
  const [pkh, _] = await addrDetails(lucid);
4663
4719
  const stakingManagerOut = stakingManagerRef ? await findStakingManagerByOutRef(stakingManagerRef, lucid) : await findStakingManager(params, lucid);
@@ -4682,15 +4738,15 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4682
4738
  }
4683
4739
  };
4684
4740
  const stakingPositionDatum = {
4685
- owner: (0, import_lucid34.fromHex)(pkh.hash),
4741
+ owner: (0, import_lucid35.fromHex)(pkh.hash),
4686
4742
  lockedAmount: /* @__PURE__ */ new Map([]),
4687
4743
  positionSnapshot: {
4688
4744
  snapshotAda: stakingManagerOut.datum.managerSnapshot.snapshotAda
4689
4745
  }
4690
4746
  };
4691
- const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.stakingToken[1].unTokenName);
4692
- const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.indyToken[1].unTokenName);
4693
- return lucid.newTx().collectFrom([stakingManagerOut.utxo], import_lucid34.Data.to(new import_lucid34.Constr(0, [pkh.hash]))).readFrom([stakingRefScriptUtxo]).pay.ToContract(
4747
+ const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.stakingToken[1].unTokenName);
4748
+ const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.indyToken[1].unTokenName);
4749
+ return lucid.newTx().collectFrom([stakingManagerOut.utxo], import_lucid35.Data.to(new import_lucid35.Constr(0, [pkh.hash]))).readFrom([stakingRefScriptUtxo]).pay.ToContract(
4694
4750
  stakingManagerOut.utxo.address,
4695
4751
  {
4696
4752
  kind: "inline",
@@ -4701,7 +4757,7 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4701
4757
  {
4702
4758
  [stakingToken]: 1n
4703
4759
  },
4704
- import_lucid34.Data.void()
4760
+ import_lucid35.Data.void()
4705
4761
  ).pay.ToContract(
4706
4762
  stakingManagerOut.utxo.address,
4707
4763
  {
@@ -4727,18 +4783,26 @@ async function adjustStakingPosition(stakingPositionRef, amount, params, lucid,
4727
4783
  ]),
4728
4784
  (_) => new Error("Expected a single staking Ref Script UTXO")
4729
4785
  );
4730
- const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.stakingToken[1].unTokenName);
4731
- const stakingManagerToken = params.stakingParams.stakingManagerNFT[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.stakingManagerNFT[1].unTokenName);
4732
- const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.indyToken[1].unTokenName);
4786
+ const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.stakingToken[1].unTokenName);
4787
+ const stakingManagerToken = params.stakingParams.stakingManagerNFT[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.stakingManagerNFT[1].unTokenName);
4788
+ const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.indyToken[1].unTokenName);
4733
4789
  const existingIndyAmount = stakingPositionOut.utxo.assets[indyToken] ?? 0n;
4734
4790
  const currentSnapshotAda = stakingManagerOut.datum.managerSnapshot.snapshotAda;
4735
4791
  const oldSnapshotAda = stakingPositionOut.datum.positionSnapshot.snapshotAda;
4736
- const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / (1000000n * 1000000n);
4792
+ const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / rewardSnapshotPrecision;
4737
4793
  const newLockedAmount = updateStakingLockedAmount(
4738
4794
  stakingPositionOut.datum.lockedAmount,
4739
4795
  BigInt(now)
4740
4796
  );
4741
- return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo]).collectFrom([stakingPositionOut.utxo], import_lucid34.Data.to(new import_lucid34.Constr(3, [amount]))).collectFrom([stakingManagerOut.utxo], import_lucid34.Data.to(new import_lucid34.Constr(1, []))).pay.ToContract(
4797
+ return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo]).collectFrom(
4798
+ [stakingPositionOut.utxo],
4799
+ serialiseStakingRedeemer({
4800
+ AdjustStakedAmount: { adjustAmount: amount }
4801
+ })
4802
+ ).collectFrom(
4803
+ [stakingManagerOut.utxo],
4804
+ serialiseStakingRedeemer("UpdateTotalStake")
4805
+ ).pay.ToContract(
4742
4806
  stakingManagerOut.utxo.address,
4743
4807
  {
4744
4808
  kind: "inline",
@@ -4764,7 +4828,7 @@ async function adjustStakingPosition(stakingPositionRef, amount, params, lucid,
4764
4828
  [stakingToken]: 1n,
4765
4829
  [indyToken]: stakingPositionOut.utxo.assets[indyToken] + amount
4766
4830
  }
4767
- ).addSignerKey((0, import_lucid34.toHex)(stakingPositionOut.datum.owner));
4831
+ ).addSignerKey((0, import_lucid35.toHex)(stakingPositionOut.datum.owner));
4768
4832
  }
4769
4833
  async function closeStakingPosition(stakingPositionRef, params, lucid, stakingManagerRef) {
4770
4834
  const stakingPositionOut = await findStakingPositionByOutRef(
@@ -4786,14 +4850,14 @@ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingMa
4786
4850
  ]),
4787
4851
  (_) => new Error("Expected a single staking token policy Ref Script UTXO")
4788
4852
  );
4789
- const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.stakingToken[1].unTokenName);
4790
- const stakingManagerToken = params.stakingParams.stakingManagerNFT[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.stakingManagerNFT[1].unTokenName);
4791
- const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + (0, import_lucid34.fromText)(params.stakingParams.indyToken[1].unTokenName);
4853
+ const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.stakingToken[1].unTokenName);
4854
+ const stakingManagerToken = params.stakingParams.stakingManagerNFT[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.stakingManagerNFT[1].unTokenName);
4855
+ const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + (0, import_lucid35.fromText)(params.stakingParams.indyToken[1].unTokenName);
4792
4856
  const existingIndyAmount = stakingPositionOut.utxo.assets[indyToken] ?? 0n;
4793
4857
  const currentSnapshotAda = stakingManagerOut.datum.managerSnapshot.snapshotAda;
4794
4858
  const oldSnapshotAda = stakingPositionOut.datum.positionSnapshot.snapshotAda;
4795
4859
  const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / (1000000n * 1000000n);
4796
- return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo, stakingTokenPolicyRefScriptUtxo]).collectFrom([stakingPositionOut.utxo], import_lucid34.Data.to(new import_lucid34.Constr(4, []))).collectFrom([stakingManagerOut.utxo], import_lucid34.Data.to(new import_lucid34.Constr(1, []))).pay.ToContract(
4860
+ return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo, stakingTokenPolicyRefScriptUtxo]).collectFrom([stakingPositionOut.utxo], import_lucid35.Data.to(new import_lucid35.Constr(4, []))).collectFrom([stakingManagerOut.utxo], import_lucid35.Data.to(new import_lucid35.Constr(1, []))).pay.ToContract(
4797
4861
  stakingManagerOut.utxo.address,
4798
4862
  {
4799
4863
  kind: "inline",
@@ -4810,37 +4874,91 @@ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingMa
4810
4874
  {
4811
4875
  [stakingToken]: -1n
4812
4876
  },
4813
- import_lucid34.Data.void()
4814
- ).addSignerKey((0, import_lucid34.toHex)(stakingPositionOut.datum.owner));
4877
+ import_lucid35.Data.void()
4878
+ ).addSignerKey((0, import_lucid35.toHex)(stakingPositionOut.datum.owner));
4879
+ }
4880
+ var MIN_UTXO_AMOUNT = 2000000n;
4881
+ async function distributeAda(stakingManagerRef, collectorRefs, params, lucid) {
4882
+ const [stakingManagerUtxo] = await lucid.utxosByOutRef([stakingManagerRef]);
4883
+ const stakingManagerDatum = parseStakingManagerDatum(
4884
+ getInlineDatumOrThrow(stakingManagerUtxo)
4885
+ );
4886
+ const collectorUtxos = (await lucid.utxosByOutRef(collectorRefs)).filter((utxo) => utxo.datum && utxo.datum === import_lucid35.Data.void()).filter((utxo) => utxo.assets.lovelace > MIN_UTXO_AMOUNT);
4887
+ if (collectorUtxos.length === 0) {
4888
+ throw new Error("No available collectors found");
4889
+ }
4890
+ const adaRewardCollected = collectorUtxos.reduce(
4891
+ (acc, utxo) => acc + utxo.assets.lovelace - MIN_UTXO_AMOUNT,
4892
+ 0n
4893
+ );
4894
+ const newSnapshot = distributeReward(
4895
+ stakingManagerDatum.managerSnapshot.snapshotAda,
4896
+ adaRewardCollected,
4897
+ stakingManagerDatum.totalStake
4898
+ );
4899
+ const stakingRefScriptUtxo = matchSingle(
4900
+ await lucid.utxosByOutRef([
4901
+ fromSystemParamsScriptRef(params.scriptReferences.stakingValidatorRef)
4902
+ ]),
4903
+ (_) => new Error("Expected a single staking Ref Script UTXO")
4904
+ );
4905
+ const collectorRefScriptUtxo = matchSingle(
4906
+ await lucid.utxosByOutRef([
4907
+ fromSystemParamsScriptRef(params.scriptReferences.collectorValidatorRef)
4908
+ ]),
4909
+ (_) => new Error("Expected a single staking Ref Script UTXO")
4910
+ );
4911
+ const tx = lucid.newTx().readFrom([stakingRefScriptUtxo, collectorRefScriptUtxo]).collectFrom([stakingManagerUtxo], serialiseStakingRedeemer("Distribute")).collectFrom(
4912
+ collectorUtxos,
4913
+ serialiseCollectorRedeemer("DistributeToStakers")
4914
+ ).pay.ToContract(
4915
+ stakingManagerUtxo.address,
4916
+ {
4917
+ kind: "inline",
4918
+ value: serialiseStakingDatum({
4919
+ ...stakingManagerDatum,
4920
+ managerSnapshot: { snapshotAda: newSnapshot }
4921
+ })
4922
+ },
4923
+ (0, import_lucid35.addAssets)(stakingManagerUtxo.assets, mkLovelacesOf(adaRewardCollected))
4924
+ );
4925
+ for (const collectorUtxo of collectorUtxos) {
4926
+ tx.pay.ToContract(
4927
+ collectorUtxo.address,
4928
+ { kind: "inline", value: import_lucid35.Data.void() },
4929
+ mkLovelacesOf(MIN_UTXO_AMOUNT)
4930
+ );
4931
+ }
4932
+ return tx;
4815
4933
  }
4816
4934
 
4817
4935
  // src/contracts/interest-oracle/transactions.ts
4818
- var import_lucid39 = require("@lucid-evolution/lucid");
4936
+ var import_lucid40 = require("@lucid-evolution/lucid");
4819
4937
 
4820
4938
  // src/contracts/one-shot/transactions.ts
4821
- var import_lucid37 = require("@lucid-evolution/lucid");
4939
+ var import_lucid38 = require("@lucid-evolution/lucid");
4822
4940
 
4823
4941
  // src/contracts/one-shot/scripts.ts
4824
- var import_lucid36 = require("@lucid-evolution/lucid");
4942
+ var import_lucid37 = require("@lucid-evolution/lucid");
4825
4943
 
4826
4944
  // src/contracts/one-shot/types.ts
4827
- var import_lucid35 = require("@lucid-evolution/lucid");
4828
- var OneShotParamsSchema = import_lucid35.Data.Object({
4829
- referenceOutRef: import_lucid35.Data.Object({
4830
- txHash: import_lucid35.Data.Bytes(),
4831
- outputIdx: import_lucid35.Data.Integer()
4945
+ var import_lucid36 = require("@lucid-evolution/lucid");
4946
+ var OneShotParamsSchema = import_lucid36.Data.Object({
4947
+ referenceOutRef: import_lucid36.Data.Object({
4948
+ txHash: import_lucid36.Data.Bytes(),
4949
+ outputIdx: import_lucid36.Data.Integer()
4832
4950
  }),
4833
- mintAmounts: import_lucid35.Data.Array(
4834
- import_lucid35.Data.Object({
4951
+ mintAmounts: import_lucid36.Data.Array(
4952
+ import_lucid36.Data.Object({
4835
4953
  /// Use hex encoded string
4836
- tokenName: import_lucid35.Data.Bytes(),
4837
- amount: import_lucid35.Data.Integer()
4954
+ tokenName: import_lucid36.Data.Bytes(),
4955
+ amount: import_lucid36.Data.Integer()
4838
4956
  })
4839
4957
  )
4840
4958
  });
4841
4959
  var OneShotParams = OneShotParamsSchema;
4842
4960
  function castOneShotParams(params) {
4843
- return import_lucid35.Data.castTo(params, OneShotParams);
4961
+ return import_lucid36.Data.castTo(params, OneShotParams);
4844
4962
  }
4845
4963
 
4846
4964
  // src/contracts/one-shot/scripts.ts
@@ -4851,7 +4969,7 @@ var oneShotPolicyData = {
4851
4969
  function mkOneShotPolicy(params) {
4852
4970
  return {
4853
4971
  type: oneShotPolicyData.type,
4854
- script: (0, import_lucid36.applyParamsToScript)(oneShotPolicyData.cborHex, [
4972
+ script: (0, import_lucid37.applyParamsToScript)(oneShotPolicyData.cborHex, [
4855
4973
  castOneShotParams(params)
4856
4974
  ])
4857
4975
  };
@@ -4861,7 +4979,7 @@ function mkOneShotPolicy(params) {
4861
4979
  var import_Array = require("fp-ts/lib/Array");
4862
4980
  async function oneShotMintTx(lucid, params) {
4863
4981
  const oneShotPolicy = mkOneShotPolicy(params);
4864
- const policyId = (0, import_lucid37.mintingPolicyToId)(oneShotPolicy);
4982
+ const policyId = (0, import_lucid38.mintingPolicyToId)(oneShotPolicy);
4865
4983
  const refUtxo = matchSingle(
4866
4984
  await lucid.utxosByOutRef([
4867
4985
  {
@@ -4877,11 +4995,11 @@ async function oneShotMintTx(lucid, params) {
4877
4995
  lucid.newTx().collectFrom([refUtxo]).mintAssets(
4878
4996
  (0, import_Array.reduce)(
4879
4997
  {},
4880
- (acc, entry) => (0, import_lucid37.addAssets)(acc, {
4881
- [(0, import_lucid37.toUnit)(policyId, entry.tokenName)]: entry.amount
4998
+ (acc, entry) => (0, import_lucid38.addAssets)(acc, {
4999
+ [(0, import_lucid38.toUnit)(policyId, entry.tokenName)]: entry.amount
4882
5000
  })
4883
5001
  )(params.mintAmounts),
4884
- import_lucid37.Data.to(new import_lucid37.Constr(0, []))
5002
+ import_lucid38.Data.to(new import_lucid38.Constr(0, []))
4885
5003
  ).attach.MintingPolicy(oneShotPolicy),
4886
5004
  policyId
4887
5005
  ];
@@ -4894,7 +5012,7 @@ async function runOneShotMintTx(lucid, params) {
4894
5012
  }
4895
5013
 
4896
5014
  // src/contracts/interest-oracle/scripts.ts
4897
- var import_lucid38 = require("@lucid-evolution/lucid");
5015
+ var import_lucid39 = require("@lucid-evolution/lucid");
4898
5016
 
4899
5017
  // src/validators/interest-oracle-validator.ts
4900
5018
  var _interestOracleValidator = {
@@ -4907,7 +5025,7 @@ var _interestOracleValidator = {
4907
5025
  function mkInterestOracleValidator(params) {
4908
5026
  return {
4909
5027
  type: "PlutusV2",
4910
- script: (0, import_lucid38.applyParamsToScript)(_interestOracleValidator.cborHex, [
5028
+ script: (0, import_lucid39.applyParamsToScript)(_interestOracleValidator.cborHex, [
4911
5029
  castInterestOracleParams(params)
4912
5030
  ])
4913
5031
  };
@@ -4932,14 +5050,14 @@ async function startInterestOracle(initialUnitaryInterest, initialInterestRate,
4932
5050
  },
4933
5051
  mintAmounts: [
4934
5052
  {
4935
- tokenName: (0, import_lucid39.fromText)(tokenName),
5053
+ tokenName: (0, import_lucid40.fromText)(tokenName),
4936
5054
  amount: 1n
4937
5055
  }
4938
5056
  ]
4939
5057
  });
4940
5058
  const validator = mkInterestOracleValidator(oracleParams);
4941
5059
  tx.pay.ToContract(
4942
- (0, import_lucid39.validatorToAddress)(network, validator),
5060
+ (0, import_lucid40.validatorToAddress)(network, validator),
4943
5061
  {
4944
5062
  kind: "inline",
4945
5063
  value: serialiseInterestOracleDatum({
@@ -4952,12 +5070,12 @@ async function startInterestOracle(initialUnitaryInterest, initialInterestRate,
4952
5070
  },
4953
5071
  {
4954
5072
  lovelace: 2500000n,
4955
- [(0, import_lucid39.toUnit)(policyId, (0, import_lucid39.fromText)(tokenName))]: 1n
5073
+ [(0, import_lucid40.toUnit)(policyId, (0, import_lucid40.fromText)(tokenName))]: 1n
4956
5074
  }
4957
5075
  );
4958
5076
  if (withScriptRef) {
4959
5077
  tx.pay.ToAddressWithData(
4960
- (0, import_lucid39.validatorToAddress)(network, validator),
5078
+ (0, import_lucid40.validatorToAddress)(network, validator),
4961
5079
  void 0,
4962
5080
  void 0,
4963
5081
  validator
@@ -4967,7 +5085,7 @@ async function startInterestOracle(initialUnitaryInterest, initialInterestRate,
4967
5085
  tx,
4968
5086
  {
4969
5087
  currencySymbol: policyId,
4970
- tokenName: (0, import_lucid39.fromText)(tokenName)
5088
+ tokenName: (0, import_lucid40.fromText)(tokenName)
4971
5089
  }
4972
5090
  ];
4973
5091
  }
@@ -5015,17 +5133,17 @@ async function feedInterestOracle(params, newInterestRate, lucid, assetClass, ut
5015
5133
  }
5016
5134
 
5017
5135
  // src/contracts/version-registry/types.ts
5018
- var import_lucid40 = require("@lucid-evolution/lucid");
5019
- var VersionRecordTokenParamsSchema = import_lucid40.Data.Object({
5136
+ var import_lucid41 = require("@lucid-evolution/lucid");
5137
+ var VersionRecordTokenParamsSchema = import_lucid41.Data.Object({
5020
5138
  upgradeToken: AssetClassSchema
5021
5139
  });
5022
5140
  var VersionRecordTokenParams = VersionRecordTokenParamsSchema;
5023
5141
  function castVersionRecordTokenParams(params) {
5024
- return import_lucid40.Data.castTo(params, VersionRecordTokenParams);
5142
+ return import_lucid41.Data.castTo(params, VersionRecordTokenParams);
5025
5143
  }
5026
5144
 
5027
5145
  // src/contracts/version-registry/scripts.ts
5028
- var import_lucid41 = require("@lucid-evolution/lucid");
5146
+ var import_lucid42 = require("@lucid-evolution/lucid");
5029
5147
 
5030
5148
  // src/validators/version-record-policy.ts
5031
5149
  var _versionRecordTokenPolicy = {
@@ -5045,7 +5163,7 @@ var _versionRegistryValidator = {
5045
5163
  function mkVersionRecordTokenPolicy(params) {
5046
5164
  return {
5047
5165
  type: "PlutusV2",
5048
- script: (0, import_lucid41.applyParamsToScript)(_versionRecordTokenPolicy.cborHex, [
5166
+ script: (0, import_lucid42.applyParamsToScript)(_versionRecordTokenPolicy.cborHex, [
5049
5167
  castVersionRecordTokenParams(params)
5050
5168
  ])
5051
5169
  };
@@ -5058,7 +5176,7 @@ var mkVersionRegistryValidator = () => {
5058
5176
  };
5059
5177
 
5060
5178
  // src/contracts/collector/scripts.ts
5061
- var import_lucid42 = require("@lucid-evolution/lucid");
5179
+ var import_lucid43 = require("@lucid-evolution/lucid");
5062
5180
 
5063
5181
  // src/validators/collector-validator.ts
5064
5182
  var _collectorValidator = {
@@ -5071,19 +5189,19 @@ var _collectorValidator = {
5071
5189
  var mkCollectorValidatorFromSP = (params) => {
5072
5190
  return {
5073
5191
  type: "PlutusV2",
5074
- script: (0, import_lucid42.applyParamsToScript)(_collectorValidator.cborHex, [
5075
- new import_lucid42.Constr(0, [
5076
- new import_lucid42.Constr(0, [
5192
+ script: (0, import_lucid43.applyParamsToScript)(_collectorValidator.cborHex, [
5193
+ new import_lucid43.Constr(0, [
5194
+ new import_lucid43.Constr(0, [
5077
5195
  params.stakingManagerNFT[0].unCurrencySymbol,
5078
- (0, import_lucid42.fromText)(params.stakingManagerNFT[1].unTokenName)
5196
+ (0, import_lucid43.fromText)(params.stakingManagerNFT[1].unTokenName)
5079
5197
  ]),
5080
- new import_lucid42.Constr(0, [
5198
+ new import_lucid43.Constr(0, [
5081
5199
  params.stakingToken[0].unCurrencySymbol,
5082
- (0, import_lucid42.fromText)(params.stakingToken[1].unTokenName)
5200
+ (0, import_lucid43.fromText)(params.stakingToken[1].unTokenName)
5083
5201
  ]),
5084
- new import_lucid42.Constr(0, [
5202
+ new import_lucid43.Constr(0, [
5085
5203
  params.versionRecordToken[0].unCurrencySymbol,
5086
- (0, import_lucid42.fromText)(params.versionRecordToken[1].unTokenName)
5204
+ (0, import_lucid43.fromText)(params.versionRecordToken[1].unTokenName)
5087
5205
  ])
5088
5206
  ])
5089
5207
  ])
@@ -5091,7 +5209,7 @@ var mkCollectorValidatorFromSP = (params) => {
5091
5209
  };
5092
5210
 
5093
5211
  // src/contracts/treasury/scripts.ts
5094
- var import_lucid43 = require("@lucid-evolution/lucid");
5212
+ var import_lucid44 = require("@lucid-evolution/lucid");
5095
5213
 
5096
5214
  // src/validators/treasury-validator.ts
5097
5215
  var _treasuryValidator = {
@@ -5104,30 +5222,30 @@ var _treasuryValidator = {
5104
5222
  var mkTreasuryValidatorFromSP = (params) => {
5105
5223
  return {
5106
5224
  type: "PlutusV2",
5107
- script: (0, import_lucid43.applyParamsToScript)(_treasuryValidator.cborHex, [
5108
- new import_lucid43.Constr(0, [
5109
- new import_lucid43.Constr(0, [
5225
+ script: (0, import_lucid44.applyParamsToScript)(_treasuryValidator.cborHex, [
5226
+ new import_lucid44.Constr(0, [
5227
+ new import_lucid44.Constr(0, [
5110
5228
  params.upgradeToken[0].unCurrencySymbol,
5111
- (0, import_lucid43.fromText)(params.upgradeToken[1].unTokenName)
5229
+ (0, import_lucid44.fromText)(params.upgradeToken[1].unTokenName)
5112
5230
  ]),
5113
- new import_lucid43.Constr(0, [
5231
+ new import_lucid44.Constr(0, [
5114
5232
  params.versionRecordToken[0].unCurrencySymbol,
5115
- (0, import_lucid43.fromText)(params.versionRecordToken[1].unTokenName)
5233
+ (0, import_lucid44.fromText)(params.versionRecordToken[1].unTokenName)
5116
5234
  ]),
5117
- params.treasuryUtxosStakeCredential ? new import_lucid43.Constr(0, [
5118
- new import_lucid43.Constr(0, [
5119
- new import_lucid43.Constr(1, [
5235
+ params.treasuryUtxosStakeCredential ? new import_lucid44.Constr(0, [
5236
+ new import_lucid44.Constr(0, [
5237
+ new import_lucid44.Constr(1, [
5120
5238
  params.treasuryUtxosStakeCredential.contents.contents
5121
5239
  ])
5122
5240
  ])
5123
- ]) : new import_lucid43.Constr(1, [])
5241
+ ]) : new import_lucid44.Constr(1, [])
5124
5242
  ])
5125
5243
  ])
5126
5244
  };
5127
5245
  };
5128
5246
 
5129
5247
  // src/contracts/execute/scripts.ts
5130
- var import_lucid44 = require("@lucid-evolution/lucid");
5248
+ var import_lucid45 = require("@lucid-evolution/lucid");
5131
5249
 
5132
5250
  // src/validators/execute-validator.ts
5133
5251
  var _executeValidator = {
@@ -5140,8 +5258,8 @@ var _executeValidator = {
5140
5258
  var mkExecuteValidator = (params) => {
5141
5259
  return {
5142
5260
  type: "PlutusV2",
5143
- script: (0, import_lucid44.applySingleCborEncoding)(
5144
- (0, import_lucid44.applyParamsToScript)(_executeValidator.cborHex, [
5261
+ script: (0, import_lucid45.applySingleCborEncoding)(
5262
+ (0, import_lucid45.applyParamsToScript)(_executeValidator.cborHex, [
5145
5263
  castExecuteParams(params)
5146
5264
  ])
5147
5265
  )
@@ -5150,8 +5268,8 @@ var mkExecuteValidator = (params) => {
5150
5268
  var mkExecuteValidatorFromSP = (params) => {
5151
5269
  return {
5152
5270
  type: "PlutusV2",
5153
- script: (0, import_lucid44.applySingleCborEncoding)(
5154
- (0, import_lucid44.applyParamsToScript)(_executeValidator.cborHex, [
5271
+ script: (0, import_lucid45.applySingleCborEncoding)(
5272
+ (0, import_lucid45.applyParamsToScript)(_executeValidator.cborHex, [
5155
5273
  castExecuteParams({
5156
5274
  govNFT: fromSystemParamsAsset(params.govNFT),
5157
5275
  upgradeToken: fromSystemParamsAsset(params.upgradeToken),
@@ -5169,62 +5287,276 @@ var mkExecuteValidatorFromSP = (params) => {
5169
5287
  };
5170
5288
  };
5171
5289
 
5290
+ // src/contracts/lrp/helpers.ts
5291
+ var import_lucid47 = require("@lucid-evolution/lucid");
5292
+
5172
5293
  // src/contracts/lrp/types.ts
5173
- var import_lucid45 = require("@lucid-evolution/lucid");
5174
- var LRPParamsSchema = import_lucid45.Data.Object({
5294
+ var import_lucid46 = require("@lucid-evolution/lucid");
5295
+ var import_fp_ts11 = require("fp-ts");
5296
+ var LRPParamsSchema = import_lucid46.Data.Object({
5175
5297
  versionRecordToken: AssetClassSchema,
5176
5298
  iassetNft: AssetClassSchema,
5177
- iassetPolicyId: import_lucid45.Data.Bytes(),
5178
- minRedemptionLovelacesAmt: import_lucid45.Data.Integer()
5299
+ iassetPolicyId: import_lucid46.Data.Bytes(),
5300
+ minRedemptionLovelacesAmt: import_lucid46.Data.Integer()
5179
5301
  });
5180
5302
  var LRPParams = LRPParamsSchema;
5181
- var LRPDatumSchema = import_lucid45.Data.Object({
5182
- owner: import_lucid45.Data.Bytes(),
5183
- iasset: import_lucid45.Data.Bytes(),
5303
+ var LRPDatumSchema = import_lucid46.Data.Object({
5304
+ owner: import_lucid46.Data.Bytes(),
5305
+ iasset: import_lucid46.Data.Bytes(),
5184
5306
  maxPrice: OnChainDecimalSchema,
5185
5307
  /**
5186
5308
  * The amount of lovelaces that is available to be spent.
5187
5309
  * This doesn't correspond to the lovelaces in UTXO's value,
5188
5310
  * since that can contain fees, too.
5189
5311
  */
5190
- lovelacesToSpend: import_lucid45.Data.Integer()
5312
+ lovelacesToSpend: import_lucid46.Data.Integer()
5191
5313
  });
5192
5314
  var LRPDatum = LRPDatumSchema;
5193
- var LRPRedeemerSchema = import_lucid45.Data.Enum([
5194
- import_lucid45.Data.Object({ Redeem: import_lucid45.Data.Object({ continuingOutputIdx: import_lucid45.Data.Integer() }) }),
5195
- import_lucid45.Data.Object({
5196
- RedeemAuxiliary: import_lucid45.Data.Object({
5197
- continuingOutputIdx: import_lucid45.Data.Integer(),
5315
+ var LRPRedeemerSchema = import_lucid46.Data.Enum([
5316
+ import_lucid46.Data.Object({ Redeem: import_lucid46.Data.Object({ continuingOutputIdx: import_lucid46.Data.Integer() }) }),
5317
+ import_lucid46.Data.Object({
5318
+ RedeemAuxiliary: import_lucid46.Data.Object({
5319
+ continuingOutputIdx: import_lucid46.Data.Integer(),
5198
5320
  mainRedeemOutRef: OutputReferenceSchema,
5199
- asset: import_lucid45.Data.Bytes(),
5321
+ asset: import_lucid46.Data.Bytes(),
5200
5322
  assetPrice: OnChainDecimalSchema,
5201
5323
  redemptionReimbursementPercentage: OnChainDecimalSchema
5202
5324
  })
5203
5325
  }),
5204
- import_lucid45.Data.Literal("Cancel"),
5205
- import_lucid45.Data.Literal("UpgradeVersion")
5326
+ import_lucid46.Data.Literal("Cancel"),
5327
+ import_lucid46.Data.Literal("UpgradeVersion")
5206
5328
  ]);
5207
5329
  var LRPRedeemer = LRPRedeemerSchema;
5208
5330
  function parseLrpDatum(datum) {
5209
- return import_lucid45.Data.from(datum, LRPDatum);
5331
+ try {
5332
+ return import_fp_ts11.option.some(import_lucid46.Data.from(datum, LRPDatum));
5333
+ } catch (_) {
5334
+ return import_fp_ts11.option.none;
5335
+ }
5336
+ }
5337
+ function parseLrpDatumOrThrow(datum) {
5338
+ return import_fp_ts11.function.pipe(
5339
+ parseLrpDatum(datum),
5340
+ import_fp_ts11.option.match(() => {
5341
+ throw new Error("Expected an LRP datum.");
5342
+ }, import_fp_ts11.function.identity)
5343
+ );
5210
5344
  }
5211
5345
  function serialiseLrpDatum(datum) {
5212
- return import_lucid45.Data.to(datum, LRPDatum);
5346
+ return import_lucid46.Data.to(datum, LRPDatum);
5213
5347
  }
5214
5348
  function serialiseLrpRedeemer(redeemer) {
5215
- return import_lucid45.Data.to(redeemer, LRPRedeemer);
5349
+ return import_lucid46.Data.to(redeemer, LRPRedeemer);
5216
5350
  }
5217
5351
  function castLrpParams(params) {
5218
- return import_lucid45.Data.castTo(params, LRPParams);
5352
+ return import_lucid46.Data.castTo(params, LRPParams);
5219
5353
  }
5220
5354
 
5221
- // src/contracts/lrp/transactions.ts
5222
- var import_lucid46 = require("@lucid-evolution/lucid");
5355
+ // src/contracts/lrp/helpers.ts
5356
+ var import_fp_ts13 = require("fp-ts");
5357
+
5358
+ // src/utils/array-utils.ts
5359
+ var import_fp_ts12 = require("fp-ts");
5360
+ function shuffle(arr) {
5361
+ const source = [...arr];
5362
+ for (let i = source.length - 1; i > 0; i--) {
5363
+ const j = Math.floor(Math.random() * (i + 1));
5364
+ [source[i], source[j]] = [source[j], source[i]];
5365
+ }
5366
+ return source;
5367
+ }
5368
+ function insertSorted(arr, item, ord) {
5369
+ if (arr.length === 0) {
5370
+ return [item];
5371
+ }
5372
+ const arrOrd = ord.compare(arr[0], arr[arr.length - 1]);
5373
+ if (arrOrd === 0) {
5374
+ if (ord.compare(arr[0], item) === -1) {
5375
+ return [...arr, item];
5376
+ } else {
5377
+ return [item, ...arr];
5378
+ }
5379
+ }
5380
+ for (let i = 0; i < arr.length; i++) {
5381
+ if (ord.compare(arr[i], item) !== arrOrd) {
5382
+ return [...import_fp_ts12.array.takeLeft(i)(arr), item, ...import_fp_ts12.array.takeRight(arr.length - i)(arr)];
5383
+ }
5384
+ }
5385
+ return [...arr, item];
5386
+ }
5387
+
5388
+ // src/contracts/lrp/helpers.ts
5223
5389
  var import_ts_pattern12 = require("ts-pattern");
5390
+ var MIN_LRP_COLLATERAL_AMT = 2000000n;
5391
+ function lrpRedeemableLovelacesInclReimb(lrp, lrpParams) {
5392
+ const datum = lrp[1];
5393
+ const utxo = lrp[0];
5394
+ let res = 0n;
5395
+ if (datum.lovelacesToSpend > lovelacesAmt(utxo.assets)) {
5396
+ res = bigintMax(lovelacesAmt(utxo.assets) - MIN_LRP_COLLATERAL_AMT, 0n);
5397
+ } else {
5398
+ res = datum.lovelacesToSpend;
5399
+ }
5400
+ if (res < lrpParams.minRedemptionLovelacesAmt) {
5401
+ return 0n;
5402
+ }
5403
+ return res;
5404
+ }
5405
+ function buildRedemptionsTx(redemptions, price, redemptionReimbursementPercentage, sysParams, tx, txOutputsBeforeCount) {
5406
+ const [[mainLrpUtxo, _], __] = (0, import_ts_pattern12.match)(redemptions).with(
5407
+ [import_ts_pattern12.P._, ...import_ts_pattern12.P.array()],
5408
+ ([[firstLrp, _2], ...rest]) => [
5409
+ [firstLrp, _2],
5410
+ rest
5411
+ ]
5412
+ ).otherwise(() => {
5413
+ throw new Error("Expects at least 1 UTXO to redeem.");
5414
+ });
5415
+ const mainLrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(mainLrpUtxo));
5416
+ return import_fp_ts13.function.pipe(
5417
+ redemptions,
5418
+ import_fp_ts13.array.reduceWithIndex(
5419
+ tx,
5420
+ (idx, acc, [lrpUtxo, redeemIAssetAmt]) => {
5421
+ const lovelacesForRedemption = ocdMul(
5422
+ {
5423
+ getOnChainInt: redeemIAssetAmt
5424
+ },
5425
+ price
5426
+ ).getOnChainInt;
5427
+ const reimburstmentLovelaces = calculateFeeFromPercentage(
5428
+ redemptionReimbursementPercentage,
5429
+ lovelacesForRedemption
5430
+ );
5431
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5432
+ const resultVal = (0, import_lucid47.addAssets)(
5433
+ lrpUtxo.assets,
5434
+ mkLovelacesOf(-lovelacesForRedemption + reimburstmentLovelaces),
5435
+ mkAssetsOf(
5436
+ {
5437
+ currencySymbol: sysParams.lrpParams.iassetPolicyId.unCurrencySymbol,
5438
+ tokenName: mainLrpDatum.iasset
5439
+ },
5440
+ redeemIAssetAmt
5441
+ )
5442
+ );
5443
+ if (lovelacesAmt(resultVal) < MIN_LRP_COLLATERAL_AMT) {
5444
+ throw new Error("LRP was incorrectly initialised.");
5445
+ }
5446
+ return acc.collectFrom(
5447
+ [lrpUtxo],
5448
+ serialiseLrpRedeemer(
5449
+ idx === 0 ? { Redeem: { continuingOutputIdx: txOutputsBeforeCount + 0n } } : {
5450
+ RedeemAuxiliary: {
5451
+ continuingOutputIdx: txOutputsBeforeCount + BigInt(idx),
5452
+ mainRedeemOutRef: {
5453
+ txHash: { hash: mainLrpUtxo.txHash },
5454
+ outputIndex: BigInt(mainLrpUtxo.outputIndex)
5455
+ },
5456
+ asset: mainLrpDatum.iasset,
5457
+ assetPrice: price,
5458
+ redemptionReimbursementPercentage
5459
+ }
5460
+ }
5461
+ )
5462
+ ).pay.ToContract(
5463
+ lrpUtxo.address,
5464
+ {
5465
+ kind: "inline",
5466
+ value: serialiseLrpDatum({
5467
+ ...lrpDatum,
5468
+ lovelacesToSpend: lrpDatum.lovelacesToSpend - lovelacesForRedemption
5469
+ })
5470
+ },
5471
+ resultVal
5472
+ );
5473
+ }
5474
+ )
5475
+ );
5476
+ }
5477
+ function calculateTotalAdaForRedemption(iasset, iassetPrice, lrpParams, allLrps, maxLrpsInTx) {
5478
+ return import_fp_ts13.function.pipe(
5479
+ allLrps,
5480
+ import_fp_ts13.array.filterMap(([utxo, datum]) => {
5481
+ if (datum.iasset !== iasset || datum.maxPrice.getOnChainInt < iassetPrice.getOnChainInt) {
5482
+ return import_fp_ts13.option.none;
5483
+ }
5484
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
5485
+ [utxo, datum],
5486
+ lrpParams
5487
+ );
5488
+ if (lovelacesToSpend === 0n) {
5489
+ return import_fp_ts13.option.none;
5490
+ }
5491
+ return import_fp_ts13.option.some(lovelacesToSpend);
5492
+ }),
5493
+ // From largest to smallest
5494
+ import_fp_ts13.array.sort(import_fp_ts13.ord.reverse(BigIntOrd)),
5495
+ // We can fit only this number of redemptions with CDP open into a single Tx.
5496
+ import_fp_ts13.array.takeLeft(maxLrpsInTx),
5497
+ sum
5498
+ );
5499
+ }
5500
+ function randomLrpsSubsetSatisfyingTargetLovelaces(iasset, targetLovelacesToSpend, iassetPrice, allLrps, lrpParams, maxLrpsInTx, randomiseFn = shuffle) {
5501
+ if (targetLovelacesToSpend < lrpParams.minRedemptionLovelacesAmt) {
5502
+ throw new Error("Can't redeem less than the minimum.");
5503
+ }
5504
+ const shuffled = randomiseFn(
5505
+ import_fp_ts13.function.pipe(
5506
+ allLrps,
5507
+ import_fp_ts13.array.filter(
5508
+ ([_, datum]) => datum.iasset === iasset && datum.maxPrice.getOnChainInt >= iassetPrice.getOnChainInt
5509
+ )
5510
+ )
5511
+ );
5512
+ let result = [];
5513
+ let runningSum = 0n;
5514
+ for (let i = 0; i < shuffled.length; i++) {
5515
+ const element = shuffled[i];
5516
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
5517
+ element,
5518
+ lrpParams
5519
+ );
5520
+ if (lovelacesToSpend < lrpParams.minRedemptionLovelacesAmt) {
5521
+ continue;
5522
+ }
5523
+ if (result.length > 0 && targetLovelacesToSpend - runningSum < lrpParams.minRedemptionLovelacesAmt) {
5524
+ const last = result[result.length - 1];
5525
+ if (lrpRedeemableLovelacesInclReimb(last, lrpParams) < lovelacesToSpend) {
5526
+ const popped = result.pop();
5527
+ runningSum -= lrpRedeemableLovelacesInclReimb(popped, lrpParams);
5528
+ } else {
5529
+ continue;
5530
+ }
5531
+ }
5532
+ result = insertSorted(
5533
+ result,
5534
+ element,
5535
+ import_fp_ts13.ord.contramap(
5536
+ ([_, dat]) => dat.lovelacesToSpend
5537
+ // From highest to lowest
5538
+ )(import_fp_ts13.ord.reverse(BigIntOrd))
5539
+ );
5540
+ runningSum += lovelacesToSpend;
5541
+ if (result.length > maxLrpsInTx) {
5542
+ const popped = result.pop();
5543
+ runningSum -= lrpRedeemableLovelacesInclReimb(popped, lrpParams);
5544
+ }
5545
+ if (runningSum >= targetLovelacesToSpend) {
5546
+ return result;
5547
+ }
5548
+ }
5549
+ if (targetLovelacesToSpend - runningSum >= lrpParams.minRedemptionLovelacesAmt) {
5550
+ throw new Error("Couldn't achieve target lovelaces");
5551
+ }
5552
+ return result;
5553
+ }
5554
+
5555
+ // src/contracts/lrp/transactions.ts
5556
+ var import_lucid48 = require("@lucid-evolution/lucid");
5224
5557
  var import_Array2 = require("fp-ts/lib/Array");
5225
- var import_Array3 = require("fp-ts/lib/Array");
5226
- var MIN_UTXO_COLLATERAL_AMT = 2000000n;
5227
- async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, lrpScriptHash, network, lrpStakeCredential) {
5558
+ async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, sysParams, lrpStakeCredential) {
5559
+ const network = lucid.config().network;
5228
5560
  const [ownPkh, _] = await addrDetails(lucid);
5229
5561
  const newDatum = {
5230
5562
  owner: ownPkh.hash,
@@ -5233,38 +5565,47 @@ async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, lrpScript
5233
5565
  lovelacesToSpend: lovelacesAmt2
5234
5566
  };
5235
5567
  return lucid.newTx().pay.ToContract(
5236
- createScriptAddress(network, lrpScriptHash, lrpStakeCredential),
5568
+ createScriptAddress(
5569
+ network,
5570
+ sysParams.validatorHashes.lrpHash,
5571
+ lrpStakeCredential
5572
+ ),
5237
5573
  {
5238
5574
  kind: "inline",
5239
5575
  value: serialiseLrpDatum(newDatum)
5240
5576
  },
5241
- { lovelace: lovelacesAmt2 + MIN_UTXO_COLLATERAL_AMT }
5577
+ { lovelace: lovelacesAmt2 + MIN_LRP_COLLATERAL_AMT }
5242
5578
  );
5243
5579
  }
5244
- async function cancelLrp(lrpOutRef, lrpRefScriptOutRef, lucid) {
5580
+ async function cancelLrp(lrpOutRef, sysParams, lucid) {
5245
5581
  const lrpScriptRefUtxo = matchSingle(
5246
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5582
+ await lucid.utxosByOutRef([
5583
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5584
+ ]),
5247
5585
  (_) => new Error("Expected a single LRP Ref Script UTXO")
5248
5586
  );
5249
5587
  const lrpUtxo = matchSingle(
5250
5588
  await lucid.utxosByOutRef([lrpOutRef]),
5251
5589
  (_) => new Error("Expected a single LRP UTXO.")
5252
5590
  );
5253
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5591
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5254
5592
  return lucid.newTx().readFrom([lrpScriptRefUtxo]).collectFrom([lrpUtxo], serialiseLrpRedeemer("Cancel")).addSignerKey(lrpDatum.owner);
5255
5593
  }
5256
- async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutRef, iassetOutRef, lucid, lrpParams, network) {
5594
+ async function redeemLrp(redemptionLrpsData, priceOracleOutRef, iassetOutRef, lucid, sysParams) {
5595
+ const network = lucid.config().network;
5257
5596
  const lrpScriptRefUtxo = matchSingle(
5258
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5259
- (_2) => new Error("Expected a single LRP Ref Script UTXO")
5597
+ await lucid.utxosByOutRef([
5598
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5599
+ ]),
5600
+ (_) => new Error("Expected a single LRP Ref Script UTXO")
5260
5601
  );
5261
5602
  const priceOracleUtxo = matchSingle(
5262
5603
  await lucid.utxosByOutRef([priceOracleOutRef]),
5263
- (_2) => new Error("Expected a single price oracle UTXO")
5604
+ (_) => new Error("Expected a single price oracle UTXO")
5264
5605
  );
5265
5606
  const iassetUtxo = matchSingle(
5266
5607
  await lucid.utxosByOutRef([iassetOutRef]),
5267
- (_2) => new Error("Expected a single IAsset UTXO")
5608
+ (_) => new Error("Expected a single IAsset UTXO")
5268
5609
  );
5269
5610
  const iassetDatum = parseIAssetDatumOrThrow(
5270
5611
  getInlineDatumOrThrow(iassetUtxo)
@@ -5274,88 +5615,35 @@ async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutR
5274
5615
  getInlineDatumOrThrow(priceOracleUtxo)
5275
5616
  );
5276
5617
  const redemptionLrps = await lucid.utxosByOutRef(lrpsToRedeemOutRefs).then((val) => (0, import_Array2.zip)(val, lrpRedemptionIAssetAmt));
5277
- const [[mainLrpUtxo, _], __] = (0, import_ts_pattern12.match)(redemptionLrps).with(
5278
- [import_ts_pattern12.P._, ...import_ts_pattern12.P.array()],
5279
- ([[firstLrp, _2], ...rest]) => [
5280
- [firstLrp, _2],
5281
- rest
5282
- ]
5283
- ).otherwise(() => {
5284
- throw new Error("Expects at least 1 UTXO to redeem.");
5285
- });
5286
- const mainLrpDatum = parseLrpDatum(getInlineDatumOrThrow(mainLrpUtxo));
5287
- const tx = (0, import_Array3.reduceWithIndex)(
5618
+ const tx = buildRedemptionsTx(
5619
+ redemptionLrps,
5620
+ priceOracleDatum.price,
5621
+ iassetDatum.redemptionReimbursementPercentage,
5622
+ sysParams,
5288
5623
  lucid.newTx(),
5289
- (idx, acc, [lrpUtxo, redeemIAssetAmt]) => {
5290
- const lovelacesForRedemption = ocdMul(
5291
- {
5292
- getOnChainInt: redeemIAssetAmt
5293
- },
5294
- priceOracleDatum.price
5295
- ).getOnChainInt;
5296
- const reimburstmentLovelaces = calculateFeeFromPercentage(
5297
- iassetDatum.redemptionReimbursementPercentage,
5298
- lovelacesForRedemption
5299
- );
5300
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5301
- return acc.collectFrom(
5302
- [lrpUtxo],
5303
- serialiseLrpRedeemer(
5304
- idx === 0 ? { Redeem: { continuingOutputIdx: 0n } } : {
5305
- RedeemAuxiliary: {
5306
- continuingOutputIdx: BigInt(idx),
5307
- mainRedeemOutRef: {
5308
- txHash: { hash: mainLrpUtxo.txHash },
5309
- outputIndex: BigInt(mainLrpUtxo.outputIndex)
5310
- },
5311
- asset: mainLrpDatum.iasset,
5312
- assetPrice: priceOracleDatum.price,
5313
- redemptionReimbursementPercentage: iassetDatum.redemptionReimbursementPercentage
5314
- }
5315
- }
5316
- )
5317
- ).pay.ToContract(
5318
- lrpUtxo.address,
5319
- {
5320
- kind: "inline",
5321
- value: serialiseLrpDatum({
5322
- ...lrpDatum,
5323
- lovelacesToSpend: lrpDatum.lovelacesToSpend - lovelacesForRedemption
5324
- })
5325
- },
5326
- (0, import_lucid46.addAssets)(
5327
- lrpUtxo.assets,
5328
- mkLovelacesOf(-lovelacesForRedemption + reimburstmentLovelaces),
5329
- mkAssetsOf(
5330
- {
5331
- currencySymbol: lrpParams.iassetPolicyId,
5332
- tokenName: mainLrpDatum.iasset
5333
- },
5334
- redeemIAssetAmt
5335
- )
5336
- )
5337
- );
5338
- }
5339
- )(redemptionLrps);
5624
+ 0n
5625
+ );
5340
5626
  return lucid.newTx().validTo(
5341
- (0, import_lucid46.slotToUnixTime)(
5627
+ (0, import_lucid48.slotToUnixTime)(
5342
5628
  network,
5343
- (0, import_lucid46.unixTimeToSlot)(network, Number(priceOracleDatum.expiration)) - 1
5629
+ (0, import_lucid48.unixTimeToSlot)(network, Number(priceOracleDatum.expiration)) - 1
5344
5630
  )
5345
5631
  ).readFrom([lrpScriptRefUtxo]).readFrom([iassetUtxo, priceOracleUtxo]).compose(tx);
5346
5632
  }
5347
- async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, lrpRefScriptOutRef, lrpParams) {
5633
+ async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, sysParams) {
5348
5634
  const lrpScriptRefUtxo = matchSingle(
5349
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5635
+ await lucid.utxosByOutRef([
5636
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5637
+ ]),
5350
5638
  (_) => new Error("Expected a single LRP Ref Script UTXO")
5351
5639
  );
5352
5640
  const lrpUtxo = matchSingle(
5353
5641
  await lucid.utxosByOutRef([lrpOutRef]),
5354
5642
  (_) => new Error("Expected a single LRP UTXO.")
5355
5643
  );
5356
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5644
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5357
5645
  const rewardAssetClass = {
5358
- currencySymbol: lrpParams.iassetPolicyId,
5646
+ currencySymbol: sysParams.lrpParams.iassetPolicyId.unCurrencySymbol,
5359
5647
  tokenName: lrpDatum.iasset
5360
5648
  };
5361
5649
  const rewardAssetsAmt = assetClassValueOf(lrpUtxo.assets, rewardAssetClass);
@@ -5378,19 +5666,19 @@ async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, lrpRefScriptOutRe
5378
5666
  lovelacesToSpend: lrpDatum.lovelacesToSpend + lovelacesAdjustAmt
5379
5667
  })
5380
5668
  },
5381
- (0, import_lucid46.addAssets)(
5669
+ (0, import_lucid48.addAssets)(
5382
5670
  lrpUtxo.assets,
5383
5671
  mkAssetsOf(rewardAssetClass, -rewardAssetsAmt),
5384
5672
  mkLovelacesOf(lovelacesAdjustAmt)
5385
5673
  )
5386
5674
  ).addSignerKey(lrpDatum.owner);
5387
5675
  }
5388
- async function claimLrp(lucid, lrpOutRef, lrpRefScriptOutRef, lrpParams) {
5389
- return adjustLrp(lucid, lrpOutRef, 0n, lrpRefScriptOutRef, lrpParams);
5676
+ async function claimLrp(lucid, lrpOutRef, sysParams) {
5677
+ return adjustLrp(lucid, lrpOutRef, 0n, sysParams);
5390
5678
  }
5391
5679
 
5392
5680
  // src/contracts/lrp/scripts.ts
5393
- var import_lucid47 = require("@lucid-evolution/lucid");
5681
+ var import_lucid49 = require("@lucid-evolution/lucid");
5394
5682
 
5395
5683
  // src/validators/lrp-validator.ts
5396
5684
  var _lrpValidator = {
@@ -5403,13 +5691,13 @@ var _lrpValidator = {
5403
5691
  var mkLrpValidator = (params) => {
5404
5692
  return {
5405
5693
  type: "PlutusV2",
5406
- script: (0, import_lucid47.applyParamsToScript)(_lrpValidator.cborHex, [castLrpParams(params)])
5694
+ script: (0, import_lucid49.applyParamsToScript)(_lrpValidator.cborHex, [castLrpParams(params)])
5407
5695
  };
5408
5696
  };
5409
5697
  var mkLrpValidatorFromSP = (params) => {
5410
5698
  return {
5411
5699
  type: "PlutusV2",
5412
- script: (0, import_lucid47.applyParamsToScript)(_lrpValidator.cborHex, [
5700
+ script: (0, import_lucid49.applyParamsToScript)(_lrpValidator.cborHex, [
5413
5701
  castLrpParams({
5414
5702
  versionRecordToken: fromSystemParamsAsset(params.versionRecordToken),
5415
5703
  iassetNft: fromSystemParamsAsset(params.iassetNft),
@@ -5421,7 +5709,7 @@ var mkLrpValidatorFromSP = (params) => {
5421
5709
  };
5422
5710
 
5423
5711
  // src/utils/helper-txs.ts
5424
- var import_lucid48 = require("@lucid-evolution/lucid");
5712
+ var import_lucid50 = require("@lucid-evolution/lucid");
5425
5713
 
5426
5714
  // src/scripts/always-fail-validator.ts
5427
5715
  var alwaysFailValidator = {
@@ -5431,11 +5719,367 @@ var alwaysFailValidator = {
5431
5719
 
5432
5720
  // src/utils/helper-txs.ts
5433
5721
  async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5434
- const scriptAddr = (0, import_lucid48.validatorToAddress)(network, alwaysFailValidator);
5722
+ const scriptAddr = (0, import_lucid50.validatorToAddress)(network, alwaysFailValidator);
5435
5723
  const txHash = await lucid.newTx().pay.ToAddressWithData(scriptAddr, void 0, {}, scriptRefValidator).complete().then((tx) => tx.sign.withWallet().complete()).then((tx) => tx.submit());
5436
5724
  await lucid.awaitTx(txHash);
5437
5725
  return { txHash, outputIndex: 0 };
5438
5726
  }
5727
+
5728
+ // src/contracts/leverage/transactions.ts
5729
+ var import_lucid51 = require("@lucid-evolution/lucid");
5730
+
5731
+ // src/contracts/leverage/helpers.ts
5732
+ var import_fp_ts14 = require("fp-ts");
5733
+ var import_decimal2 = require("decimal.js");
5734
+ var MAX_REDEMPTIONS_WITH_CDP_OPEN = 4;
5735
+ function approximateLeverageRedemptions(baseCollateral, targetLeverage, redemptionReimbursementPercentage, debtMintingFeePercentage) {
5736
+ const debtMintingFeeRatioDecimal = (0, import_decimal2.Decimal)(
5737
+ debtMintingFeePercentage.getOnChainInt
5738
+ ).div(OCD_DECIMAL_UNIT).div(100);
5739
+ const redemptionReimbursementRatioDecimal = (0, import_decimal2.Decimal)(
5740
+ redemptionReimbursementPercentage.getOnChainInt
5741
+ ).div(OCD_DECIMAL_UNIT).div(100);
5742
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
5743
+ redemptionReimbursementRatioDecimal
5744
+ );
5745
+ const bExFees = (0, import_decimal2.Decimal)(baseCollateral).mul(targetLeverage).minus(baseCollateral).floor();
5746
+ const b = bExFees.div((0, import_decimal2.Decimal)(1).minus(totalFeeRatio)).floor();
5747
+ const collateralRatio = {
5748
+ getOnChainInt: fromDecimal(
5749
+ (0, import_decimal2.Decimal)((0, import_decimal2.Decimal)(baseCollateral).add(bExFees)).div(b).mul(100n * OCD_DECIMAL_UNIT).floor()
5750
+ )
5751
+ };
5752
+ return {
5753
+ leverage: targetLeverage,
5754
+ collateralRatio,
5755
+ lovelacesForRedemptionWithReimbursement: fromDecimal(b)
5756
+ };
5757
+ }
5758
+ function summarizeActualLeverageRedemptions(lovelacesForRedemptionWithReimbursement, redemptionReimbursementPercentage, iassetPrice, lrpParams, redemptionLrps) {
5759
+ const priceDecimal = (0, import_decimal2.Decimal)(iassetPrice.getOnChainInt).div(OCD_DECIMAL_UNIT);
5760
+ const redemptionDetails = import_fp_ts14.function.pipe(
5761
+ redemptionLrps,
5762
+ import_fp_ts14.array.reduce(
5763
+ {
5764
+ remainingRedemptionLovelacesInclReim: lovelacesForRedemptionWithReimbursement,
5765
+ redemptions: []
5766
+ },
5767
+ (acc, lrp) => {
5768
+ if (acc.remainingRedemptionLovelacesInclReim < lrpParams.minRedemptionLovelacesAmt) {
5769
+ return acc;
5770
+ }
5771
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
5772
+ lrp,
5773
+ lrpParams
5774
+ );
5775
+ if (lovelacesToSpend === 0n) {
5776
+ return acc;
5777
+ }
5778
+ const newRemainingLovelaces = bigintMax(
5779
+ acc.remainingRedemptionLovelacesInclReim - lovelacesToSpend,
5780
+ 0n
5781
+ );
5782
+ const redemptionLovelacesInitial = acc.remainingRedemptionLovelacesInclReim - newRemainingLovelaces;
5783
+ const finalRedemptionIAssets = fromDecimal(
5784
+ (0, import_decimal2.Decimal)(redemptionLovelacesInitial).div(priceDecimal).floor()
5785
+ );
5786
+ const finalRedemptionLovelaces = ocdMul(
5787
+ {
5788
+ getOnChainInt: finalRedemptionIAssets
5789
+ },
5790
+ iassetPrice
5791
+ ).getOnChainInt;
5792
+ const reimbursementLovelaces = calculateFeeFromPercentage(
5793
+ redemptionReimbursementPercentage,
5794
+ finalRedemptionLovelaces
5795
+ );
5796
+ return {
5797
+ remainingRedemptionLovelacesInclReim: acc.remainingRedemptionLovelacesInclReim - finalRedemptionLovelaces,
5798
+ redemptions: [
5799
+ ...acc.redemptions,
5800
+ {
5801
+ utxo: lrp[0],
5802
+ iassetsForRedemptionAmt: finalRedemptionIAssets,
5803
+ redemptionLovelacesAmtInclReimbursement: finalRedemptionLovelaces,
5804
+ reimbursementLovelacesAmt: reimbursementLovelaces
5805
+ }
5806
+ ]
5807
+ };
5808
+ }
5809
+ )
5810
+ );
5811
+ const res = import_fp_ts14.function.pipe(
5812
+ redemptionDetails.redemptions,
5813
+ import_fp_ts14.array.reduce(
5814
+ {
5815
+ redeemedLovelaces: 0n,
5816
+ redemptionIAssets: 0n,
5817
+ reimbursementLovelaces: 0n
5818
+ },
5819
+ (acc, details) => {
5820
+ return {
5821
+ redeemedLovelaces: acc.redeemedLovelaces + details.redemptionLovelacesAmtInclReimbursement - details.reimbursementLovelacesAmt,
5822
+ reimbursementLovelaces: acc.reimbursementLovelaces + details.reimbursementLovelacesAmt,
5823
+ redemptionIAssets: acc.redemptionIAssets + details.iassetsForRedemptionAmt
5824
+ };
5825
+ }
5826
+ )
5827
+ );
5828
+ return {
5829
+ redemptions: redemptionDetails.redemptions,
5830
+ totalRedeemedLovelaces: res.redeemedLovelaces,
5831
+ totalReimbursementLovelaces: res.reimbursementLovelaces,
5832
+ totalRedemptionIAssets: res.redemptionIAssets
5833
+ };
5834
+ }
5835
+ function calculateCollateralRatioFromLeverage(iasset, leverage, baseCollateral, iassetPrice, debtMintingFeePercentage, redemptionReimbursementPercentage, lrpParams, allLrps) {
5836
+ const debtMintingFeeRatioDecimal = (0, import_decimal2.Decimal)(
5837
+ debtMintingFeePercentage.getOnChainInt
5838
+ ).div(OCD_DECIMAL_UNIT).div(100);
5839
+ const redemptionReimbursementRatioDecimal = (0, import_decimal2.Decimal)(
5840
+ redemptionReimbursementPercentage.getOnChainInt
5841
+ ).div(OCD_DECIMAL_UNIT).div(100);
5842
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
5843
+ redemptionReimbursementRatioDecimal
5844
+ );
5845
+ const maxAvailableAdaForRedemptionInclReimb = calculateTotalAdaForRedemption(
5846
+ iasset,
5847
+ iassetPrice,
5848
+ lrpParams,
5849
+ allLrps,
5850
+ MAX_REDEMPTIONS_WITH_CDP_OPEN
5851
+ );
5852
+ if (leverage <= 1 || baseCollateral <= 0n || maxAvailableAdaForRedemptionInclReimb <= 0n) {
5853
+ return void 0;
5854
+ }
5855
+ const bExFees = (0, import_decimal2.Decimal)(baseCollateral).mul(leverage).minus(baseCollateral).floor();
5856
+ const b = bExFees.div((0, import_decimal2.Decimal)(1).minus(totalFeeRatio)).floor();
5857
+ const cappedB = bigintMin(
5858
+ maxAvailableAdaForRedemptionInclReimb,
5859
+ fromDecimal(b)
5860
+ );
5861
+ const cappedBExFees = (0, import_decimal2.Decimal)(cappedB).mul((0, import_decimal2.Decimal)(1).minus(totalFeeRatio)).floor();
5862
+ const collateralRatio = (0, import_decimal2.Decimal)(
5863
+ (0, import_decimal2.Decimal)(baseCollateral).add(cappedBExFees)
5864
+ ).div(cappedB);
5865
+ return {
5866
+ getOnChainInt: fromDecimal(
5867
+ collateralRatio.mul(100n * OCD_DECIMAL_UNIT).floor()
5868
+ )
5869
+ };
5870
+ }
5871
+ function calculateLeverageFromCollateralRatio(iasset, collateralRatioPercentage, baseCollateral, iassetPrice, debtMintingFeePercentage, redemptionReimbursementPercentage, lrpParams, allLrps) {
5872
+ const debtMintingFeeRatioDecimal = (0, import_decimal2.Decimal)(
5873
+ debtMintingFeePercentage.getOnChainInt
5874
+ ).div(OCD_DECIMAL_UNIT).div(100);
5875
+ const redemptionReimbursementRatioDecimal = (0, import_decimal2.Decimal)(
5876
+ redemptionReimbursementPercentage.getOnChainInt
5877
+ ).div(OCD_DECIMAL_UNIT).div(100);
5878
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
5879
+ redemptionReimbursementRatioDecimal
5880
+ );
5881
+ const collateralRatio = (0, import_decimal2.Decimal)(collateralRatioPercentage.getOnChainInt).div(OCD_DECIMAL_UNIT).div(100);
5882
+ const maxAvailableAdaForRedemptionInclReimb = calculateTotalAdaForRedemption(
5883
+ iasset,
5884
+ iassetPrice,
5885
+ lrpParams,
5886
+ allLrps,
5887
+ MAX_REDEMPTIONS_WITH_CDP_OPEN
5888
+ );
5889
+ if (collateralRatio.toNumber() <= 1 || baseCollateral <= 0n || maxAvailableAdaForRedemptionInclReimb <= 0n) {
5890
+ return void 0;
5891
+ }
5892
+ const theoreticalMaxLeverage = (0, import_decimal2.Decimal)((0, import_decimal2.Decimal)(1).minus(totalFeeRatio)).div(collateralRatio.minus(1).add(totalFeeRatio)).add(1);
5893
+ const bExFees = theoreticalMaxLeverage.mul(baseCollateral).minus(baseCollateral).floor();
5894
+ const b = bExFees.div((0, import_decimal2.Decimal)(1).minus(totalFeeRatio)).floor();
5895
+ const cappedB = bigintMin(
5896
+ maxAvailableAdaForRedemptionInclReimb,
5897
+ fromDecimal(b)
5898
+ );
5899
+ const cappedBExFees = (0, import_decimal2.Decimal)(cappedB).mul((0, import_decimal2.Decimal)(1).minus(totalFeeRatio)).floor();
5900
+ return (0, import_decimal2.Decimal)(baseCollateral).add(cappedBExFees).div(baseCollateral).toNumber();
5901
+ }
5902
+
5903
+ // src/contracts/leverage/transactions.ts
5904
+ async function leverageCdpWithLrp(leverage, baseCollateral, priceOracleOutRef, iassetOutRef, cdpCreatorOref, interestOracleOref, collectorOref, sysParams, lucid, allLrps, currentSlot) {
5905
+ const network = lucid.config().network;
5906
+ const currentTime = BigInt((0, import_lucid51.slotToUnixTime)(network, currentSlot));
5907
+ const [pkh, skh] = await addrDetails(lucid);
5908
+ const lrpScriptRefUtxo = matchSingle(
5909
+ await lucid.utxosByOutRef([
5910
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5911
+ ]),
5912
+ (_) => new Error("Expected a single LRP Ref Script UTXO")
5913
+ );
5914
+ const cdpCreatorRefScriptUtxo = matchSingle(
5915
+ await lucid.utxosByOutRef([
5916
+ fromSystemParamsScriptRef(
5917
+ sysParams.scriptReferences.cdpCreatorValidatorRef
5918
+ )
5919
+ ]),
5920
+ (_) => new Error("Expected a single cdp creator Ref Script UTXO")
5921
+ );
5922
+ const cdpAuthTokenPolicyRefScriptUtxo = matchSingle(
5923
+ await lucid.utxosByOutRef([
5924
+ fromSystemParamsScriptRef(
5925
+ sysParams.scriptReferences.authTokenPolicies.cdpAuthTokenRef
5926
+ )
5927
+ ]),
5928
+ (_) => new Error("Expected a single cdp auth token policy Ref Script UTXO")
5929
+ );
5930
+ const iAssetTokenPolicyRefScriptUtxo = matchSingle(
5931
+ await lucid.utxosByOutRef([
5932
+ fromSystemParamsScriptRef(
5933
+ sysParams.scriptReferences.iAssetTokenPolicyRef
5934
+ )
5935
+ ]),
5936
+ (_) => new Error("Expected a single iasset token policy Ref Script UTXO")
5937
+ );
5938
+ const cdpCreatorUtxo = matchSingle(
5939
+ await lucid.utxosByOutRef([cdpCreatorOref]),
5940
+ (_) => new Error("Expected a single CDP creator UTXO")
5941
+ );
5942
+ const interestOracleUtxo = matchSingle(
5943
+ await lucid.utxosByOutRef([interestOracleOref]),
5944
+ (_) => new Error("Expected a single interest oracle UTXO")
5945
+ );
5946
+ const interestOracleDatum = parseInterestOracleDatum(
5947
+ getInlineDatumOrThrow(interestOracleUtxo)
5948
+ );
5949
+ const priceOracleUtxo = matchSingle(
5950
+ await lucid.utxosByOutRef([priceOracleOutRef]),
5951
+ (_) => new Error("Expected a single price oracle UTXO")
5952
+ );
5953
+ const priceOracleDatum = parsePriceOracleDatum(
5954
+ getInlineDatumOrThrow(priceOracleUtxo)
5955
+ );
5956
+ const iassetUtxo = matchSingle(
5957
+ await lucid.utxosByOutRef([iassetOutRef]),
5958
+ (_) => new Error("Expected a single IAsset UTXO")
5959
+ );
5960
+ const iassetDatum = parseIAssetDatumOrThrow(
5961
+ getInlineDatumOrThrow(iassetUtxo)
5962
+ );
5963
+ const maxLeverage = calculateLeverageFromCollateralRatio(
5964
+ iassetDatum.assetName,
5965
+ iassetDatum.maintenanceRatio,
5966
+ baseCollateral,
5967
+ priceOracleDatum.price,
5968
+ iassetDatum.debtMintingFeePercentage,
5969
+ iassetDatum.redemptionReimbursementPercentage,
5970
+ sysParams.lrpParams,
5971
+ allLrps
5972
+ );
5973
+ if (!maxLeverage) {
5974
+ throw new Error("Can't calculate max leverage with those parameters.");
5975
+ }
5976
+ const leverageSummary = approximateLeverageRedemptions(
5977
+ baseCollateral,
5978
+ leverage,
5979
+ iassetDatum.redemptionReimbursementPercentage,
5980
+ iassetDatum.debtMintingFeePercentage
5981
+ );
5982
+ if (maxLeverage < leverageSummary.leverage) {
5983
+ throw new Error("Can't use more leverage than max.");
5984
+ }
5985
+ if (leverageSummary.collateralRatio.getOnChainInt < iassetDatum.maintenanceRatio.getOnChainInt) {
5986
+ throw new Error(
5987
+ "Can't have collateral ratio smaller than maintenance ratio"
5988
+ );
5989
+ }
5990
+ const redemptionDetails = summarizeActualLeverageRedemptions(
5991
+ leverageSummary.lovelacesForRedemptionWithReimbursement,
5992
+ iassetDatum.redemptionReimbursementPercentage,
5993
+ priceOracleDatum.price,
5994
+ sysParams.lrpParams,
5995
+ randomLrpsSubsetSatisfyingTargetLovelaces(
5996
+ iassetDatum.assetName,
5997
+ leverageSummary.lovelacesForRedemptionWithReimbursement,
5998
+ priceOracleDatum.price,
5999
+ allLrps,
6000
+ sysParams.lrpParams,
6001
+ MAX_REDEMPTIONS_WITH_CDP_OPEN
6002
+ )
6003
+ );
6004
+ const mintedAmt = redemptionDetails.totalRedemptionIAssets;
6005
+ const debtMintingFee = calculateFeeFromPercentage(
6006
+ iassetDatum.debtMintingFeePercentage,
6007
+ ocdMul({ getOnChainInt: mintedAmt }, priceOracleDatum.price).getOnChainInt
6008
+ );
6009
+ const collateralAmt = redemptionDetails.totalRedeemedLovelaces + baseCollateral - debtMintingFee;
6010
+ const cdpNftVal = mkAssetsOf(
6011
+ fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
6012
+ 1n
6013
+ );
6014
+ const iassetTokensVal = mkAssetsOf(
6015
+ {
6016
+ currencySymbol: sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
6017
+ tokenName: iassetDatum.assetName
6018
+ },
6019
+ mintedAmt
6020
+ );
6021
+ const txValidity = oracleExpirationAwareValidity(
6022
+ currentSlot,
6023
+ Number(sysParams.cdpCreatorParams.biasTime),
6024
+ Number(priceOracleDatum.expiration),
6025
+ network
6026
+ );
6027
+ const tx = lucid.newTx().validFrom(txValidity.validFrom).validTo(txValidity.validTo).readFrom([priceOracleUtxo, interestOracleUtxo, iassetUtxo]).readFrom([
6028
+ cdpCreatorRefScriptUtxo,
6029
+ cdpAuthTokenPolicyRefScriptUtxo,
6030
+ iAssetTokenPolicyRefScriptUtxo,
6031
+ lrpScriptRefUtxo
6032
+ ]).mintAssets(cdpNftVal, import_lucid51.Data.void()).mintAssets(iassetTokensVal, import_lucid51.Data.void()).collectFrom(
6033
+ [cdpCreatorUtxo],
6034
+ serialiseCDPCreatorRedeemer({
6035
+ CreateCDP: {
6036
+ cdpOwner: pkh.hash,
6037
+ minted: mintedAmt,
6038
+ collateral: collateralAmt,
6039
+ currentTime
6040
+ }
6041
+ })
6042
+ ).pay.ToContract(
6043
+ createScriptAddress(network, sysParams.validatorHashes.cdpHash, skh),
6044
+ {
6045
+ kind: "inline",
6046
+ value: serialiseCdpDatum({
6047
+ cdpOwner: pkh.hash,
6048
+ iasset: iassetDatum.assetName,
6049
+ mintedAmt,
6050
+ cdpFees: {
6051
+ ActiveCDPInterestTracking: {
6052
+ lastSettled: currentTime,
6053
+ unitaryInterestSnapshot: calculateUnitaryInterestSinceOracleLastUpdated(
6054
+ currentTime,
6055
+ interestOracleDatum
6056
+ ) + interestOracleDatum.unitaryInterest
6057
+ }
6058
+ }
6059
+ })
6060
+ },
6061
+ (0, import_lucid51.addAssets)(cdpNftVal, mkLovelacesOf(collateralAmt))
6062
+ ).pay.ToContract(
6063
+ cdpCreatorUtxo.address,
6064
+ { kind: "inline", value: import_lucid51.Data.void() },
6065
+ cdpCreatorUtxo.assets
6066
+ ).addSignerKey(pkh.hash);
6067
+ buildRedemptionsTx(
6068
+ redemptionDetails.redemptions.map((r) => [
6069
+ r.utxo,
6070
+ r.iassetsForRedemptionAmt
6071
+ ]),
6072
+ priceOracleDatum.price,
6073
+ iassetDatum.redemptionReimbursementPercentage,
6074
+ sysParams,
6075
+ tx,
6076
+ 2n
6077
+ );
6078
+ if (debtMintingFee > 0) {
6079
+ await collectorFeeTx(debtMintingFee, lucid, sysParams, tx, collectorOref);
6080
+ }
6081
+ return tx;
6082
+ }
5439
6083
  // Annotate the CommonJS export names for ESM import in node:
5440
6084
  0 && (module.exports = {
5441
6085
  AccountContentSchema,
@@ -5464,6 +6108,8 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5464
6108
  LRPDatumSchema,
5465
6109
  LRPParamsSchema,
5466
6110
  LRPRedeemerSchema,
6111
+ MAX_REDEMPTIONS_WITH_CDP_OPEN,
6112
+ MIN_LRP_COLLATERAL_AMT,
5467
6113
  ONE_DAY,
5468
6114
  ONE_HOUR,
5469
6115
  ONE_SECOND,
@@ -5494,12 +6140,17 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5494
6140
  adjustSpAccount,
5495
6141
  adjustStakingPosition,
5496
6142
  adjustmentHelper,
6143
+ approximateLeverageRedemptions,
5497
6144
  assetClassToUnit,
5498
6145
  assetClassValueOf,
5499
6146
  balance,
6147
+ buildRedemptionsTx,
5500
6148
  burnCdp,
6149
+ calculateCollateralRatioFromLeverage,
5501
6150
  calculateIAssetRedemptionAmt,
6151
+ calculateLeverageFromCollateralRatio,
5502
6152
  calculateMinCollateralCappedIAssetRedemptionAmt,
6153
+ calculateTotalAdaForRedemption,
5503
6154
  cancelLrp,
5504
6155
  castCDPCreatorParams,
5505
6156
  castCdpParams,
@@ -5511,6 +6162,7 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5511
6162
  castPollShardParams,
5512
6163
  castPriceOracleParams,
5513
6164
  castStabilityPoolParams,
6165
+ castStakingParams,
5514
6166
  castVersionRecordTokenParams,
5515
6167
  cdpCollateralRatioPercentage,
5516
6168
  claimLrp,
@@ -5523,6 +6175,7 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5523
6175
  createShardsChunks,
5524
6176
  createSpAccount,
5525
6177
  depositCdp,
6178
+ distributeAda,
5526
6179
  endProposal,
5527
6180
  executeProposal,
5528
6181
  feedInterestOracle,
@@ -5538,12 +6191,15 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5538
6191
  getSumFromEpochToScaleToSum,
5539
6192
  initEpochToScaleToSumMap,
5540
6193
  initSpSnapshot,
6194
+ insertSorted,
5541
6195
  isAssetsZero,
6196
+ leverageCdpWithLrp,
5542
6197
  liquidateCdp,
5543
6198
  liquidationHelper,
5544
6199
  loadSystemParamsFromFile,
5545
6200
  loadSystemParamsFromUrl,
5546
6201
  lovelacesAmt,
6202
+ lrpRedeemableLovelacesInclReimb,
5547
6203
  matchSingle,
5548
6204
  mergeCdps,
5549
6205
  mergeShards,
@@ -5583,10 +6239,15 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5583
6239
  parseIAssetDatumOrThrow,
5584
6240
  parseInterestOracleDatum,
5585
6241
  parseLrpDatum,
6242
+ parseLrpDatumOrThrow,
5586
6243
  parsePriceOracleDatum,
5587
6244
  parseSnapshotEpochToScaleToSumDatum,
5588
6245
  parseStabilityPoolDatum,
6246
+ parseStakingManagerDatum,
6247
+ parseStakingPosition,
6248
+ parseStakingPositionOrThrow,
5589
6249
  processSpRequest,
6250
+ randomLrpsSubsetSatisfyingTargetLovelaces,
5590
6251
  redeemCdp,
5591
6252
  redeemLrp,
5592
6253
  runCreateScriptRefTx,
@@ -5610,12 +6271,16 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5610
6271
  serialisePriceOracleRedeemer,
5611
6272
  serialiseStabilityPoolDatum,
5612
6273
  serialiseStabilityPoolRedeemer,
6274
+ serialiseStakingDatum,
6275
+ serialiseStakingRedeemer,
5613
6276
  setSumInEpochToScaleToSum,
6277
+ shuffle,
5614
6278
  spAdd,
5615
6279
  spDiv,
5616
6280
  spMul,
5617
6281
  spSub,
5618
6282
  startInterestOracle,
6283
+ summarizeActualLeverageRedemptions,
5619
6284
  toSystemParamsAsset,
5620
6285
  treasuryFeeTx,
5621
6286
  updatePoolSnapshotWithdrawalFee,