@indigo-labs/indigo-sdk 0.2.42 → 0.3.1

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 (202) hide show
  1. package/.github/workflows/ci.yml +4 -2
  2. package/README.md +88 -15
  3. package/dist/index.d.mts +3012 -2194
  4. package/dist/index.d.ts +3012 -2194
  5. package/dist/index.js +9849 -6198
  6. package/dist/index.mjs +8733 -4933
  7. package/package.json +14 -3
  8. package/src/contracts/cdp/helpers.ts +68 -72
  9. package/src/contracts/cdp/scripts.ts +50 -13
  10. package/src/contracts/cdp/transactions.ts +841 -546
  11. package/src/contracts/cdp/types-new.ts +256 -0
  12. package/src/contracts/cdp/types.ts +26 -144
  13. package/src/contracts/cdp-creator/scripts.ts +15 -9
  14. package/src/contracts/cdp-creator/types-new.ts +50 -0
  15. package/src/contracts/cdp-creator/types.ts +5 -31
  16. package/src/contracts/collector/scripts.ts +1 -1
  17. package/src/contracts/collector/transactions.ts +23 -13
  18. package/src/contracts/collector/types-new.ts +17 -0
  19. package/src/contracts/execute/scripts.ts +19 -10
  20. package/src/contracts/execute/types-new.ts +44 -0
  21. package/src/contracts/execute/types.ts +5 -38
  22. package/src/contracts/gov/helpers.ts +187 -51
  23. package/src/contracts/gov/scripts.ts +17 -10
  24. package/src/contracts/gov/transactions.ts +599 -271
  25. package/src/contracts/gov/types-new.ts +253 -100
  26. package/src/contracts/gov/types.ts +4 -71
  27. package/src/contracts/iasset/helpers.ts +172 -0
  28. package/src/contracts/iasset/scripts.ts +38 -0
  29. package/src/contracts/iasset/types.ts +154 -0
  30. package/src/contracts/initialize/actions.ts +768 -0
  31. package/src/contracts/initialize/helpers.ts +611 -36
  32. package/src/contracts/initialize/types.ts +102 -28
  33. package/src/contracts/interest-collection/helpers.ts +19 -0
  34. package/src/contracts/interest-collection/scripts.ts +44 -0
  35. package/src/contracts/interest-collection/transactions.ts +436 -0
  36. package/src/contracts/interest-collection/types-new.ts +50 -0
  37. package/src/contracts/interest-collection/types.ts +26 -0
  38. package/src/contracts/interest-oracle/helpers.ts +2 -30
  39. package/src/contracts/interest-oracle/scripts.ts +1 -1
  40. package/src/contracts/interest-oracle/transactions.ts +21 -16
  41. package/src/contracts/interest-oracle/types-new.ts +32 -0
  42. package/src/contracts/interest-oracle/types.ts +1 -40
  43. package/src/contracts/one-shot/transactions.ts +1 -2
  44. package/src/contracts/poll/helpers.ts +5 -23
  45. package/src/contracts/poll/scripts.ts +12 -13
  46. package/src/contracts/poll/types-poll-manager.ts +1 -19
  47. package/src/contracts/poll/types-poll-new.ts +170 -0
  48. package/src/contracts/poll/types-poll-shard.ts +2 -24
  49. package/src/contracts/price-oracle/helpers.ts +1 -4
  50. package/src/contracts/price-oracle/scripts.ts +3 -8
  51. package/src/contracts/price-oracle/transactions.ts +32 -25
  52. package/src/contracts/price-oracle/types-new.ts +50 -0
  53. package/src/contracts/price-oracle/types.ts +2 -36
  54. package/src/contracts/pyth-feed/helpers.ts +58 -0
  55. package/src/contracts/pyth-feed/scripts.ts +15 -0
  56. package/src/contracts/pyth-feed/types.ts +181 -0
  57. package/src/contracts/rob/helpers.ts +405 -0
  58. package/src/contracts/rob/scripts.ts +35 -0
  59. package/src/contracts/rob/transactions.ts +410 -0
  60. package/src/contracts/rob/types-new.ts +128 -0
  61. package/src/contracts/rob/types.ts +16 -0
  62. package/src/contracts/rob-leverage/helpers.ts +424 -0
  63. package/src/contracts/{leverage → rob-leverage}/transactions.ts +68 -48
  64. package/src/contracts/stability-pool/helpers.ts +714 -230
  65. package/src/contracts/stability-pool/scripts.ts +20 -15
  66. package/src/contracts/stability-pool/transactions.ts +628 -496
  67. package/src/contracts/stability-pool/types-new.ts +247 -100
  68. package/src/contracts/stability-pool/types.ts +5 -22
  69. package/src/contracts/stableswap/helpers.ts +22 -0
  70. package/src/contracts/stableswap/scripts.ts +37 -0
  71. package/src/contracts/stableswap/transactions.ts +647 -0
  72. package/src/contracts/stableswap/types-new.ts +131 -0
  73. package/src/contracts/stableswap/types.ts +17 -0
  74. package/src/contracts/staking/helpers.ts +49 -34
  75. package/src/contracts/staking/scripts.ts +1 -1
  76. package/src/contracts/staking/transactions.ts +85 -130
  77. package/src/contracts/staking/types-new.ts +60 -28
  78. package/src/contracts/staking/types.ts +1 -28
  79. package/src/contracts/treasury/helpers.ts +21 -0
  80. package/src/contracts/treasury/scripts.ts +16 -26
  81. package/src/contracts/treasury/transactions.ts +256 -27
  82. package/src/contracts/treasury/types-new.ts +69 -0
  83. package/src/contracts/treasury/types.ts +2 -43
  84. package/src/contracts/version-registry/scripts.ts +2 -2
  85. package/src/contracts/version-registry/types-new.ts +6 -7
  86. package/src/index.ts +37 -20
  87. package/src/scripts/auth-token-policy.ts +3 -2
  88. package/src/scripts/iasset-policy.ts +3 -2
  89. package/src/types/evolution-schema-options.ts +3 -3
  90. package/src/types/generic.ts +17 -89
  91. package/src/types/multisig.ts +48 -0
  92. package/src/types/on-chain-decimal.ts +14 -7
  93. package/src/types/rational.ts +61 -0
  94. package/src/types/system-params.ts +237 -41
  95. package/src/utils/array-utils.ts +70 -1
  96. package/src/utils/bigint-utils.ts +12 -0
  97. package/src/utils/indigo-helpers.ts +8 -10
  98. package/src/utils/lucid-utils.ts +47 -40
  99. package/src/utils/oracle-helpers.ts +62 -0
  100. package/src/utils/pyth/decode.ts +223 -0
  101. package/src/utils/pyth/encode.ts +262 -0
  102. package/src/utils/pyth/index.ts +14 -0
  103. package/src/utils/pyth/types.ts +87 -0
  104. package/src/validators/always-succeed-validator.ts +6 -0
  105. package/src/validators/cdp-creator-validator.ts +2 -2
  106. package/src/validators/cdp-redeem-validator.ts +7 -0
  107. package/src/validators/cdp-validator.ts +2 -2
  108. package/src/validators/collector-validator.ts +2 -2
  109. package/src/validators/execute-validator.ts +2 -2
  110. package/src/validators/governance-validator.ts +2 -2
  111. package/src/validators/iasset-validator.ts +7 -0
  112. package/src/validators/interest-collection-validator.ts +7 -0
  113. package/src/validators/interest-oracle-validator.ts +2 -2
  114. package/src/validators/poll-manager-validator.ts +2 -2
  115. package/src/validators/poll-shard-validator.ts +2 -2
  116. package/src/validators/price-oracle-validator.ts +7 -0
  117. package/src/validators/pyth-feed-validator.ts +7 -0
  118. package/src/validators/rob-validator.ts +7 -0
  119. package/src/validators/stability-pool-validator.ts +2 -2
  120. package/src/validators/stableswap-validator.ts +7 -0
  121. package/src/validators/staking-validator.ts +2 -2
  122. package/src/validators/treasury-validator.ts +2 -2
  123. package/src/validators/version-record-policy.ts +2 -2
  124. package/src/validators/version-registry-validator.ts +2 -2
  125. package/tests/always-succeed/script.ts +7 -0
  126. package/tests/bigint-utils.test.ts +41 -0
  127. package/tests/cdp/actions.ts +610 -0
  128. package/tests/cdp/cdp-helpers.ts +55 -0
  129. package/tests/cdp/cdp-queries.ts +440 -0
  130. package/tests/cdp/cdp.test.ts +6087 -0
  131. package/tests/cdp/transactions-mutated.ts +1729 -0
  132. package/tests/data/system-params.json +177 -34
  133. package/tests/datums.test.ts +209 -210
  134. package/tests/endpoints/initialize.ts +68 -0
  135. package/tests/endpoints/interest-collector.ts +37 -0
  136. package/tests/endpoints/treasury.ts +70 -0
  137. package/tests/gov/actions.ts +406 -0
  138. package/tests/gov/gov.test.ts +4450 -0
  139. package/tests/{queries → gov}/governance-queries.ts +6 -3
  140. package/tests/hash-checks.test.ts +38 -11
  141. package/tests/indigo-test-helpers.ts +100 -0
  142. package/tests/initialize.test.ts +61 -9
  143. package/tests/interest-collection/interest-collection.test.ts +892 -0
  144. package/tests/interest-collection/interest-collector-queries.ts +49 -0
  145. package/tests/interest-collection/transactions-mutated.ts +260 -0
  146. package/tests/interest-oracle.test.ts +43 -35
  147. package/tests/mock/assets-mock.ts +234 -23
  148. package/tests/mock/protocol-params-mock.ts +21 -0
  149. package/tests/price-oracle/actions.ts +163 -0
  150. package/tests/price-oracle/price-oracle-queries.ts +12 -0
  151. package/tests/price-oracle/price-oracle.test.ts +240 -0
  152. package/tests/price-oracle/transactions-mutated.ts +62 -0
  153. package/tests/pyth/endpoints.ts +96 -0
  154. package/tests/pyth/helpers.ts +37 -0
  155. package/tests/pyth/pyth-encoding.test.ts +376 -0
  156. package/tests/pyth/pyth-indigo.test.ts +509 -0
  157. package/tests/pyth/pyth.test.ts +300 -0
  158. package/tests/queries/execute-queries.ts +6 -5
  159. package/tests/queries/iasset-queries.ts +175 -5
  160. package/tests/queries/interest-oracle-queries.ts +4 -2
  161. package/tests/queries/poll-queries.ts +8 -9
  162. package/tests/queries/stability-pool-queries.ts +95 -48
  163. package/tests/queries/staking-queries.ts +4 -2
  164. package/tests/queries/treasury-queries.ts +80 -5
  165. package/tests/rob/actions.ts +58 -0
  166. package/tests/{lrp-leverage.test.ts → rob/rob-leverage.test.ts} +393 -296
  167. package/tests/rob/rob-queries.ts +95 -0
  168. package/tests/rob/rob.test.ts +3762 -0
  169. package/tests/rob/transactions-mutated.ts +853 -0
  170. package/tests/script-size.test.ts +240 -0
  171. package/tests/setup.ts +135 -0
  172. package/tests/stability-pool/actions.ts +220 -0
  173. package/tests/stability-pool.test.ts +6121 -667
  174. package/tests/stableswap/stableswap-actions.ts +84 -0
  175. package/tests/stableswap/stableswap-queries.ts +89 -0
  176. package/tests/stableswap/stableswap.test.ts +3891 -0
  177. package/tests/stableswap/transactions-mutated.ts +348 -0
  178. package/tests/staking.test.ts +82 -99
  179. package/tests/test-helpers.ts +58 -11
  180. package/tests/treasury.test.ts +242 -0
  181. package/tests/utils/asserts.ts +74 -0
  182. package/tests/utils/benchmark-utils.ts +81 -0
  183. package/tests/utils/index.ts +122 -4
  184. package/tsconfig.json +9 -1
  185. package/vitest.config.ts +3 -1
  186. package/src/contracts/collector/types.ts +0 -16
  187. package/src/contracts/initialize/transactions.ts +0 -891
  188. package/src/contracts/leverage/helpers.ts +0 -424
  189. package/src/contracts/lrp/helpers.ts +0 -294
  190. package/src/contracts/lrp/scripts.ts +0 -27
  191. package/src/contracts/lrp/transactions.ts +0 -250
  192. package/src/contracts/lrp/types.ts +0 -131
  193. package/src/contracts/poll/types-poll.ts +0 -88
  194. package/src/contracts/vesting/helpers.ts +0 -218
  195. package/src/utils/value-helpers.ts +0 -37
  196. package/src/validators/lrp-validator.ts +0 -7
  197. package/tests/cdp.test.ts +0 -1528
  198. package/tests/gov.test.ts +0 -2011
  199. package/tests/lrp.test.ts +0 -673
  200. package/tests/queries/cdp-queries.ts +0 -220
  201. package/tests/queries/lrp-queries.ts +0 -76
  202. package/tests/queries/price-oracle-queries.ts +0 -10
