@indigo-labs/indigo-sdk 0.2.2 → 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.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/contracts/cdp/transactions.ts
2
2
  import {
3
3
  addAssets as addAssets3,
4
- Data as Data12,
4
+ Data as Data13,
5
5
  slotToUnixTime as slotToUnixTime3
6
6
  } from "@lucid-evolution/lucid";
7
7
 
@@ -805,12 +805,23 @@ function calculateMinCollateralCappedIAssetRedemptionAmt(collateralAmt, mintedAm
805
805
  }
806
806
 
807
807
  // src/utils/bigint-utils.ts
808
+ import { array as A } from "fp-ts";
808
809
  function bigintMax(a, b) {
809
810
  return a > b ? a : b;
810
811
  }
811
812
  function bigintMin(a, b) {
812
813
  return a < b ? a : b;
813
814
  }
815
+ function sum(arr) {
816
+ return A.reduce(0n, (acc, val) => acc + val)(arr);
817
+ }
818
+ function fromDecimal(val) {
819
+ return BigInt(val.toString());
820
+ }
821
+ var BigIntOrd = {
822
+ equals: (x, y) => x === y,
823
+ compare: (first, second) => first < second ? -1 : first > second ? 1 : 0
824
+ };
814
825
 
815
826
  // src/contracts/stability-pool/types-new.ts
816
827
  import { Core as EvoCore2 } from "@evolution-sdk/evolution";
@@ -986,14 +997,14 @@ function getSumFromEpochToScaleToSum(e2s2s, epoch, scale) {
986
997
  }
987
998
  return void 0;
988
999
  }
