@indigo-labs/indigo-sdk 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/index.d.mts +102 -40
  2. package/dist/index.d.ts +102 -40
  3. package/dist/index.js +900 -801
  4. package/dist/index.mjs +339 -256
  5. package/package.json +2 -2
  6. package/src/contracts/cdp/helpers.ts +7 -6
  7. package/src/contracts/cdp/transactions.ts +8 -29
  8. package/src/contracts/gov/transactions.ts +12 -16
  9. package/src/contracts/iasset/helpers.ts +2 -7
  10. package/src/contracts/initialize/actions.ts +0 -2
  11. package/src/contracts/initialize/helpers.ts +0 -4
  12. package/src/contracts/interest-collection/transactions.ts +2 -5
  13. package/src/contracts/interest-oracle/helpers.ts +4 -0
  14. package/src/contracts/interest-oracle/transactions.ts +1 -4
  15. package/src/contracts/price-oracle/helpers.ts +5 -11
  16. package/src/contracts/price-oracle/transactions.ts +2 -7
  17. package/src/contracts/rob/transactions.ts +0 -2
  18. package/src/contracts/rob-leverage/transactions.ts +1 -4
  19. package/src/contracts/stability-pool/transactions.ts +2 -8
  20. package/src/contracts/stableswap/helpers.ts +369 -1
  21. package/src/contracts/stableswap/transactions.ts +43 -191
  22. package/src/contracts/staking/transactions.ts +2 -7
  23. package/tests/cdp/actions.ts +0 -11
  24. package/tests/cdp/cdp-helpers.ts +2 -2
  25. package/tests/cdp/cdp-queries.ts +1 -3
  26. package/tests/cdp/cdp.test.ts +409 -620
  27. package/tests/cdp/transactions-mutated.ts +30 -25
  28. package/tests/endpoints/initialize.ts +0 -2
  29. package/tests/gov/actions.ts +7 -32
  30. package/tests/gov/gov.test.ts +169 -401
  31. package/tests/indigo-test-helpers.ts +0 -1
  32. package/tests/initialize.test.ts +15 -20
  33. package/tests/interest-collection/interest-collection.test.ts +0 -4
  34. package/tests/interest-oracle.test.ts +1 -8
  35. package/tests/price-oracle/actions.ts +6 -8
  36. package/tests/price-oracle/price-oracle.test.ts +1 -13
  37. package/tests/price-oracle/transactions-mutated.ts +1 -4
  38. package/tests/pyth/pyth-indigo.test.ts +8 -12
  39. package/tests/pyth/pyth.test.ts +1 -2
  40. package/tests/rob/actions.ts +0 -2
  41. package/tests/rob/rob-leverage.test.ts +164 -220
  42. package/tests/rob/rob.test.ts +158 -263
  43. package/tests/rob/transactions-mutated.ts +7 -18
  44. package/tests/stability-pool/actions.ts +4 -8
  45. package/tests/stability-pool.test.ts +164 -255
  46. package/tests/stableswap/stableswap-actions.ts +0 -1
  47. package/tests/stableswap/stableswap.test.ts +226 -4
  48. package/tests/staking.test.ts +2 -13
  49. package/tests/treasury/treasury.test.ts +6 -30
package/dist/index.mjs CHANGED
@@ -6,7 +6,6 @@ import {
6
6
  fromHex as fromHex7,
7
7
  getInputIndices as getInputIndices3,
8
8
  scriptHashToCredential as scriptHashToCredential3,
9
- slotToUnixTime as slotToUnixTime5,
10
9
  toHex as toHex7
11
10
  } from "@lucid-evolution/lucid";
12
11
 
@@ -431,16 +430,11 @@ function calculateAccruedInterest(now, unitaryInterestSnapshot, mintedAmount, in
431
430
  }
432
431
 
433
432
  // src/contracts/price-oracle/helpers.ts
