@indigo-labs/indigo-sdk 0.5.5 → 0.5.6

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 (204) hide show
  1. package/package.json +11 -1
  2. package/.claude/settings.local.json +0 -7
  3. package/.github/workflows/ci.yml +0 -66
  4. package/.husky/pre-commit +0 -1
  5. package/.nvmrc +0 -1
  6. package/.prettierignore +0 -1
  7. package/.prettierrc +0 -6
  8. package/eslint.config.mjs +0 -42
  9. package/scripts/bench.sh +0 -62
  10. package/scripts/run-repeat.sh +0 -22
  11. package/src/contracts/cdp/helpers.ts +0 -173
  12. package/src/contracts/cdp/scripts.ts +0 -70
  13. package/src/contracts/cdp/transactions.ts +0 -1584
  14. package/src/contracts/cdp/types-new.ts +0 -277
  15. package/src/contracts/cdp/types.ts +0 -43
  16. package/src/contracts/cdp-creator/queries.ts +0 -30
  17. package/src/contracts/cdp-creator/scripts.ts +0 -45
  18. package/src/contracts/cdp-creator/types-new.ts +0 -50
  19. package/src/contracts/cdp-creator/types.ts +0 -24
  20. package/src/contracts/collector/scripts.ts +0 -32
  21. package/src/contracts/collector/transactions.ts +0 -50
  22. package/src/contracts/collector/types-new.ts +0 -17
  23. package/src/contracts/execute/scripts.ts +0 -57
  24. package/src/contracts/execute/types-new.ts +0 -44
  25. package/src/contracts/execute/types.ts +0 -24
  26. package/src/contracts/gov/helpers.ts +0 -351
  27. package/src/contracts/gov/scripts.ts +0 -41
  28. package/src/contracts/gov/transactions.ts +0 -1607
  29. package/src/contracts/gov/types-new.ts +0 -268
  30. package/src/contracts/gov/types.ts +0 -22
  31. package/src/contracts/iasset/helpers.ts +0 -170
  32. package/src/contracts/iasset/queries.ts +0 -102
  33. package/src/contracts/iasset/scripts.ts +0 -38
  34. package/src/contracts/iasset/types.ts +0 -154
  35. package/src/contracts/initialize/actions.ts +0 -789
  36. package/src/contracts/initialize/helpers.ts +0 -616
  37. package/src/contracts/initialize/types.ts +0 -116
  38. package/src/contracts/interest-collection/helpers.ts +0 -19
  39. package/src/contracts/interest-collection/queries.ts +0 -66
  40. package/src/contracts/interest-collection/scripts.ts +0 -44
  41. package/src/contracts/interest-collection/transactions.ts +0 -433
  42. package/src/contracts/interest-collection/types-new.ts +0 -50
  43. package/src/contracts/interest-collection/types.ts +0 -26
  44. package/src/contracts/interest-oracle/helpers.ts +0 -61
  45. package/src/contracts/interest-oracle/scripts.ts +0 -18
  46. package/src/contracts/interest-oracle/transactions.ts +0 -151
  47. package/src/contracts/interest-oracle/types-new.ts +0 -32
  48. package/src/contracts/interest-oracle/types.ts +0 -16
  49. package/src/contracts/one-shot/scripts.ts +0 -12
  50. package/src/contracts/one-shot/transactions.ts +0 -66
  51. package/src/contracts/one-shot/types.ts +0 -22
  52. package/src/contracts/poll/helpers.ts +0 -37
  53. package/src/contracts/poll/scripts.ts +0 -71
  54. package/src/contracts/poll/types-poll-manager.ts +0 -20
  55. package/src/contracts/poll/types-poll-new.ts +0 -196
  56. package/src/contracts/poll/types-poll-shard.ts +0 -16
  57. package/src/contracts/price-oracle/helpers.ts +0 -30
  58. package/src/contracts/price-oracle/scripts.ts +0 -18
  59. package/src/contracts/price-oracle/transactions.ts +0 -115
  60. package/src/contracts/price-oracle/types-new.ts +0 -50
  61. package/src/contracts/price-oracle/types.ts +0 -16
  62. package/src/contracts/pyth-feed/helpers.ts +0 -82
  63. package/src/contracts/pyth-feed/scripts.ts +0 -15
  64. package/src/contracts/pyth-feed/types.ts +0 -181
  65. package/src/contracts/rob/helpers.ts +0 -666
  66. package/src/contracts/rob/scripts.ts +0 -35
  67. package/src/contracts/rob/transactions.ts +0 -423
  68. package/src/contracts/rob/types-new.ts +0 -128
  69. package/src/contracts/rob/types.ts +0 -16
  70. package/src/contracts/rob-leverage/helpers.ts +0 -422
  71. package/src/contracts/rob-leverage/transactions.ts +0 -368
  72. package/src/contracts/stability-pool/helpers.ts +0 -798
  73. package/src/contracts/stability-pool/queries.ts +0 -132
  74. package/src/contracts/stability-pool/scripts.ts +0 -51
  75. package/src/contracts/stability-pool/transactions.ts +0 -921
  76. package/src/contracts/stability-pool/types-new.ts +0 -385
  77. package/src/contracts/stability-pool/types.ts +0 -25
  78. package/src/contracts/stableswap/helpers.ts +0 -507
  79. package/src/contracts/stableswap/scripts.ts +0 -37
  80. package/src/contracts/stableswap/transactions.ts +0 -475
  81. package/src/contracts/stableswap/types-new.ts +0 -131
  82. package/src/contracts/stableswap/types.ts +0 -17
  83. package/src/contracts/staking/helpers.ts +0 -136
  84. package/src/contracts/staking/scripts.ts +0 -41
  85. package/src/contracts/staking/transactions.ts +0 -349
  86. package/src/contracts/staking/types-new.ts +0 -137
  87. package/src/contracts/staking/types.ts +0 -17
  88. package/src/contracts/treasury/helpers.ts +0 -21
  89. package/src/contracts/treasury/queries.ts +0 -100
  90. package/src/contracts/treasury/scripts.ts +0 -27
  91. package/src/contracts/treasury/transactions.ts +0 -334
  92. package/src/contracts/treasury/types-new.ts +0 -69
  93. package/src/contracts/treasury/types.ts +0 -14
  94. package/src/contracts/version-registry/scripts.ts +0 -29
  95. package/src/contracts/version-registry/types-new.ts +0 -18
  96. package/src/contracts/version-registry/types.ts +0 -17
  97. package/src/index.ts +0 -99
  98. package/src/scripts/always-fail-validator.ts +0 -7
  99. package/src/scripts/auth-token-policy.ts +0 -24
  100. package/src/scripts/iasset-policy.ts +0 -23
  101. package/src/types/evolution-schema-options.ts +0 -16
  102. package/src/types/generic.ts +0 -52
  103. package/src/types/multisig.ts +0 -48
  104. package/src/types/on-chain-decimal.ts +0 -57
  105. package/src/types/rational.ts +0 -76
  106. package/src/types/system-params.ts +0 -463
  107. package/src/utils/array-utils.ts +0 -108
  108. package/src/utils/bigint-utils.ts +0 -35
  109. package/src/utils/helper-txs.ts +0 -31
  110. package/src/utils/indigo-helpers.ts +0 -17
  111. package/src/utils/lucid-utils.ts +0 -125
  112. package/src/utils/oracle-helpers.ts +0 -62
  113. package/src/utils/pyth/decode.ts +0 -223
  114. package/src/utils/pyth/encode.ts +0 -262
  115. package/src/utils/pyth/index.ts +0 -14
  116. package/src/utils/pyth/types.ts +0 -87
  117. package/src/utils/time-helpers.ts +0 -4
  118. package/src/utils/utils.ts +0 -25
  119. package/src/validators/always-succeed-validator.ts +0 -6
  120. package/src/validators/cdp-creator-validator.ts +0 -7
  121. package/src/validators/cdp-redeem-validator.ts +0 -7
  122. package/src/validators/cdp-validator.ts +0 -7
  123. package/src/validators/collector-validator.ts +0 -7
  124. package/src/validators/execute-validator.ts +0 -7
  125. package/src/validators/governance-validator.ts +0 -7
  126. package/src/validators/iasset-validator.ts +0 -7
  127. package/src/validators/interest-collection-validator.ts +0 -7
  128. package/src/validators/interest-oracle-validator.ts +0 -7
  129. package/src/validators/one-shot-policy.ts +0 -7
  130. package/src/validators/poll-manager-validator.ts +0 -7
  131. package/src/validators/poll-shard-validator.ts +0 -7
  132. package/src/validators/price-oracle-validator.ts +0 -7
  133. package/src/validators/pyth-feed-validator.ts +0 -7
  134. package/src/validators/rob-validator.ts +0 -7
  135. package/src/validators/stability-pool-validator.ts +0 -7
  136. package/src/validators/stableswap-validator.ts +0 -7
  137. package/src/validators/staking-validator.ts +0 -7
  138. package/src/validators/treasury-validator.ts +0 -7
  139. package/src/validators/version-record-policy.ts +0 -7
  140. package/src/validators/version-registry-validator.ts +0 -7
  141. package/tests/always-succeed/script.ts +0 -7
  142. package/tests/array-utils.test.ts +0 -92
  143. package/tests/bigint-utils.test.ts +0 -41
  144. package/tests/cdp/actions.ts +0 -680
  145. package/tests/cdp/cdp-helpers.ts +0 -55
  146. package/tests/cdp/cdp-queries.ts +0 -423
  147. package/tests/cdp/cdp.test.ts +0 -6730
  148. package/tests/cdp/transactions-mutated.ts +0 -1733
  149. package/tests/data/system-params.json +0 -1155
  150. package/tests/datums.test.ts +0 -302
  151. package/tests/endpoints/initialize.ts +0 -78
  152. package/tests/endpoints/interest-collector.ts +0 -37
  153. package/tests/endpoints/treasury.ts +0 -70
  154. package/tests/gov/actions.ts +0 -381
  155. package/tests/gov/gov.test.ts +0 -5147
  156. package/tests/gov/governance-queries.ts +0 -37
  157. package/tests/hash-checks.test.ts +0 -112
  158. package/tests/indigo-test-helpers.ts +0 -99
  159. package/tests/initialize.test.ts +0 -79
  160. package/tests/interest-calculations.test.ts +0 -120
  161. package/tests/interest-collection/interest-collection.test.ts +0 -843
  162. package/tests/interest-collection/transactions-mutated.ts +0 -260
  163. package/tests/interest-oracle.test.ts +0 -93
  164. package/tests/mock/assets-mock.ts +0 -243
  165. package/tests/mock/protocol-params-mock.ts +0 -21
  166. package/tests/price-oracle/actions.ts +0 -161
  167. package/tests/price-oracle/price-oracle-queries.ts +0 -12
  168. package/tests/price-oracle/price-oracle.test.ts +0 -228
  169. package/tests/price-oracle/transactions-mutated.ts +0 -59
  170. package/tests/pyth/endpoints.ts +0 -96
  171. package/tests/pyth/helpers.ts +0 -37
  172. package/tests/pyth/pyth-encoding.test.ts +0 -376
  173. package/tests/pyth/pyth-feeds.test.ts +0 -943
  174. package/tests/pyth/pyth-indigo.test.ts +0 -505
  175. package/tests/pyth/pyth.test.ts +0 -299
  176. package/tests/queries/collector-queries.ts +0 -27
  177. package/tests/queries/execute-queries.ts +0 -47
  178. package/tests/queries/iasset-queries.ts +0 -149
  179. package/tests/queries/interest-oracle-queries.ts +0 -12
  180. package/tests/queries/poll-queries.ts +0 -97
  181. package/tests/queries/staking-queries.ts +0 -54
  182. package/tests/rob/actions.ts +0 -56
  183. package/tests/rob/rob-leverage.test.ts +0 -2555
  184. package/tests/rob/rob-queries.ts +0 -95
  185. package/tests/rob/rob.test.ts +0 -3677
  186. package/tests/rob/transactions-mutated.ts +0 -844
  187. package/tests/script-size.test.ts +0 -240
  188. package/tests/setup.ts +0 -135
  189. package/tests/stability-pool/actions.ts +0 -229
  190. package/tests/stability-pool.test.ts +0 -6491
  191. package/tests/stableswap/stableswap-actions.ts +0 -83
  192. package/tests/stableswap/stableswap-queries.ts +0 -98
  193. package/tests/stableswap/stableswap.test.ts +0 -4471
  194. package/tests/stableswap/transactions-mutated.ts +0 -348
  195. package/tests/staking.test.ts +0 -172
  196. package/tests/test-helpers.ts +0 -94
  197. package/tests/treasury/actions.ts +0 -67
  198. package/tests/treasury/treasury.test.ts +0 -320
  199. package/tests/utils/asserts.ts +0 -87
  200. package/tests/utils/benchmark-utils.ts +0 -130
  201. package/tests/utils/index.ts +0 -168
  202. package/tsconfig.build.json +0 -4
  203. package/tsconfig.json +0 -27
  204. package/vitest.config.ts +0 -11
