@indigo-labs/indigo-sdk 0.3.9 → 0.3.10

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.
@@ -1,4 +1,4 @@
1
- /*import {
1
+ import {
2
2
  LucidEvolution,
3
3
  TxBuilder,
4
4
  OutRef,
@@ -7,26 +7,25 @@
7
7
  slotToUnixTime,
8
8
  Data,
9
9
  fromHex,
10
+ getInputIndices,
10
11
  } from '@lucid-evolution/lucid';
11
12
  import {
12
13
  addrDetails,
13
14
  createScriptAddress,
14
15
  getInlineDatumOrThrow,
15
16
  } from '../../utils/lucid-utils';
16
- import { parsePriceOracleDatum } from '../price-oracle/types-new';
17
- import { ocdMul } from '../../types/on-chain-decimal';
18
17
  import { serialiseCdpDatum } from '../cdp/types-new';
19
- import { calculateFeeFromPercentage } from '../../utils/indigo-helpers';
20
18
  import { matchSingle } from '../../utils/utils';
21
19
  import {
22
20
  fromSystemParamsAsset,
23
21
  fromSystemParamsScriptRef,
24
22
  SystemParams,
25
23
  } from '../../types/system-params';
26
- import { oracleExpirationAwareValidity } from '../price-oracle/helpers';
27
24
  import { parseInterestOracleDatum } from '../interest-oracle/types-new';
28
- import { serialiseCDPCreatorRedeemer } from '../cdp-creator/types-new';
29
- import { collectorFeeTx } from '../collector/transactions';
25
+ import {
26
+ serialiseCDPCreatorDatum,
27
+ serialiseCDPCreatorRedeemer,
28
+ } from '../cdp-creator/types-new';
30
29
  import { calculateUnitaryInterestSinceOracleLastUpdated } from '../interest-oracle/helpers';
31
30
  import {
32
31
  approximateLeverageRedemptions,
@@ -34,33 +33,41 @@ import {
34
33
  calculateLeverageFromCollateralRatio,
35
34
  MAX_REDEMPTIONS_WITH_CDP_OPEN,
36
35
  } from './helpers';
37
- import {
38
- buildRedemptionsTx,
39
- randomLrpsSubsetSatisfyingTargetLovelaces,
40
- } from '../lrp/helpers';
36
+
41
37
  import {
42
38
  parseCollateralAssetDatumOrThrow,
43
39
  parseIAssetDatumOrThrow,
44
40
  } from '../iasset/types';
41
+ import { mkAssetsOf } from '@3rd-eye-labs/cardano-offchain-common';
42
+ import { RobDatum } from '../rob/types-new';
43
+ import { rationalToFloat } from '../../types/rational';
45
44
  import {
46
- mkAssetsOf,
47
- mkLovelacesOf,
48
- } from '@3rd-eye-labs/cardano-offchain-common';
49
- import { RobDatum } from '../lrp/types-new';
45
+ buildRedemptionsTx,
46
+ randomRobsSubsetSatisfyingTargetCollateral,
47
+ } from '../rob/helpers';
48
+ import { treasuryFeeTx } from '../treasury/transactions';
49
+ import Decimal from 'decimal.js';
50
+ import { fromDecimal } from '../../utils/bigint-utils';
51
+ import { calculateFeeFromRatio } from '../../utils/indigo-helpers';
52
+ import { retrieveAdjustedPrice } from '../../utils/oracle-helpers';
53
+ import { attachOracle } from '../iasset/helpers';
54
+ import { OracleIdx } from '../price-oracle/types-new';
50
55
 
51
- export async function leverageCdpWithLrp(
56
+ export async function leverageCdpWithRob(
52
57
  leverage: number,
53
58
  baseCollateral: bigint,
54
- priceOracleOutRef: OutRef,
59
+ priceOracleOutRef: OutRef | undefined,
55
60
  iassetOutRef: OutRef,
56
61
  collateralAssetOutRef: OutRef,
57
62
  cdpCreatorOref: OutRef,
58
63
  interestOracleOref: OutRef,
59
- collectorOref: OutRef,
64
+ treasuryOref: OutRef,
60
65
  sysParams: SystemParams,
61
66
  lucid: LucidEvolution,
62
67
  allRobs: [UTxO, RobDatum][],
63
68
  currentSlot: number,
69
+ pythMessage: string | undefined = undefined,
70
+ pythStateOref: OutRef | undefined = undefined,
64
71
  ): Promise<TxBuilder> {
65
72
  const network = lucid.config().network!;
66
73
  const currentTime = BigInt(slotToUnixTime(network, currentSlot));
@@ -112,14 +119,6 @@ export async function leverageCdpWithLrp(
112
119
  getInlineDatumOrThrow(interestOracleUtxo),
113
120
  );
114
121
 
115
- const priceOracleUtxo = matchSingle(
116
- await lucid.utxosByOutRef([priceOracleOutRef]),
117
- (_) => new Error('Expected a single price oracle UTXO'),
118
- );
119
- const priceOracleDatum = parsePriceOracleDatum(
120
- getInlineDatumOrThrow(priceOracleUtxo),
121
- );
122
-
123
122
  const iassetUtxo = matchSingle(
124
123
  await lucid.utxosByOutRef([iassetOutRef]),
125
124
  (_) => new Error('Expected a single IAsset UTXO'),
@@ -136,14 +135,25 @@ export async function leverageCdpWithLrp(
136
135
  getInlineDatumOrThrow(collateralAssetUtxo),
137
136
  );
138
137
 
138
+ const [price, _] = await retrieveAdjustedPrice(
139
+ iassetDatum.assetName,
140
+ collateralAssetDatum.collateralAsset,
141
+ collateralAssetDatum.priceInfo,
142
+ collateralAssetDatum.extraDecimals,
143
+ priceOracleOutRef,
144
+ pythMessage,
145
+ sysParams.pythConfig,
146
+ lucid,
147
+ );
148
+
139
149
  const maxLeverage = calculateLeverageFromCollateralRatio(
140
150
  collateralAssetDatum.iasset,
151
+ collateralAssetDatum.collateralAsset,
141
152
  collateralAssetDatum.maintenanceRatio,
142
153
  baseCollateral,
143
- priceOracleDatum.price,
144
- iassetDatum.debtMintingFeePercentage,
145
- iassetDatum.redemptionReimbursementPercentage,
146
- sysParams.robParams,
154
+ price,
155
+ iassetDatum.debtMintingFeeRatio,
156
+ iassetDatum.redemptionReimbursementRatio,
147
157
  allRobs,
148
158
  );
149
159
 
@@ -154,8 +164,8 @@ export async function leverageCdpWithLrp(
154
164
  const leverageSummary = approximateLeverageRedemptions(
155
165
  baseCollateral,
156
166
  leverage,
157
- iassetDatum.redemptionReimbursementPercentage,
158
- iassetDatum.debtMintingFeePercentage,
167
+ iassetDatum.redemptionProcessingFeeRatio,
168
+ iassetDatum.debtMintingFeeRatio,
159
169
  );
160
170
 
161
171
  if (maxLeverage < leverageSummary.leverage) {
@@ -163,8 +173,8 @@ export async function leverageCdpWithLrp(
163
173
  }
164
174
 
165
175
  if (
166
- leverageSummary.collateralRatio.getOnChainInt <
167
- collateralAssetDatum.maintenanceRatio.getOnChainInt
176
+ rationalToFloat(leverageSummary.collateralRatio) <
177
+ rationalToFloat(collateralAssetDatum.maintenanceRatio)
168
178
  ) {
169
179
  throw new Error(
170
180
  "Can't have collateral ratio smaller than maintenance ratio",
@@ -172,83 +182,67 @@ export async function leverageCdpWithLrp(
172
182
  }
173
183
 
174
184
  const redemptionDetails = summarizeActualLeverageRedemptions(
175
- leverageSummary.lovelacesForRedemptionWithReimbursement,
176
- iassetDatum.redemptionReimbursementPercentage,
177
- priceOracleDatum.price,
178
- sysParams.robParams,
179
- randomLrpsSubsetSatisfyingTargetLovelaces(
185
+ leverageSummary.redeemedCollateral,
186
+ iassetDatum.redemptionReimbursementRatio,
187
+ price,
188
+ randomRobsSubsetSatisfyingTargetCollateral(
180
189
  iassetDatum.assetName,
181
- leverageSummary.lovelacesForRedemptionWithReimbursement,
182
- priceOracleDatum.price,
190
+ collateralAssetDatum.collateralAsset,
191
+ leverageSummary.redeemedCollateral,
192
+ price,
183
193
  allRobs,
184
- sysParams.robParams,
185
194
  MAX_REDEMPTIONS_WITH_CDP_OPEN,
186
195
  ),
187
196
  );
188
197
 
189
- const mintedAmt = redemptionDetails.totalRedemptionIAssets;
198
+ // payout / (1 - debtMintingFee) = total minted amount
199
+ const mintedAmt = fromDecimal(
200
+ Decimal(redemptionDetails.totalIAssetPayout)
201
+ .div(
202
+ Decimal(1).minus(
203
+ Decimal(iassetDatum.debtMintingFeeRatio.numerator).div(
204
+ iassetDatum.debtMintingFeeRatio.denominator,
205
+ ),
206
+ ),
207
+ )
208
+ .floor(),
209
+ );
190
210
 
191
- const debtMintingFee = calculateFeeFromPercentage(
192
- iassetDatum.debtMintingFeePercentage,
193
- ocdMul({ getOnChainInt: mintedAmt }, priceOracleDatum.price).getOnChainInt,
211
+ const debtMintingFee = calculateFeeFromRatio(
212
+ iassetDatum.debtMintingFeeRatio,
213
+ mintedAmt,
194
214
  );
195
215
 
196
216
  const collateralAmt =
197
- redemptionDetails.totalRedeemedLovelaces + baseCollateral - debtMintingFee;
217
+ redemptionDetails.totalRedeemedCollateral + baseCollateral;
198
218
 
199
219
  const cdpNftVal = mkAssetsOf(
200
220
  fromSystemParamsAsset(sysParams.cdpParams.cdpAuthToken),
201
221
  1n,
202
222
  );
203
223
 
204
- const iassetTokensVal = mkAssetsOf(
205
- {
206
- currencySymbol: fromHex(
207
- sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
208
- ),
209
- tokenName: iassetDatum.assetName,
210
- },
211
- mintedAmt,
212
- );
224
+ const iassetClass = {
225
+ currencySymbol: fromHex(
226
+ sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
227
+ ),
228
+ tokenName: iassetDatum.assetName,
229
+ };
213
230
 
214
- const txValidity = oracleExpirationAwareValidity(
215
- currentSlot,
216
- Number(sysParams.cdpCreatorParams.biasTime),
217
- Number(priceOracleDatum.expiration),
218
- network,
219
- );
231
+ const iassetTokensVal = mkAssetsOf(iassetClass, mintedAmt);
232
+
233
+ const refScripts = [
234
+ cdpCreatorRefScriptUtxo,
235
+ cdpAuthTokenPolicyRefScriptUtxo,
236
+ iAssetTokenPolicyRefScriptUtxo,
237
+ robScriptRefUtxo,
238
+ ];
220
239
 
221
240
  const tx = lucid
222
241
  .newTx()
223
- .validFrom(txValidity.validFrom)
224
- .validTo(txValidity.validTo)
225
- // Ref inputs
226
- .readFrom([
227
- priceOracleUtxo,
228
- interestOracleUtxo,
229
- iassetUtxo,
230
- collateralAssetUtxo,
231
- ])
232
242
  // Ref scripts
233
- .readFrom([
234
- cdpCreatorRefScriptUtxo,
235
- cdpAuthTokenPolicyRefScriptUtxo,
236
- iAssetTokenPolicyRefScriptUtxo,
237
- robScriptRefUtxo,
238
- ])
243
+ .readFrom(refScripts)
239
244
  .mintAssets(cdpNftVal, Data.void())
240
245
  .mintAssets(iassetTokensVal, Data.void())
241
- .collectFrom(
242
- [cdpCreatorUtxo],
243
- serialiseCDPCreatorRedeemer({
244
- CreateCDP: {
245
- cdpOwner: fromHex(pkh.hash),
246
- minted: mintedAmt,
247
- collateral: collateralAmt,
248
- currentTime: currentTime,
249
- },
250
- }),
251
- )
252
246
  .pay.ToContract(
253
247
  createScriptAddress(network, sysParams.validatorHashes.cdpHash, skh),
254
248
  {
@@ -256,6 +250,7 @@ export async function leverageCdpWithLrp(
256
250
  value: serialiseCdpDatum({
257
251
  cdpOwner: fromHex(pkh.hash),
258
252
  iasset: iassetDatum.assetName,
253
+ collateralAsset: collateralAssetDatum.collateralAsset,
259
254
  mintedAmt: mintedAmt,
260
255
  cdpFees: {
261
256
  ActiveCDPInterestTracking: {
@@ -269,31 +264,108 @@ export async function leverageCdpWithLrp(
269
264
  },
270
265
  }),
271
266
  },
272
- addAssets(cdpNftVal, mkLovelacesOf(collateralAmt)),
267
+ addAssets(
268
+ cdpNftVal,
269
+ mkAssetsOf(collateralAssetDatum.collateralAsset, collateralAmt),
270
+ ),
273
271
  )
274
272
  .pay.ToContract(
275
273
  cdpCreatorUtxo.address,
276
- { kind: 'inline', value: Data.void() },
274
+ {
275
+ kind: 'inline',
276
+ value: serialiseCDPCreatorDatum({
277
+ creatorInputOref: {
278
+ outputIndex: BigInt(cdpCreatorUtxo.outputIndex),
279
+ txHash: fromHex(cdpCreatorUtxo.txHash),
280
+ },
281
+ }),
282
+ },
277
283
  cdpCreatorUtxo.assets,
278
- )
279
- .addSignerKey(pkh.hash);
284
+ );
285
+
286
+ const treasuryRefScriptUtxo =
287
+ debtMintingFee > 0n
288
+ ? await treasuryFeeTx(
289
+ iassetClass,
290
+ debtMintingFee,
291
+ 0n,
292
+ lucid,
293
+ sysParams,
294
+ tx,
295
+ cdpCreatorUtxo,
296
+ treasuryOref,
297
+ )
298
+ : undefined;
299
+
300
+ const { interval, referenceInputs: refInputs } = await attachOracle(
301
+ iassetDatum.assetName,
302
+ collateralAssetDatum.collateralAsset,
303
+ collateralAssetDatum.priceInfo,
304
+ priceOracleOutRef,
305
+ pythStateOref,
306
+ pythMessage,
307
+ sysParams.pythConfig,
308
+ sysParams.cdpCreatorParams.biasTime,
309
+ currentSlot,
310
+ lucid,
311
+ tx,
312
+ );
313
+
314
+ const referenceInputs = [
315
+ interestOracleUtxo,
316
+ iassetUtxo,
317
+ collateralAssetUtxo,
318
+ ...refInputs,
319
+ ];
320
+
321
+ const refInputsIndices = getInputIndices(referenceInputs, [
322
+ ...referenceInputs,
323
+ ...refScripts,
324
+ ...(treasuryRefScriptUtxo != null ? [treasuryRefScriptUtxo] : []),
325
+ ]);
326
+
327
+ const oracleIdx: OracleIdx =
328
+ priceOracleOutRef !== undefined
329
+ ? { OracleRefInputIdx: refInputsIndices[3] }
330
+ : 'OracleVoid';
331
+
332
+ tx.validFrom(interval.validFrom)
333
+ .validTo(interval.validTo)
334
+ .readFrom(referenceInputs)
335
+ .collectFrom([cdpCreatorUtxo], {
336
+ kind: 'self',
337
+ makeRedeemer: (inputIdx) => {
338
+ return serialiseCDPCreatorRedeemer({
339
+ CreateCDP: {
340
+ cdpOwner: fromHex(pkh.hash),
341
+ minted: mintedAmt,
342
+ collateralAmt: collateralAmt,
343
+ currentTime: currentTime,
344
+ creatorInputIdx: inputIdx,
345
+ creatorOutputIdx: 1n,
346
+ cdpOutputIdx: 0n,
347
+ iassetRefInputIdx: refInputsIndices[1],
348
+ collateralAssetRefInputIdx: refInputsIndices[2],
349
+ interestOracleRefInputIdx: refInputsIndices[0],
350
+ priceOracleIdx: oracleIdx,
351
+ },
352
+ });
353
+ },
354
+ });
280
355
 
281
356
  buildRedemptionsTx(
282
- redemptionDetails.redemptions.map((r) => [
283
- r.utxo,
284
- r.iassetsForRedemptionAmt,
285
- ]),
286
- priceOracleDatum.price,
287
- iassetDatum.redemptionReimbursementPercentage,
357
+ redemptionDetails.redemptions.map((r) => [r.utxo, r.iassetsPayoutAmt]),
358
+ iassetDatum.assetName,
359
+ collateralAssetDatum.collateralAsset,
360
+ price,
361
+ iassetDatum.redemptionReimbursementRatio,
288
362
  sysParams,
289
363
  tx,
290
- 2n,
364
+ 2n + (debtMintingFee > 0n ? 1n : 0n),
365
+ refInputsIndices[2],
366
+ refInputsIndices[1],
367
+ oracleIdx,
291
368
  );
292
369
 
293
- if (debtMintingFee > 0) {
294
- await collectorFeeTx(debtMintingFee, lucid, sysParams, tx, collectorOref);
295
- }
296
-
297
370
  return tx;
298
371
  }
299
- */
package/src/index.ts CHANGED
@@ -6,8 +6,6 @@ export * from './contracts/cdp/scripts';
6
6
  export * from './contracts/cdp-creator/types';
