@omnipair/dusk-sdk 2.0.2 → 2.18.0-next.20261106

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 (187) hide show
  1. package/README.md +863 -42
  2. package/dist/amounts.d.ts +9 -0
  3. package/dist/amounts.d.ts.map +1 -0
  4. package/dist/amounts.js +10 -0
  5. package/dist/amounts.js.map +1 -0
  6. package/dist/constants.d.ts +68 -27
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +153 -41
  9. package/dist/constants.js.map +1 -1
  10. package/dist/delegate.d.ts +97 -0
  11. package/dist/delegate.d.ts.map +1 -0
  12. package/dist/delegate.js +152 -0
  13. package/dist/delegate.js.map +1 -0
  14. package/dist/dusk.d.ts +14 -0
  15. package/dist/dusk.d.ts.map +1 -1
  16. package/dist/dusk.js +22 -0
  17. package/dist/dusk.js.map +1 -1
  18. package/dist/get.d.ts +3033 -385
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +109 -72
  21. package/dist/get.js.map +1 -1
  22. package/dist/hash.d.ts +9 -0
  23. package/dist/hash.d.ts.map +1 -0
  24. package/dist/hash.js +16 -0
  25. package/dist/hash.js.map +1 -0
  26. package/dist/hlp-liquidation-client.d.ts +104 -0
  27. package/dist/hlp-liquidation-client.d.ts.map +1 -0
  28. package/dist/hlp-liquidation-client.js +146 -0
  29. package/dist/hlp-liquidation-client.js.map +1 -0
  30. package/dist/idl_delegate.d.ts +3 -0
  31. package/dist/idl_delegate.d.ts.map +1 -0
  32. package/dist/idl_delegate.js +3 -0
  33. package/dist/idl_delegate.js.map +1 -0
  34. package/dist/idl_delegate.json +6268 -0
  35. package/dist/idl_v2.json +16746 -6676
  36. package/dist/index.d.ts +23 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +23 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/interest-accounting.d.ts +45 -0
  41. package/dist/interest-accounting.d.ts.map +1 -0
  42. package/dist/interest-accounting.js +59 -0
  43. package/dist/interest-accounting.js.map +1 -0
  44. package/dist/leverage-actions.d.ts +122 -0
  45. package/dist/leverage-actions.d.ts.map +1 -0
  46. package/dist/leverage-actions.js +228 -0
  47. package/dist/leverage-actions.js.map +1 -0
  48. package/dist/leverage-margins.d.ts +12 -0
  49. package/dist/leverage-margins.d.ts.map +1 -0
  50. package/dist/leverage-margins.js +45 -0
  51. package/dist/leverage-margins.js.map +1 -0
  52. package/dist/leverage-preview.d.ts +598 -0
  53. package/dist/leverage-preview.d.ts.map +1 -0
  54. package/dist/leverage-preview.js +89 -0
  55. package/dist/leverage-preview.js.map +1 -0
  56. package/dist/liquidation-client.d.ts +226 -0
  57. package/dist/liquidation-client.d.ts.map +1 -0
  58. package/dist/liquidation-client.js +237 -0
  59. package/dist/liquidation-client.js.map +1 -0
  60. package/dist/liquidation.d.ts +72 -0
  61. package/dist/liquidation.d.ts.map +1 -0
  62. package/dist/liquidation.js +104 -0
  63. package/dist/liquidation.js.map +1 -0
  64. package/dist/lp-naming.d.ts +43 -0
  65. package/dist/lp-naming.d.ts.map +1 -0
  66. package/dist/lp-naming.js +81 -0
  67. package/dist/lp-naming.js.map +1 -0
  68. package/dist/lp-vanity.d.ts +33 -0
  69. package/dist/lp-vanity.d.ts.map +1 -0
  70. package/dist/lp-vanity.js +94 -0
  71. package/dist/lp-vanity.js.map +1 -0
  72. package/dist/market-bootstrap.d.ts +109 -0
  73. package/dist/market-bootstrap.d.ts.map +1 -0
  74. package/dist/market-bootstrap.js +156 -0
  75. package/dist/market-bootstrap.js.map +1 -0
  76. package/dist/market-launch.d.ts +45 -0
  77. package/dist/market-launch.d.ts.map +1 -0
  78. package/dist/market-launch.js +76 -0
  79. package/dist/market-launch.js.map +1 -0
  80. package/dist/operator-client.d.ts +99 -0
  81. package/dist/operator-client.d.ts.map +1 -0
  82. package/dist/operator-client.js +153 -0
  83. package/dist/operator-client.js.map +1 -0
  84. package/dist/oracle.d.ts +46 -0
  85. package/dist/oracle.d.ts.map +1 -0
  86. package/dist/oracle.js +103 -0
  87. package/dist/oracle.js.map +1 -0
  88. package/dist/parameters.d.ts +231 -0
  89. package/dist/parameters.d.ts.map +1 -0
  90. package/dist/parameters.js +683 -0
  91. package/dist/parameters.js.map +1 -0
  92. package/dist/preview.d.ts +39 -1
  93. package/dist/preview.d.ts.map +1 -1
  94. package/dist/preview.js +12 -0
  95. package/dist/preview.js.map +1 -1
  96. package/dist/protection.d.ts +48 -0
  97. package/dist/protection.d.ts.map +1 -0
  98. package/dist/protection.js +88 -0
  99. package/dist/protection.js.map +1 -0
  100. package/dist/risk-pricing.d.ts +12 -0
  101. package/dist/risk-pricing.d.ts.map +1 -0
  102. package/dist/risk-pricing.js +23 -0
  103. package/dist/risk-pricing.js.map +1 -0
  104. package/dist/simulation.d.ts +45 -0
  105. package/dist/simulation.d.ts.map +1 -0
  106. package/dist/simulation.js +106 -0
  107. package/dist/simulation.js.map +1 -0
  108. package/dist/tranche-client.d.ts +121 -0
  109. package/dist/tranche-client.d.ts.map +1 -0
  110. package/dist/tranche-client.js +185 -0
  111. package/dist/tranche-client.js.map +1 -0
  112. package/dist/transfer-fees.d.ts +46 -0
  113. package/dist/transfer-fees.d.ts.map +1 -0
  114. package/dist/transfer-fees.js +76 -0
  115. package/dist/transfer-fees.js.map +1 -0
  116. package/dist/type-aliases.d.ts +265 -31
  117. package/dist/type-aliases.d.ts.map +1 -1
  118. package/dist/types_delegate.d.ts +6275 -0
  119. package/dist/types_delegate.d.ts.map +1 -0
  120. package/dist/types_delegate.js +2 -0
  121. package/dist/types_delegate.js.map +1 -0
  122. package/dist/types_v2.d.ts +16654 -6584
  123. package/dist/types_v2.d.ts.map +1 -1
  124. package/dist/virtual-book/index.d.ts +4 -0
  125. package/dist/virtual-book/index.d.ts.map +1 -0
  126. package/dist/virtual-book/index.js +4 -0
  127. package/dist/virtual-book/index.js.map +1 -0
  128. package/dist/virtual-book/market.d.ts +619 -0
  129. package/dist/virtual-book/market.d.ts.map +1 -0
  130. package/dist/virtual-book/market.js +59 -0
  131. package/dist/virtual-book/market.js.map +1 -0
  132. package/dist/virtual-book/projection.d.ts +44 -0
  133. package/dist/virtual-book/projection.d.ts.map +1 -0
  134. package/dist/virtual-book/projection.js +229 -0
  135. package/dist/virtual-book/projection.js.map +1 -0
  136. package/dist/virtual-book/quotes.d.ts +1263 -0
  137. package/dist/virtual-book/quotes.d.ts.map +1 -0
  138. package/dist/virtual-book/quotes.js +233 -0
  139. package/dist/virtual-book/quotes.js.map +1 -0
  140. package/dist/write.d.ts +427 -0
  141. package/dist/write.d.ts.map +1 -1
  142. package/dist/write.js +970 -26
  143. package/dist/write.js.map +1 -1
  144. package/dist/yield-client.d.ts +51 -0
  145. package/dist/yield-client.d.ts.map +1 -0
  146. package/dist/yield-client.js +98 -0
  147. package/dist/yield-client.js.map +1 -0
  148. package/package.json +11 -4
  149. package/src/amounts.ts +13 -0
  150. package/src/constants.ts +220 -46
  151. package/src/delegate.ts +259 -0
  152. package/src/dusk.ts +28 -0
  153. package/src/get.ts +201 -86
  154. package/src/hash.ts +15 -0
  155. package/src/hlp-liquidation-client.ts +189 -0
  156. package/src/idl_delegate.json +6268 -0
  157. package/src/idl_delegate.ts +3 -0
  158. package/src/idl_v2.json +16746 -6676
  159. package/src/index.ts +31 -0
  160. package/src/interest-accounting.ts +73 -0
  161. package/src/leverage-actions.ts +216 -0
  162. package/src/leverage-margins.ts +48 -0
  163. package/src/leverage-preview.ts +86 -0
  164. package/src/liquidation-client.ts +295 -0
  165. package/src/liquidation.ts +119 -0
  166. package/src/lp-naming.ts +127 -0
  167. package/src/lp-vanity.ts +135 -0
  168. package/src/market-bootstrap.ts +271 -0
  169. package/src/market-launch.ts +103 -0
  170. package/src/operator-client.ts +169 -0
  171. package/src/oracle.ts +120 -0
  172. package/src/parameters.ts +1019 -0
  173. package/src/preview.ts +53 -1
  174. package/src/protection.ts +112 -0
  175. package/src/risk-pricing.ts +26 -0
  176. package/src/simulation.ts +169 -0
  177. package/src/tranche-client.ts +187 -0
  178. package/src/transfer-fees.ts +99 -0
  179. package/src/type-aliases.ts +294 -32
  180. package/src/types_delegate.ts +6274 -0
  181. package/src/types_v2.ts +16745 -6675
  182. package/src/virtual-book/index.ts +3 -0
  183. package/src/virtual-book/market.ts +76 -0
  184. package/src/virtual-book/projection.ts +265 -0
  185. package/src/virtual-book/quotes.ts +308 -0
  186. package/src/write.ts +1650 -28
  187. package/src/yield-client.ts +117 -0