434
- import {
435
- slotToUnixTime,
436
- unixTimeToSlot
437
- } from "@lucid-evolution/lucid";
438
- function oracleExpirationAwareValidity(currentSlot, biasTime, oracleExpiration, network) {
439
- const validateFrom = slotToUnixTime(network, currentSlot - 1);
433
+ function oracleExpirationAwareValidity(lucid, biasTime, oracleExpiration) {
434
+ const validateFrom = lucid.slotToUnixTime(lucid.currentSlot() - 1);
440
435
  const defaultValidateTo = validateFrom + biasTime;
441
- const cappedValidateTo = slotToUnixTime(
442
- network,
443
- unixTimeToSlot(network, oracleExpiration) - 1
436
+ const cappedValidateTo = lucid.slotToUnixTime(
437
+ lucid.unixTimeToSlot(oracleExpiration) - 1
444
438
  );
445
439
  const isOracleActuallyExpired = cappedValidateTo <= validateFrom;
446
440
  return {
@@ -453,7 +447,6 @@ function oracleExpirationAwareValidity(currentSlot, biasTime, oracleExpiration,
453
447
  import { match as match13, P as P13 } from "ts-pattern";
454
448
 
455
449
  // src/contracts/cdp/helpers.ts
456
- import { slotToUnixTime as slotToUnixTime2 } from "@lucid-evolution/lucid";
457
450
  import { match as match4, P as P4 } from "ts-pattern";
458
451
 
459
452
  // src/utils/indigo-helpers.ts
@@ -471,11 +464,10 @@ function iassetValueOfCollateral(collateralAmt, oraclePrice) {
471
464
  rationalDiv(rationalFromInt(collateralAmt), oraclePrice)
472
465
  );
473
466
  }
474
- function cdpCollateralRatioPercentage(currentSlot, iassetPrice, cdpUtxoAssets, cdpContent, interestOracleDatum, network) {
475
- const currentTime = BigInt(slotToUnixTime2(network, currentSlot));
467
+ function cdpCollateralRatioPercentage(now, iassetPrice, cdpUtxoAssets, cdpContent, interestOracleDatum) {
476
468
  return match4(cdpContent.cdpFees).with({ ActiveCDPInterestTracking: P4.select() }, (interest) => {
477
469
  const interestAmt = calculateAccruedInterest(
478
- currentTime,
470
+ now,
479
471
  interest.unitaryInterestSnapshot,
480
472
  cdpContent.mintedAmt,
481
473
  interest.lastSettled,
@@ -1606,7 +1598,6 @@ import {
1606
1598
  toHex as toHex4,
1607
1599
  addAssets as addAssets3,
1608
1600
  fromHex as fromHex3,
1609
- slotToUnixTime as slotToUnixTime3,
1610
1601
  sortUTxOs,
1611
1602
  getInputIndices as getInputIndices2
1612
1603
  } from "@lucid-evolution/lucid";
@@ -2098,9 +2089,8 @@ function parseCollateralAssetDatumOrThrow(datum) {
2098
2089
  }
2099
2090
 
2100
2091
  // src/contracts/interest-collection/transactions.ts
2101
- async function batchCollectInterest(collateralAssetOref, interestCollectorOutRef, interestOracleOutRef, cdpOutRefs, params, lucid, currentSlot) {
2102
- const network = lucid.config().network;
2103
- const currentTime = BigInt(slotToUnixTime3(network, currentSlot));
2092
+ async function batchCollectInterest(collateralAssetOref, interestCollectorOutRef, interestOracleOutRef, cdpOutRefs, params, lucid) {
2093
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
2104
2094
  const interestCollectionRefScriptUtxo = matchSingle(
2105
2095
  await lucid.utxosByOutRef([
2106
2096
  fromSystemParamsScriptRef(
@@ -2196,7 +2186,7 @@ async function batchCollectInterest(collateralAssetOref, interestCollectorOutRef
2196
2186
  referenceInputs,
2197
2187
  false
2198
2188
  );
2199
- const validateFrom = slotToUnixTime3(network, currentSlot - 1);
2189
+ const validateFrom = lucid.slotToUnixTime(lucid.currentSlot() - 1);
2200
2190
  const validateTo = validateFrom + Number(params.cdpParams.biasTime);
2201
2191
  const tx = lucid.newTx().validFrom(validateFrom).validTo(validateTo).readFrom(referenceInputs).collectFrom([interestCollectorUtxo], {
2202
2192
  kind: "selected",
@@ -3246,7 +3236,6 @@ import {
3246
3236
  Data as Data18,
3247
3237
  fromHex as fromHex6,
3248
3238
  scriptHashToCredential as scriptHashToCredential2,
3249
- slotToUnixTime as slotToUnixTime4,
3250
3239
  toHex as toHex6
3251
3240
  } from "@lucid-evolution/lucid";
3252
3241
  import { match as match11, P as P11 } from "ts-pattern";
@@ -3743,11 +3732,9 @@ function derivePythPrice(derivedPythPrice, messageHex) {
3743
3732
  // src/contracts/iasset/helpers.ts
3744
3733
  import * as Core from "@evolution-sdk/evolution";
3745
3734
  var MAX_COLLATERAL_ASSETS_COUNT_PER_IASSET = 9;
3746
- function attachOracle(iasset, collateralAsset, priceInfo, priceOracleOref, pythStateOref, pythMessage, pythConfig, biasTime, currentSlot, lucid, tx) {
3735
+ function attachOracle(iasset, collateralAsset, priceInfo, priceOracleOref, pythStateOref, pythMessage, pythConfig, biasTime, lucid, tx) {
3747
3736
  return match11(priceInfo).returnType().with({ Delisted: P11.any }, () => {
3748
- const currentTime = BigInt(
3749
- slotToUnixTime4(lucid.config().network, currentSlot)
3750
- );
3737
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
3751
3738
  const validFrom = Number(currentTime - BigInt(biasTime / 2n));
3752
3739
  const validTo = Number(currentTime + BigInt(biasTime / 2n));
3753
3740
  return Promise.resolve({
@@ -3768,10 +3755,9 @@ function attachOracle(iasset, collateralAsset, priceInfo, priceOracleOref, pythS
3768
3755
  );
3769
3756
  return {
3770
3757
  interval: oracleExpirationAwareValidity(
3771
- currentSlot,
3758
+ lucid,
3772
3759
  Number(biasTime),
3773
- Number(priceOracleDatum.expirationTime),
3774
- lucid.config().network
3760
+ Number(priceOracleDatum.expirationTime)
3775
3761
  ),
3776
3762
  referenceInputs: [priceOracleUtxo]
3777
3763
  };
@@ -3875,9 +3861,9 @@ async function retrieveAdjustedPrice(iasset, collateralAsset, priceInfo, extraDe
3875
3861
  }
3876
3862
 
3877
3863
  // src/contracts/cdp/transactions.ts
3878
- async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, lucid, currentSlot, pythMessage = void 0, pythStateOref = void 0) {
3864
+ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, lucid, pythMessage = void 0, pythStateOref = void 0) {
3879
3865
  const network = lucid.config().network;
3880
- const currentTime = BigInt(slotToUnixTime5(network, currentSlot));
3866
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
3881
3867
  const [pkh, skh] = await addrDetails(lucid);
3882
3868
  const cdpCreatorRefScriptUtxo = matchSingle(
3883
3869
  await lucid.utxosByOutRef([
@@ -3999,7 +3985,6 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
3999
3985
  pythMessage,
4000
3986
  sysParams.pythConfig,
4001
3987
  sysParams.cdpCreatorParams.biasTime,
4002
- currentSlot,
4003
3988
  lucid,
4004
3989
  tx
4005
3990
  );
@@ -4047,9 +4032,8 @@ async function openCdp(collateralAmount, mintedAmount, sysParams, cdpCreatorOref
4047
4032
  });
4048
4033
  return tx;
4049
4034
  }
4050
- async function adjustCdp(collateralAdjustment, debtAdjustment, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, interestCollectorOref, sysParams, lucid, currentSlot, pythMessage = void 0, pythStateOref = void 0) {
4051
- const network = lucid.config().network;
4052
- const currentTime = BigInt(slotToUnixTime5(network, currentSlot));
4035
+ async function adjustCdp(collateralAdjustment, debtAdjustment, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, interestCollectorOref, sysParams, lucid, pythMessage = void 0, pythStateOref = void 0) {
4036
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
4053
4037
  const cdpRefScriptUtxo = matchSingle(
4054
4038
  await lucid.utxosByOutRef([
4055
4039
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -4115,7 +4099,6 @@ async function adjustCdp(collateralAdjustment, debtAdjustment, cdpOref, iassetOr
4115
4099
  pythMessage,
4116
4100
  sysParams.pythConfig,
4117
4101
  sysParams.cdpParams.biasTime,
4118
- currentSlot,
4119
4102
  lucid,
4120
4103
  tx
4121
4104
  );
@@ -4210,7 +4193,7 @@ async function adjustCdp(collateralAdjustment, debtAdjustment, cdpOref, iassetOr
4210
4193
  tx.addSignerKey(toHex7(cdpDatum.cdpOwner));
4211
4194
  return tx;
4212
4195
  }
4213
- async function depositCdp(amount, cdpOref, iassetOref, collateralAssetOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid, currentSlot) {
4196
+ async function depositCdp(amount, cdpOref, iassetOref, collateralAssetOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid) {
4214
4197
  return adjustCdp(
4215
4198
  amount,
4216
4199
  0n,
@@ -4222,11 +4205,10 @@ async function depositCdp(amount, cdpOref, iassetOref, collateralAssetOref, inte
4222
4205
  treasuryOref,
4223
4206
  interestCollectorOref,
4224
4207
  params,
4225
- lucid,
4226
- currentSlot
4208
+ lucid
4227
4209
  );
4228
4210
  }
4229
- async function withdrawCdp(amount, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid, currentSlot, pythMessage = void 0, pythStateOref = void 0) {
4211
+ async function withdrawCdp(amount, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid, pythMessage = void 0, pythStateOref = void 0) {
4230
4212
  return adjustCdp(
4231
4213
  -amount,
4232
4214
  0n,
@@ -4239,12 +4221,11 @@ async function withdrawCdp(amount, cdpOref, iassetOref, collateralAssetOref, pri
4239
4221
  interestCollectorOref,
4240
4222
  params,
4241
4223
  lucid,
4242
- currentSlot,
4243
4224
  pythMessage,
4244
4225
  pythStateOref
4245
4226
  );
4246
4227
  }
4247
- async function mintCdp(amount, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid, currentSlot, pythMessage = void 0, pythStateOref = void 0) {
4228
+ async function mintCdp(amount, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid, pythMessage = void 0, pythStateOref = void 0) {
4248
4229
  return adjustCdp(
4249
4230
  0n,
4250
4231
  amount,
@@ -4257,12 +4238,11 @@ async function mintCdp(amount, cdpOref, iassetOref, collateralAssetOref, priceOr
4257
4238
  interestCollectorOref,
4258
4239
  params,
4259
4240
  lucid,
4260
- currentSlot,
4261
4241
  pythMessage,
4262
4242
  pythStateOref
4263
4243
  );
4264
4244
  }
4265
- async function burnCdp(amount, cdpOref, iassetOref, collateralAssetOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid, currentSlot) {
4245
+ async function burnCdp(amount, cdpOref, iassetOref, collateralAssetOref, interestOracleOref, treasuryOref, interestCollectorOref, params, lucid) {
4266
4246
  return adjustCdp(
4267
4247
  0n,
4268
4248
  -amount,
@@ -4274,13 +4254,11 @@ async function burnCdp(amount, cdpOref, iassetOref, collateralAssetOref, interes
4274
4254
  treasuryOref,
4275
4255
  interestCollectorOref,
4276
4256
  params,
4277
- lucid,
4278
- currentSlot
4257
+ lucid
4279
4258
  );
4280
4259
  }
4281
- async function closeCdp(cdpOref, collateralAssetOref, interestOracleOref, interestCollectorOref, sysParams, lucid, currentSlot) {
4282
- const network = lucid.config().network;
4283
- const currentTime = BigInt(slotToUnixTime5(network, currentSlot));
4260
+ async function closeCdp(cdpOref, collateralAssetOref, interestOracleOref, interestCollectorOref, sysParams, lucid) {
4261
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
4284
4262
  const cdpRefScriptUtxo = matchSingle(
4285
4263
  await lucid.utxosByOutRef([
4286
4264
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -4322,7 +4300,7 @@ async function closeCdp(cdpOref, collateralAssetOref, interestOracleOref, intere
4322
4300
  const interestOracleDatum = parseInterestOracleDatum(
4323
4301
  getInlineDatumOrThrow(interestOracleUtxo)
4324
4302
  );
4325
- const validateFrom = slotToUnixTime5(network, currentSlot - 1);
4303
+ const validateFrom = lucid.slotToUnixTime(lucid.currentSlot() - 1);
4326
4304
  const validateTo = validateFrom + Number(sysParams.cdpCreatorParams.biasTime);
4327
4305
  const tx = lucid.newTx().readFrom([
4328
4306
  cdpRefScriptUtxo,
@@ -4380,9 +4358,8 @@ async function closeCdp(cdpOref, collateralAssetOref, interestOracleOref, intere
4380
4358
  }
4381
4359
  return tx;
4382
4360
  }
4383
- async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, interestCollectorOref, treasuryOref, govOref, sysParams, lucid, currentSlot, pythMessage = void 0, _pythStateOref = void 0) {
4384
- const network = lucid.config().network;
4385
- const currentTime = BigInt(slotToUnixTime5(network, currentSlot));
4361
+ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, interestCollectorOref, treasuryOref, govOref, sysParams, lucid, pythMessage = void 0, _pythStateOref = void 0) {
4362
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
4386
4363
  const cdpRefScriptUtxo = matchSingle(
4387
4364
  await lucid.utxosByOutRef([
4388
4365
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -4512,15 +4489,14 @@ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, coll
4512
4489
  getInlineDatumOrThrow(priceOracleUtxo)
4513
4490
  );
4514
4491
  const txValidity = oracleExpirationAwareValidity(
4515
- currentSlot,
4492
+ lucid,
4516
4493
  Number(sysParams.cdpCreatorParams.biasTime),
4517
- Number(priceOracleDatum.expirationTime),
4518
- network
4494
+ Number(priceOracleDatum.expirationTime)
4519
4495
  );
4520
4496
  referenceInputs.push(priceOracleUtxo);
4521
4497
  tx.validFrom(txValidity.validFrom).validTo(txValidity.validTo);
4522
4498
  } else {
4523
- const validateFrom = slotToUnixTime5(network, currentSlot - 1);
4499
+ const validateFrom = lucid.slotToUnixTime(lucid.currentSlot() - 1);
4524
4500
  const validateTo = validateFrom + Number(sysParams.cdpCreatorParams.biasTime);
4525
4501
  tx.validFrom(validateFrom).validTo(validateTo);
4526
4502
  }
@@ -4632,9 +4608,9 @@ async function redeemCdp(attemptedRedemptionIAssetAmt, cdpOref, iassetOref, coll
4632
4608
  );
4633
4609
  return tx;
4634
4610
  }
4635
- async function freezeCdp(cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, sysParams, lucid, currentSlot, pythMessage = void 0, pythStateOref = void 0) {
4611
+ async function freezeCdp(cdpOref, iassetOref, collateralAssetOref, priceOracleOref, interestOracleOref, sysParams, lucid, pythMessage = void 0, pythStateOref = void 0) {
4636
4612
  const network = lucid.config().network;
4637
- const currentTime = BigInt(slotToUnixTime5(network, currentSlot));
4613
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
4638
4614
  const cdpRefScriptUtxo = matchSingle(
4639
4615
  await lucid.utxosByOutRef([
4640
4616
  fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef)
@@ -4717,7 +4693,6 @@ async function freezeCdp(cdpOref, iassetOref, collateralAssetOref, priceOracleOr
4717
4693
  pythMessage,
4718
4694
  sysParams.pythConfig,
4719
4695
  sysParams.cdpParams.biasTime,
4720
- currentSlot,
4721
4696
  lucid,
4722
4697
  tx
4723
4698
  );
@@ -5317,7 +5292,6 @@ import {
5317
5292
  fromHex as fromHex8,
5318
5293
  fromText as fromText4,
5319
5294
  paymentCredentialOf as paymentCredentialOf2,
5320
- slotToUnixTime as slotToUnixTime6,
5321
5295
  toHex as toHex8
5322
5296
  } from "@lucid-evolution/lucid";
5323
5297
  import {
@@ -5770,9 +5744,9 @@ import {
5770
5744
  addressFromBech32,
5771
5745
  addressToBech32
5772
5746
  } from "@3rd-eye-labs/cardano-offchain-common";
5773
- async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lucid, currentSlot, govOref, allIAssetOrefs) {
5747
+ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lucid, govOref, allIAssetOrefs) {
5774
5748
  const network = lucid.config().network;
5775
- const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
5749
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
5776
5750
  const ownAddr = await lucid.wallet().address();
5777
5751
  const pkh = paymentCredentialOf2(ownAddr);
5778
5752
  const govRefScriptUtxo = matchSingle(
@@ -5891,9 +5865,9 @@ async function createProposal(proposalContent, treasuryWithdrawal, sysParams, lu
5891
5865
  newPollId
5892
5866
  ];
5893
5867
  }
5894
- async function createShardsChunks(chunkSize, pollManagerOref, sysParams, currentSlot, lucid) {
5868
+ async function createShardsChunks(chunkSize, pollManagerOref, sysParams, lucid) {
5895
5869
  const network = lucid.config().network;
5896
- const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
5870
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
5897
5871
  const ownAddr = await lucid.wallet().address();
5898
5872
  const pollManagerUtxo = matchSingle(
5899
5873
  await lucid.utxosByOutRef([pollManagerOref]),
@@ -5982,9 +5956,8 @@ function voteHelper(stakingPosLockedAmt, pollShard, voteOption, currentTime, ind
5982
5956
  ];
5983
5957
  return [newLockedAmt, newPollStatus];
5984
5958
  }
5985
- async function vote(voteOption, pollShardOref, stakingPositionOref, sysParams, lucid, currentSlot) {
5986
- const network = lucid.config().network;
5987
- const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
5959
+ async function vote(voteOption, pollShardOref, stakingPositionOref, sysParams, lucid) {
5960
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
5988
5961
  const ownAddr = await lucid.wallet().address();
5989
5962
  const pollShardRefScriptUtxo = matchSingle(
5990
5963
  await lucid.utxosByOutRef([
@@ -6030,7 +6003,10 @@ async function vote(voteOption, pollShardOref, stakingPositionOref, sysParams, l
6030
6003
  indyStakedAmt
6031
6004
  );
6032
6005
  return lucid.newTx().validFrom(validityFrom).validTo(
6033
- validityFrom + Number(sysParams.pollManagerParams.pBiasTime) - ONE_SECOND
6006
+ Math.min(
6007
+ validityFrom + Number(sysParams.pollManagerParams.pBiasTime) - ONE_SECOND,
6008
+ Number(pollShardDatum.votingEndTime) - ONE_SECOND
6009
+ )
6034
6010
  ).readFrom([stakingRefScriptUtxo, pollShardRefScriptUtxo]).collectFrom([stakingPosUtxo], serialiseStakingRedeemer("Lock")).collectFrom(
6035
6011
  [pollShardUtxo],
6036
6012
  serialisePollShardRedeemer({ Vote: voteOption })
@@ -6058,9 +6034,8 @@ async function vote(voteOption, pollShardOref, stakingPositionOref, sysParams, l
6058
6034
  stakingPosUtxo.assets
6059
6035
  ).addSigner(ownAddr);
6060
6036
  }
6061
- async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, currentSlot) {
6062
- const network = lucid.config().network;
6063
- const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
6037
+ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid) {
6038
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
6064
6039
  const ownAddr = await lucid.wallet().address();
6065
6040
  const pollShardRefScriptUtxo = matchSingle(
6066
6041
  await lucid.utxosByOutRef([
@@ -6147,9 +6122,9 @@ async function mergeShards(pollManagerOref, shardsOutRefs, sysParams, lucid, cur
6147
6122
  addAssets8(pollManagerUtxo.assets, shardsAggregatedAda)
6148
6123
  ).addSigner(ownAddr);
6149
6124
  }
6150
- async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSlot) {
6125
+ async function endProposal(pollManagerOref, govOref, sysParams, lucid) {
6151
6126
  const network = lucid.config().network;
6152
- const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
6127
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
6153
6128
  const ownAddr = await lucid.wallet().address();
6154
6129
  const pollManagerRefScriptUtxo = matchSingle(
6155
6130
  await lucid.utxosByOutRef([
@@ -6261,9 +6236,9 @@ async function endProposal(pollManagerOref, govOref, sysParams, lucid, currentSl
6261
6236
  }
6262
6237
  return tx;
6263
6238
  }
6264
- async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, allIAssetOrefs, iAssetOref, allCollateralAssetsOrefsOfIAsset, collateralAssetOref, stableswapPoolOrCdpCreatorOref, sysParams, lucid, currentSlot) {
6239
+ async function executeProposal(executeOref, govOref, treasuryWithdrawalOref, allIAssetOrefs, iAssetOref, allCollateralAssetsOrefsOfIAsset, collateralAssetOref, stableswapPoolOrCdpCreatorOref, sysParams, lucid) {
6265
6240
  const network = lucid.config().network;
6266
- const currentTime = BigInt(slotToUnixTime6(network, currentSlot));
6241
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
6267
6242
  const ownAddr = await lucid.wallet().address();
6268
6243
  const govUtxo = matchSingle(
6269
6244
  await lucid.utxosByOutRef([govOref]),
@@ -6998,7 +6973,6 @@ import {
6998
6973
  Data as Data32,
6999
6974
  fromHex as fromHex9,
7000
6975
  fromText as fromText5,
7001
- slotToUnixTime as slotToUnixTime7,
7002
6976
  toHex as toHex9
7003
6977
  } from "@lucid-evolution/lucid";
7004
6978
  import {
@@ -7068,9 +7042,8 @@ async function openStakingPosition(amount, params, lucid, stakingManagerRef) {
7068
7042
  }
7069
7043
  ).addSignerKey(pkh.hash);
7070
7044
  }
7071
- async function adjustStakingPosition(stakingPositionRef, amount, params, lucid, currentSlot, stakingManagerRef) {
7072
- const network = lucid.config().network;
7073
- const now = BigInt(slotToUnixTime7(network, currentSlot));
7045
+ async function adjustStakingPosition(stakingPositionRef, amount, params, lucid, stakingManagerRef) {
7046
+ const now = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
7074
7047
  const stakingPositionOut = await findStakingPositionByOutRef(
7075
7048
  stakingPositionRef,
7076
7049
  lucid
@@ -7125,9 +7098,8 @@ async function adjustStakingPosition(stakingPositionRef, amount, params, lucid,
7125
7098
  addAssets9(stakingPositionOut.utxo.assets, mkAssetsOf7(indyToken, amount))
7126
7099
  ).addSignerKey(toHex9(stakingPositionOut.datum.owner));
7127
7100
  }
7128
- async function closeStakingPosition(stakingPositionRef, params, lucid, currentSlot, stakingManagerRef) {
7129
- const network = lucid.config().network;
7130
- const now = BigInt(slotToUnixTime7(network, currentSlot));
7101
+ async function closeStakingPosition(stakingPositionRef, params, lucid, stakingManagerRef) {
7102
+ const now = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
7131
7103
  const stakingPositionOut = await findStakingPositionByOutRef(
7132
7104
  stakingPositionRef,
7133
7105
  lucid
@@ -7249,7 +7221,6 @@ function castStakingParams(params) {
7249
7221
  import {
7250
7222
  fromHex as fromHex10,
7251
7223
  fromText as fromText6,
7252
- slotToUnixTime as slotToUnixTime8,
7253
7224
  toUnit as toUnit2,
7254
7225
  validatorToAddress
7255
7226
  } from "@lucid-evolution/lucid";
@@ -7431,14 +7402,13 @@ async function startInterestOracle(initialUnitaryInterest, initialInterestRate,
7431
7402
  }
7432
7403
  ];
7433
7404
  }
7434
- async function feedInterestOracle(params, newInterestRate, lucid, currentSlot, assetClass, utxo, scriptRef2) {
7405
+ async function feedInterestOracle(params, newInterestRate, lucid, assetClass, utxo, scriptRef2) {
7435
7406
  if (!assetClass && !utxo)
7436
7407
  throw new Error("Either interest oracle nft or utxo must be provided");
7437
7408
  if (assetClass && !utxo) {
7438
7409
  utxo = await findInterestOracle(lucid, assetClass);
7439
7410
  }
7440
- const network = lucid.config().network;
7441
- const now = BigInt(slotToUnixTime8(network, currentSlot));
7411
+ const now = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
7442
7412
  const tx = lucid.newTx();
7443
7413
  const datum = parseInterestOracleDatum(getInlineDatumOrThrow(utxo));
7444
7414
  if (scriptRef2) {
@@ -7962,7 +7932,6 @@ import {
7962
7932
  fromHex as fromHex11,
7963
7933
  toHex as toHex12,
7964
7934
  addAssets as addAssets11,
7965
- slotToUnixTime as slotToUnixTime9,
7966
7935
  credentialToAddress as credentialToAddress3
7967
7936
  } from "@lucid-evolution/lucid";
7968
7937
  import {
@@ -8129,9 +8098,8 @@ async function requestSpAccountClosure(accountUtxo, sysParams, lucid, maxTxFee =
8129
8098
  )
8130
8099
  ).addSignerKey(toHex12(oldAccountDatum.owner));
8131
8100
  }
8132
- async function processSpRequestAuxiliary(stabilityPoolUtxo, accountUtxo, iAssetUtxo, allE2s2sSnapshotOrefs, sysParams, lucid, currentSlot, txFee) {
8133
- const network = lucid.config().network;
8134
- const currentTime = BigInt(slotToUnixTime9(network, currentSlot));
8101
+ async function processSpRequestAuxiliary(stabilityPoolUtxo, accountUtxo, iAssetUtxo, allE2s2sSnapshotOrefs, sysParams, lucid, txFee) {
8102
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
8135
8103
  const stabilityPoolScriptRef = matchSingle5(
8136
8104
  await lucid.utxosByOutRef([
8137
8105
  fromSystemParamsScriptRef(
@@ -8147,7 +8115,7 @@ async function processSpRequestAuxiliary(stabilityPoolUtxo, accountUtxo, iAssetU
8147
8115
  getInlineDatumOrThrow(stabilityPoolUtxo)
8148
8116
  );
8149
8117
  const baseRefInputs = [iAssetUtxo, stabilityPoolScriptRef];
8150
- const validFrom = slotToUnixTime9(network, currentSlot - 1);
8118
+ const validFrom = lucid.slotToUnixTime(lucid.currentSlot() - 1);
8151
8119
  const tx = lucid.newTx().validFrom(validFrom).validTo(validFrom + sysParams.stabilityPoolParams.accountProcessingBiasMs).readFrom(baseRefInputs).collectFrom([stabilityPoolUtxo], {
8152
8120
  kind: "selected",
8153
8121
  inputs: [stabilityPoolUtxo, accountUtxo],
@@ -8519,7 +8487,7 @@ async function processSpRequestAuxiliary(stabilityPoolUtxo, accountUtxo, iAssetU
8519
8487
  }).exhaustive();
8520
8488
  return tx;
8521
8489
  }
8522
- async function processSpRequest(stabilityPoolUtxo, accountUtxo, iAssetUtxo, allE2s2sSnapshotOrefs, sysParams, lucid, currentSlot) {
8490
+ async function processSpRequest(stabilityPoolUtxo, accountUtxo, iAssetUtxo, allE2s2sSnapshotOrefs, sysParams, lucid) {
8523
8491
  const draftTx = processSpRequestAuxiliary(
8524
8492
  stabilityPoolUtxo,
8525
8493
  accountUtxo,
@@ -8527,7 +8495,6 @@ async function processSpRequest(stabilityPoolUtxo, accountUtxo, iAssetUtxo, allE
8527
8495
  allE2s2sSnapshotOrefs,
8528
8496
  sysParams,
8529
8497
  lucid,
8530
- currentSlot,
8531
8498
  // Placeholder transation fee
8532
8499
  1n
8533
8500
  );
@@ -8539,7 +8506,6 @@ async function processSpRequest(stabilityPoolUtxo, accountUtxo, iAssetUtxo, allE
8539
8506
  allE2s2sSnapshotOrefs,
8540
8507
  sysParams,
8541
8508
  lucid,
8542
- currentSlot,
8543
8509
  fee
8544
8510
  );
8545
8511
  }
@@ -9176,7 +9142,7 @@ async function cancelRob(robOutRef, sysParams, lucid) {
9176
9142
  const robDatum = parseRobDatumOrThrow(getInlineDatumOrThrow(robUtxo));
9177
9143
  return lucid.newTx().readFrom([robScriptRefUtxo]).collectFrom([robUtxo], serialiseRobRedeemer("Cancel")).addSignerKey(toHex14(robDatum.owner));
9178
9144
  }
9179
- async function redeemRob(redemptionRobsData, priceOracleOutRef, iassetOutRef, collateralAssetOutRef, lucid, sysParams, currentSlot, pythMessage = void 0, pythStateOutRef = void 0) {
9145
+ async function redeemRob(redemptionRobsData, priceOracleOutRef, iassetOutRef, collateralAssetOutRef, lucid, sysParams, pythMessage = void 0, pythStateOutRef = void 0) {
9180
9146
  const robScriptRefUtxo = matchSingle(
9181
9147
  await lucid.utxosByOutRef([
9182
9148
  fromSystemParamsScriptRef(sysParams.scriptReferences.robValidatorRef)
@@ -9220,7 +9186,6 @@ async function redeemRob(redemptionRobsData, priceOracleOutRef, iassetOutRef, co
9220
9186
  pythMessage,
9221
9187
  sysParams.pythConfig,
9222
9188
  sysParams.cdpParams.biasTime,
9223
- currentSlot,
9224
9189
  lucid,
9225
9190
  tx
9226
9191
  );
@@ -9394,7 +9359,6 @@ var mkRobValidatorFromSP = (params) => {
9394
9359
  // src/contracts/rob-leverage/transactions.ts
9395
9360
  import {
9396
9361
  addAssets as addAssets14,
9397
- slotToUnixTime as slotToUnixTime10,
9398
9362
  Data as Data45,
9399
9363
  fromHex as fromHex14,
9400
9364
  getInputIndices as getInputIndices5
@@ -9580,9 +9544,9 @@ function calculateLeverageFromCollateralRatio(iasset, collateralAsset, collatera
9580
9544
  // src/contracts/rob-leverage/transactions.ts
9581
9545
  import { mkAssetsOf as mkAssetsOf11 } from "@3rd-eye-labs/cardano-offchain-common";
9582
9546
  import Decimal3 from "decimal.js";
9583
- async function leverageCdpWithRob(leverage, baseCollateral, priceOracleOutRef, iassetOutRef, collateralAssetOutRef, cdpCreatorOref, interestOracleOref, treasuryOref, sysParams, lucid, allRobs, currentSlot, pythMessage = void 0, pythStateOref = void 0) {
9547
+ async function leverageCdpWithRob(leverage, baseCollateral, priceOracleOutRef, iassetOutRef, collateralAssetOutRef, cdpCreatorOref, interestOracleOref, treasuryOref, sysParams, lucid, allRobs, pythMessage = void 0, pythStateOref = void 0) {
9584
9548
  const network = lucid.config().network;
9585
- const currentTime = BigInt(slotToUnixTime10(network, currentSlot));
9549
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
9586
9550
  const [pkh, skh] = await addrDetails(lucid);
9587
9551
  const robScriptRefUtxo = matchSingle(
9588
9552
  await lucid.utxosByOutRef([
@@ -9776,7 +9740,6 @@ async function leverageCdpWithRob(leverage, baseCollateral, priceOracleOutRef, i
9776
9740
  pythMessage,
9777
9741
  sysParams.pythConfig,
9778
9742
  sysParams.cdpCreatorParams.biasTime,
9779
- currentSlot,
9780
9743
  lucid,
9781
9744
  tx
9782
9745
  );
@@ -9834,7 +9797,6 @@ import {
9834
9797
  Data as Data46,
9835
9798
  fromHex as fromHex15,
9836
9799
  fromText as fromText10,
9837
- slotToUnixTime as slotToUnixTime11,
9838
9800
  validatorToAddress as validatorToAddress2
9839
9801
  } from "@lucid-evolution/lucid";
9840
9802
 
@@ -9863,9 +9825,8 @@ function mkPriceOracleValidator(params) {
9863
9825
  // src/contracts/price-oracle/transactions.ts
9864
9826
  import { mkAssetsOf as mkAssetsOf12 } from "@3rd-eye-labs/cardano-offchain-common";
9865
9827
  import * as Core2 from "@evolution-sdk/evolution";
9866
- async function startPriceOracleTx(lucid, assetName, startPrice, oracleParams, currentSlot, refOutRef, auxiliaryData) {
9867
- const network = lucid.config().network;
9868
- const now = BigInt(slotToUnixTime11(network, currentSlot));
9828
+ async function startPriceOracleTx(lucid, assetName, startPrice, oracleParams, refOutRef, auxiliaryData) {
9829
+ const now = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
9869
9830
  if (!refOutRef) {
9870
9831
  refOutRef = (await lucid.wallet().getUtxos())[0];
9871
9832
  }
@@ -9898,9 +9859,8 @@ async function startPriceOracleTx(lucid, assetName, startPrice, oracleParams, cu
9898
9859
  );
9899
9860
  return [tx, priceOracleNft];
9900
9861
  }
9901
- async function feedPriceOracleTx(lucid, oracleOref, newPrice, oracleParams, currentSlot, auxiliaryData) {
9902
- const network = lucid.config().network;
9903
- const currentTime = BigInt(slotToUnixTime11(network, currentSlot));
9862
+ async function feedPriceOracleTx(lucid, oracleOref, newPrice, oracleParams, auxiliaryData) {
9863
+ const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
9904
9864
  const priceOracleUtxo = matchSingle(
9905
9865
  await lucid.utxosByOutRef([oracleOref]),
9906
9866
  (_) => new Error("Expected a single price oracle UTXO")
@@ -10214,7 +10174,7 @@ async function initStakingManager(lucid, stakingParams) {
10214
10174
  );
10215
10175
  await submitTx(lucid, tx);
10216
10176
  }
10217
- async function handleOracleForCollateralAsset(lucid, iasset, collateralAsset, pythConfig, currentSlot) {
10177
+ async function handleOracleForCollateralAsset(lucid, iasset, collateralAsset, pythConfig) {
10218
10178
  return match20(collateralAsset.priceOracle).returnType().with({ tag: "_indigo_oracle_nft" }, async (val) => {
10219
10179
  const [pkh, _] = await addrDetails(lucid);
10220
10180
  const priceOracleParams = {
@@ -10226,8 +10186,7 @@ async function handleOracleForCollateralAsset(lucid, iasset, collateralAsset, py
10226
10186
  lucid,
10227
10187
  val.tokenName,
10228
10188
  val.startPrice,
10229
- priceOracleParams,
10230
- currentSlot
10189
+ priceOracleParams
10231
10190
  );
10232
10191
  await runAndAwaitTxBuilder(lucid, priceOracleStartTx);
10233
10192
  return { info: { OracleNft: priceOracleNft }, params: priceOracleParams };
@@ -10248,7 +10207,7 @@ async function handleOracleForCollateralAsset(lucid, iasset, collateralAsset, py
10248
10207
  });
10249
10208
  }).exhaustive();
10250
10209
  }
10251
- async function initializeAsset(lucid, iassetParams, iassetToken, collateralAssetAuthToken, cdpAuthToken, cdpParams, stableswapValidatorHash, stabilityPoolParams, stabilityPoolToken, asset, pythConfig, currentSlot) {
10210
+ async function initializeAsset(lucid, iassetParams, iassetToken, collateralAssetAuthToken, cdpAuthToken, cdpParams, stableswapValidatorHash, stabilityPoolParams, stabilityPoolToken, asset, pythConfig) {
10252
10211
  const iassetName = fromHex16(fromText11(asset.name));
10253
10212
  const collateralAssetInfos = [];
10254
10213
  for (const collateralAsset of asset.collateralAssets) {
@@ -10270,8 +10229,7 @@ async function initializeAsset(lucid, iassetParams, iassetToken, collateralAsset
10270
10229
  lucid,
10271
10230
  asset,
10272
10231
  collateralAsset,
10273
- pythConfig,
10274
- currentSlot
10232
+ pythConfig
10275
10233
  );
10276
10234
  const collateralAssetContent = {
10277
10235
  iasset: iassetName,
@@ -10672,7 +10630,7 @@ async function initPythConfig(lucid, initialAssets, pythStateAsset) {
10672
10630
  pythFeeds: allPythFeeds
10673
10631
  };
10674
10632
  }
10675
- async function init(lucid, defaultInitialAssets, currentSlot, mkPythBasedAssets = () => [], protocolParams, initOptions, spStakingCred = DEFAULT_STAKING_CRED, treasuryStakingCred = DEFAULT_STAKING_CRED) {
10633
+ async function init(lucid, defaultInitialAssets, mkPythBasedAssets = () => [], protocolParams, initOptions, spStakingCred = DEFAULT_STAKING_CRED, treasuryStakingCred = DEFAULT_STAKING_CRED) {
10676
10634
  const startSlot = lucid.currentSlot();
10677
10635
  const {
10678
10636
  totalIndySupply,
@@ -10972,8 +10930,7 @@ async function init(lucid, defaultInitialAssets, currentSlot, mkPythBasedAssets
10972
10930
  stabilityPoolParams,
10973
10931
  stabilityPoolToken,
10974
10932
  asset,
10975
- pythConfig,
10976
- currentSlot
10933
+ pythConfig
10977
10934
  );
10978
10935
  assetInfos.push(assetInfo);
10979
10936
  }
@@ -11294,6 +11251,7 @@ async function findCollateralAsset(lucid, sysParams, iassetName, collateralAsset
11294
11251
 
11295
11252
  // src/contracts/stableswap/helpers.ts
11296
11253
  import { fromHex as fromHex19, fromText as fromText14 } from "@lucid-evolution/lucid";
11254
+ import { array as A16, ord as Ord5, function as F27 } from "fp-ts";
11297
11255
 
11298
11256
  // src/contracts/stableswap/types-new.ts
11299
11257
  import {
@@ -11397,7 +11355,11 @@ function parseStableswapOrderRedeemerOrThrow(redeemerCborHex) {
11397
11355
 
11398
11356
  // src/contracts/stableswap/helpers.ts
11399
11357
  import { Data as Data52 } from "@evolution-sdk/evolution";
11358
+ import { assetClassValueOf as assetClassValueOf12 } from "@3rd-eye-labs/cardano-offchain-common";
11400
11359
  var BASE_MAX_EXECUTION_FEE = 1620000n;
11360
+ var defaultOrderProcessingConfig = {
11361
+ ignoreMaxExecutionFeeConstraint: false
11362
+ };
11401
11363
  function createDestinationDatum(datum, outRef) {
11402
11364
  if (!datum) {
11403
11365
  return serialiseStableswapOutputDatum([
@@ -11410,6 +11372,229 @@ function createDestinationDatum(datum, outRef) {
11410
11372
  }
11411
11373
  return Data52.toCBORHex(datum);
11412
11374
  }
11375
+ function psmOrderType(order, sysParams) {
11376
+ const iassetAc = {
11377
+ currencySymbol: fromHex19(
11378
+ sysParams.stableswapParams.iassetSymbol.unCurrencySymbol
11379
+ ),
11380
+ tokenName: order.datum.iasset
11381
+ };
11382
+ const suppliedIasset = assetClassValueOf12(order.utxo.assets, iassetAc);
11383
+ const suppliedCollateralAsset = assetClassValueOf12(
11384
+ order.utxo.assets,
11385
+ order.datum.collateralAsset
11386
+ );
11387
+ if (suppliedIasset != 0n && suppliedCollateralAsset != 0n || suppliedIasset == 0n && suppliedCollateralAsset == 0n) {
11388
+ return {
11389
+ type: "ERROR",
11390
+ reason: "An order must supply either iAsset or collateral asset"
11391
+ };
11392
+ }
11393
+ const isMinting = suppliedCollateralAsset > 0n;
11394
+ return isMinting ? { type: "MINTING", suppliedCollateral: suppliedCollateralAsset } : { type: "REDEEMING", suppliedIassets: suppliedIasset };
11395
+ }
11396
+ function summariseOrder(order, psmPool, sysParams, orderProcessingConfig) {
11397
+ const orderType = psmOrderType(order, sysParams);
11398
+ if (orderType.type === "ERROR") {
11399
+ return { _tag: "ERROR", reason: orderType.reason };
11400
+ }
11401
+ const isOneToOne = psmPool.datum.collateralToIassetRatio.numerator === psmPool.datum.collateralToIassetRatio.denominator;
11402
+ if (!orderProcessingConfig.ignoreMaxExecutionFeeConstraint && order.datum.maxExecutionFee < BASE_MAX_EXECUTION_FEE) {
11403
+ return {
11404
+ _tag: "ERROR",
11405
+ reason: `Max execution fee is too low. Minimum: ${BASE_MAX_EXECUTION_FEE}`
11406
+ };
11407
+ }
11408
+ if (orderType.type === "MINTING") {
11409
+ const suppliedCollateralAsset = orderType.suppliedCollateral;
11410
+ if (rationalToFloat(order.datum.maxFeeRatio) < rationalToFloat(psmPool.datum.mintingFeeRatio)) {
11411
+ return { _tag: "ERROR", reason: "Max fee ratio not satisfied" };
11412
+ }
11413
+ if (isOneToOne) {
11414
+ const fee = calculateFeeFromRatio(
11415
+ psmPool.datum.mintingFeeRatio,
11416
+ suppliedCollateralAsset
11417
+ );
11418
+ return {
11419
+ _tag: "SUCCESS",
11420
+ result: {
11421
+ order,
11422
+ orderType: "MINTING",
11423
+ swapInfo: {
11424
+ suppliedCollateralAsset,
11425
+ suppliedIasset: 0n,
11426
+ owedCollateralAsset: 0n,
11427
+ owedIasset: suppliedCollateralAsset - fee,
11428
+ mintingFee: fee,
11429
+ redemptionFee: 0n
11430
+ }
11431
+ }
11432
+ };
11433
+ } else {
11434
+ const iAssetConversion = rationalFloor(
11435
+ rationalDiv(
11436
+ rationalFromInt(suppliedCollateralAsset),
11437
+ psmPool.datum.collateralToIassetRatio
11438
+ )
11439
+ );
11440
+ const attemptedNormalizedCollateral = rationalFloor(
11441
+ rationalMul(
11442
+ rationalFromInt(iAssetConversion),
11443
+ psmPool.datum.collateralToIassetRatio
11444
+ )
11445
+ );
11446
+ const normalizedCollateralSupplied = rationalFloor(
11447
+ rationalDiv(
11448
+ rationalFromInt(attemptedNormalizedCollateral),
11449
+ psmPool.datum.collateralToIassetRatio
11450
+ )
11451
+ ) != iAssetConversion ? suppliedCollateralAsset : attemptedNormalizedCollateral;
11452
+ const fee = calculateFeeFromRatio(
11453
+ psmPool.datum.mintingFeeRatio,
11454
+ iAssetConversion
11455
+ );
11456
+ return {
11457
+ _tag: "SUCCESS",
11458
+ result: {
11459
+ order,
11460
+ orderType: "MINTING",
11461
+ swapInfo: {
11462
+ suppliedCollateralAsset: normalizedCollateralSupplied,
11463
+ suppliedIasset: 0n,
11464
+ owedIasset: iAssetConversion - fee,
11465
+ owedCollateralAsset: 0n,
11466
+ mintingFee: fee,
11467
+ redemptionFee: 0n
11468
+ }
11469
+ }
11470
+ };
11471
+ }
11472
+ } else {
11473
+ const suppliedIasset = orderType.suppliedIassets;
11474
+ if (rationalToFloat(order.datum.maxFeeRatio) < rationalToFloat(psmPool.datum.redemptionFeeRatio)) {
11475
+ return { _tag: "ERROR", reason: "Max fee ratio not satisfied" };
11476
+ }
11477
+ const fee = calculateFeeFromRatio(
11478
+ psmPool.datum.redemptionFeeRatio,
11479
+ suppliedIasset
11480
+ );
11481
+ const effectiveSuppliedIasset = suppliedIasset - fee;
11482
+ if (isOneToOne) {
11483
+ return {
11484
+ _tag: "SUCCESS",
11485
+ result: {
11486
+ order,
11487
+ orderType: "REDEEMING",
11488
+ swapInfo: {
11489
+ suppliedIasset: effectiveSuppliedIasset,
11490
+ suppliedCollateralAsset: 0n,
11491
+ owedCollateralAsset: effectiveSuppliedIasset,
11492
+ owedIasset: 0n,
11493
+ redemptionFee: fee,
11494
+ mintingFee: 0n
11495
+ }
11496
+ }
11497
+ };
11498
+ } else {
11499
+ const collateralConversion = rationalFloor(
11500
+ rationalMul(
11501
+ rationalFromInt(effectiveSuppliedIasset),
11502
+ psmPool.datum.collateralToIassetRatio
11503
+ )
11504
+ );
11505
+ const attemptedNormalizedEffectiveIasset = rationalFloor(
11506
+ rationalDiv(
11507
+ rationalFromInt(collateralConversion),
11508
+ psmPool.datum.collateralToIassetRatio
11509
+ )
11510
+ );
11511
+ const normalizedEffectiveIasset = rationalFloor(
11512
+ rationalMul(
11513
+ rationalFromInt(attemptedNormalizedEffectiveIasset),
11514
+ psmPool.datum.collateralToIassetRatio
11515
+ )
11516
+ ) != collateralConversion ? effectiveSuppliedIasset : attemptedNormalizedEffectiveIasset;
11517
+ return {
11518
+ _tag: "SUCCESS",
11519
+ result: {
11520
+ order,
11521
+ orderType: "REDEEMING",
11522
+ swapInfo: {
11523
+ suppliedIasset: normalizedEffectiveIasset,
11524
+ suppliedCollateralAsset: 0n,
11525
+ owedCollateralAsset: rationalFloor(
11526
+ rationalMul(
11527
+ rationalFromInt(effectiveSuppliedIasset),
11528
+ psmPool.datum.collateralToIassetRatio
11529
+ )
11530
+ ),
11531
+ owedIasset: 0n,
11532
+ redemptionFee: fee,
11533
+ mintingFee: 0n
11534
+ }
11535
+ }
11536
+ };
11537
+ }
11538
+ }
11539
+ }
11540
+ function pickValidSatisfiableOrders(orders, pool, sysParams, orderProcessingConfig) {
11541
+ const psmAvailableLiq = assetClassValueOf12(
11542
+ pool.utxo.assets,
11543
+ pool.datum.collateralAsset
11544
+ );
11545
+ const validOrders = orders.flatMap((order) => {
11546
+ try {
11547
+ const res = summariseOrder(order, pool, sysParams, orderProcessingConfig);
11548
+ return res._tag === "SUCCESS" ? [res.result] : [];
11549
+ } catch (_) {
11550
+ return [];
11551
+ }
11552
+ });
11553
+ const { left: mintingOrders, right: redeemingOrdersSortedDesc } = F27.pipe(
11554
+ validOrders,
11555
+ A16.partition((o) => o.orderType === "REDEEMING"),
11556
+ ({ left, right }) => ({
11557
+ left,
11558
+ // Sort the redeeming orders descending.
11559
+ right: F27.pipe(
11560
+ right,
11561
+ A16.sort(
11562
+ Ord5.contramap(
11563
+ (o) => o.swapInfo.owedCollateralAsset
11564
+ )(Ord5.reverse(BigIntOrd))
11565
+ )
11566
+ )
11567
+ })
11568
+ );
11569
+ const totalCollateralDiff = F27.pipe(
11570
+ validOrders,
11571
+ A16.reduce(
11572
+ 0n,
11573
+ (acc, order) => acc + order.swapInfo.suppliedCollateralAsset - order.swapInfo.owedCollateralAsset
11574
+ )
11575
+ );
11576
+ if (psmAvailableLiq + totalCollateralDiff >= 0n) {
11577
+ return validOrders.map((o) => o.order);
11578
+ }
11579
+ const collateralFromMinting = F27.pipe(
11580
+ mintingOrders,
11581
+ A16.reduce(0n, (acc, o) => acc + o.swapInfo.suppliedCollateralAsset)
11582
+ );
11583
+ const { selected } = F27.pipe(
11584
+ redeemingOrdersSortedDesc,
11585
+ A16.reduce(
11586
+ {
11587
+ intermediateCollateralAmt: psmAvailableLiq + collateralFromMinting,
11588
+ selected: []
11589
+ },
11590
+ ({ intermediateCollateralAmt, selected: selected2 }, order) => intermediateCollateralAmt >= order.swapInfo.owedCollateralAsset ? {
11591
+ intermediateCollateralAmt: intermediateCollateralAmt - order.swapInfo.owedCollateralAsset,
11592
+ selected: [...selected2, order]
11593
+ } : { intermediateCollateralAmt, selected: selected2 }
11594
+ )
11595
+ );
11596
+ return [...mintingOrders, ...selected].map((o) => o.order);
11597
+ }
11413
11598
 
11414
11599
  // src/contracts/stableswap/transactions.ts
11415
11600
  import {
@@ -11431,9 +11616,9 @@ import {
11431
11616
  mkLovelacesOf as mkLovelacesOf9,
11432
11617
  lovelacesAmt as lovelacesAmt5,
11433
11618
  isSameOutRef as isSameOutRef2,
11434
- assetClassValueOf as assetClassValueOf12
11619
+ assetClassValueOf as assetClassValueOf13
11435
11620
  } from "@3rd-eye-labs/cardano-offchain-common";
11436
- import { array as A16, function as F27 } from "fp-ts";
11621
+ import { array as A17, function as F28 } from "fp-ts";
11437
11622
  import { isEmpty } from "fp-ts/lib/Array";
11438
11623
  async function createStableswapOrder(iasset, collateralAsset, amount, minting, poolDatum, params, lucid, destinationAddress, destinationInlineDatum, maxExecutionFee = BASE_MAX_EXECUTION_FEE, additionalLovelaces = 0n, maxFeeRatio) {
11439
11624
  const myAddress = await lucid.wallet().address();
@@ -11507,7 +11692,7 @@ async function cancelStableswapOrder(stableswapOrderOref, sysParams, lucid) {
11507
11692
  serialiseStableswapOrderRedeemer("CancelStableswapOrder")
11508
11693
  ).addSignerKey(toHex19(stableswapOrderDatum.owner));
11509
11694
  }
11510
- async function batchProcessStableswapOrders(stableswapOrderOrefs, stableswapPoolOref, treasuryOref, sysParams, lucid) {
11695
+ async function batchProcessStableswapOrders(stableswapOrderOrefs, stableswapPoolOref, treasuryOref, sysParams, lucid, orderProcessingConfig = defaultOrderProcessingConfig) {
11511
11696
  const stableswapScriptRefUtxo = matchSingle7(
11512
11697
  await lucid.utxosByOutRef([
11513
11698
  fromSystemParamsScriptRef(
@@ -11567,134 +11752,21 @@ async function batchProcessStableswapOrders(stableswapOrderOrefs, stableswapPool
11567
11752
  if (toHex19(orderDatum.iasset) != toHex19(mainOrderDatum.iasset) || toHex19(orderDatum.collateralAsset.currencySymbol) != toHex19(mainOrderDatum.collateralAsset.currencySymbol) || toHex19(orderDatum.collateralAsset.tokenName) != toHex19(mainOrderDatum.collateralAsset.tokenName)) {
11568
11753
  throw new Error("Wrong batch of orders");
11569
11754
  }
11570
- const suppliedIasset = assetClassValueOf12(orderUtxo.assets, iassetAc);
11571
- const suppliedCollateralAsset = assetClassValueOf12(
11572
- orderUtxo.assets,
11573
- collateralAc
11755
+ const res = summariseOrder(
11756
+ { utxo: orderUtxo, datum: orderDatum },
11757
+ { utxo: stableswapPoolUtxo, datum: stableswapPoolDatum },
11758
+ sysParams,
11759
+ orderProcessingConfig
11574
11760
  );
11575
- if (suppliedIasset != 0n && suppliedCollateralAsset != 0n || suppliedIasset == 0n && suppliedCollateralAsset == 0n) {
11576
- throw new Error(
11577
- "An order must supply either iAsset or collateral asset"
11578
- );
11579
- }
11580
- const isMinting = suppliedCollateralAsset > 0n;
11581
- const isOneToOne = stableswapPoolDatum.collateralToIassetRatio.numerator === stableswapPoolDatum.collateralToIassetRatio.denominator;
11582
- if (isMinting) {
11583
- if (isOneToOne) {
11584
- const fee2 = calculateFeeFromRatio(
11585
- stableswapPoolDatum.mintingFeeRatio,
11586
- suppliedCollateralAsset
11587
- );
11588
- return {
11589
- utxo: orderUtxo,
11590
- datum: orderDatum,
11591
- swapInfo: {
11592
- suppliedCollateralAsset,
11593
- suppliedIasset: 0n,
11594
- owedCollateralAsset: 0n,
11595
- owedIasset: suppliedCollateralAsset - fee2,
11596
- mintingFee: fee2,
11597
- redemptionFee: 0n
11598
- }
11599
- };
11600
- } else {
11601
- const iAssetConversion = rationalFloor(
11602
- rationalDiv(
11603
- rationalFromInt(suppliedCollateralAsset),
11604
- stableswapPoolDatum.collateralToIassetRatio
11605
- )
11606
- );
11607
- const attemptedNormalizedCollateral = rationalFloor(
11608
- rationalMul(
11609
- rationalFromInt(iAssetConversion),
11610
- stableswapPoolDatum.collateralToIassetRatio
11611
- )
11612
- );
11613
- const normalizedCollateralSupplied = rationalFloor(
11614
- rationalDiv(
11615
- rationalFromInt(attemptedNormalizedCollateral),
11616
- stableswapPoolDatum.collateralToIassetRatio
11617
- )
11618
- ) != iAssetConversion ? suppliedCollateralAsset : attemptedNormalizedCollateral;
11619
- const fee2 = calculateFeeFromRatio(
11620
- stableswapPoolDatum.mintingFeeRatio,
11621
- iAssetConversion
11622
- );
11623
- return {
11624
- utxo: orderUtxo,
11625
- datum: orderDatum,
11626
- swapInfo: {
11627
- suppliedCollateralAsset: normalizedCollateralSupplied,
11628
- suppliedIasset: 0n,
11629
- owedCollateralAsset: 0n,
11630
- owedIasset: iAssetConversion - fee2,
11631
- mintingFee: fee2,
11632
- redemptionFee: 0n
11633
- }
11634
- };
11635
- }
11636
- } else {
11637
- const fee2 = calculateFeeFromRatio(
11638
- stableswapPoolDatum.redemptionFeeRatio,
11639
- suppliedIasset
11640
- );
11641
- const effectiveSuppliedIasset = suppliedIasset - fee2;
11642
- if (isOneToOne) {
11643
- return {
11644
- utxo: orderUtxo,
11645
- datum: orderDatum,
11646
- swapInfo: {
11647
- suppliedCollateralAsset: 0n,
11648
- suppliedIasset: effectiveSuppliedIasset,
11649
- owedCollateralAsset: effectiveSuppliedIasset,
11650
- owedIasset: 0n,
11651
- mintingFee: 0n,
11652
- redemptionFee: fee2
11653
- }
11654
- };
11655
- } else {
11656
- const collateralConversion = rationalFloor(
11657
- rationalMul(
11658
- rationalFromInt(effectiveSuppliedIasset),
11659
- stableswapPoolDatum.collateralToIassetRatio
11660
- )
11661
- );
11662
- const attemptedNormalizedEffectiveIasset = rationalFloor(
11663
- rationalDiv(
11664
- rationalFromInt(collateralConversion),
11665
- stableswapPoolDatum.collateralToIassetRatio
11666
- )
11667
- );
11668
- const normalizedEffectiveIasset = rationalFloor(
11669
- rationalMul(
11670
- rationalFromInt(attemptedNormalizedEffectiveIasset),
11671
- stableswapPoolDatum.collateralToIassetRatio
11672
- )
11673
- ) != collateralConversion ? effectiveSuppliedIasset : attemptedNormalizedEffectiveIasset;
11674
- return {
11675
- utxo: orderUtxo,
11676
- datum: orderDatum,
11677
- swapInfo: {
11678
- suppliedCollateralAsset: 0n,
11679
- suppliedIasset: normalizedEffectiveIasset,
11680
- owedCollateralAsset: rationalFloor(
11681
- rationalMul(
11682
- rationalFromInt(effectiveSuppliedIasset),
11683
- stableswapPoolDatum.collateralToIassetRatio
11684
- )
11685
- ),
11686
- owedIasset: 0n,
11687
- mintingFee: 0n,
11688
- redemptionFee: fee2
11689
- }
11690
- };
11691
- }
11761
+ if (res._tag === "ERROR") {
11762
+ throw new Error(res.reason);
11692
11763
  }
11764
+ return res.result;
11693
11765
  }
11694
11766
  );
11695
- const totalSwapInfo = F27.pipe(
11767
+ const totalSwapInfo = F28.pipe(
11696
11768
  ordersInfo,
11697
- A16.reduce(
11769
+ A17.reduce(
11698
11770
  {
11699
11771
  suppliedCollateralAsset: 0n,
11700
11772
  suppliedIasset: 0n,
@@ -11716,6 +11788,13 @@ async function batchProcessStableswapOrders(stableswapOrderOrefs, stableswapPool
11716
11788
  )
11717
11789
  );
11718
11790
  const collateralAmtChangePool = totalSwapInfo.suppliedCollateralAsset - totalSwapInfo.owedCollateralAsset;
11791
+ const newPsmPoolValue = addAssets18(
11792
+ stableswapPoolUtxo.assets,
11793
+ mkAssetsOf16(collateralAc, collateralAmtChangePool)
11794
+ );
11795
+ if (assetClassValueOf13(newPsmPoolValue, collateralAc) < 0n) {
11796
+ throw new Error("Cannot batch more than liquidity allows");
11797
+ }
11719
11798
  const amountToMint = totalSwapInfo.owedIasset - totalSwapInfo.suppliedIasset + totalSwapInfo.mintingFee;
11720
11799
  const fee = totalSwapInfo.mintingFee + totalSwapInfo.redemptionFee;
11721
11800
  const tx = lucid.newTx().readFrom([
@@ -11736,20 +11815,17 @@ async function batchProcessStableswapOrders(stableswapOrderOrefs, stableswapPool
11736
11815
  kind: "inline",
11737
11816
  value: serialiseStableswapPoolDatum(stableswapPoolDatum)
11738
11817
  },
11739
- collateralAmtChangePool != 0n ? addAssets18(
11740
- stableswapPoolUtxo.assets,
11741
- mkAssetsOf16(collateralAc, collateralAmtChangePool)
11742
- ) : stableswapPoolUtxo.assets
11818
+ newPsmPoolValue
11743
11819
  ).setMinFee(stableswapOrderOrefs.length > 1 ? 1498875n : 1030000n);
11744
11820
  if (amountToMint !== 0n) {
11745
11821
  tx.mintAssets(mkAssetsOf16(iassetAc, amountToMint), Data53.void());
11746
11822
  }
11747
- F27.pipe(
11823
+ F28.pipe(
11748
11824
  ordersInfo,
11749
- A16.reduce(tx, (acc, orderInfo) => {
11825
+ A17.reduce(tx, (acc, orderInfo) => {
11750
11826
  return acc.collectFrom(
11751
- [orderInfo.utxo],
11752
- isSameOutRef2(orderInfo.utxo, mainOrderUtxo) ? serialiseStableswapOrderRedeemer("BatchProcessStableswapOrders") : {
11827
+ [orderInfo.order.utxo],
11828
+ isSameOutRef2(orderInfo.order.utxo, mainOrderUtxo) ? serialiseStableswapOrderRedeemer("BatchProcessStableswapOrders") : {
11753
11829
  kind: "selected",
11754
11830
  makeRedeemer: (inputIndices) => {
11755
11831
  return serialiseStableswapOrderRedeemer({
@@ -11759,24 +11835,27 @@ async function batchProcessStableswapOrders(stableswapOrderOrefs, stableswapPool
11759
11835
  }
11760
11836
  });
11761
11837
  },
11762
- inputs: [orderInfo.utxo, mainOrderUtxo]
11838
+ inputs: [orderInfo.order.utxo, mainOrderUtxo]
11763
11839
  }
11764
11840
  ).pay.ToAddressWithData(
11765
- addressToBech323(orderInfo.datum.destination, lucid.config().network),
11841
+ addressToBech323(
11842
+ orderInfo.order.datum.destination,
11843
+ lucid.config().network
11844
+ ),
11766
11845
  {
11767
11846
  kind: "inline",
11768
11847
  value: createDestinationDatum(
11769
- orderInfo.datum.destinationInlineDatum ?? null,
11770
- orderInfo.utxo
11848
+ orderInfo.order.datum.destinationInlineDatum ?? null,
11849
+ orderInfo.order.utxo
11771
11850
  )
11772
11851
  },
11773
11852
  addAssets18(
11774
- // Currently, we always take the max execution fee from the order utxo.
11853
+ // NOTICE: Currently, we always take the max execution fee from the order utxo.
11775
11854
  // This can be improved so that we take the actual execution fee.
11776
11855
  mkLovelacesOf9(
11777
- lovelacesAmt5(orderInfo.utxo.assets) - orderInfo.datum.maxExecutionFee
11856
+ lovelacesAmt5(orderInfo.order.utxo.assets) - orderInfo.order.datum.maxExecutionFee
11778
11857
  ),
11779
- orderInfo.swapInfo.owedIasset > 0 ? mkAssetsOf16(iassetAc, orderInfo.swapInfo.owedIasset) : mkAssetsOf16(
11858
+ orderInfo.orderType === "MINTING" ? mkAssetsOf16(iassetAc, orderInfo.swapInfo.owedIasset) : mkAssetsOf16(
11780
11859
  collateralAc,
11781
11860
  orderInfo.swapInfo.owedCollateralAsset
11782
11861
  )
@@ -11970,6 +12049,7 @@ export {
11970
12049
  createStableswapOrder,
11971
12050
  decodePriceUpdate,
11972
12051
  decodePythMessage,
12052
+ defaultOrderProcessingConfig,
11973
12053
  depositCdp,
11974
12054
  deriveAuthToken,
11975
12055
  derivePythPrice,
@@ -12133,7 +12213,9 @@ export {
12133
12213
  parseStakingRedeemer,
12134
12214
  parseStakingRedeemerOrThrow,
12135
12215
  partitionEpochToScaleToSums,
12216
+ pickValidSatisfiableOrders,
12136
12217
  processSpRequest,
12218
+ psmOrderType,
12137
12219
  randomRobsSubsetSatisfyingTargetCollateral,
12138
12220
  rationalAdd,
12139
12221
  rationalCeil,
@@ -12207,6 +12289,7 @@ export {
12207
12289
  startPriceOracleTx,
12208
12290
  submitTx,
12209
12291
  sum,
12292
+ summariseOrder,
12210
12293
  summarizeActualLeverageRedemptions,
12211
12294
  toAssetClassFromLucid,
12212
12295
  toDataDerivedPythPrice,