7
7
  export * from './contracts/cdp-creator/scripts';
8
8
  export * from './contracts/poll/scripts';
9
- export * from './contracts/poll/types-poll-new';
10
- export * from './contracts/poll/helpers';
11
9
  export * from './contracts/collector/transactions';
12
10
  export * from './contracts/collector/types-new';
13
11
  export * from './contracts/gov/transactions';
@@ -23,6 +23,3 @@ export function loadSystemParamsFromUrl(url: string): Promise<SystemParams> {
23
23
  .then((res: Response) => res.json())
24
24
  .then((data: unknown) => data as SystemParams);
25
25
  }
26
-
27
- export const getRandomElement = <T>(arr: T[]) =>
28
- arr.length ? arr[Math.floor(Math.random() * arr.length)] : undefined;
@@ -13,7 +13,6 @@ import {
13
13
  cdpCollateralRatioPercentage,
14
14
  createScriptAddress,
15
15
  fromSystemParamsAsset,
16
- getRandomElement,
17
16
  matchSingle,
18
17
  SystemParams,
19
18
  } from '../../src';
@@ -29,6 +28,7 @@ import {
29
28
  AssetClass,
30
29
  assetClassToUnit,
31
30
  getInlineDatumOrThrow,
31
+ getRandomElement,
32
32
  } from '@3rd-eye-labs/cardano-offchain-common';