package/src/index.ts CHANGED
@@ -7,12 +7,43 @@ export * from "./type-aliases.js";
7
7
 
8
8
  // Re-export constants and utilities
9
9
  export * from "./address.js";
10
+ export * from "./amounts.js";
10
11
  export * from "./constants.js";
11
12
  export { Dusk } from "./dusk.js";
12
13
  export type { DuskOptions } from "./dusk.js";
14
+ export * from "./delegate.js";
13
15
  export * from "./get.js";
16
+ export * from "./parameters.js";
17
+ export * from "./hash.js";
14
18
  export * from "./indexer.js";
19
+ export * from "./lp-naming.js";
20
+ export * from "./leverage-margins.js";
21
+ export * from "./leverage-actions.js";
22
+ export * from "./leverage-preview.js";
23
+ export * from "./liquidation.js";
24
+ export * from "./liquidation-client.js";
25
+ export * from "./market-launch.js";
26
+ export * from "./lp-vanity.js";
27
+ export * from "./market-bootstrap.js";
15
28
  export * from "./preview.js";
16
29
  export * from "./program.js";
17
30
  export * from "./referral.js";
18
31
  export * from "./write.js";
32
+ export * from "./virtual-book/index.js";
33
+ export * from "./protection.js";
34
+
35
+ export * from "./operator-client.js";
36
+
37
+ export * from "./transfer-fees.js";
38
+
39
+ export * from "./interest-accounting.js";
40
+
41
+ export * from "./yield-client.js";
42
+
43
+ export * from "./hlp-liquidation-client.js";
44
+
45
+ export * from "./risk-pricing.js";
46
+
47
+ export * from "./tranche-client.js";
48
+
49
+ export * from "./oracle.js";
@@ -0,0 +1,73 @@
1
+ import { transferFeeCredit, type TransferFeeNotice } from "./transfer-fees.js";
2
+ import type { BorrowPosition, Market } from "./type-aliases.js";
3
+
4
+ const U64_MAX = (1n << 64n) - 1n;
5
+ const U128_MAX = (1n << 128n) - 1n;
6
+ const NAD = 1_000_000_000n;
7
+
8
+ /** Position-local public principal and indexed debt, in raw token atoms.
9
+ * Read the position and market from the same slot. The market's fixed
10
+ * principal is an aggregate and must not be used to split this loan's payoff
11
+ * or insured loss. A one-atom share-floor phase can leave recorded principal
12
+ * briefly above displayed position debt, so accrued interest is floored at 0.
13
+ */
14
+ export function borrowDebtBreakdown(
15
+ position: Pick<BorrowPosition, "fixedBaseShares" | "fixedQuoteShares" | "fixedBasePrincipal" | "fixedQuotePrincipal">,
16
+ market: Pick<Market, "debt">,
17
+ asset: "base" | "quote",
18
+ ) {
19
+ const shares = BigInt((asset === "base" ? position.fixedBaseShares : position.fixedQuoteShares).toString());
20
+ const principal = BigInt((asset === "base" ? position.fixedBasePrincipal : position.fixedQuotePrincipal).toString());
21
+ const index = BigInt((asset === "base" ? market.debt.baseBorrowIndexNad : market.debt.quoteBorrowIndexNad).toString());
22
+ amount(shares, U128_MAX);
23
+ amount(principal);
24
+ amount(index, U128_MAX);
25
+ if (index < NAD) throw new RangeError("Invalid borrow index");
26
+ const debt = shares * index / NAD;
27
+ amount(debt, U128_MAX);
28
+ return { debt, principal, accruedInterest: debt > principal ? debt - principal : 0n };
29
+ }
30
+ function amount(value: bigint, max = U64_MAX): void {
31
+ if (value < 0n || value > max) throw new RangeError("Interest amount is out of range");
32
+ }
33
+ /** Fund LP income using the historical unpaid fee book. Protocol and operator
34
+ * fees remain unpaid until borrower cash arrives. No current fee rate is used.
35
+ * Inputs must describe the same checkpointed market state. */
36
+ export function quoteInterestAdvanceAmounts(input: {
37
+ unpaidPublicInterest: bigint;
38
+ unpaidFeeInterest: bigint;
39
+ outstandingGrossAdvance: bigint;
40
+ outstandingRevenueEscrow: bigint;
41
+ reserveCash: bigint;
42
+ maxGross: bigint;
43
+ transferFee: TransferFeeNotice;
44
+ }) {
45
+ const { unpaidPublicInterest: unpaid, unpaidFeeInterest: fees,
46
+ outstandingGrossAdvance: advanced, outstandingRevenueEscrow: escrow, reserveCash, maxGross } = input;
47
+ amount(unpaid, U128_MAX);
48
+ for (const value of [fees, advanced, escrow, reserveCash, maxGross]) amount(value);
49
+ if (advanced > unpaid || escrow > advanced || escrow > fees || fees > unpaid
50
+ || fees - escrow > unpaid - advanced) throw new RangeError("Inconsistent unpaid interest/advance");
51
+ const available = unpaid - advanced;
52
+ const grossAdvance = [available, reserveCash, maxGross].reduce((a, b) => a < b ? a : b);
53
+ const revenueEscrow = available === 0n ? 0n : grossAdvance * (fees - escrow) / available;
54
+ const lpVaultDebit = grossAdvance - revenueEscrow;
55
+ const lpVaultCredit = transferFeeCredit(lpVaultDebit, input.transferFee, "effective");
56
+ return { grossAdvance, revenueEscrow, lpVaultDebit, lpVaultCredit, transferFee: lpVaultDebit - lpVaultCredit };
57
+ }
58
+
59
+ /** Allocate measured custody credit against the frozen settlement budget.
60
+ * grossTransfer excludes LP yield already funded by an advance. pendingFeeGross
61
+ * includes both protocol and operator receivables. Recipient claims are settled
62
+ * by the on-chain fee book, including fractional cash from earlier payments. */
63
+ export function allocateRepaidInterest(input: {
64
+ grossTransfer: bigint;
65
+ pendingFeeGross: bigint;
66
+ measuredVaultCredit: bigint;
67
+ }) {
68
+ const { grossTransfer, pendingFeeGross: fees, measuredVaultCredit: credit } = input;
69
+ for (const value of [grossTransfer, fees, credit]) amount(value);
70
+ if (credit > grossTransfer || fees > grossTransfer) throw new RangeError("Custody credit or fees exceed settlement");
71
+ const revenueCredit = grossTransfer === 0n ? 0n : credit * fees / grossTransfer;
72
+ return { grossTransfer, revenueCredit, lpCredit: credit - revenueCredit };
73
+ }
@@ -0,0 +1,216 @@
1
+ /** Position actions use the borrowed token as their unit of account on BOTH
2
+ * sides. A reverse position is long the held token against the borrowed token;
3
+ * this leverage is not a dollar-denominated perpetual's short delta.
4
+ */
5
+ const BPS = 10_000n;
6
+ const NAD = 1_000_000_000n;
7
+ const U64_MAX = (1n << 64n) - 1n;
8
+ const U128_MAX = (1n << 128n) - 1n;
9
+ const ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;
10
+
11
+ function unsigned(value: bigint, name: string, max = U64_MAX): bigint {
12
+ if (typeof value !== "bigint" || value < 0n || value > max)
13
+ throw new RangeError(`${name} must be an unsigned integer no greater than ${max}`);
14
+ return value;
15
+ }
16
+
17
+ export interface LeverageActionState {
18
+ collateralAmount: bigint;
19
+ /** Indexed debt, including accrued interest, in borrowed-token atoms. */
20
+ debtAmount: bigint;
21
+ /** Mark or EMA value of held collateral in borrowed-token atoms. State the
22
+ * chosen price basis in the UI. This is NOT a realizable close payout. */
23
+ collateralValue: bigint;
24
+ }
25
+
26
+ export function leverageActionMetrics(state: LeverageActionState) {
27
+ for (const [name, value] of Object.entries(state)) unsigned(value, name);
28
+ const equity = state.collateralValue - state.debtAmount;
29
+ return {
30
+ ...state, equity,
31
+ leverageBps: equity > 0n ? ceilDiv(state.collateralValue * BPS, equity) : null,
32
+ debtFree: state.debtAmount === 0n,
33
+ unitOfAccount: "debt-token" as const,
34
+ };
35
+ }
36
+
37
+ /** Matches the program's aggregate-floor-aware debt-share burn. Do not infer
38
+ * a full repayment from a rounded UI debt amount: it can need one more atom. */
39
+ export function leverageRepaymentQuote(input: {
40
+ positionShares: bigint; aggregateShares: bigint; borrowIndexNad: bigint; maxCredit: bigint;
41
+ }) {
42
+ const { positionShares: shares, aggregateShares: aggregate, borrowIndexNad: index, maxCredit } = input;
43
+ unsigned(shares, "positionShares", U128_MAX); unsigned(aggregate, "aggregateShares", U128_MAX);
44
+ unsigned(index, "borrowIndexNad", U128_MAX); unsigned(maxCredit, "maxCredit");
45
+ if (aggregate < shares || index < NAD) throw new RangeError("Invalid aggregate shares or borrow index");
46
+ const debtAt = (s: bigint) => s * index / NAD;
47
+ const debtBefore = debtAt(shares);
48
+ const fullRepayCredit = debtAt(aggregate) - debtAt(aggregate - shares);
49
+ unsigned(debtBefore, "debtAmount"); unsigned(fullRepayCredit, "fullRepayCredit");
50
+ if (shares === 0n || maxCredit === 0n) return {
51
+ sharesBurned: 0n, cashRepaid: 0n, debtReduced: 0n, debtRemaining: debtBefore, fullRepayCredit,
52
+ };
53
+ let burned = maxCredit * NAD / index;
54
+ if (burned > shares) burned = shares;
55
+ if (burned < shares && debtAt(aggregate) - debtAt(aggregate - burned - 1n) <= maxCredit) burned++;
56
+ const cashRepaid = debtAt(aggregate) - debtAt(aggregate - burned);
57
+ if (burned === 0n || cashRepaid === 0n) throw new RangeError("Repayment is below debt-share granularity");
58
+ const debtRemaining = debtAt(shares - burned);
59
+ return { sharesBurned: burned, cashRepaid, debtReduced: debtBefore - debtRemaining, debtRemaining, fullRepayCredit };
60
+ }
61
+
62
+ /** Exact slice selection used by owner and delegated partial closes. */
63
+ export function leverageCloseSlice(input: {
64
+ collateralAmount: bigint; debtShares: bigint; aggregateShares: bigint; borrowIndexNad: bigint; closeBps: number;
65
+ }) {
66
+ const { collateralAmount, debtShares, aggregateShares, borrowIndexNad, closeBps } = input;
67
+ unsigned(collateralAmount, "collateralAmount"); unsigned(debtShares, "debtShares", U128_MAX);
68
+ if (!Number.isSafeInteger(closeBps) || closeBps < 1 || closeBps > 10_000 || collateralAmount === 0n)
69
+ throw new RangeError("A close requires collateral and 1..10000 closeBps");
70
+ const collateralDebit = collateralAmount * BigInt(closeBps) / BPS;
71
+ if (collateralDebit === 0n) throw new RangeError("Close amount rounds to zero");
72
+ const sharesToBurn = ceilDiv(debtShares * collateralDebit, collateralAmount);
73
+ if (closeBps < 10_000 && debtShares > 0n && sharesToBurn >= debtShares)
74
+ throw new RangeError("Partial close would clear all debt shares; choose full close or decrease size");
75
+ const { fullRepayCredit: debtRepayment } = leverageRepaymentQuote({
76
+ positionShares: sharesToBurn, aggregateShares, borrowIndexNad, maxCredit: U64_MAX,
77
+ });
78
+ return { closeBps, collateralDebit, sharesToBurn, debtRepayment,
79
+ remainingCollateral: collateralAmount - collateralDebit, remainingDebtShares: debtShares - sharesToBurn };
80
+ }
81
+
82
+ /** Link a held-token size input to percentage without closing more than asked.
83
+ * The returned actual debit may be smaller because on-chain percentages use bps. */
84
+ export function leverageClosePercentage(collateralAmount: bigint, requestedDebit: bigint) {
85
+ unsigned(collateralAmount, "collateralAmount"); unsigned(requestedDebit, "requestedDebit");
86
+ if (collateralAmount === 0n || requestedDebit === 0n || requestedDebit > collateralAmount)
87
+ throw new RangeError("Requested close must be within the position");
88
+ const closeBps = Number(requestedDebit * BPS / collateralAmount);
89
+ if (closeBps === 0) throw new RangeError("Requested size is below one basis point of the position");
90
+ return { closeBps, collateralDebit: collateralAmount * BigInt(closeBps) / BPS };
91
+ }
92
+
93
+ export type LeveragePurchaseQuote = (netDebtInput: bigint) => Promise<bigint>;
94
+
95
+ /** Link target leverage OR additional held-token size to borrowing. The default
96
+ * target is CURRENT WHOLE-position leverage, never leverage of just the added
97
+ * slice. marginCredit is net wallet funding after its transfer fee.
98
+ *
99
+ * quoteCollateralCredit must be monotone and use one fixed curve snapshot,
100
+ * swap fees and the collateral transfer fee. Borrowed input is internal: do
101
+ * not apply a wallet input transfer fee to it. Cache/local quotes are preferred
102
+ * over a separate RPC per search iteration. This is a sizing estimate at the
103
+ * supplied price basis, not an admission check. Simulate the final instruction
104
+ * with previewLeverageAction for actual post-execution IM/MM, debt and payout.
105
+ */
106
+ export async function planLeverageIncrease(input: {
107
+ state: LeverageActionState; marginCredit?: bigint; maxBorrowAmount: bigint;
108
+ targetLeverageBps?: bigint; additionalCollateral?: bigint; quoteCollateralCredit: LeveragePurchaseQuote;
109
+ }) {
110
+ const before = leverageActionMetrics(input.state);
111
+ if (before.equity <= 0n || before.collateralAmount === 0n) throw new RangeError("Position must have positive equity and collateral");
112
+ const marginCredit = unsigned(input.marginCredit ?? 0n, "marginCredit");
113
+ let hi = unsigned(input.maxBorrowAmount, "maxBorrowAmount");
114
+ if (marginCredit + hi > U64_MAX) throw new RangeError("Combined input exceeds u64");
115
+ if (input.additionalCollateral !== undefined && input.targetLeverageBps !== undefined)
116
+ throw new Error("Select a target leverage OR an additional collateral size");
117
+ const target = input.targetLeverageBps ?? before.leverageBps!;
118
+ unsigned(target, "targetLeverageBps");
119
+ if (target < BPS) throw new RangeError("Asset-relative leverage must be at least 1x");
120
+ type Candidate = { debtAmount: bigint; marginCredit: bigint; collateralCredit: bigint;
121
+ after: ReturnType<typeof leverageActionMetrics> };
122
+ const cache = new Map<bigint, Candidate>();
123
+ async function candidate(debtAmount: bigint): Promise<Candidate> {
124
+ const cached = cache.get(debtAmount); if (cached) return cached;
125
+ const total = marginCredit + debtAmount;
126
+ const collateralCredit = total === 0n ? 0n : unsigned(await input.quoteCollateralCredit(total), "collateralCredit");
127
+ const collateralAmount = unsigned(before.collateralAmount + collateralCredit, "resultingCollateral");
128
+ const collateralValue = unsigned(collateralAmount * before.collateralValue / before.collateralAmount, "resultingValue");
129
+ const result = { debtAmount, marginCredit, collateralCredit,
130
+ after: leverageActionMetrics({ collateralAmount, collateralValue, debtAmount: unsigned(before.debtAmount + debtAmount, "resultingDebt") }) };
131
+ cache.set(debtAmount, result); return result;
132
+ }
133
+ let lo = 0n;
134
+ if (input.additionalCollateral !== undefined) {
135
+ const wanted = unsigned(input.additionalCollateral, "additionalCollateral");
136
+ if (wanted === 0n || (await candidate(lo)).collateralCredit > wanted)
137
+ throw new RangeError("Size is smaller than the wallet-funded purchase");
138
+ if ((await candidate(hi)).collateralCredit < wanted) throw new RangeError("Size exceeds the borrowing bound");
139
+ while (lo < hi) {
140
+ const mid = (lo + hi) / 2n;
141
+ if ((await candidate(mid)).collateralCredit >= wanted) hi = mid; else lo = mid + 1n;
142
+ }
143
+ } else {
144
+ const fits = (c: Awaited<ReturnType<typeof candidate>>) => c.after.equity > 0n && c.after.collateralValue * BPS <= target * c.after.equity;
145
+ if (!fits(await candidate(0n))) throw new RangeError("Target requires more margin or a separate decrease-size action");
146
+ while (lo < hi) {
147
+ const mid = (lo + hi + 1n) / 2n;
148
+ if (fits(await candidate(mid))) lo = mid; else hi = mid - 1n;
149
+ }
150
+ }
151
+ return { ...await candidate(lo), targetLeverageBps: target,
152
+ atBorrowingBound: lo === input.maxBorrowAmount, requiresSimulation: true as const };
153
+ }
154
+
155
+ /** Find the smallest sale which fully repays debt while retaining collateral.
156
+ * Same-snapshot, monotone quotes must report internal debt-token output after
157
+ * swap fees, before a possible transfer of unused output to the wallet.
158
+ */
159
+ export async function planLeverageRepayAll(input: {
160
+ collateralAmount: bigint; maxCollateralDebit: bigint; fullRepayCredit: bigint;
161
+ quoteDebtOutput: (collateralDebit: bigint) => Promise<bigint>;
162
+ }) {
163
+ const { collateralAmount, maxCollateralDebit, fullRepayCredit } = input;
164
+ for (const [name, value] of Object.entries({ collateralAmount, maxCollateralDebit, fullRepayCredit })) unsigned(value, name);
165
+ if (fullRepayCredit === 0n || maxCollateralDebit === 0n || maxCollateralDebit >= collateralAmount)
166
+ throw new RangeError("Repay-all requires debt and must leave some collateral");
167
+ let lo = 1n, hi = maxCollateralDebit;
168
+ const quote = async (amount: bigint) => unsigned(await input.quoteDebtOutput(amount), "debtOutput");
169
+ if (await quote(hi) < fullRepayCredit) throw new RangeError("Collateral limit cannot fully repay debt");
170
+ while (lo < hi) { const mid = (lo + hi) / 2n; if (await quote(mid) >= fullRepayCredit) hi = mid; else lo = mid + 1n; }
171
+ const output = await quote(lo);
172
+ return { collateralAmount: lo, minRepayOut: fullRepayCredit,
173
+ maxSurplusOut: output - fullRepayCredit, requiresSimulation: true as const };
174
+ }
175
+
176
+ /** Link a lower whole-position leverage target to the smallest collateral sale.
177
+ * Uses the same sizing-only price basis and fixed-snapshot quote contract as
178
+ * planLeverageIncrease. Exact share repayment determines the refund bound.
179
+ * The supplied maximum must bracket a target-reaching sale; price impact can
180
+ * make a larger endpoint miss even when a smaller sale would work. In that
181
+ * case, narrow the bracket using local quotes rather than inferring insolvency.
182
+ */
183
+ export async function planLeverageDecrease(input: {
184
+ state: LeverageActionState; targetLeverageBps: bigint; maxCollateralDebit: bigint;
185
+ positionShares: bigint; aggregateShares: bigint; borrowIndexNad: bigint;
186
+ quoteDebtOutput: (collateralDebit: bigint) => Promise<bigint>;
187
+ }) {
188
+ const before = leverageActionMetrics(input.state);
189
+ const target = unsigned(input.targetLeverageBps, "targetLeverageBps");
190
+ let lo = 0n, hi = unsigned(input.maxCollateralDebit, "maxCollateralDebit");
191
+ if (before.leverageBps === null || before.debtFree || target < BPS || target >= before.leverageBps || hi >= before.collateralAmount)
192
+ throw new RangeError("Choose a lower leverage of at least 1x and leave some collateral");
193
+ type Candidate = { collateralAmount: bigint; minRepayOut: bigint; maxSurplusOut: bigint;
194
+ after: ReturnType<typeof leverageActionMetrics> };
195
+ const cache = new Map<bigint, Candidate>();
196
+ async function candidate(debit: bigint): Promise<Candidate> {
197
+ const cached = cache.get(debit); if (cached) return cached;
198
+ const output = debit === 0n ? 0n : unsigned(await input.quoteDebtOutput(debit), "debtOutput");
199
+ let repayment;
200
+ try {
201
+ repayment = leverageRepaymentQuote({ ...input, maxCredit: output });
202
+ } catch (error) {
203
+ if (!(error instanceof RangeError) || !error.message.includes("granularity")) throw error;
204
+ repayment = { cashRepaid: 0n, debtRemaining: before.debtAmount, debtReduced: 0n };
205
+ }
206
+ const collateralAmount = before.collateralAmount - debit;
207
+ const result = { collateralAmount: debit, minRepayOut: repayment.cashRepaid, maxSurplusOut: output - repayment.cashRepaid,
208
+ after: leverageActionMetrics({ collateralAmount, debtAmount: repayment.debtRemaining,
209
+ collateralValue: collateralAmount * before.collateralValue / before.collateralAmount }) };
210
+ cache.set(debit, result); return result;
211
+ }
212
+ const reaches = (c: Candidate) => c.minRepayOut > 0n && c.after.equity > 0n && c.after.collateralValue * BPS <= target * c.after.equity;
213
+ if (!reaches(await candidate(hi))) throw new RangeError("Target leverage is not bracketed at this sale limit; try a smaller limit or inspect local quotes");
214
+ while (lo < hi) { const mid = (lo + hi) / 2n; if (reaches(await candidate(mid))) hi = mid; else lo = mid + 1n; }
215
+ return { ...await candidate(lo), targetLeverageBps: target, requiresSimulation: true as const };
216
+ }
@@ -0,0 +1,48 @@
1
+ import type { LeveragePosition } from "./type-aliases.js";
2
+
3
+ const BPS = 10_000n;
4
+ const NAD = 1_000_000_000n;
5
+ const U64_MAX = (1n << 64n) - 1n;
6
+ const ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;
7
+ const min = (a: bigint, b: bigint) => a < b ? a : b;
8
+
9
+ /** Read the position's stored requirements without repricing from live crowding.
10
+ * These rates are not actual equity, a liquidation price, or an executable
11
+ * opening/increase quote. Simulate the intended transaction for new risk.
12
+ */
13
+ export function getStoredLeverageMargins(
14
+ position: Pick<LeveragePosition, "collateralAmount" | "marginTerms">
15
+ ) {
16
+ const collateral = BigInt(position.collateralAmount.toString());
17
+ const terms = position.marginTerms;
18
+ const reference = BigInt(terms.referenceCollateral.toString());
19
+ const retained = BigInt(terms.admissionEquityCollateralNad.toString());
20
+ const [firstBps, secondBps] = terms.maintenanceBoundariesBps;
21
+ const [low, middle, high] = terms.maintenanceRatesBps;
22
+ const buffer = terms.entryBufferBps;
23
+ if (collateral <= 0n || collateral > U64_MAX || reference <= 0n || reference > U64_MAX ||
24
+ retained < 0n || retained >= (1n << 128n) ||
25
+ ![firstBps, secondBps, low, middle, high, buffer].every(Number.isSafeInteger) ||
26
+ firstBps <= 0 || firstBps >= secondBps || secondBps > 65_535 ||
27
+ low <= 0 || low > middle || middle > high || buffer < 0 || high + buffer >= 10_000) {
28
+ throw new Error("Invalid stored leverage margin terms");
29
+ }
30
+ const amount = collateral * BPS;
31
+ const first = reference * BigInt(firstBps);
32
+ const second = reference * BigInt(secondBps);
33
+ const aboveFirst = amount > first ? amount - first : 0n;
34
+ const aboveSecond = amount > second ? amount - second : 0n;
35
+ const weighted = min(amount, first) * BigInt(low)
36
+ + min(aboveFirst, second - first) * BigInt(middle)
37
+ + aboveSecond * BigInt(high);
38
+ const maintenanceMarginBps = Number(ceilDiv(weighted, amount));
39
+ const retainedBps = ceilDiv(retained * BPS, collateral * NAD);
40
+ if (retainedBps >= BPS) throw new Error("Stored admission requirement leaves no leverage capacity");
41
+ const initialMarginBps = Math.max(maintenanceMarginBps + buffer, Number(retainedBps));
42
+ return {
43
+ initialMarginBps,
44
+ maintenanceMarginBps,
45
+ referenceCollateral: reference,
46
+ admissionEquityCollateralNad: retained,
47
+ };
48
+ }
@@ -0,0 +1,86 @@
1
+ import { utils, type Program } from "@coral-xyz/anchor";
2
+ import { PublicKey, type TransactionInstruction } from "@solana/web3.js";
3
+ import { address, type AddressLike } from "./address.js";
4
+ import { leverageActionMetrics } from "./leverage-actions.js";
5
+ import { getStoredLeverageMargins } from "./leverage-margins.js";
6
+ import { simulatePreviewWithContext, type PreviewSimulationOptions } from "./simulation.js";
7
+ import type { LeveragePosition, Market } from "./type-aliases.js";
8
+ import type { Dusk } from "./types_v2.js";
9
+
10
+ export interface PreviewLeverageActionParams extends PreviewSimulationOptions {
11
+ market: AddressLike;
12
+ leveragePosition: AddressLike;
13
+ /** The actual action and optional setup instructions, in execution order.
14
+ * Simulation does not sign, submit, or move funds. Wallet accounts must be
15
+ * funded in the simulated bank, just as for the real transaction. */
16
+ instructions: readonly TransactionInstruction[];
17
+ }
18
+
19
+ /** Authoritative simulation of the complete owner action, including hLP,
20
+ * current interest, mint fees, new admission terms and atomic failure. All
21
+ * returned accounts/events come from the same simulated bank. EMA metrics
22
+ * are explicitly mark valuations, not execution proceeds or liquidation quotes.
23
+ */
24
+ export async function previewLeverageAction(program: Program<Dusk>, params: PreviewLeverageActionParams) {
25
+ const marketKey = address(params.market), positionKey = address(params.leveragePosition);
26
+ const simulation = await simulatePreviewWithContext(program, params.instructions, {
27
+ ...params, accounts: [marketKey, positionKey], innerInstructions: true, requireReturnData: false,
28
+ });
29
+ const [marketInfo, positionInfo] = simulation.value.accounts!;
30
+ if (!marketInfo || marketInfo.owner !== program.programId.toBase58()) throw new Error("Missing Dusk market after simulation");
31
+ const market = program.coder.accounts.decode<Market>("market", Buffer.from(marketInfo.data[0], "base64"));
32
+ let position: LeveragePosition | null = null;
33
+ if (positionInfo && positionInfo.lamports > 0) {
34
+ if (positionInfo.owner !== program.programId.toBase58()) throw new Error("Unexpected simulated position owner");
35
+ position = program.coder.accounts.decode<LeveragePosition>("leveragePosition", Buffer.from(positionInfo.data[0], "base64"));
36
+ if (!position.market.equals(marketKey)) throw new Error("Position belongs to another market");
37
+ }
38
+ const flows = new Map<string, { mint: PublicKey; debit: bigint; credit: bigint }>();
39
+ const flow = (mint: PublicKey, debit: bigint, credit: bigint) => {
40
+ const key = mint.toBase58();
41
+ const old = flows.get(key) ?? { mint, debit: 0n, credit: 0n };
42
+ flows.set(key, { mint, debit: old.debit + debit, credit: old.credit + credit });
43
+ };
44
+ let matched = 0;
45
+ for (const group of simulation.value.innerInstructions ?? []) for (const ix of group.instructions) {
46
+ // RPCs return either explicit program IDs or compiled indexes for inner instructions.
47
+ const raw = ix as unknown as { programId?: string | PublicKey; programIdIndex?: number; data?: string };
48
+ const programId = raw.programId ? new PublicKey(raw.programId)
49
+ : raw.programIdIndex === undefined ? undefined : simulation.accountKeys[raw.programIdIndex];
50
+ if (!programId?.equals(program.programId) || !raw.data) continue;
51
+ const data = Buffer.from(utils.bytes.bs58.decode(raw.data));
52
+ if (data.length < 16 || !data.subarray(0, 8).equals(Buffer.from("e445a52e51cb9a1d", "hex"))) continue;
53
+ const event = program.coder.events.decode(data.subarray(8).toString("base64"));
54
+ const value = event?.data as Record<string, unknown> | undefined;
55
+ if (!event || !value || !(value.position instanceof PublicKey) || !value.position.equals(positionKey)) continue;
56
+ if (!(value.market instanceof PublicKey) || !value.market.equals(marketKey)) throw new Error("Mismatched leverage event market");
57
+ const amount = (field: string) => BigInt(String(value[field] ?? 0));
58
+ if (event.name === "leveragePositionUpdated") {
59
+ flow(value.debtAssetMint as PublicKey, amount("ownerDebit"), amount("ownerCredit")); matched++;
60
+ } else if (event.name === "leveragePositionClosed") {
61
+ flow(value.debtAssetMint as PublicKey, 0n, amount("residual")); matched++;
62
+ } else if (event.name === "debtFreePositionClosed") {
63
+ flow(market.baseSide.assetMint, 0n, amount("baseReceived"));
64
+ flow(market.quoteSide.assetMint, 0n, amount("quoteReceived")); matched++;
65
+ }
66
+ }
67
+ if (!matched) throw new Error("RPC did not return the position action's CPI events; cannot quote wallet cash flows");
68
+ let metrics = null;
69
+ if (position) {
70
+ const debtIsBase = position.debtAsset === 0;
71
+ const heldSide = debtIsBase ? market.quoteSide : market.baseSide;
72
+ const debtSide = debtIsBase ? market.baseSide : market.quoteSide;
73
+ const price = BigInt((debtIsBase ? market.risk.quotePriceEmaNad : market.risk.basePriceEmaNad).toString());
74
+ const index = BigInt((debtIsBase ? market.debt.baseBorrowIndexNad : market.debt.quoteBorrowIndexNad).toString());
75
+ const collateralAmount = BigInt(position.collateralAmount.toString());
76
+ const collateralValue = collateralAmount * price * 10n ** BigInt(debtSide.assetDecimals)
77
+ / (1_000_000_000n * 10n ** BigInt(heldSide.assetDecimals));
78
+ metrics = leverageActionMetrics({ collateralAmount, collateralValue,
79
+ debtAmount: BigInt(position.debtShares.toString()) * index / 1_000_000_000n });
80
+ }
81
+ return { slot: simulation.context.slot, observedAt: simulation.observedAt,
82
+ unitsConsumed: simulation.value.unitsConsumed, logs: simulation.value.logs,
83
+ market, position, closed: position === null, walletFlows: [...flows.values()],
84
+ priceBasis: "symmetric-ema" as const, metrics,
85
+ marginTerms: position ? getStoredLeverageMargins(position) : null };
86
+ }