@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.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,45 +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
- var StakingRedeemerSchema = Data16.Enum([
2452
- Data16.Object({
2453
- CreateStakingPosition: Data16.Object({
2454
- creatorPkh: Data16.Bytes()
2475
+ var StakingParams = StakingParamsSchema;
2476
+ var StakingRedeemerSchema = Data17.Enum([
2477
+ Data17.Object({
2478
+ CreateStakingPosition: Data17.Object({
2479
+ creatorPkh: Data17.Bytes()
2455
2480
  })
2456
2481
  }),
2457
- Data16.Literal("UpdateTotalStake"),
2458
- Data16.Literal("Distribute"),
2459
- Data16.Object({
2460
- AdjustStakedAmount: Data16.Object({
2461
- adjustAmount: Data16.Integer()
2482
+ Data17.Literal("UpdateTotalStake"),
2483
+ Data17.Literal("Distribute"),
2484
+ Data17.Object({
2485
+ AdjustStakedAmount: Data17.Object({
2486
+ adjustAmount: Data17.Integer()
2462
2487
  })
2463
2488
  }),
2464
- Data16.Literal("Unstake"),
2465
- Data16.Literal("Lock"),
2466
- Data16.Literal("UpgradeVersion")
2489
+ Data17.Literal("Unstake"),
2490
+ Data17.Literal("Lock"),
2491
+ Data17.Literal("UpgradeVersion")
2467
2492
  ]);
2468
2493
  var StakingRedeemer = StakingRedeemerSchema;
2469
2494
  function serialiseStakingRedeemer(redeemer) {
2470
- return Data16.to(redeemer, StakingRedeemer);
2495
+ return Data17.to(redeemer, StakingRedeemer);
2496
+ }
2497
+ function castStakingParams(params) {
2498
+ return Data17.castTo(params, StakingParams);
2471
2499
  }
2472
2500
 
2473
2501
  // src/contracts/staking/types-new.ts
@@ -2543,7 +2571,7 @@ import {
2543
2571
  // src/contracts/staking/scripts.ts
2544
2572
  import {
2545
2573
  applyParamsToScript as applyParamsToScript4,
2546
- Constr as Constr2,
2574
+ Constr,
2547
2575
  fromText as fromText2
2548
2576
  } from "@lucid-evolution/lucid";
2549
2577
 
@@ -2559,24 +2587,24 @@ var mkStakingValidatorFromSP = (params) => {
2559
2587
  return {
2560
2588
  type: "PlutusV2",
2561
2589
  script: applyParamsToScript4(_stakingValidator.cborHex, [
2562
- new Constr2(0, [
2563
- new Constr2(0, [
2590
+ new Constr(0, [
2591
+ new Constr(0, [
2564
2592
  params.stakingManagerNFT[0].unCurrencySymbol,
2565
2593
  fromText2(params.stakingManagerNFT[1].unTokenName)
2566
2594
  ]),
2567
- new Constr2(0, [
2595
+ new Constr(0, [
2568
2596
  params.stakingToken[0].unCurrencySymbol,
2569
2597
  fromText2(params.stakingToken[1].unTokenName)
2570
2598
  ]),
2571
- new Constr2(0, [
2599
+ new Constr(0, [
2572
2600
  params.indyToken[0].unCurrencySymbol,
2573
2601
  fromText2(params.indyToken[1].unTokenName)
2574
2602
  ]),
2575
- new Constr2(0, [
2603
+ new Constr(0, [
2576
2604
  params.pollToken[0].unCurrencySymbol,
2577
2605
  fromText2(params.pollToken[1].unTokenName)
2578
2606
  ]),
2579
- new Constr2(0, [
2607
+ new Constr(0, [
2580
2608
  params.versionRecordToken[0].unCurrencySymbol,
2581
2609
  fromText2(params.versionRecordToken[1].unTokenName)
2582
2610
  ]),
@@ -2643,10 +2671,14 @@ function findStakingPositionByOutRef(stakingPositionRef, lucid) {
2643
2671
  return result;
2644
2672
  });
2645
2673
  }
2674
+ var rewardSnapshotPrecision = OCD_DECIMAL_UNIT * OCD_DECIMAL_UNIT;
2675
+ function distributeReward(snapshotAda, adaReward, totalStake) {
2676
+ return snapshotAda + adaReward * rewardSnapshotPrecision / totalStake;
2677
+ }
2646
2678
 
2647
2679
  // src/contracts/vesting/helpers.ts
2648
2680
  import { match as match10, P as P9 } from "ts-pattern";
2649
- import { array as A2 } from "fp-ts";
2681
+ import { array as A3 } from "fp-ts";
2650
2682
  var teamVestingSchedule = [
2651
2683
  {
2652
2684
  vestedAtTime: 1669067100000n,
@@ -2833,7 +2865,7 @@ var govDistributionSchedule = {
2833
2865
  ]
2834
2866
  };
2835
2867
  function calculateTotalVestedTeam(currentTime) {
2836
- return A2.reduce(0n, (acc, schedule) => {
2868
+ return A3.reduce(0n, (acc, schedule) => {
2837
2869
  if (currentTime >= schedule.vestedAtTime) {
2838
2870
  return acc + schedule.unlockAmt;
2839
2871
  } else {
@@ -2891,37 +2923,37 @@ function pollPassQuorum(initialIndyDist, pollStatus, currentTime, minQuorum, tre
2891
2923
  }
2892
2924
 
2893
2925
  // src/contracts/execute/types.ts
2894
- import { Data as Data17 } from "@lucid-evolution/lucid";
2926
+ import { Data as Data18 } from "@lucid-evolution/lucid";
2895
2927
  import { option as O5, function as F6 } from "fp-ts";
2896
- var ExecuteParamsSchema = Data17.Object({
2928
+ var ExecuteParamsSchema = Data18.Object({
2897
2929
  govNFT: AssetClassSchema,
2898
2930
  upgradeToken: AssetClassSchema,
2899
2931
  iAssetToken: AssetClassSchema,
2900
2932
  stabilityPoolToken: AssetClassSchema,
2901
2933
  versionRecordToken: AssetClassSchema,
2902
- cdpValHash: Data17.Bytes(),
2903
- sPoolValHash: Data17.Bytes(),
2904
- versionRegistryValHash: Data17.Bytes(),
2905
- treasuryValHash: Data17.Bytes(),
2934
+ cdpValHash: Data18.Bytes(),
2935
+ sPoolValHash: Data18.Bytes(),
2936
+ versionRegistryValHash: Data18.Bytes(),
2937
+ treasuryValHash: Data18.Bytes(),
2906
2938
  indyAsset: AssetClassSchema
2907
2939
  });
2908
2940
  var ExecuteParams = ExecuteParamsSchema;
2909
- var ExecuteDatumSchema = Data17.Object({
2910
- id: Data17.Integer(),
2941
+ var ExecuteDatumSchema = Data18.Object({
2942
+ id: Data18.Integer(),
2911
2943
  content: ProposalContentSchema,
2912
- passedTime: Data17.Integer(),
2913
- votingEndTime: Data17.Integer(),
2914
- protocolVersion: Data17.Integer(),
2944
+ passedTime: Data18.Integer(),
2945
+ votingEndTime: Data18.Integer(),
2946
+ protocolVersion: Data18.Integer(),
2915
2947
  /// Value proposed to be withdrawn from the treasury as part of the proposal.
2916
- treasuryWithdrawal: Data17.Nullable(TreasuryWithdrawalSchema)
2948
+ treasuryWithdrawal: Data18.Nullable(TreasuryWithdrawalSchema)
2917
2949
  });
2918
2950
  var ExecuteDatum = ExecuteDatumSchema;
2919
2951
  function serialiseExecuteDatum(d) {
2920
- return Data17.to(d, ExecuteDatum);
2952
+ return Data18.to(d, ExecuteDatum);
2921
2953
  }
2922
2954
  function parseExecuteDatum(d) {
2923
2955
  try {
2924
- return O5.some(Data17.from(d, ExecuteDatum));
2956
+ return O5.some(Data18.from(d, ExecuteDatum));
2925
2957
  } catch (_) {
2926
2958
  return O5.none;
2927
2959
  }
@@ -2935,16 +2967,16 @@ function parseExecuteDatumOrThrow(d) {
2935
2967
  );
2936
2968
  }
2937
2969
  function castExecuteParams(params) {
2938
- return Data17.castTo(params, ExecuteParams);
2970
+ return Data18.castTo(params, ExecuteParams);
2939
2971
  }
2940
2972
 
2941
2973
  // src/contracts/gov/helpers.ts
2942
2974
  import { pipe } from "fp-ts/lib/function";
2943
2975
  import {
2944
- array as A3,
2976
+ array as A4,
2945
2977
  option as O6,
2946
2978
  string as S,
2947
- ord as Ord,
2979
+ ord as Ord2,
2948
2980
  function as F7
2949
2981
  } from "fp-ts";
2950
2982
  import {
@@ -2955,7 +2987,7 @@ function proposalDeposit(baseDeposit, activeProposals) {
2955
2987
  return baseDeposit * 2n ** activeProposals;
2956
2988
  }
2957
2989
  function createValueFromWithdrawal(w) {
2958
- return A3.reduce(
2990
+ return A4.reduce(
2959
2991
  {},
2960
2992
  (acc, [cs, tk, amt]) => addAssets4(acc, mkAssetsOf({ currencySymbol: cs, tokenName: tk }, amt))
2961
2993
  )(w.value);
@@ -2974,20 +3006,20 @@ async function findRelativeIAssetForInsertion(newIAssetTokenName, allIAssetOrefs
2974
3006
  return pipe(
2975
3007
  // Sort the asset names
2976
3008
  iassetUtxos,
2977
- A3.sort(
2978
- Ord.contramap((x) => toText2(x.datum.assetName))(
3009
+ A4.sort(
3010
+ Ord2.contramap((x) => toText2(x.datum.assetName))(
2979
3011
  S.Ord
2980
3012
  )
2981
3013
  ),
2982
3014
  // split head and tail
2983
- A3.foldLeft(
3015
+ A4.foldLeft(
2984
3016
  () => O6.none,
2985
3017
  (head, rest) => O6.some([head, rest])
2986
3018
  ),
2987
3019
  // find the preceding iasset for the new token name
2988
3020
  O6.flatMap(
2989
3021
  ([firstIAsset, rest]) => O6.some(
2990
- A3.reduce(
3022
+ A4.reduce(
2991
3023
  firstIAsset,
2992
3024
  (acc, iasset) => toText2(iasset.datum.assetName) < newIAssetTokenName ? iasset : acc
2993
3025
  )(rest)
@@ -3127,7 +3159,7 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
3127
3159
  }).otherwise(() => {
3128
3160
  });
3129
3161
  return [
3130
- tx.mintAssets(pollNftValue, Data18.void()).readFrom([govRefScriptUtxo, pollAuthTokenPolicyRefScriptUtxo]).collectFrom(
3162
+ tx.mintAssets(pollNftValue, Data19.void()).readFrom([govRefScriptUtxo, pollAuthTokenPolicyRefScriptUtxo]).collectFrom(
3131
3163
  [govUtxo],
3132
3164
  serialiseGovRedeemer({
3133
3165
  CreatePoll: {
@@ -3225,7 +3257,7 @@ async function createShardsChunks(chunkSize, pollManagerOref, sysParams, current
3225
3257
  const pollNft = fromSystemParamsAsset(sysParams.govParams.pollToken);
3226
3258
  const tx = lucid.newTx().validFrom(Number(currentTime) - ONE_SECOND).validTo(
3227
3259
  Number(currentTime + sysParams.pollManagerParams.pBiasTime) - ONE_SECOND
3228
- ).mintAssets(mkAssetsOf(pollNft, shardsCount), Data18.void()).readFrom([pollAuthTokenPolicyRefScriptUtxo, pollManagerRefScriptUtxo]).collectFrom(
3260
+ ).mintAssets(mkAssetsOf(pollNft, shardsCount), Data19.void()).readFrom([pollAuthTokenPolicyRefScriptUtxo, pollManagerRefScriptUtxo]).collectFrom(
3229
3261
  [pollManagerUtxo],
3230
3262
  serialisePollManagerRedeemer({ CreateShards: { currentTime } })
3231
3263
  ).pay.ToContract(
@@ -3395,8 +3427,8 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3395
3427
  const shardUtxos = await lucid.utxosByOutRef(shardsOutRefs);
3396
3428
  const aggregatedStatus = F8.pipe(
3397
3429
  shardUtxos,
3398
- A4.map((utxo) => parsePollShardOrThrow(getInlineDatumOrThrow(utxo))),
3399
- A4.reduce(
3430
+ A5.map((utxo) => parsePollShardOrThrow(getInlineDatumOrThrow(utxo))),
3431
+ A5.reduce(
3400
3432
  pollManagerDatum.status,
3401
3433
  (acc, shard) => ({
3402
3434
  yesVotes: acc.yesVotes + shard.status.yesVotes,
@@ -3404,7 +3436,7 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3404
3436
  })
3405
3437
  )
3406
3438
  );
3407
- const shardsAggregatedAda = A4.reduce(
3439
+ const shardsAggregatedAda = A5.reduce(
3408
3440
  {},
3409
3441
  (acc, utxo) => addAssets5(acc, mkLovelacesOf(lovelacesAmt(utxo.assets)))
3410
3442
  )(shardUtxos);
@@ -3415,7 +3447,7 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
3415
3447
  pollShardRefScriptUtxo,
3416
3448
  pollManagerRefScriptUtxo,
3417
3449
  pollAuthTokenPolicyRefScriptUtxo
3418
- ]).mintAssets(mkAssetsOf(pollNft, -BigInt(shardsOutRefs.length)), Data18.void()).collectFrom(
3450
+ ]).mintAssets(mkAssetsOf(pollNft, -BigInt(shardsOutRefs.length)), Data19.void()).collectFrom(
3419
3451
  [pollManagerUtxo],
3420
3452
  serialisePollManagerRedeemer({
3421
3453
  MergeShardsManager: { currentTime }
@@ -3525,7 +3557,7 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3525
3557
  ).collectFrom(
3526
3558
  [govUtxo],
3527
3559
  serialiseGovRedeemer({ WitnessEndPoll: { currentTime } })
3528
- ).mintAssets(mkAssetsOf(pollNft, -1n), Data18.void()).pay.ToContract(
3560
+ ).mintAssets(mkAssetsOf(pollNft, -1n), Data19.void()).pay.ToContract(
3529
3561
  govUtxo.address,
3530
3562
  {
3531
3563
  kind: "inline",
@@ -3551,11 +3583,11 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
3551
3583
  })
3552
3584
  },
3553
3585
  upgradeTokenVal
3554
- ).mintAssets(upgradeTokenVal, Data18.void());
3586
+ ).mintAssets(upgradeTokenVal, Data19.void());
3555
3587
  } else {
3556
3588
  tx.pay.ToContract(
3557
3589
  createScriptAddress(network, sysParams.validatorHashes.treasuryHash),
3558
- { kind: "inline", value: Data18.void() },
3590
+ { kind: "inline", value: Data19.void() },
3559
3591
  mkAssetsOf(
3560
3592
  indyAsset,
3561
3593
  assetClassValueOf(pollManagerUtxo.assets, indyAsset)
@@ -3650,7 +3682,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3650
3682
  sysParams.treasuryParams.treasuryUtxosStakeCredential
3651
3683
  ) : void 0
3652
3684
  ),
3653
- { kind: "inline", value: Data18.void() },
3685
+ { kind: "inline", value: Data19.void() },
3654
3686
  withdrawalChangeVal
3655
3687
  );
3656
3688
  }
@@ -3727,7 +3759,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3727
3759
  cdpRefScriptUtxo,
3728
3760
  iassetTokenPolicyRefScriptUtxo,
3729
3761
  stabilityPoolTokenPolicyRefScriptUtxo
3730
- ]).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(
3731
3763
  govUtxo.address,
3732
3764
  {
3733
3765
  kind: "inline",
@@ -3893,7 +3925,7 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3893
3925
  fromSystemParamsAsset(sysParams.executeParams.versionRecordToken),
3894
3926
  1n
3895
3927
  );
3896
- tx.readFrom([govRefScriptUtxo, versionRecordTokenPolicyRefScriptUtxo]).mintAssets(versionRecordNftVal, Data18.void()).pay.ToContract(
3928
+ tx.readFrom([govRefScriptUtxo, versionRecordTokenPolicyRefScriptUtxo]).mintAssets(versionRecordNftVal, Data19.void()).pay.ToContract(
3897
3929
  createScriptAddress(
3898
3930
  network,
3899
3931
  sysParams.validatorHashes.versionRegistryHash
@@ -3921,56 +3953,56 @@ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, all
3921
3953
  govUtxo.assets
3922
3954
  );
3923
3955
  }).exhaustive();
3924
- 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(
3925
3957
  mkAssetsOf(fromSystemParamsAsset(sysParams.govParams.upgradeToken), -1n),
3926
- Data18.void()
3958
+ Data19.void()
3927
3959
  ).addSigner(ownAddr);
3928
3960
  return tx;
3929
3961
  }
3930
3962
 
3931
3963
  // src/contracts/stability-pool/transactions.ts
3932
3964
  import {
3933
- Constr as Constr3,
3965
+ Constr as Constr2,
3934
3966
  fromText as fromText5,
3935
3967
  validatorToScriptHash as validatorToScriptHash2,
3936
- Data as Data20,
3968
+ Data as Data21,
3937
3969
  credentialToAddress as credentialToAddress3,
3938
3970
  fromHex as fromHex2,
3939
3971
  toHex
3940
3972
  } from "@lucid-evolution/lucid";
3941
3973
 
3942
3974
  // src/contracts/stability-pool/types.ts
3943
- import { Data as Data19 } from "@lucid-evolution/lucid";
3944
- var ActionReturnDatumSchema = Data19.Enum([
3945
- Data19.Object({
3946
- IndigoStabilityPoolAccountAdjustment: Data19.Object({
3975
+ import { Data as Data20 } from "@lucid-evolution/lucid";
3976
+ var ActionReturnDatumSchema = Data20.Enum([
3977
+ Data20.Object({
3978
+ IndigoStabilityPoolAccountAdjustment: Data20.Object({
3947
3979
  spent_account: OutputReferenceSchema
3948
3980
  })
3949
3981
  }),
3950
- Data19.Object({
3951
- IndigoStabilityPoolAccountClosure: Data19.Object({
3982
+ Data20.Object({
3983
+ IndigoStabilityPoolAccountClosure: Data20.Object({
3952
3984
  closed_account: OutputReferenceSchema
3953
3985
  })
3954
3986
  })
3955
3987
  ]);
3956
3988
  var ActionReturnDatum = ActionReturnDatumSchema;
3957
- var StabilityPoolParamsSchema = Data19.Object({
3958
- assetSymbol: Data19.Bytes(),
3989
+ var StabilityPoolParamsSchema = Data20.Object({
3990
+ assetSymbol: Data20.Bytes(),
3959
3991
  stabilityPoolToken: AssetClassSchema,
3960
3992
  snapshotEpochToScaleToSumToken: AssetClassSchema,
3961
3993
  accountToken: AssetClassSchema,
3962
3994
  cdpToken: AssetClassSchema,
3963
3995
  iAssetAuthToken: AssetClassSchema,
3964
3996
  versionRecordToken: AssetClassSchema,
3965
- collectorValHash: Data19.Bytes(),
3997
+ collectorValHash: Data20.Bytes(),
3966
3998
  govNFT: AssetClassSchema,
3967
- accountCreateFeeLovelaces: Data19.Integer(),
3968
- accountAdjustmentFeeLovelaces: Data19.Integer(),
3969
- requestCollateralLovelaces: Data19.Integer()
3999
+ accountCreateFeeLovelaces: Data20.Integer(),
4000
+ accountAdjustmentFeeLovelaces: Data20.Integer(),
4001
+ requestCollateralLovelaces: Data20.Integer()
3970
4002
  });
3971
4003
  var StabilityPoolParams = StabilityPoolParamsSchema;
3972
4004
  function castStabilityPoolParams(params) {
3973
- return Data19.castTo(params, StabilityPoolParams);
4005
+ return Data20.castTo(params, StabilityPoolParams);
3974
4006
  }
3975
4007
 
3976
4008
  // src/contracts/stability-pool/scripts.ts
@@ -4011,7 +4043,10 @@ var mkStabilityPoolValidatorFromSP = (params) => {
4011
4043
  };
4012
4044
 
4013
4045
  // src/contracts/stability-pool/transactions.ts
4014
- import { addressFromBech32 as addressFromBech322, addressToBech32 as addressToBech322 } from "@3rd-eye-labs/cardano-offchain-common";
4046
+ import {
4047
+ addressFromBech32 as addressFromBech322,
4048
+ addressToBech32 as addressToBech322
4049
+ } from "@3rd-eye-labs/cardano-offchain-common";
4015
4050
  async function createSpAccount(asset, amount, params, lucid) {
4016
4051
  const [pkh, _skh] = await addrDetails(lucid);
4017
4052
  const minLovelaces = BigInt(
@@ -4210,7 +4245,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4210
4245
  {
4211
4246
  [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + fromText5(params.stabilityPoolParams.accountToken[1].unTokenName)]: 1n
4212
4247
  },
4213
- Data20.to(new Constr3(0, []))
4248
+ Data21.to(new Constr2(0, []))
4214
4249
  );
4215
4250
  tx.pay.ToContract(
4216
4251
  stabilityPoolUtxo.address,
@@ -4321,12 +4356,14 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4321
4356
  stabilityPoolDatum.poolSnapshot.scale,
4322
4357
  newPoolSum
4323
4358
  );
4324
- console.log("balanceChange", balanceChange);
4325
- console.log("withdrawalFee", withdrawalFee);
4326
- console.log("rewardLovelacesFee", rewardLovelacesFee);
4327
- console.log("reward", reward);
4328
4359
  if (rewardLovelacesFee > 0n) {
4329
- await collectorFeeTx(rewardLovelacesFee, lucid, params, tx, collectorOref);
4360
+ await collectorFeeTx(
4361
+ rewardLovelacesFee,
4362
+ lucid,
4363
+ params,
4364
+ tx,
4365
+ collectorOref
4366
+ );
4330
4367
  }
4331
4368
  tx.readFrom([govUtxo, iAssetUtxo, ...refInputs]);
4332
4369
  tx.pay.ToContract(
@@ -4369,7 +4406,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4369
4406
  outputAddress,
4370
4407
  {
4371
4408
  kind: "inline",
4372
- value: Data20.to(
4409
+ value: Data21.to(
4373
4410
  {
4374
4411
  IndigoStabilityPoolAccountAdjustment: {
4375
4412
  spent_account: {
@@ -4443,7 +4480,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4443
4480
  {
4444
4481
  [params.stabilityPoolParams.accountToken[0].unCurrencySymbol + fromText5(params.stabilityPoolParams.accountToken[1].unTokenName)]: -1n
4445
4482
  },
4446
- Data20.to(new Constr3(0, []))
4483
+ Data21.to(new Constr2(0, []))
4447
4484
  );
4448
4485
  const assetOutputAmountForSP = stabilityPoolUtxo.assets[params.stabilityPoolParams.assetSymbol.unCurrencySymbol + fromText5(asset)] - fromSPInteger(withdrawnAmt) - withdrawalFeeAmount;
4449
4486
  tx.pay.ToContract(
@@ -4470,7 +4507,7 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4470
4507
  outputAddress,
4471
4508
  {
4472
4509
  kind: "inline",
4473
- value: Data20.to(
4510
+ value: Data21.to(
4474
4511
  {
4475
4512
  IndigoStabilityPoolAccountClosure: {
4476
4513
  closed_account: {
@@ -4494,8 +4531,9 @@ async function processSpRequest(asset, stabilityPoolUtxo, accountUtxo, govUtxo,
4494
4531
 
4495
4532
  // src/contracts/staking/transactions.ts
4496
4533
  import {
4497
- Constr as Constr4,
4498
- Data as Data21,
4534
+ addAssets as addAssets6,
4535
+ Constr as Constr3,
4536
+ Data as Data22,
4499
4537
  fromHex as fromHex3,
4500
4538
  fromText as fromText6,
4501
4539
  toHex as toHex2
@@ -4532,7 +4570,7 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4532
4570
  };
4533
4571
  const stakingToken = params.stakingParams.stakingToken[0].unCurrencySymbol + fromText6(params.stakingParams.stakingToken[1].unTokenName);
4534
4572
  const indyToken = params.stakingParams.indyToken[0].unCurrencySymbol + fromText6(params.stakingParams.indyToken[1].unTokenName);
4535
- 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(
4536
4574
  stakingManagerOut.utxo.address,
4537
4575
  {
4538
4576
  kind: "inline",
@@ -4543,7 +4581,7 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
4543
4581
  {
4544
4582
  [stakingToken]: 1n
4545
4583
  },
4546
- Data21.void()
4584
+ Data22.void()
4547
4585
  ).pay.ToContract(
4548
4586
  stakingManagerOut.utxo.address,
4549
4587
  {
@@ -4575,12 +4613,20 @@ async function adjustStakingPosition(stakingPositionRef, amount, params, lucid,
4575
4613
  const existingIndyAmount = stakingPositionOut.utxo.assets[indyToken] ?? 0n;
4576
4614
  const currentSnapshotAda = stakingManagerOut.datum.managerSnapshot.snapshotAda;
4577
4615
  const oldSnapshotAda = stakingPositionOut.datum.positionSnapshot.snapshotAda;
4578
- const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / (1000000n * 1000000n);
4616
+ const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / rewardSnapshotPrecision;
4579
4617
  const newLockedAmount = updateStakingLockedAmount(
4580
4618
  stakingPositionOut.datum.lockedAmount,
4581
4619
  BigInt(now)
4582
4620
  );
4583
- 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(
4584
4630
  stakingManagerOut.utxo.address,
4585
4631
  {
4586
4632
  kind: "inline",
@@ -4635,7 +4681,7 @@ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingMa
4635
4681
  const currentSnapshotAda = stakingManagerOut.datum.managerSnapshot.snapshotAda;
4636
4682
  const oldSnapshotAda = stakingPositionOut.datum.positionSnapshot.snapshotAda;
4637
4683
  const adaReward = (currentSnapshotAda - oldSnapshotAda) * existingIndyAmount / (1000000n * 1000000n);
4638
- 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(
4639
4685
  stakingManagerOut.utxo.address,
4640
4686
  {
4641
4687
  kind: "inline",
@@ -4652,9 +4698,63 @@ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingMa
4652
4698
  {
4653
4699
  [stakingToken]: -1n
4654
4700
  },
4655
- Data21.void()
4701
+ Data22.void()
4656
4702
  ).addSignerKey(toHex2(stakingPositionOut.datum.owner));
4657
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
+ }
4658
4758
 
4659
4759
  // src/contracts/interest-oracle/transactions.ts
4660
4760
  import {
@@ -4665,9 +4765,9 @@ import {
4665
4765
 
4666
4766
  // src/contracts/one-shot/transactions.ts
4667
4767
  import {
4668
- addAssets as addAssets6,
4669
- Constr as Constr5,
4670
- Data as Data23,
4768
+ addAssets as addAssets7,
4769
+ Constr as Constr4,
4770
+ Data as Data24,
4671
4771
  mintingPolicyToId,
4672
4772
  toUnit as toUnit2
4673
4773
  } from "@lucid-evolution/lucid";
@@ -4678,23 +4778,23 @@ import {
4678
4778
  } from "@lucid-evolution/lucid";
4679
4779
 
4680
4780
  // src/contracts/one-shot/types.ts
4681
- import { Data as Data22 } from "@lucid-evolution/lucid";
4682
- var OneShotParamsSchema = Data22.Object({
4683
- referenceOutRef: Data22.Object({
4684
- txHash: Data22.Bytes(),
4685
- 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()
4686
4786
  }),
4687
- mintAmounts: Data22.Array(
4688
- Data22.Object({
4787
+ mintAmounts: Data23.Array(
4788
+ Data23.Object({
4689
4789
  /// Use hex encoded string
4690
- tokenName: Data22.Bytes(),
4691
- amount: Data22.Integer()
4790
+ tokenName: Data23.Bytes(),
4791
+ amount: Data23.Integer()
4692
4792
  })
4693
4793
  )
4694
4794
  });
4695
4795
  var OneShotParams = OneShotParamsSchema;
4696
4796
  function castOneShotParams(params) {
4697
- return Data22.castTo(params, OneShotParams);
4797
+ return Data23.castTo(params, OneShotParams);
4698
4798
  }
4699
4799
 
4700
4800
  // src/contracts/one-shot/scripts.ts
@@ -4731,11 +4831,11 @@ async function oneShotMintTx(lucid, params) {
4731
4831
  lucid.newTx().collectFrom([refUtxo]).mintAssets(
4732
4832
  reduce(
4733
4833
  {},
4734
- (acc, entry) => addAssets6(acc, {
4834
+ (acc, entry) => addAssets7(acc, {
4735
4835
  [toUnit2(policyId, entry.tokenName)]: entry.amount
4736
4836
  })
4737
4837
  )(params.mintAmounts),
4738
- Data23.to(new Constr5(0, []))
4838
+ Data24.to(new Constr4(0, []))
4739
4839
  ).attach.MintingPolicy(oneShotPolicy),
4740
4840
  policyId
4741
4841
  ];
@@ -4869,13 +4969,13 @@ async function feedInterestOracle(params, newInterestRate, lucid, assetClass, ut
4869
4969
  }
4870
4970
 
4871
4971
  // src/contracts/version-registry/types.ts
4872
- import { Data as Data24 } from "@lucid-evolution/lucid";
4873
- var VersionRecordTokenParamsSchema = Data24.Object({
4972
+ import { Data as Data25 } from "@lucid-evolution/lucid";
4973
+ var VersionRecordTokenParamsSchema = Data25.Object({
4874
4974
  upgradeToken: AssetClassSchema
4875
4975
  });
4876
4976
  var VersionRecordTokenParams = VersionRecordTokenParamsSchema;
4877
4977
  function castVersionRecordTokenParams(params) {
4878
- return Data24.castTo(params, VersionRecordTokenParams);
4978
+ return Data25.castTo(params, VersionRecordTokenParams);
4879
4979
  }
4880
4980
 
4881
4981
  // src/contracts/version-registry/scripts.ts
@@ -4916,7 +5016,7 @@ var mkVersionRegistryValidator = () => {
4916
5016
  // src/contracts/collector/scripts.ts
4917
5017
  import {
4918
5018
  applyParamsToScript as applyParamsToScript9,
4919
- Constr as Constr6,
5019
+ Constr as Constr5,
4920
5020
  fromText as fromText8
4921
5021
  } from "@lucid-evolution/lucid";
4922
5022
 
@@ -4932,16 +5032,16 @@ var mkCollectorValidatorFromSP = (params) => {
4932
5032
  return {
4933
5033
  type: "PlutusV2",
4934
5034
  script: applyParamsToScript9(_collectorValidator.cborHex, [
4935
- new Constr6(0, [
4936
- new Constr6(0, [
5035
+ new Constr5(0, [
5036
+ new Constr5(0, [
4937
5037
  params.stakingManagerNFT[0].unCurrencySymbol,
4938
5038
  fromText8(params.stakingManagerNFT[1].unTokenName)
4939
5039
  ]),
4940
- new Constr6(0, [
5040
+ new Constr5(0, [
4941
5041
  params.stakingToken[0].unCurrencySymbol,
4942
5042
  fromText8(params.stakingToken[1].unTokenName)
4943
5043
  ]),
4944
- new Constr6(0, [
5044
+ new Constr5(0, [
4945
5045
  params.versionRecordToken[0].unCurrencySymbol,
4946
5046
  fromText8(params.versionRecordToken[1].unTokenName)
4947
5047
  ])
@@ -4953,7 +5053,7 @@ var mkCollectorValidatorFromSP = (params) => {
4953
5053
  // src/contracts/treasury/scripts.ts
4954
5054
  import {
4955
5055
  applyParamsToScript as applyParamsToScript10,
4956
- Constr as Constr7,
5056
+ Constr as Constr6,
4957
5057
  fromText as fromText9
4958
5058
  } from "@lucid-evolution/lucid";
4959
5059
 
@@ -4969,22 +5069,22 @@ var mkTreasuryValidatorFromSP = (params) => {
4969
5069
  return {
4970
5070
  type: "PlutusV2",
4971
5071
  script: applyParamsToScript10(_treasuryValidator.cborHex, [
4972
- new Constr7(0, [
4973
- new Constr7(0, [
5072
+ new Constr6(0, [
5073
+ new Constr6(0, [
4974
5074
  params.upgradeToken[0].unCurrencySymbol,
4975
5075
  fromText9(params.upgradeToken[1].unTokenName)
4976
5076
  ]),
4977
- new Constr7(0, [
5077
+ new Constr6(0, [
4978
5078
  params.versionRecordToken[0].unCurrencySymbol,
4979
5079
  fromText9(params.versionRecordToken[1].unTokenName)
4980
5080
  ]),
4981
- params.treasuryUtxosStakeCredential ? new Constr7(0, [
4982
- new Constr7(0, [
4983
- new Constr7(1, [
5081
+ params.treasuryUtxosStakeCredential ? new Constr6(0, [
5082
+ new Constr6(0, [
5083
+ new Constr6(1, [
4984
5084
  params.treasuryUtxosStakeCredential.contents.contents
4985
5085
  ])
4986
5086
  ])
4987
- ]) : new Constr7(1, [])
5087
+ ]) : new Constr6(1, [])
4988
5088
  ])
4989
5089
  ])
4990
5090
  };
@@ -5036,66 +5136,280 @@ var mkExecuteValidatorFromSP = (params) => {
5036
5136
  };
5037
5137
  };
5038
5138
 
5139
+ // src/contracts/lrp/helpers.ts
5140
+ import { addAssets as addAssets8 } from "@lucid-evolution/lucid";
5141
+
5039
5142
  // src/contracts/lrp/types.ts
5040
- import { Data as Data25 } from "@lucid-evolution/lucid";
5041
- 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({
5042
5146
  versionRecordToken: AssetClassSchema,
5043
5147
  iassetNft: AssetClassSchema,
5044
- iassetPolicyId: Data25.Bytes(),
5045
- minRedemptionLovelacesAmt: Data25.Integer()
5148
+ iassetPolicyId: Data26.Bytes(),
5149
+ minRedemptionLovelacesAmt: Data26.Integer()
5046
5150
  });
5047
5151
  var LRPParams = LRPParamsSchema;
5048
- var LRPDatumSchema = Data25.Object({
5049
- owner: Data25.Bytes(),
5050
- iasset: Data25.Bytes(),
5152
+ var LRPDatumSchema = Data26.Object({
5153
+ owner: Data26.Bytes(),
5154
+ iasset: Data26.Bytes(),
5051
5155
  maxPrice: OnChainDecimalSchema,
5052
5156
  /**
5053
5157
  * The amount of lovelaces that is available to be spent.
5054
5158
  * This doesn't correspond to the lovelaces in UTXO's value,
5055
5159
  * since that can contain fees, too.
5056
5160
  */
5057
- lovelacesToSpend: Data25.Integer()
5161
+ lovelacesToSpend: Data26.Integer()
5058
5162
  });
5059
5163
  var LRPDatum = LRPDatumSchema;
5060
- var LRPRedeemerSchema = Data25.Enum([
5061
- Data25.Object({ Redeem: Data25.Object({ continuingOutputIdx: Data25.Integer() }) }),
5062
- Data25.Object({
5063
- RedeemAuxiliary: Data25.Object({
5064
- 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(),
5065
5169
  mainRedeemOutRef: OutputReferenceSchema,
5066
- asset: Data25.Bytes(),
5170
+ asset: Data26.Bytes(),
5067
5171
  assetPrice: OnChainDecimalSchema,
5068
5172
  redemptionReimbursementPercentage: OnChainDecimalSchema
5069
5173
  })
5070
5174
  }),
5071
- Data25.Literal("Cancel"),
5072
- Data25.Literal("UpgradeVersion")
5175
+ Data26.Literal("Cancel"),
5176
+ Data26.Literal("UpgradeVersion")
5073
5177
  ]);
5074
5178
  var LRPRedeemer = LRPRedeemerSchema;
5075
5179
  function parseLrpDatum(datum) {
5076
- 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
+ );
5077
5193
  }
5078
5194
  function serialiseLrpDatum(datum) {
5079
- return Data25.to(datum, LRPDatum);
5195
+ return Data26.to(datum, LRPDatum);
5080
5196
  }
5081
5197
  function serialiseLrpRedeemer(redeemer) {
5082
- return Data25.to(redeemer, LRPRedeemer);
5198
+ return Data26.to(redeemer, LRPRedeemer);
5083
5199
  }
5084
5200
  function castLrpParams(params) {
5085
- 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;
5086
5402
  }
5087
5403
 
5088
5404
  // src/contracts/lrp/transactions.ts
5089
5405
  import {
5090
- addAssets as addAssets7,
5406
+ addAssets as addAssets9,
5091
5407
  unixTimeToSlot as unixTimeToSlot2,
5092
5408
  slotToUnixTime as slotToUnixTime5
5093
5409
  } from "@lucid-evolution/lucid";
5094
- import { match as match12, P as P11 } from "ts-pattern";
5095
5410
  import { unzip, zip } from "fp-ts/lib/Array";
5096
- import { reduceWithIndex } from "fp-ts/lib/Array";
5097
- var MIN_UTXO_COLLATERAL_AMT = 2000000n;
5098
- 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;
5099
5413
  const [ownPkh, _] = await addrDetails(lucid);
5100
5414
  const newDatum = {
5101
5415
  owner: ownPkh.hash,
@@ -5104,38 +5418,47 @@ async function openLrp(assetTokenName, lovelacesAmt2, maxPrice, lucid, lrpScript
5104
5418
  lovelacesToSpend: lovelacesAmt2
5105
5419
  };
5106
5420
  return lucid.newTx().pay.ToContract(
5107
- createScriptAddress(network, lrpScriptHash, lrpStakeCredential),
5421
+ createScriptAddress(
5422
+ network,
5423
+ sysParams.validatorHashes.lrpHash,
5424
+ lrpStakeCredential
5425
+ ),
5108
5426
  {
5109
5427
  kind: "inline",
5110
5428
  value: serialiseLrpDatum(newDatum)
5111
5429
  },
5112
- { lovelace: lovelacesAmt2 + MIN_UTXO_COLLATERAL_AMT }
5430
+ { lovelace: lovelacesAmt2 + MIN_LRP_COLLATERAL_AMT }
5113
5431
  );
5114
5432
  }
5115
- async function cancelLrp(lrpOutRef, lrpRefScriptOutRef, lucid) {
5433
+ async function cancelLrp(lrpOutRef, sysParams, lucid) {
5116
5434
  const lrpScriptRefUtxo = matchSingle(
5117
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5435
+ await lucid.utxosByOutRef([
5436
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5437
+ ]),
5118
5438
  (_) => new Error("Expected a single LRP Ref Script UTXO")
5119
5439
  );
5120
5440
  const lrpUtxo = matchSingle(
5121
5441
  await lucid.utxosByOutRef([lrpOutRef]),
5122
5442
  (_) => new Error("Expected a single LRP UTXO.")
5123
5443
  );
5124
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5444
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5125
5445
  return lucid.newTx().readFrom([lrpScriptRefUtxo]).collectFrom([lrpUtxo], serialiseLrpRedeemer("Cancel")).addSignerKey(lrpDatum.owner);
5126
5446
  }
5127
- 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;
5128
5449
  const lrpScriptRefUtxo = matchSingle(
5129
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5130
- (_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")
5131
5454
  );
5132
5455
  const priceOracleUtxo = matchSingle(
5133
5456
  await lucid.utxosByOutRef([priceOracleOutRef]),
5134
- (_2) => new Error("Expected a single price oracle UTXO")
5457
+ (_) => new Error("Expected a single price oracle UTXO")
5135
5458
  );
5136
5459
  const iassetUtxo = matchSingle(
5137
5460
  await lucid.utxosByOutRef([iassetOutRef]),
5138
- (_2) => new Error("Expected a single IAsset UTXO")
5461
+ (_) => new Error("Expected a single IAsset UTXO")
5139
5462
  );
5140
5463
  const iassetDatum = parseIAssetDatumOrThrow(
5141
5464
  getInlineDatumOrThrow(iassetUtxo)
@@ -5145,69 +5468,14 @@ async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutR
5145
5468
  getInlineDatumOrThrow(priceOracleUtxo)
5146
5469
  );
5147
5470
  const redemptionLrps = await lucid.utxosByOutRef(lrpsToRedeemOutRefs).then((val) => zip(val, lrpRedemptionIAssetAmt));
5148
- const [[mainLrpUtxo, _], __] = match12(redemptionLrps).with(
5149
- [P11._, ...P11.array()],
5150
- ([[firstLrp, _2], ...rest]) => [
5151
- [firstLrp, _2],
5152
- rest
5153
- ]
5154
- ).otherwise(() => {
5155
- throw new Error("Expects at least 1 UTXO to redeem.");
5156
- });
5157
- const mainLrpDatum = parseLrpDatum(getInlineDatumOrThrow(mainLrpUtxo));
5158
- const tx = reduceWithIndex(
5471
+ const tx = buildRedemptionsTx(
5472
+ redemptionLrps,
5473
+ priceOracleDatum.price,
5474
+ iassetDatum.redemptionReimbursementPercentage,
5475
+ sysParams,
5159
5476
  lucid.newTx(),
5160
- (idx, acc, [lrpUtxo, redeemIAssetAmt]) => {
5161
- const lovelacesForRedemption = ocdMul(
5162
- {
5163
- getOnChainInt: redeemIAssetAmt
5164
- },
5165
- priceOracleDatum.price
5166
- ).getOnChainInt;
5167
- const reimburstmentLovelaces = calculateFeeFromPercentage(
5168
- iassetDatum.redemptionReimbursementPercentage,
5169
- lovelacesForRedemption
5170
- );
5171
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5172
- return acc.collectFrom(
5173
- [lrpUtxo],
5174
- serialiseLrpRedeemer(
5175
- idx === 0 ? { Redeem: { continuingOutputIdx: 0n } } : {
5176
- RedeemAuxiliary: {
5177
- continuingOutputIdx: BigInt(idx),
5178
- mainRedeemOutRef: {
5179
- txHash: { hash: mainLrpUtxo.txHash },
5180
- outputIndex: BigInt(mainLrpUtxo.outputIndex)
5181
- },
5182
- asset: mainLrpDatum.iasset,
5183
- assetPrice: priceOracleDatum.price,
5184
- redemptionReimbursementPercentage: iassetDatum.redemptionReimbursementPercentage
5185
- }
5186
- }
5187
- )
5188
- ).pay.ToContract(
5189
- lrpUtxo.address,
5190
- {
5191
- kind: "inline",
5192
- value: serialiseLrpDatum({
5193
- ...lrpDatum,
5194
- lovelacesToSpend: lrpDatum.lovelacesToSpend - lovelacesForRedemption
5195
- })
5196
- },
5197
- addAssets7(
5198
- lrpUtxo.assets,
5199
- mkLovelacesOf(-lovelacesForRedemption + reimburstmentLovelaces),
5200
- mkAssetsOf(
5201
- {
5202
- currencySymbol: lrpParams.iassetPolicyId,
5203
- tokenName: mainLrpDatum.iasset
5204
- },
5205
- redeemIAssetAmt
5206
- )
5207
- )
5208
- );
5209
- }
5210
- )(redemptionLrps);
5477
+ 0n
5478
+ );
5211
5479
  return lucid.newTx().validTo(
5212
5480
  slotToUnixTime5(
5213
5481
  network,
@@ -5215,18 +5483,20 @@ async function redeemLrp(redemptionLrpsData, lrpRefScriptOutRef, priceOracleOutR
5215
5483
  )
5216
5484
  ).readFrom([lrpScriptRefUtxo]).readFrom([iassetUtxo, priceOracleUtxo]).compose(tx);
5217
5485
  }
5218
- async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, lrpRefScriptOutRef, lrpParams) {
5486
+ async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, sysParams) {
5219
5487
  const lrpScriptRefUtxo = matchSingle(
5220
- await lucid.utxosByOutRef([lrpRefScriptOutRef]),
5488
+ await lucid.utxosByOutRef([
5489
+ fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef)
5490
+ ]),
5221
5491
  (_) => new Error("Expected a single LRP Ref Script UTXO")
5222
5492
  );
5223
5493
  const lrpUtxo = matchSingle(
5224
5494
  await lucid.utxosByOutRef([lrpOutRef]),
5225
5495
  (_) => new Error("Expected a single LRP UTXO.")
5226
5496
  );
5227
- const lrpDatum = parseLrpDatum(getInlineDatumOrThrow(lrpUtxo));
5497
+ const lrpDatum = parseLrpDatumOrThrow(getInlineDatumOrThrow(lrpUtxo));
5228
5498
  const rewardAssetClass = {
5229
- currencySymbol: lrpParams.iassetPolicyId,
5499
+ currencySymbol: sysParams.lrpParams.iassetPolicyId.unCurrencySymbol,
5230
5500
  tokenName: lrpDatum.iasset
5231
5501
  };
5232
5502
  const rewardAssetsAmt = assetClassValueOf(lrpUtxo.assets, rewardAssetClass);
@@ -5249,15 +5519,15 @@ async function adjustLrp(lucid, lrpOutRef, lovelacesAdjustAmt, lrpRefScriptOutRe
5249
5519
  lovelacesToSpend: lrpDatum.lovelacesToSpend + lovelacesAdjustAmt
5250
5520
  })
5251
5521
  },
5252
- addAssets7(
5522
+ addAssets9(
5253
5523
  lrpUtxo.assets,
5254
5524
  mkAssetsOf(rewardAssetClass, -rewardAssetsAmt),
5255
5525
  mkLovelacesOf(lovelacesAdjustAmt)
5256
5526
  )
5257
5527
  ).addSignerKey(lrpDatum.owner);
5258
5528
  }
5259
- async function claimLrp(lucid, lrpOutRef, lrpRefScriptOutRef, lrpParams) {
5260
- return adjustLrp(lucid, lrpOutRef, 0n, lrpRefScriptOutRef, lrpParams);
5529
+ async function claimLrp(lucid, lrpOutRef, sysParams) {
5530
+ return adjustLrp(lucid, lrpOutRef, 0n, sysParams);
5261
5531
  }
5262
5532
 
5263
5533
  // src/contracts/lrp/scripts.ts
@@ -5309,6 +5579,366 @@ async function runCreateScriptRefTx(lucid, scriptRefValidator, network) {
5309
5579
  await lucid.awaitTx(txHash);
5310
5580
  return { txHash, outputIndex: 0 };
5311
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
+ }
5312
5942
  export {
5313
5943
  AccountContentSchema,
5314
5944
  ActionReturnDatum,
@@ -5336,6 +5966,8 @@ export {
5336
5966
  LRPDatumSchema,
5337
5967
  LRPParamsSchema,
5338
5968
  LRPRedeemerSchema,
5969
+ MAX_REDEMPTIONS_WITH_CDP_OPEN,
5970
+ MIN_LRP_COLLATERAL_AMT,
5339
5971
  ONE_DAY,
5340
5972
  ONE_HOUR,
5341
5973
  ONE_SECOND,
@@ -5366,12 +5998,17 @@ export {
5366
5998
  adjustSpAccount,
5367
5999
  adjustStakingPosition,
5368
6000
  adjustmentHelper,
6001
+ approximateLeverageRedemptions,
5369
6002
  assetClassToUnit,
5370
6003
  assetClassValueOf,
5371
6004
  balance,
6005
+ buildRedemptionsTx,
5372
6006
  burnCdp,
6007
+ calculateCollateralRatioFromLeverage,
5373
6008
  calculateIAssetRedemptionAmt,
6009
+ calculateLeverageFromCollateralRatio,
5374
6010
  calculateMinCollateralCappedIAssetRedemptionAmt,
6011
+ calculateTotalAdaForRedemption,
5375
6012
  cancelLrp,
5376
6013
  castCDPCreatorParams,
5377
6014
  castCdpParams,
@@ -5383,6 +6020,7 @@ export {
5383
6020
  castPollShardParams,
5384
6021
  castPriceOracleParams,
5385
6022
  castStabilityPoolParams,
6023
+ castStakingParams,
5386
6024
  castVersionRecordTokenParams,
5387
6025
  cdpCollateralRatioPercentage,
5388
6026
  claimLrp,
@@ -5395,6 +6033,7 @@ export {
5395
6033
  createShardsChunks,
5396
6034
  createSpAccount,
5397
6035
  depositCdp,
6036
+ distributeAda,
5398
6037
  endProposal,
5399
6038
  executeProposal,
5400
6039
  feedInterestOracle,
@@ -5410,12 +6049,15 @@ export {
5410
6049
  getSumFromEpochToScaleToSum,
5411
6050
  initEpochToScaleToSumMap,
5412
6051
  initSpSnapshot,
6052
+ insertSorted,
5413
6053
  isAssetsZero,
6054
+ leverageCdpWithLrp,
5414
6055
  liquidateCdp,
5415
6056
  liquidationHelper,
5416
6057
  loadSystemParamsFromFile,
5417
6058
  loadSystemParamsFromUrl,
5418
6059
  lovelacesAmt,
6060
+ lrpRedeemableLovelacesInclReimb,
5419
6061
  matchSingle,
5420
6062
  mergeCdps,
5421
6063
  mergeShards,
@@ -5455,10 +6097,15 @@ export {
5455
6097
  parseIAssetDatumOrThrow,
5456
6098
  parseInterestOracleDatum,
5457
6099
  parseLrpDatum,
6100
+ parseLrpDatumOrThrow,
5458
6101
  parsePriceOracleDatum,
5459
6102
  parseSnapshotEpochToScaleToSumDatum,
5460
6103
  parseStabilityPoolDatum,
6104
+ parseStakingManagerDatum,
6105
+ parseStakingPosition,
6106
+ parseStakingPositionOrThrow,
5461
6107
  processSpRequest,
6108
+ randomLrpsSubsetSatisfyingTargetLovelaces,
5462
6109
  redeemCdp,
5463
6110
  redeemLrp,
5464
6111
  runCreateScriptRefTx,
@@ -5482,12 +6129,16 @@ export {
5482
6129
  serialisePriceOracleRedeemer,
5483
6130
  serialiseStabilityPoolDatum,
5484
6131
  serialiseStabilityPoolRedeemer,
6132
+ serialiseStakingDatum,
6133
+ serialiseStakingRedeemer,
5485
6134
  setSumInEpochToScaleToSum,
6135
+ shuffle,
5486
6136
  spAdd,
5487
6137
  spDiv,
5488
6138
  spMul,
5489
6139
  spSub,
5490
6140
  startInterestOracle,
6141
+ summarizeActualLeverageRedemptions,
5491
6142
  toSystemParamsAsset,
5492
6143
  treasuryFeeTx,
5493
6144
  updatePoolSnapshotWithdrawalFee,