UNPKG

@indigo-labs/indigo-sdk

Version:

Indigo SDK for interacting with Indigo endpoints via lucid-evolution

1,265 lines (1,242 loc) 730 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { AccountContentSchema: () => AccountContentSchema, AikenIntervalIntervalBound: () => AikenIntervalIntervalBound, AikenIntervalIntervalBoundType: () => AikenIntervalIntervalBoundType, AssetClassSchema: () => AssetClassSchema2, BASE_MAX_EXECUTION_FEE: () => BASE_MAX_EXECUTION_FEE, BASE_MAX_TX_FEE: () => BASE_MAX_TX_FEE, BigIntOrd: () => BigIntOrd, CDPCreatorParams: () => CDPCreatorParams, CardanoTransactionValidityRange: () => CardanoTransactionValidityRange, CollectorRedeemerSchema: () => CollectorRedeemerSchema, CredentialD: () => CredentialD, CredentialSchema: () => CredentialSchema, DEFAULT_INIT_OPTIONS: () => DEFAULT_INIT_OPTIONS, DerivedPythPriceSchema: () => DerivedPythPriceSchema, ExecuteParams: () => ExecuteParams, GovParams: () => GovParams, IAssetPriceInfoSchema: () => IAssetPriceInfoSchema, IAssetScriptParams: () => IAssetScriptParams, INIT_TOKEN_NAMES: () => INIT_TOKEN_NAMES, InterestCollectionParamsSchema: () => InterestCollectionParamsSchema, InterestOracleDatumSchema: () => InterestOracleDatumSchema, InterestOracleParamsSchema: () => InterestOracleParamsSchema, MAX_BUY_ROB_REDEMPTIONS_COUNT: () => MAX_BUY_ROB_REDEMPTIONS_COUNT, MAX_COLLATERAL_ASSETS_COUNT_PER_IASSET: () => MAX_COLLATERAL_ASSETS_COUNT_PER_IASSET, MAX_E2S2S_ENTRIES_COUNT: () => MAX_E2S2S_ENTRIES_COUNT, MAX_REDEMPTIONS_WITH_CDP_OPEN: () => MAX_REDEMPTIONS_WITH_CDP_OPEN, MAX_SELL_ROB_REDEMPTIONS_COUNT: () => MAX_SELL_ROB_REDEMPTIONS_COUNT, MIN_ROB_COLLATERAL_AMT: () => MIN_ROB_COLLATERAL_AMT, ONE_DAY: () => ONE_DAY, ONE_HOUR: () => ONE_HOUR, ONE_SECOND: () => ONE_SECOND, ONE_YEAR: () => ONE_YEAR, OneShotParamsSchema: () => OneShotParamsSchema, OracleIdxSchema: () => OracleIdxSchema, PRICE_UPDATE_MAGIC: () => PRICE_UPDATE_MAGIC, PollManagerParams: () => PollManagerParams, PollShardParams: () => PollShardParams, PriceOracleParamsSchema: () => PriceOracleParamsSchema, ProposalContentSchema: () => ProposalContentSchema, ProtocolParamsSchema: () => ProtocolParamsSchema, RationalSchema: () => RationalSchema, RobParamsSchema: () => RobParamsSchema, SOLANA_FORMAT_MAGIC: () => SOLANA_FORMAT_MAGIC, SPIntegerSchema: () => SPIntegerSchema, SnapshotEpochToScaleToSumContentSchema: () => SnapshotEpochToScaleToSumContentSchema, StabilityPoolContentSchema: () => StabilityPoolContentSchema, StabilityPoolDatumSchema: () => StabilityPoolDatumSchema, StabilityPoolParams: () => StabilityPoolParams, StabilityPoolRedeemerSchema: () => StabilityPoolRedeemerSchema, StableswapOrderDatumSchema: () => StableswapOrderDatumSchema, StakeCredential: () => StakeCredential, StakeCredentialSchema: () => StakeCredentialSchema, TreasuryWithdrawalSchema: () => TreasuryWithdrawalSchema, VerificationKeyHashSchema: () => VerificationKeyHashSchema, VersionRecordTokenParams: () => VersionRecordTokenParams, addrDetails: () => addrDetails, adjustCdp: () => adjustCdp, adjustPriceToDecimals: () => adjustPriceToDecimals, adjustRob: () => adjustRob, adjustStakingPosition: () => adjustStakingPosition, alwaysFailValidator: () => alwaysFailValidator, annulRequest: () => annulRequest, approximateLeverageRedemptions: () => approximateLeverageRedemptions, attachOracle: () => attachOracle, balance: () => balance, batchCollectInterest: () => batchCollectInterest, batchProcessStableswapOrders: () => batchProcessStableswapOrders, bigintMax: () => bigintMax, bigintMin: () => bigintMin, buildRedemptionsTx: () => buildRedemptionsTx, burnCdp: () => burnCdp, calculateAccruedInterest: () => calculateAccruedInterest, calculateAdaReward: () => calculateAdaReward, calculateCollateralRatioFromLeverage: () => calculateCollateralRatioFromLeverage, calculateIAssetRedemptionAmt: () => calculateIAssetRedemptionAmt, calculateLeverageFromCollateralRatio: () => calculateLeverageFromCollateralRatio, calculateMinCollateralCappedIAssetRedemptionAmt: () => calculateMinCollateralCappedIAssetRedemptionAmt, calculatePurchaseAmtWhenRobBuyOrder: () => calculatePurchaseAmtWhenRobBuyOrder, calculatePurchaseAmtWhenRobSellOrder: () => calculatePurchaseAmtWhenRobSellOrder, calculateSpendAmtWhenRobBuyOrder: () => calculateSpendAmtWhenRobBuyOrder, calculateSpendAmtWhenRobSellOrder: () => calculateSpendAmtWhenRobSellOrder, calculateTotalCollateralForRedemption: () => calculateTotalCollateralForRedemption, calculateUnitaryInterest: () => calculateUnitaryInterest, calculateUnitaryInterestSinceOracleLastUpdated: () => calculateUnitaryInterestSinceOracleLastUpdated, cancelRob: () => cancelRob, cancelStableswapOrder: () => cancelStableswapOrder, castCDPCreatorParams: () => castCDPCreatorParams, castCdpParams: () => castCdpParams, castCdpRedeemParams: () => castCdpRedeemParams, castExecuteParams: () => castExecuteParams, castGovParams: () => castGovParams, castInterestCollectionParams: () => castInterestCollectionParams, castInterestOracleParams: () => castInterestOracleParams, castOneShotParams: () => castOneShotParams, castPollManagerParams: () => castPollManagerParams, castPollShardParams: () => castPollShardParams, castPriceOracleParams: () => castPriceOracleParams, castRobParams: () => castRobParams, castStabilityPoolParams: () => castStabilityPoolParams, castStakingParams: () => castStakingParams, castVersionRecordTokenParams: () => castVersionRecordTokenParams, cdpCollateralRatioPercentage: () => cdpCollateralRatioPercentage, claimRob: () => claimRob, closeCdp: () => closeCdp, closeStakingPosition: () => closeStakingPosition, collectInterestTx: () => collectInterestTx, collectorFeeTx: () => collectorFeeTx, createDestinationDatum: () => createDestinationDatum, createE2s2sSnapshots: () => createE2s2sSnapshots, createProcessRequestAccountRedeemer: () => createProcessRequestAccountRedeemer, createProposal: () => createProposal, createScriptAddress: () => createScriptAddress, createShardsChunks: () => createShardsChunks, createStableswapOrder: () => createStableswapOrder, decodePriceUpdate: () => decodePriceUpdate, decodePythMessage: () => decodePythMessage, depositCdp: () => depositCdp, deriveAuthToken: () => deriveAuthToken, distributeAda: () => distributeAda, distributeInterest: () => distributeInterest, distributeReward: () => distributeReward, divideOnChainCompatible: () => divideOnChainCompatible, encodePriceUpdate: () => encodePriceUpdate, encodePythMessage: () => encodePythMessage, encodeSignedPythMessage: () => encodeSignedPythMessage, endProposal: () => endProposal, estimateUtxoMinLovelace: () => estimateUtxoMinLovelace, executeProposal: () => executeProposal, feedInterestOracle: () => feedInterestOracle, feedPriceOracleTx: () => feedPriceOracleTx, findRelevantE2s2sIdxs: () => findRelevantE2s2sIdxs, findStakingManager: () => findStakingManager, findStakingManagerByOutRef: () => findStakingManagerByOutRef, findStakingPositionByOutRef: () => findStakingPositionByOutRef, freezeCdp: () => freezeCdp, fromDataDerivedPythPrice: () => fromDataDerivedPythPrice, fromDecimal: () => fromDecimal, fromSPInteger: () => fromSPInteger, fromSysParamsCredential: () => fromSysParamsCredential, fromSysParamsDerivedPythPrice: () => fromSysParamsDerivedPythPrice, fromSysParamsPythFeedParams: () => fromSysParamsPythFeedParams, fromSysParamsStakeCredential: () => fromSysParamsStakeCredential, fromSystemParamsAsset: () => fromSystemParamsAsset, fromSystemParamsAssetLucid: () => fromSystemParamsAssetLucid, fromSystemParamsScriptRef: () => fromSystemParamsScriptRef, getAssetClassComparisonStr: () => getAssetClassComparisonStr, getInlineDatumOrThrow: () => getInlineDatumOrThrow, getPythFeedConfig: () => getPythFeedConfig, getUpdatedAccountDeposit: () => getUpdatedAccountDeposit, handleOracleForCollateralAsset: () => handleOracleForCollateralAsset, iassetValueOfCollateral: () => iassetValueOfCollateral, init: () => init, initCDPCreator: () => initCDPCreator, initCollector: () => initCollector, initGovernance: () => initGovernance, initInterestCollector: () => initInterestCollector, initPythConfig: () => initPythConfig, initScriptRef: () => initScriptRef, initSpState: () => initSpState, initStakingManager: () => initStakingManager, initSumVal: () => initSumVal, initTreasury: () => initTreasury, initializeAsset: () => initializeAsset, insertSorted: () => insertSorted, isBuyOrderFullyRedeemed: () => isBuyOrderFullyRedeemed, isFullyRedeemed: () => isFullyRedeemed, isSameEpochToScaleKey: () => isSameEpochToScaleKey, leverageCdpWithRob: () => leverageCdpWithRob, liquidateCdp: () => liquidateCdp, liquidationHelper: () => liquidationHelper, loadSystemParamsFromFile: () => loadSystemParamsFromFile, loadSystemParamsFromUrl: () => loadSystemParamsFromUrl, matchSingle: () => matchSingle, mergeCdps: () => mergeCdps, mergeShards: () => mergeShards, mintAuthTokenDirect: () => mintAuthTokenDirect, mintCdp: () => mintCdp, mintOneTimeAsset: () => mintOneTimeAsset, mintOneTimeToken: () => mintOneTimeToken, mkAuthTokenPolicy: () => mkAuthTokenPolicy, mkCDPCreatorValidator: () => mkCDPCreatorValidator, mkCDPCreatorValidatorFromSP: () => mkCDPCreatorValidatorFromSP, mkCdpRedeemValidatorFromSP: () => mkCdpRedeemValidatorFromSP, mkCdpValidatorFromSP: () => mkCdpValidatorFromSP, mkCollectorValidatorFromSP: () => mkCollectorValidatorFromSP, mkExecuteValidator: () => mkExecuteValidator, mkExecuteValidatorFromSP: () => mkExecuteValidatorFromSP, mkGovValidator: () => mkGovValidator, mkGovValidatorFromSP: () => mkGovValidatorFromSP, mkIAssetTokenPolicy: () => mkIAssetTokenPolicy, mkIAssetValidatorFromSP: () => mkIAssetValidatorFromSP, mkInterestCollectionValidator: () => mkInterestCollectionValidator, mkInterestCollectionValidatorFromSP: () => mkInterestCollectionValidatorFromSP, mkInterestOracleValidator: () => mkInterestOracleValidator, mkOneShotPolicy: () => mkOneShotPolicy, mkPollManagerValidator: () => mkPollManagerValidator, mkPollManagerValidatorFromSP: () => mkPollManagerValidatorFromSP, mkPollShardValidator: () => mkPollShardValidator, mkPollShardValidatorFromSP: () => mkPollShardValidatorFromSP, mkPriceOracleValidator: () => mkPriceOracleValidator, mkPythFeedValidator: () => mkPythFeedValidator, mkRobValidator: () => mkRobValidator, mkRobValidatorFromSP: () => mkRobValidatorFromSP, mkSPInteger: () => mkSPInteger, mkStabilityPoolAddr: () => mkStabilityPoolAddr, mkStabilityPoolValidator: () => mkStabilityPoolValidator, mkStabilityPoolValidatorFromSP: () => mkStabilityPoolValidatorFromSP, mkStableswapValidator: () => mkStableswapValidator, mkStableswapValidatorFromSP: () => mkStableswapValidatorFromSP, mkStakingValidatorFromSP: () => mkStakingValidatorFromSP, mkTreasuryAddr: () => mkTreasuryAddr, mkTreasuryValidatorFromSP: () => mkTreasuryValidatorFromSP, mkVersionRecordTokenPolicy: () => mkVersionRecordTokenPolicy, mkVersionRegistryValidator: () => mkVersionRegistryValidator, oneShotMintTx: () => oneShotMintTx, openCdp: () => openCdp, openRob: () => openRob, openStakingPosition: () => openStakingPosition, parseAccountDatum: () => parseAccountDatum, parseAccountDatumOrThrow: () => parseAccountDatumOrThrow, parseCdpDatum: () => parseCdpDatum, parseCdpDatumOrThrow: () => parseCdpDatumOrThrow, parseCdpRedeemer: () => parseCdpRedeemer, parseCdpRedeemerOrThrow: () => parseCdpRedeemerOrThrow, parseCollateralAssetDatum: () => parseCollateralAssetDatum, parseCollateralAssetDatumOrThrow: () => parseCollateralAssetDatumOrThrow, parseExecuteDatum: () => parseExecuteDatum, parseExecuteDatumOrThrow: () => parseExecuteDatumOrThrow, parseGovDatum: () => parseGovDatum, parseGovDatumOrThrow: () => parseGovDatumOrThrow, parseIAssetDatum: () => parseIAssetDatum, parseIAssetDatumOrThrow: () => parseIAssetDatumOrThrow, parseInterestCollectionDatum: () => parseInterestCollectionDatum, parseInterestOracleDatum: () => parseInterestOracleDatum, parsePollManager: () => parsePollManager, parsePollManagerOrThrow: () => parsePollManagerOrThrow, parsePollShard: () => parsePollShard, parsePollShardOrThrow: () => parsePollShardOrThrow, parsePollShardRedeemer: () => parsePollShardRedeemer, parsePollShardRedeemerOrThrow: () => parsePollShardRedeemerOrThrow, parsePriceOracleDatum: () => parsePriceOracleDatum, parsePythStateDatum: () => parsePythStateDatum, parseRobDatum: () => parseRobDatum, parseRobDatumOrThrow: () => parseRobDatumOrThrow, parseRobRedeemer: () => parseRobRedeemer, parseRobRedeemerOrThrow: () => parseRobRedeemerOrThrow, parseSnapshotEpochToScaleToSumDatum: () => parseSnapshotEpochToScaleToSumDatum, parseSnapshotEpochToScaleToSumDatumOrThrow: () => parseSnapshotEpochToScaleToSumDatumOrThrow, parseStabilityPoolDatum: () => parseStabilityPoolDatum, parseStabilityPoolDatumOrThrow: () => parseStabilityPoolDatumOrThrow, parseStabilityPoolRedeemer: () => parseStabilityPoolRedeemer, parseStabilityPoolRedeemerOrThrow: () => parseStabilityPoolRedeemerOrThrow, parseStableswapOrderDatum: () => parseStableswapOrderDatum, parseStableswapOrderDatumOrThrow: () => parseStableswapOrderDatumOrThrow, parseStableswapOrderRedeemer: () => parseStableswapOrderRedeemer, parseStableswapOrderRedeemerOrThrow: () => parseStableswapOrderRedeemerOrThrow, parseStableswapPoolDatum: () => parseStableswapPoolDatum, parseStableswapPoolDatumOrThrow: () => parseStableswapPoolDatumOrThrow, parseStakingManagerDatum: () => parseStakingManagerDatum, parseStakingPosition: () => parseStakingPosition, parseStakingPositionOrThrow: () => parseStakingPositionOrThrow, parseStakingRedeemer: () => parseStakingRedeemer, parseStakingRedeemerOrThrow: () => parseStakingRedeemerOrThrow, partitionEpochToScaleToSums: () => partitionEpochToScaleToSums, processSpRequest: () => processSpRequest, randomRobsSubsetSatisfyingTargetCollateral: () => randomRobsSubsetSatisfyingTargetCollateral, rationalAdd: () => rationalAdd, rationalCeil: () => rationalCeil, rationalDiv: () => rationalDiv, rationalFloor: () => rationalFloor, rationalFromInt: () => rationalFromInt, rationalMul: () => rationalMul, rationalNegate: () => rationalNegate, rationalSub: () => rationalSub, rationalToFloat: () => rationalToFloat, rationalZero: () => rationalZero, redeemCdp: () => redeemCdp, redeemRob: () => redeemRob, repsertReadonlyArr: () => repsertReadonlyArr, repsertWithReadonlyArr: () => repsertWithReadonlyArr, requestSpAccountAdjustment: () => requestSpAccountAdjustment, requestSpAccountClosure: () => requestSpAccountClosure, requestSpAccountCreation: () => requestSpAccountCreation, rewardSnapshotPrecision: () => rewardSnapshotPrecision, robAmtToSpend: () => robAmtToSpend, robBuyOrderFilledAssets: () => robBuyOrderFilledAssets, robBuyOrderSummary: () => robBuyOrderSummary, robCollateralAmtToSpend: () => robCollateralAmtToSpend, robIAssetAmtToSpend: () => robIAssetAmtToSpend, robSellOrderFilledAssets: () => robSellOrderFilledAssets, runCreateScriptRefTx: () => runCreateScriptRefTx, runOneShotMintTx: () => runOneShotMintTx, scriptRef: () => scriptRef, serialiseActionReturnDatum: () => serialiseActionReturnDatum, serialiseCdpDatum: () => serialiseCdpDatum, serialiseCdpRedeemer: () => serialiseCdpRedeemer, serialiseCollectorRedeemer: () => serialiseCollectorRedeemer, serialiseExecuteDatum: () => serialiseExecuteDatum, serialiseFeedInterestOracleRedeemer: () => serialiseFeedInterestOracleRedeemer, serialiseGovDatum: () => serialiseGovDatum, serialiseGovRedeemer: () => serialiseGovRedeemer, serialiseIAssetDatum: () => serialiseIAssetDatum, serialiseIAssetRedeemer: () => serialiseIAssetRedeemer, serialiseInterestCollectionDatum: () => serialiseInterestCollectionDatum, serialiseInterestCollectionRedeemer: () => serialiseInterestCollectionRedeemer, serialiseInterestOracleDatum: () => serialiseInterestOracleDatum, serialisePollDatum: () => serialisePollDatum, serialisePollManagerRedeemer: () => serialisePollManagerRedeemer, serialisePollShardRedeemer: () => serialisePollShardRedeemer, serialisePriceOracleDatum: () => serialisePriceOracleDatum, serialisePriceOracleRedeemer: () => serialisePriceOracleRedeemer, serialisePythFeedParams: () => serialisePythFeedParams, serialisePythFeedRedeemer: () => serialisePythFeedRedeemer, serialisePythStateDatum: () => serialisePythStateDatum, serialisePythUpdatesRedeemer: () => serialisePythUpdatesRedeemer, serialiseRedeemCdpWithdrawalRedeemer: () => serialiseRedeemCdpWithdrawalRedeemer, serialiseRobDatum: () => serialiseRobDatum, serialiseRobRedeemer: () => serialiseRobRedeemer, serialiseStabilityPoolDatum: () => serialiseStabilityPoolDatum, serialiseStabilityPoolRedeemer: () => serialiseStabilityPoolRedeemer, serialiseStableswapOrderDatum: () => serialiseStableswapOrderDatum, serialiseStableswapOrderRedeemer: () => serialiseStableswapOrderRedeemer, serialiseStableswapOutputDatum: () => serialiseStableswapOutputDatum, serialiseStableswapPoolDatum: () => serialiseStableswapPoolDatum, serialiseStakingDatum: () => serialiseStakingDatum, serialiseStakingRedeemer: () => serialiseStakingRedeemer, shuffle: () => shuffle, signersAllOf: () => signersAllOf, spAdd: () => spAdd, spDiv: () => spDiv, spMul: () => spMul, spSub: () => spSub, spZeroNegatives: () => spZeroNegatives, startInterestOracle: () => startInterestOracle, startPriceOracleTx: () => startPriceOracleTx, submitTx: () => submitTx, sum: () => sum, summarizeActualLeverageRedemptions: () => summarizeActualLeverageRedemptions, toAssetClassFromLucid: () => toAssetClassFromLucid, toDataDerivedPythPrice: () => toDataDerivedPythPrice, toSystemParamsAsset: () => toSystemParamsAsset, treasuryCollect: () => treasuryCollect, treasuryFeeTx: () => treasuryFeeTx, treasuryMerge: () => treasuryMerge, treasuryPrepareWithdrawal: () => treasuryPrepareWithdrawal, treasurySplit: () => treasurySplit, updateAccount: () => updateAccount, updatePermissions: () => updatePermissions, updatePoolStateWhenWithdrawalFee: () => updatePoolStateWhenWithdrawalFee, updateStableswapPoolFees: () => updateStableswapPoolFees, updateStakingLockedAmount: () => updateStakingLockedAmount, vote: () => vote, withdrawCdp: () => withdrawCdp, zeroNegatives: () => zeroNegatives }); module.exports = __toCommonJS(index_exports); // src/contracts/cdp/transactions.ts var import_lucid14 = require("@lucid-evolution/lucid"); // src/types/system-params.ts var import_lucid = require("@lucid-evolution/lucid"); // src/contracts/pyth-feed/types.ts var import_evolution2 = require("@evolution-sdk/evolution"); // src/types/evolution-schema-options.ts var DEFAULT_SCHEMA_OPTIONS = { mode: "custom", useIndefiniteArrays: true, // This is important to match aiken's Map encoding. useIndefiniteMaps: false, useDefiniteForEmpty: true, sortMapKeys: false, useMinimalEncoding: true, mapsAsObjects: false, encodeMapAsPairs: false }; // src/types/rational.ts var import_evolution = require("@evolution-sdk/evolution"); // src/utils/bigint-utils.ts var import_fp_ts = require("fp-ts"); function divideOnChainCompatible(a, b) { const res = a / b; return res + (res < 0n ? -1n : 0n); } function bigintMax(a, b) { return a > b ? a : b; } function bigintMin(a, b) { return a < b ? a : b; } function sum(arr) { return import_fp_ts.array.reduce(0n, (acc, val) => acc + val)(arr); } function fromDecimal(val) { return BigInt(val.toString()); } function zeroNegatives(a) { return bigintMax(0n, a); } var BigIntOrd = { equals: (x, y) => x === y, compare: (first, second) => first < second ? -1 : first > second ? 1 : 0 }; // src/types/rational.ts var RationalSchema = import_evolution.TSchema.Struct({ numerator: import_evolution.TSchema.Integer, denominator: import_evolution.TSchema.Integer }); var rationalZero = { numerator: 0n, denominator: 1n }; function rationalFromInt(a) { return { numerator: a, denominator: 1n }; } function rationalFloor(a) { return divideOnChainCompatible(a.numerator, a.denominator); } function rationalCeil(a) { const intDiv = a.numerator / a.denominator; return a.numerator % a.denominator > 0n ? intDiv + 1n : intDiv; } function rationalNegate(a) { return { numerator: -a.numerator, denominator: a.denominator }; } function rationalAdd(a, b) { return { numerator: a.numerator * b.denominator + b.numerator * a.denominator, denominator: a.denominator * b.denominator }; } function rationalSub(a, b) { return { numerator: a.numerator * b.denominator - b.numerator * a.denominator, denominator: a.denominator * b.denominator }; } function rationalMul(a, b) { return { numerator: a.numerator * b.numerator, denominator: a.denominator * b.denominator }; } function rationalDiv(a, b) { if (b.numerator === 0n) throw new Error("Cannot divide by zero."); return { numerator: a.numerator * b.denominator, denominator: a.denominator * b.numerator }; } function rationalToFloat(a) { return Number(a.numerator) / Number(a.denominator); } // src/contracts/pyth-feed/types.ts var PythConfigurationSchema = import_evolution2.TSchema.Struct({ priceFeedId: import_evolution2.TSchema.Integer }); var OpaqueData = import_evolution2.Schema.typeSchema(import_evolution2.Data.DataSchema); var DerivedPythPriceSchema = import_evolution2.TSchema.Union( import_evolution2.TSchema.Struct( { Value: import_evolution2.TSchema.Struct( { configuration: PythConfigurationSchema }, { flatFields: true } ) }, { flatInUnion: true } ), import_evolution2.TSchema.Struct( { Inverse: import_evolution2.TSchema.Struct({ value: OpaqueData }, { flatFields: true }) }, { flatInUnion: true } ), import_evolution2.TSchema.Struct( { Divide: import_evolution2.TSchema.Struct( { x: OpaqueData, y: OpaqueData }, { flatFields: true } ) }, { flatInUnion: true } ) ); function fromDataDerivedPythPrice(data) { return import_evolution2.Data.withSchema(DerivedPythPriceSchema).fromCBORHex( import_evolution2.Data.toCBORHex(data) ); } function toDataDerivedPythPrice(derivedPythPrice) { return import_evolution2.Data.withSchema(DerivedPythPriceSchema).toData(derivedPythPrice); } var PythFeedParamsSchema = import_evolution2.TSchema.Struct({ config: DerivedPythPriceSchema, pythStatePolicyId: import_evolution2.TSchema.ByteArray }); function serialisePythFeedParams(params) { return import_evolution2.Data.withSchema(PythFeedParamsSchema).toData(params); } var PythFeedRedeemerSchema = import_evolution2.TSchema.Struct( { price: RationalSchema, auxiliaryData: OpaqueData }, { flatInUnion: true } ); function serialisePythFeedRedeemer(r) { return import_evolution2.Data.withSchema( PythFeedRedeemerSchema, DEFAULT_SCHEMA_OPTIONS ).toCBORHex(r); } var AikenIntervalIntervalBoundType = import_evolution2.TSchema.Union( import_evolution2.TSchema.TaggedStruct("NegativeInfinity", {}, { flatInUnion: true }), import_evolution2.TSchema.TaggedStruct( "Finite", { finite: import_evolution2.TSchema.Integer }, { flatInUnion: true } ), import_evolution2.TSchema.TaggedStruct("PositiveInfinity", {}, { flatInUnion: true }) ); var AikenIntervalIntervalBound = import_evolution2.TSchema.Struct({ bound_type: AikenIntervalIntervalBoundType, is_inclusive: import_evolution2.TSchema.Boolean }); var CardanoTransactionValidityRange = import_evolution2.TSchema.Struct({ lower_bound: AikenIntervalIntervalBound, upper_bound: AikenIntervalIntervalBound }); var PythStateDatumSchema = import_evolution2.TSchema.Struct( { governance: import_evolution2.TSchema.Struct( { wormhole: import_evolution2.TSchema.ByteArray, emitterChain: import_evolution2.TSchema.Integer, emitterAddress: import_evolution2.TSchema.ByteArray, seenSequence: import_evolution2.TSchema.Integer }, { flatInUnion: true } ), trustedSigners: import_evolution2.TSchema.Map( import_evolution2.TSchema.ByteArray, CardanoTransactionValidityRange ), deprecatedWithdrawScripts: import_evolution2.TSchema.Map( CardanoTransactionValidityRange, import_evolution2.TSchema.ByteArray ), withdraw_script: import_evolution2.TSchema.ByteArray }, { flatInUnion: true } ); function serialisePythStateDatum(r) { return import_evolution2.Data.withSchema( PythStateDatumSchema, DEFAULT_SCHEMA_OPTIONS ).toCBORHex(r); } function parsePythStateDatum(datum) { return import_evolution2.Data.withSchema( PythStateDatumSchema, DEFAULT_SCHEMA_OPTIONS ).fromCBORHex(datum); } var PythUpdatesRedeemerSchema = import_evolution2.TSchema.Array(import_evolution2.TSchema.ByteArray); function serialisePythUpdatesRedeemer(r) { return import_evolution2.Data.withSchema( PythUpdatesRedeemerSchema, DEFAULT_SCHEMA_OPTIONS ).toCBORHex(r); } // src/types/system-params.ts var import_ts_pattern = require("ts-pattern"); var import_ts_pattern2 = require("ts-pattern"); function fromSysParamsDerivedPythPrice(cfg) { return (0, import_ts_pattern.match)(cfg).returnType().with({ tag: "value", val: import_ts_pattern2.P.select() }, (val) => { return { Value: { configuration: { priceFeedId: BigInt(val.priceFeedId) } } }; }).with({ tag: "inverse", val: import_ts_pattern2.P.select() }, (val) => { return { Inverse: { value: toDataDerivedPythPrice(fromSysParamsDerivedPythPrice(val)) } }; }).with({ tag: "divide", val: import_ts_pattern2.P.select() }, (val) => { return { Divide: { x: toDataDerivedPythPrice(fromSysParamsDerivedPythPrice(val[0])), y: toDataDerivedPythPrice(fromSysParamsDerivedPythPrice(val[1])) } }; }).exhaustive(); } function fromSysParamsPythFeedParams(params) { return { config: fromSysParamsDerivedPythPrice(params.config), pythStatePolicyId: (0, import_lucid.fromHex)(params.pythStatePolicyId.unCurrencySymbol) }; } function getPythFeedConfig(cfg, iasset, collateralAsset) { const res = cfg.pythFeeds[`${(0, import_lucid.toText)((0, import_lucid.toHex)(iasset))}/${(0, import_lucid.toHex)(collateralAsset.currencySymbol)}.${(0, import_lucid.toHex)(collateralAsset.tokenName)}`]; if (res == null) throw new Error("No Pyth config known for such assets combination"); return res; } function toSystemParamsAsset(asset) { return [ { unCurrencySymbol: (0, import_lucid.toHex)(asset.currencySymbol) }, { unTokenName: (0, import_lucid.toText)((0, import_lucid.toHex)(asset.tokenName)) } ]; } function fromSystemParamsAsset(asset) { return { currencySymbol: (0, import_lucid.fromHex)(asset[0].unCurrencySymbol), tokenName: (0, import_lucid.fromHex)((0, import_lucid.fromText)(asset[1].unTokenName)) }; } function fromSystemParamsAssetLucid(asset) { return { currencySymbol: asset[0].unCurrencySymbol, tokenName: (0, import_lucid.fromText)(asset[1].unTokenName) }; } function fromSystemParamsScriptRef(ref) { return { outputIndex: ref.input.index, txHash: ref.input.transactionId }; } function fromSysParamsCredential(cred) { if (cred.contents.tag === "PublicKeyCredential") { return { type: "Key", hash: cred.contents.contents }; } return { type: "Script", hash: cred.contents.contents }; } function fromSysParamsStakeCredential(cred) { return { Inline: [ cred.contents.tag === "PublicKeyCredential" ? { PublicKeyCredential: [cred.contents.contents] } : { ScriptCredential: [cred.contents.contents] } ] }; } // src/utils/lucid-utils.ts var import_lucid2 = require("@lucid-evolution/lucid"); var import_ts_pattern3 = require("ts-pattern"); function getInlineDatumOrThrow(utxo) { if (utxo.datum != null) { return utxo.datum; } throw new Error( "Expected an inline datum for OutRef: " + JSON.stringify({ txHash: utxo.txHash, outputIndex: utxo.outputIndex }) ); } async function addrDetails(lucid) { const addr = await lucid.wallet().address(); let stakeCredential = void 0; try { stakeCredential = (0, import_lucid2.stakeCredentialOf)(addr); } catch (_) { } return [(0, import_lucid2.paymentCredentialOf)(addr), stakeCredential]; } function createScriptAddress(network, scriptHash, stakeCredential) { return (0, import_lucid2.credentialToAddress)( network, (0, import_lucid2.scriptHashToCredential)(scriptHash), stakeCredential ); } async function scriptRef(ref, lucid) { const utxos = await lucid.utxosByOutRef([ { txHash: ref.input.transactionId, outputIndex: ref.input.index } ]); if (utxos.length === 0) throw Error("Unable to locate script ref."); return utxos[0]; } async function submitTx(lucid, tx) { const txHash = await tx.complete().then((t) => t.sign.withWallet().complete()).then((t) => t.submit()); await lucid.awaitTx(txHash); } function balance(utxos) { return utxos.reduce((acc, utxo) => (0, import_lucid2.addAssets)(acc, utxo.assets), {}); } function estimateUtxoMinLovelace(protocolParameters, destinationAddr, assets, destinationDatum = void 0, scriptRef2 = void 0) { return (0, import_lucid2.calculateMinLovelaceFromUTxO)(protocolParameters.coinsPerUtxoByte, { address: destinationAddr, datumHash: (0, import_ts_pattern3.match)(destinationDatum).with({ kind: "hash", value: import_ts_pattern3.P.select() }, (dHash) => dHash).otherwise(() => null), datum: (0, import_ts_pattern3.match)(destinationDatum).with({ kind: "inline", value: import_ts_pattern3.P.select() }, (data) => import_lucid2.Data.to(data)).otherwise(() => null), assets, // Use dummy tx hash and out idx txHash: "0000000000000000000000000000000000000000000000000000000000000000", outputIndex: 0, scriptRef: scriptRef2 ?? null }); } // src/utils/utils.ts var fs = __toESM(require("fs")); var import_ts_pattern4 = require("ts-pattern"); function matchSingle(xs, mkErr) { return (0, import_ts_pattern4.match)(xs).with([import_ts_pattern4.P.select()], (res) => res).otherwise(() => { throw mkErr(xs); }); } function loadSystemParamsFromFile(file) { return JSON.parse(fs.readFileSync(file, "utf-8")); } function loadSystemParamsFromUrl(url) { return fetch(url).then((res) => res.json()).then((data) => data); } // src/utils/time-helpers.ts var ONE_SECOND = 1e3; var ONE_HOUR = 3600000n; var ONE_DAY = 86400000n; var ONE_YEAR = 31536000000n; // src/types/on-chain-decimal.ts var import_evolution3 = require("@evolution-sdk/evolution"); var OCD_DECIMAL_UNIT = 1000000n; var OnChainDecimalSchema = import_evolution3.TSchema.Struct({ getOnChainInt: import_evolution3.TSchema.Integer }); function ocdDiv(a, b) { return { getOnChainInt: divideOnChainCompatible( a.getOnChainInt * OCD_DECIMAL_UNIT, b.getOnChainInt ) }; } // src/contracts/interest-oracle/helpers.ts var unitaryInterestPrecision = 1000000000000000000n; function calculateUnitaryInterest(timePeriod, interestRate) { return timePeriod * interestRate * unitaryInterestPrecision / ONE_YEAR / OCD_DECIMAL_UNIT; } function calculateUnitaryInterestSinceOracleLastUpdated(now, oracleDatum) { return calculateUnitaryInterest( now - oracleDatum.lastUpdated, oracleDatum.interestRate.getOnChainInt ); } function calculateAccruedInterest(now, unitaryInterestSnapshot, mintedAmount, interestLastSettled, interestOracleDatum) { if (interestOracleDatum.unitaryInterest >= unitaryInterestSnapshot) { const interestFromPreviousRates = (interestOracleDatum.unitaryInterest - unitaryInterestSnapshot) * mintedAmount / unitaryInterestPrecision; const lastRateInterest = (now - interestOracleDatum.lastUpdated) * interestOracleDatum.interestRate.getOnChainInt * mintedAmount / ONE_YEAR / OCD_DECIMAL_UNIT; return interestFromPreviousRates + lastRateInterest; } else { return (now - interestLastSettled) * interestOracleDatum.interestRate.getOnChainInt * mintedAmount / ONE_YEAR / OCD_DECIMAL_UNIT; } } // src/contracts/price-oracle/helpers.ts var import_lucid3 = require("@lucid-evolution/lucid"); function oracleExpirationAwareValidity(currentSlot, biasTime, oracleExpiration, network) { const validateFrom = (0, import_lucid3.slotToUnixTime)(network, currentSlot - 1); const defaultValidateTo = validateFrom + biasTime; const cappedValidateTo = (0, import_lucid3.slotToUnixTime)( network, (0, import_lucid3.unixTimeToSlot)(network, oracleExpiration) - 1 ); const isOracleActuallyExpired = cappedValidateTo <= validateFrom; return { validFrom: validateFrom, validTo: isOracleActuallyExpired ? defaultValidateTo : Math.min(defaultValidateTo, cappedValidateTo) }; } // src/contracts/cdp/transactions.ts var import_ts_pattern14 = require("ts-pattern"); // src/contracts/cdp/helpers.ts var import_lucid4 = require("@lucid-evolution/lucid"); var import_ts_pattern5 = require("ts-pattern"); // src/utils/indigo-helpers.ts function calculateFeeFromRatio(feeRatio, amount) { if (amount < 0) { return 0n; } return rationalFloor(rationalMul(rationalFromInt(amount), feeRatio)); } // src/contracts/cdp/helpers.ts var import_cardano_offchain_common = require("@3rd-eye-labs/cardano-offchain-common"); function iassetValueOfCollateral(collateralAmt, oraclePrice) { return rationalFloor( rationalDiv(rationalFromInt(collateralAmt), oraclePrice) ); } function cdpCollateralRatioPercentage(currentSlot, iassetPrice, cdpUtxo, cdpContent, interestOracleDatum, network) { const currentTime = BigInt((0, import_lucid4.slotToUnixTime)(network, currentSlot)); return (0, import_ts_pattern5.match)(cdpContent.cdpFees).with({ ActiveCDPInterestTracking: import_ts_pattern5.P.select() }, (interest) => { const interestAmt = calculateAccruedInterest( currentTime, interest.unitaryInterestSnapshot, cdpContent.mintedAmt, interest.lastSettled, interestOracleDatum ); const collateral = (0, import_cardano_offchain_common.assetClassValueOf)( cdpUtxo.assets, cdpContent.collateralAsset ); const ratio = rationalDiv( rationalFromInt(collateral), rationalMul( rationalFromInt(cdpContent.mintedAmt + interestAmt), iassetPrice ) ); return Number(ratio.numerator * 100n / ratio.denominator); }).with({ FrozenCDPAccumulatedFees: import_ts_pattern5.P.any }, () => 0).exhaustive(); } function calculateIAssetRedemptionAmt(collateralAmt, mintedAmt, price, rmr) { return rationalCeil( rationalDiv( rationalAdd( rationalNegate(rationalDiv(rationalFromInt(collateralAmt), price)), rationalMul(rmr, rationalFromInt(mintedAmt)) ), rationalSub(rmr, rationalFromInt(1n)) ) ); } function calculateMinCollateralCappedIAssetRedemptionAmt(collateralAmt, mintedAmt, price, rmr, reimbursementRatio, minCollateral) { const uncappedMaxIAssetRedemptionAmt = calculateIAssetRedemptionAmt( collateralAmt, mintedAmt, price, rmr ); const uncappedMaxRedemptionLovelacesAmt = rationalFloor( rationalMul(price, rationalFromInt(uncappedMaxIAssetRedemptionAmt)) ); const maxReimburstment = calculateFeeFromRatio( reimbursementRatio, uncappedMaxRedemptionLovelacesAmt ); const doesMaxBreakMinCollateral = collateralAmt - uncappedMaxRedemptionLovelacesAmt + maxReimburstment < minCollateral; if (!doesMaxBreakMinCollateral) { return { uncappedIAssetRedemptionAmt: uncappedMaxIAssetRedemptionAmt, cappedIAssetRedemptionAmt: uncappedMaxIAssetRedemptionAmt }; } else if (collateralAmt <= minCollateral) { return { uncappedIAssetRedemptionAmt: uncappedMaxIAssetRedemptionAmt, cappedIAssetRedemptionAmt: 0n }; } else { const resLovelaces = rationalDiv( rationalFromInt(minCollateral - collateralAmt), rationalSub(reimbursementRatio, rationalFromInt(1n)) ); const resIAsset = rationalDiv(resLovelaces, price); return { uncappedIAssetRedemptionAmt: uncappedMaxIAssetRedemptionAmt, cappedIAssetRedemptionAmt: rationalFloor(resIAsset) }; } } function adjustPriceToDecimals(extraDecimals, price) { return extraDecimals === 0n ? price : extraDecimals > 0n ? rationalMul(price, rationalFromInt(10n ** extraDecimals)) : rationalDiv(price, rationalFromInt(10n ** -extraDecimals)); } // src/contracts/stability-pool/types-new.ts var import_evolution4 = require("@evolution-sdk/evolution"); var import_ts_pattern6 = require("ts-pattern"); var import_fp_ts2 = require("fp-ts"); var import_cardano_offchain_common2 = require("@3rd-eye-labs/cardano-offchain-common"); var SPIntegerSchema = import_evolution4.TSchema.Struct({ value: import_evolution4.TSchema.Integer }); var AccountActionSchema = import_evolution4.TSchema.Union( import_evolution4.TSchema.Literal("Create", { flatInUnion: true }), import_evolution4.TSchema.Struct( { Adjust: import_evolution4.TSchema.Struct( { amount: import_evolution4.TSchema.Integer, outputAddress: import_cardano_offchain_common2.AddressSchema }, { flatFields: true } ) }, { flatInUnion: true } ), import_evolution4.TSchema.Struct( { Close: import_evolution4.TSchema.Struct( { outputAddress: import_cardano_offchain_common2.AddressSchema, maxTxFee: import_evolution4.TSchema.Integer }, { flatFields: true } ) }, { flatInUnion: true } ) ); var SumSnapshotSchema = import_evolution4.TSchema.Struct({ sumVal: SPIntegerSchema, isLastInEpoch: import_evolution4.TSchema.Boolean, isFirstSnapshot: import_evolution4.TSchema.Boolean }); var EpochToScaleKeySchema = import_evolution4.TSchema.Struct({ epoch: import_evolution4.TSchema.Integer, scale: import_evolution4.TSchema.Integer }); var EpochToScaleToSumEntrySchema = import_evolution4.TSchema.Tuple([ EpochToScaleKeySchema, SumSnapshotSchema ]); var StateSnapshotSchema = import_evolution4.TSchema.Struct({ productVal: SPIntegerSchema, depositVal: SPIntegerSchema, epoch: import_evolution4.TSchema.Integer, scale: import_evolution4.TSchema.Integer }); var AssetSnapshotSchema = import_evolution4.TSchema.Struct({ currentSumVal: SPIntegerSchema, epoch2scale2sum: import_evolution4.TSchema.Array(EpochToScaleToSumEntrySchema) }); var AssetStateSchema = import_evolution4.TSchema.Tuple([import_cardano_offchain_common2.AssetClassSchema, AssetSnapshotSchema]); var StabilityPoolContentSchema = import_evolution4.TSchema.Struct({ iasset: import_evolution4.TSchema.ByteArray, state: StateSnapshotSchema, assetStates: import_evolution4.TSchema.Array(AssetStateSchema) }); var AccountContentSchema = import_evolution4.TSchema.Struct({ owner: import_evolution4.TSchema.ByteArray, iasset: import_evolution4.TSchema.ByteArray, state: StateSnapshotSchema, assetSums: import_evolution4.TSchema.Array(import_evolution4.TSchema.Tuple([import_cardano_offchain_common2.AssetClassSchema, SPIntegerSchema])), request: import_evolution4.TSchema.NullOr(AccountActionSchema), lastRequestProcessingTime: import_evolution4.TSchema.Integer }); var SnapshotEpochToScaleToSumContentSchema = import_evolution4.TSchema.Struct({ snapshot: import_evolution4.TSchema.Array(EpochToScaleToSumEntrySchema), iasset: import_evolution4.TSchema.ByteArray, collateralAsset: import_cardano_offchain_common2.AssetClassSchema }); var StabilityPoolDatumSchema = import_evolution4.TSchema.Union( import_evolution4.TSchema.Struct( { StabilityPool: StabilityPoolContentSchema }, { flatInUnion: true } ), import_evolution4.TSchema.Struct({ Account: AccountContentSchema }, { flatInUnion: true }), import_evolution4.TSchema.Struct( { SnapshotEpochToScaleToSum: SnapshotEpochToScaleToSumContentSchema }, { flatInUnion: true } ) ); var E2S2SIndexSchema = import_evolution4.TSchema.Union( import_evolution4.TSchema.Struct( { StabilityPoolListIdx: import_evolution4.TSchema.Integer }, { flatInUnion: true } ), import_evolution4.TSchema.Struct( { RefInputIdx: import_evolution4.TSchema.Struct( { refInputIdx: import_evolution4.TSchema.Integer, snapshotListIdx: import_evolution4.TSchema.Integer }, { flatFields: true } ) }, { flatInUnion: true } ) ); var E2S2SIndicesPerAssetSchema = import_evolution4.TSchema.Array( import_evolution4.TSchema.Tuple([E2S2SIndexSchema, import_evolution4.TSchema.NullOr(E2S2SIndexSchema)]) ); var ProcessRequestAccountContentSchema = import_evolution4.TSchema.Struct( { poolInputIdx: import_evolution4.TSchema.Integer, accountInputIdx: import_evolution4.TSchema.Integer, e2s2sIdxs: E2S2SIndicesPerAssetSchema, currentTime: import_evolution4.TSchema.Integer }, { flatFields: true } ); var StabilityPoolRedeemerSchema = import_evolution4.TSchema.Union( import_evolution4.TSchema.Struct({ RequestAction: AccountActionSchema }, { flatInUnion: true }), import_evolution4.TSchema.Struct( { ProcessRequestPool: import_evolution4.TSchema.Struct( { poolInputIdx: import_evolution4.TSchema.Integer, accountInputIdx: import_evolution4.TSchema.Integer }, { flatFields: true } ) }, { flatInUnion: true } ), import_evolution4.TSchema.Struct( { ProcessRequestAccount: ProcessRequestAccountContentSchema }, { flatInUnion: true } ), import_evolution4.TSchema.Literal("AnnulRequest", { flatInUnion: true }), import_evolution4.TSchema.Struct( { LiquidateCDP: import_evolution4.TSchema.Struct( { cdpIdx: import_evolution4.TSchema.Integer }, { flatFields: true } ) }, { flatInUnion: true } ), import_evolution4.TSchema.Literal("RecordEpochToScaleToSum", { flatInUnion: true }), import_evolution4.TSchema.Literal("UpgradeVersion", { flatInUnion: true }) ); var ActionReturnDatumSchema = import_evolution4.TSchema.Union( import_evolution4.TSchema.Struct( { IndigoStabilityPoolAccountAdjustment: import_cardano_offchain_common2.OutputReferenceSchema }, { flatInUnion: true } ), import_evolution4.TSchema.Struct( { IndigoStabilityPoolAccountClosure: import_cardano_offchain_common2.OutputReferenceSchema }, { flatInUnion: true } ) ); function serialiseActionReturnDatum(d) { return import_evolution4.Data.withSchema( ActionReturnDatumSchema, DEFAULT_SCHEMA_OPTIONS ).toCBORHex(d); } function serialiseStabilityPoolRedeemer(r) { return import_evolution4.Data.withSchema( StabilityPoolRedeemerSchema, DEFAULT_SCHEMA_OPTIONS ).toCBORHex(r); } function parseStabilityPoolRedeemer(datum) { try { return import_fp_ts2.option.some( import_evolution4.Data.withSchema( StabilityPoolRedeemerSchema, DEFAULT_SCHEMA_OPTIONS ).fromCBORHex(datum) ); } catch (_) { return import_fp_ts2.option.none; } } function parseStabilityPoolRedeemerOrThrow(datum) { return import_fp_ts2.function.pipe( parseStabilityPoolRedeemer(datum), import_fp_ts2.option.match(() => { throw new Error("Expected a StabilityPoolRedeemer datum."); }, import_fp_ts2.function.identity) ); } function serialiseStabilityPoolDatum(d, useIndefiniteMaps = false) { return import_evolution4.Data.withSchema(StabilityPoolDatumSchema, { ...DEFAULT_SCHEMA_OPTIONS, useIndefiniteMaps }).toCBORHex(d); } function parseStabilityPoolDatum(datum) { try { return (0, import_ts_pattern6.match)( import_evolution4.Data.withSchema( StabilityPoolDatumSchema, DEFAULT_SCHEMA_OPTIONS ).fromCBORHex(datum) ).with({ StabilityPool: import_ts_pattern6.P.select() }, (res) => import_fp_ts2.option.some(res)).otherwise(() => import_fp_ts2.option.none); } catch (_) { return import_fp_ts2.option.none; } } function parseStabilityPoolDatumOrThrow(datum) { return import_fp_ts2.function.pipe( parseStabilityPoolDatum(datum), import_fp_ts2.option.match(() => { throw new Error("Expected stability pool datum."); }, import_fp_ts2.function.identity) ); } function parseAccountDatum(datum) { try { return (0, import_ts_pattern6.match)( import_evolution4.Data.withSchema( StabilityPoolDatumSchema, DEFAULT_SCHEMA_OPTIONS ).fromCBORHex(datum) ).with({ Account: import_ts_pattern6.P.select() }, (res) => import_fp_ts2.option.some(res)).otherwise(() => import_fp_ts2.option.none); } catch (_) { return import_fp_ts2.option.none; } } function parseAccountDatumOrThrow(datum) { return import_fp_ts2.function.pipe( parseAccountDatum(datum), import_fp_ts2.option.match(() => { throw new Error("Expected account datum."); }, import_fp_ts2.function.identity) ); } function parseSnapshotEpochToScaleToSumDatum(datum) { try { return (0, import_ts_pattern6.match)( import_evolution4.Data.withSchema( StabilityPoolDatumSchema, DEFAULT_SCHEMA_OPTIONS ).fromCBORHex(datum) ).with({ SnapshotEpochToScaleToSum: import_ts_pattern6.P.select() }, (res) => import_fp_ts2.option.some(res)).otherwise(() => import_fp_ts2.option.none); } catch (_) { return import_fp_ts2.option.none; } } function parseSnapshotEpochToScaleToSumDatumOrThrow(datum) { return import_fp_ts2.function.pipe( parseSnapshotEpochToScaleToSumDatum(datum), import_fp_ts2.option.match(() => { throw new Error("Expected snapshot e2s2s datum."); }, import_fp_ts2.function.identity) ); } var spPrecision = 1000000000000000000n; function mkSPInteger(value) { return { value: value * spPrecision }; } function fromSPInteger(value) { return divideOnChainCompatible(value.value, spPrecision); } function spAdd(a, b) { return { value: a.value + b.value }; } function spSub(a, b) { return { value: a.value - b.value }; } function spMul(a, b) { return { value: divideOnChainCompatible(a.value * b.value, spPrecision) }; } function spDiv(a, b) { return { value: divideOnChainCompatible(a.value * spPrecision, b.value) }; } function spZeroNegatives(a) { return { value: zeroNegatives(a.value) }; } // src/contracts/stability-pool/helpers.ts var import_lucid8 = require("@lucid-evolution/lucid"); var import_fp_ts4 = require("fp-ts"); var import_cardano_offchain_common3 = require("@3rd-eye-labs/cardano-offchain-common"); // src/utils/array-utils.ts var import_fp_ts3 = require("fp-ts"); function shuffle(arr) { const source = [...arr]; for (let i = source.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [source[i], source[j]] = [source[j], source[i]]; } return source; } function insertSorted(arr, item, ord) { if (arr.length === 0) { return [item]; } const arrOrd = ord.compare(arr[0], arr[arr.length - 1]); if (arrOrd === 0) { if (ord.compare(arr[0], item) === -1) { return [...arr, item]; } else { return [item, ...arr]; } } for (let i = 0; i < arr.length; i++) { if (ord.compare(arr[i], item) !== arrOrd) { return [...import_fp_ts3.array.takeLeft(i)(arr), item, ...import_fp_ts3.array.takeRight(arr.length - i)(arr)]; } } return [...arr, item]; } var repsertReadonlyArr = (predicate, val, mkKey) => (arr) => { const idx = import_fp_ts3.function.pipe( arr, import_fp_ts3.readonlyArray.findIndex(([key, _]) => predicate(key)) ); const res = import_fp_ts3.function.pipe( idx, import_fp_ts3.option.chain( (i) => import_fp_ts3.function.pipe( arr, import_fp_ts3.readonlyArray.modifyAt(i, ([key, _]) => [key, val]) ) ) ); return import_fp_ts3.function.pipe( res, import_fp_ts3.option.getOrElse(() => [ ...arr, [mkKey(), val] ]) ); }; var repsertWithReadonlyArr = (predicate, replaceVal, newVal, mkKey) => (arr) => { const idx = import_fp_ts3.function.pipe( arr, import_fp_ts3.readonlyArray.findIndex(([key, _]) => predicate(key)) ); const res = import_fp_ts3.function.pipe( idx, import_fp_ts3.option.chain( (i) => import_fp_ts3.function.pipe( arr, import_fp_