@indigo-labs/indigo-sdk 0.2.42 → 0.3.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 (201) hide show
  1. package/.github/workflows/ci.yml +4 -2
  2. package/dist/index.d.mts +3008 -2194
  3. package/dist/index.d.ts +3008 -2194
  4. package/dist/index.js +9827 -6194
  5. package/dist/index.mjs +8591 -4809
  6. package/package.json +14 -3
  7. package/src/contracts/cdp/helpers.ts +68 -72
  8. package/src/contracts/cdp/scripts.ts +50 -13
  9. package/src/contracts/cdp/transactions.ts +831 -545
  10. package/src/contracts/cdp/types-new.ts +256 -0
  11. package/src/contracts/cdp/types.ts +26 -144
  12. package/src/contracts/cdp-creator/scripts.ts +15 -9
  13. package/src/contracts/cdp-creator/types-new.ts +50 -0
  14. package/src/contracts/cdp-creator/types.ts +5 -31
  15. package/src/contracts/collector/scripts.ts +1 -1
  16. package/src/contracts/collector/transactions.ts +23 -13
  17. package/src/contracts/collector/types-new.ts +17 -0
  18. package/src/contracts/execute/scripts.ts +19 -10
  19. package/src/contracts/execute/types-new.ts +44 -0
  20. package/src/contracts/execute/types.ts +5 -38
  21. package/src/contracts/gov/helpers.ts +187 -51
  22. package/src/contracts/gov/scripts.ts +17 -10
  23. package/src/contracts/gov/transactions.ts +599 -271
  24. package/src/contracts/gov/types-new.ts +253 -100
  25. package/src/contracts/gov/types.ts +4 -71
  26. package/src/contracts/iasset/helpers.ts +172 -0
  27. package/src/contracts/iasset/scripts.ts +38 -0
  28. package/src/contracts/iasset/types.ts +154 -0
  29. package/src/contracts/initialize/actions.ts +768 -0
  30. package/src/contracts/initialize/helpers.ts +611 -36
  31. package/src/contracts/initialize/types.ts +102 -28
  32. package/src/contracts/interest-collection/helpers.ts +19 -0
  33. package/src/contracts/interest-collection/scripts.ts +44 -0
  34. package/src/contracts/interest-collection/transactions.ts +436 -0
  35. package/src/contracts/interest-collection/types-new.ts +50 -0
  36. package/src/contracts/interest-collection/types.ts +26 -0
  37. package/src/contracts/interest-oracle/helpers.ts +2 -30
  38. package/src/contracts/interest-oracle/scripts.ts +1 -1
  39. package/src/contracts/interest-oracle/transactions.ts +21 -16
  40. package/src/contracts/interest-oracle/types-new.ts +32 -0
  41. package/src/contracts/interest-oracle/types.ts +1 -40
  42. package/src/contracts/one-shot/transactions.ts +1 -2
  43. package/src/contracts/poll/helpers.ts +5 -23
  44. package/src/contracts/poll/scripts.ts +12 -13
  45. package/src/contracts/poll/types-poll-manager.ts +1 -19
  46. package/src/contracts/poll/types-poll-new.ts +170 -0
  47. package/src/contracts/poll/types-poll-shard.ts +2 -24
  48. package/src/contracts/price-oracle/helpers.ts +1 -4
  49. package/src/contracts/price-oracle/scripts.ts +3 -8
  50. package/src/contracts/price-oracle/transactions.ts +32 -25
  51. package/src/contracts/price-oracle/types-new.ts +50 -0
  52. package/src/contracts/price-oracle/types.ts +2 -36
  53. package/src/contracts/pyth-feed/helpers.ts +58 -0
  54. package/src/contracts/pyth-feed/scripts.ts +15 -0
  55. package/src/contracts/pyth-feed/types.ts +181 -0
  56. package/src/contracts/rob/helpers.ts +405 -0
  57. package/src/contracts/rob/scripts.ts +35 -0
  58. package/src/contracts/rob/transactions.ts +410 -0
  59. package/src/contracts/rob/types-new.ts +128 -0
  60. package/src/contracts/rob/types.ts +16 -0
  61. package/src/contracts/rob-leverage/helpers.ts +424 -0
  62. package/src/contracts/{leverage → rob-leverage}/transactions.ts +68 -48
  63. package/src/contracts/stability-pool/helpers.ts +714 -230
  64. package/src/contracts/stability-pool/scripts.ts +20 -15
  65. package/src/contracts/stability-pool/transactions.ts +625 -493
  66. package/src/contracts/stability-pool/types-new.ts +237 -100
  67. package/src/contracts/stability-pool/types.ts +5 -22
  68. package/src/contracts/stableswap/helpers.ts +22 -0
  69. package/src/contracts/stableswap/scripts.ts +37 -0
  70. package/src/contracts/stableswap/transactions.ts +647 -0
  71. package/src/contracts/stableswap/types-new.ts +131 -0
  72. package/src/contracts/stableswap/types.ts +17 -0
  73. package/src/contracts/staking/helpers.ts +49 -34
  74. package/src/contracts/staking/scripts.ts +1 -1
  75. package/src/contracts/staking/transactions.ts +85 -130
  76. package/src/contracts/staking/types-new.ts +60 -28
  77. package/src/contracts/staking/types.ts +1 -28
  78. package/src/contracts/treasury/helpers.ts +21 -0
  79. package/src/contracts/treasury/scripts.ts +16 -26
  80. package/src/contracts/treasury/transactions.ts +256 -27
  81. package/src/contracts/treasury/types-new.ts +69 -0
  82. package/src/contracts/treasury/types.ts +2 -43
  83. package/src/contracts/version-registry/scripts.ts +2 -2
  84. package/src/contracts/version-registry/types-new.ts +6 -7
  85. package/src/index.ts +37 -20
  86. package/src/scripts/auth-token-policy.ts +3 -2
  87. package/src/scripts/iasset-policy.ts +3 -2
  88. package/src/types/evolution-schema-options.ts +3 -3
  89. package/src/types/generic.ts +17 -89
  90. package/src/types/multisig.ts +48 -0
  91. package/src/types/on-chain-decimal.ts +14 -7
  92. package/src/types/rational.ts +61 -0
  93. package/src/types/system-params.ts +237 -41
  94. package/src/utils/array-utils.ts +70 -1
  95. package/src/utils/bigint-utils.ts +12 -0
  96. package/src/utils/indigo-helpers.ts +8 -10
  97. package/src/utils/lucid-utils.ts +47 -40
  98. package/src/utils/oracle-helpers.ts +62 -0
  99. package/src/utils/pyth/decode.ts +223 -0
  100. package/src/utils/pyth/encode.ts +262 -0
  101. package/src/utils/pyth/index.ts +14 -0
  102. package/src/utils/pyth/types.ts +87 -0
  103. package/src/validators/always-succeed-validator.ts +6 -0
  104. package/src/validators/cdp-creator-validator.ts +2 -2
  105. package/src/validators/cdp-redeem-validator.ts +7 -0
  106. package/src/validators/cdp-validator.ts +2 -2
  107. package/src/validators/collector-validator.ts +2 -2
  108. package/src/validators/execute-validator.ts +2 -2
  109. package/src/validators/governance-validator.ts +2 -2
  110. package/src/validators/iasset-validator.ts +7 -0
  111. package/src/validators/interest-collection-validator.ts +7 -0
  112. package/src/validators/interest-oracle-validator.ts +2 -2
  113. package/src/validators/poll-manager-validator.ts +2 -2
  114. package/src/validators/poll-shard-validator.ts +2 -2
  115. package/src/validators/price-oracle-validator.ts +7 -0
  116. package/src/validators/pyth-feed-validator.ts +7 -0
  117. package/src/validators/rob-validator.ts +7 -0
  118. package/src/validators/stability-pool-validator.ts +2 -2
  119. package/src/validators/stableswap-validator.ts +7 -0
  120. package/src/validators/staking-validator.ts +2 -2
  121. package/src/validators/treasury-validator.ts +2 -2
  122. package/src/validators/version-record-policy.ts +2 -2
  123. package/src/validators/version-registry-validator.ts +2 -2
  124. package/tests/always-succeed/script.ts +7 -0
  125. package/tests/bigint-utils.test.ts +41 -0
  126. package/tests/cdp/actions.ts +611 -0
  127. package/tests/cdp/cdp-helpers.ts +55 -0
  128. package/tests/cdp/cdp-queries.ts +440 -0
  129. package/tests/cdp/cdp.test.ts +6087 -0
  130. package/tests/cdp/transactions-mutated.ts +1729 -0
  131. package/tests/data/system-params.json +177 -34
  132. package/tests/datums.test.ts +209 -210
  133. package/tests/endpoints/initialize.ts +68 -0
  134. package/tests/endpoints/interest-collector.ts +37 -0
  135. package/tests/endpoints/treasury.ts +70 -0
  136. package/tests/gov/actions.ts +406 -0
  137. package/tests/gov/gov.test.ts +4450 -0
  138. package/tests/{queries → gov}/governance-queries.ts +6 -3
  139. package/tests/hash-checks.test.ts +38 -11
  140. package/tests/indigo-test-helpers.ts +100 -0
  141. package/tests/initialize.test.ts +61 -9
  142. package/tests/interest-collection/interest-collection.test.ts +892 -0
  143. package/tests/interest-collection/interest-collector-queries.ts +49 -0
  144. package/tests/interest-collection/transactions-mutated.ts +260 -0
  145. package/tests/interest-oracle.test.ts +43 -35
  146. package/tests/mock/assets-mock.ts +234 -23
  147. package/tests/mock/protocol-params-mock.ts +21 -0
  148. package/tests/price-oracle/actions.ts +163 -0
  149. package/tests/price-oracle/price-oracle-queries.ts +12 -0
  150. package/tests/price-oracle/price-oracle.test.ts +240 -0
  151. package/tests/price-oracle/transactions-mutated.ts +62 -0
  152. package/tests/pyth/endpoints.ts +96 -0
  153. package/tests/pyth/helpers.ts +37 -0
  154. package/tests/pyth/pyth-encoding.test.ts +376 -0
  155. package/tests/pyth/pyth-indigo.test.ts +509 -0
  156. package/tests/pyth/pyth.test.ts +300 -0
  157. package/tests/queries/execute-queries.ts +6 -5
  158. package/tests/queries/iasset-queries.ts +175 -5
  159. package/tests/queries/interest-oracle-queries.ts +4 -2
  160. package/tests/queries/poll-queries.ts +8 -9
  161. package/tests/queries/stability-pool-queries.ts +95 -48
  162. package/tests/queries/staking-queries.ts +4 -2
  163. package/tests/queries/treasury-queries.ts +80 -5
  164. package/tests/rob/actions.ts +58 -0
  165. package/tests/{lrp-leverage.test.ts → rob/rob-leverage.test.ts} +393 -296
  166. package/tests/rob/rob-queries.ts +95 -0
  167. package/tests/rob/rob.test.ts +3762 -0
  168. package/tests/rob/transactions-mutated.ts +853 -0
  169. package/tests/script-size.test.ts +240 -0
  170. package/tests/setup.ts +135 -0
  171. package/tests/stability-pool/actions.ts +210 -0
  172. package/tests/stability-pool.test.ts +5469 -666
  173. package/tests/stableswap/stableswap-actions.ts +84 -0
  174. package/tests/stableswap/stableswap-queries.ts +89 -0
  175. package/tests/stableswap/stableswap.test.ts +3891 -0
  176. package/tests/stableswap/transactions-mutated.ts +348 -0
  177. package/tests/staking.test.ts +82 -99
  178. package/tests/test-helpers.ts +58 -11
  179. package/tests/treasury.test.ts +242 -0
  180. package/tests/utils/asserts.ts +74 -0
  181. package/tests/utils/benchmark-utils.ts +81 -0
  182. package/tests/utils/index.ts +122 -4
  183. package/tsconfig.json +9 -1
  184. package/vitest.config.ts +3 -1
  185. package/src/contracts/collector/types.ts +0 -16
  186. package/src/contracts/initialize/transactions.ts +0 -891
  187. package/src/contracts/leverage/helpers.ts +0 -424
  188. package/src/contracts/lrp/helpers.ts +0 -294
  189. package/src/contracts/lrp/scripts.ts +0 -27
  190. package/src/contracts/lrp/transactions.ts +0 -250
  191. package/src/contracts/lrp/types.ts +0 -131
  192. package/src/contracts/poll/types-poll.ts +0 -88
  193. package/src/contracts/vesting/helpers.ts +0 -218
  194. package/src/utils/value-helpers.ts +0 -37
  195. package/src/validators/lrp-validator.ts +0 -7
  196. package/tests/cdp.test.ts +0 -1528
  197. package/tests/gov.test.ts +0 -2011
  198. package/tests/lrp.test.ts +0 -673
  199. package/tests/queries/cdp-queries.ts +0 -220
  200. package/tests/queries/lrp-queries.ts +0 -76
  201. package/tests/queries/price-oracle-queries.ts +0 -10