@@ -1,1733 +0,0 @@
1
- import {
2
- addAssets,
3
- Data,
4
- fromHex,
5
- LucidEvolution,
6
- Credential,
7
- OutRef,
8
- toHex,
9
- TxBuilder,
10
- UTxO,
11
- getInputIndices,
12
- credentialToAddress,
13
- validatorToScriptHash,
14
- credentialToRewardAddress,
15
- scriptHashToCredential,
16
- } from '@lucid-evolution/lucid';
17
- import {
18
- fromSystemParamsAsset,
19
- fromSystemParamsScriptRef,
20
- SystemParams,
21
- } from '../../src/types/system-params';
22
- import {
23
- addrDetails,
24
- calculateMinCollateralCappedIAssetRedemptionAmt,
25
- createScriptAddress,
26
- getInlineDatumOrThrow,
27
- matchSingle,
28
- mkPriceOracleValidator,
29
- mkTreasuryValidatorFromSP,
30
- ONE_SECOND,
31
- PriceOracleParams,
32
- treasuryFeeTx,
33
- } from '../../src';
34
- import {
35
- parseCdpDatumOrThrow,
36
- serialiseCdpDatum,
37
- serialiseCdpRedeemer,
38
- serialiseRedeemCdpWithdrawalRedeemer,
39
- } from '../../src/contracts/cdp/types-new';
40
- import {
41
- parseCollateralAssetDatumOrThrow,
42
- parseIAssetDatumOrThrow,
43
- } from '../../src/contracts/iasset/types';
44
- import {
45
- parsePriceOracleDatum,
46
- serialisePriceOracleDatum,
47
- serialisePriceOracleRedeemer,
48
- } from '../../src/contracts/price-oracle/types-new';
49
- import { parseInterestOracleDatum } from '../../src/contracts/interest-oracle/types-new';
50
- import { parseGovDatumOrThrow } from '../../src/contracts/gov/types-new';
51
- import { match, P } from 'ts-pattern';
52
- import {
53
- calculateAccruedInterest,
54
- calculateUnitaryInterestSinceOracleLastUpdated,
55
- } from '../../src/contracts/interest-oracle/helpers';
56
- import { calculateFeeFromRatio } from '../../src/utils/indigo-helpers';
57
- import {
58
- AssetClass,
59
- assetClassValueOf,
60
- mkAssetsOf,
61
- mkLovelacesOf,
62
- } from '@3rd-eye-labs/cardano-offchain-common';
63
- import { bigintMin } from '../../src/utils/bigint-utils';
64
- import { oracleExpirationAwareValidity } from '../../src/contracts/price-oracle/helpers';
65
- import {
66
- findAllNecessaryOrefs,
67
- findCdp,
68
- findPriceOracleFromCollateralAsset,
69
- } from './cdp-queries';
70
- import { collectInterestTx } from '../../src/contracts/interest-collection/transactions';
71
- import { findCollateralAsset, findIAsset } from '../queries/iasset-queries';
72
- import { findInterestOracle } from '../queries/interest-oracle-queries';
73
- import { AssetInfo } from '../endpoints/initialize';
74
- import { LucidContext } from '../test-helpers';
75
- import { option as O, function as F } from 'fp-ts';
76
- import { findPriceOracle } from '../price-oracle/price-oracle-queries';
77
- import { findRandomNonAdminInterestCollector } from '../../src/contracts/interest-collection/queries';
78
- import {
79
- serialiseCDPCreatorDatum,
80
- serialiseCDPCreatorRedeemer,
81
- } from '../../src/contracts/cdp-creator/types-new';
82
- import {
83
- CollectInterestVariation,
84
- testCollectInterest,
85
- } from '../interest-collection/transactions-mutated';
86
- import { findRandomTreasuryUtxoWithOnlyAda } from '../../src/contracts/treasury/queries';
87
- import {
88
- Rational,
89
- rationalFloor,
90
- rationalFromInt,
91
- rationalMul,
92
- } from '../../src/types/rational';
93
- import { retrieveAdjustedPrice } from '../../src/utils/oracle-helpers';
94
- import * as Core from '@evolution-sdk/evolution';
95
-
96
- export async function mutatedRedeemCdp(
97
- /**
98
- * When the goal is to redeem the maximum possible, just pass in the total minted amount of the CDP.
99
- * The logic will automatically cap the amount to the max.
100
- */
101
- attemptedRedemptionIAssetAmt: bigint,
102
- cdpOref: OutRef,
103
- iassetOref: OutRef,
104
- collateralAssetOref: OutRef,
105
- priceOracleOref: OutRef | undefined,
106
- interestOracleOref: OutRef,
107
- interestCollectorOref: OutRef,
108
- govOref: OutRef,
109
- sysParams: SystemParams,
110
- lucid: LucidEvolution,
111
- pythMessage?: string,
112
- ): Promise<TxBuilder> {
113
- const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
114
-
115
- const cdpRefScriptUtxo = matchSingle(
116
- await lucid.utxosByOutRef([
117
- fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef),
118
- ]),
119
- (_) => new Error('Expected a single cdp Ref Script UTXO'),
120
- );
121
-
122
- const cdpRedeemRefScriptUtxo = matchSingle(
123
- await lucid.utxosByOutRef([
124
- fromSystemParamsScriptRef(
125
- sysParams.scriptReferences.cdpRedeemValidatorRef,
126
- ),
127
- ]),
128
- (_) => new Error('Expected a single cdp redeem Ref Script UTXO'),
129
- );
130
-
131
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
132
- await lucid.utxosByOutRef([
133
- fromSystemParamsScriptRef(
134
- sysParams.scriptReferences.iAssetTokenPolicyRef,
135
- ),
136
- ]),
137
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
138
- );
139
-
140
- const cdpUtxo = matchSingle(
141
- await lucid.utxosByOutRef([cdpOref]),
142
- (_) => new Error('Expected a single cdp UTXO'),
143
- );
144
- const cdpDatum = parseCdpDatumOrThrow(getInlineDatumOrThrow(cdpUtxo));
145
-
146
- const iassetUtxo = matchSingle(
147
- await lucid.utxosByOutRef([iassetOref]),
148
- (_) => new Error('Expected a single iasset UTXO'),
149
- );
150
- const iassetDatum = parseIAssetDatumOrThrow(
151
- getInlineDatumOrThrow(iassetUtxo),
152
- );
153
-
154
- const collateralAssetUtxo = matchSingle(
155
- await lucid.utxosByOutRef([collateralAssetOref]),
156
- (_) => new Error('Expected a single iasset UTXO'),
157
- );
158
- const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
159
- getInlineDatumOrThrow(collateralAssetUtxo),
160
- );
161
-
162
- const isDelisted = match(collateralAssetDatum.priceInfo)
163
- .with({ Delisted: P.any }, () => true)
164
- .otherwise(() => false);
165
-
166
- if (!isDelisted && priceOracleOref === undefined) {
167
- throw new Error('Missing price oracle');
168
- }
169
-
170
- const [adjustedPrice, priceOracleUtxo] = await retrieveAdjustedPrice(
171
- iassetDatum.assetName,
172
- collateralAssetDatum.collateralAsset,
173
- collateralAssetDatum.priceInfo,
174
- collateralAssetDatum.extraDecimals,
175
- priceOracleOref,
176
- pythMessage,
177
- sysParams.pythConfig,
178
- lucid,
179
- );
180
-
181
- const interestOracleUtxo = matchSingle(
182
- await lucid.utxosByOutRef([interestOracleOref]),
183
- (_) => new Error('Expected a single interest oracle UTXO'),
184
- );
185
- const interestOracleDatum = parseInterestOracleDatum(
186
- getInlineDatumOrThrow(interestOracleUtxo),
187
- );
188
-
189
- const govUtxo = matchSingle(
190
- await lucid.utxosByOutRef([govOref]),
191
- (_) => new Error('Expected a single gov UTXO'),
192
- );
193
- const govDatum = parseGovDatumOrThrow(getInlineDatumOrThrow(govUtxo));
194
-
195
- const interestAmt = match(cdpDatum.cdpFees)
196
- .with({ FrozenCDPAccumulatedFees: P.any }, () => {
197
- throw new Error('CDP fees wrong');
198
- })
199
- .with({ ActiveCDPInterestTracking: P.select() }, (interest) => {
200
- return calculateAccruedInterest(
201
- currentTime,
202
- interest.unitaryInterestSnapshot,
203
- cdpDatum.mintedAmt,
204
- interest.lastSettled,
205
- interestOracleDatum,
206
- );
207
- })
208
- .exhaustive();
209
-
210
- const collateralAmt = assetClassValueOf(
211
- cdpUtxo.assets,
212
- cdpDatum.collateralAsset,
213
- );
214
-
215
- const totalCdpDebt = cdpDatum.mintedAmt + interestAmt;
216
-
217
- const [isPartial, redemptionIAssetAmt] = (() => {
218
- const res = calculateMinCollateralCappedIAssetRedemptionAmt(
219
- collateralAmt,
220
- totalCdpDebt,
221
- adjustedPrice,
222
- collateralAssetDatum.redemptionRatio,
223
- iassetDatum.redemptionReimbursementRatio,
224
- BigInt(collateralAssetDatum.minCollateralAmt),
225
- );
226
-
227
- const redemptionAmt = bigintMin(
228
- attemptedRedemptionIAssetAmt,
229
- res.cappedIAssetRedemptionAmt,
230
- );
231
-
232
- return [redemptionAmt < res.cappedIAssetRedemptionAmt, redemptionAmt];
233
- })();
234
-
235
- if (redemptionIAssetAmt <= 0) {
236
- throw new Error("There's no iAssets available for redemption.");
237
- }
238
-
239
- const redemptionCollateralAmt = rationalFloor(
240
- rationalMul(adjustedPrice, rationalFromInt(redemptionIAssetAmt)),
241
- );
242
-
243
- const isPublicRedemption =
244
- !govDatum.protocolParams.cdpRedemptionRequiredSignature;
245
-
246
- const partialRedemptionFee =
247
- isPartial && isPublicRedemption
248
- ? BigInt(sysParams.cdpRedeemParams.partialRedemptionExtraFeeLovelace)
249
- : 0n;
250
-
251
- const processingFee = calculateFeeFromRatio(
252
- iassetDatum.redemptionProcessingFeeRatio,
253
- redemptionIAssetAmt,
254
- );
255
-
256
- const reimburstmentFee = calculateFeeFromRatio(
257
- iassetDatum.redemptionReimbursementRatio,
258
- redemptionCollateralAmt,
259
- );
260
-
261
- const referenceScripts = [
262
- cdpRefScriptUtxo,
263
- iAssetTokenPolicyRefScriptUtxo,
264
- cdpRedeemRefScriptUtxo,
265
- ];
266
-
267
- const referenceInputs = [
268
- iassetUtxo,
269
- collateralAssetUtxo,
270
- interestOracleUtxo,
271
- govUtxo,
272
- ];
273
-
274
- const tx = lucid
275
- .newTx()
276
- // Ref Script
277
- .readFrom(referenceScripts)
278
- // Ref inputs
279
- .readFrom(referenceInputs)
280
- .collectFrom([cdpUtxo], serialiseCdpRedeemer('RedeemCdp'))
281
- .mintAssets(
282
- mkAssetsOf(
283
- {
284
- currencySymbol: fromHex(
285
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
286
- ),
287
- tokenName: iassetDatum.assetName,
288
- },
289
- interestAmt - redemptionIAssetAmt,
290
- ),
291
- Data.void(),
292
- )
293
- .pay.ToContract(
294
- cdpUtxo.address,
295
- {
296
- kind: 'inline',
297
- value: serialiseCdpDatum({
298
- ...cdpDatum,
299
- mintedAmt: totalCdpDebt - redemptionIAssetAmt,
300
- cdpFees: {
301
- ActiveCDPInterestTracking: {
302
- lastSettled: currentTime,
303
- unitaryInterestSnapshot:
304
- interestOracleDatum.unitaryInterest +
305
- calculateUnitaryInterestSinceOracleLastUpdated(
306
- currentTime,
307
- interestOracleDatum,
308
- ),
309
- },
310
- },
311
- }),
312
- },
313
- addAssets(
314
- cdpUtxo.assets,
315
- mkLovelacesOf(-redemptionCollateralAmt),
316
- mkLovelacesOf(reimburstmentFee),
317
- ),
318
- );
319
-
320
- if (priceOracleUtxo !== undefined) {
321
- const priceOracleDatum = parsePriceOracleDatum(
322
- getInlineDatumOrThrow(priceOracleUtxo),
323
- );
324
- const txValidity = oracleExpirationAwareValidity(
325
- lucid,
326
- Number(sysParams.cdpCreatorParams.biasTime),
327
- Number(priceOracleDatum.expirationTime),
328
- );
329
-
330
- referenceInputs.push(priceOracleUtxo);
331
-
332
- tx.validFrom(txValidity.validFrom)
333
- .validTo(txValidity.validTo)
334
- .readFrom([priceOracleUtxo]);
335
- } else {
336
- const validateFrom = lucid.slotToUnixTime(lucid.currentSlot() - 1);
337
- const validateTo =
338
- validateFrom + Number(sysParams.cdpCreatorParams.biasTime);
339
-
340
- tx.validFrom(validateFrom).validTo(validateTo);
341
- }
342
-
343
- // Trigger CDP Redeem Withdrawal validator
344
- tx.withdraw(
345
- credentialToRewardAddress(
346
- lucid.config().network!,
347
- scriptHashToCredential(sysParams.cdpParams.cdpRedeemValHash),
348
- ),
349
- 0n,
350
- serialiseRedeemCdpWithdrawalRedeemer({
351
- cdpOutReference: {
352
- txHash: fromHex(cdpUtxo.txHash),
353
- outputIndex: BigInt(cdpUtxo.outputIndex),
354
- },
355
- currentTime: currentTime,
356
- priceOracleIdx: priceOracleUtxo
357
- ? {
358
- OracleRefInputIdx: getInputIndices(
359
- [priceOracleUtxo],
360
- [...referenceInputs, ...referenceScripts],
361
- )[0],
362
- }
363
- : 'OracleVoid',
364
- }),
365
- );
366
-
367
- //TODO: Use a treasury input to save on ADA.
368
- tx.pay.ToContract(
369
- credentialToAddress(lucid.config().network!, {
370
- hash: validatorToScriptHash(
371
- mkTreasuryValidatorFromSP(sysParams.treasuryParams),
372
- ),
373
- type: 'Script',
374
- }),
375
- { kind: 'inline', value: Data.void() },
376
- addAssets(
377
- mkAssetsOf(cdpDatum.collateralAsset, processingFee),
378
- mkLovelacesOf(partialRedemptionFee),
379
- ),
380
- );
381
- if (interestAmt > 0n) {
382
- await collectInterestTx(
383
- mkAssetsOf(
384
- {
385
- currencySymbol: fromHex(
386
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
387
- ),
388
- tokenName: iassetDatum.assetName,
389
- },
390
- interestAmt,
391
- ),
392
- lucid,
393
- sysParams,
394
- tx,
395
- interestCollectorOref,
396
- );
397
- }
398
-
399
- return tx;
400
- }
401
-
402
- export async function runOpenCdpDelisted(
403
- context: LucidContext,
404
- sysParams: SystemParams,
405
- asset: string,
406
- collateralAsset: AssetClass,
407
- initialCollateral: bigint,
408
- initialMint: bigint,
409
- ): Promise<TxBuilder> {
410
- const orefs = await findAllNecessaryOrefs(
411
- context.lucid,
412
- sysParams,
413
- asset,
414
- collateralAsset,
415
- );
416
-
417
- const network = context.lucid.config().network!;
418
- const currentTime = BigInt(
419
- context.lucid.slotToUnixTime(context.lucid.currentSlot()),
420
- );
421
-
422
- const [pkh, skh] = await addrDetails(context.lucid);
423
-
424
- const cdpCreatorRefScriptUtxo = matchSingle(
425
- await context.lucid.utxosByOutRef([
426
- fromSystemParamsScriptRef(
427
- sysParams.scriptReferences.cdpCreatorValidatorRef,
428
- ),
429
- ]),
430
- (_) => new Error('Expected a single cdp creator Ref Script UTXO'),
431
- );
432
- const cdpAuthTokenPolicyRefScriptUtxo = matchSingle(
433
- await context.lucid.utxosByOutRef([
434
- fromSystemParamsScriptRef(
435
- sysParams.scriptReferences.authTokenPolicies.cdpAuthTokenRef,
436
- ),
437
- ]),
438
- (_) => new Error('Expected a single cdp auth token policy Ref Script UTXO'),
439
- );
440
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
441
- await context.lucid.utxosByOutRef([
442
- fromSystemParamsScriptRef(
443
- sysParams.scriptReferences.iAssetTokenPolicyRef,
444
- ),
445
- ]),
446
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
447
- );
448
-
449
- const iassetUtxo = matchSingle(
450
- await context.lucid.utxosByOutRef([orefs.iasset.utxo]),
451
- (_) => new Error('Expected a single iasset UTXO'),
452
- );
453
- const iassetDatum = parseIAssetDatumOrThrow(
454
- getInlineDatumOrThrow(iassetUtxo),
455
- );
456
-
457
- const collateralAssetUtxo = matchSingle(
458
- await context.lucid.utxosByOutRef([orefs.collateralAsset.utxo]),
459
- (_) => new Error('Expected a single iasset UTXO'),
460
- );
461
- const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
462
- getInlineDatumOrThrow(collateralAssetUtxo),
463
- );
464
-
465
- const interestOracleUtxo = matchSingle(
466
- await context.lucid.utxosByOutRef([orefs.interestOracleUtxo]),
467
- (_) => new Error('Expected a single interest oracle UTXO'),
468
- );
469
- const interestOracleDatum = parseInterestOracleDatum(
470
- getInlineDatumOrThrow(interestOracleUtxo),
471
- );
472
-
473
- const cdpCreatorUtxo = matchSingle(
474
- await context.lucid.utxosByOutRef([orefs.cdpCreatorUtxo]),
475
- (_) => new Error('Expected a single CDP creator UTXO'),
476
- );
477
-
478
- const cdpNftVal = mkAssetsOf(
479
- fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
480
- 1n,
481
- );
482
-
483
- const iassetClass = {
484
- currencySymbol: fromHex(
485
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
486
- ),
487
- tokenName: iassetDatum.assetName,
488
- };
489
-
490
- const iassetTokensVal = mkAssetsOf(iassetClass, initialMint);
491
-
492
- const refScripts: UTxO[] = [
493
- cdpCreatorRefScriptUtxo,
494
- cdpAuthTokenPolicyRefScriptUtxo,
495
- iAssetTokenPolicyRefScriptUtxo,
496
- ];
497
-
498
- const referenceInputs: UTxO[] = [
499
- interestOracleUtxo,
500
- iassetUtxo,
501
- collateralAssetUtxo,
502
- ];
503
-
504
- const tx = context.lucid
505
- .newTx()
506
- .readFrom(refScripts)
507
- .readFrom(referenceInputs)
508
- .mintAssets(cdpNftVal, Data.void())
509
- .mintAssets(iassetTokensVal, Data.void())
510
- .pay.ToContract(
511
- createScriptAddress(network, sysParams.validatorHashes.cdpHash, skh),
512
- {
513
- kind: 'inline',
514
- value: serialiseCdpDatum({
515
- cdpOwner: fromHex(pkh.hash),
516
- iasset: iassetDatum.assetName,
517
- collateralAsset: collateralAssetDatum.collateralAsset,
518
- mintedAmt: initialMint,
519
- cdpFees: {
520
- ActiveCDPInterestTracking: {
521
- lastSettled: currentTime,
522
- unitaryInterestSnapshot:
523
- calculateUnitaryInterestSinceOracleLastUpdated(
524
- currentTime,
525
- interestOracleDatum,
526
- ) + interestOracleDatum.unitaryInterest,
527
- },
528
- },
529
- }),
530
- },
531
- addAssets(
532
- cdpNftVal,
533
- mkAssetsOf(collateralAssetDatum.collateralAsset, initialCollateral),
534
- ),
535
- )
536
- .pay.ToContract(
537
- cdpCreatorUtxo.address,
538
- {
539
- kind: 'inline',
540
- value: serialiseCDPCreatorDatum({
541
- creatorInputOref: {
542
- outputIndex: BigInt(cdpCreatorUtxo.outputIndex),
543
- txHash: fromHex(cdpCreatorUtxo.txHash),
544
- },
545
- }),
546
- },
547
- cdpCreatorUtxo.assets,
548
- );
549
-
550
- const debtMintingFee = calculateFeeFromRatio(
551
- iassetDatum.debtMintingFeeRatio,
552
- initialMint,
553
- );
554
-
555
- const treasuryRefScriptUtxo =
556
- debtMintingFee > 0
557
- ? await treasuryFeeTx(
558
- iassetClass,
559
- debtMintingFee,
560
- 0n,
561
- context.lucid,
562
- sysParams,
563
- tx,
564
- cdpCreatorUtxo,
565
- orefs.treasuryUtxo,
566
- )
567
- : undefined;
568
-
569
- const validFrom = context.lucid.slotToUnixTime(
570
- context.lucid.currentSlot() - 1,
571
- );
572
- const validTo = validFrom + Number(sysParams.cdpCreatorParams.biasTime);
573
-
574
- tx.validFrom(validFrom).validTo(validTo);
575
-
576
- // We need to take into account the treasury ref script.
577
- const refInputsIndices = getInputIndices(referenceInputs, [
578
- ...referenceInputs,
579
- ...refScripts,
580
- ...(treasuryRefScriptUtxo != null ? [treasuryRefScriptUtxo] : []),
581
- ]);
582
-
583
- tx.collectFrom([cdpCreatorUtxo], {
584
- kind: 'self',
585
- makeRedeemer: (inputIdx) => {
586
- return serialiseCDPCreatorRedeemer({
587
- CreateCDP: {
588
- cdpOwner: fromHex(pkh.hash),
589
- minted: initialMint,
590
- collateralAmt: initialCollateral,
591
- currentTime: currentTime,
592
- creatorInputIdx: inputIdx,
593
- creatorOutputIdx: 1n,
594
- cdpOutputIdx: 0n,
595
- iassetRefInputIdx: refInputsIndices[1],
596
- collateralAssetRefInputIdx: refInputsIndices[2],
597
- interestOracleRefInputIdx: refInputsIndices[0],
598
- priceOracleIdx: 'OracleVoid',
599
- },
600
- });
601
- },
602
- });
603
-
604
- return tx;
605
- }
606
-
607
- export async function runOpenCdpAndUpdateOracle(
608
- context: LucidContext,
609
- sysParams: SystemParams,
610
- asset: string,
611
- collateralAsset: AssetClass,
612
- initialCollateral: bigint,
613
- initialMint: bigint,
614
- oracleParams: PriceOracleParams,
615
- newPrice: Rational,
616
- ): Promise<TxBuilder> {
617
- const orefs = await findAllNecessaryOrefs(
618
- context.lucid,
619
- sysParams,
620
- asset,
621
- collateralAsset,
622
- );
623
-
624
- const network = context.lucid.config().network!;
625
- const currentTime = BigInt(
626
- context.lucid.slotToUnixTime(context.lucid.currentSlot()),
627
- );
628
-
629
- const [pkh, skh] = await addrDetails(context.lucid);
630
-
631
- const oracleValidator = mkPriceOracleValidator(oracleParams);
632
-
633
- const cdpCreatorRefScriptUtxo = matchSingle(
634
- await context.lucid.utxosByOutRef([
635
- fromSystemParamsScriptRef(
636
- sysParams.scriptReferences.cdpCreatorValidatorRef,
637
- ),
638
- ]),
639
- (_) => new Error('Expected a single cdp creator Ref Script UTXO'),
640
- );
641
- const cdpAuthTokenPolicyRefScriptUtxo = matchSingle(
642
- await context.lucid.utxosByOutRef([
643
- fromSystemParamsScriptRef(
644
- sysParams.scriptReferences.authTokenPolicies.cdpAuthTokenRef,
645
- ),
646
- ]),
647
- (_) => new Error('Expected a single cdp auth token policy Ref Script UTXO'),
648
- );
649
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
650
- await context.lucid.utxosByOutRef([
651
- fromSystemParamsScriptRef(
652
- sysParams.scriptReferences.iAssetTokenPolicyRef,
653
- ),
654
- ]),
655
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
656
- );
657
-
658
- const iassetUtxo = matchSingle(
659
- await context.lucid.utxosByOutRef([orefs.iasset.utxo]),
660
- (_) => new Error('Expected a single iasset UTXO'),
661
- );
662
- const iassetDatum = parseIAssetDatumOrThrow(
663
- getInlineDatumOrThrow(iassetUtxo),
664
- );
665
-
666
- const collateralAssetUtxo = matchSingle(
667
- await context.lucid.utxosByOutRef([orefs.collateralAsset.utxo]),
668
- (_) => new Error('Expected a single iasset UTXO'),
669
- );
670
- const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
671
- getInlineDatumOrThrow(collateralAssetUtxo),
672
- );
673
-
674
- const priceOracleUtxo = await findPriceOracleFromCollateralAsset(
675
- context.lucid,
676
- orefs.collateralAsset,
677
- );
678
-
679
- if (!priceOracleUtxo) throw new Error('Expected a price oracle');
680
-
681
- const interestOracleUtxo = matchSingle(
682
- await context.lucid.utxosByOutRef([orefs.interestOracleUtxo]),
683
- (_) => new Error('Expected a single interest oracle UTXO'),
684
- );
685
- const interestOracleDatum = parseInterestOracleDatum(
686
- getInlineDatumOrThrow(interestOracleUtxo),
687
- );
688
-
689
- const cdpCreatorUtxo = matchSingle(
690
- await context.lucid.utxosByOutRef([orefs.cdpCreatorUtxo]),
691
- (_) => new Error('Expected a single CDP creator UTXO'),
692
- );
693
-
694
- const cdpNftVal = mkAssetsOf(
695
- fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
696
- 1n,
697
- );
698
-
699
- const iassetClass = {
700
- currencySymbol: fromHex(
701
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
702
- ),
703
- tokenName: iassetDatum.assetName,
704
- };
705
-
706
- const iassetTokensVal = mkAssetsOf(iassetClass, initialMint);
707
-
708
- const refScripts: UTxO[] = [
709
- cdpCreatorRefScriptUtxo,
710
- cdpAuthTokenPolicyRefScriptUtxo,
711
- iAssetTokenPolicyRefScriptUtxo,
712
- ];
713
-
714
- const referenceInputs: UTxO[] = [
715
- interestOracleUtxo,
716
- iassetUtxo,
717
- collateralAssetUtxo,
718
- ];
719
-
720
- const tx = context.lucid
721
- .newTx()
722
- .validFrom(Number(currentTime - oracleParams.biasTime) + ONE_SECOND)
723
- .validTo(Number(currentTime + oracleParams.biasTime) - ONE_SECOND)
724
- .attach.SpendingValidator(oracleValidator)
725
- .readFrom(refScripts)
726
- .readFrom(referenceInputs)
727
- .mintAssets(cdpNftVal, Data.void())
728
- .mintAssets(iassetTokensVal, Data.void())
729
- .collectFrom(
730
- [priceOracleUtxo],
731
- serialisePriceOracleRedeemer({
732
- currentTime: currentTime,
733
- newPrice: newPrice,
734
- }),
735
- )
736
- .pay.ToContract(
737
- priceOracleUtxo.address,
738
- {
739
- kind: 'inline',
740
- value: serialisePriceOracleDatum({
741
- price: newPrice,
742
- expirationTime: currentTime + oracleParams.expirationPeriod,
743
- auxiliaryData: Core.Data.fromCBORHex(Data.void()),
744
- }),
745
- },
746
- priceOracleUtxo.assets,
747
- )
748
- .pay.ToContract(
749
- createScriptAddress(network, sysParams.validatorHashes.cdpHash, skh),
750
- {
751
- kind: 'inline',
752
- value: serialiseCdpDatum({
753
- cdpOwner: fromHex(pkh.hash),
754
- iasset: iassetDatum.assetName,
755
- collateralAsset: collateralAssetDatum.collateralAsset,
756
- mintedAmt: initialMint,
757
- cdpFees: {
758
- ActiveCDPInterestTracking: {
759
- lastSettled: currentTime,
760
- unitaryInterestSnapshot:
761
- calculateUnitaryInterestSinceOracleLastUpdated(
762
- currentTime,
763
- interestOracleDatum,
764
- ) + interestOracleDatum.unitaryInterest,
765
- },
766
- },
767
- }),
768
- },
769
- addAssets(
770
- cdpNftVal,
771
- mkAssetsOf(collateralAssetDatum.collateralAsset, initialCollateral),
772
- ),
773
- )
774
- .pay.ToContract(
775
- cdpCreatorUtxo.address,
776
- {
777
- kind: 'inline',
778
- value: serialiseCDPCreatorDatum({
779
- creatorInputOref: {
780
- outputIndex: BigInt(cdpCreatorUtxo.outputIndex),
781
- txHash: fromHex(cdpCreatorUtxo.txHash),
782
- },
783
- }),
784
- },
785
- cdpCreatorUtxo.assets,
786
- )
787
- .addSignerKey(pkh.hash);
788
-
789
- const debtMintingFee = calculateFeeFromRatio(
790
- iassetDatum.debtMintingFeeRatio,
791
- initialMint,
792
- );
793
-
794
- const treasuryRefScriptUtxo =
795
- debtMintingFee > 0
796
- ? await treasuryFeeTx(
797
- iassetClass,
798
- debtMintingFee,
799
- 0n,
800
- context.lucid,
801
- sysParams,
802
- tx,
803
- cdpCreatorUtxo,
804
- orefs.treasuryUtxo,
805
- )
806
- : undefined;
807
-
808
- // We need to take into account the treasury ref script as well.
809
- const refInputsIndices = getInputIndices(referenceInputs, [
810
- ...referenceInputs,
811
- ...refScripts,
812
- ...(treasuryRefScriptUtxo != null ? [treasuryRefScriptUtxo] : []),
813
- ]);
814
-
815
- tx.collectFrom([cdpCreatorUtxo], {
816
- kind: 'self',
817
- makeRedeemer: (inputIdx) => {
818
- return serialiseCDPCreatorRedeemer({
819
- CreateCDP: {
820
- cdpOwner: fromHex(pkh.hash),
821
- minted: initialMint,
822
- collateralAmt: initialCollateral,
823
- currentTime: currentTime,
824
- creatorInputIdx: inputIdx,
825
- creatorOutputIdx: 2n,
826
- cdpOutputIdx: 1n,
827
- iassetRefInputIdx: refInputsIndices[1],
828
- collateralAssetRefInputIdx: refInputsIndices[2],
829
- interestOracleRefInputIdx: refInputsIndices[0],
830
- priceOracleIdx: { OracleOutputIdx: 0n },
831
- },
832
- });
833
- },
834
- });
835
-
836
- return tx;
837
- }
838
-
839
- export async function runTestAdjustCdpDelisted(
840
- context: LucidContext,
841
- sysParams: SystemParams,
842
- asset: string,
843
- collateralAsset: AssetClass,
844
- collateralAdjustment: bigint,
845
- debtAdjustment: bigint,
846
- ): Promise<TxBuilder> {
847
- const currentTime = BigInt(
848
- context.lucid.slotToUnixTime(context.lucid.currentSlot()),
849
- );
850
- const [pkh, skh] = await addrDetails(context.lucid);
851
-
852
- const cdp = await findCdp(
853
- context.lucid,
854
- sysParams.validatorHashes.cdpHash,
855
- fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
856
- pkh.hash,
857
- skh,
858
- );
859
-
860
- const cdpRefScriptUtxo = matchSingle(
861
- await context.lucid.utxosByOutRef([
862
- fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef),
863
- ]),
864
- (_) => new Error('Expected a single cdp Ref Script UTXO'),
865
- );
866
-
867
- const cdpUtxo = matchSingle(
868
- await context.lucid.utxosByOutRef([cdp.utxo]),
869
- (_) => new Error('Expected a single cdp UTXO'),
870
- );
871
- const cdpDatum = parseCdpDatumOrThrow(getInlineDatumOrThrow(cdpUtxo));
872
-
873
- const iassetOutput = await findIAsset(
874
- context.lucid,
875
- sysParams.validatorHashes.iassetHash,
876
- fromSystemParamsAsset(sysParams.cdpParams.iAssetAuthToken),
877
- asset,
878
- );
879
-
880
- const iassetUtxo = matchSingle(
881
- await context.lucid.utxosByOutRef([iassetOutput.utxo]),
882
- (_) => new Error('Expected a single iasset UTXO'),
883
- );
884
- const iassetDatum = parseIAssetDatumOrThrow(
885
- getInlineDatumOrThrow(iassetUtxo),
886
- );
887
-
888
- const collateralAssetOutput = await findCollateralAsset(
889
- context.lucid,
890
- sysParams,
891
- fromSystemParamsAsset(sysParams.cdpParams.collateralAssetAuthToken),
892
- asset,
893
- collateralAsset,
894
- );
895
-
896
- const collateralAssetUtxo = matchSingle(
897
- await context.lucid.utxosByOutRef([collateralAssetOutput.utxo]),
898
- (_) => new Error('Expected a single collateral asset UTXO'),
899
- );
900
- const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
901
- getInlineDatumOrThrow(collateralAssetUtxo),
902
- );
903
-
904
- const interestOracleUtxo = await findInterestOracle(
905
- context.lucid,
906
- collateralAssetDatum.interestOracleNft,
907
- );
908
-
909
- const interestOracleDatum = parseInterestOracleDatum(
910
- getInlineDatumOrThrow(interestOracleUtxo),
911
- );
912
-
913
- const interestCollectorUtxo = await findRandomNonAdminInterestCollector(
914
- context.lucid,
915
- sysParams,
916
- );
917
-
918
- const validateFrom = context.lucid.slotToUnixTime(
919
- context.lucid.currentSlot() - 1,
920
- );
921
- const validateTo =
922
- validateFrom + Number(sysParams.cdpParams.biasTime) - 60_000;
923
-
924
- const interestAmt = match(cdpDatum.cdpFees)
925
- .with({ FrozenCDPAccumulatedFees: P.any }, () => {
926
- throw new Error('CDP fees wrong');
927
- })
928
- .with({ ActiveCDPInterestTracking: P.select() }, (interest) => {
929
- return calculateAccruedInterest(
930
- currentTime,
931
- interest.unitaryInterestSnapshot,
932
- cdpDatum.mintedAmt,
933
- interest.lastSettled,
934
- interestOracleDatum,
935
- );
936
- })
937
- .exhaustive();
938
-
939
- const mintedAmountChange = debtAdjustment + interestAmt;
940
-
941
- const tx = context.lucid
942
- .newTx()
943
- .validFrom(validateFrom)
944
- .validTo(validateTo)
945
- .collectFrom(
946
- [cdpUtxo],
947
- serialiseCdpRedeemer({
948
- AdjustCdp: {
949
- currentTime: currentTime,
950
- debtAdjustment,
951
- collateralAdjustment,
952
- priceOracleIdx: 'OracleVoid',
953
- },
954
- }),
955
- )
956
- .readFrom([cdpRefScriptUtxo])
957
- .readFrom([iassetUtxo, collateralAssetUtxo, interestOracleUtxo])
958
- .pay.ToContract(
959
- cdpUtxo.address,
960
- {
961
- kind: 'inline',
962
- value: serialiseCdpDatum({
963
- ...cdpDatum,
964
- mintedAmt: cdpDatum.mintedAmt + mintedAmountChange,
965
- cdpFees: {
966
- ActiveCDPInterestTracking: {
967
- lastSettled: currentTime,
968
- unitaryInterestSnapshot:
969
- calculateUnitaryInterestSinceOracleLastUpdated(
970
- currentTime,
971
- interestOracleDatum,
972
- ) + interestOracleDatum.unitaryInterest,
973
- },
974
- },
975
- }),
976
- },
977
- addAssets(
978
- cdpUtxo.assets,
979
- mkAssetsOf(cdpDatum.collateralAsset, collateralAdjustment),
980
- ),
981
- );
982
-
983
- if (!cdpDatum.cdpOwner) {
984
- throw new Error('Expected active CDP');
985
- }
986
-
987
- tx.addSignerKey(toHex(cdpDatum.cdpOwner));
988
-
989
- if (mintedAmountChange !== 0n) {
990
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
991
- await context.lucid.utxosByOutRef([
992
- fromSystemParamsScriptRef(
993
- sysParams.scriptReferences.iAssetTokenPolicyRef,
994
- ),
995
- ]),
996
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
997
- );
998
-
999
- const iassetTokensVal = mkAssetsOf(
1000
- {
1001
- currencySymbol: fromHex(
1002
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1003
- ),
1004
- tokenName: iassetDatum.assetName,
1005
- },
1006
- mintedAmountChange,
1007
- );
1008
-
1009
- tx.readFrom([iAssetTokenPolicyRefScriptUtxo]).mintAssets(
1010
- iassetTokensVal,
1011
- Data.void(),
1012
- );
1013
- }
1014
-
1015
- const iAssetAc = {
1016
- currencySymbol: fromHex(
1017
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1018
- ),
1019
- tokenName: iassetDatum.assetName,
1020
- };
1021
-
1022
- if (interestAmt > 0n) {
1023
- await collectInterestTx(
1024
- mkAssetsOf(iAssetAc, interestAmt),
1025
- context.lucid,
1026
- sysParams,
1027
- tx,
1028
- interestCollectorUtxo,
1029
- );
1030
- }
1031
-
1032
- let treasuryFee = 0n;
1033
-
1034
- if (debtAdjustment > 0n) {
1035
- const treasuryUtxo = await findRandomTreasuryUtxoWithOnlyAda(
1036
- context.lucid,
1037
- sysParams,
1038
- );
1039
-
1040
- treasuryFee += calculateFeeFromRatio(
1041
- iassetDatum.debtMintingFeeRatio,
1042
- debtAdjustment,
1043
- );
1044
-
1045
- if (treasuryFee > 0n) {
1046
- await treasuryFeeTx(
1047
- iAssetAc,
1048
- treasuryFee,
1049
- 0n,
1050
- context.lucid,
1051
- sysParams,
1052
- tx,
1053
- cdpUtxo,
1054
- treasuryUtxo,
1055
- );
1056
- }
1057
- }
1058
-
1059
- return tx;
1060
- }
1061
-
1062
- export async function runTestDepositCdpWithInterestVar(
1063
- context: LucidContext,
1064
- sysParams: SystemParams,
1065
- iasset: string,
1066
- collateralAsset: AssetClass,
1067
- interestCollectorUtxo: UTxO,
1068
- interestVariation: CollectInterestVariation,
1069
-
1070
- amount: bigint = 1_000_000n,
1071
- ): Promise<TxBuilder> {
1072
- const currentTime = BigInt(
1073
- context.lucid.slotToUnixTime(context.lucid.currentSlot()),
1074
- );
1075
- const [pkh, skh] = await addrDetails(context.lucid);
1076
-
1077
- const cdp = await findCdp(
1078
- context.lucid,
1079
- sysParams.validatorHashes.cdpHash,
1080
- fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
1081
- pkh.hash,
1082
- skh,
1083
- );
1084
-
1085
- const cdpRefScriptUtxo = matchSingle(
1086
- await context.lucid.utxosByOutRef([
1087
- fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef),
1088
- ]),
1089
- (_) => new Error('Expected a single cdp Ref Script UTXO'),
1090
- );
1091
-
1092
- const cdpUtxo = matchSingle(
1093
- await context.lucid.utxosByOutRef([cdp.utxo]),
1094
- (_) => new Error('Expected a single cdp UTXO'),
1095
- );
1096
- const cdpDatum = parseCdpDatumOrThrow(getInlineDatumOrThrow(cdpUtxo));
1097
-
1098
- const iassetOutput = await findIAsset(
1099
- context.lucid,
1100
- sysParams.validatorHashes.iassetHash,
1101
- fromSystemParamsAsset(sysParams.cdpParams.iAssetAuthToken),
1102
- iasset,
1103
- );
1104
-
1105
- const iassetUtxo = matchSingle(
1106
- await context.lucid.utxosByOutRef([iassetOutput.utxo]),
1107
- (_) => new Error('Expected a single iasset UTXO'),
1108
- );
1109
- const iassetDatum = parseIAssetDatumOrThrow(
1110
- getInlineDatumOrThrow(iassetUtxo),
1111
- );
1112
-
1113
- const collateralAssetOutput = await findCollateralAsset(
1114
- context.lucid,
1115
- sysParams,
1116
- fromSystemParamsAsset(sysParams.cdpParams.collateralAssetAuthToken),
1117
- iasset,
1118
- collateralAsset,
1119
- );
1120
-
1121
- const collateralAssetUtxo = matchSingle(
1122
- await context.lucid.utxosByOutRef([collateralAssetOutput.utxo]),
1123
- (_) => new Error('Expected a single iasset UTXO'),
1124
- );
1125
-
1126
- const interestOracleUtxo = await findInterestOracle(
1127
- context.lucid,
1128
- collateralAssetOutput.datum.interestOracleNft,
1129
- );
1130
- const interestOracleDatum = parseInterestOracleDatum(
1131
- getInlineDatumOrThrow(interestOracleUtxo),
1132
- );
1133
-
1134
- const validateFrom = context.lucid.slotToUnixTime(
1135
- context.lucid.currentSlot() - 1,
1136
- );
1137
- const validateTo =
1138
- validateFrom + Number(sysParams.cdpParams.biasTime) - 60_000;
1139
-
1140
- const interestAmt = match(cdpDatum.cdpFees)
1141
- .with({ FrozenCDPAccumulatedFees: P.any }, () => {
1142
- throw new Error('CDP fees wrong');
1143
- })
1144
- .with({ ActiveCDPInterestTracking: P.select() }, (interest) => {
1145
- return calculateAccruedInterest(
1146
- currentTime,
1147
- interest.unitaryInterestSnapshot,
1148
- cdpDatum.mintedAmt,
1149
- interest.lastSettled,
1150
- interestOracleDatum,
1151
- );
1152
- })
1153
- .exhaustive();
1154
-
1155
- const mintedAmountChange = interestAmt;
1156
-
1157
- const tx = context.lucid
1158
- .newTx()
1159
- .validFrom(validateFrom)
1160
- .validTo(validateTo)
1161
- .collectFrom(
1162
- [cdpUtxo],
1163
- serialiseCdpRedeemer({
1164
- AdjustCdp: {
1165
- currentTime: currentTime,
1166
- debtAdjustment: 0n,
1167
- collateralAdjustment: amount,
1168
- priceOracleIdx: 'OracleVoid',
1169
- },
1170
- }),
1171
- )
1172
- .readFrom([cdpRefScriptUtxo])
1173
- .readFrom([iassetUtxo, collateralAssetUtxo, interestOracleUtxo])
1174
- .pay.ToContract(
1175
- cdpUtxo.address,
1176
- {
1177
- kind: 'inline',
1178
- value: serialiseCdpDatum({
1179
- ...cdpDatum,
1180
- mintedAmt: cdpDatum.mintedAmt + mintedAmountChange,
1181
- cdpFees: {
1182
- ActiveCDPInterestTracking: {
1183
- lastSettled: currentTime,
1184
- unitaryInterestSnapshot:
1185
- calculateUnitaryInterestSinceOracleLastUpdated(
1186
- currentTime,
1187
- interestOracleDatum,
1188
- ) + interestOracleDatum.unitaryInterest,
1189
- },
1190
- },
1191
- }),
1192
- },
1193
- addAssets(cdpUtxo.assets, mkLovelacesOf(amount)),
1194
- );
1195
-
1196
- if (!cdpDatum.cdpOwner) {
1197
- throw new Error('Expected active CDP');
1198
- }
1199
-
1200
- tx.addSignerKey(toHex(cdpDatum.cdpOwner));
1201
-
1202
- if (mintedAmountChange !== 0n) {
1203
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
1204
- await context.lucid.utxosByOutRef([
1205
- fromSystemParamsScriptRef(
1206
- sysParams.scriptReferences.iAssetTokenPolicyRef,
1207
- ),
1208
- ]),
1209
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
1210
- );
1211
-
1212
- const iassetTokensVal = mkAssetsOf(
1213
- {
1214
- currencySymbol: fromHex(
1215
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1216
- ),
1217
- tokenName: iassetDatum.assetName,
1218
- },
1219
- mintedAmountChange,
1220
- );
1221
-
1222
- tx.readFrom([iAssetTokenPolicyRefScriptUtxo]).mintAssets(
1223
- iassetTokensVal,
1224
- Data.void(),
1225
- );
1226
- }
1227
-
1228
- if (interestAmt > 0n) {
1229
- await testCollectInterest(
1230
- mkAssetsOf(
1231
- {
1232
- currencySymbol: fromHex(
1233
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1234
- ),
1235
- tokenName: iassetDatum.assetName,
1236
- },
1237
- interestAmt,
1238
- ),
1239
- context.lucid,
1240
- sysParams,
1241
- tx,
1242
- interestCollectorUtxo,
1243
- interestVariation,
1244
- );
1245
- }
1246
-
1247
- return tx;
1248
- }
1249
-
1250
- export async function runCloseCdpWrongOracle(
1251
- lucid: LucidEvolution,
1252
- sysParams: SystemParams,
1253
- iasset: string,
1254
- wrongAsset: string,
1255
- collateralAsset: AssetClass,
1256
- ): Promise<TxBuilder> {
1257
- const [pkh, skh] = await addrDetails(lucid);
1258
-
1259
- const cdp = await findCdp(
1260
- lucid,
1261
- sysParams.validatorHashes.cdpHash,
1262
- fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
1263
- pkh.hash,
1264
- skh,
1265
- );
1266
- const orefs = await findAllNecessaryOrefs(
1267
- lucid,
1268
- sysParams,
1269
- iasset,
1270
- collateralAsset,
1271
- );
1272
-
1273
- const priceOracleOref = await findPriceOracleFromCollateralAsset(
1274
- lucid,
1275
- orefs.collateralAsset,
1276
- );
1277
-
1278
- const currentTime = BigInt(lucid.slotToUnixTime(lucid.currentSlot()));
1279
-
1280
- const cdpRefScriptUtxo = matchSingle(
1281
- await lucid.utxosByOutRef([
1282
- fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef),
1283
- ]),
1284
- (_) => new Error('Expected a single cdp Ref Script UTXO'),
1285
- );
1286
-
1287
- const cdpAuthTokenPolicyRefScriptUtxo = matchSingle(
1288
- await lucid.utxosByOutRef([
1289
- fromSystemParamsScriptRef(
1290
- sysParams.scriptReferences.authTokenPolicies.cdpAuthTokenRef,
1291
- ),
1292
- ]),
1293
- (_) => new Error('Expected a single cdp auth token policy Ref Script UTXO'),
1294
- );
1295
-
1296
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
1297
- await lucid.utxosByOutRef([
1298
- fromSystemParamsScriptRef(
1299
- sysParams.scriptReferences.iAssetTokenPolicyRef,
1300
- ),
1301
- ]),
1302
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
1303
- );
1304
-
1305
- const cdpUtxo = matchSingle(
1306
- await lucid.utxosByOutRef([cdp.utxo]),
1307
- (_) => new Error('Expected a single cdp UTXO'),
1308
- );
1309
- const cdpDatum = parseCdpDatumOrThrow(getInlineDatumOrThrow(cdpUtxo));
1310
-
1311
- const iassetUtxo = matchSingle(
1312
- await lucid.utxosByOutRef([orefs.iasset.utxo]),
1313
- (_) => new Error('Expected a single iasset UTXO'),
1314
- );
1315
- const iassetDatum = parseIAssetDatumOrThrow(
1316
- getInlineDatumOrThrow(iassetUtxo),
1317
- );
1318
-
1319
- const priceOracleUtxo = matchSingle(
1320
- await lucid.utxosByOutRef([priceOracleOref!]),
1321
- (_) => new Error('Expected a single price oracle UTXO'),
1322
- );
1323
- const priceOracleDatum = parsePriceOracleDatum(
1324
- getInlineDatumOrThrow(priceOracleUtxo),
1325
- );
1326
-
1327
- const wrongCollateral = await findCollateralAsset(
1328
- lucid,
1329
- sysParams,
1330
- fromSystemParamsAsset(sysParams.cdpParams.collateralAssetAuthToken),
1331
- wrongAsset,
1332
- collateralAsset,
1333
- );
1334
-
1335
- const wrongInterestOracleUtxo = await findInterestOracle(
1336
- lucid,
1337
- wrongCollateral.datum.interestOracleNft,
1338
- );
1339
-
1340
- const wrongInterestOracleDatum = parseInterestOracleDatum(
1341
- getInlineDatumOrThrow(wrongInterestOracleUtxo),
1342
- );
1343
-
1344
- const txValidity = oracleExpirationAwareValidity(
1345
- lucid,
1346
- Number(sysParams.cdpCreatorParams.biasTime),
1347
- Number(priceOracleDatum.expirationTime),
1348
- );
1349
-
1350
- const tx = lucid
1351
- .newTx()
1352
- .readFrom([
1353
- cdpRefScriptUtxo,
1354
- iAssetTokenPolicyRefScriptUtxo,
1355
- cdpAuthTokenPolicyRefScriptUtxo,
1356
- ])
1357
- .readFrom([wrongCollateral.utxo, wrongInterestOracleUtxo])
1358
- .validFrom(txValidity.validFrom)
1359
- .validTo(txValidity.validTo)
1360
- .mintAssets(
1361
- mkAssetsOf(
1362
- {
1363
- currencySymbol: fromHex(
1364
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1365
- ),
1366
- tokenName: iassetDatum.assetName,
1367
- },
1368
- -cdpDatum.mintedAmt,
1369
- ),
1370
- Data.void(),
1371
- )
1372
- .mintAssets(
1373
- mkAssetsOf(fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken), -1n),
1374
- Data.void(),
1375
- )
1376
- .collectFrom(
1377
- [cdpUtxo],
1378
- serialiseCdpRedeemer({ CloseCdp: { currentTime: currentTime } }),
1379
- );
1380
-
1381
- if (!cdpDatum.cdpOwner) {
1382
- throw new Error('Expected active CDP');
1383
- }
1384
-
1385
- tx.addSignerKey(toHex(cdpDatum.cdpOwner));
1386
-
1387
- const interestAmt = match(cdpDatum.cdpFees)
1388
- .with({ FrozenCDPAccumulatedFees: P.any }, () => {
1389
- throw new Error('CDP fees wrong');
1390
- })
1391
- .with({ ActiveCDPInterestTracking: P.select() }, (interest) => {
1392
- return calculateAccruedInterest(
1393
- currentTime,
1394
- interest.unitaryInterestSnapshot,
1395
- cdpDatum.mintedAmt,
1396
- interest.lastSettled,
1397
- wrongInterestOracleDatum,
1398
- );
1399
- })
1400
- .exhaustive();
1401
-
1402
- if (interestAmt > 0n) {
1403
- await collectInterestTx(
1404
- mkAssetsOf(
1405
- {
1406
- currencySymbol: fromHex(
1407
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1408
- ),
1409
- tokenName: cdpDatum.iasset,
1410
- },
1411
- interestAmt,
1412
- ),
1413
- lucid,
1414
- sysParams,
1415
- tx,
1416
- orefs.interestCollectorUtxo,
1417
- );
1418
- }
1419
-
1420
- return tx;
1421
- }
1422
-
1423
- export async function runRedeemCdpWrongOracle(
1424
- context: LucidContext,
1425
- sysParams: SystemParams,
1426
- assetInfo: AssetInfo,
1427
- wrongAssetInfo: AssetInfo,
1428
- collateralAsset: AssetClass,
1429
- pkh: string,
1430
- skh: Credential | undefined,
1431
- ): Promise<TxBuilder> {
1432
- const cdp = await findCdp(
1433
- context.lucid,
1434
- sysParams.validatorHashes.cdpHash,
1435
- fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
1436
- pkh,
1437
- skh,
1438
- );
1439
-
1440
- const cdpRedeemRefScriptUtxo = matchSingle(
1441
- await context.lucid.utxosByOutRef([
1442
- fromSystemParamsScriptRef(
1443
- sysParams.scriptReferences.cdpRedeemValidatorRef,
1444
- ),
1445
- ]),
1446
- (_) => new Error('Expected a single cdp redeem Ref Script UTXO'),
1447
- );
1448
-
1449
- const orefs = await findAllNecessaryOrefs(
1450
- context.lucid,
1451
- sysParams,
1452
- assetInfo.iassetTokenNameAscii,
1453
- collateralAsset,
1454
- );
1455
-
1456
- const wrongIasset = await findIAsset(
1457
- context.lucid,
1458
- sysParams.validatorHashes.iassetHash,
1459
- fromSystemParamsAsset(sysParams.cdpParams.iAssetAuthToken),
1460
- wrongAssetInfo.iassetTokenNameAscii,
1461
- );
1462
-
1463
- const wrongCollateral = await findCollateralAsset(
1464
- context.lucid,
1465
- sysParams,
1466
- fromSystemParamsAsset(sysParams.cdpParams.collateralAssetAuthToken),
1467
- wrongAssetInfo.iassetTokenNameAscii,
1468
- collateralAsset,
1469
- );
1470
-
1471
- const wrongInterestOracleUtxo = await findInterestOracle(
1472
- context.lucid,
1473
- wrongCollateral.datum.interestOracleNft,
1474
- );
1475
-
1476
- const wrongInterestOracleDatum = parseInterestOracleDatum(
1477
- getInlineDatumOrThrow(wrongInterestOracleUtxo),
1478
- );
1479
-
1480
- const wrongPriceOracleUtxo = await findPriceOracle(
1481
- context.lucid,
1482
- match(wrongCollateral.datum.priceInfo)
1483
- .with({ OracleNft: P.select() }, (oracleNft) => oracleNft)
1484
- .otherwise(() => {
1485
- throw new Error('Expected active oracle');
1486
- }),
1487
- );
1488
-
1489
- const wrongPriceOracleDatum = parsePriceOracleDatum(
1490
- getInlineDatumOrThrow(wrongPriceOracleUtxo),
1491
- );
1492
-
1493
- const currentTime = BigInt(
1494
- context.lucid.slotToUnixTime(context.lucid.currentSlot()),
1495
- );
1496
-
1497
- const cdpRefScriptUtxo = matchSingle(
1498
- await context.lucid.utxosByOutRef([
1499
- fromSystemParamsScriptRef(sysParams.scriptReferences.cdpValidatorRef),
1500
- ]),
1501
- (_) => new Error('Expected a single cdp Ref Script UTXO'),
1502
- );
1503
-
1504
- const iAssetTokenPolicyRefScriptUtxo = matchSingle(
1505
- await context.lucid.utxosByOutRef([
1506
- fromSystemParamsScriptRef(
1507
- sysParams.scriptReferences.iAssetTokenPolicyRef,
1508
- ),
1509
- ]),
1510
- (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
1511
- );
1512
-
1513
- const cdpUtxo = matchSingle(
1514
- await context.lucid.utxosByOutRef([cdp.utxo]),
1515
- (_) => new Error('Expected a single cdp UTXO'),
1516
- );
1517
- const cdpDatum = parseCdpDatumOrThrow(getInlineDatumOrThrow(cdpUtxo));
1518
-
1519
- const govUtxo = matchSingle(
1520
- await context.lucid.utxosByOutRef([orefs.govUtxo]),
1521
- (_) => new Error('Expected a single gov UTXO'),
1522
- );
1523
- const govDatum = parseGovDatumOrThrow(getInlineDatumOrThrow(govUtxo));
1524
-
1525
- const interestAmt = match(cdpDatum.cdpFees)
1526
- .with({ FrozenCDPAccumulatedFees: P.any }, () => {
1527
- throw new Error('CDP fees wrong');
1528
- })
1529
- .with({ ActiveCDPInterestTracking: P.select() }, (interest) => {
1530
- return calculateAccruedInterest(
1531
- currentTime,
1532
- interest.unitaryInterestSnapshot,
1533
- cdpDatum.mintedAmt,
1534
- interest.lastSettled,
1535
- wrongInterestOracleDatum,
1536
- );
1537
- })
1538
- .exhaustive();
1539
-
1540
- const collateralAmt = assetClassValueOf(
1541
- cdpUtxo.assets,
1542
- cdpDatum.collateralAsset,
1543
- );
1544
-
1545
- const totalCdpDebt = cdpDatum.mintedAmt + interestAmt;
1546
-
1547
- const [isPartial, redemptionIAssetAmt] = (() => {
1548
- const res = calculateMinCollateralCappedIAssetRedemptionAmt(
1549
- collateralAmt,
1550
- totalCdpDebt,
1551
- wrongPriceOracleDatum.price,
1552
- wrongCollateral.datum.redemptionRatio,
1553
- wrongIasset.datum.redemptionReimbursementRatio,
1554
- BigInt(wrongCollateral.datum.minCollateralAmt),
1555
- );
1556
-
1557
- const redemptionAmt = bigintMin(
1558
- cdp.datum.mintedAmt,
1559
- res.cappedIAssetRedemptionAmt,
1560
- );
1561
-
1562
- return [redemptionAmt < res.cappedIAssetRedemptionAmt, redemptionAmt];
1563
- })();
1564
-
1565
- if (redemptionIAssetAmt <= 0) {
1566
- throw new Error("There's no iAssets available for redemption.");
1567
- }
1568
-
1569
- const redemptionCollateralAmt = rationalFloor(
1570
- rationalMul(
1571
- wrongPriceOracleDatum.price,
1572
- rationalFromInt(redemptionIAssetAmt),
1573
- ),
1574
- );
1575
-
1576
- const processingFee = calculateFeeFromRatio(
1577
- wrongIasset.datum.redemptionProcessingFeeRatio,
1578
- redemptionCollateralAmt,
1579
- );
1580
- const reimburstmentFee = calculateFeeFromRatio(
1581
- wrongIasset.datum.redemptionReimbursementRatio,
1582
- redemptionCollateralAmt,
1583
- );
1584
-
1585
- const txValidity = oracleExpirationAwareValidity(
1586
- context.lucid,
1587
- Number(sysParams.cdpCreatorParams.biasTime),
1588
- Number(wrongPriceOracleDatum.expirationTime),
1589
- );
1590
-
1591
- const referenceInputs = [
1592
- wrongIasset.utxo,
1593
- wrongCollateral.utxo,
1594
- wrongPriceOracleUtxo,
1595
- wrongInterestOracleUtxo,
1596
- govUtxo,
1597
- ];
1598
-
1599
- const referenceScripts = [
1600
- cdpRefScriptUtxo,
1601
- iAssetTokenPolicyRefScriptUtxo,
1602
- cdpRedeemRefScriptUtxo,
1603
- ];
1604
-
1605
- const tx = context.lucid.newTx().readFrom(referenceScripts);
1606
-
1607
- const interestCollectorRefScriptUtxo =
1608
- interestAmt > 0n
1609
- ? await collectInterestTx(
1610
- mkAssetsOf(
1611
- {
1612
- currencySymbol: fromHex(
1613
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1614
- ),
1615
- tokenName: cdpDatum.iasset,
1616
- },
1617
- interestAmt,
1618
- ),
1619
- context.lucid,
1620
- sysParams,
1621
- tx,
1622
- orefs.interestCollectorUtxo,
1623
- )
1624
- : undefined;
1625
-
1626
- // We need to take into account the interest collector ref script as well.
1627
- const priceOracleIdx = getInputIndices(
1628
- [wrongPriceOracleUtxo],
1629
- [
1630
- ...referenceInputs,
1631
- ...referenceScripts,
1632
- ...(interestCollectorRefScriptUtxo != null
1633
- ? [interestCollectorRefScriptUtxo]
1634
- : []),
1635
- ],
1636
- )[0];
1637
-
1638
- tx.readFrom(referenceInputs)
1639
- // Trigger CDP Redeem Withdrawal validator
1640
- .withdraw(
1641
- credentialToRewardAddress(
1642
- context.lucid.config().network!,
1643
- scriptHashToCredential(sysParams.cdpParams.cdpRedeemValHash),
1644
- ),
1645
- 0n,
1646
- serialiseRedeemCdpWithdrawalRedeemer({
1647
- cdpOutReference: {
1648
- txHash: fromHex(cdpUtxo.txHash),
1649
- outputIndex: BigInt(cdpUtxo.outputIndex),
1650
- },
1651
- currentTime: currentTime,
1652
- priceOracleIdx: { OracleRefInputIdx: priceOracleIdx },
1653
- }),
1654
- )
1655
- .validFrom(txValidity.validFrom)
1656
- .validTo(txValidity.validTo)
1657
- .collectFrom([cdpUtxo], serialiseCdpRedeemer('RedeemCdp'))
1658
- .mintAssets(
1659
- mkAssetsOf(
1660
- {
1661
- currencySymbol: fromHex(
1662
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
1663
- ),
1664
- tokenName: cdpDatum.iasset,
1665
- },
1666
- interestAmt - redemptionIAssetAmt,
1667
- ),
1668
- Data.void(),
1669
- )
1670
- .pay.ToContract(
1671
- cdpUtxo.address,
1672
- {
1673
- kind: 'inline',
1674
- value: serialiseCdpDatum({
1675
- ...cdpDatum,
1676
- mintedAmt: totalCdpDebt - redemptionIAssetAmt,
1677
- cdpFees: {
1678
- ActiveCDPInterestTracking: {
1679
- lastSettled: currentTime,
1680
- unitaryInterestSnapshot:
1681
- wrongInterestOracleDatum.unitaryInterest +
1682
- calculateUnitaryInterestSinceOracleLastUpdated(
1683
- currentTime,
1684
- wrongInterestOracleDatum,
1685
- ),
1686
- },
1687
- },
1688
- }),
1689
- },
1690
- addAssets(
1691
- cdpUtxo.assets,
1692
- mkAssetsOf(
1693
- cdpDatum.collateralAsset,
1694
- -redemptionCollateralAmt + reimburstmentFee,
1695
- ),
1696
- ),
1697
- );
1698
-
1699
- const partialRedemptionFee = F.pipe(
1700
- govDatum.protocolParams.cdpRedemptionRequiredSignature,
1701
- O.fromNullable,
1702
- O.match(
1703
- // When public redemptions
1704
- () => {
1705
- return isPartial
1706
- ? BigInt(sysParams.cdpRedeemParams.partialRedemptionExtraFeeLovelace)
1707
- : 0n;
1708
- },
1709
- // When private redemptions
1710
- (requiredSignature) => {
1711
- tx.addSignerKey(toHex(requiredSignature));
1712
- return 0n;
1713
- },
1714
- ),
1715
- );
1716
-
1717
- //TODO: Use a treasury input to save on ADA.
1718
- tx.pay.ToContract(
1719
- credentialToAddress(context.lucid.config().network!, {
1720
- hash: validatorToScriptHash(
1721
- mkTreasuryValidatorFromSP(sysParams.treasuryParams),
1722
- ),
1723
- type: 'Script',
1724
- }),
1725
- { kind: 'inline', value: Data.void() },
1726
- addAssets(
1727
- mkAssetsOf(cdpDatum.collateralAsset, processingFee),
1728
- mkLovelacesOf(partialRedemptionFee),
1729
- ),
1730
- );
1731
-
1732
- return tx;
1733
- }