@indigo-labs/indigo-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.nvmrc +1 -0
  2. package/.prettierrc +6 -0
  3. package/README.md +21 -0
  4. package/babel.config.cjs +13 -0
  5. package/dist/contracts/cdp-creator.d.ts +9 -0
  6. package/dist/contracts/cdp-creator.js +58 -0
  7. package/dist/contracts/cdp.d.ts +22 -0
  8. package/dist/contracts/cdp.js +542 -0
  9. package/dist/contracts/collector.d.ts +9 -0
  10. package/dist/contracts/collector.js +52 -0
  11. package/dist/contracts/gov.d.ts +5 -0
  12. package/dist/contracts/gov.js +50 -0
  13. package/dist/contracts/interest-oracle.d.ts +8 -0
  14. package/dist/contracts/interest-oracle.js +39 -0
  15. package/dist/contracts/price-oracle.d.ts +5 -0
  16. package/dist/contracts/price-oracle.js +18 -0
  17. package/dist/contracts/treasury.d.ts +9 -0
  18. package/dist/contracts/treasury.js +56 -0
  19. package/dist/helpers/asset-helpers.d.ts +11 -0
  20. package/dist/helpers/asset-helpers.js +23 -0
  21. package/dist/helpers/cdp-helpers.d.ts +5 -0
  22. package/dist/helpers/cdp-helpers.js +5 -0
  23. package/dist/helpers/helpers.d.ts +4 -0
  24. package/dist/helpers/helpers.js +14 -0
  25. package/dist/helpers/lucid-utils.d.ts +6 -0
  26. package/dist/helpers/lucid-utils.js +18 -0
  27. package/dist/helpers/time-helpers.d.ts +3 -0
  28. package/dist/helpers/time-helpers.js +3 -0
  29. package/dist/index.d.ts +23 -0
  30. package/dist/index.js +23 -0
  31. package/dist/scripts/cdp-creator-validator.d.ts +6 -0
  32. package/dist/scripts/cdp-creator-validator.js +6 -0
  33. package/dist/scripts/cdp-validator.d.ts +6 -0
  34. package/dist/scripts/cdp-validator.js +6 -0
  35. package/dist/scripts/collector-validator.d.ts +6 -0
  36. package/dist/scripts/collector-validator.js +5 -0
  37. package/dist/scripts/interest-oracle-validator.d.ts +6 -0
  38. package/dist/scripts/interest-oracle-validator.js +5 -0
  39. package/dist/scripts/treasury-validator.d.ts +6 -0
  40. package/dist/scripts/treasury-validator.js +5 -0
  41. package/dist/types/generic.d.ts +10 -0
  42. package/dist/types/generic.js +1 -0
  43. package/dist/types/indigo/cdp.d.ts +37 -0
  44. package/dist/types/indigo/cdp.js +1 -0
  45. package/dist/types/indigo/gov.d.ts +20 -0
  46. package/dist/types/indigo/gov.js +1 -0
  47. package/dist/types/indigo/interest-oracle.d.ts +5 -0
  48. package/dist/types/indigo/interest-oracle.js +1 -0
  49. package/dist/types/indigo/price-oracle.d.ts +4 -0
  50. package/dist/types/indigo/price-oracle.js +1 -0
  51. package/dist/types/system-params.d.ts +217 -0
  52. package/dist/types/system-params.js +1 -0
  53. package/jest.config.js +13 -0
  54. package/package.json +46 -0
  55. package/src/contracts/cdp-creator.ts +86 -0
  56. package/src/contracts/cdp.ts +892 -0
  57. package/src/contracts/collector.ts +91 -0
  58. package/src/contracts/gov.ts +58 -0
  59. package/src/contracts/interest-oracle.ts +49 -0
  60. package/src/contracts/price-oracle.ts +24 -0
  61. package/src/contracts/treasury.ts +95 -0
  62. package/src/helpers/asset-helpers.ts +28 -0
  63. package/src/helpers/cdp-helpers.ts +9 -0
  64. package/src/helpers/helpers.ts +17 -0
  65. package/src/helpers/lucid-utils.ts +24 -0
  66. package/src/helpers/time-helpers.ts +3 -0
  67. package/src/index.ts +23 -0
  68. package/src/scripts/cdp-creator-validator.ts +9 -0
  69. package/src/scripts/cdp-validator.ts +9 -0
  70. package/src/scripts/collector-validator.ts +8 -0
  71. package/src/scripts/interest-oracle-validator.ts +8 -0
  72. package/src/scripts/treasury-validator.ts +8 -0
  73. package/src/types/generic.ts +13 -0
  74. package/src/types/indigo/cdp.ts +33 -0
  75. package/src/types/indigo/gov.ts +21 -0
  76. package/src/types/indigo/interest-oracle.ts +5 -0
  77. package/src/types/indigo/price-oracle.ts +4 -0
  78. package/src/types/system-params.ts +228 -0
  79. package/tests/data/system-params.json +989 -0
  80. package/tests/datums.test.ts +51 -0
  81. package/tests/hash-checks.test.ts +17 -0
  82. package/tests/interest-calculations.test.ts +143 -0
  83. package/tsconfig.json +35 -0
