-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate-machine.ts
More file actions
2406 lines (2103 loc) · 93.9 KB
/
state-machine.ts
File metadata and controls
2406 lines (2103 loc) · 93.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { DEXOrderTransaction } from "@minswap/felis-build-tx";
import { DexVersion, OrderV2Direction, OrderV2StepType } from "@minswap/felis-dex-v2";
import { Address, Asset, getTimeFromSlotMagic, type NetworkEnvironment, Utxo } from "@minswap/felis-ledger-core";
import { Duration, Maybe, RustModule, safeFreeRustObjects } from "@minswap/felis-ledger-utils";
import { LiqwidProvider, LiqwidProviderV2 } from "@minswap/felis-lending-market";
import { CoinSelectionAlgorithm, EmulatorProvider } from "@minswap/felis-tx-builder";
import invariant from "@minswap/tiny-invariant";
import type { MarketConfig } from "../config";
import { DEFAULT_DENOMINATOR, ERROR_BUILD_TX_CODE, REPAY_MIN_VALUE_THRESHOLD_NUM } from "../constants";
import { CardanoscanProvider } from "../provider";
import type { KupoService } from "../provider/kupo";
import { logger } from "../utils";
export namespace StateMachine {
export enum PositionSide {
LONG = "LONG",
SHORT = "SHORT",
}
export enum PositionStatus {
PENDING = "PENDING",
OPEN = "OPEN",
CLOSING = "CLOSING",
CLOSED = "CLOSED",
}
export enum LongOrderType {
LONG_BUY = "LONG_BUY",
LONG_SUPPLY = "LONG_SUPPLY",
LONG_BORROW = "LONG_BORROW",
LONG_BUY_MORE = "LONG_BUY_MORE",
LONG_SELL = "LONG_SELL",
LONG_REPAY = "LONG_REPAY",
LONG_REPAY_FRACTION = "LONG_REPAY_FRACTION",
LONG_WITHDRAW_FRACTION = "LONG_WITHDRAW_FRACTION",
LONG_SELL_FREED = "LONG_SELL_FREED",
LONG_WITHDRAW = "LONG_WITHDRAW",
LONG_SELL_ALL = "LONG_SELL_ALL",
}
export enum ShortOrderType {
SHORT_SUPPLY = "SHORT_SUPPLY",
SHORT_BORROW = "SHORT_BORROW",
SHORT_SELL = "SHORT_SELL",
SHORT_BUY = "SHORT_BUY",
SHORT_REPAY = "SHORT_REPAY",
SHORT_REPAY_FRACTION = "SHORT_REPAY_FRACTION",
SHORT_WITHDRAW_FRACTION = "SHORT_WITHDRAW_FRACTION",
SHORT_BUY_FREED = "SHORT_BUY_FREED",
SHORT_WITHDRAW = "SHORT_WITHDRAW",
}
export type BuiltResult = {
txRaw: string;
txId: string;
validTo: number;
/** When set, position-service should switch from fractional to full repay flow */
redirectToFullRepay?: {
/** The order type to update (e.g. SHORT_REPAY) */
targetOrderType: string;
/** Amount in for the full repay order */
amountIn: string;
/** Asset in for the full repay order */
assetIn: string;
/** Expected output asset for the full repay order */
assetOut: string;
/** Fractional order types to delete */
deleteOrderTypes: string[];
};
};
// Common order data type for all Handle functions
export type OrderData = {
orderType: string;
assetIn: string | null;
amountIn: string | null;
assetOut: string | null;
};
// Common options for all Handle functions
export type HandleBuildTxOptions = {
order: OrderData;
marketConfig: MarketConfig;
userAddress: string;
networkEnv: NetworkEnvironment;
utxos: string[];
/** Amount to borrow (used for LONG_BORROW / SHORT_BORROW) */
amountBorrow?: string;
/** Loan transaction ID (used for SHORT_REPAY to identify the loan) */
loanTxId?: string;
/** Loan output index (used for SHORT_REPAY) */
loanOutputIndex?: number;
/** Collateral qToken amount (used for SHORT_REPAY to redeem collateral) */
collateralAmount?: string;
/** Kupo service for querying user wallet balance */
kupoService: KupoService;
};
export const handleLongBuy = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(
order.orderType === LongOrderType.LONG_BUY || order.orderType === LongOrderType.LONG_BUY_MORE,
"Invalid order type for handleLongBuy",
);
invariant(order.assetIn, "assetIn is required for LONG_BUY order");
invariant(order.amountIn, "amountIn is required for LONG_BUY order");
invariant(order.assetOut, "assetOut is required for LONG_BUY order");
const walletUtxos: Utxo[] = utxos.map((u) => Utxo.fromHex(u));
const sender = Address.fromBech32(userAddress);
const txb = DEXOrderTransaction.createBulkOrdersTx({
networkEnv,
sender,
orderOptions: [
{
lpAsset: Asset.fromString(marketConfig.ammLpAsset),
version: DexVersion.DEX_V2,
type: OrderV2StepType.SWAP_EXACT_IN,
assetIn: marketConfig.assetA,
amountIn: BigInt(order.amountIn),
minimumAmountOut: 1n,
direction: OrderV2Direction.A_TO_B,
killOnFailed: false,
isLimitOrder: false,
},
],
});
const validTo = Date.now() + Duration.newMinutes(3).milliseconds;
txb.validToUnixTime(validTo);
const { txComplete, txId } = await txb.completeUnsafeForTxChaining({
coinSelectionAlgorithm: CoinSelectionAlgorithm.SPEND_ALL,
walletUtxos,
changeAddress: sender,
provider: new EmulatorProvider(networkEnv),
});
const txRaw = txComplete.complete();
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
safeFreeRustObjects(eTx);
return {
txRaw,
txId: txId,
validTo,
};
};
export const handleLongSupply = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(order.orderType === LongOrderType.LONG_SUPPLY, "Invalid order type for handleLongSupply");
invariant(order.assetIn, "assetIn is required for LONG_SUPPLY order");
invariant(order.amountIn, "amountIn is required for LONG_SUPPLY order");
const marketId = marketConfig.longCollateralMarketId as LiqwidProvider.MarketId;
const buildTxResult = await LiqwidProvider.getSupplyTransaction({
marketId,
amount: Number(order.amountIn),
address: userAddress,
utxos,
networkEnv,
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build supply transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProvider.getLiqwidTxHash(txRaw);
return {
txRaw,
txId,
validTo: validTo.getTime(),
};
};
export const handleLongBorrow = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos, amountBorrow } = options;
invariant(order.orderType === LongOrderType.LONG_BORROW, "Invalid order type for handleLongBorrow");
invariant(order.assetIn, "assetIn is required for LONG_BORROW order");
invariant(order.amountIn, "amountIn is required for LONG_BORROW order");
invariant(amountBorrow, "amountBorrow is required for LONG_BORROW order");
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
const buildTxResult = await LiqwidProviderV2.Transactions.borrow(apiConfig, {
address: userAddress,
utxos,
marketId: marketConfig.borrowMarketIdLong as LiqwidProviderV2.MarketId,
amount: Number(amountBorrow),
collaterals: [
{
id: marketConfig.assetBQTokenTicker,
amount: Number(order.amountIn),
},
],
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build borrow transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProviderV2.getTxHash(txRaw);
return {
txRaw,
txId,
validTo: validTo.getTime(),
};
};
/**
* Build LONG_SELL or LONG_SELL_ALL transaction: Sell asset B for asset A (B_TO_A swap via DEX)
*/
export const handleLongSell = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(
order.orderType === LongOrderType.LONG_SELL || order.orderType === LongOrderType.LONG_SELL_ALL,
"Invalid order type for handleLongSell",
);
invariant(order.assetIn, "assetIn is required for LONG_SELL order");
invariant(order.amountIn, "amountIn is required for LONG_SELL order");
invariant(order.assetOut, "assetOut is required for LONG_SELL order");
const walletUtxos: Utxo[] = utxos.map((u) => Utxo.fromHex(u));
const sender = Address.fromBech32(userAddress);
const txb = DEXOrderTransaction.createBulkOrdersTx({
networkEnv,
sender,
orderOptions: [
{
lpAsset: Asset.fromString(marketConfig.ammLpAsset),
version: DexVersion.DEX_V2,
type: OrderV2StepType.SWAP_EXACT_IN,
assetIn: marketConfig.assetB,
amountIn: BigInt(order.amountIn),
minimumAmountOut: 1n,
direction: OrderV2Direction.B_TO_A,
killOnFailed: false,
isLimitOrder: false,
},
],
});
const validTo = Date.now() + Duration.newMinutes(3).milliseconds;
txb.validToUnixTime(validTo);
const { txComplete, txId } = await txb.completeUnsafeForTxChaining({
coinSelectionAlgorithm: CoinSelectionAlgorithm.SPEND_ALL,
walletUtxos,
changeAddress: sender,
provider: new EmulatorProvider(networkEnv),
});
const txRaw = txComplete.complete();
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
safeFreeRustObjects(eTx);
return {
txRaw,
txId: txId,
validTo,
};
};
const checkLongRepayFunds = async (
networkEnv: NetworkEnvironment,
userAddress: string,
marketConfig: MarketConfig,
availableADA: number,
): Promise<{ canFullRepay: boolean; canRepay: boolean; loan: LiqwidProviderV2.Loan; loanAmount: bigint }> => {
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
const userAddr = Address.fromBech32(userAddress);
const pkh = userAddr.toPubKeyHash()?.keyHash.hex;
invariant(pkh, "Failed to extract public key hash from user address");
const loansResult = await LiqwidProviderV2.Data.loansForUser(apiConfig, [pkh]);
if (loansResult.type === "err") {
throw new Error(`Failed to fetch loans before repay: ${loansResult.error.message}`);
}
const loan = loansResult.value.find((l) => l.marketId === marketConfig.borrowMarketIdLong);
invariant(loan, `No active loan found for market ${marketConfig.borrowMarketIdLong}`);
const loanAmount = BigInt(Math.round(loan.amount * 1_000_000));
const canFullRepay = BigInt(availableADA) >= loanAmount;
let canRepay = true;
const marketsResult = await LiqwidProviderV2.Data.markets(apiConfig, {
ids: [marketConfig.borrowMarketIdLong],
});
if (marketsResult.type === "ok" && marketsResult.value.results.length > 0) {
const liqwidMarket = marketsResult.value.results[0];
const minValueRaw = BigInt(Math.round(liqwidMarket.parameters.minValue * 1_000_000));
const minThreshold = (minValueRaw * REPAY_MIN_VALUE_THRESHOLD_NUM) / DEFAULT_DENOMINATOR;
if (!canFullRepay && loanAmount <= minThreshold) {
canRepay = false;
}
}
return { canFullRepay, canRepay, loan, loanAmount };
};
/**
* Build LONG_REPAY transaction: Full repay — pay off entire loan and redeem all collateral.
* Only called when waitingLongSell / waitingLongSellFreed confirmed canFullRepay = true.
* Fetches loan from Liqwid API to get current UTXO and collateral info.
*/
export const handleLongRepay = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos, kupoService } = options;
invariant(order.orderType === LongOrderType.LONG_REPAY, "Invalid order type for handleLongRepay");
invariant(order.assetIn, "assetIn is required for LONG_REPAY order");
invariant(order.amountIn, "amountIn is required for LONG_REPAY order");
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
// Fetch current loan from API (always up-to-date)
const userAddr = Address.fromBech32(userAddress);
const pkh = userAddr.toPubKeyHash()?.keyHash.hex;
invariant(pkh, "Failed to extract public key hash from user address");
const loansResult = await LiqwidProviderV2.Data.loansForUser(apiConfig, [pkh]);
if (loansResult.type === "err") {
throw new Error(`Failed to fetch loans for full repay: ${loansResult.error.message}`);
}
const loan = loansResult.value.find((l) => l.marketId === marketConfig.borrowMarketIdLong);
invariant(loan, `No active loan found for market ${marketConfig.borrowMarketIdLong}`);
// Check if the user has enough ADA in wallet to cover the full debt
const loanAmountRaw = BigInt(Math.round(loan.amount * 1_000_000));
const walletBalance = await kupoService.getBalanceOfPubKeyAddress(userAddress);
const availableAda = walletBalance.get(marketConfig.assetA);
if (availableAda < loanAmountRaw) {
throw new Error(ERROR_BUILD_TX_CODE.ERROR_CANNOT_REPAY);
}
const loanUtxoId = `${loan.transactionId}-${loan.transactionIndex}`;
// Format collateral ID as "{MarketId}.{policyId}"
const qTokenParts = marketConfig.assetBQTokenRaw.split(".");
const qTokenPolicyId = qTokenParts[0];
const collateralId = `${marketConfig.borrowMarketIdLong}.${qTokenPolicyId}`;
const qTokenAmountFloat = loan.collaterals[0]?.qTokenAmount;
invariant(qTokenAmountFloat !== undefined, "Loan has no collateral");
const qTokenAmountRaw = Math.round(qTokenAmountFloat * 1_000_000);
logger.info("handleLongRepay: full repay", {
loanId: loan.id,
loanAmount: loan.amount,
qTokenAmountRaw,
loanUtxoId,
});
const buildTxResult = await LiqwidProviderV2.Transactions.repayLoan(apiConfig, {
address: userAddress,
utxos,
loanUtxoId,
collaterals: [
{
id: collateralId,
amount: qTokenAmountRaw,
},
],
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build repay transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProviderV2.getTxHash(txRaw);
return {
txRaw,
txId,
validTo: validTo.getTime(),
};
};
// ============================================================================
// FRACTIONAL LONG REPAY FLOW
// ============================================================================
//
// Triggered when LONG_SELL output (ADA received) < current loan amount.
//
// Full cycle until position is fully closed:
//
// LONG_SELL
// │ (ADA received < loan)
// ▼
// LONG_REPAY_FRACTION ──── modifyBorrow(newDebt, reducedCollateral, redeemCollateral=true)
// │
// ▼
// LONG_WITHDRAW_FRACTION ── withdraw freed qTokens → assetB
// │
// ▼
// LONG_SELL_FREED ────────── sell freed assetB → ADA
// │
// ├── accumulated ADA < remaining loan? ──► loop back to LONG_REPAY_FRACTION
// │
// └── accumulated ADA >= remaining loan? ──► LONG_REPAY (full repay)
// │
// LONG_WITHDRAW
// │
// LONG_SELL_ALL
//
// Key constraints:
// 1. newDebt = currentDebt - partialRepayAmount, must satisfy newDebt >= market.parameters.minValue.
// If loanAmount - availableADA < minValue, target newDebt = minValue instead
// (repay less this round so the position stays legal), then on the next
// LONG_SELL_FREED the remaining minValue will be fully repayable.
// 2. newCollateral is proportionally reduced:
// newCollateral = floor(totalCollateral * newDebt / currentDebt)
// 3. The loan UTXO ID changes after each modifyBorrow. Handlers fetch the current
// loan from the Liqwid API (always up-to-date).
// 4. Decision to enter fractional flow is made in waitingLongSell / waitingLongSellFreed
// (each function does only one thing: handleLongRepay = full repay only).
// ============================================================================
/**
* Build LONG_REPAY_FRACTION: Partial debt repay via modifyBorrow.
* Self-contained — fetches current loan from Liqwid API.
* Reduces debt by available ADA while keeping full collateral unchanged.
* Step 2 (LONG_WITHDRAW_FRACTION) reduces collateral proportionally in a separate tx.
*/
export const handleLongRepayFraction = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos, kupoService } = options;
invariant(order.orderType === LongOrderType.LONG_REPAY_FRACTION, "Invalid order type for handleLongRepayFraction");
invariant(order.assetIn, "assetIn is required for LONG_REPAY_FRACTION order");
invariant(order.amountIn, "amountIn (ADA available to repay) is required for LONG_REPAY_FRACTION order");
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
// Fetch current loan from API (always up-to-date, even after prior modifyBorrow calls)
const userAddr = Address.fromBech32(userAddress);
const pkh = userAddr.toPubKeyHash()?.keyHash.hex;
invariant(pkh, "Failed to extract public key hash from user address");
const loansResult = await LiqwidProviderV2.Data.loansForUser(apiConfig, [pkh]);
if (loansResult.type === "err") {
throw new Error(`Failed to fetch loans for partial repay: ${loansResult.error.message}`);
}
const loan = loansResult.value.find((l) => l.marketId === marketConfig.borrowMarketIdLong);
invariant(loan, `No active loan found for market ${marketConfig.borrowMarketIdLong}`);
const loanUtxoId = `${loan.transactionId}-${loan.transactionIndex}`;
// Fetch market to get minimum borrow amount constraint.
const marketResult = await LiqwidProviderV2.Data.market(
apiConfig,
marketConfig.borrowMarketIdLong as LiqwidProviderV2.MarketId,
);
if (marketResult.type === "err") {
throw new Error(`Failed to fetch market for partial repay: ${marketResult.error.message}`);
}
invariant(marketResult.value, `Market ${marketConfig.borrowMarketIdLong} not found`);
const minValueLovelace = Math.round(marketResult.value.parameters.minValue * 1_000_000); // ADA → Lovelace
// loan.amount is in ADA (float); convert to Lovelace to match order.amountIn and API expectations.
const currentDebtLovelace = Math.round(loan.amount * 1_000_000);
const availableLovelace = Number(order.amountIn); // already in Lovelace
// Query wallet balance via Kupo — if wallet has enough ADA, build full repay tx instead
const walletBalance = await kupoService.getBalanceOfPubKeyAddress(userAddress);
const walletAda = walletBalance.get(marketConfig.assetA);
if (walletAda >= BigInt(currentDebtLovelace)) {
logger.info("handleLongRepayFraction: wallet has enough for full repay, redirecting", {
walletAda: walletAda.toString(),
currentDebtLovelace,
});
const fullRepayResult = await handleLongRepay({
...options,
order: { ...order, orderType: LongOrderType.LONG_REPAY, amountIn: walletAda.toString() },
});
return {
...fullRepayResult,
redirectToFullRepay: {
targetOrderType: LongOrderType.LONG_REPAY,
amountIn: walletAda.toString(),
assetIn: marketConfig.assetA.toString(),
assetOut: marketConfig.assetBQTokenRaw,
deleteOrderTypes: [
LongOrderType.LONG_REPAY_FRACTION,
LongOrderType.LONG_WITHDRAW_FRACTION,
LongOrderType.LONG_SELL_FREED,
],
},
};
}
const qTokenAmountFloat = loan.collaterals[0]?.qTokenAmount;
invariant(qTokenAmountFloat !== undefined, "Loan has no collateral — cannot compute partial repay");
// qTokenAmount from API is human-readable (divided by 10^6), convert to raw on-chain amount
const qTokenAmountRaw = Math.round(qTokenAmountFloat * 1_000_000);
// Remaining debt must stay >= minValue so the position stays protocol-legal.
const newDebt = Math.max(currentDebtLovelace - availableLovelace, minValueLovelace);
// Check: both the repay amount AND remaining debt must be >= minValue.
const repayAmount = currentDebtLovelace - newDebt;
if (repayAmount < minValueLovelace || (availableLovelace < currentDebtLovelace && newDebt < minValueLovelace)) {
throw new Error(ERROR_BUILD_TX_CODE.ERROR_CANNOT_REPAY);
}
logger.info("handleLongRepayFraction", {
currentDebtLovelace,
availableLovelace,
minValueLovelace,
qTokenAmountRaw,
newDebt,
loanId: loan.id,
});
const qTokenParts = marketConfig.assetBQTokenRaw.split(".");
const qTokenPolicyId = qTokenParts[0];
const collateralId = `${marketConfig.borrowMarketIdLong}.${qTokenPolicyId}`;
// Step 1 of fractional close: reduce debt only, keep FULL collateral unchanged.
// Step 2 (LONG_WITHDRAW_FRACTION) will reduce collateral proportionally in a separate tx.
const buildTxResult = await LiqwidProviderV2.Transactions.repayLoanFraction(apiConfig, {
address: userAddress,
utxos,
loanUtxoId,
amount: newDebt,
collaterals: [{ id: collateralId, amount: qTokenAmountRaw }],
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build repay-fraction transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
safeFreeRustObjects(eTx, txBody);
// Liqwid may build repay-fraction tx without TTL; default to 3 minutes
const validTo = Maybe.isJust(ttl) ? getTimeFromSlotMagic(networkEnv, ttl) : new Date(Date.now() + 3 * 60 * 1000);
const txId = LiqwidProviderV2.getTxHash(txRaw);
return { txRaw, txId, validTo: validTo.getTime() };
};
/**
* Wait for LONG_REPAY_FRACTION tx confirmation.
*
* LONG_REPAY_FRACTION is a Liqwid modifyBorrow tx that reduces debt while keeping
* full collateral. No tokens are returned to the user (ADA is consumed as repayment).
*
* On confirmation → transition to LONG_WITHDRAW_FRACTION:
* amountIn = originalDebtLovelace (for proportional collateral calc in handleLongWithdrawFraction)
*/
export const waitingLongRepayFraction = async (options: WaitingOptions): Promise<WaitingResult> => {
const { marketConfig, txHash, userAddress, cardanoscanProvider, originalDebtLovelace } = options;
invariant(originalDebtLovelace, "originalDebtLovelace is required for waitingLongRepayFraction");
const txFoundOnChain = await cardanoscanProvider.findTransactionByHash(
userAddress,
txHash,
CardanoscanProvider.PAGE_SIZE,
CardanoscanProvider.MAX_PAGE,
);
if (txFoundOnChain) {
// LONG_REPAY_FRACTION has no output (ADA consumed as repayment) → no amountOut
return {
isConfirmed: true,
nextOrderType: LongOrderType.LONG_WITHDRAW_FRACTION,
assetIn: marketConfig.assetA.toString(), // placeholder (handler fetches loan from API)
amountIn: originalDebtLovelace, // original debt for proportional collateral calc
assetOut: marketConfig.assetB.toString(), // asset B will be received after withdraw
};
}
return { isConfirmed: false };
};
/**
* Build LONG_WITHDRAW_FRACTION: Reduce collateral via modifyBorrow after a partial repay.
* Keeps the same debt level, reduces collateral proportionally, and redeems freed qTokens
* to the underlying asset (sent to wallet for selling in LONG_SELL_FREED).
*/
export const handleLongWithdrawFraction = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(
order.orderType === LongOrderType.LONG_WITHDRAW_FRACTION,
"Invalid order type for handleLongWithdrawFraction",
);
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
// Fetch current loan state (after LONG_REPAY_FRACTION: debt reduced, collateral unchanged)
const userAddr = Address.fromBech32(userAddress);
const pkh = userAddr.toPubKeyHash()?.keyHash.hex;
invariant(pkh, "Failed to extract public key hash from user address");
const loansResult = await LiqwidProviderV2.Data.loansForUser(apiConfig, [pkh]);
if (loansResult.type === "err") {
throw new Error(`Failed to fetch loans for withdraw fraction: ${loansResult.error.message}`);
}
const loan = loansResult.value.find((l) => l.marketId === marketConfig.borrowMarketIdLong);
invariant(loan, `No active loan found for market ${marketConfig.borrowMarketIdLong}`);
// Use loan UTXO info from the API (always up-to-date after modifyBorrow calls)
const loanUtxoId = `${loan.transactionId}-${loan.transactionIndex}`;
const currentDebtLovelace = Math.round(loan.amount * 1_000_000);
const qTokenAmountFloat = loan.collaterals[0]?.qTokenAmount;
invariant(qTokenAmountFloat !== undefined, "Loan has no collateral");
const qTokenAmountRaw = Math.round(qTokenAmountFloat * 1_000_000);
// Fetch market to compute proportional collateral based on original debt ratio.
// order.amountIn stores the original debt (before LONG_REPAY_FRACTION) for proportional calc.
const originalDebtLovelace = order.amountIn ? Number(order.amountIn) : currentDebtLovelace;
const proportionalCollateral = Math.floor(qTokenAmountRaw * (currentDebtLovelace / originalDebtLovelace));
logger.info("handleLongWithdrawFraction", {
currentDebtLovelace,
originalDebtLovelace,
qTokenAmountRaw,
proportionalCollateral,
freedCollateral: qTokenAmountRaw - proportionalCollateral,
loanId: loan.id,
});
const qTokenParts = marketConfig.assetBQTokenRaw.split(".");
const qTokenPolicyId = qTokenParts[0];
const collateralId = `${marketConfig.borrowMarketIdLong}.${qTokenPolicyId}`;
// Step 2: keep same debt, reduce collateral proportionally, redeem freed qTokens to underlying.
const buildTxResult = await LiqwidProviderV2.Transactions.repayLoanFraction(apiConfig, {
address: userAddress,
utxos,
loanUtxoId,
amount: currentDebtLovelace,
collaterals: [{ id: collateralId, amount: proportionalCollateral }],
redeemCollateral: true,
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build withdraw-fraction transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProviderV2.getTxHash(txRaw);
return { txRaw, txId, validTo: validTo.getTime() };
};
/**
* Wait for LONG_WITHDRAW_FRACTION tx confirmation.
* Finds asset B received (freed collateral redeemed to underlying) and transitions to LONG_SELL_FREED.
*/
export const waitingLongWithdrawFraction = async (options: WaitingOptions): Promise<WaitingResult> => {
const { marketConfig, txHash, userAddress, cardanoscanProvider } = options;
const txFoundOnChain = await cardanoscanProvider.findTransactionByHash(
userAddress,
txHash,
CardanoscanProvider.PAGE_SIZE,
CardanoscanProvider.MAX_PAGE,
);
if (txFoundOnChain) {
const userAddressHex = userAddress.toHex();
const assetBUnit = marketConfig.assetB.toBlockFrostString();
for (const output of txFoundOnChain.outputs) {
if (output.address === userAddressHex) {
if (output.tokens && output.tokens.length > 0) {
const matchingToken = output.tokens.find((token) => token.assetId === assetBUnit);
if (matchingToken) {
const amountOut = BigInt(matchingToken.value);
return {
isConfirmed: true,
nextOrderType: LongOrderType.LONG_SELL_FREED,
assetIn: marketConfig.assetB.toString(),
amountIn: amountOut.toString(),
assetOut: marketConfig.assetA.toString(),
amountOut: amountOut.toString(),
};
}
}
}
}
throw new Error(
`LONG_WITHDRAW_FRACTION tx confirmed (${txHash}) but could not find output with asset ${marketConfig.assetB.toString()}`,
);
}
return { isConfirmed: false };
};
/**
* Build LONG_SELL_FREED: Sell freed assetB for ADA. Same DEX swap as handleLongSell.
*/
export const handleLongSellFreed = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
invariant(options.order.orderType === LongOrderType.LONG_SELL_FREED, "Invalid order type for handleLongSellFreed");
return handleLongSell({ ...options, order: { ...options.order, orderType: LongOrderType.LONG_SELL } });
};
/**
* Wait for LONG_SELL_FREED order output to be spent (DEX consumed).
*
* On confirmation, transitions to LONG_REPAY (full repay) with the ADA received.
* The LONG_REPAY handler will check if funds are sufficient; if not, it will
* trigger another fractional cycle automatically.
*/
export const waitingLongSellFreed = async (options: WaitingOptions): Promise<WaitingResult> => {
const { marketConfig, txHash, orderOutputIndex, userAddress, cardanoscanProvider, networkEnv } = options;
invariant(orderOutputIndex !== undefined, "orderOutputIndex is required for waitingLongSellFreed");
const userAddressHex = userAddress.toHex();
const spendingTx = await cardanoscanProvider.findTransactionHasSpent(
userAddress,
txHash,
orderOutputIndex,
CardanoscanProvider.PAGE_SIZE,
CardanoscanProvider.MAX_PAGE,
);
if (spendingTx) {
for (const output of spendingTx.outputs) {
if (output.address === userAddressHex) {
const amountOut = BigInt(output.value);
// Check if we now have enough ADA to fully repay the remaining loan.
const { canFullRepay, canRepay, loanAmount } = await checkLongRepayFunds(
networkEnv,
userAddress.bech32,
marketConfig,
Number(amountOut),
);
logger.info("waitingLongSellFreed: repay check", {
available: amountOut.toString(),
loanAmount: loanAmount.toString(),
canFullRepay,
canRepay,
});
if (!canRepay) {
throw new Error(ERROR_BUILD_TX_CODE.ERROR_CANNOT_REPAY);
}
if (canFullRepay) {
// Enough ADA → transition to existing LONG_REPAY (from closePosition)
return {
isConfirmed: true,
nextOrderType: LongOrderType.LONG_REPAY,
assetIn: marketConfig.assetA.toString(),
amountIn: amountOut.toString(),
assetOut: marketConfig.assetBQTokenRaw,
amountOut: amountOut.toString(),
};
}
// Still not enough → loop: create another fractional cycle
return {
isConfirmed: true,
nextOrderType: LongOrderType.LONG_REPAY_FRACTION,
assetIn: marketConfig.assetA.toString(),
amountIn: amountOut.toString(),
assetOut: marketConfig.assetA.toString(),
amountOut: amountOut.toString(),
additionalOrders: [
{ orderType: LongOrderType.LONG_REPAY_FRACTION },
{ orderType: LongOrderType.LONG_WITHDRAW_FRACTION },
{ orderType: LongOrderType.LONG_SELL_FREED },
],
originalDebtLovelace: loanAmount.toString(),
};
}
}
throw new Error(`LONG_SELL_FREED output spent (tx: ${spendingTx.hash}) but could not find ADA output for user`);
}
return { isConfirmed: false };
};
/**
* Build LONG_WITHDRAW transaction: Withdraw underlying asset from Liqwid
* Uses the amountOut from LONG_SUPPLY order as the withdraw amount
*/
export const handleLongWithdraw = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(order.orderType === LongOrderType.LONG_WITHDRAW, "Invalid order type for handleLongWithdraw");
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
const marketId = marketConfig.longCollateralMarketId as LiqwidProviderV2.MarketId;
// Get current qToken balance from UTxOs (may differ from original supply after fractional cycles)
const qTokenAsset = Asset.fromString(marketConfig.assetBQTokenRaw);
let qTokenBalance = 0n;
for (const utxoHex of utxos) {
const utxo = Utxo.fromHex(utxoHex);
const amount = utxo.output.value.get(qTokenAsset);
if (amount > 0n) {
qTokenBalance += amount;
}
}
invariant(qTokenBalance > 0n, "No qToken balance found in user UTxOs for LONG_WITHDRAW");
// Convert qToken amount to underlying amount via market exchange rate
const marketResult = await LiqwidProviderV2.Data.market(apiConfig, marketId);
if (marketResult.type === "err") {
throw new Error(`Failed to fetch market data: ${marketResult.error.message}`);
}
const market = marketResult.value;
invariant(market, `Market ${marketId} not found`);
const withdrawAmount = Math.floor(Number(qTokenBalance) * market.exchangeRate);
logger.info("handleLongWithdraw", {
qTokenBalance: qTokenBalance.toString(),
exchangeRate: market.exchangeRate,
withdrawAmount,
});
const buildTxResult = await LiqwidProviderV2.Transactions.withdraw(apiConfig, {
address: userAddress,
utxos,
marketId,
amount: withdrawAmount,
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build withdraw transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProviderV2.getTxHash(txRaw);
return {
txRaw,
txId,
validTo: validTo.getTime(),
};
};
// ============================================================================
// SHORT Build Functions
// ============================================================================
/**
* Build SHORT_SUPPLY transaction: Supply asset A (ADA) to Liqwid, receive qADA
*/
export const handleShortSupply = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(order.orderType === ShortOrderType.SHORT_SUPPLY, "Invalid order type for handleShortSupply");
invariant(order.assetIn, "assetIn is required for SHORT_SUPPLY order");
invariant(order.amountIn, "amountIn is required for SHORT_SUPPLY order");
const marketId = marketConfig.shortCollateralMarketId as LiqwidProvider.MarketId;
const buildTxResult = await LiqwidProvider.getSupplyTransaction({
marketId,
amount: Number(order.amountIn),
address: userAddress,
utxos,
networkEnv,
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build supply transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProvider.getLiqwidTxHash(txRaw);
return {
txRaw,
txId,
validTo: validTo.getTime(),
};
};
/**
* Build SHORT_BORROW transaction: Borrow asset B using qADA as collateral
*/
export const handleShortBorrow = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos, amountBorrow } = options;
invariant(order.orderType === ShortOrderType.SHORT_BORROW, "Invalid order type for handleShortBorrow");
invariant(order.assetIn, "assetIn is required for SHORT_BORROW order");
invariant(order.amountIn, "amountIn is required for SHORT_BORROW order");
invariant(amountBorrow, "amountBorrow is required for SHORT_BORROW order");
const apiConfig = LiqwidProviderV2.createConfig(networkEnv);
const buildTxResult = await LiqwidProviderV2.Transactions.borrow(apiConfig, {
address: userAddress,
utxos,
marketId: marketConfig.borrowMarketIdShort as LiqwidProviderV2.MarketId,
amount: Number(amountBorrow),
collaterals: [
{
id: marketConfig.assetAQTokenTicker,
amount: Number(order.amountIn),
},
],
});
if (buildTxResult.type === "err") {
throw new Error(`Failed to build borrow transaction: ${buildTxResult.error.message}`);
}
const txRaw = buildTxResult.value;
const ECSL = RustModule.getE;
const eTx = ECSL.Transaction.from_hex(txRaw);
const txBody = eTx.body();
const ttl = txBody.ttl();
invariant(Maybe.isJust(ttl), "TTL must be set in the transaction body");
safeFreeRustObjects(eTx, txBody);
const validTo = getTimeFromSlotMagic(networkEnv, ttl);
const txId = LiqwidProviderV2.getTxHash(txRaw);
return {
txRaw,
txId,
validTo: validTo.getTime(),
};
};
/**
* Build SHORT_SELL transaction: Sell asset B for asset A via DEX (B_TO_A swap)
* Reuses the same DEX swap pattern as handleLongSell
*/
export const handleShortSell = async (options: HandleBuildTxOptions): Promise<BuiltResult> => {
const { order, marketConfig, userAddress, networkEnv, utxos } = options;
invariant(order.orderType === ShortOrderType.SHORT_SELL, "Invalid order type for handleShortSell");
invariant(order.assetIn, "assetIn is required for SHORT_SELL order");
invariant(order.amountIn, "amountIn is required for SHORT_SELL order");
invariant(order.assetOut, "assetOut is required for SHORT_SELL order");
const walletUtxos: Utxo[] = utxos.map((u) => Utxo.fromHex(u));
const sender = Address.fromBech32(userAddress);
const txb = DEXOrderTransaction.createBulkOrdersTx({
networkEnv,
sender,
orderOptions: [
{
lpAsset: Asset.fromString(marketConfig.ammLpAsset),
version: DexVersion.DEX_V2,
type: OrderV2StepType.SWAP_EXACT_IN,
assetIn: marketConfig.assetB,
amountIn: BigInt(order.amountIn),
minimumAmountOut: 1n,
direction: OrderV2Direction.B_TO_A,
killOnFailed: false,
isLimitOrder: false,