@indigo-labs/indigo-sdk 0.5.4 → 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 (208) hide show
  1. package/dist/index.d.mts +11 -1
  2. package/dist/index.d.ts +11 -1
  3. package/dist/index.js +17 -0
  4. package/dist/index.mjs +15 -0
  5. package/package.json +11 -1
  6. package/.claude/settings.local.json +0 -7
  7. package/.github/workflows/ci.yml +0 -66
  8. package/.husky/pre-commit +0 -1
  9. package/.nvmrc +0 -1
  10. package/.prettierignore +0 -1
  11. package/.prettierrc +0 -6
  12. package/eslint.config.mjs +0 -42
  13. package/scripts/bench.sh +0 -62
  14. package/scripts/run-repeat.sh +0 -22
  15. package/src/contracts/cdp/helpers.ts +0 -173
  16. package/src/contracts/cdp/scripts.ts +0 -70
  17. package/src/contracts/cdp/transactions.ts +0 -1584
  18. package/src/contracts/cdp/types-new.ts +0 -277
  19. package/src/contracts/cdp/types.ts +0 -43
  20. package/src/contracts/cdp-creator/queries.ts +0 -30
  21. package/src/contracts/cdp-creator/scripts.ts +0 -45
  22. package/src/contracts/cdp-creator/types-new.ts +0 -50
  23. package/src/contracts/cdp-creator/types.ts +0 -24
  24. package/src/contracts/collector/scripts.ts +0 -32
  25. package/src/contracts/collector/transactions.ts +0 -50
  26. package/src/contracts/collector/types-new.ts +0 -17
  27. package/src/contracts/execute/scripts.ts +0 -57
  28. package/src/contracts/execute/types-new.ts +0 -44
  29. package/src/contracts/execute/types.ts +0 -24
  30. package/src/contracts/gov/helpers.ts +0 -351
  31. package/src/contracts/gov/scripts.ts +0 -41
  32. package/src/contracts/gov/transactions.ts +0 -1607
  33. package/src/contracts/gov/types-new.ts +0 -268
  34. package/src/contracts/gov/types.ts +0 -22
  35. package/src/contracts/iasset/helpers.ts +0 -170
  36. package/src/contracts/iasset/queries.ts +0 -102
  37. package/src/contracts/iasset/scripts.ts +0 -38
  38. package/src/contracts/iasset/types.ts +0 -154
  39. package/src/contracts/initialize/actions.ts +0 -789
  40. package/src/contracts/initialize/helpers.ts +0 -616
  41. package/src/contracts/initialize/types.ts +0 -116
  42. package/src/contracts/interest-collection/helpers.ts +0 -19
  43. package/src/contracts/interest-collection/queries.ts +0 -66
  44. package/src/contracts/interest-collection/scripts.ts +0 -44
  45. package/src/contracts/interest-collection/transactions.ts +0 -433
  46. package/src/contracts/interest-collection/types-new.ts +0 -50
  47. package/src/contracts/interest-collection/types.ts +0 -26
  48. package/src/contracts/interest-oracle/helpers.ts +0 -61
  49. package/src/contracts/interest-oracle/scripts.ts +0 -18
  50. package/src/contracts/interest-oracle/transactions.ts +0 -151
  51. package/src/contracts/interest-oracle/types-new.ts +0 -32
  52. package/src/contracts/interest-oracle/types.ts +0 -16
  53. package/src/contracts/one-shot/scripts.ts +0 -12
  54. package/src/contracts/one-shot/transactions.ts +0 -66
  55. package/src/contracts/one-shot/types.ts +0 -22
  56. package/src/contracts/poll/helpers.ts +0 -37
  57. package/src/contracts/poll/scripts.ts +0 -71
  58. package/src/contracts/poll/types-poll-manager.ts +0 -20
  59. package/src/contracts/poll/types-poll-new.ts +0 -196
  60. package/src/contracts/poll/types-poll-shard.ts +0 -16
  61. package/src/contracts/price-oracle/helpers.ts +0 -30
  62. package/src/contracts/price-oracle/scripts.ts +0 -18
  63. package/src/contracts/price-oracle/transactions.ts +0 -115
  64. package/src/contracts/price-oracle/types-new.ts +0 -50
  65. package/src/contracts/price-oracle/types.ts +0 -16
  66. package/src/contracts/pyth-feed/helpers.ts +0 -82
  67. package/src/contracts/pyth-feed/scripts.ts +0 -15
  68. package/src/contracts/pyth-feed/types.ts +0 -181
  69. package/src/contracts/rob/helpers.ts +0 -666
  70. package/src/contracts/rob/scripts.ts +0 -35
  71. package/src/contracts/rob/transactions.ts +0 -423
  72. package/src/contracts/rob/types-new.ts +0 -128
  73. package/src/contracts/rob/types.ts +0 -16
  74. package/src/contracts/rob-leverage/helpers.ts +0 -422
  75. package/src/contracts/rob-leverage/transactions.ts +0 -368
  76. package/src/contracts/stability-pool/helpers.ts +0 -798
  77. package/src/contracts/stability-pool/queries.ts +0 -132
  78. package/src/contracts/stability-pool/scripts.ts +0 -51
  79. package/src/contracts/stability-pool/transactions.ts +0 -921
  80. package/src/contracts/stability-pool/types-new.ts +0 -385
  81. package/src/contracts/stability-pool/types.ts +0 -25
  82. package/src/contracts/stableswap/helpers.ts +0 -507
  83. package/src/contracts/stableswap/scripts.ts +0 -37
  84. package/src/contracts/stableswap/transactions.ts +0 -475
  85. package/src/contracts/stableswap/types-new.ts +0 -131
  86. package/src/contracts/stableswap/types.ts +0 -17
  87. package/src/contracts/staking/helpers.ts +0 -136
  88. package/src/contracts/staking/scripts.ts +0 -41
  89. package/src/contracts/staking/transactions.ts +0 -349
  90. package/src/contracts/staking/types-new.ts +0 -137
  91. package/src/contracts/staking/types.ts +0 -17
  92. package/src/contracts/treasury/helpers.ts +0 -21
  93. package/src/contracts/treasury/queries.ts +0 -100
  94. package/src/contracts/treasury/scripts.ts +0 -27
  95. package/src/contracts/treasury/transactions.ts +0 -334
  96. package/src/contracts/treasury/types-new.ts +0 -69
  97. package/src/contracts/treasury/types.ts +0 -14
  98. package/src/contracts/version-registry/scripts.ts +0 -29
  99. package/src/contracts/version-registry/types-new.ts +0 -18
  100. package/src/contracts/version-registry/types.ts +0 -17
  101. package/src/index.ts +0 -93
  102. package/src/scripts/always-fail-validator.ts +0 -7
  103. package/src/scripts/auth-token-policy.ts +0 -24
  104. package/src/scripts/iasset-policy.ts +0 -23
  105. package/src/types/evolution-schema-options.ts +0 -16
  106. package/src/types/generic.ts +0 -52
  107. package/src/types/multisig.ts +0 -48
  108. package/src/types/on-chain-decimal.ts +0 -57
  109. package/src/types/rational.ts +0 -61
  110. package/src/types/system-params.ts +0 -463
  111. package/src/utils/array-utils.ts +0 -108
  112. package/src/utils/bigint-utils.ts +0 -35
  113. package/src/utils/helper-txs.ts +0 -31
  114. package/src/utils/indigo-helpers.ts +0 -17
  115. package/src/utils/lucid-utils.ts +0 -125
  116. package/src/utils/oracle-helpers.ts +0 -62
  117. package/src/utils/pyth/decode.ts +0 -223
  118. package/src/utils/pyth/encode.ts +0 -262
  119. package/src/utils/pyth/index.ts +0 -14
  120. package/src/utils/pyth/types.ts +0 -87
  121. package/src/utils/time-helpers.ts +0 -4
  122. package/src/utils/utils.ts +0 -25
  123. package/src/validators/always-succeed-validator.ts +0 -6
  124. package/src/validators/cdp-creator-validator.ts +0 -7
  125. package/src/validators/cdp-redeem-validator.ts +0 -7
  126. package/src/validators/cdp-validator.ts +0 -7
  127. package/src/validators/collector-validator.ts +0 -7
  128. package/src/validators/execute-validator.ts +0 -7
  129. package/src/validators/governance-validator.ts +0 -7
  130. package/src/validators/iasset-validator.ts +0 -7
  131. package/src/validators/interest-collection-validator.ts +0 -7
  132. package/src/validators/interest-oracle-validator.ts +0 -7
  133. package/src/validators/one-shot-policy.ts +0 -7
  134. package/src/validators/poll-manager-validator.ts +0 -7
  135. package/src/validators/poll-shard-validator.ts +0 -7
  136. package/src/validators/price-oracle-validator.ts +0 -7
  137. package/src/validators/pyth-feed-validator.ts +0 -7
  138. package/src/validators/rob-validator.ts +0 -7
  139. package/src/validators/stability-pool-validator.ts +0 -7
  140. package/src/validators/stableswap-validator.ts +0 -7
  141. package/src/validators/staking-validator.ts +0 -7
  142. package/src/validators/treasury-validator.ts +0 -7
  143. package/src/validators/version-record-policy.ts +0 -7
  144. package/src/validators/version-registry-validator.ts +0 -7
  145. package/tests/always-succeed/script.ts +0 -7
  146. package/tests/array-utils.test.ts +0 -92
  147. package/tests/bigint-utils.test.ts +0 -41
  148. package/tests/cdp/actions.ts +0 -680
  149. package/tests/cdp/cdp-helpers.ts +0 -55
  150. package/tests/cdp/cdp-queries.ts +0 -423
  151. package/tests/cdp/cdp.test.ts +0 -6730
  152. package/tests/cdp/transactions-mutated.ts +0 -1733
  153. package/tests/data/system-params.json +0 -1155
  154. package/tests/datums.test.ts +0 -302
  155. package/tests/endpoints/initialize.ts +0 -78
  156. package/tests/endpoints/interest-collector.ts +0 -37
  157. package/tests/endpoints/treasury.ts +0 -70
  158. package/tests/gov/actions.ts +0 -381
  159. package/tests/gov/gov.test.ts +0 -5147
  160. package/tests/gov/governance-queries.ts +0 -37
  161. package/tests/hash-checks.test.ts +0 -112
  162. package/tests/indigo-test-helpers.ts +0 -99
  163. package/tests/initialize.test.ts +0 -79
  164. package/tests/interest-calculations.test.ts +0 -120
  165. package/tests/interest-collection/interest-collection.test.ts +0 -843
  166. package/tests/interest-collection/transactions-mutated.ts +0 -260
  167. package/tests/interest-oracle.test.ts +0 -93
  168. package/tests/mock/assets-mock.ts +0 -243
  169. package/tests/mock/protocol-params-mock.ts +0 -21
  170. package/tests/price-oracle/actions.ts +0 -161
  171. package/tests/price-oracle/price-oracle-queries.ts +0 -12
  172. package/tests/price-oracle/price-oracle.test.ts +0 -228
  173. package/tests/price-oracle/transactions-mutated.ts +0 -59
  174. package/tests/pyth/endpoints.ts +0 -96
  175. package/tests/pyth/helpers.ts +0 -37
  176. package/tests/pyth/pyth-encoding.test.ts +0 -376
  177. package/tests/pyth/pyth-feeds.test.ts +0 -943
  178. package/tests/pyth/pyth-indigo.test.ts +0 -505
  179. package/tests/pyth/pyth.test.ts +0 -299
  180. package/tests/queries/collector-queries.ts +0 -27
  181. package/tests/queries/execute-queries.ts +0 -47
  182. package/tests/queries/iasset-queries.ts +0 -149
  183. package/tests/queries/interest-oracle-queries.ts +0 -12
  184. package/tests/queries/poll-queries.ts +0 -97
  185. package/tests/queries/staking-queries.ts +0 -54
  186. package/tests/rob/actions.ts +0 -56
  187. package/tests/rob/rob-leverage.test.ts +0 -2555
  188. package/tests/rob/rob-queries.ts +0 -95
  189. package/tests/rob/rob.test.ts +0 -3677
  190. package/tests/rob/transactions-mutated.ts +0 -844
  191. package/tests/script-size.test.ts +0 -240
  192. package/tests/setup.ts +0 -135
  193. package/tests/stability-pool/actions.ts +0 -229
  194. package/tests/stability-pool.test.ts +0 -6491
  195. package/tests/stableswap/stableswap-actions.ts +0 -83
  196. package/tests/stableswap/stableswap-queries.ts +0 -98
  197. package/tests/stableswap/stableswap.test.ts +0 -4471
  198. package/tests/stableswap/transactions-mutated.ts +0 -348
  199. package/tests/staking.test.ts +0 -172
  200. package/tests/test-helpers.ts +0 -94
  201. package/tests/treasury/actions.ts +0 -67
  202. package/tests/treasury/treasury.test.ts +0 -320
  203. package/tests/utils/asserts.ts +0 -87
  204. package/tests/utils/benchmark-utils.ts +0 -130
  205. package/tests/utils/index.ts +0 -168
  206. package/tsconfig.build.json +0 -4
  207. package/tsconfig.json +0 -27
  208. package/vitest.config.ts +0 -11
