@indigo-labs/indigo-sdk 0.5.5 → 0.5.6

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 (204) hide show
  1. package/package.json +11 -1
  2. package/.claude/settings.local.json +0 -7
  3. package/.github/workflows/ci.yml +0 -66
  4. package/.husky/pre-commit +0 -1
  5. package/.nvmrc +0 -1
  6. package/.prettierignore +0 -1
  7. package/.prettierrc +0 -6
  8. package/eslint.config.mjs +0 -42
  9. package/scripts/bench.sh +0 -62
  10. package/scripts/run-repeat.sh +0 -22
  11. package/src/contracts/cdp/helpers.ts +0 -173
  12. package/src/contracts/cdp/scripts.ts +0 -70
  13. package/src/contracts/cdp/transactions.ts +0 -1584
  14. package/src/contracts/cdp/types-new.ts +0 -277
  15. package/src/contracts/cdp/types.ts +0 -43
  16. package/src/contracts/cdp-creator/queries.ts +0 -30
  17. package/src/contracts/cdp-creator/scripts.ts +0 -45
  18. package/src/contracts/cdp-creator/types-new.ts +0 -50
  19. package/src/contracts/cdp-creator/types.ts +0 -24
  20. package/src/contracts/collector/scripts.ts +0 -32
  21. package/src/contracts/collector/transactions.ts +0 -50
  22. package/src/contracts/collector/types-new.ts +0 -17
  23. package/src/contracts/execute/scripts.ts +0 -57
  24. package/src/contracts/execute/types-new.ts +0 -44
  25. package/src/contracts/execute/types.ts +0 -24
  26. package/src/contracts/gov/helpers.ts +0 -351
  27. package/src/contracts/gov/scripts.ts +0 -41
  28. package/src/contracts/gov/transactions.ts +0 -1607
  29. package/src/contracts/gov/types-new.ts +0 -268
  30. package/src/contracts/gov/types.ts +0 -22
  31. package/src/contracts/iasset/helpers.ts +0 -170
  32. package/src/contracts/iasset/queries.ts +0 -102
  33. package/src/contracts/iasset/scripts.ts +0 -38
  34. package/src/contracts/iasset/types.ts +0 -154
  35. package/src/contracts/initialize/actions.ts +0 -789
  36. package/src/contracts/initialize/helpers.ts +0 -616
  37. package/src/contracts/initialize/types.ts +0 -116
  38. package/src/contracts/interest-collection/helpers.ts +0 -19
  39. package/src/contracts/interest-collection/queries.ts +0 -66
  40. package/src/contracts/interest-collection/scripts.ts +0 -44
  41. package/src/contracts/interest-collection/transactions.ts +0 -433
  42. package/src/contracts/interest-collection/types-new.ts +0 -50
  43. package/src/contracts/interest-collection/types.ts +0 -26
  44. package/src/contracts/interest-oracle/helpers.ts +0 -61
  45. package/src/contracts/interest-oracle/scripts.ts +0 -18
  46. package/src/contracts/interest-oracle/transactions.ts +0 -151
  47. package/src/contracts/interest-oracle/types-new.ts +0 -32
  48. package/src/contracts/interest-oracle/types.ts +0 -16
  49. package/src/contracts/one-shot/scripts.ts +0 -12
  50. package/src/contracts/one-shot/transactions.ts +0 -66
  51. package/src/contracts/one-shot/types.ts +0 -22
  52. package/src/contracts/poll/helpers.ts +0 -37
  53. package/src/contracts/poll/scripts.ts +0 -71
  54. package/src/contracts/poll/types-poll-manager.ts +0 -20
  55. package/src/contracts/poll/types-poll-new.ts +0 -196
  56. package/src/contracts/poll/types-poll-shard.ts +0 -16
  57. package/src/contracts/price-oracle/helpers.ts +0 -30
  58. package/src/contracts/price-oracle/scripts.ts +0 -18
  59. package/src/contracts/price-oracle/transactions.ts +0 -115
  60. package/src/contracts/price-oracle/types-new.ts +0 -50
  61. package/src/contracts/price-oracle/types.ts +0 -16
  62. package/src/contracts/pyth-feed/helpers.ts +0 -82
  63. package/src/contracts/pyth-feed/scripts.ts +0 -15
  64. package/src/contracts/pyth-feed/types.ts +0 -181
  65. package/src/contracts/rob/helpers.ts +0 -666
  66. package/src/contracts/rob/scripts.ts +0 -35
  67. package/src/contracts/rob/transactions.ts +0 -423
  68. package/src/contracts/rob/types-new.ts +0 -128
  69. package/src/contracts/rob/types.ts +0 -16
  70. package/src/contracts/rob-leverage/helpers.ts +0 -422
  71. package/src/contracts/rob-leverage/transactions.ts +0 -368
  72. package/src/contracts/stability-pool/helpers.ts +0 -798
  73. package/src/contracts/stability-pool/queries.ts +0 -132
  74. package/src/contracts/stability-pool/scripts.ts +0 -51
  75. package/src/contracts/stability-pool/transactions.ts +0 -921
  76. package/src/contracts/stability-pool/types-new.ts +0 -385
  77. package/src/contracts/stability-pool/types.ts +0 -25
  78. package/src/contracts/stableswap/helpers.ts +0 -507
  79. package/src/contracts/stableswap/scripts.ts +0 -37
  80. package/src/contracts/stableswap/transactions.ts +0 -475
  81. package/src/contracts/stableswap/types-new.ts +0 -131
  82. package/src/contracts/stableswap/types.ts +0 -17
  83. package/src/contracts/staking/helpers.ts +0 -136
  84. package/src/contracts/staking/scripts.ts +0 -41
  85. package/src/contracts/staking/transactions.ts +0 -349
  86. package/src/contracts/staking/types-new.ts +0 -137
  87. package/src/contracts/staking/types.ts +0 -17
  88. package/src/contracts/treasury/helpers.ts +0 -21
  89. package/src/contracts/treasury/queries.ts +0 -100
  90. package/src/contracts/treasury/scripts.ts +0 -27
  91. package/src/contracts/treasury/transactions.ts +0 -334
  92. package/src/contracts/treasury/types-new.ts +0 -69
  93. package/src/contracts/treasury/types.ts +0 -14
  94. package/src/contracts/version-registry/scripts.ts +0 -29
  95. package/src/contracts/version-registry/types-new.ts +0 -18
  96. package/src/contracts/version-registry/types.ts +0 -17
  97. package/src/index.ts +0 -99
  98. package/src/scripts/always-fail-validator.ts +0 -7
  99. package/src/scripts/auth-token-policy.ts +0 -24
  100. package/src/scripts/iasset-policy.ts +0 -23
  101. package/src/types/evolution-schema-options.ts +0 -16
  102. package/src/types/generic.ts +0 -52
  103. package/src/types/multisig.ts +0 -48
  104. package/src/types/on-chain-decimal.ts +0 -57
  105. package/src/types/rational.ts +0 -76
  106. package/src/types/system-params.ts +0 -463
  107. package/src/utils/array-utils.ts +0 -108
  108. package/src/utils/bigint-utils.ts +0 -35
  109. package/src/utils/helper-txs.ts +0 -31
  110. package/src/utils/indigo-helpers.ts +0 -17
  111. package/src/utils/lucid-utils.ts +0 -125
  112. package/src/utils/oracle-helpers.ts +0 -62
  113. package/src/utils/pyth/decode.ts +0 -223
  114. package/src/utils/pyth/encode.ts +0 -262
  115. package/src/utils/pyth/index.ts +0 -14
  116. package/src/utils/pyth/types.ts +0 -87
  117. package/src/utils/time-helpers.ts +0 -4
  118. package/src/utils/utils.ts +0 -25
  119. package/src/validators/always-succeed-validator.ts +0 -6
  120. package/src/validators/cdp-creator-validator.ts +0 -7
  121. package/src/validators/cdp-redeem-validator.ts +0 -7
  122. package/src/validators/cdp-validator.ts +0 -7
  123. package/src/validators/collector-validator.ts +0 -7
  124. package/src/validators/execute-validator.ts +0 -7
  125. package/src/validators/governance-validator.ts +0 -7
  126. package/src/validators/iasset-validator.ts +0 -7
  127. package/src/validators/interest-collection-validator.ts +0 -7
  128. package/src/validators/interest-oracle-validator.ts +0 -7
  129. package/src/validators/one-shot-policy.ts +0 -7
  130. package/src/validators/poll-manager-validator.ts +0 -7
  131. package/src/validators/poll-shard-validator.ts +0 -7
  132. package/src/validators/price-oracle-validator.ts +0 -7
  133. package/src/validators/pyth-feed-validator.ts +0 -7
  134. package/src/validators/rob-validator.ts +0 -7
  135. package/src/validators/stability-pool-validator.ts +0 -7
  136. package/src/validators/stableswap-validator.ts +0 -7
  137. package/src/validators/staking-validator.ts +0 -7
  138. package/src/validators/treasury-validator.ts +0 -7
  139. package/src/validators/version-record-policy.ts +0 -7
  140. package/src/validators/version-registry-validator.ts +0 -7
  141. package/tests/always-succeed/script.ts +0 -7
  142. package/tests/array-utils.test.ts +0 -92
  143. package/tests/bigint-utils.test.ts +0 -41
  144. package/tests/cdp/actions.ts +0 -680
  145. package/tests/cdp/cdp-helpers.ts +0 -55
  146. package/tests/cdp/cdp-queries.ts +0 -423
  147. package/tests/cdp/cdp.test.ts +0 -6730
  148. package/tests/cdp/transactions-mutated.ts +0 -1733
  149. package/tests/data/system-params.json +0 -1155
  150. package/tests/datums.test.ts +0 -302
  151. package/tests/endpoints/initialize.ts +0 -78
  152. package/tests/endpoints/interest-collector.ts +0 -37
  153. package/tests/endpoints/treasury.ts +0 -70
  154. package/tests/gov/actions.ts +0 -381
  155. package/tests/gov/gov.test.ts +0 -5147
  156. package/tests/gov/governance-queries.ts +0 -37
  157. package/tests/hash-checks.test.ts +0 -112
  158. package/tests/indigo-test-helpers.ts +0 -99
  159. package/tests/initialize.test.ts +0 -79
  160. package/tests/interest-calculations.test.ts +0 -120
  161. package/tests/interest-collection/interest-collection.test.ts +0 -843
  162. package/tests/interest-collection/transactions-mutated.ts +0 -260
  163. package/tests/interest-oracle.test.ts +0 -93
  164. package/tests/mock/assets-mock.ts +0 -243
  165. package/tests/mock/protocol-params-mock.ts +0 -21
  166. package/tests/price-oracle/actions.ts +0 -161
  167. package/tests/price-oracle/price-oracle-queries.ts +0 -12
  168. package/tests/price-oracle/price-oracle.test.ts +0 -228
  169. package/tests/price-oracle/transactions-mutated.ts +0 -59
  170. package/tests/pyth/endpoints.ts +0 -96
  171. package/tests/pyth/helpers.ts +0 -37
  172. package/tests/pyth/pyth-encoding.test.ts +0 -376
  173. package/tests/pyth/pyth-feeds.test.ts +0 -943
  174. package/tests/pyth/pyth-indigo.test.ts +0 -505
  175. package/tests/pyth/pyth.test.ts +0 -299
  176. package/tests/queries/collector-queries.ts +0 -27
  177. package/tests/queries/execute-queries.ts +0 -47
  178. package/tests/queries/iasset-queries.ts +0 -149
  179. package/tests/queries/interest-oracle-queries.ts +0 -12
  180. package/tests/queries/poll-queries.ts +0 -97
  181. package/tests/queries/staking-queries.ts +0 -54
  182. package/tests/rob/actions.ts +0 -56
  183. package/tests/rob/rob-leverage.test.ts +0 -2555
  184. package/tests/rob/rob-queries.ts +0 -95
  185. package/tests/rob/rob.test.ts +0 -3677
  186. package/tests/rob/transactions-mutated.ts +0 -844
  187. package/tests/script-size.test.ts +0 -240
  188. package/tests/setup.ts +0 -135
  189. package/tests/stability-pool/actions.ts +0 -229
  190. package/tests/stability-pool.test.ts +0 -6491
  191. package/tests/stableswap/stableswap-actions.ts +0 -83
  192. package/tests/stableswap/stableswap-queries.ts +0 -98
  193. package/tests/stableswap/stableswap.test.ts +0 -4471
  194. package/tests/stableswap/transactions-mutated.ts +0 -348
  195. package/tests/staking.test.ts +0 -172
  196. package/tests/test-helpers.ts +0 -94
  197. package/tests/treasury/actions.ts +0 -67
  198. package/tests/treasury/treasury.test.ts +0 -320
  199. package/tests/utils/asserts.ts +0 -87
  200. package/tests/utils/benchmark-utils.ts +0 -130
  201. package/tests/utils/index.ts +0 -168
  202. package/tsconfig.build.json +0 -4
  203. package/tsconfig.json +0 -27
  204. package/vitest.config.ts +0 -11