@@ -0,0 +1,410 @@
1
+ import {
2
+ LucidEvolution,
3
+ TxBuilder,
4
+ Credential,
5
+ OutRef,
6
+ addAssets,
7
+ fromHex,
8
+ toHex,
9
+ fromText,
10
+ Assets,
11
+ getInputIndices,
12
+ } from '@lucid-evolution/lucid';
13
+ import {
14
+ addrDetails,
15
+ createScriptAddress,
16
+ getInlineDatumOrThrow,
17
+ } from '../../utils/lucid-utils';
18
+ import {
19
+ readonlyArray as RA,
20
+ array as A,
21
+ function as F,
22
+ option as O,
23
+ } from 'fp-ts';
24
+ import { unzip, zip } from 'fp-ts/lib/Array';
25
+ import {
26
+ adaAssetClass,
27
+ AssetClass,
28
+ assetClassValueOf,
29
+ isSameAssetClass,
30
+ mkAssetsOf,
31
+ mkLovelacesOf,
32
+ negateAssets,
33
+ } from '@3rd-eye-labs/cardano-offchain-common';
34
+ import { matchSingle } from '../../utils/utils';
35
+ import {
36
+ RobDatum,
37
+ RobOrderType,
38
+ parseRobDatumOrThrow,
39
+ serialiseRobDatum,
40
+ serialiseRobRedeemer,
41
+ } from './types-new';
42
+ import {
43
+ parseCollateralAssetDatumOrThrow,
44
+ parseIAssetDatumOrThrow,
45
+ } from '../iasset/types';
46
+ import {
47
+ fromSystemParamsScriptRef,
48
+ SystemParams,
49
+ } from '../../types/system-params';
50
+ import {
51
+ buildRedemptionsTx,
52
+ isFullyRedeemed,
53
+ MIN_ROB_COLLATERAL_AMT as MIN_ROB_COLLATERAL_AMT,
54
+ robAmountToSpend,
55
+ } from './helpers';
56
+ import { match, P } from 'ts-pattern';
57
+ import { Rational } from '../../types/rational';
58
+ import { attachOracle } from '../iasset/helpers';
59
+ import { retrieveAdjustedPrice } from '../../utils/oracle-helpers';
60
+
61
+ export async function openRob(
62
+ assetTokenNameAscii: string,
63
+ depositAmt: bigint,
64
+ orderType: RobOrderType,
65
+ lucid: LucidEvolution,
66
+ sysParams: SystemParams,
67
+ robStakeCredential?: Credential,
68
+ ): Promise<TxBuilder> {
69
+ const network = lucid.config().network!;
70
+ const [ownPkh, _] = await addrDetails(lucid);
71
+
72
+ const newDatum: RobDatum = {
73
+ owner: fromHex(ownPkh.hash),
74
+ iasset: fromHex(fromText(assetTokenNameAscii)),
75
+ orderType: orderType,
76
+ robRefInput: {
77
+ txHash: fromHex(
78
+ '0000000000000000000000000000000000000000000000000000000000000000',
79
+ ),
80
+ outputIndex: 0n,
81
+ },
82
+ };
83
+
84
+ const depositVal = match(orderType)
85
+ .with({ BuyIAssetOrder: P.select() }, (buyContent) =>
86
+ mkAssetsOf(buyContent.collateralAsset, depositAmt),
87
+ )
88
+ .with({ SellIAssetOrder: P.any }, (_) =>
89
+ mkAssetsOf(
90
+ {
91
+ currencySymbol: fromHex(
92
+ sysParams.cdpParams.cdpAssetSymbol.unCurrencySymbol,
93
+ ),
94
+ tokenName: newDatum.iasset,
95
+ },
96
+ depositAmt,
97
+ ),
98
+ )
99
+ .exhaustive();
100
+
101
+ return lucid.newTx().pay.ToContract(
102
+ createScriptAddress(
103
+ network,
104
+ sysParams.validatorHashes.robHash,
105
+ robStakeCredential,
106
+ ),
107
+ {
108
+ kind: 'inline',
109
+ value: serialiseRobDatum(newDatum),
110
+ },
111
+ addAssets(depositVal, mkLovelacesOf(MIN_ROB_COLLATERAL_AMT)),
112
+ );
113
+ }
114
+
115
+ export async function cancelRob(
116
+ robOutRef: OutRef,
117
+ sysParams: SystemParams,
118
+ lucid: LucidEvolution,
119
+ ): Promise<TxBuilder> {
120
+ const robScriptRefUtxo = matchSingle(
121
+ await lucid.utxosByOutRef([
122
+ fromSystemParamsScriptRef(sysParams.scriptReferences.robValidatorRef),
123
+ ]),
124
+ (_) => new Error('Expected a single ROB Ref Script UTXO'),
125
+ );
126
+
127
+ const robUtxo = matchSingle(
128
+ await lucid.utxosByOutRef([robOutRef]),
129
+ (_) => new Error('Expected a single ROB UTXO.'),
130
+ );
131
+
132
+ const robDatum = parseRobDatumOrThrow(getInlineDatumOrThrow(robUtxo));
133
+
134
+ return lucid
135
+ .newTx()
136
+ .readFrom([robScriptRefUtxo])
137
+ .collectFrom([robUtxo], serialiseRobRedeemer('Cancel'))
138
+ .addSignerKey(toHex(robDatum.owner));
139
+ }
140
+
141
+ export async function redeemRob(
142
+ /**
143
+ * The tuple represents the ROB UTXO and the amount to payout for a redemption. In case of buy order,
144
+ * it's denominated in iAssets, in case of sell order, it's denominated in collateral asset.
145
+ */
146
+ redemptionRobsData: [OutRef, bigint][],
147
+ priceOracleOutRef: OutRef | undefined,
148
+ iassetOutRef: OutRef,
149
+ collateralAssetOutRef: OutRef,
150
+ lucid: LucidEvolution,
151
+ sysParams: SystemParams,
152
+ currentSlot: number,
153
+ pythMessage: string | undefined = undefined,
154
+ pythStateOutRef: OutRef | undefined = undefined,
155
+ ): Promise<TxBuilder> {
156
+ const robScriptRefUtxo = matchSingle(
157
+ await lucid.utxosByOutRef([
158
+ fromSystemParamsScriptRef(sysParams.scriptReferences.robValidatorRef),
159
+ ]),
160
+ (_) => new Error('Expected a single ROB Ref Script UTXO'),
161
+ );
162
+
163
+ const iassetUtxo = matchSingle(
164
+ await lucid.utxosByOutRef([iassetOutRef]),
165
+ (_) => new Error('Expected a single IAsset UTXO'),
166
+ );
167
+
168
+ const iassetDatum = parseIAssetDatumOrThrow(
169
+ getInlineDatumOrThrow(iassetUtxo),
170
+ );
171
+
172
+ const collateralAssetUtxo = matchSingle(
173
+ await lucid.utxosByOutRef([collateralAssetOutRef]),
174
+ (_) => new Error('Expected a single collateral asset UTXO'),
175
+ );
176
+
177
+ const collateralAssetDatum = parseCollateralAssetDatumOrThrow(
178
+ getInlineDatumOrThrow(collateralAssetUtxo),
179
+ );
180
+
181
+ const [robsToRedeemOutRefs, robRedemptionIAssetAmt] =
182
+ unzip(redemptionRobsData);
183
+
184
+ const [adjustedPrice, _] = await retrieveAdjustedPrice(
185
+ iassetDatum.assetName,
186
+ collateralAssetDatum.collateralAsset,
187
+ collateralAssetDatum.priceInfo,
188
+ collateralAssetDatum.extraDecimals,
189
+ priceOracleOutRef,
190
+ pythMessage,
191
+ sysParams.pythConfig,
192
+ lucid,
193
+ );
194
+
195
+ const redemptionRobs = await lucid
196
+ .utxosByOutRef(robsToRedeemOutRefs)
197
+ .then((val) => zip(val, robRedemptionIAssetAmt));
198
+
199
+ const allRefInputs = [robScriptRefUtxo, iassetUtxo, collateralAssetUtxo];
200
+
201
+ const tx = lucid.newTx();
202
+ const { interval, referenceInputs } = await attachOracle(
203
+ iassetDatum.assetName,
204
+ collateralAssetDatum.collateralAsset,
205
+ collateralAssetDatum.priceInfo,
206
+ priceOracleOutRef,
207
+ pythStateOutRef,
208
+ pythMessage,
209
+ sysParams.pythConfig,
210
+ sysParams.cdpParams.biasTime,
211
+ currentSlot,
212
+ lucid,
213
+ tx,
214
+ );
215
+
216
+ // Set the validity interval for the transaction
217
+ tx.validFrom(interval.validFrom).validTo(interval.validTo);
218
+
219
+ // Read from the reference inputs
220
+ allRefInputs.push(...referenceInputs);
221
+
222
+ const refInputIdxs = getInputIndices(allRefInputs, allRefInputs);
223
+
224
+ buildRedemptionsTx(
225
+ redemptionRobs,
226
+ iassetDatum.assetName,
227
+ collateralAssetDatum.collateralAsset,
228
+ adjustedPrice,
229
+ iassetDatum.redemptionReimbursementRatio,
230
+ sysParams,
231
+ tx,
232
+ 0n,
233
+ refInputIdxs[2],
234
+ refInputIdxs[1],
235
+ priceOracleOutRef !== undefined ? refInputIdxs[3] : null,
236
+ );
237
+
238
+ tx.readFrom(allRefInputs);
239
+
240
+ return tx;
241
+ }
242
+
243
+ /**
244
+ * Create Tx adjusting the ROB and claiming the received iAssets
245
+ */
246
+ export async function adjustRob(
247
+ lucid: LucidEvolution,
248
+ robOutRef: OutRef,
249
+ /**
250
+ * A positive amount increases the deposit in the ROB,
251
+ * and a negative amount takes deposit from the ROB.
252
+ */
253
+ adjustmentAmt: bigint,
254
+ newLimitPrice:
255
+ | { BuyOrder: Rational }
256
+ | { SellOrder: { newLimitPrices: [AssetClass, Rational][] } }
257
+ | undefined,
258
+ sysParams: SystemParams,
259
+ ): Promise<TxBuilder> {
260
+ const robScriptRefUtxo = matchSingle(
261
+ await lucid.utxosByOutRef([
262
+ fromSystemParamsScriptRef(sysParams.scriptReferences.robValidatorRef),
263
+ ]),
264
+ (_) => new Error('Expected a single ROB Ref Script UTXO'),
265
+ );
266
+
267
+ const robUtxo = matchSingle(
268
+ await lucid.utxosByOutRef([robOutRef]),
269
+ (_) => new Error('Expected a single ROB UTXO.'),
270
+ );
271
+
272
+ const robDatum = parseRobDatumOrThrow(getInlineDatumOrThrow(robUtxo));
273
+
274
+ // The claim case
275
+ if (adjustmentAmt === 0n && isFullyRedeemed(robUtxo, robDatum, sysParams)) {
276
+ throw new Error(
277
+ "When there's no more lovelaces to spend, use close instead of claim.",
278
+ );
279
+ }
280
+
281
+ // Negative adjust case
282
+ if (
283
+ adjustmentAmt < 0 &&
284
+ robAmountToSpend(robUtxo, robDatum, sysParams) <= -adjustmentAmt
285
+ ) {
286
+ throw new Error(
287
+ "Can't adjust negatively by more than available. Also, for adjusting by exactly the amount deposited, a close action should be used instead.",
288
+ );
289
+ }
290
+
291
+ const iassetAc: AssetClass = {
292
+ currencySymbol: fromHex(
293
+ sysParams.robParams.iassetPolicyId.unCurrencySymbol,
294
+ ),
295
+ tokenName: robDatum.iasset,
296
+ };
297
+
298
+ const [depositAsset, rewardVal] = match(robDatum.orderType)
299
+ .returnType<[AssetClass, Assets]>()
300
+ .with({ BuyIAssetOrder: P.select() }, (buyContent) => {
301
+ const reward = assetClassValueOf(robUtxo.assets, iassetAc);
302
+
303
+ return [buyContent.collateralAsset, mkAssetsOf(iassetAc, reward)];
304
+ })
305
+ .with({ SellIAssetOrder: P.select() }, (content) => {
306
+ const reward = F.pipe(
307
+ content.allowedCollateralAssets,
308
+ RA.reduce<readonly [AssetClass, Rational], Assets>(
309
+ {},
310
+ (acc, [asset, _]) => {
311
+ const amt =
312
+ assetClassValueOf(robUtxo.assets, asset) -
313
+ // in case of ADA, the min has to stay.
314
+ (isSameAssetClass(asset, adaAssetClass)
315
+ ? MIN_ROB_COLLATERAL_AMT
316
+ : 0n);
317
+
318
+ return addAssets(acc, mkAssetsOf(asset, amt));
319
+ },
320
+ ),
321
+ );
322
+
323
+ return [iassetAc, reward];
324
+ })
325
+ .exhaustive();
326
+
327
+ return lucid
328
+ .newTx()
329
+ .readFrom([robScriptRefUtxo])
330
+ .collectFrom([robUtxo], serialiseRobRedeemer('Cancel'))
331
+ .pay.ToContract(
332
+ robUtxo.address,
333
+ {
334
+ kind: 'inline',
335
+ value: serialiseRobDatum({
336
+ ...robDatum,
337
+ orderType:
338
+ newLimitPrice == null
339
+ ? robDatum.orderType
340
+ : match(robDatum.orderType)
341
+ .returnType<RobOrderType>()
342
+ .with({ BuyIAssetOrder: P.select() }, (content) => {
343
+ const newPrice = match(newLimitPrice)
344
+ .with({ BuyOrder: P.select() }, (price) => price)
345
+ .otherwise(() => {
346
+ throw new Error(
347
+ 'Must use buy order price change on buy order.',
348
+ );
349
+ });
350
+
351
+ return {
352
+ BuyIAssetOrder: { ...content, maxPrice: newPrice },
353
+ };
354
+ })
355
+ .with({ SellIAssetOrder: P.select() }, (content) => {
356
+ const newPrices = match(newLimitPrice)
357
+ .with(
358
+ { SellOrder: { newLimitPrices: P.select() } },
359
+ (prices) => prices,
360
+ )
361
+ .otherwise(() => {
362
+ throw new Error(
363
+ 'Must use sell order price change on sell order.',
364
+ );
365
+ });
366
+
367
+ return {
368
+ SellIAssetOrder: {
369
+ allowedCollateralAssets:
370
+ content.allowedCollateralAssets.map((entry) =>
371
+ F.pipe(
372
+ newPrices,
373
+ A.findFirst((newPrice) =>
374
+ isSameAssetClass(newPrice[0], entry[0]),
375
+ ),
376
+ O.match(
377
+ () => entry,
378
+ (newPrice) =>
379
+ [
380
+ entry[0],
381
+ newPrice[1],
382
+ ] satisfies typeof entry,
383
+ ),
384
+ ),
385
+ ),
386
+ },
387
+ };
388
+ })
389
+ .exhaustive(),
390
+ }),
391
+ },
392
+ addAssets(
393
+ robUtxo.assets,
394
+ mkAssetsOf(depositAsset, adjustmentAmt),
395
+ negateAssets(rewardVal),
396
+ ),
397
+ )
398
+ .addSignerKey(toHex(robDatum.owner));
399
+ }
400
+
401
+ /**
402
+ * Create Tx claiming the received iAssets.
403
+ */
404
+ export async function claimRob(
405
+ lucid: LucidEvolution,
406
+ robOutRef: OutRef,
407
+ sysParams: SystemParams,
408
+ ): Promise<TxBuilder> {
409
+ return adjustRob(lucid, robOutRef, 0n, undefined, sysParams);
410
+ }
@@ -0,0 +1,128 @@
1
+ import { TSchema, Data } from '@evolution-sdk/evolution';
2
+ import { DEFAULT_SCHEMA_OPTIONS } from '../../types/evolution-schema-options';
3
+ import {
4
+ AssetClassSchema,
5
+ OutputReferenceSchema,
6
+ } from '@3rd-eye-labs/cardano-offchain-common';
7
+ import { option as O, function as F } from 'fp-ts';
8
+ import { UTxO } from '@lucid-evolution/lucid';
9
+ import { RationalSchema } from '../../types/rational';
10
+ import { OracleIdxSchema } from '../price-oracle/types-new';
11
+
12
+ const RobOrderTypeSchema = TSchema.Union(
13
+ TSchema.Struct(
14
+ {
15
+ BuyIAssetOrder: TSchema.Struct(
16
+ {
17
+ collateralAsset: AssetClassSchema,
18
+ maxPrice: RationalSchema,
19
+ },
20
+ { flatFields: true },
21
+ ),
22
+ },
23
+ { flatInUnion: true },
24
+ ),
25
+ TSchema.Struct(
26
+ {
27
+ SellIAssetOrder: TSchema.Struct(
28
+ {
29
+ allowedCollateralAssets: TSchema.Array(
30
+ TSchema.Tuple([AssetClassSchema, RationalSchema]),
31
+ ),
32
+ },
33
+ { flatFields: true },
34
+ ),
35
+ },
36
+ { flatInUnion: true },
37
+ ),
38
+ );
39
+
40
+ export type RobOrderType = typeof RobOrderTypeSchema.Type;
41
+
42
+ const RobDatumSchema = TSchema.Struct({
43
+ owner: TSchema.ByteArray,
44
+ iasset: TSchema.ByteArray,
45
+ orderType: RobOrderTypeSchema,
46
+ robRefInput: OutputReferenceSchema,
47
+ });
48
+
49
+ export type RobDatum = typeof RobDatumSchema.Type;
50
+
51
+ const RobRedeemerSchema = TSchema.Union(
52
+ TSchema.Struct(
53
+ {
54
+ Redeem: TSchema.Struct(
55
+ {
56
+ ownInputIdx: TSchema.Integer,
57
+ collateralAssetRefInputIdx: TSchema.Integer,
58
+ iassetRefInputIdx: TSchema.Integer,
59
+ continuingOutputIdx: TSchema.Integer,
60
+ sellOrderAllowedAssetsIdx: TSchema.Integer,
61
+ priceOracleIdx: OracleIdxSchema,
62
+ },
63
+ { flatFields: true },
64
+ ),
65
+ },
66
+ { flatInUnion: true },
67
+ ),
68
+ TSchema.Literal('Cancel', { flatInUnion: true }),
69
+ TSchema.Literal('UpgradeVersion', { flatInUnion: true }),
70
+ );
71
+
72
+ export type RobRedeemer = typeof RobRedeemerSchema.Type;
73
+
74
+ export function parseRobDatum(datum: string): O.Option<RobDatum> {
75
+ try {
76
+ return O.some(
77
+ Data.withSchema(RobDatumSchema, DEFAULT_SCHEMA_OPTIONS).fromCBORHex(
78
+ datum,
79
+ ),
80
+ );
81
+ } catch (_) {
82
+ return O.none;
83
+ }
84
+ }
85
+
86
+ export function parseRobDatumOrThrow(datum: string): RobDatum {
87
+ return F.pipe(
88
+ parseRobDatum(datum),
89
+ O.match(() => {
90
+ throw new Error('Expected an ROB datum.');
91
+ }, F.identity),
92
+ );
93
+ }
94
+
95
+ export function serialiseRobDatum(d: RobDatum): string {
96
+ return Data.withSchema(RobDatumSchema, DEFAULT_SCHEMA_OPTIONS).toCBORHex(d);
97
+ }
98
+
99
+ export function serialiseRobRedeemer(r: RobRedeemer): string {
100
+ return Data.withSchema(RobRedeemerSchema, DEFAULT_SCHEMA_OPTIONS).toCBORHex(
101
+ r,
102
+ );
103
+ }
104
+
105
+ export function parseRobRedeemer(
106
+ redeemerCborHex: string,
107
+ ): O.Option<RobRedeemer> {
108
+ try {
109
+ return O.some(
110
+ Data.withSchema(RobRedeemerSchema, DEFAULT_SCHEMA_OPTIONS).fromCBORHex(
111
+ redeemerCborHex,
112
+ ),
113
+ );
114
+ } catch (_) {
115
+ return O.none;
116
+ }
117
+ }
118
+
119
+ export function parseRobRedeemerOrThrow(redeemerCborHex: string): RobRedeemer {
120
+ return F.pipe(
121
+ parseRobRedeemer(redeemerCborHex),
122
+ O.match(() => {
123
+ throw new Error('Expected an ROB redeemer.');
124
+ }, F.identity),
125
+ );
126
+ }
127
+
128
+ export type RobOutput = { datum: RobDatum; utxo: UTxO };
@@ -0,0 +1,16 @@
1
+ import { Data } from '@lucid-evolution/lucid';
2
+ import { AssetClassSchema } from '../../types/generic';
3
+
4
+ export const RobParamsSchema = Data.Object({
5
+ versionRecordToken: AssetClassSchema,
6
+ iassetAuthToken: AssetClassSchema,
7
+ collateralAssetAuthToken: AssetClassSchema,
8
+ iassetPolicyId: Data.Bytes(),
9
+ iassetValHash: Data.Bytes(),
10
+ });
11
+ export type RobParams = Data.Static<typeof RobParamsSchema>;
12
+ const RobParams = RobParamsSchema as unknown as RobParams;
13
+
14
+ export function castRobParams(params: RobParams): Data {
15
+ return Data.castTo(params, RobParams);
16
+ }