@@ -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 { RobParamsSP } from '../../types/system-params';
65
+ // import {
66
+ // calculateTotalAdaForRedemption,
67
+ // lrpRedeemableLovelacesInclReimb,
68
+ // } from '../lrp/helpers';
69
+ // import { RobDatum } from '../lrp/types-new';
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: RobParamsSP,
150
+ // // Picking from the beginning until the iasset redemption amount is satisfied.
151
+ // redemptionLrps: [UTxO, RobDatum][],
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, RobDatum], 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: Uint8Array<ArrayBufferLike>,
280
+ // leverage: number,
281
+ // baseCollateral: bigint,
282
+ // iassetPrice: OnChainDecimal,
283
+ // debtMintingFeePercentage: OnChainDecimal,
284
+ // redemptionReimbursementPercentage: OnChainDecimal,
285
+ // lrpParams: RobParamsSP,
286
+ // allLrps: [UTxO, RobDatum][],
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: Uint8Array<ArrayBufferLike>,
354
+ // collateralRatioPercentage: OnChainDecimal,
355
+ // baseCollateral: bigint,
356
+ // iassetPrice: OnChainDecimal,
357
+ // debtMintingFeePercentage: OnChainDecimal,
358
+ // redemptionReimbursementPercentage: OnChainDecimal,
359
+ // lrpParams: RobParamsSP,
360
+ // allLrps: [UTxO, RobDatum][],
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
+ // }
@@ -1,22 +1,21 @@
1
- import {
1
+ /*import {
2
2
  LucidEvolution,
3
3
  TxBuilder,
4
+ OutRef,
4
5
  UTxO,
5
6
  addAssets,
6
7
  slotToUnixTime,
7
8
  Data,
9
+ fromHex,
8
10
  } from '@lucid-evolution/lucid';
9
11
  import {
10
12
  addrDetails,
11
13
  createScriptAddress,
12
14
  getInlineDatumOrThrow,
13
- resolveUtxo,
14
- UtxoOrOutRef,
15
15
  } from '../../utils/lucid-utils';
16
- import { parsePriceOracleDatum } from '../price-oracle/types';
16
+ import { parsePriceOracleDatum } from '../price-oracle/types-new';
17
17
  import { ocdMul } from '../../types/on-chain-decimal';
18
- import { parseIAssetDatumOrThrow, serialiseCdpDatum } from '../cdp/types';
19
- import { mkAssetsOf, mkLovelacesOf } from '../../utils/value-helpers';
18
+ import { serialiseCdpDatum } from '../cdp/types-new';
20
19
  import { calculateFeeFromPercentage } from '../../utils/indigo-helpers';
21
20
  import { matchSingle } from '../../utils/utils';
22
21
  import {
@@ -25,8 +24,8 @@ import {
25
24
  SystemParams,
26
25
  } from '../../types/system-params';
27
26
  import { oracleExpirationAwareValidity } from '../price-oracle/helpers';
28
- import { parseInterestOracleDatum } from '../interest-oracle/types';
29
- import { serialiseCDPCreatorRedeemer } from '../cdp-creator/types';
27
+ import { parseInterestOracleDatum } from '../interest-oracle/types-new';
28
+ import { serialiseCDPCreatorRedeemer } from '../cdp-creator/types-new';
30
29
  import { collectorFeeTx } from '../collector/transactions';
31
30
  import { calculateUnitaryInterestSinceOracleLastUpdated } from '../interest-oracle/helpers';
32
31
  import {
@@ -35,23 +34,32 @@ import {
35
34
  calculateLeverageFromCollateralRatio,
36
35
  MAX_REDEMPTIONS_WITH_CDP_OPEN,
37
36
  } from './helpers';
38
- import { LRPDatum } from '../lrp/types';
39
37
  import {
40
38
  buildRedemptionsTx,
41
39
  randomLrpsSubsetSatisfyingTargetLovelaces,
42
40
  } from '../lrp/helpers';
41
+ import {
42
+ parseCollateralAssetDatumOrThrow,
43
+ parseIAssetDatumOrThrow,
44
+ } from '../iasset/types';
45
+ import {
46
+ mkAssetsOf,
47
+ mkLovelacesOf,
48
+ } from '@3rd-eye-labs/cardano-offchain-common';
49
+ import { RobDatum } from '../lrp/types-new';
43
50
 
44
51
  export async function leverageCdpWithLrp(
45
52
  leverage: number,
46
53
  baseCollateral: bigint,
47
- priceOracle: UtxoOrOutRef,
48
- iasset: UtxoOrOutRef,
49
- cdpCreator: UtxoOrOutRef,
50
- interestOracle: UtxoOrOutRef,
51
- collector: UtxoOrOutRef,
54
+ priceOracleOutRef: OutRef,
55
+ iassetOutRef: OutRef,
56
+ collateralAssetOutRef: OutRef,
57
+ cdpCreatorOref: OutRef,
58
+ interestOracleOref: OutRef,
59
+ collectorOref: OutRef,
52
60
  sysParams: SystemParams,
53
61
  lucid: LucidEvolution,
54
- allLrps: [UTxO, LRPDatum][],
62
+ allRobs: [UTxO, RobDatum][],
55
63
  currentSlot: number,
56
64
  ): Promise<TxBuilder> {
57
65
  const network = lucid.config().network!;
@@ -59,11 +67,11 @@ export async function leverageCdpWithLrp(
59
67
 
60
68
  const [pkh, skh] = await addrDetails(lucid);
61
69
 
62
- const lrpScriptRefUtxo = matchSingle(
70
+ const robScriptRefUtxo = matchSingle(
63
71
  await lucid.utxosByOutRef([
64
- fromSystemParamsScriptRef(sysParams.scriptReferences.lrpValidatorRef),
72
+ fromSystemParamsScriptRef(sysParams.scriptReferences.robValidatorRef),
65
73
  ]),
66
- (_) => new Error('Expected a single LRP Ref Script UTXO'),
74
+ (_) => new Error('Expected a single ROB Ref Script UTXO'),
67
75
  );
68
76
 
69
77
  const cdpCreatorRefScriptUtxo = matchSingle(
@@ -91,48 +99,52 @@ export async function leverageCdpWithLrp(
91
99
  (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
92
100
  );
93
101
 
94
- const cdpCreatorUtxo = await resolveUtxo(
95
- cdpCreator,
96
- lucid,
97
- 'Expected a single CDP creator UTXO',
102
+ const cdpCreatorUtxo = matchSingle(
103
+ await lucid.utxosByOutRef([cdpCreatorOref]),
104
+ (_) => new Error('Expected a single CDP creator UTXO'),
98
105
  );
99
106
 
100
- const interestOracleUtxo = await resolveUtxo(
101
- interestOracle,
102
- lucid,
103
- 'Expected a single interest oracle UTXO',
107
+ const interestOracleUtxo = matchSingle(
108
+ await lucid.utxosByOutRef([interestOracleOref]),
109
+ (_) => new Error('Expected a single interest oracle UTXO'),
104
110
  );
105
111
  const interestOracleDatum = parseInterestOracleDatum(
106
112
  getInlineDatumOrThrow(interestOracleUtxo),
107
113
  );
108
114
 
109
- const priceOracleUtxo = await resolveUtxo(
110
- priceOracle,
111
- lucid,
112
- 'Expected a single price oracle UTXO',
115
+ const priceOracleUtxo = matchSingle(
116
+ await lucid.utxosByOutRef([priceOracleOutRef]),
117
+ (_) => new Error('Expected a single price oracle UTXO'),
113
118
  );
114
119
  const priceOracleDatum = parsePriceOracleDatum(
115
120
  getInlineDatumOrThrow(priceOracleUtxo),
116
121
  );
117
122
 
118
- const iassetUtxo = await resolveUtxo(
119
- iasset,
120
- lucid,
121
- 'Expected a single IAsset UTXO',
123
+ const iassetUtxo = matchSingle(
124
+ await lucid.utxosByOutRef([iassetOutRef]),
125
+ (_) => new Error('Expected a single IAsset UTXO'),
122
126
  );
123
127
  const iassetDatum = parseIAssetDatumOrThrow(
124
128
  getInlineDatumOrThrow(iassetUtxo),
125
129
  );
126
130
 
131
+ const collateralAssetUtxo = matchSingle(
132
+ await lucid.utxosByOutRef([collateralAssetOutRef]),
133
+ (_) => new Error('Expected a single collateral asset UTXO'),
134
+ );
135
+ const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
136
+ getInlineDatumOrThrow(collateralAssetUtxo),
137
+ );
138
+
127
139
  const maxLeverage = calculateLeverageFromCollateralRatio(
128
- iassetDatum.assetName,
129
- iassetDatum.maintenanceRatio,
140
+ collateralAssetDatum.iasset,
141
+ collateralAssetDatum.maintenanceRatio,
130
142
  baseCollateral,
131
143
  priceOracleDatum.price,
132
144
  iassetDatum.debtMintingFeePercentage,
133
145
  iassetDatum.redemptionReimbursementPercentage,
134
- sysParams.lrpParams,
135
- allLrps,
146
+ sysParams.robParams,
147
+ allRobs,
136
148
  );
137
149
 
138
150
  if (!maxLeverage) {
@@ -152,7 +164,7 @@ export async function leverageCdpWithLrp(
152
164
 
153
165
  if (
154
166
  leverageSummary.collateralRatio.getOnChainInt <
155
- iassetDatum.maintenanceRatio.getOnChainInt
167
+ collateralAssetDatum.maintenanceRatio.getOnChainInt
156
168
  ) {
157
169
  throw new Error(
158
170
  "Can't have collateral ratio smaller than maintenance ratio",
@@ -163,13 +175,13 @@ export async function leverageCdpWithLrp(
163
175
  leverageSummary.lovelacesForRedemptionWithReimbursement,
164
176
  iassetDatum.redemptionReimbursementPercentage,
165
177
  priceOracleDatum.price,
166
- sysParams.lrpParams,
178
+ sysParams.robParams,
167
179
  randomLrpsSubsetSatisfyingTargetLovelaces(
168
180
  iassetDatum.assetName,
169
181
  leverageSummary.lovelacesForRedemptionWithReimbursement,
170
182
  priceOracleDatum.price,
171
- allLrps,
172
- sysParams.lrpParams,
183
+ allRobs,
184
+ sysParams.robParams,
173
185
  MAX_REDEMPTIONS_WITH_CDP_OPEN,
174
186
  ),
175
187
  );
@@ -191,7 +203,9 @@ export async function leverageCdpWithLrp(
191
203
 
192
204
  const iassetTokensVal = mkAssetsOf(
193
205
  {
194
- currencySymbol: sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
206
+ currencySymbol: fromHex(
207
+ sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
208
+ ),
195
209
  tokenName: iassetDatum.assetName,
196
210
  },
197
211
  mintedAmt,
@@ -209,13 +223,18 @@ export async function leverageCdpWithLrp(
209
223
  .validFrom(txValidity.validFrom)
210
224
  .validTo(txValidity.validTo)
211
225
  // Ref inputs
212
- .readFrom([priceOracleUtxo, interestOracleUtxo, iassetUtxo])
226
+ .readFrom([
227
+ priceOracleUtxo,
228
+ interestOracleUtxo,
229
+ iassetUtxo,
230
+ collateralAssetUtxo,
231
+ ])
213
232
  // Ref scripts
214
233
  .readFrom([
215
234
  cdpCreatorRefScriptUtxo,
216
235
  cdpAuthTokenPolicyRefScriptUtxo,
217
236
  iAssetTokenPolicyRefScriptUtxo,
218
- lrpScriptRefUtxo,
237
+ robScriptRefUtxo,
219
238
  ])
220
239
  .mintAssets(cdpNftVal, Data.void())
221
240
  .mintAssets(iassetTokensVal, Data.void())
@@ -223,7 +242,7 @@ export async function leverageCdpWithLrp(
223
242
  [cdpCreatorUtxo],
224
243
  serialiseCDPCreatorRedeemer({
225
244
  CreateCDP: {
226
- cdpOwner: pkh.hash,
245
+ cdpOwner: fromHex(pkh.hash),
227
246
  minted: mintedAmt,
228
247
  collateral: collateralAmt,
229
248
  currentTime: currentTime,
@@ -235,7 +254,7 @@ export async function leverageCdpWithLrp(
235
254
  {
236
255
  kind: 'inline',
237
256
  value: serialiseCdpDatum({
238
- cdpOwner: pkh.hash,
257
+ cdpOwner: fromHex(pkh.hash),
239
258
  iasset: iassetDatum.assetName,
240
259
  mintedAmt: mintedAmt,
241
260
  cdpFees: {
@@ -272,8 +291,9 @@ export async function leverageCdpWithLrp(
272
291
  );
273
292
 
274
293
  if (debtMintingFee > 0) {
275
- await collectorFeeTx(debtMintingFee, lucid, sysParams, tx, collector);
294
+ await collectorFeeTx(debtMintingFee, lucid, sysParams, tx, collectorOref);
276
295
  }
277
296
 
278
297
  return tx;
279
298
  }
299
+ */