@@ -1,921 +0,0 @@
1
- import {
2
- fromText,
3
- LucidEvolution,
4
- TxBuilder,
5
- Data,
6
- UTxO,
7
- fromHex,
8
- toHex,
9
- addAssets,
10
- OutRef,
11
- credentialToAddress,
12
- } from '@lucid-evolution/lucid';
13
- import {
14
- fromSysParamsCredential,
15
- fromSystemParamsAsset,
16
- fromSystemParamsScriptRef,
17
- SystemParams,
18
- } from '../../types/system-params';
19
- import { addrDetails, getInlineDatumOrThrow } from '../../utils/lucid-utils';
20
- import {
21
- BASE_MAX_TX_FEE,
22
- createProcessRequestAccountRedeemer,
23
- findRelevantE2s2sIdxs,
24
- initSpState,
25
- liquidationHelper,
26
- partitionEpochToScaleToSums,
27
- updateAccount,
28
- updatePoolStateWhenWithdrawalFee,
29
- } from './helpers';
30
- import { calculateFeeFromRatio } from '../../utils/indigo-helpers';
31
- import {
32
- AccountAction,
33
- AccountContent,
34
- fromSPInteger,
35
- mkSPInteger,
36
- parseAccountDatumOrThrow,
37
- parseStabilityPoolDatumOrThrow,
38
- serialiseActionReturnDatum,
39
- serialiseStabilityPoolDatum,
40
- serialiseStabilityPoolRedeemer,
41
- spAdd,
42
- spSub,
43
- spZeroNegatives,
44
- } from './types-new';
45
- import {
46
- adaAssetClass,
47
- addressFromBech32,
48
- addressToBech32,
49
- AssetClass,
50
- assetClassValueOf,
51
- estimateUtxoMinLovelace,
52
- lovelacesAmt,
53
- matchSingle,
54
- mkAssetsOf,
55
- mkLovelacesOf,
56
- negateAssets,
57
- } from '@3rd-eye-labs/cardano-offchain-common';
58
- import { parseIAssetDatumOrThrow } from '../iasset/types';
59
- import { match, P } from 'ts-pattern';
60
- import { bigintMax, zeroNegatives } from '../../utils/bigint-utils';
61
-
62
- export async function requestSpAccountCreation(
63
- assetAscii: string,
64
- amount: bigint,
65
- sysParams: SystemParams,
66
- lucid: LucidEvolution,
67
- ): Promise<TxBuilder> {
68
- const [pkh, _skh] = await addrDetails(lucid);
69
-
70
- const iasset = fromHex(fromText(assetAscii));
71
- const iassetAssetClass = {
72
- currencySymbol: fromHex(
73
- sysParams.stabilityPoolParams.assetSymbol.unCurrencySymbol,
74
- ),
75
- tokenName: iasset,
76
- };
77
-
78
- const datum: AccountContent = {
79
- owner: fromHex(pkh.hash),
80
- iasset: iasset,
81
- state: { ...initSpState, depositVal: mkSPInteger(amount) },
82
- assetSums: [],
83
- request: 'Create',
84
- lastRequestProcessingTime: 0n,
85
- };
86
-
87
- return lucid
88
- .newTx()
89
- .pay.ToContract(
90
- credentialToAddress(
91
- lucid.config().network!,
92
- {
93
- hash: sysParams.validatorHashes.stabilityPoolHash,
94
- type: 'Script',
95
- },
96
- sysParams.stabilityPoolParams.stakeCredential != null
97
- ? fromSysParamsCredential(
98
- sysParams.stabilityPoolParams.stakeCredential,
99
- )
100
- : undefined,
101
- ),
102
- {
103
- kind: 'inline',
104
- value: serialiseStabilityPoolDatum({ Account: datum }),
105
- },
106
- addAssets(
107
- mkAssetsOf(iassetAssetClass, amount),
108
- mkLovelacesOf(
109
- // TODO: Calculate a more accurate amount to just cover costs.
110
- // This should cover the account creation fee,
111
- // the minimum ADA for the account UTxO and the transaction fee.
112
- BigInt(sysParams.stabilityPoolParams.accountCreateFeeLovelaces) +
113
- 3_000_000n,
114
- ),
115
- ),
116
- )
117
- .addSignerKey(pkh.hash);
118
- }
119
-
120
- export async function requestSpAccountAdjustment(
121
- amount: bigint,
122
- accountUtxo: UTxO,
123
- sysParams: SystemParams,
124
- lucid: LucidEvolution,
125
- ): Promise<TxBuilder> {
126
- const myAddress = await lucid.wallet().address();
127
-
128
- const stabilityPoolScriptRef = matchSingle(
129
- await lucid.utxosByOutRef([
130
- fromSystemParamsScriptRef(
131
- sysParams.scriptReferences.stabilityPoolValidatorRef,
132
- ),
133
- ]),
134
- (_) => new Error('Expected a single stability pool Ref Script UTXO'),
135
- );
136
-
137
- const oldAccountDatum: AccountContent = parseAccountDatumOrThrow(
138
- getInlineDatumOrThrow(accountUtxo),
139
- );
140
-
141
- const newAccountDatum: AccountContent = {
142
- ...oldAccountDatum,
143
- request: {
144
- Adjust: {
145
- amount: amount,
146
- outputAddress: addressFromBech32(myAddress),
147
- },
148
- },
149
- };
150
-
151
- return lucid
152
- .newTx()
153
- .readFrom([stabilityPoolScriptRef])
154
- .collectFrom(
155
- [accountUtxo],
156
- serialiseStabilityPoolRedeemer({
157
- RequestAction: {
158
- Adjust: {
159
- amount: amount,
160
- outputAddress: addressFromBech32(myAddress),
161
- },
162
- },
163
- }),
164
- )
165
- .pay.ToContract(
166
- accountUtxo.address,
167
- {
168
- kind: 'inline',
169
- value: serialiseStabilityPoolDatum({
170
- Account: newAccountDatum,
171
- }),
172
- },
173
- addAssets(
174
- mkLovelacesOf(
175
- // TODO: Calculate a more accurate amount to just cover costs.
176
- // This should cover the minimum ADA for 2 UTxOs (account and
177
- // rewards withdrawal) and the transaction fee.
178
- 5_000_000n,
179
- ),
180
- mkAssetsOf(
181
- fromSystemParamsAsset(sysParams.stabilityPoolParams.accountToken),
182
- 1n,
183
- ),
184
- amount > 0n
185
- ? mkAssetsOf(
186
- {
187
- currencySymbol: fromHex(
188
- sysParams.stabilityPoolParams.assetSymbol.unCurrencySymbol,
189
- ),
190
- tokenName: oldAccountDatum.iasset,
191
- },
192
- amount,
193
- )
194
- : {},
195
- ),
196
- )
197
- .addSignerKey(toHex(oldAccountDatum.owner));
198
- }
199
-
200
- export async function requestSpAccountClosure(
201
- accountUtxo: UTxO,
202
- sysParams: SystemParams,
203
- lucid: LucidEvolution,
204
- maxTxFee: bigint = BASE_MAX_TX_FEE,
205
- ): Promise<TxBuilder> {
206
- const myAddress = await lucid.wallet().address();
207
-
208
- const stabilityPoolScriptRef = matchSingle(
209
- await lucid.utxosByOutRef([
210
- fromSystemParamsScriptRef(
211
- sysParams.scriptReferences.stabilityPoolValidatorRef,
212
- ),
213
- ]),
214
- (_) => new Error('Expected a single stability pool Ref Script UTXO'),
215
- );
216
-
217
- const request: AccountAction = {
218
- Close: {
219
- outputAddress: addressFromBech32(myAddress),
220
- maxTxFee: maxTxFee,
221
- },
222
- };
223
- const oldAccountDatum: AccountContent = parseAccountDatumOrThrow(
224
- getInlineDatumOrThrow(accountUtxo),
225
- );
226
- const newAccountDatum: AccountContent = {
227
- ...oldAccountDatum,
228
- request: request,
229
- };
230
-
231
- return lucid
232
- .newTx()
233
- .readFrom([stabilityPoolScriptRef])
234
- .collectFrom(
235
- [accountUtxo],
236
- serialiseStabilityPoolRedeemer({ RequestAction: request }),
237
- )
238
- .pay.ToContract(
239
- accountUtxo.address,
240
- {
241
- kind: 'inline',
242
- value: serialiseStabilityPoolDatum({ Account: newAccountDatum }),
243
- },
244
- addAssets(
245
- mkLovelacesOf(
246
- // TODO: Calculate a more accurate amount to just cover costs.
247
- // This should cover the minimum ADA for the rewards UTxO and the transaction fee.
248
- 3_000_000n,
249
- ),
250
- mkAssetsOf(
251
- fromSystemParamsAsset(sysParams.stabilityPoolParams.accountToken),
252
- 1n,
253
- ),
254
- ),
255
- )
256
- .addSignerKey(toHex(oldAccountDatum.owner));
257
- }
258
-
259
- async function processSpRequestAuxiliary(
260
- stabilityPoolUtxo: UTxO,
261
- accountUtxo: UTxO,
262
- iAssetUtxo: UTxO,
263
- /**
264
- * For performance provide only the ones related to the pool's iAsset.
265
- */
266
- allE2s2sSnapshotOrefs: OutRef[],
267
- sysParams: SystemParams,
268
- lucid: LucidEvolution,
269
- txFee: bigint,
270
- currentSlot?: number,
271
- ): Promise<TxBuilder> {
272
- const slot = currentSlot !== undefined ? currentSlot : lucid.currentSlot();
273
- const currentTime = BigInt(lucid.slotToUnixTime(slot));
274
-
275
- const stabilityPoolScriptRef = matchSingle(
276
- await lucid.utxosByOutRef([
277
- fromSystemParamsScriptRef(
278
- sysParams.scriptReferences.stabilityPoolValidatorRef,
279
- ),
280
- ]),
281
- (_) => new Error('Expected a single stability pool Ref Script UTXO'),
282
- );
283
-
284
- const accountDatum = parseAccountDatumOrThrow(
285
- getInlineDatumOrThrow(accountUtxo),
286
- );
287
-
288
- const stabilityPoolDatum = parseStabilityPoolDatumOrThrow(
289
- getInlineDatumOrThrow(stabilityPoolUtxo),
290
- );
291
-
292
- const baseRefInputs = [iAssetUtxo, stabilityPoolScriptRef];
293
-
294
- const validFrom = lucid.slotToUnixTime(slot - 1);
295
- const tx = lucid
296
- .newTx()
297
- .validFrom(validFrom)
298
- .validTo(validFrom + sysParams.stabilityPoolParams.accountProcessingBiasMs)
299
- .readFrom(baseRefInputs)
300
- .collectFrom([stabilityPoolUtxo], {
301
- kind: 'selected',
302
- inputs: [stabilityPoolUtxo, accountUtxo],
303
- makeRedeemer: (indices) =>
304
- serialiseStabilityPoolRedeemer({
305
- ProcessRequestPool: {
306
- poolInputIdx: indices[0],
307
- accountInputIdx: indices[1],
308
- },
309
- }),
310
- });
311
- if (!accountDatum.request) throw new Error('Account Request is null');
312
-
313
- const iassetAssetClass: AssetClass = {
314
- currencySymbol: fromHex(
315
- sysParams.stabilityPoolParams.assetSymbol.unCurrencySymbol,
316
- ),
317
- tokenName: stabilityPoolDatum.iasset,
318
- };
319
-
320
- await match(accountDatum.request)
321
- .with('Create', async (_) => {
322
- const accountTokenScriptRef = matchSingle(
323
- await lucid.utxosByOutRef([
324
- fromSystemParamsScriptRef(
325
- sysParams.scriptReferences.authTokenPolicies.accountTokenRef,
326
- ),
327
- ]),
328
- (_) =>
329
- new Error('Expected a single cdp auth token policy Ref Script UTXO'),
330
- );
331
-
332
- const requestDepositAmt = assetClassValueOf(
333
- accountUtxo.assets,
334
- iassetAssetClass,
335
- );
336
-
337
- const poolAddr = credentialToAddress(
338
- lucid.config().network!,
339
- {
340
- hash: sysParams.validatorHashes.stabilityPoolHash,
341
- type: 'Script',
342
- },
343
- sysParams.stabilityPoolParams.stakeCredential != null
344
- ? fromSysParamsCredential(
345
- sysParams.stabilityPoolParams.stakeCredential,
346
- )
347
- : undefined,
348
- );
349
-
350
- const accountOutputAdaAmt =
351
- lovelacesAmt(accountUtxo.assets) -
352
- BigInt(sysParams.stabilityPoolParams.accountCreateFeeLovelaces) -
353
- txFee;
354
-
355
- const accountTokenVal = mkAssetsOf(
356
- fromSystemParamsAsset(sysParams.stabilityPoolParams.accountToken),
357
- 1n,
358
- );
359
-
360
- const accountOutputDatum = serialiseStabilityPoolDatum({
361
- Account: {
362
- owner: accountDatum.owner,
363
- iasset: stabilityPoolDatum.iasset,
364
- state: {
365
- ...stabilityPoolDatum.state,
366
- depositVal: mkSPInteger(requestDepositAmt),
367
- },
368
- assetSums: stabilityPoolDatum.assetStates.map(([key, val]) => [
369
- key,
370
- val.currentSumVal,
371
- ]),
372
- request: null,
373
- lastRequestProcessingTime: currentTime,
374
- },
375
- });
376
-
377
- const accountOutMinUtxoLovelace = estimateUtxoMinLovelace(
378
- lucid.config().protocolParameters!,
379
- poolAddr,
380
- accountTokenVal,
381
- { InlineDatum: { datum: accountOutputDatum } },
382
- );
383
-
384
- // This is to prevent spending ADA from the wallet submitting the request processing Tx.
385
- if (accountOutputAdaAmt < accountOutMinUtxoLovelace) {
386
- throw new Error("Request doesn't have enough ADA to be processed.");
387
- }
388
-
389
- tx.readFrom([accountTokenScriptRef])
390
- .collectFrom([accountUtxo], {
391
- kind: 'selected',
392
- inputs: [stabilityPoolUtxo, accountUtxo],
393
- makeRedeemer: (indices) =>
394
- serialiseStabilityPoolRedeemer({
395
- ProcessRequestAccount: {
396
- poolInputIdx: indices[0],
397
- accountInputIdx: indices[1],
398
- e2s2sIdxs: [],
399
- currentTime: currentTime,
400
- },
401
- }),
402
- })
403
- .mintAssets(accountTokenVal, Data.void())
404
- .pay.ToContract(
405
- poolAddr,
406
- {
407
- kind: 'inline',
408
- value: serialiseStabilityPoolDatum({
409
- StabilityPool: liquidationHelper(
410
- {
411
- ...stabilityPoolDatum,
412
- state: {
413
- ...stabilityPoolDatum.state,
414
- depositVal: spAdd(
415
- stabilityPoolDatum.state.depositVal,
416
- mkSPInteger(requestDepositAmt),
417
- ),
418
- },
419
- },
420
- adaAssetClass,
421
- 0n,
422
- BigInt(sysParams.stabilityPoolParams.accountCreateFeeLovelaces),
423
- ),
424
- }),
425
- },
426
- addAssets(
427
- stabilityPoolUtxo.assets,
428
- mkAssetsOf(iassetAssetClass, requestDepositAmt),
429
- mkLovelacesOf(
430
- BigInt(sysParams.stabilityPoolParams.accountCreateFeeLovelaces),
431
- ),
432
- ),
433
- )
434
- .pay.ToContract(
435
- poolAddr,
436
- {
437
- kind: 'inline',
438
- value: accountOutputDatum,
439
- },
440
- addAssets(accountTokenVal, mkLovelacesOf(accountOutputAdaAmt)),
441
- )
442
- .setMinFee(txFee);
443
- })
444
- .with({ Adjust: P.select() }, async (adjustContent) => {
445
- const iassetDatum = parseIAssetDatumOrThrow(
446
- getInlineDatumOrThrow(iAssetUtxo),
447
- );
448
-
449
- const accountDepositChange = adjustContent.amount;
450
- const outputAddress = addressToBech32(
451
- adjustContent.outputAddress,
452
- lucid.config().network!,
453
- );
454
-
455
- const e2s2sIdxs = await findRelevantE2s2sIdxs(
456
- lucid,
457
- stabilityPoolDatum,
458
- accountDatum.state,
459
- allE2s2sSnapshotOrefs,
460
- );
461
-
462
- const { updatedAccountContent, reward } = updateAccount(
463
- stabilityPoolDatum,
464
- accountDatum,
465
- e2s2sIdxs,
466
- );
467
-
468
- const isDepositOrRewardWithdrawal = accountDepositChange >= 0;
469
-
470
- const accountBalanceChange = isDepositOrRewardWithdrawal
471
- ? accountDepositChange
472
- : bigintMax(
473
- accountDepositChange,
474
- -fromSPInteger(updatedAccountContent.state.depositVal),
475
- );
476
-
477
- const newPoolDepositExcludingFee = spZeroNegatives(
478
- spAdd(
479
- stabilityPoolDatum.state.depositVal,
480
- mkSPInteger(accountBalanceChange),
481
- ),
482
- );
483
-
484
- const withdrawalFeeAmt =
485
- isDepositOrRewardWithdrawal || newPoolDepositExcludingFee.value === 0n
486
- ? 0n
487
- : calculateFeeFromRatio(
488
- iassetDatum.stabilityPoolWithdrawalFeeRatio,
489
- -accountBalanceChange,
490
- );
491
-
492
- const newPoolState = updatePoolStateWhenWithdrawalFee(withdrawalFeeAmt, {
493
- ...stabilityPoolDatum.state,
494
- depositVal: newPoolDepositExcludingFee,
495
- });
496
-
497
- const { e2s2sRefInputs, mkProcessRequestAccountRedeemerContent } =
498
- createProcessRequestAccountRedeemer(
499
- e2s2sIdxs,
500
- baseRefInputs,
501
- currentTime,
502
- );
503
-
504
- if (e2s2sRefInputs.length > 0) {
505
- tx.readFrom(e2s2sRefInputs);
506
- }
507
-
508
- tx.collectFrom([accountUtxo], {
509
- kind: 'selected',
510
- inputs: [stabilityPoolUtxo, accountUtxo],
511
- makeRedeemer: (indices) => {
512
- return serialiseStabilityPoolRedeemer({
513
- ProcessRequestAccount: mkProcessRequestAccountRedeemerContent(
514
- indices[0],
515
- indices[1],
516
- ),
517
- });
518
- },
519
- }).pay.ToContract(
520
- stabilityPoolUtxo.address,
521
- {
522
- kind: 'inline',
523
- value: serialiseStabilityPoolDatum({
524
- StabilityPool: {
525
- ...stabilityPoolDatum,
526
- state: newPoolState,
527
- },
528
- }),
529
- },
530
- addAssets(
531
- stabilityPoolUtxo.assets,
532
- negateAssets(reward),
533
- mkAssetsOf(iassetAssetClass, accountBalanceChange + withdrawalFeeAmt),
534
- ),
535
- );
536
-
537
- const theoreticalOwnerOutputVal = addAssets(
538
- reward,
539
- isDepositOrRewardWithdrawal
540
- ? {}
541
- : mkAssetsOf(
542
- iassetAssetClass,
543
- -accountBalanceChange - withdrawalFeeAmt,
544
- ),
545
- );
546
- const ownerOutputDat = serialiseActionReturnDatum({
547
- IndigoStabilityPoolAccountAdjustment: {
548
- txHash: fromHex(accountUtxo.txHash),
549
- outputIndex: BigInt(accountUtxo.outputIndex),
550
- },
551
- });
552
-
553
- const ownerOutputMinUtxoLovelace = estimateUtxoMinLovelace(
554
- lucid.config().protocolParameters!,
555
- outputAddress,
556
- theoreticalOwnerOutputVal,
557
- { InlineDatum: { datum: ownerOutputDat } },
558
- );
559
-
560
- // Add extra lovelaces only when needed to reach minUTxo lovelaces.
561
- const extraOwnerOutputLovelacesAmt =
562
- lovelacesAmt(theoreticalOwnerOutputVal) >= ownerOutputMinUtxoLovelace
563
- ? 0n
564
- : ownerOutputMinUtxoLovelace -
565
- lovelacesAmt(theoreticalOwnerOutputVal);
566
-
567
- const actualOwnerOutputVal = addAssets(
568
- theoreticalOwnerOutputVal,
569
- mkLovelacesOf(extraOwnerOutputLovelacesAmt),
570
- );
571
-
572
- const accountOutputDat = serialiseStabilityPoolDatum({
573
- Account: {
574
- ...updatedAccountContent,
575
- state: {
576
- ...updatedAccountContent.state,
577
- depositVal: spAdd(
578
- updatedAccountContent.state.depositVal,
579
- mkSPInteger(accountBalanceChange),
580
- ),
581
- },
582
- request: null,
583
- lastRequestProcessingTime: currentTime,
584
- },
585
- });
586
-
587
- const accountOutputValWithoutAda = mkAssetsOf(
588
- fromSystemParamsAsset(sysParams.stabilityPoolParams.accountToken),
589
- 1n,
590
- );
591
-
592
- const accountOutMinUtxoLovelace = estimateUtxoMinLovelace(
593
- lucid.config().protocolParameters!,
594
- stabilityPoolUtxo.address,
595
- accountOutputValWithoutAda,
596
- { InlineDatum: { datum: accountOutputDat } },
597
- );
598
-
599
- const accountOutputAdaAmt =
600
- lovelacesAmt(accountUtxo.assets) - extraOwnerOutputLovelacesAmt - txFee;
601
-
602
- // This is to prevent spending ADA from the wallet submitting the request processing Tx.
603
- if (accountOutputAdaAmt < accountOutMinUtxoLovelace) {
604
- throw new Error("Account doesn't have enough ADA to be processed.");
605
- }
606
-
607
- tx.pay
608
- .ToContract(
609
- stabilityPoolUtxo.address,
610
- {
611
- kind: 'inline',
612
- value: accountOutputDat,
613
- },
614
- addAssets(
615
- accountOutputValWithoutAda,
616
- mkLovelacesOf(accountOutputAdaAmt),
617
- ),
618
- )
619
- .pay.ToAddressWithData(
620
- outputAddress,
621
- {
622
- kind: 'inline',
623
- value: ownerOutputDat,
624
- },
625
- actualOwnerOutputVal,
626
- )
627
- .setMinFee(txFee);
628
- })
629
- .with({ Close: P.select() }, async (closeContent) => {
630
- if (txFee > closeContent.maxTxFee) {
631
- throw new Error("Account doesn't allow current transaction fee.");
632
- }
633
-
634
- const accountTokenScriptRef = matchSingle(
635
- await lucid.utxosByOutRef([
636
- fromSystemParamsScriptRef(
637
- sysParams.scriptReferences.authTokenPolicies.accountTokenRef,
638
- ),
639
- ]),
640
- (_) =>
641
- new Error('Expected a single cdp auth token policy Ref Script UTXO'),
642
- );
643
-
644
- const iassetDatum = parseIAssetDatumOrThrow(
645
- getInlineDatumOrThrow(iAssetUtxo),
646
- );
647
-
648
- const outputAddress = addressToBech32(
649
- closeContent.outputAddress,
650
- lucid.config().network!,
651
- );
652
-
653
- const e2s2sIdxs = await findRelevantE2s2sIdxs(
654
- lucid,
655
- stabilityPoolDatum,
656
- accountDatum.state,
657
- allE2s2sSnapshotOrefs,
658
- );
659
-
660
- const { updatedAccountContent, reward } = updateAccount(
661
- stabilityPoolDatum,
662
- accountDatum,
663
- e2s2sIdxs,
664
- );
665
-
666
- const newPoolDepositExcludingFee = spZeroNegatives(
667
- spSub(
668
- stabilityPoolDatum.state.depositVal,
669
- updatedAccountContent.state.depositVal,
670
- ),
671
- );
672
-
673
- const withdrawnAmt = zeroNegatives(
674
- fromSPInteger(updatedAccountContent.state.depositVal),
675
- );
676
-
677
- const withdrawalFeeAmt =
678
- newPoolDepositExcludingFee.value === 0n
679
- ? 0n
680
- : calculateFeeFromRatio(
681
- iassetDatum.stabilityPoolWithdrawalFeeRatio,
682
- withdrawnAmt,
683
- );
684
-
685
- const newPoolState = updatePoolStateWhenWithdrawalFee(withdrawalFeeAmt, {
686
- ...stabilityPoolDatum.state,
687
- depositVal: newPoolDepositExcludingFee,
688
- });
689
-
690
- const { e2s2sRefInputs, mkProcessRequestAccountRedeemerContent } =
691
- createProcessRequestAccountRedeemer(
692
- e2s2sIdxs,
693
- [...baseRefInputs, accountTokenScriptRef],
694
- currentTime,
695
- );
696
-
697
- if (e2s2sRefInputs.length > 0) {
698
- tx.readFrom(e2s2sRefInputs);
699
- }
700
-
701
- tx.readFrom([accountTokenScriptRef])
702
- .collectFrom([accountUtxo], {
703
- kind: 'selected',
704
- inputs: [stabilityPoolUtxo, accountUtxo],
705
- makeRedeemer: (indices) => {
706
- return serialiseStabilityPoolRedeemer({
707
- ProcessRequestAccount: mkProcessRequestAccountRedeemerContent(
708
- indices[0],
709
- indices[1],
710
- ),
711
- });
712
- },
713
- })
714
- .mintAssets(
715
- mkAssetsOf(
716
- fromSystemParamsAsset(sysParams.stabilityPoolParams.accountToken),
717
- -1n,
718
- ),
719
- Data.void(),
720
- )
721
- .pay.ToContract(
722
- stabilityPoolUtxo.address,
723
- {
724
- kind: 'inline',
725
- value: serialiseStabilityPoolDatum({
726
- StabilityPool: {
727
- ...stabilityPoolDatum,
728
- state: newPoolState,
729
- },
730
- }),
731
- },
732
- addAssets(
733
- stabilityPoolUtxo.assets,
734
- negateAssets(reward),
735
- mkAssetsOf(iassetAssetClass, -withdrawnAmt + withdrawalFeeAmt),
736
- ),
737
- )
738
- .pay.ToAddressWithData(
739
- outputAddress,
740
- {
741
- kind: 'inline',
742
- value: serialiseActionReturnDatum({
743
- IndigoStabilityPoolAccountClosure: {
744
- txHash: fromHex(accountUtxo.txHash),
745
- outputIndex: BigInt(accountUtxo.outputIndex),
746
- },
747
- }),
748
- },
749
- addAssets(
750
- mkLovelacesOf(lovelacesAmt(accountUtxo.assets) - txFee),
751
- reward,
752
- mkAssetsOf(iassetAssetClass, withdrawnAmt - withdrawalFeeAmt),
753
- ),
754
- )
755
- .setMinFee(txFee);
756
- })
757
- .exhaustive();
758
-
759
- return tx;
760
- }
761
-
762
- export async function processSpRequest(
763
- stabilityPoolUtxo: UTxO,
764
- accountUtxo: UTxO,
765
- iAssetUtxo: UTxO,
766
- /**
767
- * For performance provide only the ones related to the pool's iAsset.
768
- */
769
- allE2s2sSnapshotOrefs: OutRef[],
770
- sysParams: SystemParams,
771
- lucid: LucidEvolution,
772
- currentSlot?: number,
773
- ): Promise<TxBuilder> {
774
- const draftTx = processSpRequestAuxiliary(
775
- stabilityPoolUtxo,
776
- accountUtxo,
777
- iAssetUtxo,
778
- allE2s2sSnapshotOrefs,
779
- sysParams,
780
- lucid,
781
- // Placeholder transation fee
782
- 1n,
783
- currentSlot,
784
- );
785
-
786
- const fee = (await (await draftTx).complete()).toTransaction().body().fee();
787
-
788
- return processSpRequestAuxiliary(
789
- stabilityPoolUtxo,
790
- accountUtxo,
791
- iAssetUtxo,
792
- allE2s2sSnapshotOrefs,
793
- sysParams,
794
- lucid,
795
- fee,
796
- currentSlot,
797
- );
798
- }
799
-
800
- export async function createE2s2sSnapshots(
801
- stabilityPoolOref: OutRef,
802
- sysParams: SystemParams,
803
- lucid: LucidEvolution,
804
- ): Promise<TxBuilder> {
805
- const stabilityPoolRefScriptUtxo = matchSingle(
806
- await lucid.utxosByOutRef([
807
- fromSystemParamsScriptRef(
808
- sysParams.scriptReferences.stabilityPoolValidatorRef,
809
- ),
810
- ]),
811
- (_) => new Error('Expected a single stability pool Ref Script UTXO'),
812
- );
813
- const snapshotE2s2sPolicyRefScriptUtxo = matchSingle(
814
- await lucid.utxosByOutRef([
815
- fromSystemParamsScriptRef(
816
- sysParams.scriptReferences.authTokenPolicies
817
- .snapshotEpochToScaleToSumTokenRef,
818
- ),
819
- ]),
820
- (_) => new Error('Expected a single snapshot e2s2s policy Ref Script UTXO'),
821
- );
822
-
823
- const spUtxo = matchSingle(
824
- await lucid.utxosByOutRef([stabilityPoolOref]),
825
- (_) => new Error('Expected a single stability pool UTXO'),
826
- );
827
- const spDatum = parseStabilityPoolDatumOrThrow(getInlineDatumOrThrow(spUtxo));
828
-
829
- const [newSnapshotDatums, newAssetStates] =
830
- partitionEpochToScaleToSums(spDatum);
831
-
832
- if (newSnapshotDatums.length === 0) {
833
- throw new Error('There has to be a snapshot being created.');
834
- }
835
-
836
- const snapshotAc = fromSystemParamsAsset(
837
- sysParams.stabilityPoolParams.snapshotEpochToScaleToSumToken,
838
- );
839
-
840
- const tx = lucid
841
- .newTx()
842
- .readFrom([stabilityPoolRefScriptUtxo, snapshotE2s2sPolicyRefScriptUtxo])
843
- .collectFrom(
844
- [spUtxo],
845
- serialiseStabilityPoolRedeemer('RecordEpochToScaleToSum'),
846
- )
847
- .mintAssets(
848
- mkAssetsOf(snapshotAc, BigInt(newSnapshotDatums.length)),
849
- Data.void(),
850
- )
851
- .pay.ToContract(
852
- spUtxo.address,
853
- {
854
- kind: 'inline',
855
- value: serialiseStabilityPoolDatum({
856
- StabilityPool: { ...spDatum, assetStates: newAssetStates },
857
- }),
858
- },
859
- spUtxo.assets,
860
- );
861
-
862
- for (const newDatum of newSnapshotDatums) {
863
- tx.pay.ToContract(
864
- spUtxo.address,
865
- {
866
- kind: 'inline',
867
- value: serialiseStabilityPoolDatum({
868
- SnapshotEpochToScaleToSum: newDatum,
869
- }),
870
- },
871
- mkAssetsOf(snapshotAc, 1n),
872
- );
873
- }
874
-
875
- return tx;
876
- }
877
-
878
- export async function annulRequest(
879
- accountUtxo: UTxO,
880
- params: SystemParams,
881
- lucid: LucidEvolution,
882
- ): Promise<TxBuilder> {
883
- const stabilityPoolRefScriptUtxo = matchSingle(
884
- await lucid.utxosByOutRef([
885
- fromSystemParamsScriptRef(
886
- params.scriptReferences.stabilityPoolValidatorRef,
887
- ),
888
- ]),
889
- (_) => new Error('Expected a single stability pool Ref Script UTXO'),
890
- );
891
- const oldAccountDatum: AccountContent = parseAccountDatumOrThrow(
892
- getInlineDatumOrThrow(accountUtxo),
893
- );
894
-
895
- const tx = lucid
896
- .newTx()
897
- .readFrom([stabilityPoolRefScriptUtxo])
898
- .collectFrom([accountUtxo], serialiseStabilityPoolRedeemer('AnnulRequest'))
899
- .addSignerKey(toHex(oldAccountDatum.owner));
900
-
901
- if (oldAccountDatum.request !== 'Create') {
902
- tx.pay.ToContract(
903
- accountUtxo.address,
904
- {
905
- kind: 'inline',
906
- value: serialiseStabilityPoolDatum({
907
- Account: {
908
- ...oldAccountDatum,
909
- request: null,
910
- },
911
- }),
912
- },
913
- mkAssetsOf(
914
- fromSystemParamsAsset(params.stabilityPoolParams.accountToken),
915
- 1n,
916
- ),
917
- );
918
- }
919
-
920
- return tx;
921
- }