@indigo-labs/indigo-sdk 0.2.41 → 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 -495
  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
@@ -1,18 +1,57 @@
1
+ import { AssetClass } from '@3rd-eye-labs/cardano-offchain-common';
2
+ import { InterestOracleParams } from '../interest-oracle/types';
1
3
  import { PriceOracleParams } from '../price-oracle/types';
4
+ import { Rational } from '../../types/rational';
5
+ import { PythFeedParamsSP } from '../../types/system-params';
2
6
 
3
- /**
4
- * Configuration for an asset to be initialized on the Indigo Protocol.
5
- */
6
- export type InitialAsset = {
7
- name: string;
8
- priceOracle: {
9
- tokenName: string;
10
- startPrice: bigint;
11
- params: {
12
- biasTime: bigint;
13
- expirationTime: bigint;
14
- };
7
+ export type CollateralAssetInfo = {
8
+ collateralAsset: AssetClass;
9
+ oracleParams: PriceOracleParams | undefined;
10
+ interestOracleParams: InterestOracleParams;
11
+ interestOracleNft: AssetClass;
12
+ };
13
+
14
+ export type AssetInfo = {
15
+ iassetTokenNameAscii: string;
16
+ collateralAssets: CollateralAssetInfo[];
17
+ };
18
+
19
+ /** Price oracle config for indigo oracle (used during initialize) */
20
+ export type IndigoOracleNftParam = {
21
+ tag: '_indigo_oracle_nft';
22
+ tokenName: string;
23
+ startPrice: Rational;
24
+ params: {
25
+ biasTime: bigint;
26
+ expirationPeriod: bigint;
15
27
  };
28
+ };
29
+
30
+ /** Price oracle config for Pyth (used during initialize) */
31
+ export type PythOracleParam = {
32
+ tag: '_pyth_oracle_nft';
33
+ pythFeedParams: PythFeedParamsSP;
34
+ };
35
+
36
+ export type PriceOracleParam = IndigoOracleNftParam | PythOracleParam;
37
+
38
+ export type InitialStablepoolParam = {
39
+ collateralAsset: AssetClass;
40
+ collateralToIassetRatio: Rational;
41
+ mintingFeeRatio: Rational;
42
+ redemptionFeeRatio: Rational;
43
+ mintingEnabled: boolean;
44
+ redemptionEnabled: boolean;
45
+ feeManager: string | undefined;
46
+ minMintOrderAmount: bigint;
47
+ minRedemptionOrderAmount: bigint;
48
+ };
49
+
50
+ /** Collateral asset input for initialize */
51
+ export type InitialCollateralAssetParam = {
52
+ collateralAsset: AssetClass;
53
+ extraDecimals: bigint;
54
+ priceOracle: PriceOracleParam;
16
55
  interestOracle: {
17
56
  tokenName: string;
18
57
  initialInterestRate: bigint;
@@ -20,23 +59,58 @@ export type InitialAsset = {
20
59
  biasTime: bigint;
21
60
  };
22
61
  };
23
- redemptionRatioPercentage: bigint;
24
- maintenanceRatioPercentage: bigint;
25
- liquidationRatioPercentage: bigint;
26
- debtMintingFeePercentage: bigint;
27
- liquidationProcessingFeePercentage: bigint;
28
- stabilityPoolWithdrawalFeePercentage: bigint;
29
- redemptionReimbursementPercentage: bigint;
30
- redemptionProcessingFeePercentage: bigint;
31
- interestCollectorPortionPercentage: bigint;
62
+ redemptionRatio: Rational;
63
+ maintenanceRatio: Rational;
64
+ liquidationRatio: Rational;
65
+ minCollateralAmt: bigint;
66
+ firstCollateralAsset: boolean;
67
+ nextCollateralAsset: AssetClass | undefined;
68
+ };
69
+
70
+ /** IAsset input for initialize */
71
+ export type InitialAssetParam = {
72
+ name: string;
73
+ collateralAssets: InitialCollateralAssetParam[];
74
+ stablepools: InitialStablepoolParam[];
75
+ debtMintingFeeRatio: Rational;
76
+ liquidationProcessingFeeRatio: Rational;
77
+ stabilityPoolWithdrawalFeeRatio: Rational;
78
+ redemptionReimbursementRatio: Rational;
79
+ redemptionProcessingFeeRatio: Rational;
32
80
  firstAsset: boolean;
33
- nextAsset?: string;
81
+ nextAsset?: string | undefined;
34
82
  };
35
83
 
36
- /**
37
- * Result of initializing a single asset (iAsset + stability pool + oracles).
38
- */
39
- export type AssetInfo = {
40
- iassetTokenNameAscii: string;
41
- oracleParams: PriceOracleParams;
84
+ /** Configurable options for protocol initialization */
85
+ export type InitializeOptions = {
86
+ /** Number of CDP creator UTxOs to create */
87
+ numCdpCreators: bigint;
88
+ /** Number of collector UTxOs to create */
89
+ numCollectors: bigint;
90
+ /** Number of interest collector UTxOs to create */
91
+ numInterestCollectors: bigint;
92
+ /** Number of treasury UTxo deployments */
93
+ numTreasuryUtxos: bigint;
94
+ /** INDY amount to send to the treasury */
95
+ treasuryIndyAmount: bigint;
96
+ /** Total INDY token supply to mint */
97
+ totalIndySupply: bigint;
98
+
99
+ /** Stability pool: fee in lovelace to create an SP account */
100
+ accountCreateFeeLovelaces: bigint;
101
+ /** Stability pool: cooldown between account processing (ms) */
102
+ accountProcessingCooldownMs: bigint;
103
+
104
+ /** Interest collection: cooldown between interest settlement (slot) */
105
+ interestSettlementCooldown: bigint;
106
+
107
+ /** CDP redeem: extra fee in lovelace for partial redemption */
108
+ partialRedemptionExtraFeeLovelace: number;
109
+ /** Default Protocol bias time (ms). Used for CDP, CDP Redeem, Stability Pool, Interest Collection, Interest Oracle, Price Oracle, and Stableswap. */
110
+ biasTime: bigint;
111
+ gBiasTime?: bigint;
112
+ accountProcessingBiasTime?: bigint;
113
+
114
+ /** Lovelace per interest collector deployment UTxO */
115
+ interestCollectorUtxoLovelaces: bigint;
42
116
  };
@@ -0,0 +1,19 @@
1
+ import { toHex } from '@lucid-evolution/lucid';
2
+ import { fromDataMultisig, Multisig } from '../../types/multisig';
3
+ import { Data } from '@evolution-sdk/evolution';
4
+
5
+ export function signersAllOf(multisig: Multisig): string[] {
6
+ if ('Signature' in multisig) {
7
+ return [toHex(multisig.Signature.keyHash)];
8
+ } else {
9
+ return multisig.AtLeast.authSignatories
10
+ .map((signatory: Data.Data) => {
11
+ try {
12
+ return signersAllOf(fromDataMultisig(signatory));
13
+ } catch {
14
+ return [];
15
+ }
16
+ })
17
+ .flat();
18
+ }
19
+ }
@@ -0,0 +1,44 @@
1
+ import { applyParamsToScript } from '@lucid-evolution/lucid';
2
+ import { SpendingValidator } from '@lucid-evolution/lucid';
3
+ import { _interestCollectionValidator } from '../../validators/interest-collection-validator';
4
+ import {
5
+ castInterestCollectionParams,
6
+ InterestCollectionParams,
7
+ } from './types';
8
+ import {
9
+ fromSystemParamsAssetLucid,
10
+ InterestCollectionParamsSP,
11
+ } from '../../types/system-params';
12
+
13
+ export function mkInterestCollectionValidator(
14
+ params: InterestCollectionParams,
15
+ ): SpendingValidator {
16
+ return {
17
+ type: 'PlutusV3',
18
+ script: applyParamsToScript(_interestCollectionValidator.cborHex, [
19
+ castInterestCollectionParams(params),
20
+ ]),
21
+ };
22
+ }
23
+
24
+ export const mkInterestCollectionValidatorFromSP = (
25
+ params: InterestCollectionParamsSP,
26
+ ): SpendingValidator => {
27
+ return {
28
+ type: 'PlutusV3',
29
+ script: applyParamsToScript(_interestCollectionValidator.cborHex, [
30
+ castInterestCollectionParams({
31
+ versionRecordNft: fromSystemParamsAssetLucid(params.versionRecordNft),
32
+ multisigUtxoNft: fromSystemParamsAssetLucid(params.multisigUtxoNft),
33
+ cdpAuthTk: fromSystemParamsAssetLucid(params.cdpAuthTk),
34
+ collateralAssetAuthTk: fromSystemParamsAssetLucid(
35
+ params.collateralAssetAuthTk,
36
+ ),
37
+ govAuthTk: fromSystemParamsAssetLucid(params.govAuthTk),
38
+ cdpAssetSymbol: params.cdpAssetSymbol.unCurrencySymbol,
39
+ cdpBiasTime: BigInt(params.cdpBiasTime),
40
+ interestSettlementCooldown: BigInt(params.interestSettlementCooldown),
41
+ }),
42
+ ]),
43
+ };
44
+ };
@@ -0,0 +1,436 @@
1
+ import {
2
+ Data,
3
+ LucidEvolution,
4
+ OutRef,
5
+ toHex,
6
+ TxBuilder,
7
+ UTxO,
8
+ addAssets,
9
+ Assets,
10
+ fromHex,
11
+ slotToUnixTime,
12
+ sortUTxOs,
13
+ getInputIndices,
14
+ } from '@lucid-evolution/lucid';
15
+ import {
16
+ fromSystemParamsAsset,
17
+ fromSystemParamsScriptRef,
18
+ SystemParams,
19
+ } from '../../types/system-params';
20
+ import { matchSingle } from '../../utils/utils';
21
+ import {
22
+ parseInterestCollectionDatum,
23
+ serialiseInterestCollectionDatum,
24
+ serialiseInterestCollectionRedeemer,
25
+ } from './types-new';
26
+ import {
27
+ assetClassValueOf,
28
+ getInlineDatumOrThrow,
29
+ mkAssetsOf,
30
+ } from '@3rd-eye-labs/cardano-offchain-common';
31
+ import { createScriptAddress } from '../../utils/lucid-utils';
32
+ import {
33
+ CDPContent,
34
+ parseCdpDatumOrThrow,
35
+ serialiseCdpDatum,
36
+ serialiseCdpRedeemer,
37
+ } from '../cdp/types-new';
38
+ import { parseInterestOracleDatum } from '../interest-oracle/types-new';
39
+ import {
40
+ calculateAccruedInterest,
41
+ calculateUnitaryInterestSinceOracleLastUpdated,
42
+ } from '../interest-oracle/helpers';
43
+ import { match, P } from 'ts-pattern';
44
+ import { array as A, function as F } from 'fp-ts';
45
+ import { parseCollateralAssetDatumOrThrow } from '../iasset/types';
46
+ import { Multisig } from '../../types/multisig';
47
+
48
+ type CDPInfo = {
49
+ utxo: UTxO;
50
+ datum: CDPContent;
51
+ accruedInterest: bigint;
52
+ };
53
+
54
+ export async function batchCollectInterest(
55
+ collateralAssetOref: OutRef,
56
+ interestCollectorOutRef: OutRef,
57
+ interestOracleOutRef: OutRef,
58
+ cdpOutRefs: OutRef[],
59
+ params: SystemParams,
60
+ lucid: LucidEvolution,
61
+ currentSlot: number,
62
+ ): Promise<TxBuilder> {
63
+ const network = lucid.config().network!;
64
+ const currentTime = BigInt(slotToUnixTime(network, currentSlot));
65
+
66
+ const interestCollectionRefScriptUtxo = matchSingle(
67
+ await lucid.utxosByOutRef([
68
+ fromSystemParamsScriptRef(
69
+ params.scriptReferences.interestCollectionValidatorRef,
70
+ ),
71
+ ]),
72
+ (_) => new Error('Expected a single interest collection Ref Script UTXO'),
73
+ );
74
+
75
+ const cdpRefScriptUtxo = matchSingle(
76
+ await lucid.utxosByOutRef([
77
+ fromSystemParamsScriptRef(params.scriptReferences.cdpValidatorRef),
78
+ ]),
79
+ (_) => new Error('Expected a single cdp Ref Script UTXO'),
80
+ );
81
+
82
+ const iAssetTokenPolicyRefScriptUtxo = matchSingle(
83
+ await lucid.utxosByOutRef([
84
+ fromSystemParamsScriptRef(params.scriptReferences.iAssetTokenPolicyRef),
85
+ ]),
86
+ (_) => new Error('Expected a single iasset token policy Ref Script UTXO'),
87
+ );
88
+
89
+ const collateralAssetUtxo = matchSingle(
90
+ await lucid.utxosByOutRef([collateralAssetOref]),
91
+ (_) => new Error('Expected a single iasset UTXO'),
92
+ );
93
+
94
+ const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
95
+ getInlineDatumOrThrow(collateralAssetUtxo),
96
+ );
97
+
98
+ const interestCollectorUtxo: UTxO = matchSingle(
99
+ await lucid.utxosByOutRef([interestCollectorOutRef]),
100
+ (_) => new Error('Expected a single interest collector UTXO'),
101
+ );
102
+
103
+ // Confirm that the interest collector UTXO is NOT of InterestCollectorDatum type
104
+ if (
105
+ assetClassValueOf(
106
+ interestCollectorUtxo.assets,
107
+ fromSystemParamsAsset(params.interestCollectionParams.multisigUtxoNft),
108
+ )
109
+ ) {
110
+ throw new Error(
111
+ 'Interest collector UTXO is of InterestCollectorDatum type',
112
+ );
113
+ }
114
+
115
+ const interestOracleUtxo: UTxO = matchSingle(
116
+ await lucid.utxosByOutRef([interestOracleOutRef]),
117
+ (_) => new Error('Expected a single interest oracle UTXO'),
118
+ );
119
+
120
+ const interestOracleDatum = parseInterestOracleDatum(
121
+ getInlineDatumOrThrow(interestOracleUtxo),
122
+ );
123
+
124
+ const cdpUtxos = await lucid.utxosByOutRef(cdpOutRefs);
125
+
126
+ const sortedCdpUtxos = sortUTxOs(cdpUtxos, 'Canonical');
127
+
128
+ if (sortedCdpUtxos.length !== cdpOutRefs.length) {
129
+ throw new Error('Expected certain number of CDPs');
130
+ }
131
+
132
+ function getAccruedInterest(cdpDatum: CDPContent): bigint {
133
+ return match(cdpDatum.cdpFees)
134
+ .with({ FrozenCDPAccumulatedFees: P.any }, () => {
135
+ throw new Error('CDP fees wrong');
136
+ })
137
+ .with({ ActiveCDPInterestTracking: P.select() }, (interest) => {
138
+ return calculateAccruedInterest(
139
+ currentTime,
140
+ interest.unitaryInterestSnapshot,
141
+ cdpDatum.mintedAmt,
142
+ interest.lastSettled,
143
+ interestOracleDatum,
144
+ );
145
+ })
146
+ .exhaustive();
147
+ }
148
+
149
+ const cdpsInfo: CDPInfo[] = sortedCdpUtxos.map((cdpUtxo) => {
150
+ const cdpDatum = parseCdpDatumOrThrow(getInlineDatumOrThrow(cdpUtxo));
151
+ return {
152
+ utxo: cdpUtxo,
153
+ datum: cdpDatum,
154
+ accruedInterest: getAccruedInterest(cdpDatum),
155
+ };
156
+ });
157
+
158
+ const accumulatedInterest = F.pipe(
159
+ cdpsInfo,
160
+ A.reduce<CDPInfo, bigint>(
161
+ 0n,
162
+ (acc, cdpInfo) => acc + cdpInfo.accruedInterest,
163
+ ),
164
+ );
165
+
166
+ const updatedUnitarySnapshot =
167
+ calculateUnitaryInterestSinceOracleLastUpdated(
168
+ currentTime,
169
+ interestOracleDatum,
170
+ ) + interestOracleDatum.unitaryInterest;
171
+
172
+ const referenceInputs = [
173
+ collateralAssetUtxo,
174
+ interestOracleUtxo,
175
+ interestCollectionRefScriptUtxo,
176
+ cdpRefScriptUtxo,
177
+ iAssetTokenPolicyRefScriptUtxo,
178
+ ];
179
+
180
+ const referenceInputIndices = getInputIndices(
181
+ [collateralAssetUtxo, interestOracleUtxo],
182
+ referenceInputs,
183
+ false,
184
+ );
185
+
186
+ const validateFrom = slotToUnixTime(network, currentSlot - 1);
187
+ const validateTo = validateFrom + Number(params.cdpParams.biasTime);
188
+
189
+ const tx = lucid
190
+ .newTx()
191
+ .validFrom(validateFrom)
192
+ .validTo(validateTo)
193
+ .readFrom(referenceInputs)
194
+ .collectFrom([interestCollectorUtxo], {
195
+ kind: 'selected',
196
+ makeRedeemer: (inputIndices: bigint[]) => {
197
+ return serialiseInterestCollectionRedeemer({
198
+ BatchCollectInterest: {
199
+ currentTime: currentTime,
200
+ ownInputIndex: inputIndices[0],
201
+ collateralAssetRefInputIndex: referenceInputIndices[0],
202
+ interestOracleRefInputIndex: referenceInputIndices[1],
203
+ },
204
+ });
205
+ },
206
+ inputs: [interestCollectorUtxo],
207
+ })
208
+ .mintAssets(
209
+ mkAssetsOf(
210
+ {
211
+ currencySymbol: fromHex(
212
+ params.cdpParams.cdpAssetSymbol.unCurrencySymbol,
213
+ ),
214
+ tokenName: collateralAssetDatum.iasset,
215
+ },
216
+ accumulatedInterest,
217
+ ),
218
+ Data.void(),
219
+ )
220
+ .pay.ToContract(
221
+ createScriptAddress(
222
+ lucid.config().network!,
223
+ params.validatorHashes.interestCollectionHash,
224
+ ),
225
+ { kind: 'inline', value: Data.void() },
226
+ addAssets(
227
+ interestCollectorUtxo.assets,
228
+ mkAssetsOf(
229
+ {
230
+ currencySymbol: fromHex(
231
+ params.cdpParams.cdpAssetSymbol.unCurrencySymbol,
232
+ ),
233
+ tokenName: collateralAssetDatum.iasset,
234
+ },
235
+ accumulatedInterest,
236
+ ),
237
+ ),
238
+ );
239
+
240
+ F.pipe(
241
+ cdpsInfo,
242
+ A.reduce<CDPInfo, TxBuilder>(tx, (acc, cdpInfo) =>
243
+ acc
244
+ .collectFrom([cdpInfo.utxo], {
245
+ kind: 'selected',
246
+ makeRedeemer: (inputIndices: bigint[]) => {
247
+ return serialiseCdpRedeemer({
248
+ SettleInterest: { interestCollectorInputIndex: inputIndices[0] },
249
+ });
250
+ },
251
+ inputs: [interestCollectorUtxo],
252
+ })
253
+ .pay.ToContract(
254
+ cdpInfo.utxo.address,
255
+ {
256
+ kind: 'inline',
257
+ value: serialiseCdpDatum({
258
+ ...cdpInfo.datum,
259
+ mintedAmt: cdpInfo.datum.mintedAmt + cdpInfo.accruedInterest,
260
+ cdpFees: {
261
+ ActiveCDPInterestTracking: {
262
+ lastSettled: currentTime,
263
+ unitaryInterestSnapshot: updatedUnitarySnapshot,
264
+ },
265
+ },
266
+ }),
267
+ },
268
+ cdpInfo.utxo.assets,
269
+ ),
270
+ ),
271
+ );
272
+
273
+ return tx;
274
+ }
275
+
276
+ export async function collectInterestTx(
277
+ value: Assets,
278
+ lucid: LucidEvolution,
279
+ sysParams: SystemParams,
280
+ tx: TxBuilder,
281
+ interestCollectorOref: OutRef,
282
+ ): Promise<UTxO> {
283
+ const interestCollectorUtxo = matchSingle(
284
+ await lucid.utxosByOutRef([interestCollectorOref]),
285
+ (_) => new Error('Expected a single interest collector UTXO'),
286
+ );
287
+ const interestCollectorRefScriptUtxo = matchSingle(
288
+ await lucid.utxosByOutRef([
289
+ fromSystemParamsScriptRef(
290
+ sysParams.scriptReferences.interestCollectionValidatorRef,
291
+ ),
292
+ ]),
293
+ (_) => new Error('Expected a single interest collector Ref Script UTXO'),
294
+ );
295
+
296
+ tx.readFrom([interestCollectorRefScriptUtxo])
297
+ .collectFrom(
298
+ [interestCollectorUtxo],
299
+ serialiseInterestCollectionRedeemer('CollectInterest'),
300
+ )
301
+ .pay.ToContract(
302
+ interestCollectorUtxo.address,
303
+ { kind: 'inline', value: Data.void() },
304
+ addAssets(interestCollectorUtxo.assets, value),
305
+ );
306
+
307
+ return interestCollectorRefScriptUtxo;
308
+ }
309
+
310
+ export async function distributeInterest(
311
+ interestCollectorOutRefs: OutRef[],
312
+ interestAdminOutRef: OutRef,
313
+ params: SystemParams,
314
+ lucid: LucidEvolution,
315
+ ): Promise<TxBuilder> {
316
+ const interestCollectorUtxos = [];
317
+
318
+ for (const outRef of interestCollectorOutRefs) {
319
+ interestCollectorUtxos.push(
320
+ matchSingle(
321
+ await lucid.utxosByOutRef([outRef]),
322
+ (_) => new Error('Expected a single UTXO with that reference'),
323
+ ),
324
+ );
325
+ }
326
+
327
+ const interestAdminUtxo: UTxO = matchSingle(
328
+ (await lucid.utxosByOutRef([interestAdminOutRef])).filter((utxo) =>
329
+ assetClassValueOf(
330
+ utxo.assets,
331
+ fromSystemParamsAsset(params.interestCollectionParams.multisigUtxoNft),
332
+ ),
333
+ ),
334
+ (_) => new Error('Expected a single interest admin UTXO'),
335
+ );
336
+
337
+ const interestAdminDatum = parseInterestCollectionDatum(
338
+ getInlineDatumOrThrow(interestAdminUtxo),
339
+ );
340
+
341
+ // Find the script reference UTXO for the interest collection validator
342
+ const interestCollectionRefScriptUtxo = matchSingle(
343
+ await lucid.utxosByOutRef([
344
+ fromSystemParamsScriptRef(
345
+ params.scriptReferences.interestCollectionValidatorRef,
346
+ ),
347
+ ]),
348
+ (_) => new Error('Expected a single interest collection Ref Script UTXO'),
349
+ );
350
+
351
+ const tx = lucid
352
+ .newTx()
353
+ .readFrom([interestCollectionRefScriptUtxo, interestAdminUtxo])
354
+ .collectFrom(
355
+ interestCollectorUtxos,
356
+ serialiseInterestCollectionRedeemer('Distribute'),
357
+ );
358
+
359
+ // TODO: Handle tx contruction for Multisig
360
+ if ('Signature' in interestAdminDatum.admin_permissions) {
361
+ tx.addSignerKey(
362
+ toHex(interestAdminDatum.admin_permissions.Signature.keyHash),
363
+ );
364
+ } else {
365
+ // TODO: Handle other admin permissions types
366
+ throw new Error('Unsupported admin permissions type');
367
+ }
368
+
369
+ return tx;
370
+ }
371
+
372
+ export async function updatePermissions(
373
+ interestAdminOutRef: OutRef,
374
+ govOref: OutRef,
375
+ newAdminPermissions: Multisig,
376
+ expectedSigners: string[],
377
+ params: SystemParams,
378
+ lucid: LucidEvolution,
379
+ ): Promise<TxBuilder> {
380
+ const interestAdminUtxo: UTxO = matchSingle(
381
+ (await lucid.utxosByOutRef([interestAdminOutRef])).filter((utxo) =>
382
+ assetClassValueOf(
383
+ utxo.assets,
384
+ fromSystemParamsAsset(params.interestCollectionParams.multisigUtxoNft),
385
+ ),
386
+ ),
387
+ (_) => new Error('Expected a single interest admin UTXO'),
388
+ );
389
+
390
+ const govUtxo: UTxO = matchSingle(
391
+ (await lucid.utxosByOutRef([govOref])).filter((utxo) =>
392
+ assetClassValueOf(
393
+ utxo.assets,
394
+ fromSystemParamsAsset(params.interestCollectionParams.govAuthTk),
395
+ ),
396
+ ),
397
+ (_) => new Error('Expected a single interest admin UTXO'),
398
+ );
399
+
400
+ // Find the script reference UTXO for the interest collection validator
401
+ const interestCollectionRefScriptUtxo = matchSingle(
402
+ await lucid.utxosByOutRef([
403
+ fromSystemParamsScriptRef(
404
+ params.scriptReferences.interestCollectionValidatorRef,
405
+ ),
406
+ ]),
407
+ (_) => new Error('Expected a single interest collection Ref Script UTXO'),
408
+ );
409
+
410
+ const tx = lucid
411
+ .newTx()
412
+ .readFrom([interestCollectionRefScriptUtxo, govUtxo])
413
+ .collectFrom(
414
+ [interestAdminUtxo],
415
+ serialiseInterestCollectionRedeemer('UpdatePermissions'),
416
+ )
417
+ .pay.ToContract(
418
+ createScriptAddress(
419
+ lucid.config().network!,
420
+ params.validatorHashes.interestCollectionHash,
421
+ ),
422
+ {
423
+ kind: 'inline',
424
+ value: serialiseInterestCollectionDatum({
425
+ admin_permissions: newAdminPermissions,
426
+ }),
427
+ },
428
+ interestAdminUtxo.assets,
429
+ );
430
+
431
+ for (const signer of expectedSigners) {
432
+ tx.addSignerKey(signer);
433
+ }
434
+
435
+ return tx;
436
+ }
@@ -0,0 +1,50 @@
1
+ import { TSchema, Data } from '@evolution-sdk/evolution';
2
+ import { MultisigSchema } from '../../types/multisig';
3
+
4
+ const InterestCollectionDatumSchema = TSchema.Struct({
5
+ admin_permissions: MultisigSchema,
6
+ });
7
+
8
+ export type InterestCollectionDatum = typeof InterestCollectionDatumSchema.Type;
9
+
10
+ const InterestCollectionRedeemerSchema = TSchema.Union(
11
+ TSchema.Literal('CollectInterest', { flatInUnion: true }),
12
+ TSchema.Struct(
13
+ {
14
+ BatchCollectInterest: TSchema.Struct(
15
+ {
16
+ currentTime: TSchema.Integer,
17
+ ownInputIndex: TSchema.Integer,
18
+ collateralAssetRefInputIndex: TSchema.Integer,
19
+ interestOracleRefInputIndex: TSchema.Integer,
20
+ },
21
+ { flatFields: true },
22
+ ),
23
+ },
24
+ { flatInUnion: true },
25
+ ),
26
+ TSchema.Literal('Distribute', { flatInUnion: true }),
27
+ TSchema.Literal('UpdatePermissions', { flatInUnion: true }),
28
+ TSchema.Literal('UpgradeVersion', { flatInUnion: true }),
29
+ );
30
+
31
+ export type InterestCollectionRedeemer =
32
+ typeof InterestCollectionRedeemerSchema.Type;
33
+
34
+ export function serialiseInterestCollectionRedeemer(
35
+ redeemer: InterestCollectionRedeemer,
36
+ ): string {
37
+ return Data.withSchema(InterestCollectionRedeemerSchema).toCBORHex(redeemer);
38
+ }
39
+
40
+ export function parseInterestCollectionDatum(
41
+ datum: string,
42
+ ): InterestCollectionDatum {
43
+ return Data.withSchema(InterestCollectionDatumSchema).fromCBORHex(datum);
44
+ }
45
+
46
+ export function serialiseInterestCollectionDatum(
47
+ datum: InterestCollectionDatum,
48
+ ): string {
49
+ return Data.withSchema(InterestCollectionDatumSchema).toCBORHex(datum);
50
+ }