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