@@ -0,0 +1,892 @@
1
+ import {
2
+ applyParamsToScript,
3
+ Assets,
4
+ Constr,
5
+ Credential,
6
+ Data,
7
+ fromText,
8
+ LucidEvolution,
9
+ OutRef,
10
+ SpendingValidator,
11
+ toText,
12
+ TxBuilder,
13
+ UTxO,
14
+ validatorToAddress,
15
+ validatorToScriptHash,
16
+ } from '@lucid-evolution/lucid';
17
+ import {
18
+ CdpParams,
19
+ ScriptReferences,
20
+ SystemParams,
21
+ } from '../types/system-params';
22
+ import { IAssetHelpers } from '../helpers/asset-helpers';
23
+ import { PriceOracleContract } from './price-oracle';
24
+ import { CDPCreatorContract } from './cdp-creator';
25
+ import { CollectorContract } from './collector';
26
+ import { InterestOracleContract } from './interest-oracle';
27
+ import { GovContract } from './gov';
28
+ import { TreasuryContract } from './treasury';
29
+ import { addrDetails, getRandomElement, scriptRef } from '../helpers/lucid-utils';
30
+ import { AssetClass } from '../types/generic';
31
+ import { calculateFeeFromPercentage } from '../helpers/helpers';
32
+ import { CDP, CDPDatum, CDPFees } from '../types/indigo/cdp';
33
+ import { _cdpValidator } from '../scripts/cdp-validator';
34
+
35
+ export class CDPContract {
36
+ static async openPosition(
37
+ asset: string,
38
+ collateralAmount: bigint,
39
+ mintedAmount: bigint,
40
+ params: SystemParams,
41
+ lucid: LucidEvolution,
42
+ assetRef?: OutRef,
43
+ priceOracleRef?: OutRef,
44
+ interestOracleRef?: OutRef,
45
+ cdpCreatorRef?: OutRef,
46
+ collectorRef?: OutRef,
47
+ ): Promise<TxBuilder> {
48
+ const [pkh, skh] = await addrDetails(lucid);
49
+ const now = Date.now();
50
+ const assetOut = await (assetRef
51
+ ? IAssetHelpers.findIAssetByRef(assetRef, params, lucid)
52
+ : IAssetHelpers.findIAssetByName(asset, params, lucid));
53
+
54
+ // Fail if delisted asset
55
+ if ('getOnChainPrice' in assetOut.datum.price)
56
+ return Promise.reject('Trying to open CDP against delisted asset');
57
+
58
+ const oracleAsset = assetOut.datum.price as AssetClass;
59
+ const oracleOut = priceOracleRef
60
+ ? (await lucid.utxosByOutRef([priceOracleRef]))[0]
61
+ : await lucid.utxoByUnit(
62
+ oracleAsset[0].unCurrencySymbol +
63
+ fromText(oracleAsset[1].unTokenName),
64
+ );
65
+ if (!oracleOut.datum) return Promise.reject('Price Oracle datum not found');
66
+ const oracleDatum = PriceOracleContract.decodePriceOracleDatum(
67
+ oracleOut.datum,
68
+ );
69
+
70
+ const interestOracleAsset = assetOut.datum.interestOracle;
71
+ const interestOracleOut = interestOracleRef
72
+ ? (await lucid.utxosByOutRef([interestOracleRef]))[0]
73
+ : await lucid.utxoByUnit(
74
+ interestOracleAsset[0].unCurrencySymbol +
75
+ fromText(interestOracleAsset[1].unTokenName),
76
+ );
77
+ if (!interestOracleOut.datum)
78
+ return Promise.reject('Interest Oracle datum not found');
79
+ const interestOracleDatum =
80
+ InterestOracleContract.decodeInterestOracleDatum(interestOracleOut.datum);
81
+
82
+ const cdpCreatorOut = getRandomElement(
83
+ cdpCreatorRef
84
+ ? await lucid.utxosByOutRef([cdpCreatorRef])
85
+ : await lucid.utxosAtWithUnit(
86
+ CDPCreatorContract.address(params.cdpCreatorParams, lucid),
87
+ params.cdpCreatorParams.cdpCreatorNft[0].unCurrencySymbol +
88
+ fromText(params.cdpCreatorParams.cdpCreatorNft[1].unTokenName),
89
+ ),
90
+ );
91
+ const cdpCreatorRedeemer = CDPCreatorContract.redeemer(
92
+ pkh,
93
+ mintedAmount,
94
+ collateralAmount,
95
+ BigInt(now),
96
+ );
97
+ const cdpCreatorScriptRefUtxo = await CDPCreatorContract.scriptRef(
98
+ params.scriptReferences,
99
+ lucid,
100
+ );
101
+
102
+ const cdpAddress = CDPContract.address(params.cdpParams, lucid, skh);
103
+ const cdpToken =
104
+ params.cdpParams.cdpAuthToken[0].unCurrencySymbol +
105
+ fromText(params.cdpParams.cdpAuthToken[1].unTokenName);
106
+
107
+ const cdpValue: Assets = {
108
+ lovelace: collateralAmount,
109
+ };
110
+ cdpValue[cdpToken] = 1n;
111
+ const newSnapshot = InterestOracleContract.calculateUnitaryInterestSinceOracleLastUpdated(
112
+ BigInt(now),
113
+ interestOracleDatum,
114
+ ) + interestOracleDatum.unitaryInterest;
115
+ const cdpDatum = CDPContract.datum(pkh, asset, mintedAmount, {
116
+ type: 'ActiveCDPInterestTracking',
117
+ last_settled: BigInt(now),
118
+ unitary_interest_snapshot: newSnapshot
119
+ });
120
+
121
+ const assetToken =
122
+ params.cdpParams.cdpAssetSymbol.unCurrencySymbol + fromText(asset);
123
+ const cdpTokenMintValue: Assets = {};
124
+ cdpTokenMintValue[cdpToken] = 1n;
125
+ const iassetTokenMintValue: Assets = {};
126
+ iassetTokenMintValue[assetToken] = BigInt(mintedAmount);
127
+
128
+ const cdpAuthTokenScriptRefUtxo = await CDPContract.cdpAuthTokenRef(
129
+ params.scriptReferences,
130
+ lucid,
131
+ );
132
+ const iAssetTokenScriptRefUtxo = await CDPContract.assetTokenRef(
133
+ params.scriptReferences,
134
+ lucid,
135
+ );
136
+
137
+ const debtMintingFee = calculateFeeFromPercentage(
138
+ BigInt(assetOut.datum.debtMintingFeePercentage.getOnChainInt),
139
+ mintedAmount * oracleDatum.price,
140
+ );
141
+
142
+ // Oracle timestamp - 20s (length of a slot)
143
+ const cappedValidateTo = oracleDatum.expiration - 20_001n;
144
+ const timeValidFrom = now - 1_000;
145
+ const timeValidTo_ = now + params.cdpCreatorParams.biasTime - 1_000;
146
+ const timeValidTo =
147
+ cappedValidateTo <= timeValidFrom
148
+ ? timeValidTo_
149
+ : Math.min(timeValidTo_, Number(cappedValidateTo));
150
+
151
+ const tx = lucid
152
+ .newTx()
153
+ .collectFrom([cdpCreatorOut], Data.to(cdpCreatorRedeemer))
154
+ .readFrom([cdpCreatorScriptRefUtxo])
155
+ .pay.ToContract(
156
+ cdpAddress,
157
+ { kind: 'inline', value: Data.to(cdpDatum) },
158
+ cdpValue,
159
+ )
160
+ .pay.ToContract(
161
+ cdpCreatorOut.address,
162
+ { kind: 'inline', value: cdpCreatorOut.datum },
163
+ cdpCreatorOut.assets,
164
+ )
165
+ .readFrom([oracleOut, interestOracleOut, assetOut.utxo])
166
+ .mintAssets(cdpTokenMintValue, Data.to(new Constr(0, [])))
167
+ .readFrom([cdpAuthTokenScriptRefUtxo])
168
+ .mintAssets(iassetTokenMintValue, Data.to(new Constr(0, [])))
169
+ .readFrom([iAssetTokenScriptRefUtxo])
170
+ .addSignerKey(pkh.hash)
171
+ .validFrom(Number(now - 60_000))
172
+ .validTo(Number(timeValidTo));
173
+
174
+ if (debtMintingFee > 0) {
175
+ await CollectorContract.feeTx(
176
+ debtMintingFee,
177
+ lucid,
178
+ params,
179
+ tx,
180
+ collectorRef,
181
+ );
182
+ }
183
+ return tx;
184
+ }
185
+
186
+ static async deposit(
187
+ cdpRef: OutRef,
188
+ amount: bigint,
189
+ params: SystemParams,
190
+ lucid: LucidEvolution,
191
+ assetRef?: OutRef,
192
+ priceOracleRef?: OutRef,
193
+ interestOracleRef?: OutRef,
194
+ collectorRef?: OutRef,
195
+ govRef?: OutRef,
196
+ treasuryRef?: OutRef,
197
+ ): Promise<TxBuilder> {
198
+ return CDPContract.adjust(
199
+ cdpRef,
200
+ amount,
201
+ 0n,
202
+ params,
203
+ lucid,
204
+ assetRef,
205
+ priceOracleRef,
206
+ interestOracleRef,
207
+ collectorRef,
208
+ govRef,
209
+ treasuryRef,
210
+ );
211
+ }
212
+
213
+ static async withdraw(
214
+ cdpRef: OutRef,
215
+ amount: bigint,
216
+ params: SystemParams,
217
+ lucid: LucidEvolution,
218
+ assetRef?: OutRef,
219
+ priceOracleRef?: OutRef,
220
+ interestOracleRef?: OutRef,
221
+ collectorRef?: OutRef,
222
+ govRef?: OutRef,
223
+ treasuryRef?: OutRef,
224
+ ): Promise<TxBuilder> {
225
+ return CDPContract.adjust(
226
+ cdpRef,
227
+ -amount,
228
+ 0n,
229
+ params,
230
+ lucid,
231
+ assetRef,
232
+ priceOracleRef,
233
+ interestOracleRef,
234
+ collectorRef,
235
+ govRef,
236
+ treasuryRef,
237
+ );
238
+ }
239
+
240
+ static async mint(
241
+ cdpRef: OutRef,
242
+ amount: bigint,
243
+ params: SystemParams,
244
+ lucid: LucidEvolution,
245
+ assetRef?: OutRef,
246
+ priceOracleRef?: OutRef,
247
+ interestOracleRef?: OutRef,
248
+ collectorRef?: OutRef,
249
+ govRef?: OutRef,
250
+ treasuryRef?: OutRef,
251
+ ): Promise<TxBuilder> {
252
+ return CDPContract.adjust(
253
+ cdpRef,
254
+ 0n,
255
+ amount,
256
+ params,
257
+ lucid,
258
+ assetRef,
259
+ priceOracleRef,
260
+ interestOracleRef,
261
+ collectorRef,
262
+ govRef,
263
+ treasuryRef,
264
+ );
265
+ }
266
+
267
+ static async burn(
268
+ cdpRef: OutRef,
269
+ amount: bigint,
270
+ params: SystemParams,
271
+ lucid: LucidEvolution,
272
+ assetRef?: OutRef,
273
+ priceOracleRef?: OutRef,
274
+ interestOracleRef?: OutRef,
275
+ collectorRef?: OutRef,
276
+ govRef?: OutRef,
277
+ treasuryRef?: OutRef,
278
+ ): Promise<TxBuilder> {
279
+ return CDPContract.adjust(
280
+ cdpRef,
281
+ 0n,
282
+ -amount,
283
+ params,
284
+ lucid,
285
+ assetRef,
286
+ priceOracleRef,
287
+ interestOracleRef,
288
+ collectorRef,
289
+ govRef,
290
+ treasuryRef,
291
+ );
292
+ }
293
+
294
+ static async adjust(
295
+ cdpRef: OutRef,
296
+ collateralAmount: bigint,
297
+ mintAmount: bigint,
298
+ params: SystemParams,
299
+ lucid: LucidEvolution,
300
+ assetRef?: OutRef,
301
+ priceOracleRef?: OutRef,
302
+ interestOracleRef?: OutRef,
303
+ collectorRef?: OutRef,
304
+ govRef?: OutRef,
305
+ treasuryRef?: OutRef,
306
+ ): Promise<TxBuilder> {
307
+ // Find Pkh, Skh
308
+ const [pkh, skh] = await addrDetails(lucid);
309
+ const now = Date.now();
310
+
311
+ // Fail if no pkh
312
+ if (!pkh)
313
+ return Promise.reject(
314
+ 'Unable to determine the pub key hash of the wallet',
315
+ );
316
+
317
+ // Find Outputs: iAsset Output, CDP Output, Gov Output
318
+ const cdp = (await lucid.utxosByOutRef([cdpRef]))[0];
319
+ if (!cdp.datum) throw 'Unable to find CDP Datum';
320
+ const cdpDatum = CDPContract.decodeCdpDatum(cdp.datum);
321
+ if (cdpDatum.type !== 'CDP') throw 'Invalid CDP Datum';
322
+ const iAsset = await (assetRef
323
+ ? IAssetHelpers.findIAssetByRef(assetRef, params, lucid)
324
+ : IAssetHelpers.findIAssetByName(cdpDatum.asset, params, lucid));
325
+
326
+ const gov = govRef
327
+ ? (await lucid.utxosByOutRef([govRef]))[0]
328
+ : await lucid.utxoByUnit(
329
+ params.govParams.govNFT[0].unCurrencySymbol +
330
+ fromText(params.govParams.govNFT[1].unTokenName),
331
+ );
332
+ // const [iAsset, cdp, gov] = await lucid.utxosByOutRef([
333
+ // dIAssetTokenRef,
334
+ // dCDPTokenRef,
335
+ // dGovTokenRef,
336
+ // ]);
337
+ if (!gov.datum) throw 'Unable to find Gov Datum';
338
+ const govData = GovContract.decodeGovDatum(gov.datum);
339
+ if (!govData) throw 'No Governance datum found';
340
+ const cdpScriptRefUtxo = await CDPContract.scriptRef(
341
+ params.scriptReferences,
342
+ lucid,
343
+ );
344
+ const cdpAssets = Object.assign({}, cdp.assets);
345
+ cdpAssets['lovelace'] = cdp.assets['lovelace'] + collateralAmount;
346
+
347
+ const interestOracleAsset = iAsset.datum.interestOracle;
348
+ const interestOracleOut = interestOracleRef
349
+ ? (await lucid.utxosByOutRef([interestOracleRef]))[0]
350
+ : await lucid.utxoByUnit(
351
+ interestOracleAsset[0].unCurrencySymbol +
352
+ fromText(interestOracleAsset[1].unTokenName),
353
+ );
354
+ if (!interestOracleOut.datum)
355
+ return Promise.reject('Interest Oracle datum not found');
356
+ const interestOracleDatum =
357
+ InterestOracleContract.decodeInterestOracleDatum(interestOracleOut.datum);
358
+
359
+ let tx = lucid
360
+ .newTx()
361
+ .collectFrom([cdp], Data.to(new Constr(0, [BigInt(now), mintAmount, collateralAmount])))
362
+ .readFrom([iAsset.utxo, gov, cdpScriptRefUtxo])
363
+ .addSignerKey(pkh.hash);
364
+ if (!cdp.datum) throw 'Unable to find CDP Datum';
365
+ let cdpD = CDPContract.decodeCdpDatum(cdp.datum);
366
+ if (!cdpD || cdpD.type !== 'CDP') throw 'Invalid CDP Datum';
367
+
368
+ if (cdpD.fees.type !== 'ActiveCDPInterestTracking')
369
+ throw 'Invalid CDP Fees';
370
+
371
+ const newSnapshot = InterestOracleContract.calculateUnitaryInterestSinceOracleLastUpdated(
372
+ BigInt(now),
373
+ interestOracleDatum,
374
+ ) + interestOracleDatum.unitaryInterest;
375
+
376
+ const cdpD_: CDP = {
377
+ ...cdpD,
378
+ mintedAmount: cdpD.mintedAmount + mintAmount,
379
+ fees: {
380
+ type: 'ActiveCDPInterestTracking',
381
+ last_settled: BigInt(now),
382
+ unitary_interest_snapshot: newSnapshot
383
+ }
384
+ };
385
+
386
+ tx.pay.ToContract(
387
+ cdp.address,
388
+ {
389
+ kind: 'inline',
390
+ value: CDPContract.encodeCdpDatum(cdpD_),
391
+ },
392
+ cdpAssets,
393
+ );
394
+
395
+ // Find Oracle Ref Input
396
+ const oracleAsset = iAsset.datum.price as AssetClass;
397
+ const oracleRefInput = priceOracleRef
398
+ ? (await lucid.utxosByOutRef([priceOracleRef]))[0]
399
+ : await lucid.utxoByUnit(
400
+ oracleAsset[0].unCurrencySymbol +
401
+ fromText(oracleAsset[1].unTokenName),
402
+ );
403
+
404
+ // Fail if delisted asset
405
+ if (!oracleRefInput.datum) return Promise.reject('Invalid oracle input');
406
+ const od = PriceOracleContract.decodePriceOracleDatum(oracleRefInput.datum);
407
+ if (!od) return Promise.reject('Invalid oracle input');
408
+
409
+ // TODO: Sanity check: oacle expiration
410
+ // Oracle timestamp - 20s (length of a slot)
411
+ // Oracle timestamp - 20s (length of a slot)
412
+ const cappedValidateTo = od.expiration - 20_001n;
413
+ const timeValidFrom = now - 1_000;
414
+ const timeValidTo_ = now + params.cdpCreatorParams.biasTime - 1_000;
415
+ const timeValidTo =
416
+ cappedValidateTo <= timeValidFrom
417
+ ? timeValidTo_
418
+ : Math.min(timeValidTo_, Number(cappedValidateTo));
419
+ tx
420
+ .readFrom([oracleRefInput])
421
+ .validFrom(Number(timeValidFrom))
422
+ .validTo(Number(timeValidTo));
423
+
424
+ let fee = 0n;
425
+ if (collateralAmount < 0) {
426
+ fee += calculateFeeFromPercentage(
427
+ govData.protocolParams.collateralFeePercentage,
428
+ collateralAmount,
429
+ );
430
+ }
431
+
432
+ if (mintAmount > 0) {
433
+ fee += calculateFeeFromPercentage(
434
+ iAsset.datum.debtMintingFeePercentage.getOnChainInt,
435
+ mintAmount * od.price,
436
+ );
437
+ }
438
+
439
+ // Interest payment
440
+
441
+ const interestPaymentAsset = InterestOracleContract.calculateAccruedInterest(
442
+ BigInt(now),
443
+ cdpD.fees.unitary_interest_snapshot,
444
+ cdpD.mintedAmount,
445
+ cdpD.fees.last_settled,
446
+ interestOracleDatum,
447
+ );
448
+ const interestPayment = (interestPaymentAsset * od.price) / 1_000_000n;
449
+ const interestCollectorPayment = calculateFeeFromPercentage(
450
+ iAsset.datum.interestCollectorPortionPercentage.getOnChainInt,
451
+ interestPayment,
452
+ );
453
+ const interestTreasuryPayment = interestPayment - interestCollectorPayment;
454
+ console.log(interestPayment, interestCollectorPayment, interestTreasuryPayment);
455
+ if (interestTreasuryPayment > 0) {
456
+ await TreasuryContract.feeTx(interestTreasuryPayment, lucid, params, tx, treasuryRef);
457
+ }
458
+
459
+ fee += interestCollectorPayment;
460
+ tx.readFrom([interestOracleOut]);
461
+
462
+ if (mintAmount !== 0n) {
463
+ const iAssetTokenScriptRefUtxo = await CDPContract.assetTokenRef(
464
+ params.scriptReferences,
465
+ lucid,
466
+ );
467
+ const iassetToken =
468
+ params.cdpParams.cdpAssetSymbol.unCurrencySymbol + fromText(cdpD.asset);
469
+ const mintValue = {} as Assets;
470
+ mintValue[iassetToken] = mintAmount;
471
+
472
+ tx.readFrom([iAssetTokenScriptRefUtxo]).mintAssets(
473
+ mintValue,
474
+ Data.to(new Constr(0, [])),
475
+ );
476
+ }
477
+
478
+ if (fee > 0n) {
479
+ await CollectorContract.feeTx(fee, lucid, params, tx, collectorRef)
480
+ }
481
+
482
+ return tx;
483
+ }
484
+
485
+ static async close(
486
+ cdpRef: OutRef,
487
+ params: SystemParams,
488
+ lucid: LucidEvolution,
489
+ assetRef?: OutRef,
490
+ priceOracleRef?: OutRef,
491
+ interestOracleRef?: OutRef,
492
+ collectorRef?: OutRef,
493
+ govRef?: OutRef,
494
+ treasuryRef?: OutRef,
495
+ ): Promise<TxBuilder> {
496
+ // Find Pkh, Skh
497
+ const [pkh, skh] = await addrDetails(lucid);
498
+ const now = Date.now();
499
+
500
+ // Fail if no pkh
501
+ if (!pkh)
502
+ return Promise.reject(
503
+ 'Unable to determine the pub key hash of the wallet',
504
+ );
505
+
506
+ // Find Outputs: iAsset Output, CDP Output, Gov Output
507
+ const cdp = (await lucid.utxosByOutRef([cdpRef]))[0];
508
+ if (!cdp.datum) throw 'Unable to find CDP Datum';
509
+ const cdpDatum = CDPContract.decodeCdpDatum(cdp.datum);
510
+ if (cdpDatum.type !== 'CDP') throw 'Invalid CDP Datum';
511
+ const iAsset = await (assetRef
512
+ ? IAssetHelpers.findIAssetByRef(assetRef, params, lucid)
513
+ : IAssetHelpers.findIAssetByName(cdpDatum.asset, params, lucid));
514
+
515
+ const gov = govRef
516
+ ? (await lucid.utxosByOutRef([govRef]))[0]
517
+ : await lucid.utxoByUnit(
518
+ params.govParams.govNFT[0].unCurrencySymbol +
519
+ fromText(params.govParams.govNFT[1].unTokenName),
520
+ );
521
+
522
+ if (!gov.datum) throw 'Unable to find Gov Datum';
523
+ const govData = GovContract.decodeGovDatum(gov.datum);
524
+ if (!govData) throw 'No Governance datum found';
525
+ const cdpScriptRefUtxo = await CDPContract.scriptRef(
526
+ params.scriptReferences,
527
+ lucid,
528
+ );
529
+
530
+ const interestOracleAsset = iAsset.datum.interestOracle;
531
+ const interestOracleOut = interestOracleRef
532
+ ? (await lucid.utxosByOutRef([interestOracleRef]))[0]
533
+ : await lucid.utxoByUnit(
534
+ interestOracleAsset[0].unCurrencySymbol +
535
+ fromText(interestOracleAsset[1].unTokenName),
536
+ );
537
+ if (!interestOracleOut.datum)
538
+ return Promise.reject('Interest Oracle datum not found');
539
+ const interestOracleDatum =
540
+ InterestOracleContract.decodeInterestOracleDatum(interestOracleOut.datum);
541
+
542
+ let tx = lucid
543
+ .newTx()
544
+ .collectFrom([cdp], Data.to(new Constr(1, [BigInt(now)])))
545
+ .readFrom([iAsset.utxo, gov, cdpScriptRefUtxo])
546
+ .addSignerKey(pkh.hash);
547
+ if (!cdp.datum) throw 'Unable to find CDP Datum';
548
+ let cdpD = CDPContract.decodeCdpDatum(cdp.datum);
549
+ if (!cdpD || cdpD.type !== 'CDP') throw 'Invalid CDP Datum';
550
+
551
+ if (cdpD.fees.type !== 'ActiveCDPInterestTracking')
552
+ throw 'Invalid CDP Fees';
553
+
554
+ // Find Oracle Ref Input
555
+ const oracleAsset = iAsset.datum.price as AssetClass;
556
+ const oracleRefInput = priceOracleRef
557
+ ? (await lucid.utxosByOutRef([priceOracleRef]))[0]
558
+ : await lucid.utxoByUnit(
559
+ oracleAsset[0].unCurrencySymbol +
560
+ fromText(oracleAsset[1].unTokenName),
561
+ );
562
+
563
+ // Fail if delisted asset
564
+ if (!oracleRefInput.datum) return Promise.reject('Invalid oracle input');
565
+ const od = PriceOracleContract.decodePriceOracleDatum(oracleRefInput.datum);
566
+ if (!od) return Promise.reject('Invalid oracle input');
567
+
568
+ // TODO: Sanity check: oacle expiration
569
+ // Oracle timestamp - 20s (length of a slot)
570
+ // Oracle timestamp - 20s (length of a slot)
571
+ const cappedValidateTo = od.expiration - 20_001n;
572
+ const timeValidFrom = now - 1_000;
573
+ const timeValidTo_ = now + params.cdpCreatorParams.biasTime - 1_000;
574
+ const timeValidTo =
575
+ cappedValidateTo <= timeValidFrom
576
+ ? timeValidTo_
577
+ : Math.min(timeValidTo_, Number(cappedValidateTo));
578
+ tx
579
+ .readFrom([oracleRefInput])
580
+ .validFrom(Number(timeValidFrom))
581
+ .validTo(Number(timeValidTo));
582
+
583
+ let fee = 0n;
584
+
585
+ // Interest payment
586
+ const interestPaymentAsset = InterestOracleContract.calculateAccruedInterest(
587
+ BigInt(now),
588
+ cdpD.fees.unitary_interest_snapshot,
589
+ cdpD.mintedAmount,
590
+ cdpD.fees.last_settled,
591
+ interestOracleDatum,
592
+ );
593
+ const interestPayment = (interestPaymentAsset * od.price) / 1_000_000n;
594
+ const interestCollectorPayment = calculateFeeFromPercentage(
595
+ iAsset.datum.interestCollectorPortionPercentage.getOnChainInt,
596
+ interestPayment,
597
+ );
598
+ const interestTreasuryPayment = interestPayment - interestCollectorPayment;
599
+ console.log(interestPayment, interestCollectorPayment, interestTreasuryPayment);
600
+ if (interestTreasuryPayment > 0) {
601
+ await TreasuryContract.feeTx(interestTreasuryPayment, lucid, params, tx, treasuryRef);
602
+ }
603
+
604
+ fee += interestCollectorPayment;
605
+ tx.readFrom([interestOracleOut]);
606
+
607
+ const iAssetTokenScriptRefUtxo = await CDPContract.assetTokenRef(
608
+ params.scriptReferences,
609
+ lucid,
610
+ );
611
+ const iassetToken =
612
+ params.cdpParams.cdpAssetSymbol.unCurrencySymbol + fromText(cdpD.asset);
613
+ const assetBurnValue = {} as Assets;
614
+ assetBurnValue[iassetToken] = -BigInt(cdpD.mintedAmount);
615
+ const cdpTokenBurnValue = {} as Assets;
616
+ cdpTokenBurnValue[params.cdpParams.cdpAuthToken[0].unCurrencySymbol + fromText(params.cdpParams.cdpAuthToken[1].unTokenName)] = -1n;
617
+ const cdpAuthTokenScriptRefUtxo = await CDPContract.cdpAuthTokenRef(
618
+ params.scriptReferences,
619
+ lucid,
620
+ );
621
+ tx.readFrom([iAssetTokenScriptRefUtxo]).mintAssets(
622
+ assetBurnValue,
623
+ Data.to(new Constr(0, [])),
624
+ ).readFrom([cdpAuthTokenScriptRefUtxo]).mintAssets(
625
+ cdpTokenBurnValue,
626
+ Data.to(new Constr(0, [])),
627
+ );
628
+
629
+ if (fee > 0n) {
630
+ await CollectorContract.feeTx(fee, lucid, params, tx, collectorRef)
631
+ }
632
+
633
+ return tx;
634
+ }
635
+
636
+ static decodeCdpDatum(datum: string): CDPDatum {
637
+ const cdpDatum = Data.from(datum) as any;
638
+ if (cdpDatum.index == 1 && cdpDatum.fields[0].index == 0) {
639
+ const iasset = cdpDatum.fields[0].fields;
640
+ return {
641
+ type: 'IAsset',
642
+ name: toText(iasset[0]),
643
+ price:
644
+ iasset[1].index === 0
645
+ ? { getOnChainInt: iasset[1].fields[0] }
646
+ : [
647
+ { unCurrencySymbol: iasset[1].fields[0].fields[0].fields[0] },
648
+ {
649
+ unTokenName: toText(iasset[1].fields[0].fields[0].fields[1]),
650
+ },
651
+ ],
652
+ interestOracle: [
653
+ { unCurrencySymbol: iasset[2].fields[0] },
654
+ { unTokenName: toText(iasset[2].fields[1]) },
655
+ ],
656
+ redemptionRatioPercentage: { getOnChainInt: iasset[3].fields[0] },
657
+ maintenanceRatioPercentage: { getOnChainInt: iasset[4].fields[0] },
658
+ liquidationRatioPercentage: { getOnChainInt: iasset[5].fields[0] },
659
+ debtMintingFeePercentage: { getOnChainInt: iasset[6].fields[0] },
660
+ liquidationProcessingFeePercentage: {
661
+ getOnChainInt: iasset[7].fields[0],
662
+ },
663
+ stabilityPoolWithdrawalFeePercentage: {
664
+ getOnChainInt: iasset[8].fields[0],
665
+ },
666
+ redemptionReimbursementPercentage: {
667
+ getOnChainInt: iasset[9].fields[0],
668
+ },
669
+ redemptionProcessingFeePercentage: {
670
+ getOnChainInt: iasset[10].fields[0],
671
+ },
672
+ interestCollectorPortionPercentage: {
673
+ getOnChainInt: iasset[11].fields[0],
674
+ },
675
+ firstAsset: iasset[12].index === 1,
676
+ nextAsset:
677
+ iasset[13].index === 0 ? toText(iasset[13].fields[0]) : undefined,
678
+ };
679
+ } else if (cdpDatum.index == 0 && cdpDatum.fields[0].index == 0) {
680
+ const cdp = cdpDatum.fields[0].fields;
681
+ return {
682
+ type: 'CDP',
683
+ owner: cdp[0].fields[0],
684
+ asset: toText(cdp[1]),
685
+ mintedAmount: cdp[2],
686
+ fees:
687
+ cdp[3].index === 0
688
+ ? {
689
+ type: 'ActiveCDPInterestTracking',
690
+ last_settled: cdp[3].fields[0],
691
+ unitary_interest_snapshot: cdp[3].fields[1],
692
+ }
693
+ : {
694
+ type: 'FrozenCDPAccumulatedFees',
695
+ lovelaces_treasury: cdp[3].fields[0],
696
+ lovelaces_indy_stakers: cdp[3].fields[1],
697
+ },
698
+ };
699
+ }
700
+
701
+ throw 'Invalid CDP Datum provided';
702
+ }
703
+
704
+ static encodeCdpDatum(datum: CDPDatum): string {
705
+ if (datum.type === 'CDP') {
706
+ return Data.to(
707
+ new Constr(0, [
708
+ new Constr(0, [
709
+ datum.owner ? new Constr(0, [datum.owner]) : new Constr(1, []),
710
+ fromText(datum.asset),
711
+ BigInt(datum.mintedAmount),
712
+ datum.fees.type === 'ActiveCDPInterestTracking'
713
+ ? new Constr(0, [
714
+ datum.fees.last_settled,
715
+ datum.fees.unitary_interest_snapshot,
716
+ ])
717
+ : new Constr(1, [
718
+ datum.fees.lovelaces_treasury,
719
+ datum.fees.lovelaces_indy_stakers,
720
+ ]),
721
+ ]),
722
+ ]),
723
+ );
724
+ } else if (datum.type === 'IAsset') {
725
+ return Data.to(
726
+ new Constr(1, [
727
+ new Constr(0, [
728
+ fromText(datum.name),
729
+ 'getOnChainInt' in datum.price
730
+ ? new Constr(0, [
731
+ new Constr(0, [BigInt(datum.price.getOnChainInt)]),
732
+ ])
733
+ : new Constr(1, [
734
+ new Constr(0, [
735
+ new Constr(0, [
736
+ datum.price[0].unCurrencySymbol,
737
+ fromText(datum.price[1].unTokenName),
738
+ ]),
739
+ ]),
740
+ ]),
741
+ new Constr(0, [
742
+ datum.interestOracle[0].unCurrencySymbol,
743
+ fromText(datum.interestOracle[1].unTokenName),
744
+ ]),
745
+ new Constr(0, [
746
+ BigInt(datum.redemptionRatioPercentage.getOnChainInt),
747
+ ]),
748
+ new Constr(0, [
749
+ BigInt(datum.maintenanceRatioPercentage.getOnChainInt),
750
+ ]),
751
+ new Constr(0, [
752
+ BigInt(datum.liquidationRatioPercentage.getOnChainInt),
753
+ ]),
754
+ new Constr(0, [
755
+ BigInt(datum.debtMintingFeePercentage.getOnChainInt),
756
+ ]),
757
+ new Constr(0, [
758
+ BigInt(datum.liquidationProcessingFeePercentage.getOnChainInt),
759
+ ]),
760
+ new Constr(0, [
761
+ BigInt(datum.stabilityPoolWithdrawalFeePercentage.getOnChainInt),
762
+ ]),
763
+ new Constr(0, [
764
+ BigInt(datum.redemptionReimbursementPercentage.getOnChainInt),
765
+ ]),
766
+ new Constr(0, [
767
+ BigInt(datum.redemptionProcessingFeePercentage.getOnChainInt),
768
+ ]),
769
+ new Constr(0, [
770
+ BigInt(datum.interestCollectorPortionPercentage.getOnChainInt),
771
+ ]),
772
+ datum.firstAsset ? new Constr(1, []) : new Constr(0, []),
773
+ datum.nextAsset
774
+ ? new Constr(0, [fromText(datum.nextAsset)])
775
+ : new Constr(1, []),
776
+ ]),
777
+ ]),
778
+ );
779
+ }
780
+
781
+ throw 'Invalid CDP Datum provided';
782
+ }
783
+
784
+ static datum(
785
+ hash: Credential,
786
+ asset: string,
787
+ mintedAmount: bigint,
788
+ fees: CDPFees,
789
+ ): Constr<Data> {
790
+ return new Constr(0, [
791
+ new Constr(0, [
792
+ new Constr(0, [hash.hash]),
793
+ fromText(asset),
794
+ BigInt(mintedAmount),
795
+ fees.type === 'ActiveCDPInterestTracking'
796
+ ? new Constr(0, [
797
+ BigInt(fees.last_settled),
798
+ BigInt(fees.unitary_interest_snapshot),
799
+ ])
800
+ : new Constr(0, [
801
+ BigInt(fees.lovelaces_treasury),
802
+ BigInt(fees.lovelaces_indy_stakers),
803
+ ]),
804
+ ]),
805
+ ]);
806
+ }
807
+
808
+ static validator(params: CdpParams): SpendingValidator {
809
+ return {
810
+ type: _cdpValidator.type,
811
+ script: applyParamsToScript(_cdpValidator.cborHex, [
812
+ new Constr(0, [
813
+ new Constr(0, [
814
+ params.cdpAuthToken[0].unCurrencySymbol,
815
+ fromText(params.cdpAuthToken[1].unTokenName),
816
+ ]),
817
+ params.cdpAssetSymbol.unCurrencySymbol,
818
+ new Constr(0, [
819
+ params.iAssetAuthToken[0].unCurrencySymbol,
820
+ fromText(params.iAssetAuthToken[1].unTokenName),
821
+ ]),
822
+ new Constr(0, [
823
+ params.stabilityPoolAuthToken[0].unCurrencySymbol,
824
+ fromText(params.stabilityPoolAuthToken[1].unTokenName),
825
+ ]),
826
+ new Constr(0, [
827
+ params.versionRecordToken[0].unCurrencySymbol,
828
+ fromText(params.versionRecordToken[1].unTokenName),
829
+ ]),
830
+ new Constr(0, [
831
+ params.upgradeToken[0].unCurrencySymbol,
832
+ fromText(params.upgradeToken[1].unTokenName),
833
+ ]),
834
+ params.collectorValHash,
835
+ params.spValHash,
836
+ new Constr(0, [
837
+ params.govNFT[0].unCurrencySymbol,
838
+ fromText(params.govNFT[1].unTokenName),
839
+ ]),
840
+ BigInt(params.minCollateralInLovelace),
841
+ BigInt(params.partialRedemptionExtraFeeLovelace),
842
+ BigInt(params.biasTime),
843
+ params.treasuryValHash,
844
+ ]),
845
+ ]),
846
+ };
847
+ }
848
+
849
+ static validatorHash(params: CdpParams): string {
850
+ return validatorToScriptHash(CDPContract.validator(params));
851
+ }
852
+
853
+ static address(
854
+ cdpParams: CdpParams,
855
+ lucid: LucidEvolution,
856
+ skh?: Credential,
857
+ ) {
858
+ const network = lucid.config().network;
859
+ if (!network) {
860
+ throw new Error('Network configuration is undefined');
861
+ }
862
+ return validatorToAddress(network, CDPContract.validator(cdpParams), skh);
863
+ }
864
+
865
+ static scriptRef(
866
+ params: ScriptReferences,
867
+ lucid: LucidEvolution,
868
+ ): Promise<UTxO> {
869
+ return scriptRef(params.cdpValidatorRef, lucid);
870
+ }
871
+
872
+ static cdpAuthTokenRef(
873
+ params: ScriptReferences,
874
+ lucid: LucidEvolution,
875
+ ): Promise<UTxO> {
876
+ return scriptRef(params.authTokenPolicies.cdpAuthTokenRef, lucid);
877
+ }
878
+
879
+ static assetTokenRef(
880
+ params: ScriptReferences,
881
+ lucid: LucidEvolution,
882
+ ): Promise<UTxO> {
883
+ return scriptRef(params.iAssetTokenPolicyRef, lucid);
884
+ }
885
+
886
+ static assetAuthTokenRef(
887
+ params: ScriptReferences,
888
+ lucid: LucidEvolution,
889
+ ): Promise<UTxO> {
890
+ return scriptRef(params.authTokenPolicies.iAssetTokenRef, lucid);
891
+ }
892
+ }