@@ -1,798 +0,0 @@
1
- import {
2
- addAssets,
3
- Address,
4
- Assets,
5
- credentialToAddress,
6
- getInputIndices,
7
- LucidEvolution,
8
- OutRef,
9
- toHex,
10
- UTxO,
11
- validatorToScriptHash,
12
- } from '@lucid-evolution/lucid';
13
- import {
14
- AccountContent,
15
- AssetSnapshot,
16
- AssetState,
17
- E2S2SIndex,
18
- E2S2SIndicesPerAsset,
19
- EpochToScaleKey,
20
- EpochToScaleToSumEntry,
21
- fromSPInteger,
22
- mkSPInteger,
23
- parseSnapshotEpochToScaleToSumDatumOrThrow,
24
- ProcessRequestAccountContent,
25
- SnapshotEpochToScaleToSumContent,
26
- spAdd,
27
- spDiv,
28
- SPInteger,
29
- spMul,
30
- spSub,
31
- StabilityPoolContent,
32
- StateSnapshot,
33
- SumSnapshot,
34
- } from './types-new';
35
- import {
36
- readonlyArray as RA,
37
- array as A,
38
- function as F,
39
- option as O,
40
- } from 'fp-ts';
41
- import {
42
- AssetClass,
43
- getInlineDatumOrThrow,
44
- isSameAssetClass,
45
- isSameOutRef,
46
- mkAssetsOf,
47
- } from '@3rd-eye-labs/cardano-offchain-common';
48
- import { repsertWithReadonlyArr } from '../../utils/array-utils';
49
- import { match, P } from 'ts-pattern';
50
- import {
51
- fromSysParamsCredential,
52
- SystemParams,
53
- } from '../../types/system-params';
54
- import { mkStabilityPoolValidatorFromSP } from './scripts';
55
-
56
- export const BASE_MAX_TX_FEE = 1_250_000n;
57
-
58
- export const MAX_E2S2S_ENTRIES_COUNT = 5;
59
- const newScaleMultiplier = 1_000_000_000n;
60
-
61
- export const initSumVal: SPInteger = { value: 0n };
62
-
63
- export const initSpState: StateSnapshot = {
64
- productVal: mkSPInteger(1n),
65
- depositVal: { value: 0n },
66
- epoch: 0n,
67
- scale: 0n,
68
- };
69
-
70
- export function mkStabilityPoolAddr(
71
- lucid: LucidEvolution,
72
- sysParams: SystemParams,
73
- ): Address {
74
- return credentialToAddress(
75
- lucid.config().network!,
76
- {
77
- hash: validatorToScriptHash(
78
- mkStabilityPoolValidatorFromSP(sysParams.stabilityPoolParams),
79
- ),
80
- type: 'Script',
81
- },
82
- sysParams.stabilityPoolParams.stakeCredential != null
83
- ? fromSysParamsCredential(sysParams.stabilityPoolParams.stakeCredential)
84
- : undefined,
85
- );
86
- }
87
-
88
- export function isSameEpochToScaleKey(
89
- a: EpochToScaleKey,
90
- b: EpochToScaleKey,
91
- ): boolean {
92
- return a.epoch === b.epoch && a.scale === b.scale;
93
- }
94
-
95
- type StabilityPoolListIdx = {
96
- spListIdx: number;
97
- sumSnapshot: readonly [EpochToScaleKey, SumSnapshot];
98
- };
99
- type SnapshotIdx = {
100
- snapshotUtxo: UTxO;
101
- snapshotDatum: SnapshotEpochToScaleToSumContent;
102
- snapshotListIdx: number;
103
- sumSnapshot: readonly [EpochToScaleKey, SumSnapshot];
104
- };
105
- export type FindE2S2SIdxResult = StabilityPoolListIdx | SnapshotIdx;
106
-
107
- function findE2s2sIdx(
108
- expectedKey: EpochToScaleKey,
109
- collateralAsset: AssetClass,
110
- spAssetState: AssetSnapshot,
111
- e2s2sUtxos: [UTxO, SnapshotEpochToScaleToSumContent][],
112
- ): O.Option<FindE2S2SIdxResult> {
113
- return F.pipe(
114
- // Try to find the s1 in sp e2s2s.
115
- F.pipe(
116
- spAssetState.epoch2scale2sum,
117
- RA.findIndex(([key, _]) => isSameEpochToScaleKey(key, expectedKey)),
118
- ),
119
- O.match<number, O.Option<FindE2S2SIdxResult>>(
120
- // When such e2sKey non existent in sp e2s2s, find it in e2s2s snapshots
121
- () =>
122
- F.pipe(
123
- e2s2sUtxos,
124
- A.findFirst(
125
- ([_, datum]) =>
126
- isSameAssetClass(datum.collateralAsset, collateralAsset) &&
127
- F.pipe(
128
- datum.snapshot,
129
- RA.exists(([key, _]) =>
130
- isSameEpochToScaleKey(expectedKey, key),
131
- ),
132
- ),
133
- ),
134
- O.map((res) => {
135
- const listIdx = F.pipe(
136
- res[1].snapshot,
137
- RA.findIndex(([key, _]) =>
138
- isSameEpochToScaleKey(key, expectedKey),
139
- ),
140
- O.getOrElse<number>(() => {
141
- throw new Error(
142
- 'It was supposed to be there. Some logic error.',
143
- );
144
- }),
145
- );
146
-
147
- return {
148
- snapshotUtxo: res[0],
149
- snapshotDatum: res[1],
150
- snapshotListIdx: listIdx,
151
- sumSnapshot: res[1].snapshot[listIdx],
152
- } satisfies SnapshotIdx;
153
- }),
154
- ),
155
- (poolIdx) =>
156
- O.some({
157
- spListIdx: poolIdx,
158
- sumSnapshot: spAssetState.epoch2scale2sum[poolIdx],
159
- } satisfies StabilityPoolListIdx),
160
- ),
161
- );
162
- }
163
-
164
- export async function findRelevantE2s2sIdxs(
165
- lucid: LucidEvolution,
166
- stabilityPool: StabilityPoolContent,
167
- accountState: StateSnapshot,
168
- allSnapshotsOutRefs: OutRef[],
169
- ): Promise<[FindE2S2SIdxResult, O.Option<FindE2S2SIdxResult>][]> {
170
- const e2s2sUtxos = (await lucid.utxosByOutRef(allSnapshotsOutRefs))
171
- .map((utxo) => {
172
- return [
173
- utxo,
174
- parseSnapshotEpochToScaleToSumDatumOrThrow(getInlineDatumOrThrow(utxo)),
175
- ] satisfies [UTxO, SnapshotEpochToScaleToSumContent];
176
- })
177
- .filter(([_, d]) => toHex(d.iasset) === toHex(stabilityPool.iasset));
178
-
179
- const s1E2sKey: EpochToScaleKey = {
180
- epoch: accountState.epoch,
181
- scale: accountState.scale,
182
- };
183
- const s2E2sKey: EpochToScaleKey = {
184
- epoch: accountState.epoch,
185
- scale: accountState.scale + 1n,
186
- };
187
-
188
- return stabilityPool.assetStates.map(([collateralAsset, spAssetState]) => {
189
- const s1Res = F.pipe(
190
- findE2s2sIdx(s1E2sKey, collateralAsset, spAssetState, e2s2sUtxos),
191
- // When it's non-existent, we need to find proof it doesn't exist.
192
- O.getOrElse(() =>
193
- F.pipe(
194
- e2s2sUtxos,
195
- A.findFirst(
196
- ([_, datum]) =>
197
- isSameAssetClass(datum.collateralAsset, collateralAsset) &&
198
- F.pipe(
199
- datum.snapshot,
200
- RA.exists(([_, val]) => val.isFirstSnapshot),
201
- ),
202
- ),
203
- O.match<[UTxO, SnapshotEpochToScaleToSumContent], FindE2S2SIdxResult>(
204
- // Try to find the proof in pool's list.
205
- () =>
206
- F.pipe(
207
- spAssetState.epoch2scale2sum,
208
- RA.findIndex(([_, dat]) => dat.isFirstSnapshot),
209
- O.match(
210
- () => {
211
- throw new Error(
212
- "Couldn't find relevant proof for s1 non-existence.",
213
- );
214
- },
215
- (poolIdx) =>
216
- ({
217
- spListIdx: poolIdx,
218
- sumSnapshot: spAssetState.epoch2scale2sum[poolIdx],
219
- }) satisfies StabilityPoolListIdx,
220
- ),
221
- ),
222
- (snapshotProof) => {
223
- const listIdx = F.pipe(
224
- snapshotProof[1].snapshot,
225
- RA.findIndex(([_, val]) => val.isFirstSnapshot),
226
- O.getOrElse<number>(() => {
227
- throw new Error(
228
- 'It was supposed to be there. Some logic error.',
229
- );
230
- }),
231
- );
232
-
233
- return {
234
- snapshotUtxo: snapshotProof[0],
235
- snapshotDatum: snapshotProof[1],
236
- snapshotListIdx: listIdx,
237
- sumSnapshot: snapshotProof[1].snapshot[listIdx],
238
- } satisfies SnapshotIdx;
239
- },
240
- ),
241
- ),
242
- ),
243
- );
244
-
245
- const s2Res = findE2s2sIdx(
246
- s2E2sKey,
247
- collateralAsset,
248
- spAssetState,
249
- e2s2sUtxos,
250
- );
251
-
252
- // Is actual s1 index?
253
- if (isSameEpochToScaleKey(s1Res.sumSnapshot[0], s1E2sKey)) {
254
- return [
255
- s1Res,
256
- F.pipe(
257
- s2Res,
258
- O.match(
259
- () => {
260
- // When s1 is not just a proof and is last in epoch, it proves s2 non-existant.
261
- if (s1Res.sumSnapshot[1].isLastInEpoch) {
262
- return O.none;
263
- } else {
264
- throw new Error('Expected s2 to be existent.');
265
- }
266
- },
267
- (res) => O.some(res),
268
- ),
269
- ),
270
- ];
271
- } else {
272
- // When s1 is just a proof.
273
- return [
274
- s1Res,
275
- F.pipe(
276
- s2Res,
277
- O.match(
278
- () => {
279
- // When the non-existance proof works for s2 as well
280
- if (
281
- s1Res.sumSnapshot[1].isFirstSnapshot &&
282
- (s1Res.sumSnapshot[0].epoch > s2E2sKey.epoch ||
283
- (s1Res.sumSnapshot[0].epoch === s2E2sKey.epoch &&
284
- s1Res.sumSnapshot[0].scale > s2E2sKey.scale))
285
- ) {
286
- return O.none;
287
- }
288
-
289
- throw new Error("S1 proof doesn't work for s2.");
290
- },
291
- // s2 exists.
292
- (res) => O.some(res),
293
- ),
294
- ),
295
- ];
296
- }
297
- });
298
- }
299
-
300
- export function createProcessRequestAccountRedeemer(
301
- e2s2sIdxs: [FindE2S2SIdxResult, O.Option<FindE2S2SIdxResult>][],
302
- otherRefInputs: UTxO[],
303
- currentTime: bigint,
304
- ): {
305
- e2s2sRefInputs: UTxO[];
306
- mkProcessRequestAccountRedeemerContent: (
307
- poolInputIdx: bigint,
308
- accountInputIdx: bigint,
309
- ) => ProcessRequestAccountContent;
310
- } {
311
- const allE2s2sSnapshotRefInputs = F.pipe(
312
- e2s2sIdxs,
313
- A.flatMap(([s1, s2]) => {
314
- const s1RefInput = match(s1)
315
- .with({ snapshotUtxo: P.select() }, (utxo) => O.some(utxo))
316
- .otherwise(() => O.none);
317
-
318
- const s2RefInput = F.pipe(
319
- s2,
320
- O.match(
321
- () => [],
322
- (s) =>
323
- match(s)
324
- .with({ snapshotUtxo: P.select() }, (utxo) =>
325
- F.pipe(
326
- s1RefInput,
327
- O.match(
328
- () => [utxo],
329
- // when s1 ref input is same as s2 ref input, don't reference it again
330
- (s1In) => (isSameOutRef(s1In, utxo) ? [] : [utxo]),
331
- ),
332
- ),
333
- )
334
- .otherwise(() => []),
335
- ),
336
- );
337
-
338
- return [...F.pipe([s1RefInput], A.compact), ...s2RefInput];
339
- }),
340
- );
341
-
342
- const e2s2sInputsIndices = getInputIndices(allE2s2sSnapshotRefInputs, [
343
- ...otherRefInputs,
344
- ...allE2s2sSnapshotRefInputs,
345
- ]);
346
-
347
- const createE2s2sIdx = (s: FindE2S2SIdxResult): E2S2SIndex =>
348
- match(s)
349
- .returnType<E2S2SIndex>()
350
- .with({ spListIdx: P.select() }, (spListIdx) => ({
351
- StabilityPoolListIdx: BigInt(spListIdx),
352
- }))
353
- .with({ snapshotUtxo: P.any }, (obj) => {
354
- const idxForIdx = F.pipe(
355
- allE2s2sSnapshotRefInputs,
356
- A.findIndex((input) => isSameOutRef(input, obj.snapshotUtxo)),
357
- O.getOrElse<number>(() => {
358
- throw new Error('Expected to find the index.');
359
- }),
360
- );
361
-
362
- return {
363
- RefInputIdx: {
364
- refInputIdx: e2s2sInputsIndices[idxForIdx],
365
- snapshotListIdx: BigInt(obj.snapshotListIdx),
366
- },
367
- };
368
- })
369
- .exhaustive();
370
-
371
- return {
372
- e2s2sRefInputs: allE2s2sSnapshotRefInputs,
373
- mkProcessRequestAccountRedeemerContent: (
374
- poolInputIdx: bigint,
375
- accountInputIdx: bigint,
376
- ) => ({
377
- poolInputIdx: poolInputIdx,
378
- accountInputIdx: accountInputIdx,
379
- e2s2sIdxs: F.pipe(
380
- e2s2sIdxs,
381
- A.reduce<
382
- [FindE2S2SIdxResult, O.Option<FindE2S2SIdxResult>],
383
- E2S2SIndicesPerAsset
384
- >([], (acc, [s1, s2]) => {
385
- return [
386
- ...acc,
387
- [
388
- createE2s2sIdx(s1),
389
- F.pipe(
390
- s2,
391
- O.match(
392
- () => null,
393
- (s) => createE2s2sIdx(s),
394
- ),
395
- ),
396
- ],
397
- ];
398
- }),
399
- ),
400
- currentTime: currentTime,
401
- }),
402
- };
403
- }
404
-
405
- function calculateReward(
406
- s1: SPInteger,
407
- s2: SPInteger,
408
- accountSumVal: SPInteger,
409
- accountState: StateSnapshot,
410
- ): bigint {
411
- const a1 = spSub(s1, accountSumVal);
412
- const a2 = spDiv(spSub(s2, s1), mkSPInteger(newScaleMultiplier));
413
-
414
- return F.pipe(
415
- spDiv(
416
- spMul(spAdd(a1, a2), accountState.depositVal),
417
- accountState.productVal,
418
- ),
419
- fromSPInteger,
420
- );
421
- }
422
-
423
- function getE2s2sEntry(
424
- idx: FindE2S2SIdxResult,
425
- assetState: AssetSnapshot,
426
- ): EpochToScaleToSumEntry {
427
- return match(idx)
428
- .returnType<EpochToScaleToSumEntry>()
429
- .with(
430
- { spListIdx: P.select() },
431
- (spIdx) => assetState.epoch2scale2sum[spIdx],
432
- )
433
- .with(
434
- { snapshotUtxo: P.any },
435
- (obj) => obj.snapshotDatum.snapshot[obj.snapshotListIdx],
436
- )
437
- .exhaustive();
438
- }
439
-
440
- /**
441
- * Sp account rewards per collateral asset.
442
- */
443
- export function rewardsPerAsset(
444
- poolAssetStates: readonly AssetState[],
445
- e2s2sIdxs: [FindE2S2SIdxResult, O.Option<FindE2S2SIdxResult>][],
446
- accountAssetSums: readonly (readonly [AssetClass, SPInteger])[],
447
- accountState: StateSnapshot,
448
- ): [AssetClass, bigint][] {
449
- const expectedS1Key: EpochToScaleKey = {
450
- epoch: accountState.epoch,
451
- scale: accountState.scale,
452
- };
453
-
454
- return F.pipe(
455
- RA.zip(e2s2sIdxs)(poolAssetStates),
456
- RA.reduce<
457
- readonly [AssetState, [FindE2S2SIdxResult, O.Option<FindE2S2SIdxResult>]],
458
- [AssetClass, bigint][]
459
- >([], (acc, [[poolAsset, poolAssetState], [s1Idx, s2Idx]]) => {
460
- const s1Res = getE2s2sEntry(s1Idx, poolAssetState);
461
-
462
- const s1 = isSameEpochToScaleKey(s1Res[0], expectedS1Key)
463
- ? s1Res[1].sumVal
464
- : initSumVal;
465
-
466
- const s2 = F.pipe(
467
- s2Idx,
468
- O.match(
469
- () => s1,
470
- (s2Res) => s2Res.sumSnapshot[1].sumVal,
471
- ),
472
- );
473
-
474
- const reward = calculateReward(
475
- s1,
476
- s2,
477
- F.pipe(
478
- accountAssetSums,
479
- RA.findFirst(([accountAsset, _]) =>
480
- isSameAssetClass(accountAsset, poolAsset),
481
- ),
482
- O.match(
483
- // When account doesn't have this asset in snapshots
484
- () => initSumVal,
485
- (accountSumVal) => accountSumVal[1],
486
- ),
487
- ),
488
- accountState,
489
- );
490
-
491
- return [[poolAsset, reward], ...acc];
492
- }),
493
- );
494
- }
495
-
496
- export function getUpdatedAccountDeposit(
497
- poolState: StateSnapshot,
498
- accountState: StateSnapshot,
499
- ): SPInteger {
500
- if (poolState.epoch > accountState.epoch) {
501
- return mkSPInteger(0n);
502
- } else if (poolState.scale - accountState.scale > 1) {
503
- return mkSPInteger(0n);
504
- } else if (poolState.scale > accountState.scale) {
505
- return spDiv(spMul(accountState.depositVal, poolState.productVal), {
506
- value: accountState.productVal.value * newScaleMultiplier,
507
- });
508
- } else {
509
- return spDiv(
510
- spMul(accountState.depositVal, poolState.productVal),
511
- accountState.productVal,
512
- );
513
- }
514
- }
515
-
516
- export function updateAccount(
517
- pool: StabilityPoolContent,
518
- account: AccountContent,
519
- e2s2sIdxs: [FindE2S2SIdxResult, O.Option<FindE2S2SIdxResult>][],
520
- ): {
521
- updatedAccountContent: AccountContent;
522
- reward: Assets;
523
- } {
524
- const accountState = account.state;
525
- const fund = getUpdatedAccountDeposit(pool.state, accountState);
526
-
527
- const rewards = rewardsPerAsset(
528
- pool.assetStates,
529
- e2s2sIdxs,
530
- account.assetSums,
531
- accountState,
532
- );
533
-
534
- const newDepositVal =
535
- fund.value <
536
- spDiv(accountState.depositVal, mkSPInteger(1_000_000_000n)).value
537
- ? mkSPInteger(0n)
538
- : fund;
539
-
540
- return {
541
- updatedAccountContent: {
542
- ...account,
543
- state: { ...pool.state, depositVal: newDepositVal },
544
- assetSums: F.pipe(
545
- pool.assetStates,
546
- RA.map(([key, assetState]) => [key, assetState.currentSumVal]),
547
- ),
548
- },
549
- reward: F.pipe(
550
- rewards,
551
- A.reduce<[AssetClass, bigint], Assets>({}, (acc, [asset, amt]) =>
552
- addAssets(acc, mkAssetsOf(asset, amt)),
553
- ),
554
- ),
555
- };
556
- }
557
- export function liquidationHelper(
558
- poolContent: StabilityPoolContent,
559
- collateralAsset: AssetClass,
560
- iassetBurnAmt: bigint,
561
- /**
562
- * The collateral absorbed
563
- */
564
- reward: bigint,
565
- ): StabilityPoolContent {
566
- const lossPerUnitStaked = spDiv(
567
- mkSPInteger(iassetBurnAmt),
568
- poolContent.state.depositVal,
569
- );
570
-
571
- const productFactor = spSub(mkSPInteger(1n), lossPerUnitStaked);
572
-
573
- const isScaleIncrease =
574
- spMul(poolContent.state.productVal, productFactor).value <
575
- newScaleMultiplier;
576
-
577
- const newSnapshotP = spMul(
578
- {
579
- value:
580
- poolContent.state.productVal.value *
581
- (isScaleIncrease ? newScaleMultiplier : 1n),
582
- },
583
- productFactor,
584
- );
585
-
586
- const currentS = F.pipe(
587
- poolContent.assetStates,
588
- RA.findFirstMap(([ac, assetSnap]) =>
589
- isSameAssetClass(ac, collateralAsset)
590
- ? O.some(assetSnap.currentSumVal)
591
- : O.none,
592
- ),
593
- O.getOrElse(() => initSumVal),
594
- );
595
-
596
- const newSnapshotS = spAdd(
597
- currentS,
598
- spDiv(
599
- spMul(mkSPInteger(reward), poolContent.state.productVal),
600
- poolContent.state.depositVal,
601
- ),
602
- );
603
-
604
- const isEpochIncrease = newSnapshotP.value <= 0;
605
-
606
- const newState: StateSnapshot = isEpochIncrease
607
- ? { ...initSpState, epoch: poolContent.state.epoch + 1n }
608
- : {
609
- productVal: newSnapshotP,
610
- depositVal: spSub(
611
- poolContent.state.depositVal,
612
- mkSPInteger(iassetBurnAmt),
613
- ),
614
- epoch: poolContent.state.epoch,
615
- scale: poolContent.state.scale + (isScaleIncrease ? 1n : 0n),
616
- };
617
-
618
- const currentE2S2SKey: EpochToScaleKey = {
619
- epoch: poolContent.state.epoch,
620
- scale: poolContent.state.scale,
621
- };
622
-
623
- const newCollateralAssetSumVal = isEpochIncrease ? initSumVal : newSnapshotS;
624
-
625
- const newAssetStates = (() => {
626
- const updatedAssetStates = F.pipe(
627
- poolContent.assetStates,
628
- repsertWithReadonlyArr<AssetClass, AssetSnapshot>(
629
- (key) => isSameAssetClass(key, collateralAsset),
630
- (assetSnap) => ({
631
- currentSumVal: newCollateralAssetSumVal,
632
- epoch2scale2sum: F.pipe(
633
- assetSnap.epoch2scale2sum,
634
- RA.modifyAt(0, ([key, val]) => [
635
- key,
636
- { ...val, sumVal: newSnapshotS } satisfies SumSnapshot,
637
- ]),
638
- O.getOrElse<readonly EpochToScaleToSumEntry[]>(() => {
639
- throw new Error('There has to be first entry');
640
- }),
641
- ),
642
- }),
643
- () => ({
644
- currentSumVal: newCollateralAssetSumVal,
645
- epoch2scale2sum: [
646
- [
647
- currentE2S2SKey,
648
- {
649
- sumVal: newSnapshotS,
650
- isFirstSnapshot: true,
651
- isLastInEpoch: true,
652
- },
653
- ],
654
- ],
655
- }),
656
- () => collateralAsset,
657
- ),
658
- );
659
-
660
- if (isEpochIncrease) {
661
- return F.pipe(
662
- updatedAssetStates,
663
- RA.map<AssetState, AssetState>(([key, assetSnap]) => [
664
- key,
665
- {
666
- currentSumVal: initSumVal,
667
- epoch2scale2sum: [
668
- [
669
- {
670
- epoch: poolContent.state.epoch + 1n,
671
- scale: 0n,
672
- },
673
- {
674
- sumVal: initSumVal,
675
- isLastInEpoch: true,
676
- isFirstSnapshot: false,
677
- },
678
- ],
679
- ...assetSnap.epoch2scale2sum,
680
- ],
681
- },
682
- ]),
683
- );
684
- } else if (isScaleIncrease) {
685
- return F.pipe(
686
- updatedAssetStates,
687
- RA.map<AssetState, AssetState>(([key, assetSnap]) => [
688
- key,
689
- {
690
- ...assetSnap,
691
- epoch2scale2sum: match(assetSnap.epoch2scale2sum)
692
- .returnType<readonly EpochToScaleToSumEntry[]>()
693
- .with([[P.any, P.any], ...P.array()], ([[key, val], ...rest]) => {
694
- const newScaleEntry: EpochToScaleToSumEntry = [
695
- {
696
- epoch: poolContent.state.epoch,
697
- scale: poolContent.state.scale + 1n,
698
- },
699
- {
700
- sumVal: val.sumVal,
701
- isLastInEpoch: true,
702
- isFirstSnapshot: false,
703
- },
704
- ];
705
-
706
- return [
707
- newScaleEntry,
708
- [key, { ...val, isLastInEpoch: false } satisfies SumSnapshot],
709
- ...rest,
710
- ];
711
- })
712
- .otherwise(() => {
713
- throw new Error('There has to be at least 1 entry');
714
- }),
715
- },
716
- ]),
717
- );
718
- } else {
719
- return updatedAssetStates;
720
- }
721
- })();
722
-
723
- return {
724
- ...poolContent,
725
- assetStates: newAssetStates,
726
- state: newState,
727
- };
728
- }
729
-
730
- export function updatePoolStateWhenWithdrawalFee(
731
- withdrawalFeeAmt: bigint,
732
- updatedPoolState: StateSnapshot,
733
- ): StateSnapshot {
734
- if (withdrawalFeeAmt === 0n) {
735
- return updatedPoolState;
736
- } else {
737
- const withdrawalFeeSpInt = mkSPInteger(withdrawalFeeAmt);
738
- const newDepositVal = spAdd(
739
- updatedPoolState.depositVal,
740
- withdrawalFeeSpInt,
741
- );
742
-
743
- const productFactor = spAdd(
744
- mkSPInteger(1n),
745
- spDiv(withdrawalFeeSpInt, updatedPoolState.depositVal),
746
- );
747
-
748
- const newProductVal = spMul(updatedPoolState.productVal, productFactor);
749
-
750
- return {
751
- ...updatedPoolState,
752
- productVal: newProductVal,
753
- depositVal: newDepositVal,
754
- };
755
- }
756
- }
757
-
758
- export function partitionEpochToScaleToSums(
759
- spContent: StabilityPoolContent,
760
- ): readonly [
761
- readonly SnapshotEpochToScaleToSumContent[],
762
- readonly AssetState[],
763
- ] {
764
- const res = F.pipe(
765
- spContent.assetStates,
766
- RA.map<AssetState, [SnapshotEpochToScaleToSumContent[], AssetState]>(
767
- ([collateralAsset, assetState]) => {
768
- if (assetState.epoch2scale2sum.length >= MAX_E2S2S_ENTRIES_COUNT) {
769
- const { right: remaining, left: snapshotMapItems } = F.pipe(
770
- assetState.epoch2scale2sum,
771
- RA.partition(
772
- ([e2sKey, _]) =>
773
- e2sKey.epoch === spContent.state.epoch &&
774
- e2sKey.scale === spContent.state.scale,
775
- ),
776
- );
777
-
778
- return [
779
- [
780
- {
781
- iasset: spContent.iasset,
782
- collateralAsset: collateralAsset,
783
- snapshot: snapshotMapItems,
784
- },
785
- ],
786
- [collateralAsset, { ...assetState, epoch2scale2sum: remaining }],
787
- ];
788
- } else {
789
- return [[], [collateralAsset, assetState]];
790
- }
791
- },
792
- ),
793
- );
794
-
795
- const [newSnapshots, newAssetStates] = RA.unzip(res);
796
-
797
- return [RA.flatten(newSnapshots), newAssetStates];
798
- }