33
33
  import {
34
34
  InterestOracleDatum,
@@ -47,8 +47,20 @@ export async function init(
47
47
  ) => InitialAssetParam[] = () => [],
48
48
  overrideProtocolParams: Partial<ProtocolParams> = {},
49
49
  initOptions: InitializeOptions = DEFAULT_INIT_OPTIONS,
50
- spStakingCred?: ScriptCredential,
51
- treasuryStakingCred?: ScriptCredential,
50
+ spStakingCred: ScriptCredential = {
51
+ tag: 'StakingHash',
52
+ contents: {
53
+ tag: 'ScriptCredential',
54
+ contents: 'b8358aadd30c60eba168608ad5e875592e9b7cb8c700827cde87f9a3',
55
+ },
56
+ },
57
+ treasuryStakingCred: ScriptCredential = {
58
+ tag: 'StakingHash',
59
+ contents: {
60
+ tag: 'ScriptCredential',
61
+ contents: 'b8358aadd30c60eba168608ad5e875592e9b7cb8c700827cde87f9a3',
62
+ },
63
+ },
52
64
  ): Promise<ReturnType<typeof initContract>> {
53
65
  const protocolParams: ProtocolParams = {
54
66
  ...protocolParamsMock,
@@ -1,10 +1,11 @@
1
1
  import { LucidEvolution, UTxO } from '@lucid-evolution/lucid';
2
- import { createScriptAddress, getRandomElement } from '../../src';
2
+ import { createScriptAddress } from '../../src';
3
3
  import { option as O, function as F } from 'fp-ts';
4
4
  import {
5
5
  AssetClass,
6
6
  assetClassToUnit,
7
7
  assetClassValueOf,
8
+ getRandomElement,
8
9
  matchSingle,
9
10
  } from '@3rd-eye-labs/cardano-offchain-common';
10
11
 
@@ -1,6 +1,7 @@
1
1
  import { LucidEvolution, UTxO } from '@lucid-evolution/lucid';
2
- import { createScriptAddress, getRandomElement } from '../../src';
2
+ import { createScriptAddress } from '../../src';
3
3
  import { option as O, function as F } from 'fp-ts';
4
+ import { getRandomElement } from '@3rd-eye-labs/cardano-offchain-common';
4
5
 
5
6
  export async function findAllCollectors(
6
7
  lucid: LucidEvolution,
@@ -1,10 +1,11 @@
1
1
  import { LucidEvolution, ScriptHash, UTxO } from '@lucid-evolution/lucid';
2
2
 
3
- import { matchSingle, createScriptAddress, getRandomElement } from '../../src';
3
+ import { matchSingle, createScriptAddress } from '../../src';
4
4
  import { option as O, array as A, function as F } from 'fp-ts';
5
5
  import {
6
6
  AssetClass,
7
7
  assetClassToUnit,
8
+ getRandomElement,
8
9
  } from '@3rd-eye-labs/cardano-offchain-common';
9
10
  import {
10
11
  parsePollManager,
@@ -1,9 +1,10 @@
1
1
  import { LucidEvolution, UTxO } from '@lucid-evolution/lucid';
2
- import { getRandomElement, SystemParams } from '../../src';
2
+ import { SystemParams } from '../../src';
3
3
  import { option as O, function as F } from 'fp-ts';
4
4
  import {
5
5
  AssetClass,
6
6
  assetClassToUnit,
7
+ getRandomElement,
7
8
  } from '@3rd-eye-labs/cardano-offchain-common';
8
9
 
9
10
  export async function findRandomTreasuryUtxo(