989
- function setSumInEpochToScaleToSum(e2s2s, epoch, scale, sum) {
1000
+ function setSumInEpochToScaleToSum(e2s2s, epoch, scale, sum2) {
990
1001
  const map = /* @__PURE__ */ new Map();
991
1002
  for (const [key, value] of e2s2s.entries()) {
992
1003
  if (!(key.epoch === epoch && key.scale === scale)) {
993
1004
  map.set(key, value);
994
1005
  }
995
1006
  }
996
- map.set({ epoch, scale }, sum);
1007
+ map.set({ epoch, scale }, sum2);
997
1008
  return map;
998
1009
  }
999
1010
  function getAccountReward(account, e2s2s) {
@@ -1167,13 +1178,26 @@ function liquidationHelper(spContent, iassetBurnAmt, reward) {
1167
1178
  }
1168
1179
 
1169
1180
  // src/contracts/cdp/transactions.ts
1170
- import { array as A, function as F3 } from "fp-ts";
1181
+ import { array as A2, function as F3 } from "fp-ts";
1171
1182
 
1172
1183
  // src/contracts/collector/transactions.ts
1173
1184
  import {
1174
- Constr,
1175
- Data as Data9
1185
+ Data as Data10
1176
1186
  } from "@lucid-evolution/lucid";
1187
+
1188
+ // src/contracts/collector/types.ts
1189
+ import { Data as Data9 } from "@lucid-evolution/lucid";
1190
+ var CollectorRedeemerSchema = Data9.Enum([
1191
+ Data9.Literal("Collect"),
1192
+ Data9.Literal("DistributeToStakers"),
1193
+ Data9.Literal("UpgradeVersion")
1194
+ ]);
1195
+ var CollectorRedeemer = CollectorRedeemerSchema;
1196
+ function serialiseCollectorRedeemer(redeemer) {
1197
+ return Data9.to(redeemer, CollectorRedeemer);
1198
+ }
1199
+
1200
+ // src/contracts/collector/transactions.ts
1177
1201
  async function collectorFeeTx(fee, lucid, params, tx, collectorOref) {
1178
1202
  const collectorUtxo = matchSingle(
1179
1203
  await lucid.utxosByOutRef([collectorOref]),
@@ -1185,9 +1209,9 @@ async function collectorFeeTx(fee, lucid, params, tx, collectorOref) {
1185
1209
  ]),
1186
1210
  (_) => new Error("Expected a single collector Ref Script UTXO")
1187
1211
  );
1188
- tx.collectFrom([collectorUtxo], Data9.to(new Constr(0, []))).pay.ToContract(
1212
+ tx.collectFrom([collectorUtxo], serialiseCollectorRedeemer("Collect")).pay.ToContract(
1189
1213
  collectorUtxo.address,
1190
- { kind: "inline", value: Data9.to(new Constr(0, [])) },
1214
+ { kind: "inline", value: Data10.void() },
1191
1215
  {
1192
1216
  ...collectorUtxo.assets,
1193
1217
  lovelace: collectorUtxo.assets.lovelace + fee
@@ -1198,35 +1222,35 @@ async function collectorFeeTx(fee, lucid, params, tx, collectorOref) {
1198
1222
  // src/contracts/treasury/transactions.ts
1199
1223
  import {
1200
1224
  addAssets as addAssets2,
1201
- Data as Data11
1225
+ Data as Data12
1202
1226
  } from "@lucid-evolution/lucid";
1203
1227
 
1204
1228
  // src/contracts/treasury/types.ts
1205
- import { Data as Data10 } from "@lucid-evolution/lucid";
1206
- var TreasuryParamsSchema = Data10.Object({
1229
+ import { Data as Data11 } from "@lucid-evolution/lucid";
1230
+ var TreasuryParamsSchema = Data11.Object({
1207
1231
  upgradeToken: AssetClassSchema,
1208
1232
  versionRecordToken: AssetClassSchema,
1209
- treasuryUtxosStakeCredential: Data10.Nullable(StakeCredentialSchema)
1233
+ treasuryUtxosStakeCredential: Data11.Nullable(StakeCredentialSchema)
1210
1234
  });
1211
- var TreasuryRedeemerSchema = Data10.Enum([
1212
- Data10.Literal("Withdraw"),
1213
- Data10.Literal("PrepareWithdraw"),
1214
- Data10.Literal("Split"),
1215
- Data10.Literal("Merge"),
1216
- Data10.Literal("CollectAda"),
1217
- Data10.Literal("UpgradeVersion")
1235
+ var TreasuryRedeemerSchema = Data11.Enum([
1236
+ Data11.Literal("Withdraw"),
1237
+ Data11.Literal("PrepareWithdraw"),
1238
+ Data11.Literal("Split"),
1239
+ Data11.Literal("Merge"),
1240
+ Data11.Literal("CollectAda"),
1241
+ Data11.Literal("UpgradeVersion")
1218
1242
  ]);
1219
1243
  var TreasuryRedeemer = TreasuryRedeemerSchema;
1220
- var WithdrawalOutputDatumSchema = Data10.Tuple([
1221
- Data10.Bytes(),
1244
+ var WithdrawalOutputDatumSchema = Data11.Tuple([
1245
+ Data11.Bytes(),
1222
1246
  OutputReferenceSchema
1223
1247
  ]);
1224
1248
  var WithdrawalOutputDatum = WithdrawalOutputDatumSchema;
1225
1249
  function serialiseWithdrawalOutputDatum(d) {
1226
- return Data10.to(d, WithdrawalOutputDatum);
1250
+ return Data11.to(d, WithdrawalOutputDatum);
1227
1251
  }
1228
1252
  function serialiseTreasuryRedeemer(redeemer) {
1229
- return Data10.to(redeemer, TreasuryRedeemer);
1253
+ return Data11.to(redeemer, TreasuryRedeemer);
1230
1254
  }
1231
1255
 
1232
1256
  // src/contracts/treasury/transactions.ts
@@ -1245,7 +1269,7 @@ async function treasuryFeeTx(fee, lucid, sysParams, tx, treasuryOref) {
1245
1269
  );
1246
1270
  tx.readFrom([treasuryRefScriptUtxo]).collectFrom([treasuryUtxo], serialiseTreasuryRedeemer("CollectAda")).pay.ToContract(
1247
1271
  treasuryUtxo.address,
1248
- { kind: "inline", value: Data11.void() },
1272
+ { kind: "inline", value: Data12.void() },
1249
1273
  addAssets2(treasuryUtxo.assets, mkLovelacesOf(fee))
1250
1274
  );
1251
1275
  }
@@ -1329,7 +1353,7 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
1329
1353
  cdpCreatorRefScriptUtxo,
1330
1354
  cdpAuthTokenPolicyRefScriptUtxo,
1331
1355
  iAssetTokenPolicyRefScriptUtxo
1332
- ]).mintAssets(cdpNftVal, Data12.void()).mintAssets(iassetTokensVal, Data12.void()).collectFrom(
1356
+ ]).mintAssets(cdpNftVal, Data13.void()).mintAssets(iassetTokensVal, Data13.void()).collectFrom(
1333
1357
  [cdpCreatorUtxo],
1334
1358
  serialiseCDPCreatorRedeemer({
1335
1359
  CreateCDP: {
@@ -1361,7 +1385,7 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
1361
1385
  addAssets3(cdpNftVal, mkLovelacesOf(collateralAmount))
1362
1386
  ).pay.ToContract(
1363
1387
  cdpCreatorUtxo.address,
1364
- { kind: "inline", value: Data12.void() },
1388
+ { kind: "inline", value: Data13.void() },
1365
1389
  cdpCreatorUtxo.assets
1366
1390
  ).readFrom([priceOracleUtxo, interestOracleUtxo, iassetUtxo]).addSignerKey(pkh.hash);
1367
1391
  const debtMintingFee = calculateFeeFromPercentage(
@@ -1474,7 +1498,7 @@ async function adjustCdp(collateralAmount, mintAmount, cdpOref, iassetOref, pric
1474
1498
  );
1475
1499
  tx.readFrom([iAssetTokenPolicyRefScriptUtxo]).mintAssets(
1476
1500
  iassetTokensVal,
1477
- Data12.void()
1501
+ Data13.void()
1478
1502
  );
1479
1503
  }
1480
1504
  const interestAdaAmt = match7(cdpDatum.cdpFees).with({ FrozenCDPAccumulatedFees: P6.any }, () => {
@@ -1659,10 +1683,10 @@ async function closeCdp(cdpOref, iassetOref, priceOracleOref, interestOracleOref
1659
1683
  },
1660
1684
  -cdpDatum.mintedAmt
1661
1685
  ),
1662
- Data12.void()
1686
+ Data13.void()
1663
1687
  ).mintAssets(
1664
1688
  mkAssetsOf(fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken), -1n),
1665
- Data12.void()
1689
+ Data13.void()
1666
1690
  ).collectFrom(
1667
1691
  [cdpUtxo],
1668
1692
  serialiseCdpRedeemer({ CloseCdp: { currentTime } })
@@ -1817,7 +1841,7 @@ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, pric
1817
1841
  },
1818
1842
  -redemptionIAssetAmt
1819
1843
  ),
1820
- Data12.void()
1844
+ Data13.void()
1821
1845
  ).pay.ToContract(
1822
1846
  cdpUtxo.address,
1823
1847
  {
@@ -2027,7 +2051,7 @@ async function liquidateCdp(cdpOref, stabilityPoolOref, collectorOref, treasuryO
2027
2051
  stabilityPoolRefScriptUtxo,
2028
2052
  iAssetTokenPolicyRefScriptUtxo,
2029
2053
  cdpAuthTokenPolicyRefScriptUtxo
2030
- ]).collectFrom([spUtxo], serialiseStabilityPoolRedeemer("LiquidateCDP")).collectFrom([cdpUtxo], serialiseCdpRedeemer("Liquidate")).mintAssets(mkAssetsOf(iassetsAc, -iassetBurnAmt), Data12.void()).pay.ToContract(
2054
+ ]).collectFrom([spUtxo], serialiseStabilityPoolRedeemer("LiquidateCDP")).collectFrom([cdpUtxo], serialiseCdpRedeemer("Liquidate")).mintAssets(mkAssetsOf(iassetsAc, -iassetBurnAmt), Data13.void()).pay.ToContract(
2031
2055
  spUtxo.address,
2032
2056
  {
2033
2057
  kind: "inline",
@@ -2069,7 +2093,7 @@ async function liquidateCdp(cdpOref, stabilityPoolOref, collectorOref, treasuryO
2069
2093
  } else {
2070
2094
  tx.mintAssets(
2071
2095
  mkAssetsOf(cdpNftAc, -assetClassValueOf(cdpUtxo.assets, cdpNftAc)),
2072
- Data12.void()
2096
+ Data13.void()
2073
2097
  );
2074
2098
  }
2075
2099
  await collectorFeeTx(
@@ -2098,15 +2122,15 @@ async function mergeCdps(cdpsToMergeUtxos, sysParams, lucid) {
2098
2122
  }
2099
2123
  const aggregatedVal = F3.pipe(
2100
2124
  cdpUtxos,
2101
- A.reduce({}, (acc, utxo) => addAssets3(acc, utxo.assets))
2125
+ A2.reduce({}, (acc, utxo) => addAssets3(acc, utxo.assets))
2102
2126
  );
2103
2127
  const aggregatedMintedAmt = F3.pipe(
2104
2128
  cdpDatums,
2105
- A.reduce(0n, (acc, cdpDat) => acc + cdpDat.mintedAmt)
2129
+ A2.reduce(0n, (acc, cdpDat) => acc + cdpDat.mintedAmt)
2106
2130
  );
2107
2131
  const { aggregatedFeeTreasury, aggregatedFeeIndyStakers } = F3.pipe(
2108
2132
  cdpDatums,
2109
- A.reduce(
2133
+ A2.reduce(
2110
2134
  { aggregatedFeeIndyStakers: 0n, aggregatedFeeTreasury: 0n },
2111
2135
  (acc, cdpDat) => match7(cdpDat.cdpFees).returnType().with({ FrozenCDPAccumulatedFees: P6.select() }, (fees) => ({
2112
2136
  aggregatedFeeIndyStakers: acc.aggregatedFeeIndyStakers + fees.lovelacesIndyStakers,
@@ -2115,7 +2139,7 @@ async function mergeCdps(cdpsToMergeUtxos, sysParams, lucid) {
2115
2139
  )
2116
2140
  );
2117
2141
  const [[mainMergeUtxo, mainCdpDatum], otherMergeUtxos] = match7(
2118
- A.zip(cdpUtxos, cdpDatums)
2142
+ A2.zip(cdpUtxos, cdpDatums)
2119
2143
  ).returnType().with([P6._, ...P6.array()], ([main, ...other]) => [
2120
2144
  main,
2121
2145
  other.map((a) => a[0])
@@ -2232,61 +2256,61 @@ var mkCDPCreatorValidatorFromSP = (params) => {
2232
2256
  import { applyParamsToScript as applyParamsToScript3 } from "@lucid-evolution/lucid";
2233
2257
 
2234
2258
  // src/contracts/poll/types-poll-manager.ts
2235
- import { Data as Data13 } from "@lucid-evolution/lucid";
2236
- var PollManagerParamsSchema = Data13.Object({
2259
+ import { Data as Data14 } from "@lucid-evolution/lucid";
2260
+ var PollManagerParamsSchema = Data14.Object({
2237
2261
  govNFT: AssetClassSchema,
2238
2262
  pollToken: AssetClassSchema,
2239
2263
  upgradeToken: AssetClassSchema,
2240
2264
  indyAsset: AssetClassSchema,
2241
- govExecuteValHash: Data13.Bytes(),
2242
- pBiasTime: Data13.Integer(),
2243
- shardValHash: Data13.Bytes(),
2244
- treasuryValHash: Data13.Bytes(),
2245
- initialIndyDistribution: Data13.Integer()
2265
+ govExecuteValHash: Data14.Bytes(),
2266
+ pBiasTime: Data14.Integer(),
2267
+ shardValHash: Data14.Bytes(),
2268
+ treasuryValHash: Data14.Bytes(),
2269
+ initialIndyDistribution: Data14.Integer()
2246
2270
  });
2247
2271
  var PollManagerParams = PollManagerParamsSchema;
2248
- var PollManagerRedeemerSchema = Data13.Enum([
2249
- Data13.Object({
2250
- EndPoll: Data13.Object({ currentTime: Data13.Integer() })
2272
+ var PollManagerRedeemerSchema = Data14.Enum([
2273
+ Data14.Object({
2274
+ EndPoll: Data14.Object({ currentTime: Data14.Integer() })
2251
2275
  }),
2252
- Data13.Object({ CreateShards: Data13.Object({ currentTime: Data13.Integer() }) }),
2253
- Data13.Object({
2254
- MergeShardsManager: Data13.Object({ currentTime: Data13.Integer() })
2276
+ Data14.Object({ CreateShards: Data14.Object({ currentTime: Data14.Integer() }) }),
2277
+ Data14.Object({
2278
+ MergeShardsManager: Data14.Object({ currentTime: Data14.Integer() })
2255
2279
  })
2256
2280
  ]);
2257
2281
  var PollManagerRedeemer = PollManagerRedeemerSchema;
2258
2282
  function serialisePollManagerRedeemer(r) {
2259
- return Data13.to(r, PollManagerRedeemer);
2283
+ return Data14.to(r, PollManagerRedeemer);
2260
2284
  }
2261
2285
  function castPollManagerParams(params) {
2262
- return Data13.castTo(params, PollManagerParams);
2286
+ return Data14.castTo(params, PollManagerParams);
2263
2287
  }
2264
2288
 
2265
2289
  // src/contracts/poll/types-poll-shard.ts
2266
- import { Data as Data14 } from "@lucid-evolution/lucid";
2267
- var PollShardParamsSchema = Data14.Object({
2290
+ import { Data as Data15 } from "@lucid-evolution/lucid";
2291
+ var PollShardParamsSchema = Data15.Object({
2268
2292
  pollToken: AssetClassSchema,
2269
2293
  stakingToken: AssetClassSchema,
2270
2294
  indyAsset: AssetClassSchema,
2271
- stakingValHash: Data14.Bytes()
2295
+ stakingValHash: Data15.Bytes()
2272
2296
  });
2273
2297
  var PollShardParams = PollShardParamsSchema;
2274
- var VoteOptionSchema = Data14.Enum([Data14.Literal("Yes"), Data14.Literal("No")]);
2275
- var PollShardRedeemerSchema = Data14.Enum([
2276
- Data14.Object({ Vote: Data14.Object({ content: VoteOptionSchema }) }),
2277
- Data14.Object({
2278
- MergeShards: Data14.Object({
2279
- currentTime: Data14.Integer(),
2298
+ var VoteOptionSchema = Data15.Enum([Data15.Literal("Yes"), Data15.Literal("No")]);
2299
+ var PollShardRedeemerSchema = Data15.Enum([
2300
+ Data15.Object({ Vote: Data15.Object({ content: VoteOptionSchema }) }),
2301
+ Data15.Object({
2302
+ MergeShards: Data15.Object({
2303
+ currentTime: Data15.Integer(),
2280
2304
  pollManagerRef: OutputReferenceSchema
2281
2305
  })
2282
2306
  })
2283
2307
  ]);
2284
2308
  var PollShardRedeemer = PollShardRedeemerSchema;
2285
2309
  function serialisePollShardRedeemer(redeemer) {
2286
- return Data14.to(redeemer, PollShardRedeemer);
2310
+ return Data15.to(redeemer, PollShardRedeemer);
2287
2311
  }
2288
2312
  function castPollShardParams(params) {
2289
- return Data14.castTo(params, PollShardParams);
2313
+ return Data15.castTo(params, PollShardParams);
2290
2314
  }
2291
2315
 
2292
2316
  // src/validators/poll-manager-validator.ts
@@ -2363,44 +2387,44 @@ import {
2363
2387
  } from "@lucid-evolution/lucid";
2364
2388
 
2365
2389
  // src/contracts/poll/types-poll.ts
2366
- import { Data as Data15 } from "@lucid-evolution/lucid";
2390
+ import { Data as Data16 } from "@lucid-evolution/lucid";
2367
2391
  import { option as O3, function as F4 } from "fp-ts";
2368
2392
  import { match as match8, P as P7 } from "ts-pattern";
2369
- var PollStatusSchema = Data15.Object({
2370
- yesVotes: Data15.Integer(),
2371
- noVotes: Data15.Integer()
2393
+ var PollStatusSchema = Data16.Object({
2394
+ yesVotes: Data16.Integer(),
2395
+ noVotes: Data16.Integer()
2372
2396
  });
2373
- var PollManagerContentSchema = Data15.Object({
2374
- pollId: Data15.Integer(),
2375
- pollOwner: Data15.Bytes(),
2397
+ var PollManagerContentSchema = Data16.Object({
2398
+ pollId: Data16.Integer(),
2399
+ pollOwner: Data16.Bytes(),
2376
2400
  content: ProposalContentSchema,
2377
- treasuryWithdrawal: Data15.Nullable(TreasuryWithdrawalSchema),
2401
+ treasuryWithdrawal: Data16.Nullable(TreasuryWithdrawalSchema),
2378
2402
  status: PollStatusSchema,
2379
- votingEndTime: Data15.Integer(),
2380
- createdShardsCount: Data15.Integer(),
2381
- talliedShardsCount: Data15.Integer(),
2382
- totalShardsCount: Data15.Integer(),
2383
- proposingEndTime: Data15.Integer(),
2384
- expirationTime: Data15.Integer(),
2385
- protocolVersion: Data15.Integer(),
2386
- minimumQuorum: Data15.Integer()
2403
+ votingEndTime: Data16.Integer(),
2404
+ createdShardsCount: Data16.Integer(),
2405
+ talliedShardsCount: Data16.Integer(),
2406
+ totalShardsCount: Data16.Integer(),
2407
+ proposingEndTime: Data16.Integer(),
2408
+ expirationTime: Data16.Integer(),
2409
+ protocolVersion: Data16.Integer(),
2410
+ minimumQuorum: Data16.Integer()
2387
2411
  });
2388
- var PollShardContentSchema = Data15.Object({
2389
- pollId: Data15.Integer(),
2412
+ var PollShardContentSchema = Data16.Object({
2413
+ pollId: Data16.Integer(),
2390
2414
  status: PollStatusSchema,
2391
- votingEndTime: Data15.Integer(),
2415
+ votingEndTime: Data16.Integer(),
2392
2416
  managerAddress: AddressSchema
2393
2417
  });
2394
- var PollDatumSchema = Data15.Enum([
2395
- Data15.Object({
2396
- PollManager: Data15.Object({ content: PollManagerContentSchema })
2418
+ var PollDatumSchema = Data16.Enum([
2419
+ Data16.Object({
2420
+ PollManager: Data16.Object({ content: PollManagerContentSchema })
2397
2421
  }),
2398
- Data15.Object({ PollShard: Data15.Object({ content: PollShardContentSchema }) })
2422
+ Data16.Object({ PollShard: Data16.Object({ content: PollShardContentSchema }) })
2399
2423
  ]);
2400
2424
  var PollDatum = PollDatumSchema;
2401
2425
  function parsePollManager(datum) {
2402
2426
  try {
2403
- return match8(Data15.from(datum, PollDatum)).with({ PollManager: P7.select() }, (res) => O3.some(res.content)).otherwise(() => O3.none);
2427
+ return match8(Data16.from(datum, PollDatum)).with({ PollManager: P7.select() }, (res) => O3.some(res.content)).otherwise(() => O3.none);
2404
2428
  } catch (_) {
2405
2429
  return O3.none;
2406
2430
  }
@@ -2415,7 +2439,7 @@ function parsePollManagerOrThrow(datum) {
2415
2439
  }
2416
2440
  function parsePollShard(datum) {
2417
2441
  try {
2418
- return match8(Data15.from(datum, PollDatum)).with({ PollShard: P7.select() }, (res) => O3.some(res.content)).otherwise(() => O3.none);
2442
+ return match8(Data16.from(datum, PollDatum)).with({ PollShard: P7.select() }, (res) => O3.some(res.content)).otherwise(() => O3.none);
2419
2443
  } catch (_) {
2420
2444
  return O3.none;
2421
2445
  }
@@ -2429,49 +2453,49 @@ function parsePollShardOrThrow(datum) {
2429
2453
  );
2430
2454
  }
2431
2455
  function serialisePollDatum(datum) {
2432
- return Data15.to(datum, PollDatum);
2456
+ return Data16.to(datum, PollDatum);
2433
2457
  }
2434
2458
 
2435
2459
  // src/contracts/gov/transactions.ts
2436
- import { Data as Data18 } from "@lucid-evolution/lucid";
2460
+ import { Data as Data19 } from "@lucid-evolution/lucid";
2437
2461
  import { pipe as pipe2 } from "fp-ts/lib/function";
2438
- import { array as A4, option as O7, function as F8 } from "fp-ts";
2462
+ import { array as A5, option as O7, function as F8 } from "fp-ts";
2439
2463
  import { match as match11, P as P10 } from "ts-pattern";
2440
2464
 
2441
2465
  // src/contracts/staking/types.ts
2442
- import { Data as Data16 } from "@lucid-evolution/lucid";
2443
- var StakingParamsSchema = Data16.Object({
2466
+ import { Data as Data17 } from "@lucid-evolution/lucid";
2467
+ var StakingParamsSchema = Data17.Object({
2444
2468
  stakingManagerNft: AssetClassSchema,
2445
2469
  stakingToken: AssetClassSchema,
2446
2470
  indyToken: AssetClassSchema,
2447
2471
  pollToken: AssetClassSchema,
2448
2472
  versionRecordToken: AssetClassSchema,
2449
- collectorValHash: Data16.Bytes()
2473
+ collectorValHash: Data17.Bytes()
2450
2474
  });
2451
2475
  var StakingParams = StakingParamsSchema;
2452
- var StakingRedeemerSchema = Data16.Enum([
2453
- Data16.Object({
2454
- CreateStakingPosition: Data16.Object({
2455
- creatorPkh: Data16.Bytes()
2476
+ var StakingRedeemerSchema = Data17.Enum([
2477
+ Data17.Object({
2478
+ CreateStakingPosition: Data17.Object({
2479
+ creatorPkh: Data17.Bytes()
2456
2480
  })
2457
2481
  }),
2458
- Data16.Literal("UpdateTotalStake"),
2459
- Data16.Literal("Distribute"),
2460
- Data16.Object({
2461
- AdjustStakedAmount: Data16.Object({
2462
- adjustAmount: Data16.Integer()
2482
+ Data17.Literal("UpdateTotalStake"),
2483
+ Data17.Literal("Distribute"),
2484
+ Data17.Object({
2485
+ AdjustStakedAmount: Data17.Object({
2486
+ adjustAmount: Data17.Integer()
2463
2487
  })
2464
2488
  }),
2465
- Data16.Literal("Unstake"),
2466
- Data16.Literal("Lock"),
2467
- Data16.Literal("UpgradeVersion")
2489
+ Data17.Literal("Unstake"),
2490
+ Data17.Literal("Lock"),
2491
+ Data17.Literal("UpgradeVersion")
2468
2492
  ]);
2469
2493
  var StakingRedeemer = StakingRedeemerSchema;
2470
2494
  function serialiseStakingRedeemer(redeemer) {
2471
- return Data16.to(redeemer, StakingRedeemer);
2495
+ return Data17.to(redeemer, StakingRedeemer);
2472
2496
  }
2473
2497
  function castStakingParams(params) {
2474
- return Data16.castTo(params, StakingParams);
2498
+ return Data17.castTo(params, StakingParams);
2475
2499
  }
2476
2500
 
2477
2501
  // src/contracts/staking/types-new.ts
@@ -2547,7 +2571,7 @@ import {
2547
2571
  // src/contracts/staking/scripts.ts
2548
2572
  import {
2549
2573
  applyParamsToScript as applyParamsToScript4,
2550
- Constr as Constr2,
2574
+ Constr,
2551
2575
  fromText as fromText2
2552
2576
  } from "@lucid-evolution/lucid";
2553
2577
 
@@ -2563,24 +2587,24 @@ var mkStakingValidatorFromSP = (params) => {
2563
2587
  return {
2564
2588
  type: "PlutusV2",
2565
2589
  script: applyParamsToScript4(_stakingValidator.cborHex, [
2566
- new Constr2(0, [
2567
- new Constr2(0, [
2590
+ new Constr(0, [
2591
+ new Constr(0, [
2568
2592
  params.stakingManagerNFT[0].unCurrencySymbol,
2569
2593
  fromText2(params.stakingManagerNFT[1].unTokenName)
2570
2594
  ]),
2571
- new Constr2(0, [
2595
+ new Constr(0, [
2572
2596
  params.stakingToken[0].unCurrencySymbol,
2573
2597
  fromText2(params.stakingToken[1].unTokenName)
2574
2598
  ]),
2575
- new Constr2(0, [
2599
+ new Constr(0, [
2576
2600
  params.indyToken[0].unCurrencySymbol,
2577
2601
  fromText2(params.indyToken[1].unTokenName)
2578
2602
  ]),
2579
- new Constr2(0, [
2603
+ new Constr(0, [
2580
2604
  params.pollToken[0].unCurrencySymbol,
2581
2605
  fromText2(params.pollToken[1].unTokenName)
2582
2606
  ]),
2583
- new Constr2(0, [
2607
+ new Constr(0, [
2584
2608
  params.versionRecordToken[0].unCurrencySymbol,
2585
2609
  fromText2(params.versionRecordToken[1].unTokenName)
2586
2610
  ]),
@@ -2647,10 +2671,14 @@ function findStakingPositionByOutRef(stakingPositionRef, lucid) {
2647
2671
  return result;
2648
2672
  });
2649
2673
  }
2674
+ var rewardSnapshotPrecision = OCD_DECIMAL_UNIT * OCD_DECIMAL_UNIT;
2675
+ function distributeReward(snapshotAda, adaReward, totalStake) {
2676
+ return snapshotAda + adaReward * rewardSnapshotPrecision / totalStake;
2677
+ }
2650
2678
 
2651
2679
  // src/contracts/vesting/helpers.ts
2652
2680
  import { match as match10, P as P9 } from "ts-pattern";
2653
- import { array as A2 } from "fp-ts";
2681
+ import { array as A3 } from "fp-ts";
2654
2682
  var teamVestingSchedule = [
2655
2683
  {
2656
2684
  vestedAtTime: 1669067100000n,
@@ -2837,7 +2865,7 @@ var govDistributionSchedule = {
2837
2865
  ]
2838
2866
  };
2839
2867
  function calculateTotalVestedTeam(currentTime) {
2840
- return A2.reduce(0n, (acc, schedule) => {
2868
+ return A3.reduce(0n, (acc, schedule) => {
2841
2869
  if (currentTime >= schedule.vestedAtTime) {
2842
2870
  return acc + schedule.unlockAmt;
2843
2871
  } else {
@@ -2895,37 +2923,37 @@ function pollPassQuorum(initialIndyDist, pollStatus, currentTime, minQuorum, tre
2895
2923
  }
2896
2924
 
2897
2925
  // src/contracts/execute/types.ts
2898
- import { Data as Data17 } from "@lucid-evolution/lucid";
2926
+ import { Data as Data18 } from "@lucid-evolution/lucid";
2899
2927
  import { option as O5, function as F6 } from "fp-ts";
2900
- var ExecuteParamsSchema = Data17.Object({
2928
+ var ExecuteParamsSchema = Data18.Object({
2901
2929
  govNFT: AssetClassSchema,
2902
2930
  upgradeToken: AssetClassSchema,
2903
2931
  iAssetToken: AssetClassSchema,
2904
2932
  stabilityPoolToken: AssetClassSchema,
2905
2933
  versionRecordToken: AssetClassSchema,
2906
- cdpValHash: Data17.Bytes(),
2907
- sPoolValHash: Data17.Bytes(),
2908
- versionRegistryValHash: Data17.Bytes(),
2909
- treasuryValHash: Data17.Bytes(),
2934
+ cdpValHash: Data18.Bytes(),
2935
+ sPoolValHash: Data18.Bytes(),
2936
+ versionRegistryValHash: Data18.Bytes(),
2937
+ treasuryValHash: Data18.Bytes(),
2910
2938
  indyAsset: AssetClassSchema
2911
2939
  });
2912
2940
  var ExecuteParams = ExecuteParamsSchema;
2913
- var ExecuteDatumSchema = Data17.Object({
2914
- id: Data17.Integer(),
2941
+ var ExecuteDatumSchema = Data18.Object({
2942
+ id: Data18.Integer(),
2915
2943
  content: ProposalContentSchema,
2916
- passedTime: Data17.Integer(),
2917
- votingEndTime: Data17.Integer(),
2918
- protocolVersion: Data17.Integer(),
2944
+ passedTime: Data18.Integer(),
2945
+ votingEndTime: Data18.Integer(),
2946
+ protocolVersion: Data18.Integer(),
2919
2947
  /// Value proposed to be withdrawn from the treasury as part of the proposal.
2920
- treasuryWithdrawal: Data17.Nullable(TreasuryWithdrawalSchema)
2948
+ treasuryWithdrawal: Data18.Nullable(TreasuryWithdrawalSchema)
2921
2949
  });
2922
2950
  var ExecuteDatum = ExecuteDatumSchema;
2923
2951
  function serialiseExecuteDatum(d) {
2924
- return Data17.to(d, ExecuteDatum);
2952
+ return Data18.to(d, ExecuteDatum);
2925
2953
  }
2926
2954
  function parseExecuteDatum(d) {
2927
2955
  try {
2928
- return O5.some(Data17.from(d, ExecuteDatum));
2956
+ return O5.some(Data18.from(d, ExecuteDatum));
2929
2957
  } catch (_) {
2930
2958
  return O5.none;
2931
2959
  }
@@ -2939,16 +2967,16 @@ function parseExecuteDatumOrThrow(d) {
2939
2967
  );
2940
2968
  }
2941
2969
  function castExecuteParams(params) {
2942
- return Data17.castTo(params, ExecuteParams);
2970
+ return Data18.castTo(params, ExecuteParams);
2943
2971
  }
2944
2972
 
2945
2973
  // src/contracts/gov/helpers.ts
2946
2974
  import { pipe } from "fp-ts/lib/function";
2947
2975
  import {
2948
- array as A3,
2976
+ array as A4,
2949
2977
  option as O6,
2950
2978
  string as S,
2951
- ord as Ord,
2979
+ ord as Ord2,
2952
2980
  function as F7
2953
2981
  } from "fp-ts";
2954
2982
  import {
@@ -2959,7 +2987,7 @@ function proposalDeposit(baseDeposit, activeProposals) {
2959
2987
  return baseDeposit * 2n ** activeProposals;
2960
2988
  }
2961
2989
  function createValueFromWithdrawal(w) {
2962
- return A3.reduce(
2990
+ return A4.reduce(
2963
2991
  {},
2964
2992
  (acc, [cs, tk, amt]) => addAssets4(acc, mkAssetsOf({ currencySymbol: cs, tokenName: tk }, amt))
2965
2993
  )(w.value);
@@ -2978,20 +3006,20 @@ async function findRelativeIAssetForInsertion(newIAssetTokenName, allIAssetOrefs
2978
3006
  return pipe(
2979
3007
  // Sort the asset names
2980
3008
  iassetUtxos,
2981
- A3.sort(
2982
- Ord.contramap((x) => toText2(x.datum.assetName))(
3009
+ A4.sort(
3010
+ Ord2.contramap((x) => toText2(x.datum.assetName))(
2983
3011
  S.Ord
2984
3012
  )
2985
3013
  ),
2986
3014
  // split head and tail
2987
- A3.foldLeft(
3015
+ A4.foldLeft(
2988
3016
  () => O6.none,
2989
3017
  (head, rest) => O6.some([head, rest])
2990
3018
  ),
2991
3019
  // find the preceding iasset for the new token name
2992
3020
  O6.flatMap(
2993
3021
  ([firstIAsset, rest]) => O6.some(
2994
- A3.reduce(
3022
+ A4.reduce(
2995
3023
  firstIAsset,
2996
3024
  (acc, iasset) => toText2(iasset.datum.assetName) < newIAssetTokenName ? iasset : acc
2997
3025
  )(rest)
@@ -3131,7 +3159,7 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
3131
3159
  }).otherwise(() => {
3132
3160
  });
3133
3161
  return [
3134
- tx.mintAssets(pollNftValue, Data18.void()).readFrom([govRefScriptUtxo, pollAuthTokenPolicyRefScriptUtxo]).collectFrom(
3162
+ tx.mintAssets(pollNftValue, Data19.void()).readFrom([govRefScriptUtxo, pollAuthTokenPolicyRefScriptUtxo]).collectFrom(
3135
3163
  [govUtxo],
3136
3164
  serialiseGovRedeemer({
3137
3165
  CreatePoll: {
@@ -3229,7 +3257,7 @@ async function createShardsChunks(chunkSize, pollManagerOref, sysParams, current
3229
3257
  const pollNft = fromSystemParamsAsset(sysParams.govParams.pollToken);
3230
3258
  const tx = lucid.newTx().validFrom(Number(currentTime) - ONE_SECOND).validTo(
3231
3259
  Number(currentTime + sysParams.pollManagerParams.pBiasTime) - ONE_SECOND
3232
- ).mintAssets(mkAssetsOf(pollNft, shardsCount), Data18.void()).readFrom([pollAuthTokenPolicyRefScriptUtxo, pollManagerRefScriptUtxo]).collectFrom(
3260
+ ).mintAssets(mkAssetsOf(pollNft, shardsCount), Data19.void()).readFrom([pollAuthTokenPolicyRefScriptUtxo, pollManagerRefScriptUtxo]).collectFrom(
3233
3261
  [pollManagerUtxo],
3234
3262
  serialisePollManagerRedeemer({ CreateShards: { currentTime } })
3235
3263
  ).pay.ToContract(
@@ -3399,8 +3427,8 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3399
3427
  const shardUtxos = await lucid.utxosByOutRef(shardsOutRefs);
3400
3428
  const aggregatedStatus = F8.pipe(
3401
3429
  shardUtxos,
3402
- A4.map((utxo) => parsePollShardOrThrow(getInlineDatumOrThrow(utxo))),
3403
- A4.reduce(
3430
+ A5.map((utxo) => parsePollShardOrThrow(getInlineDatumOrThrow(utxo))),
3431
+ A5.reduce(
3404
3432
  pollManagerDatum.status,
3405
3433
  (acc, shard) => ({
3406
3434
  yesVotes: acc.yesVotes + shard.status.yesVotes,
@@ -3408,7 +3436,7 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3408
3436
  })
3409
3437
  )
3410
3438
  );
3411
- const shardsAggregatedAda = A4.reduce(
3439
+ const shardsAggregatedAda = A5.reduce(
3412
3440
  {},
3413
3441
  (acc, utxo) => addAssets5(acc, mkLovelacesOf(lovelacesAmt(utxo.assets)))
3414
3442
  )(shardUtxos);
@@ -3419,7 +3447,7 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3419
3447
  pollShardRefScriptUtxo,
3420
3448
  pollManagerRefScriptUtxo,
3421
3449
  pollAuthTokenPolicyRefScriptUtxo
3422
- ]).mintAssets(mkAssetsOf(pollNft, -BigInt(shardsOutRefs.length)), Data18.void()).collectFrom(
3450
+ ]).mintAssets(mkAssetsOf(pollNft, -BigInt(shardsOutRefs.length)), Data19.void()).collectFrom(
3423
3451
  [pollManagerUtxo],
3424
3452
  serialisePollManagerRedeemer({
3425
3453
  MergeShardsManager: { currentTime }
@@ -3529,7 +3557,7 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3529
3557
  ).collectFrom(
3530
3558
  [govUtxo],
3531
3559
  serialiseGovRedeemer({ WitnessEndPoll: { currentTime } })
3532
- ).mintAssets(mkAssetsOf(pollNft, -1n), Data18.void()).pay.ToContract(
3560
+ ).mintAssets(mkAssetsOf(pollNft, -1n), Data19.void()).pay.ToContract(
3533
3561
  govUtxo.address,
3534
3562
  {
3535
3563
  kind: "inline",
@@ -3555,11 +3583,11 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3555
3583
  })
3556
3584
  },
3557
3585
  upgradeTokenVal
3558
- ).mintAssets(upgradeTokenVal, Data18.void());
3586
+ ).mintAssets(upgradeTokenVal, Data19.void());
3559
3587
  } else {
3560
3588
  tx.pay.ToContract(
3561
3589
  createScriptAddress(network, sysParams.validatorHashes.treasuryHash),
3562
- { kind: "inline", value: Data18.void() },
3590
+ { kind: "inline", value: Data19.void() },
3563
3591
  mkAssetsOf(
3564
3592
  indyAsset,
3565
3593
  assetClassValueOf(pollManagerUtxo.assets, indyAsset)
@@ -3654,7 +3682,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3654
3682
  sysParams.treasuryParams.treasuryUtxosStakeCredential
3655
3683
  ) : void 0
3656
3684
  ),
3657
- { kind: "inline", value: Data18.void() },
3685
+ { kind: "inline", value: Data19.void() },
3658
3686
  withdrawalChangeVal
3659
3687
  );
3660
3688
  }
@@ -3731,7 +3759,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3731
3759
  cdpRefScriptUtxo,
3732
3760
  iassetTokenPolicyRefScriptUtxo,
3733
3761
  stabilityPoolTokenPolicyRefScriptUtxo
3734
- ]).mintAssets(spAuthVal, Data18.void()).mintAssets(iassetAuthVal, Data18.void()).collectFrom([govUtxo], serialiseGovRedeemer("UpgradeGov")).pay.ToContract(
3762
+ ]).mintAssets(spAuthVal, Data19.void()).mintAssets(iassetAuthVal, Data19.void()).collectFrom([govUtxo], serialiseGovRedeemer("UpgradeGov")).pay.ToContract(
3735
3763
  govUtxo.address,
3736
3764
  {
3737
3765
  kind: "inline",
@@ -3897,7 +3925,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3897
3925
  fromSystemParamsAsset(sysParams.executeParams.versionRecordToken),
3898
3926
  1n
3899
3927
  );
3900
- tx.readFrom([govRefScriptUtxo, versionRecordTokenPolicyRefScriptUtxo]).mintAssets(versionRecordNftVal, Data18.void()).pay.ToContract(
3928
+ tx.readFrom([govRefScriptUtxo, versionRecordTokenPolicyRefScriptUtxo]).mintAssets(versionRecordNftVal, Data19.void()).pay.ToContract(
3901
3929
  createScriptAddress(
3902
3930
  network,
3903
3931
  sysParams.validatorHashes.versionRegistryHash
@@ -3925,56 +3953,56 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3925
3953
  govUtxo.assets
3926
3954
  );
3927
3955
  }).exhaustive();
3928
- tx.readFrom([upgradeTokenPolicyRefScriptUtxo, executeRefScriptUtxo]).validFrom(Number(currentTime) - ONE_SECOND).validTo(Number(currentTime + sysParams.govParams.gBiasTime) - ONE_SECOND).collectFrom([executeUtxo], Data18.void()).mintAssets(
3956
+ tx.readFrom([upgradeTokenPolicyRefScriptUtxo, executeRefScriptUtxo]).validFrom(Number(currentTime) - ONE_SECOND).validTo(Number(currentTime + sysParams.govParams.gBiasTime) - ONE_SECOND).collectFrom([executeUtxo], Data19.void()).mintAssets(
3929
3957
  mkAssetsOf(fromSystemParamsAsset(sysParams.govParams.upgradeToken), -1n),
3930
- Data18.void()
3958
+ Data19.void()
3931
3959
  ).addSigner(ownAddr);
3932
3960
  return tx;
3933
3961
  }
3934
3962
 
3935
3963
  // src/contracts/stability-pool/transactions.ts
3936
3964
  import {
3937
- Constr as Constr3,
3965
+ Constr as Constr2,
3938
3966
  fromText as fromText5,
3939
3967
  validatorToScriptHash as validatorToScriptHash2,
3940
- Data as Data20,
3968
+ Data as Data21,
3941
3969
  credentialToAddress as credentialToAddress3,
3942
3970
  fromHex as fromHex2,
3943
3971
  toHex
3944
3972
  } from "@lucid-evolution/lucid";
3945
3973
 
3946
3974
  // src/contracts/stability-pool/types.ts
3947
- import { Data as Data19 } from "@lucid-evolution/lucid";
3948
- var ActionReturnDatumSchema = Data19.Enum([
3949
- Data19.Object({
3950
- IndigoStabilityPoolAccountAdjustment: Data19.Object({
3975
+ import { Data as Data20 } from "@lucid-evolution/lucid";
3976
+ var ActionReturnDatumSchema = Data20.Enum([
3977
+ Data20.Object({
3978
+ IndigoStabilityPoolAccountAdjustment: Data20.Object({
3951
3979
  spent_account: OutputReferenceSchema
3952
3980
  })
3953
3981
  }),
3954
- Data19.Object({
3955
- IndigoStabilityPoolAccountClosure: Data19.Object({
3982
+ Data20.Object({
3983
+ IndigoStabilityPoolAccountClosure: Data20.Object({
3956
3984
  closed_account: OutputReferenceSchema
3957
3985
  })
3958
3986
  })
3959
3987
  ]);
3960
3988
  var ActionReturnDatum = ActionReturnDatumSchema;
3961
- var StabilityPoolParamsSchema = Data19.Object({
3962
- assetSymbol: Data19.Bytes(),
3989
+ var StabilityPoolParamsSchema = Data20.Object({
3990
+ assetSymbol: Data20.Bytes(),
3963
3991
  stabilityPoolToken: AssetClassSchema,
3964
3992
  snapshotEpochToScaleToSumToken: AssetClassSchema,
3965
3993
  accountToken: AssetClassSchema,
3966
3994
  cdpToken: AssetClassSchema,
3967
3995
  iAssetAuthToken: AssetClassSchema,
3968
3996
  versionRecordToken: AssetClassSchema,
3969
- collectorValHash: Data19.Bytes(),
3997
+ collectorValHash: Data20.Bytes(),
3970
3998
  govNFT: AssetClassSchema,
3971
- accountCreateFeeLovelaces: Data19.Integer(),
3972
- accountAdjustmentFeeLovelaces: Data19.Integer(),
3973
- requestCollateralLovelaces: Data19.Integer()
3999
+ accountCreateFeeLovelaces: Data20.Integer(),
4000
+ accountAdjustmentFeeLovelaces: Data20.Integer(),
4001
+ requestCollateralLovelaces: Data20.Integer()
3974
4002
  });
3975
4003
  var StabilityPoolParams = StabilityPoolParamsSchema;
3976
4004
  function castStabilityPoolParams(params) {
3977
- return Data19.castTo(params, StabilityPoolParams);
4005
+ return Data20.castTo(params, StabilityPoolParams);
3978
4006
  }
3979
4007
 
3980
4008
  // src/contracts/stability-pool/scripts.ts
@@ -4217,7 +4245,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4217
4245
  {
4218
4246
  [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + fromText5(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4219
4247
  },
4220
- Data20.to(new Constr3(0, []))
4248
+ Data21.to(new Constr2(0, []))
4221
4249
  );
4222
4250
  tx.pay.ToContract(
4223
4251
  stabilityPoolUtxo.address,
@@ -4378,7 +4406,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4378
4406
  outputAddress,
4379
4407
  {
4380
4408
  kind: "inline",
4381
- value: Data20.to(
4409
+ value: Data21.to(
4382
4410
  {
4383
4411
  IndigoStabilityPoolAccountAdjustment: {
4384
4412
  spent_account: {
@@ -4452,7 +4480,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4452
4480
  {
4453
4481
  [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + fromText5(params.stabilityPoolParams.accountToken[1].unTokenName)]: -1n
4454
4482
  },
4455
- Data20.to(new Constr3(0, []))
4483
+ Data21.to(new Constr2(0, []))
4456
4484
  );
4457
4485
  const assetOutputAmountForSP = stabilityPoolUtxo.assets[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + fromText5(asset)] - fromSPInteger(withdrawnAmt) - withdrawalFeeAmount;
4458
4486
  tx.pay.ToContract(
@@ -4479,7 +4507,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4479
4507
  outputAddress,
4480
4508
  {
4481
4509
  kind: "inline",
4482
- value: Data20.to(
4510
+ value: Data21.to(
4483
4511
  {
4484
4512
  IndigoStabilityPoolAccountClosure: {
4485
4513
  closed_account: {
@@ -4503,8 +4531,9 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4503
4531
 
4504
4532
  // src/contracts/staking/transactions.ts
4505
4533
  import {
4506
- Constr as Constr4,
4507
- Data as Data21,
4534
+ addAssets as addAssets6,
4535
+ Constr as Constr3,
4536
+ Data as Data22,
4508
4537
  fromHex as fromHex3,
4509
4538
  fromText as fromText6,
4510
4539
  toHex as toHex2
@@ -4541,7 +4570,7 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4541
4570
  };
4542
4571
  const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + fromText6(params.stakingParams.stakingToken[1].unTokenName);
4543
4572
  const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + fromText6(params.stakingParams.indyToken[1].unTokenName);
4544
- return lucid.newTx().collectFrom([stakingManagerOut.utxo], Data21.to(new Constr4(0, [pkh.hash]))).readFrom([stakingRefScriptUtxo]).pay.ToContract(
4573
+ return lucid.newTx().collectFrom([stakingManagerOut.utxo], Data22.to(new Constr3(0, [pkh.hash]))).readFrom([stakingRefScriptUtxo]).pay.ToContract(
4545
4574
  stakingManagerOut.utxo.address,
4546
4575
  {
4547
4576
  kind: "inline",
@@ -4552,7 +4581,7 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4552
4581
  {
4553
4582
  [stakingToken]: 1n
4554
4583
  },
4555
- Data21.void()
4584
+ Data22.void()
4556
4585
  ).pay.ToContract(
4557
4586
  stakingManagerOut.utxo.address,
4558
4587
  {
@@ -4584,12 +4613,20 @@ async function adjustStakingPosition(stakingPositionRef, amount, params, lucid,
4584
4613
  const existingIndyAmount = stakingPositionOut.utxo.assets[indyToken] ?? 0n;
4585
4614
  const currentSnapshotAda = stakingManagerOut.datum.managerSnapshot.snapshotAda;
4586
4615
  const oldSnapshotAda = stakingPositionOut.datum.positionSnapshot.snapshotAda;
4587
- const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / (1000000n * 1000000n);
4616
+ const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / rewardSnapshotPrecision;
4588
4617
  const newLockedAmount = updateStakingLockedAmount(
4589
4618
  stakingPositionOut.datum.lockedAmount,
4590
4619
  BigInt(now)
4591
4620
  );
4592
- return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo]).collectFrom([stakingPositionOut.utxo], Data21.to(new Constr4(3, [amount]))).collectFrom([stakingManagerOut.utxo], Data21.to(new Constr4(1, []))).pay.ToContract(
4621
+ return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo]).collectFrom(
4622
+ [stakingPositionOut.utxo],
4623
+ serialiseStakingRedeemer({
4624
+ AdjustStakedAmount: { adjustAmount: amount }
4625
+ })
4626
+ ).collectFrom(
4627
+ [stakingManagerOut.utxo],
4628
+ serialiseStakingRedeemer("UpdateTotalStake")
4629
+ ).pay.ToContract(
4593
4630
  stakingManagerOut.utxo.address,
4594
4631
  {
4595
4632
  kind: "inline",
@@ -4644,7 +4681,7 @@ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingMa
4644
4681
  const currentSnapshotAda = stakingManagerOut.datum.managerSnapshot.snapshotAda;
4645
4682
  const oldSnapshotAda = stakingPositionOut.datum.positionSnapshot.snapshotAda;
4646
4683
  const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / (1000000n * 1000000n);
4647
- return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo, stakingTokenPolicyRefScriptUtxo]).collectFrom([stakingPositionOut.utxo], Data21.to(new Constr4(4, []))).collectFrom([stakingManagerOut.utxo], Data21.to(new Constr4(1, []))).pay.ToContract(
4684
+ return lucid.newTx().validFrom(Date.now()).readFrom([stakingRefScriptUtxo, stakingTokenPolicyRefScriptUtxo]).collectFrom([stakingPositionOut.utxo], Data22.to(new Constr3(4, []))).collectFrom([stakingManagerOut.utxo], Data22.to(new Constr3(1, []))).pay.ToContract(
4648
4685
  stakingManagerOut.utxo.address,
4649
4686
  {
4650
4687
  kind: "inline",
@@ -4661,9 +4698,63 @@ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingMa
4661
4698
  {
4662
4699
  [stakingToken]: -1n
4663
4700
  },
4664
- Data21.void()
4701
+ Data22.void()
4665
4702
  ).addSignerKey(toHex2(stakingPositionOut.datum.owner));
4666
4703
  }
4704
+ var MIN_UTXO_AMOUNT = 2000000n;
4705
+ async function distributeAda(stakingManagerRef, collectorRefs, params, lucid) {
4706
+ const [stakingManagerUtxo] = await lucid.utxosByOutRef([stakingManagerRef]);
4707
+ const stakingManagerDatum = parseStakingManagerDatum(
4708
+ getInlineDatumOrThrow(stakingManagerUtxo)
4709
+ );
4710
+ const collectorUtxos = (await lucid.utxosByOutRef(collectorRefs)).filter((utxo) => utxo.datum && utxo.datum === Data22.void()).filter((utxo) => utxo.assets.lovelace > MIN_UTXO_AMOUNT);
4711
+ if (collectorUtxos.length === 0) {
4712
+ throw new Error("No available collectors found");
4713
+ }
4714
+ const adaRewardCollected = collectorUtxos.reduce(
4715
+ (acc, utxo) => acc + utxo.assets.lovelace - MIN_UTXO_AMOUNT,
4716
+ 0n
4717
+ );
4718
+ const newSnapshot = distributeReward(
4719
+ stakingManagerDatum.managerSnapshot.snapshotAda,
4720
+ adaRewardCollected,
4721
+ stakingManagerDatum.totalStake
4722
+ );
4723
+ const stakingRefScriptUtxo = matchSingle(
4724
+ await lucid.utxosByOutRef([
4725
+ fromSystemParamsScriptRef(params.scriptReferences.stakingValidatorRef)
4726
+ ]),
4727
+ (_) => new Error("Expected a single staking Ref Script UTXO")
4728
+ );
4729
+ const collectorRefScriptUtxo = matchSingle(
4730
+ await lucid.utxosByOutRef([
4731
+ fromSystemParamsScriptRef(params.scriptReferences.collectorValidatorRef)
4732
+ ]),
4733
+ (_) => new Error("Expected a single staking Ref Script UTXO")
4734
+ );
4735
+ const tx = lucid.newTx().readFrom([stakingRefScriptUtxo, collectorRefScriptUtxo]).collectFrom([stakingManagerUtxo], serialiseStakingRedeemer("Distribute")).collectFrom(
4736
+ collectorUtxos,
4737
+ serialiseCollectorRedeemer("DistributeToStakers")
4738
+ ).pay.ToContract(
4739
+ stakingManagerUtxo.address,
4740
+ {
4741
+ kind: "inline",
4742
+ value: serialiseStakingDatum({
4743
+ ...stakingManagerDatum,
4744
+ managerSnapshot: { snapshotAda: newSnapshot }
4745
+ })
4746
+ },
4747
+ addAssets6(stakingManagerUtxo.assets, mkLovelacesOf(adaRewardCollected))
4748
+ );
4749
+ for (const collectorUtxo of collectorUtxos) {
4750
+ tx.pay.ToContract(
4751
+ collectorUtxo.address,
4752
+ { kind: "inline", value: Data22.void() },
4753
+ mkLovelacesOf(MIN_UTXO_AMOUNT)
4754
+ );
4755
+ }
4756
+ return tx;
4757
+ }
4667
4758
 
4668
4759
  // src/contracts/interest-oracle/transactions.ts
4669
4760
  import {
@@ -4674,9 +4765,9 @@ import {
4674
4765
 
4675
4766
  // src/contracts/one-shot/transactions.ts
4676
4767
  import {
4677
- addAssets as addAssets6,
4678
- Constr as Constr5,
4679
- Data as Data23,
4768
+ addAssets as addAssets7,
4769
+ Constr as Constr4,
4770
+ Data as Data24,
4680
4771
  mintingPolicyToId,
4681
4772
  toUnit as toUnit2
4682
4773
  } from "@lucid-evolution/lucid";
@@ -4687,23 +4778,23 @@ import {
4687
4778
  } from "@lucid-evolution/lucid";
4688
4779
 
4689
4780
  // src/contracts/one-shot/types.ts
4690
- import { Data as Data22 } from "@lucid-evolution/lucid";
4691
- var OneShotParamsSchema = Data22.Object({
4692
- referenceOutRef: Data22.Object({
4693
- txHash: Data22.Bytes(),
4694
- outputIdx: Data22.Integer()
4781
+ import { Data as Data23 } from "@lucid-evolution/lucid";
4782
+ var OneShotParamsSchema = Data23.Object({
4783
+ referenceOutRef: Data23.Object({
4784
+ txHash: Data23.Bytes(),
4785
+ outputIdx: Data23.Integer()
4695
4786
  }),
4696
- mintAmounts: Data22.Array(
4697
- Data22.Object({
4787
+ mintAmounts: Data23.Array(
4788
+ Data23.Object({
4698
4789
  /// Use hex encoded string
4699
- tokenName: Data22.Bytes(),
4700
- amount: Data22.Integer()
4790
+ tokenName: Data23.Bytes(),
4791
+ amount: Data23.Integer()
4701
4792
  })
4702
4793
  )
4703
4794
  });
4704
4795
  var OneShotParams = OneShotParamsSchema;
4705
4796
  function castOneShotParams(params) {
4706
- return Data22.castTo(params, OneShotParams);
4797
+ return Data23.castTo(params, OneShotParams);
4707
4798
  }
4708
4799
 
4709
4800
  // src/contracts/one-shot/scripts.ts
@@ -4740,11 +4831,11 @@ async function oneShotMintTx(lucid, params) {
4740
4831
  lucid.newTx().collectFrom([refUtxo]).mintAssets(
4741
4832
  reduce(
4742
4833
  {},
4743
- (acc, entry) => addAssets6(acc, {
4834
+ (acc, entry) => addAssets7(acc, {
4744
4835
  [toUnit2(policyId, entry.tokenName)]: entry.amount
4745
4836
  })
4746
4837
  )(params.mintAmounts),
4747
- Data23.to(new Constr5(0, []))
4838
+ Data24.to(new Constr4(0, []))
4748
4839
  ).attach.MintingPolicy(oneShotPolicy),
4749
4840
  policyId
4750
4841
  ];
@@ -4878,13 +4969,13 @@ async function feedInterestOracle(params, newInterestRate, lucid, assetClass, ut
4878
4969
  }
4879
4970
 
4880
4971
  // src/contracts/version-registry/types.ts
4881
- import { Data as Data24 } from "@lucid-evolution/lucid";
4882
- var VersionRecordTokenParamsSchema = Data24.Object({
4972
+ import { Data as Data25 } from "@lucid-evolution/lucid";
4973
+ var VersionRecordTokenParamsSchema = Data25.Object({
4883
4974
  upgradeToken: AssetClassSchema
4884
4975
  });
4885
4976
  var VersionRecordTokenParams = VersionRecordTokenParamsSchema;
4886
4977
  function castVersionRecordTokenParams(params) {
4887
- return Data24.castTo(params, VersionRecordTokenParams);
4978
+ return Data25.castTo(params, VersionRecordTokenParams);
4888
4979
  }
4889
4980
 
4890
4981
  // src/contracts/version-registry/scripts.ts
@@ -4925,7 +5016,7 @@ var mkVersionRegistryValidator = () => {
4925
5016
  // src/contracts/collector/scripts.ts
4926
5017
  import {
4927
5018
  applyParamsToScript as applyParamsToScript9,
4928
- Constr as Constr6,
5019
+ Constr as Constr5,
4929
5020
  fromText as fromText8
4930
5021
  } from "@lucid-evolution/lucid";
4931
5022
 
@@ -4941,16 +5032,16 @@ var mkCollectorValidatorFromSP = (params) => {
4941
5032
  return {
4942
5033
  type: "PlutusV2",
4943
5034
  script: applyParamsToScript9(_collectorValidator.cborHex, [
4944
- new Constr6(0, [
4945
- new Constr6(0, [
5035
+ new Constr5(0, [
5036
+ new Constr5(0, [
4946
5037
  params.stakingManagerNFT[0].unCurrencySymbol,
4947
5038
  fromText8(params.stakingManagerNFT[1].unTokenName)
4948
5039
  ]),
4949
- new Constr6(0, [
5040
+ new Constr5(0, [
4950
5041
  params.stakingToken[0].unCurrencySymbol,
4951
5042
  fromText8(params.stakingToken[1].unTokenName)
4952
5043
  ]),
4953
- new Constr6(0, [
5044
+ new Constr5(0, [
4954
5045
  params.versionRecordToken[0].unCurrencySymbol,
4955
5046
  fromText8(params.versionRecordToken[1].unTokenName)
4956
5047
  ])
@@ -4962,7 +5053,7 @@ var mkCollectorValidatorFromSP = (params) => {
4962
5053
  // src/contracts/treasury/scripts.ts
4963
5054
  import {
4964
5055
  applyParamsToScript as applyParamsToScript10,
4965
- Constr as Constr7,
5056
+ Constr as Constr6,
4966
5057
  fromText as fromText9
4967
5058
  } from "@lucid-evolution/lucid";
4968
5059
 
@@ -4978,22 +5069,22 @@ var mkTreasuryValidatorFromSP = (params) => {
4978
5069
  return {
4979
5070
  type: "PlutusV2",
4980
5071
  script: applyParamsToScript10(_treasuryValidator.cborHex, [
4981
- new Constr7(0, [
4982
- new Constr7(0, [
5072
+ new Constr6(0, [
5073
+ new Constr6(0, [
4983
5074
  params.upgradeToken[0].unCurrencySymbol,
4984
5075
  fromText9(params.upgradeToken[1].unTokenName)
4985
5076
  ]),
4986
- new Constr7(0, [
5077
+ new Constr6(0, [
4987
5078
  params.versionRecordToken[0].unCurrencySymbol,
4988
5079
  fromText9(params.versionRecordToken[1].unTokenName)
4989
5080
  ]),
4990
- params.treasuryUtxosStakeCredential ? new Constr7(0, [
4991
- new Constr7(0, [
4992
- new Constr7(1, [
5081
+ params.treasuryUtxosStakeCredential ? new Constr6(0, [
5082
+ new Constr6(0, [
5083
+ new Constr6(1, [
4993
5084
  params.treasuryUtxosStakeCredential.contents.contents
4994
5085
  ])
4995
5086
  ])
4996
- ]) : new Constr7(1, [])
5087
+ ]) : new Constr6(1, [])
4997
5088
  ])
4998
5089
  ])
4999
5090
  };
@@ -5045,66 +5136,280 @@ var mkExecuteValidatorFromSP = (params) => {
5045
5136
  };
5046
5137
  };
5047
5138
 
5139
+ // src/contracts/lrp/helpers.ts
5140
+ import { addAssets as addAssets8 } from "@lucid-evolution/lucid";
5141
+
5048
5142
  // src/contracts/lrp/types.ts
5049
- import { Data as Data25 } from "@lucid-evolution/lucid";
5050
- var LRPParamsSchema = Data25.Object({
5143
+ import { Data as Data26 } from "@lucid-evolution/lucid";
5144
+ import { option as O8, function as F9 } from "fp-ts";
5145
+ var LRPParamsSchema = Data26.Object({
5051
5146
  versionRecordToken: AssetClassSchema,
5052
5147
  iassetNft: AssetClassSchema,
5053
- iassetPolicyId: Data25.Bytes(),
5054
- minRedemptionLovelacesAmt: Data25.Integer()
5148
+ iassetPolicyId: Data26.Bytes(),
5149
+ minRedemptionLovelacesAmt: Data26.Integer()
5055
5150
  });
5056
5151
  var LRPParams = LRPParamsSchema;
5057
- var LRPDatumSchema = Data25.Object({
5058
- owner: Data25.Bytes(),
5059
- iasset: Data25.Bytes(),
5152
+ var LRPDatumSchema = Data26.Object({
5153
+ owner: Data26.Bytes(),
5154
+ iasset: Data26.Bytes(),
5060
5155
  maxPrice: OnChainDecimalSchema,
5061
5156
  /**
5062
5157
  * The amount of lovelaces that is available to be spent.
5063
5158
  * This doesn't correspond to the lovelaces in UTXO's value,
5064
5159
  * since that can contain fees, too.
5065
5160
  */
5066
- lovelacesToSpend: Data25.Integer()
5161
+ lovelacesToSpend: Data26.Integer()
5067
5162
  });
5068
5163
  var LRPDatum = LRPDatumSchema;
5069
- var LRPRedeemerSchema = Data25.Enum([
5070
- Data25.Object({ Redeem: Data25.Object({ continuingOutputIdx: Data25.Integer() }) }),
5071
- Data25.Object({
5072
- RedeemAuxiliary: Data25.Object({
5073
- continuingOutputIdx: Data25.Integer(),
5164
+ var LRPRedeemerSchema = Data26.Enum([
5165
+ Data26.Object({ Redeem: Data26.Object({ continuingOutputIdx: Data26.Integer() }) }),
5166
+ Data26.Object({
5167
+ RedeemAuxiliary: Data26.Object({
5168
+ continuingOutputIdx: Data26.Integer(),
5074
5169
  mainRedeemOutRef: OutputReferenceSchema,
5075
- asset: Data25.Bytes(),
5170
+ asset: Data26.Bytes(),
5076
5171
  assetPrice: OnChainDecimalSchema,
5077
5172
  redemptionReimbursementPercentage: OnChainDecimalSchema
5078
5173
  })
5079
5174
  }),
5080
- Data25.Literal("Cancel"),
5081
- Data25.Literal("UpgradeVersion")
5175
+ Data26.Literal("Cancel"),
5176
+ Data26.Literal("UpgradeVersion")
5082
5177
  ]);
5083
5178
  var LRPRedeemer = LRPRedeemerSchema;
5084
5179
  function parseLrpDatum(datum) {
5085
- return Data25.from(datum, LRPDatum);
5180
+ try {
5181
+ return O8.some(Data26.from(datum, LRPDatum));
5182
+ } catch (_) {
5183
+ return O8.none;
5184
+ }
5185
+ }
5186
+ function parseLrpDatumOrThrow(datum) {
5187
+ return F9.pipe(
5188
+ parseLrpDatum(datum),
5189
+ O8.match(() => {
5190
+ throw new Error("Expected an LRP datum.");
5191
+ }, F9.identity)
5192
+ );
5086
5193
  }
5087
5194
  function serialiseLrpDatum(datum) {
5088
- return Data25.to(datum, LRPDatum);
5195
+ return Data26.to(datum, LRPDatum);
5089
5196
  }
5090
5197
  function serialiseLrpRedeemer(redeemer) {
5091
- return Data25.to(redeemer, LRPRedeemer);
5198
+ return Data26.to(redeemer, LRPRedeemer);
5092
5199
  }
5093
5200
  function castLrpParams(params) {
5094
- return Data25.castTo(params, LRPParams);
5201
+ return Data26.castTo(params, LRPParams);
5202
+ }
5203
+
5204
+ // src/contracts/lrp/helpers.ts
5205
+ import { array as A7, function as F10, ord as Ord4, option as O9 } from "fp-ts";
5206
+
5207
+ // src/utils/array-utils.ts
5208
+ import { array as A6 } from "fp-ts";
5209
+ function shuffle(arr) {
5210
+ const source = [...arr];
5211
+ for (let i = source.length - 1; i > 0; i--) {
5212
+ const j = Math.floor(Math.random() * (i + 1));
5213
+ [source[i], source[j]] = [source[j], source[i]];
5214
+ }
5215
+ return source;
5216
+ }
5217
+ function insertSorted(arr, item, ord) {
5218
+ if (arr.length === 0) {
5219
+ return [item];
5220
+ }
5221
+ const arrOrd = ord.compare(arr[0], arr[arr.length - 1]);
5222
+ if (arrOrd === 0) {
5223
+ if (ord.compare(arr[0], item) === -1) {
5224
+ return [...arr, item];
5225
+ } else {
5226
+ return [item, ...arr];
5227
+ }
5228
+ }
5229
+ for (let i = 0; i < arr.length; i++) {
5230
+ if (ord.compare(arr[i], item) !== arrOrd) {
5231
+ return [...A6.takeLeft(i)(arr), item, ...A6.takeRight(arr.length - i)(arr)];
5232
+ }
5233
+ }
5234
+ return [...arr, item];
5235
+ }
5236
+
5237
+ // src/contracts/lrp/helpers.ts
5238
+ import { match as match12, P as P11 } from "ts-pattern";
5239
+ var MIN_LRP_COLLATERAL_AMT = 2000000n;
5240
+ function lrpRedeemableLovelacesInclReimb(lrp, lrpParams) {
5241
+ const datum = lrp[1];
5242
+ const utxo = lrp[0];
5243
+ let res = 0n;
5244
+ if (datum.lovelacesToSpend > lovelacesAmt(utxo.assets)) {
5245
+ res = bigintMax(lovelacesAmt(utxo.assets) - MIN_LRP_COLLATERAL_AMT, 0n);
5246
+ } else {
5247
+ res = datum.lovelacesToSpend;
5248
+ }
5249
+ if (res < lrpParams.minRedemptionLovelacesAmt) {
5250
+ return 0n;
5251
+ }
5252
+ return res;
5253
+ }
5254
+ function buildRedemptionsTx(redemptions, price, redemptionReimbursementPercentage, sysParams, tx, txOutputsBeforeCount) {
5255
+ const [[mainLrpUtxo, _], __] = match12(redemptions).with(
5256
+ [P11._, ...P11.array()],
5257
+ ([[firstLrp, _2], ...rest]) => [
5258
+ [firstLrp, _2],
5259
+ rest
5260
+ ]
5261
+ ).otherwise(() => {
5262
+ throw new Error("Expects at least 1 UTXO to redeem.");
5263
+ });
5264
+ const mainLrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(mainLrpUtxo));
5265
+ return F10.pipe(
5266
+ redemptions,
5267
+ A7.reduceWithIndex(
5268
+ tx,
5269
+ (idx, acc, [lrpUtxo, redeemIAssetAmt]) => {
5270
+ const lovelacesForRedemption = ocdMul(
5271
+ {
5272
+ getOnChainInt: redeemIAssetAmt
5273
+ },
5274
+ price
5275
+ ).getOnChainInt;
5276
+ const reimburstmentLovelaces = calculateFeeFromPercentage(
5277
+ redemptionReimbursementPercentage,
5278
+ lovelacesForRedemption
5279
+ );
5280
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5281
+ const resultVal = addAssets8(
5282
+ lrpUtxo.assets,
5283
+ mkLovelacesOf(-lovelacesForRedemption + reimburstmentLovelaces),
5284
+ mkAssetsOf(
5285
+ {
5286
+ currencySymbol: sysParams.lrpParams.iassetPolicyId.unCurrencySymbol,
5287
+ tokenName: mainLrpDatum.iasset
5288
+ },
5289
+ redeemIAssetAmt
5290
+ )
5291
+ );
5292
+ if (lovelacesAmt(resultVal) < MIN_LRP_COLLATERAL_AMT) {
5293
+ throw new Error("LRP was incorrectly initialised.");
5294
+ }
5295
+ return acc.collectFrom(
5296
+ [lrpUtxo],
5297
+ serialiseLrpRedeemer(
5298
+ idx === 0 ? { Redeem: { continuingOutputIdx: txOutputsBeforeCount + 0n } } : {
5299
+ RedeemAuxiliary: {
5300
+ continuingOutputIdx: txOutputsBeforeCount + BigInt(idx),
5301
+ mainRedeemOutRef: {
5302
+ txHash: { hash: mainLrpUtxo.txHash },
5303
+ outputIndex: BigInt(mainLrpUtxo.outputIndex)
5304
+ },
5305
+ asset: mainLrpDatum.iasset,
5306
+ assetPrice: price,
5307
+ redemptionReimbursementPercentage
5308
+ }
5309
+ }
5310
+ )
5311
+ ).pay.ToContract(
5312
+ lrpUtxo.address,
5313
+ {
5314
+ kind: "inline",
5315
+ value: serialiseLrpDatum({
5316
+ ...lrpDatum,
5317
+ lovelacesToSpend: lrpDatum.lovelacesToSpend - lovelacesForRedemption
5318
+ })
5319
+ },
5320
+ resultVal
5321
+ );
5322
+ }
5323
+ )
5324
+ );
5325
+ }
5326
+ function calculateTotalAdaForRedemption(iasset, iassetPrice, lrpParams, allLrps, maxLrpsInTx) {
5327
+ return F10.pipe(
5328
+ allLrps,
5329
+ A7.filterMap(([utxo, datum]) => {
5330
+ if (datum.iasset !== iasset || datum.maxPrice.getOnChainInt < iassetPrice.getOnChainInt) {
5331
+ return O9.none;
5332
+ }
5333
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
5334
+ [utxo, datum],
5335
+ lrpParams
5336
+ );
5337
+ if (lovelacesToSpend === 0n) {
5338
+ return O9.none;
5339
+ }
5340
+ return O9.some(lovelacesToSpend);
5341
+ }),
5342
+ // From largest to smallest
5343
+ A7.sort(Ord4.reverse(BigIntOrd)),
5344
+ // We can fit only this number of redemptions with CDP open into a single Tx.
5345
+ A7.takeLeft(maxLrpsInTx),
5346
+ sum
5347
+ );
5348
+ }
5349
+ function randomLrpsSubsetSatisfyingTargetLovelaces(iasset, targetLovelacesToSpend, iassetPrice, allLrps, lrpParams, maxLrpsInTx, randomiseFn = shuffle) {
5350
+ if (targetLovelacesToSpend < lrpParams.minRedemptionLovelacesAmt) {
5351
+ throw new Error("Can't redeem less than the minimum.");
5352
+ }
5353
+ const shuffled = randomiseFn(
5354
+ F10.pipe(
5355
+ allLrps,
5356
+ A7.filter(
5357
+ ([_, datum]) => datum.iasset === iasset && datum.maxPrice.getOnChainInt >= iassetPrice.getOnChainInt
5358
+ )
5359
+ )
5360
+ );
5361
+ let result = [];
5362
+ let runningSum = 0n;
5363
+ for (let i = 0; i < shuffled.length; i++) {
5364
+ const element = shuffled[i];
5365
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
5366
+ element,
5367
+ lrpParams
5368
+ );
5369
+ if (lovelacesToSpend < lrpParams.minRedemptionLovelacesAmt) {
5370
+ continue;
5371
+ }
5372
+ if (result.length > 0 && targetLovelacesToSpend - runningSum < lrpParams.minRedemptionLovelacesAmt) {
5373
+ const last = result[result.length - 1];
5374
+ if (lrpRedeemableLovelacesInclReimb(last, lrpParams) < lovelacesToSpend) {
5375
+ const popped = result.pop();
5376
+ runningSum -= lrpRedeemableLovelacesInclReimb(popped, lrpParams);
5377
+ } else {
5378
+ continue;
5379
+ }
5380
+ }
5381
+ result = insertSorted(
5382
+ result,
5383
+ element,
5384
+ Ord4.contramap(
5385
+ ([_, dat]) => dat.lovelacesToSpend
5386
+ // From highest to lowest
5387
+ )(Ord4.reverse(BigIntOrd))
5388
+ );
5389
+ runningSum += lovelacesToSpend;
5390
+ if (result.length > maxLrpsInTx) {
5391
+ const popped = result.pop();
5392
+ runningSum -= lrpRedeemableLovelacesInclReimb(popped, lrpParams);
5393
+ }
5394
+ if (runningSum >= targetLovelacesToSpend) {
5395
+ return result;
5396
+ }
5397
+ }
5398
+ if (targetLovelacesToSpend - runningSum >= lrpParams.minRedemptionLovelacesAmt) {
5399
+ throw new Error("Couldn't achieve target lovelaces");
5400
+ }
5401
+ return result;
5095
5402
  }
5096
5403
 
5097
5404
  // src/contracts/lrp/transactions.ts
5098
5405
  import {
5099
- addAssets as addAssets7,
5406
+ addAssets as addAssets9,
5100
5407
  unixTimeToSlot as unixTimeToSlot2,
5101
5408
  slotToUnixTime as slotToUnixTime5
5102
5409
  } from "@lucid-evolution/lucid";
5103
- import { match as match12, P as P11 } from "ts-pattern";
5104
5410
  import { unzip, zip } from "fp-ts/lib/Array";
5105
- import { reduceWithIndex } from "fp-ts/lib/Array";
5106
- var MIN_UTXO_COLLATERAL_AMT = 2000000n;
5107
- async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, lrpScriptHash, network, lrpStakeCredential) {
5411
+ async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, sysParams, lrpStakeCredential) {
5412
+ const network = lucid.config().network;
5108
5413
  const [ownPkh, _] = await addrDetails(lucid);
5109
5414
  const newDatum = {
5110
5415
  owner: ownPkh.hash,
@@ -5113,38 +5418,47 @@ async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, lrpScript
5113
5418
  lovelacesToSpend: lovelacesAmt2
5114
5419
  };
5115
5420
  return lucid.newTx().pay.ToContract(
5116
- createScriptAddress(network, lrpScriptHash, lrpStakeCredential),
5421
+ createScriptAddress(
5422
+ network,
5423
+ sysParams.validatorHashes.lrpHash,
5424
+ lrpStakeCredential
5425
+ ),
5117
5426
  {
5118
5427
  kind: "inline",
5119
5428
  value: serialiseLrpDatum(newDatum)
5120
5429
  },
5121
- { lovelace: lovelacesAmt2 + MIN_UTXO_COLLATERAL_AMT }
5430
+ { lovelace: lovelacesAmt2 + MIN_LRP_COLLATERAL_AMT }
5122
5431
  );
5123
5432
  }
5124
- async function cancelLrp(lrpOutRef, lrpRefScriptOutRef, lucid) {
5433
+ async function cancelLrp(lrpOutRef, sysParams, lucid) {
5125
5434
  const lrpScriptRefUtxo = matchSingle(
5126
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5435
+ await lucid.utxosByOutRef([
5436
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5437
+ ]),
5127
5438
  (_) => new Error("Expected a single LRP Ref Script UTXO")
5128
5439
  );
5129
5440
  const lrpUtxo = matchSingle(
5130
5441
  await lucid.utxosByOutRef([lrpOutRef]),
5131
5442
  (_) => new Error("Expected a single LRP UTXO.")
5132
5443
  );
5133
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5444
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5134
5445
  return lucid.newTx().readFrom([lrpScriptRefUtxo]).collectFrom([lrpUtxo], serialiseLrpRedeemer("Cancel")).addSignerKey(lrpDatum.owner);
5135
5446
  }
5136
- async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutRef, iassetOutRef, lucid, lrpParams, network) {
5447
+ async function redeemLrp(redemptionLrpsData, priceOracleOutRef, iassetOutRef, lucid, sysParams) {
5448
+ const network = lucid.config().network;
5137
5449
  const lrpScriptRefUtxo = matchSingle(
5138
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5139
- (_2) => new Error("Expected a single LRP Ref Script UTXO")
5450
+ await lucid.utxosByOutRef([
5451
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5452
+ ]),
5453
+ (_) => new Error("Expected a single LRP Ref Script UTXO")
5140
5454
  );
5141
5455
  const priceOracleUtxo = matchSingle(
5142
5456
  await lucid.utxosByOutRef([priceOracleOutRef]),
5143
- (_2) => new Error("Expected a single price oracle UTXO")
5457
+ (_) => new Error("Expected a single price oracle UTXO")
5144
5458
  );
5145
5459
  const iassetUtxo = matchSingle(
5146
5460
  await lucid.utxosByOutRef([iassetOutRef]),
5147
- (_2) => new Error("Expected a single IAsset UTXO")
5461
+ (_) => new Error("Expected a single IAsset UTXO")
5148
5462
  );
5149
5463
  const iassetDatum = parseIAssetDatumOrThrow(
5150
5464
  getInlineDatumOrThrow(iassetUtxo)
@@ -5154,69 +5468,14 @@ async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutR
5154
5468
  getInlineDatumOrThrow(priceOracleUtxo)
5155
5469
  );
5156
5470
  const redemptionLrps = await lucid.utxosByOutRef(lrpsToRedeemOutRefs).then((val) => zip(val, lrpRedemptionIAssetAmt));
5157
- const [[mainLrpUtxo, _], __] = match12(redemptionLrps).with(
5158
- [P11._, ...P11.array()],
5159
- ([[firstLrp, _2], ...rest]) => [
5160
- [firstLrp, _2],
5161
- rest
5162
- ]
5163
- ).otherwise(() => {
5164
- throw new Error("Expects at least 1 UTXO to redeem.");
5165
- });
5166
- const mainLrpDatum = parseLrpDatum(getInlineDatumOrThrow(mainLrpUtxo));
5167
- const tx = reduceWithIndex(
5471
+ const tx = buildRedemptionsTx(
5472
+ redemptionLrps,
5473
+ priceOracleDatum.price,
5474
+ iassetDatum.redemptionReimbursementPercentage,
5475
+ sysParams,
5168
5476
  lucid.newTx(),
5169
- (idx, acc, [lrpUtxo, redeemIAssetAmt]) => {
5170
- const lovelacesForRedemption = ocdMul(
5171
- {
5172
- getOnChainInt: redeemIAssetAmt
5173
- },
5174
- priceOracleDatum.price
5175
- ).getOnChainInt;
5176
- const reimburstmentLovelaces = calculateFeeFromPercentage(
5177
- iassetDatum.redemptionReimbursementPercentage,
5178
- lovelacesForRedemption
5179
- );
5180
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5181
- return acc.collectFrom(
5182
- [lrpUtxo],
5183
- serialiseLrpRedeemer(
5184
- idx === 0 ? { Redeem: { continuingOutputIdx: 0n } } : {
5185
- RedeemAuxiliary: {
5186
- continuingOutputIdx: BigInt(idx),
5187
- mainRedeemOutRef: {
5188
- txHash: { hash: mainLrpUtxo.txHash },
5189
- outputIndex: BigInt(mainLrpUtxo.outputIndex)
5190
- },
5191
- asset: mainLrpDatum.iasset,
5192
- assetPrice: priceOracleDatum.price,
5193
- redemptionReimbursementPercentage: iassetDatum.redemptionReimbursementPercentage
5194
- }
5195
- }
5196
- )
5197
- ).pay.ToContract(
5198
- lrpUtxo.address,
5199
- {
5200
- kind: "inline",
5201
- value: serialiseLrpDatum({
5202
- ...lrpDatum,
5203
- lovelacesToSpend: lrpDatum.lovelacesToSpend - lovelacesForRedemption
5204
- })
5205
- },
5206
- addAssets7(
5207
- lrpUtxo.assets,
5208
- mkLovelacesOf(-lovelacesForRedemption + reimburstmentLovelaces),
5209
- mkAssetsOf(
5210
- {
5211
- currencySymbol: lrpParams.iassetPolicyId,
5212
- tokenName: mainLrpDatum.iasset
5213
- },
5214
- redeemIAssetAmt
5215
- )
5216
- )
5217
- );
5218
- }
5219
- )(redemptionLrps);
5477
+ 0n
5478
+ );
5220
5479
  return lucid.newTx().validTo(
5221
5480
  slotToUnixTime5(
5222
5481
  network,
@@ -5224,18 +5483,20 @@ async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutR
5224
5483
  )
5225
5484
  ).readFrom([lrpScriptRefUtxo]).readFrom([iassetUtxo, priceOracleUtxo]).compose(tx);
5226
5485
  }
5227
- async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, lrpRefScriptOutRef, lrpParams) {
5486
+ async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, sysParams) {
5228
5487
  const lrpScriptRefUtxo = matchSingle(
5229
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5488
+ await lucid.utxosByOutRef([
5489
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5490
+ ]),
5230
5491
  (_) => new Error("Expected a single LRP Ref Script UTXO")
5231
5492
  );
5232
5493
  const lrpUtxo = matchSingle(
5233
5494
  await lucid.utxosByOutRef([lrpOutRef]),
5234
5495
  (_) => new Error("Expected a single LRP UTXO.")
5235
5496
  );
5236
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5497
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5237
5498
  const rewardAssetClass = {
5238
- currencySymbol: lrpParams.iassetPolicyId,
5499
+ currencySymbol: sysParams.lrpParams.iassetPolicyId.unCurrencySymbol,
5239
5500
  tokenName: lrpDatum.iasset
5240
5501
  };
5241
5502
  const rewardAssetsAmt = assetClassValueOf(lrpUtxo.assets, rewardAssetClass);
@@ -5258,15 +5519,15 @@ async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, lrpRefScriptOutRe
5258
5519
  lovelacesToSpend: lrpDatum.lovelacesToSpend + lovelacesAdjustAmt
5259
5520
  })
5260
5521
  },
5261
- addAssets7(
5522
+ addAssets9(
5262
5523
  lrpUtxo.assets,
5263
5524
  mkAssetsOf(rewardAssetClass, -rewardAssetsAmt),
5264
5525
  mkLovelacesOf(lovelacesAdjustAmt)
5265
5526
  )
5266
5527
  ).addSignerKey(lrpDatum.owner);
5267
5528
  }
5268
- async function claimLrp(lucid, lrpOutRef, lrpRefScriptOutRef, lrpParams) {
5269
- return adjustLrp(lucid, lrpOutRef, 0n, lrpRefScriptOutRef, lrpParams);
5529
+ async function claimLrp(lucid, lrpOutRef, sysParams) {
5530
+ return adjustLrp(lucid, lrpOutRef, 0n, sysParams);
5270
5531
  }
5271
5532
 
5272
5533
  // src/contracts/lrp/scripts.ts
@@ -5318,6 +5579,366 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5318
5579
  await lucid.awaitTx(txHash);
5319
5580
  return { txHash, outputIndex: 0 };
5320
5581
  }
5582
+
5583
+ // src/contracts/leverage/transactions.ts
5584
+ import {
5585
+ addAssets as addAssets10,
5586
+ slotToUnixTime as slotToUnixTime6,
5587
+ Data as Data27
5588
+ } from "@lucid-evolution/lucid";
5589
+
5590
+ // src/contracts/leverage/helpers.ts
5591
+ import { array as A8, function as F11 } from "fp-ts";
5592
+ import { Decimal as Decimal2 } from "decimal.js";
5593
+ var MAX_REDEMPTIONS_WITH_CDP_OPEN = 4;
5594
+ function approximateLeverageRedemptions(baseCollateral, targetLeverage, redemptionReimbursementPercentage, debtMintingFeePercentage) {
5595
+ const debtMintingFeeRatioDecimal = Decimal2(
5596
+ debtMintingFeePercentage.getOnChainInt
5597
+ ).div(OCD_DECIMAL_UNIT).div(100);
5598
+ const redemptionReimbursementRatioDecimal = Decimal2(
5599
+ redemptionReimbursementPercentage.getOnChainInt
5600
+ ).div(OCD_DECIMAL_UNIT).div(100);
5601
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
5602
+ redemptionReimbursementRatioDecimal
5603
+ );
5604
+ const bExFees = Decimal2(baseCollateral).mul(targetLeverage).minus(baseCollateral).floor();
5605
+ const b = bExFees.div(Decimal2(1).minus(totalFeeRatio)).floor();
5606
+ const collateralRatio = {
5607
+ getOnChainInt: fromDecimal(
5608
+ Decimal2(Decimal2(baseCollateral).add(bExFees)).div(b).mul(100n * OCD_DECIMAL_UNIT).floor()
5609
+ )
5610
+ };
5611
+ return {
5612
+ leverage: targetLeverage,
5613
+ collateralRatio,
5614
+ lovelacesForRedemptionWithReimbursement: fromDecimal(b)
5615
+ };
5616
+ }
5617
+ function summarizeActualLeverageRedemptions(lovelacesForRedemptionWithReimbursement, redemptionReimbursementPercentage, iassetPrice, lrpParams, redemptionLrps) {
5618
+ const priceDecimal = Decimal2(iassetPrice.getOnChainInt).div(OCD_DECIMAL_UNIT);
5619
+ const redemptionDetails = F11.pipe(
5620
+ redemptionLrps,
5621
+ A8.reduce(
5622
+ {
5623
+ remainingRedemptionLovelacesInclReim: lovelacesForRedemptionWithReimbursement,
5624
+ redemptions: []
5625
+ },
5626
+ (acc, lrp) => {
5627
+ if (acc.remainingRedemptionLovelacesInclReim < lrpParams.minRedemptionLovelacesAmt) {
5628
+ return acc;
5629
+ }
5630
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
5631
+ lrp,
5632
+ lrpParams
5633
+ );
5634
+ if (lovelacesToSpend === 0n) {
5635
+ return acc;
5636
+ }
5637
+ const newRemainingLovelaces = bigintMax(
5638
+ acc.remainingRedemptionLovelacesInclReim - lovelacesToSpend,
5639
+ 0n
5640
+ );
5641
+ const redemptionLovelacesInitial = acc.remainingRedemptionLovelacesInclReim - newRemainingLovelaces;
5642
+ const finalRedemptionIAssets = fromDecimal(
5643
+ Decimal2(redemptionLovelacesInitial).div(priceDecimal).floor()
5644
+ );
5645
+ const finalRedemptionLovelaces = ocdMul(
5646
+ {
5647
+ getOnChainInt: finalRedemptionIAssets
5648
+ },
5649
+ iassetPrice
5650
+ ).getOnChainInt;
5651
+ const reimbursementLovelaces = calculateFeeFromPercentage(
5652
+ redemptionReimbursementPercentage,
5653
+ finalRedemptionLovelaces
5654
+ );
5655
+ return {
5656
+ remainingRedemptionLovelacesInclReim: acc.remainingRedemptionLovelacesInclReim - finalRedemptionLovelaces,
5657
+ redemptions: [
5658
+ ...acc.redemptions,
5659
+ {
5660
+ utxo: lrp[0],
5661
+ iassetsForRedemptionAmt: finalRedemptionIAssets,
5662
+ redemptionLovelacesAmtInclReimbursement: finalRedemptionLovelaces,
5663
+ reimbursementLovelacesAmt: reimbursementLovelaces
5664
+ }
5665
+ ]
5666
+ };
5667
+ }
5668
+ )
5669
+ );
5670
+ const res = F11.pipe(
5671
+ redemptionDetails.redemptions,
5672
+ A8.reduce(
5673
+ {
5674
+ redeemedLovelaces: 0n,
5675
+ redemptionIAssets: 0n,
5676
+ reimbursementLovelaces: 0n
5677
+ },
5678
+ (acc, details) => {
5679
+ return {
5680
+ redeemedLovelaces: acc.redeemedLovelaces + details.redemptionLovelacesAmtInclReimbursement - details.reimbursementLovelacesAmt,
5681
+ reimbursementLovelaces: acc.reimbursementLovelaces + details.reimbursementLovelacesAmt,
5682
+ redemptionIAssets: acc.redemptionIAssets + details.iassetsForRedemptionAmt
5683
+ };
5684
+ }
5685
+ )
5686
+ );
5687
+ return {
5688
+ redemptions: redemptionDetails.redemptions,
5689
+ totalRedeemedLovelaces: res.redeemedLovelaces,
5690
+ totalReimbursementLovelaces: res.reimbursementLovelaces,
5691
+ totalRedemptionIAssets: res.redemptionIAssets
5692
+ };
5693
+ }
5694
+ function calculateCollateralRatioFromLeverage(iasset, leverage, baseCollateral, iassetPrice, debtMintingFeePercentage, redemptionReimbursementPercentage, lrpParams, allLrps) {
5695
+ const debtMintingFeeRatioDecimal = Decimal2(
5696
+ debtMintingFeePercentage.getOnChainInt
5697
+ ).div(OCD_DECIMAL_UNIT).div(100);
5698
+ const redemptionReimbursementRatioDecimal = Decimal2(
5699
+ redemptionReimbursementPercentage.getOnChainInt
5700
+ ).div(OCD_DECIMAL_UNIT).div(100);
5701
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
5702
+ redemptionReimbursementRatioDecimal
5703
+ );
5704
+ const maxAvailableAdaForRedemptionInclReimb = calculateTotalAdaForRedemption(
5705
+ iasset,
5706
+ iassetPrice,
5707
+ lrpParams,
5708
+ allLrps,
5709
+ MAX_REDEMPTIONS_WITH_CDP_OPEN
5710
+ );
5711
+ if (leverage <= 1 || baseCollateral <= 0n || maxAvailableAdaForRedemptionInclReimb <= 0n) {
5712
+ return void 0;
5713
+ }
5714
+ const bExFees = Decimal2(baseCollateral).mul(leverage).minus(baseCollateral).floor();
5715
+ const b = bExFees.div(Decimal2(1).minus(totalFeeRatio)).floor();
5716
+ const cappedB = bigintMin(
5717
+ maxAvailableAdaForRedemptionInclReimb,
5718
+ fromDecimal(b)
5719
+ );
5720
+ const cappedBExFees = Decimal2(cappedB).mul(Decimal2(1).minus(totalFeeRatio)).floor();
5721
+ const collateralRatio = Decimal2(
5722
+ Decimal2(baseCollateral).add(cappedBExFees)
5723
+ ).div(cappedB);
5724
+ return {
5725
+ getOnChainInt: fromDecimal(
5726
+ collateralRatio.mul(100n * OCD_DECIMAL_UNIT).floor()
5727
+ )
5728
+ };
5729
+ }
5730
+ function calculateLeverageFromCollateralRatio(iasset, collateralRatioPercentage, baseCollateral, iassetPrice, debtMintingFeePercentage, redemptionReimbursementPercentage, lrpParams, allLrps) {
5731
+ const debtMintingFeeRatioDecimal = Decimal2(
5732
+ debtMintingFeePercentage.getOnChainInt
5733
+ ).div(OCD_DECIMAL_UNIT).div(100);
5734
+ const redemptionReimbursementRatioDecimal = Decimal2(
5735
+ redemptionReimbursementPercentage.getOnChainInt
5736
+ ).div(OCD_DECIMAL_UNIT).div(100);
5737
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
5738
+ redemptionReimbursementRatioDecimal
5739
+ );
5740
+ const collateralRatio = Decimal2(collateralRatioPercentage.getOnChainInt).div(OCD_DECIMAL_UNIT).div(100);
5741
+ const maxAvailableAdaForRedemptionInclReimb = calculateTotalAdaForRedemption(
5742
+ iasset,
5743
+ iassetPrice,
5744
+ lrpParams,
5745
+ allLrps,
5746
+ MAX_REDEMPTIONS_WITH_CDP_OPEN
5747
+ );
5748
+ if (collateralRatio.toNumber() <= 1 || baseCollateral <= 0n || maxAvailableAdaForRedemptionInclReimb <= 0n) {
5749
+ return void 0;
5750
+ }
5751
+ const theoreticalMaxLeverage = Decimal2(Decimal2(1).minus(totalFeeRatio)).div(collateralRatio.minus(1).add(totalFeeRatio)).add(1);
5752
+ const bExFees = theoreticalMaxLeverage.mul(baseCollateral).minus(baseCollateral).floor();
5753
+ const b = bExFees.div(Decimal2(1).minus(totalFeeRatio)).floor();
5754
+ const cappedB = bigintMin(
5755
+ maxAvailableAdaForRedemptionInclReimb,
5756
+ fromDecimal(b)
5757
+ );
5758
+ const cappedBExFees = Decimal2(cappedB).mul(Decimal2(1).minus(totalFeeRatio)).floor();
5759
+ return Decimal2(baseCollateral).add(cappedBExFees).div(baseCollateral).toNumber();
5760
+ }
5761
+
5762
+ // src/contracts/leverage/transactions.ts
5763
+ async function leverageCdpWithLrp(leverage, baseCollateral, priceOracleOutRef, iassetOutRef, cdpCreatorOref, interestOracleOref, collectorOref, sysParams, lucid, allLrps, currentSlot) {
5764
+ const network = lucid.config().network;
5765
+ const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
5766
+ const [pkh, skh] = await addrDetails(lucid);
5767
+ const lrpScriptRefUtxo = matchSingle(
5768
+ await lucid.utxosByOutRef([
5769
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5770
+ ]),
5771
+ (_) => new Error("Expected a single LRP Ref Script UTXO")
5772
+ );
5773
+ const cdpCreatorRefScriptUtxo = matchSingle(
5774
+ await lucid.utxosByOutRef([
5775
+ fromSystemParamsScriptRef(
5776
+ sysParams.scriptReferences.cdpCreatorValidatorRef
5777
+ )
5778
+ ]),
5779
+ (_) => new Error("Expected a single cdp creator Ref Script UTXO")
5780
+ );
5781
+ const cdpAuthTokenPolicyRefScriptUtxo = matchSingle(
5782
+ await lucid.utxosByOutRef([
5783
+ fromSystemParamsScriptRef(
5784
+ sysParams.scriptReferences.authTokenPolicies.cdpAuthTokenRef
5785
+ )
5786
+ ]),
5787
+ (_) => new Error("Expected a single cdp auth token policy Ref Script UTXO")
5788
+ );
5789
+ const iAssetTokenPolicyRefScriptUtxo = matchSingle(
5790
+ await lucid.utxosByOutRef([
5791
+ fromSystemParamsScriptRef(
5792
+ sysParams.scriptReferences.iAssetTokenPolicyRef
5793
+ )
5794
+ ]),
5795
+ (_) => new Error("Expected a single iasset token policy Ref Script UTXO")
5796
+ );
5797
+ const cdpCreatorUtxo = matchSingle(
5798
+ await lucid.utxosByOutRef([cdpCreatorOref]),
5799
+ (_) => new Error("Expected a single CDP creator UTXO")
5800
+ );
5801
+ const interestOracleUtxo = matchSingle(
5802
+ await lucid.utxosByOutRef([interestOracleOref]),
5803
+ (_) => new Error("Expected a single interest oracle UTXO")
5804
+ );
5805
+ const interestOracleDatum = parseInterestOracleDatum(
5806
+ getInlineDatumOrThrow(interestOracleUtxo)
5807
+ );
5808
+ const priceOracleUtxo = matchSingle(
5809
+ await lucid.utxosByOutRef([priceOracleOutRef]),
5810
+ (_) => new Error("Expected a single price oracle UTXO")
5811
+ );
5812
+ const priceOracleDatum = parsePriceOracleDatum(
5813
+ getInlineDatumOrThrow(priceOracleUtxo)
5814
+ );
5815
+ const iassetUtxo = matchSingle(
5816
+ await lucid.utxosByOutRef([iassetOutRef]),
5817
+ (_) => new Error("Expected a single IAsset UTXO")
5818
+ );
5819
+ const iassetDatum = parseIAssetDatumOrThrow(
5820
+ getInlineDatumOrThrow(iassetUtxo)
5821
+ );
5822
+ const maxLeverage = calculateLeverageFromCollateralRatio(
5823
+ iassetDatum.assetName,
5824
+ iassetDatum.maintenanceRatio,
5825
+ baseCollateral,
5826
+ priceOracleDatum.price,
5827
+ iassetDatum.debtMintingFeePercentage,
5828
+ iassetDatum.redemptionReimbursementPercentage,
5829
+ sysParams.lrpParams,
5830
+ allLrps
5831
+ );
5832
+ if (!maxLeverage) {
5833
+ throw new Error("Can't calculate max leverage with those parameters.");
5834
+ }
5835
+ const leverageSummary = approximateLeverageRedemptions(
5836
+ baseCollateral,
5837
+ leverage,
5838
+ iassetDatum.redemptionReimbursementPercentage,
5839
+ iassetDatum.debtMintingFeePercentage
5840
+ );
5841
+ if (maxLeverage < leverageSummary.leverage) {
5842
+ throw new Error("Can't use more leverage than max.");
5843
+ }
5844
+ if (leverageSummary.collateralRatio.getOnChainInt < iassetDatum.maintenanceRatio.getOnChainInt) {
5845
+ throw new Error(
5846
+ "Can't have collateral ratio smaller than maintenance ratio"
5847
+ );
5848
+ }
5849
+ const redemptionDetails = summarizeActualLeverageRedemptions(
5850
+ leverageSummary.lovelacesForRedemptionWithReimbursement,
5851
+ iassetDatum.redemptionReimbursementPercentage,
5852
+ priceOracleDatum.price,
5853
+ sysParams.lrpParams,
5854
+ randomLrpsSubsetSatisfyingTargetLovelaces(
5855
+ iassetDatum.assetName,
5856
+ leverageSummary.lovelacesForRedemptionWithReimbursement,
5857
+ priceOracleDatum.price,
5858
+ allLrps,
5859
+ sysParams.lrpParams,
5860
+ MAX_REDEMPTIONS_WITH_CDP_OPEN
5861
+ )
5862
+ );
5863
+ const mintedAmt = redemptionDetails.totalRedemptionIAssets;
5864
+ const debtMintingFee = calculateFeeFromPercentage(
5865
+ iassetDatum.debtMintingFeePercentage,
5866
+ ocdMul({ getOnChainInt: mintedAmt }, priceOracleDatum.price).getOnChainInt
5867
+ );
5868
+ const collateralAmt = redemptionDetails.totalRedeemedLovelaces + baseCollateral - debtMintingFee;
5869
+ const cdpNftVal = mkAssetsOf(
5870
+ fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
5871
+ 1n
5872
+ );
5873
+ const iassetTokensVal = mkAssetsOf(
5874
+ {
5875
+ currencySymbol: sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
5876
+ tokenName: iassetDatum.assetName
5877
+ },
5878
+ mintedAmt
5879
+ );
5880
+ const txValidity = oracleExpirationAwareValidity(
5881
+ currentSlot,
5882
+ Number(sysParams.cdpCreatorParams.biasTime),
5883
+ Number(priceOracleDatum.expiration),
5884
+ network
5885
+ );
5886
+ const tx = lucid.newTx().validFrom(txValidity.validFrom).validTo(txValidity.validTo).readFrom([priceOracleUtxo, interestOracleUtxo, iassetUtxo]).readFrom([
5887
+ cdpCreatorRefScriptUtxo,
5888
+ cdpAuthTokenPolicyRefScriptUtxo,
5889
+ iAssetTokenPolicyRefScriptUtxo,
5890
+ lrpScriptRefUtxo
5891
+ ]).mintAssets(cdpNftVal, Data27.void()).mintAssets(iassetTokensVal, Data27.void()).collectFrom(
5892
+ [cdpCreatorUtxo],
5893
+ serialiseCDPCreatorRedeemer({
5894
+ CreateCDP: {
5895
+ cdpOwner: pkh.hash,
5896
+ minted: mintedAmt,
5897
+ collateral: collateralAmt,
5898
+ currentTime
5899
+ }
5900
+ })
5901
+ ).pay.ToContract(
5902
+ createScriptAddress(network, sysParams.validatorHashes.cdpHash, skh),
5903
+ {
5904
+ kind: "inline",
5905
+ value: serialiseCdpDatum({
5906
+ cdpOwner: pkh.hash,
5907
+ iasset: iassetDatum.assetName,
5908
+ mintedAmt,
5909
+ cdpFees: {
5910
+ ActiveCDPInterestTracking: {
5911
+ lastSettled: currentTime,
5912
+ unitaryInterestSnapshot: calculateUnitaryInterestSinceOracleLastUpdated(
5913
+ currentTime,
5914
+ interestOracleDatum
5915
+ ) + interestOracleDatum.unitaryInterest
5916
+ }
5917
+ }
5918
+ })
5919
+ },
5920
+ addAssets10(cdpNftVal, mkLovelacesOf(collateralAmt))
5921
+ ).pay.ToContract(
5922
+ cdpCreatorUtxo.address,
5923
+ { kind: "inline", value: Data27.void() },
5924
+ cdpCreatorUtxo.assets
5925
+ ).addSignerKey(pkh.hash);
5926
+ buildRedemptionsTx(
5927
+ redemptionDetails.redemptions.map((r) => [
5928
+ r.utxo,
5929
+ r.iassetsForRedemptionAmt
5930
+ ]),
5931
+ priceOracleDatum.price,
5932
+ iassetDatum.redemptionReimbursementPercentage,
5933
+ sysParams,
5934
+ tx,
5935
+ 2n
5936
+ );
5937
+ if (debtMintingFee > 0) {
5938
+ await collectorFeeTx(debtMintingFee, lucid, sysParams, tx, collectorOref);
5939
+ }
5940
+ return tx;
5941
+ }
5321
5942
  export {
5322
5943
  AccountContentSchema,
5323
5944
  ActionReturnDatum,
@@ -5345,6 +5966,8 @@ export {
5345
5966
  LRPDatumSchema,
5346
5967
  LRPParamsSchema,
5347
5968
  LRPRedeemerSchema,
5969
+ MAX_REDEMPTIONS_WITH_CDP_OPEN,
5970
+ MIN_LRP_COLLATERAL_AMT,
5348
5971
  ONE_DAY,
5349
5972
  ONE_HOUR,
5350
5973
  ONE_SECOND,
@@ -5375,12 +5998,17 @@ export {
5375
5998
  adjustSpAccount,
5376
5999
  adjustStakingPosition,
5377
6000
  adjustmentHelper,
6001
+ approximateLeverageRedemptions,
5378
6002
  assetClassToUnit,
5379
6003
  assetClassValueOf,
5380
6004
  balance,
6005
+ buildRedemptionsTx,
5381
6006
  burnCdp,
6007
+ calculateCollateralRatioFromLeverage,
5382
6008
  calculateIAssetRedemptionAmt,
6009
+ calculateLeverageFromCollateralRatio,
5383
6010
  calculateMinCollateralCappedIAssetRedemptionAmt,
6011
+ calculateTotalAdaForRedemption,
5384
6012
  cancelLrp,
5385
6013
  castCDPCreatorParams,
5386
6014
  castCdpParams,
@@ -5405,6 +6033,7 @@ export {
5405
6033
  createShardsChunks,
5406
6034
  createSpAccount,
5407
6035
  depositCdp,
6036
+ distributeAda,
5408
6037
  endProposal,
5409
6038
  executeProposal,
5410
6039
  feedInterestOracle,
@@ -5420,12 +6049,15 @@ export {
5420
6049
  getSumFromEpochToScaleToSum,
5421
6050
  initEpochToScaleToSumMap,
5422
6051
  initSpSnapshot,
6052
+ insertSorted,
5423
6053
  isAssetsZero,
6054
+ leverageCdpWithLrp,
5424
6055
  liquidateCdp,
5425
6056
  liquidationHelper,
5426
6057
  loadSystemParamsFromFile,
5427
6058
  loadSystemParamsFromUrl,
5428
6059
  lovelacesAmt,
6060
+ lrpRedeemableLovelacesInclReimb,
5429
6061
  matchSingle,
5430
6062
  mergeCdps,
5431
6063
  mergeShards,
@@ -5465,6 +6097,7 @@ export {
5465
6097
  parseIAssetDatumOrThrow,
5466
6098
  parseInterestOracleDatum,
5467
6099
  parseLrpDatum,
6100
+ parseLrpDatumOrThrow,
5468
6101
  parsePriceOracleDatum,
5469
6102
  parseSnapshotEpochToScaleToSumDatum,
5470
6103
  parseStabilityPoolDatum,
@@ -5472,6 +6105,7 @@ export {
5472
6105
  parseStakingPosition,
5473
6106
  parseStakingPositionOrThrow,
5474
6107
  processSpRequest,
6108
+ randomLrpsSubsetSatisfyingTargetLovelaces,
5475
6109
  redeemCdp,
5476
6110
  redeemLrp,
5477
6111
  runCreateScriptRefTx,
@@ -5498,11 +6132,13 @@ export {
5498
6132
  serialiseStakingDatum,
5499
6133
  serialiseStakingRedeemer,
5500
6134
  setSumInEpochToScaleToSum,
6135
+ shuffle,
5501
6136
  spAdd,
5502
6137
  spDiv,
5503
6138
  spMul,
5504
6139
  spSub,
5505
6140
  startInterestOracle,
6141
+ summarizeActualLeverageRedemptions,
5506
6142
  toSystemParamsAsset,
5507
6143
  treasuryFeeTx,
5508
6144
  updatePoolSnapshotWithdrawalFee,