@indigo-labs/indigo-sdk 0.2.1 → 0.2.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigo-labs/indigo-sdk",
3
- "version": "0.2.1",
3
+ "version": "0.2.4",
4
4
  "description": "Indigo SDK for interacting with Indigo endpoints via lucid-evolution",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -1,5 +1,4 @@
1
1
  import {
2
- Constr,
3
2
  Data,
4
3
  LucidEvolution,
5
4
  OutRef,
@@ -11,6 +10,7 @@ import {
11
10
  SystemParams,
12
11
  } from '../../types/system-params';
13
12
  import { matchSingle } from '../../utils/utils';
13
+ import { serialiseCollectorRedeemer } from './types';
14
14
 
15
15
  export async function collectorFeeTx(
16
16
  fee: bigint,
@@ -31,10 +31,10 @@ export async function collectorFeeTx(
31
31
  (_) => new Error('Expected a single collector Ref Script UTXO'),
32
32
  );
33
33
 
34
- tx.collectFrom([collectorUtxo], Data.to(new Constr(0, [])))
34
+ tx.collectFrom([collectorUtxo], serialiseCollectorRedeemer('Collect'))
35
35
  .pay.ToContract(
36
36
  collectorUtxo.address,
37
- { kind: 'inline', value: Data.to(new Constr(0, [])) },
37
+ { kind: 'inline', value: Data.void() },
38
38
  {
39
39
  ...collectorUtxo.assets,
40
40
  lovelace: collectorUtxo.assets.lovelace + fee,
@@ -0,0 +1,16 @@
1
+ import { Data, Redeemer } from '@lucid-evolution/lucid';
2
+
3
+ const CollectorRedeemerSchema = Data.Enum([
4
+ Data.Literal('Collect'),
5
+ Data.Literal('DistributeToStakers'),
6
+ Data.Literal('UpgradeVersion'),
7
+ ]);
8
+ export type CollectorRedeemer = Data.Static<typeof CollectorRedeemerSchema>;
9
+ const CollectorRedeemer =
10
+ CollectorRedeemerSchema as unknown as CollectorRedeemer;
11
+
12
+ export function serialiseCollectorRedeemer(
13
+ redeemer: CollectorRedeemer,
14
+ ): Redeemer {
15
+ return Data.to<CollectorRedeemer>(redeemer, CollectorRedeemer);
16
+ }
@@ -0,0 +1,424 @@
1
+ /**
2
+ * The following is the math related to the leverage calculations.
3
+ *
4
+ * Leverage is the multiplier you apply to the base deposit and you get the amount of final collateral
5
+ * the CDP should have. Additionally, the minted amount is used to pay for fees. The leverage a user picks, is
6
+ * already taking into account the fees, i.e. the fees are paid from the borrowed assets.
7
+ *
8
+ * There's a direct relationship between collateral ratio and leverage multiplier. Each leverage multiplier
9
+ * results in a single collateral ratio and vice versa. Maximum potential leverage is the leverage that
10
+ * results in collateral ratio being the maintenance collateral ratio of the corresponding iAsset.
11
+ *
12
+ * `d` = base deposit
13
+ * `b` = total borrowed value (including the fees)
14
+ * `L` = leverage
15
+ * `f_m` = debt minting fee
16
+ * `f_r` = reimbursement fee
17
+ * `c` = collateral ratio
18
+ *
19
+ * The following is a detailed derivation of the math:
20
+ *
21
+ * 1. Since the redemption fee is proportional to the borrowed amount,
22
+ * we can express the ADA we get from the order book as `b'=b*(1-f_r)`,
23
+ * since some of the borrowed amount goes back to the order book.
24
+ *
25
+ * 2. Since all the minted iAsset are used to get borrowed ADA,
26
+ * the value of the minted asset will be `b`.
27
+ *
28
+ * 3. The minting fee is a percentage of the value of the minted iAsset.
29
+ * Therefore the available ADA to add as collateral is `b''=b' - b*f_m = b*(1 - f_r - f_m)`.
30
+ *
31
+ * 4. The collateral ratio can now be expressed as `c = (d + b * (1 - f_r - f_m)) / b`.
32
+ *
33
+ * 5. Working out the expression, we can express `b` in terms of everything else: `b = d / (c - 1 + f_r + f_m)`.
34
+ *
35
+ * 6. The minted amount will be `b / asset_price`.
36
+ *
37
+ * 7. Collateral amount of the CDP is `d + b * (1 - f_r - f_m)`
38
+ *
39
+ * 8. Leverage calculation: `L = (d + b * (1 - f_r - f_m)) / d`.
40
+ *
41
+ * Plugging in the `b` formula we get: `L = (d + (d / (c - 1 + f_r + f_m)) * (1 - f_r - f_m)) / d`.
42
+ *
43
+ * Simplified, yields the following:
44
+ * `L = 1 + ((1 - f_r - f_m) / (c - 1 + f_r + f_m))`
45
+ *
46
+ * 9. `b'' = b * (1 - f_r - f_m)`
47
+ * Solved for `b` yields the following:
48
+ * `b = b'' / (1 - f_r - f_m)`
49
+ *
50
+ * 10. Having leverage and base deposit, we can find `b''`:
51
+ * `b’’ = d(L - 1)`
52
+ */
53
+
54
+ import { UTxO } from '@lucid-evolution/lucid';
55
+ import {
56
+ OCD_DECIMAL_UNIT,
57
+ ocdMul,
58
+ OnChainDecimal,
59
+ } from '../../types/on-chain-decimal';
60
+ import { calculateFeeFromPercentage } from '../../utils/indigo-helpers';
61
+ import { bigintMax, bigintMin, fromDecimal } from '../../utils/bigint-utils';
62
+ import { array as A, function as F } from 'fp-ts';
63
+ import { Decimal } from 'decimal.js';
64
+ import { LrpParamsSP } from '../../types/system-params';
65
+ import {
66
+ calculateTotalAdaForRedemption,
67
+ lrpRedeemableLovelacesInclReimb,
68
+ } from '../lrp/helpers';
69
+ import { LRPDatum } from '../lrp/types';
70
+
71
+ /**
72
+ * How many LRP redemptions can we fit into a TX with CDP open.
73
+ */
74
+ export const MAX_REDEMPTIONS_WITH_CDP_OPEN = 4;
75
+
76
+ type LRPRedemptionDetails = {
77
+ utxo: UTxO;
78
+ /**
79
+ * This is including the reimbursement fee.
80
+ **/
81
+ redemptionLovelacesAmtInclReimbursement: bigint;
82
+ iassetsForRedemptionAmt: bigint;
83
+ reimbursementLovelacesAmt: bigint;
84
+ };
85
+
86
+ type ApproximateLeverageRedemptionsResult = {
87
+ leverage: number;
88
+ collateralRatio: OnChainDecimal;
89
+ lovelacesForRedemptionWithReimbursement: bigint;
90
+ };
91
+ /**
92
+ * We assume exact precision. However, actual redemptions include rounding and
93
+ * the rounding behaviour changes based on the number of redemptions.
94
+ * This may slightly tweak the numbers and the result can be different.
95
+ *
96
+ * The math is described at the top of this code file.
97
+ */
98
+ export function approximateLeverageRedemptions(
99
+ baseCollateral: bigint,
100
+ targetLeverage: number,
101
+ redemptionReimbursementPercentage: OnChainDecimal,
102
+ debtMintingFeePercentage: OnChainDecimal,
103
+ ): ApproximateLeverageRedemptionsResult {
104
+ const debtMintingFeeRatioDecimal = Decimal(
105
+ debtMintingFeePercentage.getOnChainInt,
106
+ )
107
+ .div(OCD_DECIMAL_UNIT)
108
+ .div(100);
109
+ const redemptionReimbursementRatioDecimal = Decimal(
110
+ redemptionReimbursementPercentage.getOnChainInt,
111
+ )
112
+ .div(OCD_DECIMAL_UNIT)
113
+ .div(100);
114
+
115
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
116
+ redemptionReimbursementRatioDecimal,
117
+ );
118
+
119
+ // b''
120
+ const bExFees = Decimal(baseCollateral)
121
+ .mul(targetLeverage)
122
+ .minus(baseCollateral)
123
+ .floor();
124
+
125
+ // b = b’’ / (1-f_r - f_m)
126
+ const b = bExFees.div(Decimal(1).minus(totalFeeRatio)).floor();
127
+
128
+ // c = (d + b * (1 - f_r - f_m)) / b
129
+ const collateralRatio = {
130
+ getOnChainInt: fromDecimal(
131
+ Decimal(Decimal(baseCollateral).add(bExFees))
132
+ .div(b)
133
+ .mul(100n * OCD_DECIMAL_UNIT)
134
+ .floor(),
135
+ ),
136
+ };
137
+
138
+ return {
139
+ leverage: targetLeverage,
140
+ collateralRatio: collateralRatio,
141
+ lovelacesForRedemptionWithReimbursement: fromDecimal(b),
142
+ };
143
+ }
144
+
145
+ export function summarizeActualLeverageRedemptions(
146
+ lovelacesForRedemptionWithReimbursement: bigint,
147
+ redemptionReimbursementPercentage: OnChainDecimal,
148
+ iassetPrice: OnChainDecimal,
149
+ lrpParams: LrpParamsSP,
150
+ // Picking from the beginning until the iasset redemption amount is satisfied.
151
+ redemptionLrps: [UTxO, LRPDatum][],
152
+ ): {
153
+ redemptions: LRPRedemptionDetails[];
154
+ /**
155
+ * The actual amount received from redemptions (i.e. without the reimbursement fee).
156
+ */
157
+ totalRedeemedLovelaces: bigint;
158
+ /**
159
+ * Total lovelaces amt that has been reimbursted
160
+ */
161
+ totalReimbursementLovelaces: bigint;
162
+ totalRedemptionIAssets: bigint;
163
+ } {
164
+ const priceDecimal = Decimal(iassetPrice.getOnChainInt).div(OCD_DECIMAL_UNIT);
165
+
166
+ type Accumulator = {
167
+ /// This is including the redemption reimbursement
168
+ remainingRedemptionLovelacesInclReim: bigint;
169
+ redemptions: LRPRedemptionDetails[];
170
+ };
171
+
172
+ const redemptionDetails = F.pipe(
173
+ redemptionLrps,
174
+ A.reduce<[UTxO, LRPDatum], Accumulator>(
175
+ {
176
+ remainingRedemptionLovelacesInclReim:
177
+ lovelacesForRedemptionWithReimbursement,
178
+ redemptions: [],
179
+ },
180
+ (acc, lrp) => {
181
+ if (
182
+ acc.remainingRedemptionLovelacesInclReim <
183
+ lrpParams.minRedemptionLovelacesAmt
184
+ ) {
185
+ return acc;
186
+ }
187
+
188
+ const lovelacesToSpend = lrpRedeemableLovelacesInclReimb(
189
+ lrp,
190
+ lrpParams,
191
+ );
192
+
193
+ if (lovelacesToSpend === 0n) {
194
+ return acc;
195
+ }
196
+
197
+ const newRemainingLovelaces = bigintMax(
198
+ acc.remainingRedemptionLovelacesInclReim - lovelacesToSpend,
199
+ 0n,
200
+ );
201
+ const redemptionLovelacesInitial =
202
+ acc.remainingRedemptionLovelacesInclReim - newRemainingLovelaces;
203
+
204
+ const finalRedemptionIAssets = fromDecimal(
205
+ Decimal(redemptionLovelacesInitial).div(priceDecimal).floor(),
206
+ );
207
+ // We need to calculate the new number since redemptionIAssets got corrected by rounding.
208
+ const finalRedemptionLovelaces = ocdMul(
209
+ {
210
+ getOnChainInt: finalRedemptionIAssets,
211
+ },
212
+ iassetPrice,
213
+ ).getOnChainInt;
214
+
215
+ const reimbursementLovelaces = calculateFeeFromPercentage(
216
+ redemptionReimbursementPercentage,
217
+ finalRedemptionLovelaces,
218
+ );
219
+
220
+ return {
221
+ remainingRedemptionLovelacesInclReim:
222
+ acc.remainingRedemptionLovelacesInclReim - finalRedemptionLovelaces,
223
+ redemptions: [
224
+ ...acc.redemptions,
225
+ {
226
+ utxo: lrp[0],
227
+ iassetsForRedemptionAmt: finalRedemptionIAssets,
228
+ redemptionLovelacesAmtInclReimbursement: finalRedemptionLovelaces,
229
+ reimbursementLovelacesAmt: reimbursementLovelaces,
230
+ },
231
+ ],
232
+ };
233
+ },
234
+ ),
235
+ );
236
+
237
+ const res = F.pipe(
238
+ redemptionDetails.redemptions,
239
+ A.reduce<
240
+ LRPRedemptionDetails,
241
+ {
242
+ redeemedLovelaces: bigint;
243
+ redemptionIAssets: bigint;
244
+ reimbursementLovelaces: bigint;
245
+ }
246
+ >(
247
+ {
248
+ redeemedLovelaces: 0n,
249
+ redemptionIAssets: 0n,
250
+ reimbursementLovelaces: 0n,
251
+ },
252
+ (acc, details) => {
253
+ return {
254
+ redeemedLovelaces:
255
+ acc.redeemedLovelaces +
256
+ details.redemptionLovelacesAmtInclReimbursement -
257
+ details.reimbursementLovelacesAmt,
258
+ reimbursementLovelaces:
259
+ acc.reimbursementLovelaces + details.reimbursementLovelacesAmt,
260
+ redemptionIAssets:
261
+ acc.redemptionIAssets + details.iassetsForRedemptionAmt,
262
+ };
263
+ },
264
+ ),
265
+ );
266
+
267
+ return {
268
+ redemptions: redemptionDetails.redemptions,
269
+ totalRedeemedLovelaces: res.redeemedLovelaces,
270
+ totalReimbursementLovelaces: res.reimbursementLovelaces,
271
+ totalRedemptionIAssets: res.redemptionIAssets,
272
+ };
273
+ }
274
+
275
+ /**
276
+ * The math is described at the top of this code file.
277
+ */
278
+ export function calculateCollateralRatioFromLeverage(
279
+ iasset: string,
280
+ leverage: number,
281
+ baseCollateral: bigint,
282
+ iassetPrice: OnChainDecimal,
283
+ debtMintingFeePercentage: OnChainDecimal,
284
+ redemptionReimbursementPercentage: OnChainDecimal,
285
+ lrpParams: LrpParamsSP,
286
+ allLrps: [UTxO, LRPDatum][],
287
+ ): OnChainDecimal | undefined {
288
+ const debtMintingFeeRatioDecimal = Decimal(
289
+ debtMintingFeePercentage.getOnChainInt,
290
+ )
291
+ .div(OCD_DECIMAL_UNIT)
292
+ .div(100);
293
+ const redemptionReimbursementRatioDecimal = Decimal(
294
+ redemptionReimbursementPercentage.getOnChainInt,
295
+ )
296
+ .div(OCD_DECIMAL_UNIT)
297
+ .div(100);
298
+
299
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
300
+ redemptionReimbursementRatioDecimal,
301
+ );
302
+
303
+ const maxAvailableAdaForRedemptionInclReimb = calculateTotalAdaForRedemption(
304
+ iasset,
305
+ iassetPrice,
306
+ lrpParams,
307
+ allLrps,
308
+ MAX_REDEMPTIONS_WITH_CDP_OPEN,
309
+ );
310
+
311
+ if (
312
+ leverage <= 1 ||
313
+ baseCollateral <= 0n ||
314
+ maxAvailableAdaForRedemptionInclReimb <= 0n
315
+ ) {
316
+ return undefined;
317
+ }
318
+
319
+ // b''
320
+ const bExFees = Decimal(baseCollateral)
321
+ .mul(leverage)
322
+ .minus(baseCollateral)
323
+ .floor();
324
+
325
+ // b = b’’ / (1-f_r - f_m)
326
+ const b = bExFees.div(Decimal(1).minus(totalFeeRatio)).floor();
327
+
328
+ const cappedB = bigintMin(
329
+ maxAvailableAdaForRedemptionInclReimb,
330
+ fromDecimal(b),
331
+ );
332
+
333
+ const cappedBExFees = Decimal(cappedB)
334
+ .mul(Decimal(1).minus(totalFeeRatio))
335
+ .floor();
336
+
337
+ // c = (d + b * (1 - f_r - f_m)) / b
338
+ const collateralRatio = Decimal(
339
+ Decimal(baseCollateral).add(cappedBExFees),
340
+ ).div(cappedB);
341
+
342
+ return {
343
+ getOnChainInt: fromDecimal(
344
+ collateralRatio.mul(100n * OCD_DECIMAL_UNIT).floor(),
345
+ ),
346
+ };
347
+ }
348
+
349
+ /**
350
+ * The math is described at the top of this code file.
351
+ */
352
+ export function calculateLeverageFromCollateralRatio(
353
+ iasset: string,
354
+ collateralRatioPercentage: OnChainDecimal,
355
+ baseCollateral: bigint,
356
+ iassetPrice: OnChainDecimal,
357
+ debtMintingFeePercentage: OnChainDecimal,
358
+ redemptionReimbursementPercentage: OnChainDecimal,
359
+ lrpParams: LrpParamsSP,
360
+ allLrps: [UTxO, LRPDatum][],
361
+ ): number | undefined {
362
+ const debtMintingFeeRatioDecimal = Decimal(
363
+ debtMintingFeePercentage.getOnChainInt,
364
+ )
365
+ .div(OCD_DECIMAL_UNIT)
366
+ .div(100);
367
+ const redemptionReimbursementRatioDecimal = Decimal(
368
+ redemptionReimbursementPercentage.getOnChainInt,
369
+ )
370
+ .div(OCD_DECIMAL_UNIT)
371
+ .div(100);
372
+
373
+ const totalFeeRatio = debtMintingFeeRatioDecimal.add(
374
+ redemptionReimbursementRatioDecimal,
375
+ );
376
+
377
+ const collateralRatio = Decimal(collateralRatioPercentage.getOnChainInt)
378
+ .div(OCD_DECIMAL_UNIT)
379
+ .div(100);
380
+
381
+ const maxAvailableAdaForRedemptionInclReimb = calculateTotalAdaForRedemption(
382
+ iasset,
383
+ iassetPrice,
384
+ lrpParams,
385
+ allLrps,
386
+ MAX_REDEMPTIONS_WITH_CDP_OPEN,
387
+ );
388
+
389
+ if (
390
+ collateralRatio.toNumber() <= 1 ||
391
+ baseCollateral <= 0n ||
392
+ maxAvailableAdaForRedemptionInclReimb <= 0n
393
+ ) {
394
+ return undefined;
395
+ }
396
+
397
+ // The leverage unconstrained by the liquidity in LRP
398
+ const theoreticalMaxLeverage = Decimal(Decimal(1).minus(totalFeeRatio))
399
+ .div(collateralRatio.minus(1).add(totalFeeRatio))
400
+ .add(1);
401
+
402
+ // b''
403
+ const bExFees = theoreticalMaxLeverage
404
+ .mul(baseCollateral)
405
+ .minus(baseCollateral)
406
+ .floor();
407
+
408
+ // b = b’’ / (1-f_r - f_m)
409
+ const b = bExFees.div(Decimal(1).minus(totalFeeRatio)).floor();
410
+
411
+ const cappedB = bigintMin(
412
+ maxAvailableAdaForRedemptionInclReimb,
413
+ fromDecimal(b),
414
+ );
415
+
416
+ const cappedBExFees = Decimal(cappedB)
417
+ .mul(Decimal(1).minus(totalFeeRatio))
418
+ .floor();
419
+
420
+ return Decimal(baseCollateral)
421
+ .add(cappedBExFees)
422
+ .div(baseCollateral)
423
+ .toNumber();
424
+ }