@omnipair/dusk-sdk 2.0.1 → 2.16.0-next.20261102

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 (192) hide show
  1. package/README.md +1085 -26
  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 +80 -33
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +175 -64
  9. package/dist/constants.js.map +1 -1
  10. package/dist/delegate.d.ts +94 -0
  11. package/dist/delegate.d.ts.map +1 -0
  12. package/dist/delegate.js +131 -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 +3285 -237
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +140 -71
  21. package/dist/get.js.map +1 -1
  22. package/dist/governance-client.d.ts +169 -0
  23. package/dist/governance-client.d.ts.map +1 -0
  24. package/dist/governance-client.js +146 -0
  25. package/dist/governance-client.js.map +1 -0
  26. package/dist/governance.d.ts +313 -0
  27. package/dist/governance.d.ts.map +1 -0
  28. package/dist/governance.js +902 -0
  29. package/dist/governance.js.map +1 -0
  30. package/dist/hash.d.ts +9 -0
  31. package/dist/hash.d.ts.map +1 -0
  32. package/dist/hash.js +16 -0
  33. package/dist/hash.js.map +1 -0
  34. package/dist/hlp-liquidation-client.d.ts +106 -0
  35. package/dist/hlp-liquidation-client.d.ts.map +1 -0
  36. package/dist/hlp-liquidation-client.js +150 -0
  37. package/dist/hlp-liquidation-client.js.map +1 -0
  38. package/dist/idl_delegate.d.ts +3 -0
  39. package/dist/idl_delegate.d.ts.map +1 -0
  40. package/dist/idl_delegate.js +3 -0
  41. package/dist/idl_delegate.js.map +1 -0
  42. package/dist/idl_delegate.json +6119 -0
  43. package/dist/idl_v2.json +18372 -6121
  44. package/dist/index.d.ts +23 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +23 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interest-accounting.d.ts +49 -0
  49. package/dist/interest-accounting.d.ts.map +1 -0
  50. package/dist/interest-accounting.js +72 -0
  51. package/dist/interest-accounting.js.map +1 -0
  52. package/dist/leverage-actions.d.ts +122 -0
  53. package/dist/leverage-actions.d.ts.map +1 -0
  54. package/dist/leverage-actions.js +228 -0
  55. package/dist/leverage-actions.js.map +1 -0
  56. package/dist/leverage-margins.d.ts +12 -0
  57. package/dist/leverage-margins.d.ts.map +1 -0
  58. package/dist/leverage-margins.js +45 -0
  59. package/dist/leverage-margins.js.map +1 -0
  60. package/dist/leverage-preview.d.ts +587 -0
  61. package/dist/leverage-preview.d.ts.map +1 -0
  62. package/dist/leverage-preview.js +89 -0
  63. package/dist/leverage-preview.js.map +1 -0
  64. package/dist/liquidation-client.d.ts +230 -0
  65. package/dist/liquidation-client.d.ts.map +1 -0
  66. package/dist/liquidation-client.js +239 -0
  67. package/dist/liquidation-client.js.map +1 -0
  68. package/dist/liquidation.d.ts +78 -0
  69. package/dist/liquidation.d.ts.map +1 -0
  70. package/dist/liquidation.js +122 -0
  71. package/dist/liquidation.js.map +1 -0
  72. package/dist/lp-naming.d.ts +43 -0
  73. package/dist/lp-naming.d.ts.map +1 -0
  74. package/dist/lp-naming.js +81 -0
  75. package/dist/lp-naming.js.map +1 -0
  76. package/dist/lp-vanity.d.ts +33 -0
  77. package/dist/lp-vanity.d.ts.map +1 -0
  78. package/dist/lp-vanity.js +94 -0
  79. package/dist/lp-vanity.js.map +1 -0
  80. package/dist/market-bootstrap.d.ts +109 -0
  81. package/dist/market-bootstrap.d.ts.map +1 -0
  82. package/dist/market-bootstrap.js +158 -0
  83. package/dist/market-bootstrap.js.map +1 -0
  84. package/dist/market-launch.d.ts +45 -0
  85. package/dist/market-launch.d.ts.map +1 -0
  86. package/dist/market-launch.js +76 -0
  87. package/dist/market-launch.js.map +1 -0
  88. package/dist/oracle.d.ts +46 -0
  89. package/dist/oracle.d.ts.map +1 -0
  90. package/dist/oracle.js +103 -0
  91. package/dist/oracle.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/referral.d.ts +28 -28
  101. package/dist/referral.d.ts.map +1 -1
  102. package/dist/referral.js +41 -33
  103. package/dist/referral.js.map +1 -1
  104. package/dist/risk-pricing.d.ts +14 -0
  105. package/dist/risk-pricing.d.ts.map +1 -0
  106. package/dist/risk-pricing.js +25 -0
  107. package/dist/risk-pricing.js.map +1 -0
  108. package/dist/simulation.d.ts +45 -0
  109. package/dist/simulation.d.ts.map +1 -0
  110. package/dist/simulation.js +106 -0
  111. package/dist/simulation.js.map +1 -0
  112. package/dist/tranche-client.d.ts +121 -0
  113. package/dist/tranche-client.d.ts.map +1 -0
  114. package/dist/tranche-client.js +185 -0
  115. package/dist/tranche-client.js.map +1 -0
  116. package/dist/transfer-fees.d.ts +46 -0
  117. package/dist/transfer-fees.d.ts.map +1 -0
  118. package/dist/transfer-fees.js +76 -0
  119. package/dist/transfer-fees.js.map +1 -0
  120. package/dist/type-aliases.d.ts +271 -30
  121. package/dist/type-aliases.d.ts.map +1 -1
  122. package/dist/types_delegate.d.ts +6126 -0
  123. package/dist/types_delegate.d.ts.map +1 -0
  124. package/dist/types_delegate.js +2 -0
  125. package/dist/types_delegate.js.map +1 -0
  126. package/dist/types_v2.d.ts +18105 -5854
  127. package/dist/types_v2.d.ts.map +1 -1
  128. package/dist/virtual-book/index.d.ts +4 -0
  129. package/dist/virtual-book/index.d.ts.map +1 -0
  130. package/dist/virtual-book/index.js +4 -0
  131. package/dist/virtual-book/index.js.map +1 -0
  132. package/dist/virtual-book/market.d.ts +608 -0
  133. package/dist/virtual-book/market.d.ts.map +1 -0
  134. package/dist/virtual-book/market.js +59 -0
  135. package/dist/virtual-book/market.js.map +1 -0
  136. package/dist/virtual-book/projection.d.ts +44 -0
  137. package/dist/virtual-book/projection.d.ts.map +1 -0
  138. package/dist/virtual-book/projection.js +229 -0
  139. package/dist/virtual-book/projection.js.map +1 -0
  140. package/dist/virtual-book/quotes.d.ts +1241 -0
  141. package/dist/virtual-book/quotes.d.ts.map +1 -0
  142. package/dist/virtual-book/quotes.js +233 -0
  143. package/dist/virtual-book/quotes.js.map +1 -0
  144. package/dist/write.d.ts +584 -14
  145. package/dist/write.d.ts.map +1 -1
  146. package/dist/write.js +1371 -47
  147. package/dist/write.js.map +1 -1
  148. package/dist/yield-client.d.ts +51 -0
  149. package/dist/yield-client.d.ts.map +1 -0
  150. package/dist/yield-client.js +98 -0
  151. package/dist/yield-client.js.map +1 -0
  152. package/package.json +9 -2
  153. package/src/amounts.ts +13 -0
  154. package/src/constants.ts +276 -111
  155. package/src/delegate.ts +238 -0
  156. package/src/dusk.ts +28 -0
  157. package/src/get.ts +267 -90
  158. package/src/governance-client.ts +234 -0
  159. package/src/governance.ts +1422 -0
  160. package/src/hash.ts +15 -0
  161. package/src/hlp-liquidation-client.ts +195 -0
  162. package/src/idl_delegate.json +6119 -0
  163. package/src/idl_delegate.ts +3 -0
  164. package/src/idl_v2.json +18372 -6121
  165. package/src/index.ts +31 -0
  166. package/src/interest-accounting.ts +85 -0
  167. package/src/leverage-actions.ts +216 -0
  168. package/src/leverage-margins.ts +48 -0
  169. package/src/leverage-preview.ts +86 -0
  170. package/src/liquidation-client.ts +297 -0
  171. package/src/liquidation.ts +137 -0
  172. package/src/lp-naming.ts +127 -0
  173. package/src/lp-vanity.ts +135 -0
  174. package/src/market-bootstrap.ts +273 -0
  175. package/src/market-launch.ts +103 -0
  176. package/src/oracle.ts +120 -0
  177. package/src/preview.ts +53 -1
  178. package/src/protection.ts +112 -0
  179. package/src/referral.ts +71 -71
  180. package/src/risk-pricing.ts +28 -0
  181. package/src/simulation.ts +169 -0
  182. package/src/tranche-client.ts +187 -0
  183. package/src/transfer-fees.ts +99 -0
  184. package/src/type-aliases.ts +280 -30
  185. package/src/types_delegate.ts +6125 -0
  186. package/src/types_v2.ts +18372 -6121
  187. package/src/virtual-book/index.ts +3 -0
  188. package/src/virtual-book/market.ts +76 -0
  189. package/src/virtual-book/projection.ts +265 -0
  190. package/src/virtual-book/quotes.ts +308 -0
  191. package/src/write.ts +2394 -67
  192. package/src/yield-client.ts +117 -0
package/README.md CHANGED
@@ -1,6 +1,146 @@
1
1
  # @omnipair/dusk-sdk
2
2
 
3
- TypeScript SDK for Omnipair Dusk (v2).
3
+ For volume, fee, and borrower-interest consumers, see the
4
+ [accounting event contract](../../programs/dusk/ACCOUNTING_EVENTS.md).
5
+ `SwapExecuted` covers spot and leverage AMM executions and the market state they
6
+ leave behind. `BorrowInterestAccrued`
7
+ separates credit, margin, and hLP accrual; `BorrowInterestPaid` reports actual
8
+ collections with the same source attribution. Typed events and their
9
+ `SwapOrigin`/`DebtSource` discriminants are exported from this package.
10
+
11
+ TypeScript SDK for Dusk, the Omnipair V2 protocol architecture. This package
12
+ targets Dusk market layout 8, including bounded oracle policies, aggregate leverage exposure and stored
13
+ position margin terms. Regenerate clients and use matching account layouts.
14
+
15
+ ## Bounded oracle markets
16
+
17
+ Market creation selects native or oracle-guided pricing in the same
18
+ `initializeMarket` instruction. In the SDK, omit `oracle` (or pass `null`) for
19
+ native pricing at λ = 0; pass an `OraclePolicyInput` to launch with that policy:
20
+
21
+ ```typescript
22
+ const instruction = await dusk.write.initializeMarketInstruction({
23
+ ...creationParams,
24
+ oracle: policy, // omit or use null for native pricing
25
+ });
26
+ ```
27
+
28
+ The creator does not send a separate oracle-configuration instruction. Creation
29
+ validates and stores the policy atomically with the market and its LP metadata;
30
+ `MarketCreated.oracle` reports the selected policy. Creation needs no live feed
31
+ account. First liquidity and subsequent price-sensitive operations authenticate
32
+ a current report when λ is positive. An invalid initial policy rolls back market
33
+ creation and the treasury creation charge.
34
+
35
+ Guided creation has no independent opening price: omit `bootstrapPriceNad` or
36
+ pass zero. The SDK and program reject a nonzero value when λ is positive.
37
+ `addLiquidityInstruction` takes two maximum gross spends. On the first guided
38
+ deposit the validated execution-time report sets their usable ratio; base is
39
+ rounded down and quote up to token atoms, and unused tokens stay in the owner's
40
+ wallet. The existing `minYlpAmount` floor still applies. Native first deposits
41
+ keep their caller-selected ratio, and subsequent deposits remain proportional
42
+ to existing reserves. The first-deposit change preserves all wire layouts.
43
+
44
+ Every market can later activate an oracle, change its source/weight/cap, or return
45
+ to native pricing through the existing parameter-proposal lifecycle.
46
+ `parameterUpdate.oracle(policy)` creates the proposal update. Subsequent changes
47
+ require governance, including before first liquidity; no creator-only setter
48
+ remains. `oraclePolicy()` validates the wire format. Positive weights are
49
+ 1–9,999 bps and a nonempty policy's adjustment multiplier must exceed one;
50
+ there are no creation-time oracle ceilings or automatic outage-driven changes.
51
+ See [the implementation contract](../../docs/OP_GAMM_IMPLEMENTATION_STATUS.md)
52
+ for the coupled swap, lending and hLP behavior.
53
+
54
+ Use `marketCreationLookupTablePlan` and `marketCreationV0Transaction` for the
55
+ creation transaction. The latter rejects a packet larger than 1,232 bytes;
56
+ metadata and optional setup instructions must fit alongside the selected policy.
57
+ An address lookup table compresses account addresses, not metadata or policy
58
+ bytes. The launch scripts accept optional `DUSK_ORACLE_POLICY_JSON` using
59
+ `OraclePolicyInput` field names (base58 addresses, 32-byte feed-ID arrays and
60
+ string values for large integers); omission selects native pricing. They resolve
61
+ the stored policy's feeds and compute budget when seeding liquidity.
62
+
63
+ Raw Anchor callers must include `oracle: null` or a serialized policy. The
64
+ `initializeMarket` argument layout now starts with `paramsHash`, followed by
65
+ `config` and `oracle`; rebuild instruction encoders and event decoders using the
66
+ vendored IDL. The removed `configureInitialOracle` instruction and
67
+ `InitialOracleConfigured` event are replaced by creation parameters and
68
+ `MarketCreated.oracle`.
69
+
70
+ Provider and feed layout are independent: normalized direct pair
71
+ (`NORMALIZED_ORACLE_V1`, format 1), fully verified Pyth ratio (`PYTH_RATIO_V2`, 2),
72
+ fully verified Pyth direct pair (`PYTH_DIRECT_V3`, 3), or normalized ratio
73
+ (`NORMALIZED_RATIO_V4`, 4). One feed must actually quote the ordered market pair;
74
+ META/USD alone is not META/USDC. Two feeds must share a denomination and include
75
+ an observed quote-asset price. Ratio uncertainty is rounded outward and each leg
76
+ is authenticated and checked for age and publication skew. Layout 8 stores
77
+ per-leg counters/content hashes so independent updates cannot hide normalized
78
+ report equivocation or rollback. Do not decode layout-7 accounts with this SDK.
79
+ A market selects the provider, feed identities, age and confidence policy. The normalized provider
80
+ must serialize the exact Borsh `NormalizedOracleV1` envelope defined in
81
+ [oracle.rs](../../programs/dusk/src/oracle.rs), including the underlying source
82
+ observation time, both mints and a monotonically increasing nonzero sequence.
83
+ Dusk does not fetch an off-chain report or give Horus special authority.
84
+
85
+ High-level builders fetch the policy and append feed accounts after the existing
86
+ hLP/hook prefix. Positive-weight transaction builders add the compute and heap
87
+ budgets. When composing **raw instructions**, add
88
+ `oracleComputeBudgetInstructions(policy)` once before constructing any
89
+ index-bound flash plan; do not prepend instructions after binding its indices.
90
+ Resolve `oracleReadAccounts(policy)` for direct Anchor calls. Zero weight needs
91
+ neither feed accounts nor OP budgets. Simulate the whole transaction, including
92
+ any provider update and callback: a passing isolated price calculation does not
93
+ establish route feasibility.
94
+
95
+ A stale or invalid source rejects price-sensitive operations. Direct repayment
96
+ in the debt token and adding collateral remain possible without a valid price;
97
+ this does not permit a collateral sale or removal. Oracle updates change the
98
+ market reference but do not execute an hLP hedge by themselves.
99
+
100
+ ## Protocol revenue defaults
101
+
102
+ `DEFAULT_PROTOCOL_REVENUE_SHARE_BPS` is exported from the generated program IDL.
103
+ Its initial value is 2,000 bps (20%): the protocol share of base swap fees,
104
+ paid borrowing/leverage/hLP interest, and liquidation fees. Dynamic swap
105
+ surcharges remain excluded. Liquidation's total charge is still 1% of net debt
106
+ repaid, subject to available surplus; the shared constant sets the protocol's
107
+ share of that charge.
108
+
109
+ `initFutarchyAuthority` now accepts nullable `swapBps` and `interestBps`. Pass
110
+ `null` for the program default, or a number for an explicit override, including
111
+ zero. Governance can subsequently change either share and the auction split.
112
+ The bootstrap script uses the program defaults when `DUSK_PROTOCOL_SWAP_BPS` and
113
+ `DUSK_PROTOCOL_INTEREST_BPS` are unset. Regenerate clients for this instruction change.
114
+ Changing the Rust default affects new authorities and liquidation allocations;
115
+ existing authorities retain their configured swap and interest shares.
116
+
117
+ The initial auction split remains 100% fee auctions / 0% buybacks. Referral
118
+ commissions come out of the protocol interest share before the auction split.
119
+ The separate voluntary-order service charge and flat market-creation charge
120
+ are not revenue-share percentages and are outside this default.
121
+
122
+ ## Stored leverage margins
123
+
124
+ ```typescript
125
+ import { getStoredLeverageMargins } from "@omnipair/dusk-sdk";
126
+
127
+ const position = await dusk.get.leveragePosition(positionAddress);
128
+ const { initialMarginBps, maintenanceMarginBps } = getStoredLeverageMargins(position);
129
+ // Or fetch and decode in one call:
130
+ const margins = await dusk.get.leverageMargins(positionAddress);
131
+ ```
132
+
133
+ The helper reads the saved terms and applies the same conservative rate rounding
134
+ as Rust. It does not recalculate an existing position from live market crowding.
135
+ `admissionEquityCollateralNad` is collateral atoms times 1e9, not dollars or
136
+ debt-token atoms. These are required margin rates, not actual equity or an
137
+ executable leverage quote. Price and interest still change health. Simulate the
138
+ complete proposed transaction for openings, increases and withdrawals; executable
139
+ equity, cash and Token-2022 fees can impose tighter constraints.
140
+
141
+ `LeveragePositionOpened` and `LeveragePositionUpdated` include `marginTerms`.
142
+ Indexers should retain those fields per position and replace them on subsequent
143
+ position updates, rather than deriving old-position terms from current liquidity.
4
144
 
5
145
  A `Dusk` instance is an enriched Anchor program facade. It exposes the raw
6
146
  Anchor program through `dusk.program`, alongside typed on-chain reads and
@@ -11,6 +151,124 @@ The package exports the generated Anchor IDL/types, PDA helpers, typed preview
11
151
  decoders, a small write/read facade over the Dusk program, and an indexer client
12
152
  for historical API data.
13
153
 
154
+ ## Flash and emergency liquidations
155
+
156
+ `get.simulateWithContext(plan.instructions, { requireReturnData: false, lookupTables })`
157
+ preserves the absolute begin/settle indices in a built flash plan. Existing
158
+ compute budgets are retained (or explicitly overridden in place). A flash plan
159
+ missing either budget is rejected rather than silently shifted. Ordinary
160
+ previews receive a budget prefix. Set `preserveInstructionIndices: true` for
161
+ other programs with index-bound plans. Do not prepend instructions after `buildFlash`; pass
162
+ setup instructions through its `prefixInstructions` argument instead.
163
+
164
+ The auction start/fill/backstop and old full leverage-liquidation instructions
165
+ have been replaced. Use `dusk.liquidations` for either borrowing or leverage:
166
+
167
+ ```typescript
168
+ const position = { market, position: positionAddress, kind: "leverage" as const,
169
+ debtAsset: "quote" as const };
170
+ // Read-only simulation; no registration transaction is required.
171
+ const health = await dusk.liquidations.previewHealth(position);
172
+ const quote = await dusk.liquidations.preview({ ...position, maxRepayment: 1_000_000n });
173
+ const plan = await dusk.liquidations.buildFlash({
174
+ ...position, buyer, maxRepayment: 1_000_000n,
175
+ route: async (ctx) => {
176
+ // Return instructions that sell collateral or pay from buyer inventory.
177
+ // Deliver ctx.requiredPaymentCredit NET into ctx.repaymentVault.
178
+ // grossLiquidationPayment() handles the incoming token transfer fee.
179
+ return buildPaymentRoute(ctx);
180
+ },
181
+ });
182
+ // Compile plan.instructions unchanged, using flashLiquidationV0Transaction()
183
+ // with the necessary address lookup tables, then simulate, sign and submit.
184
+ ```
185
+
186
+ `settlement: "duskAmm"` instead sells the flashed collateral in the paired settle,
187
+ with debt principal netted internally and no escrow-payment instruction. The
188
+ buyer must retain the flashed collateral until settle. Its return transfer can
189
+ incur another collateral token fee. Settlement rejects an AMM quote that cannot
190
+ fund the fixed obligation; it never silently debits the owner's wallet.
191
+ If the route changes active hLP accounts, pass the complete final-state account
192
+ list through `settleRemainingAccounts`; the default resolves the current market.
193
+
194
+ `previewEmergency()` and `buildEmergency()` accept `collateralDebit` and `full`.
195
+
196
+ Emergency internal settlement uses **symmetric EMA price and smoothed curve depth**,
197
+ with the market's concentration. Both preview and settlement report
198
+ `referencePriceNad` (debt per collateral at 1e9 scale) and `referenceDepthNad` (normalized
199
+ curve depth, not TVL). `buildEmergency()` also returns these as bigint
200
+ `reference.priceNad` / `reference.depthNad`. `swapOutput` is the debt value credited
201
+ by this inventory settlement; it is not a live-spot execution quote. The pool
202
+ receives real collateral and reduces the loan, with funded cash payouts and real
203
+ hLP reconciliation. Normal flash routes, including `settlement: "duskAmm"`, retain
204
+ their venue's executable quotes.
205
+
206
+ The full fee schedule remains: launch price and divergence use the reference
207
+ curve; volatility uses the existing accumulator and decay. Thus changed fee
208
+ history can change net proceeds even when price/depth EMAs are unchanged. Live
209
+ spot/depth are not substituted into reference sizing or its full-close proof.
210
+ Use a fresh preview and simulate the complete transaction. The returned reference
211
+ is not a lock; the builder's minimum-output/reward arguments still apply.
212
+
213
+ They enforce the emergency EMA-health gate (equity at or below 70% of MM).
214
+ A full reference-priced settlement needs nonpositive EMA equity or the program's conservative proof
215
+ that no smaller reference-priced settlement can restore MM +2 percentage points after all costs.
216
+ A useful below-target partial or an external flash opportunity does not veto
217
+ this fallback. Full normal swap fees, rewards and loss accounting still apply.
218
+ Failure to certify, including proof-budget exhaustion, rejects full closure.
219
+ Smaller improving fills remain available. Preview and simulate the intended
220
+ operation: a failed slice is not full-close permission. There is no configurable
221
+ minimum remaining debt.
222
+
223
+ Ordinary `preview({ full: true })` / `buildFlash({ full: true })` retain the
224
+ stricter no-improving-partial certificate. An accepted full `previewEmergency`
225
+ quote does not authorize a full ordinary flash fill. Both builders use their
226
+ respective on-chain previews; do not infer permission from the incentive helper.
227
+
228
+ Builders return unsigned instructions and owner-owned payout accounts. Prefix
229
+ instructions belong in the builder request: inserting instructions afterwards
230
+ invalidates the bound settle index. Helpers include ATA setup, a 256 KiB heap,
231
+ a 1.4M compute-unit limit and required hLP accounts. A compute-unit limit supplied
232
+ in the prefix overrides the default; set the priority price there as needed.
233
+ The session closes at settle. Its payment token account persists for reuse,
234
+ including withheld Token-2022 fees; preexisting token donations do not count as
235
+ payment and are not refunded to the next buyer.
236
+
237
+ The 0.5%–5% ramp sets a maximum buyer discount. Partial quotes choose the highest
238
+ whole-basis-point discount within that range that improves health after the
239
+ 1% repayment charge and collateral transfer costs. If none works, the partial
240
+ rejects. Read the actual rate from `quote.rates.buyerDiscountBps`; use
241
+ `liquidationIncentives(...).maximumBuyerDiscountBps` only for the ceiling. The
242
+ legacy helper field `buyerDiscountBps` remains a deprecated alias for that ceiling.
243
+ Position-health previews also report the ceiling, not an executable purchase.
244
+
245
+ Market creation has no minimum remaining-debt setting. Partial `maxRepayment`
246
+ requests retain at least one debt share; small remainders are allowed when the
247
+ fill improves health. A request beyond the first MM+2 recovery crossing rejects;
248
+ request a smaller amount. Emergency collateral slices also respect health
249
+ improvement and a conservative recovery cap. The bound includes base swap fees and
250
+ checks surviving AMM amounts against actual execution costs. A bounded search
251
+ can still refuse a target crossing when it cannot certify the result;
252
+ useful below-target slices remain permitted. Preview acceptance does not reserve
253
+ liquidity or guarantee keeper profitability. Simulate the complete transaction.
254
+
255
+ `liquidationHealth`, `liquidationIncentives`, `liquidationFeeAllocation`,
256
+ `liquidationInsuranceTarget`, and `liquidationLossAllocation` use integer atoms
257
+ and mirror the policy arithmetic. They do not replace the on-chain execution
258
+ preview. Incentives depend only on current health; there is no time ramp or
259
+ stored distress episode. `liquidationIncentives` takes only the health input.
260
+
261
+ Indexers should consume `FlashLiquidationBegun`, `FlashLiquidationSettled`,
262
+ `EmergencyLiquidationSettled`. AMM settlement also emits
263
+ `SwapExecuted`; external purchases do not generate Dusk swap volume. For emergency
264
+ settlement, its start price/output describe the reference-priced debt offset;
265
+ its final reserve/spot snapshots describe the actual pool. Correlate it with
266
+ `EmergencyLiquidationSettled` rather than treating it as a live execution quote. Collected
267
+ interest retains `BorrowInterestPaid`/referral events. A terminal settlement
268
+ clears the debt leg but leaves position rent to the existing owner cleanup path.
269
+ `previewBorrowPosition` reports `liquidationHealth`, `liquidationRates` and
270
+ `liquidationDistress`; obsolete auction penalty and repayment-cap fields are gone.
271
+
14
272
  ## Install
15
273
 
16
274
  ```bash
@@ -26,7 +284,7 @@ import { AnchorProvider } from "@coral-xyz/anchor";
26
284
  import { Connection } from "@solana/web3.js";
27
285
  import { Dusk } from "@omnipair/dusk-sdk";
28
286
 
29
- const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed");
287
+ const connection = new Connection(process.env.SOLANA_RPC_URL!, "confirmed");
30
288
  const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });
31
289
 
32
290
  const dusk = new Dusk({
@@ -44,13 +302,13 @@ The client is intentionally split by source of truth:
44
302
  ## Write Instructions
45
303
 
46
304
  ```typescript
47
- const ix = await dusk.write.instruction(
48
- "swap",
305
+ const ix = await dusk.write.swapInstruction(
49
306
  {
50
307
  exactAssetIn: amountIn,
51
308
  minAssetOut: minAmountOut,
52
309
  },
53
310
  {
311
+ market,
54
312
  accounts: {
55
313
  market,
56
314
  futarchyAuthority,
@@ -59,38 +317,343 @@ const ix = await dusk.write.instruction(
59
317
  assetOutMint,
60
318
  reserveInVault,
61
319
  reserveOutVault,
62
- feeInVault,
63
320
  traderAssetInAccount,
64
321
  traderAssetOutAccount,
65
322
  tokenProgram,
66
323
  token2022Program,
67
- eventAuthority,
68
- program: dusk.program.programId,
69
324
  },
70
325
  }
71
326
  );
72
327
  ```
73
328
 
329
+ `swapBuilder(...)`, `swapInstruction(...)`, `swapTransaction(...)`, and
330
+ `swapRpc(...)` fetch the market before building the swap. Whenever either hLP
331
+ side has nonzero supply or residual exposure, they prepend the canonical
332
+ five-account prefix exactly once: `[yLP mint, base hLP yLP vault, quote hLP yLP
333
+ vault, base interest vault, quote interest vault]`. Caller-provided remaining
334
+ accounts remain after that prefix.
335
+
336
+ The write client supplies the canonical event-CPI authority and Dusk program
337
+ accounts for instructions that emit CPI events.
338
+
74
339
  `write.builder(...)`, `write.transaction(...)`, and `write.rpc(...)` expose the
75
340
  same generic path for every Dusk instruction in the IDL.
76
341
 
77
- ### Referral Origination Fees
342
+ ### Leverage funding
343
+
344
+ Leverage positions accept margin only in the debt token: USDC for a META long,
345
+ META for a META short. `buildOpenLeverageInstruction` swaps the credited margin
346
+ plus borrowing into the opposite token held as collateral. `closeLeverageInstruction`
347
+ sells exposure, repays the debt and returns the residual in the debt token.
348
+ An application can swap a different wallet token into the required funding token
349
+ before opening; the protocol has no optional collateral-funded mode.
350
+
351
+ ### Position actions
352
+
353
+ See [the position action contract](../../docs/LEVERAGE_POSITION_ACTIONS.md) for
354
+ amount units, rounding and the six agreed controls. All sizing is in the debt
355
+ token on both market directions; neither token needs to be a stablecoin.
356
+
357
+ - `increaseLeverageInstruction`: borrow and buy, with no wallet funding.
358
+ - `addToLeverageInstruction`: swap `marginAmount` (gross debt-token funding) plus
359
+ `debtAmount` into held collateral. Select leverage for the whole resulting
360
+ position; `planLeverageIncrease` defaults to its current leverage.
361
+ - `addLeverageMarginInstruction` / `repayLeverageInstruction`: repay debt without
362
+ swapping held collateral. No standalone margin withdrawal is supported.
363
+ - `decreaseLeverageInstruction`: sell collateral into repayment, including full
364
+ repayment to 1x. `maxSurplusOut` defaults to zero and explicitly bounds any
365
+ gross surplus returned to the owner's debt-token account.
366
+ - `closeLeverageInstruction`: `closeBps` selects a proportional owner partial
367
+ close; omit it for a full close. `minAmountOut` is net wallet receipt.
368
+
369
+ `leverageActionMetrics`, `planLeverageIncrease`, `planLeverageDecrease`,
370
+ `planLeverageRepayAll`, `leverageRepaymentQuote`, `leverageCloseSlice` and
371
+ `leverageClosePercentage` support linked controls with bigint arithmetic.
372
+ Sizing callbacks must use same-snapshot, fee-adjusted internal quotes. For a
373
+ final executable check, simulate the actual action:
374
+
375
+ ```ts
376
+ const ix = await dusk.write.addToLeverageInstruction({
377
+ ...positionAccounts,
378
+ ownerDebtAccount,
379
+ marginAmount: 100_000_000n,
380
+ debtAmount: 200_000_000n,
381
+ minCollateralOut,
382
+ });
383
+ const preview = await dusk.get.previewLeverageAction({
384
+ market, leveragePosition, instructions: [ix], feePayer: owner,
385
+ });
386
+ // Review preview.walletFlows, preview.metrics, and preview.marginTerms.
387
+ // Simulation never submits or signs the transaction.
388
+ ```
389
+
390
+ Metrics returned by this preview use the symmetric EMA, before any hypothetical
391
+ liquidation costs. They are not executable close payout or liquidation eligibility;
392
+ the actual action's wallet flows come from its simulated settlement events.
393
+
394
+
395
+ ### Swap and LP Transfer Events
78
396
 
79
- A referrer first designates the wallet that may receive claimed fees:
397
+ `SwapExecuted` records the market immediately after a completed trade: the
398
+ internal yLP supply and, per side, a `MarketSideSnapshot` with the spot price
399
+ and price EMA exactly as `preview_market` reports them for the same state and
400
+ slot, plus the swap-fee and interest growth indexes. `start_price_nad` is the
401
+ Base price actually used to quote that trade, after any pending controller
402
+ step. Swap events provide historical execution and post-swap observations;
403
+ they are not a continuous live-price feed. For a prospective quote, use
404
+ `preview_swap` with the intended input and current state rather than treating
405
+ the last event's post-swap spot as the next trade's starting price.
406
+
407
+ `LpTransferred` reports each yLP or hLP transfer through the Dusk transfer
408
+ hook as an ordinary CPI event. `buildLpTransferHookAccountMetas` includes the
409
+ event authority the hook needs; Token-2022 ignores it for mints initialized
410
+ with the earlier seven-entry list, which transfer without a receipt.
411
+ `buildLpTransferHookValidationAccountData({ ..., legacyLayout: true })`
412
+ encodes that earlier list.
413
+
414
+ ### Optional insurance funding
415
+
416
+ Markets can start with zero insurance. A voluntary top-up uses the existing
417
+ `fortify_market` instruction; it is a donation and does not mint LP shares or
418
+ give the donor a withdrawal claim.
419
+
420
+ ```typescript
421
+ const topUp = await dusk.write.fortifyMarketInstruction({
422
+ donor: wallet.publicKey,
423
+ market,
424
+ asset: "quote",
425
+ assetMint: quoteMint,
426
+ amount: 1_000_000n, // Gross raw token atoms, not a USD amount.
427
+ // Optional: assetTokenProgram avoids the mint-owner RPC read.
428
+ // Optional: donorAssetAccount overrides the donor's default ATA.
429
+ });
430
+ ```
431
+
432
+ The builder does not fetch the market, so it can be appended after market
433
+ initialization, subject to the transaction's account, size and compute limits.
434
+ The donor's source token account must already exist. SPL Token and Token-2022
435
+ are supported; insurance accounting records the net amount actually received
436
+ after any transfer fee. `fortifyMarketTransaction(...)` wraps the same
437
+ instruction in a transaction without signing or sending it.
438
+
439
+ ### Direct-yLP Parameter Governance
440
+
441
+ Market layout v2 has no market manager. The program exposes eight independent
442
+ parameter families: Fee, Concentration, IRM, EMA Half-Lives, Daily Borrow
443
+ Limit, Center Controller, Insurance, and Oracle. A direct yLP holder burn-locks at least
444
+ 1% of eligible direct yLP to create a typed proposal. Strictly more than 50%
445
+ support queues it for a 7-day timelock and a 7-day execution window. Execution
446
+ is permissionless. Proposals containing exactly one Oracle update can restore
447
+ pricing despite distress or high utilization; positive weight still verifies a
448
+ fresh proposed source. Every other proposal, including mixed Oracle proposals,
449
+ requires both lending sides below 80% utilization and adequate market health.
450
+ Support thresholds, timelock, and execution window apply to every proposal.
451
+
452
+ Use the typed update constructors so values are checked against the same hard
453
+ bounds before an instruction is built:
454
+
455
+ ```typescript
456
+ import {
457
+ concentrationParameterUpdate,
458
+ uploadProposalMetadata,
459
+ } from "@omnipair/dusk-sdk";
460
+
461
+ const update = concentrationParameterUpdate({
462
+ // 20x center depth versus the reserve-matched CPMM.
463
+ peakAmplificationNad: 20n * 1_000_000_000n,
464
+ // Full peak depth inside ±100 bps, then one 400-bps shoulder.
465
+ coreHalfWidthBps: 100,
466
+ fadeWidthBps: 400,
467
+ });
468
+
469
+ const metadata = await uploadProposalMetadata({
470
+ title: "Update the concentration shape",
471
+ markdown: markdownSource, // string or exact UTF-8 Uint8Array
472
+ upload: async (exactBytes, { contentType }) => {
473
+ // Pin to IPFS, upload to Arweave, or use durable HTTPS storage.
474
+ // Do not transform `exactBytes` while uploading.
475
+ return { uri: await uploadGovernanceDocument(exactBytes, contentType) };
476
+ },
477
+ });
478
+
479
+ const { proposal, transaction } = await dusk.write.createParameterProposal({
480
+ proposer: wallet.publicKey,
481
+ market,
482
+ nonce: 7,
483
+ // One to seven updates, at most one per family, in any order. They are
484
+ // sent in family order and pass or fail together.
485
+ updates: [update],
486
+ metadata,
487
+ initialSupport,
488
+ // holderYlpAccount is optional; the Token-2022 ATA is the default.
489
+ });
490
+ ```
491
+
492
+ `uploadProposalMetadata(...)` uploads the exact Markdown bytes through the
493
+ provided storage adapter, retrieves the resulting URI, and verifies the exact
494
+ length and SHA-256 before returning `ProposalMetadataV1`. For content that is
495
+ already uploaded, use `createProposalMetadata(...)`; it performs the same
496
+ retrieval check. Accepted on-chain URI schemes are `ipfs://`, `ar://`, and
497
+ `https://`. IPFS content must still be pinned; a CID alone is not a persistence
498
+ guarantee.
499
+
500
+ Governance websites should call `tryFetchProposalDescription(...)`. Render the
501
+ Markdown only when `verified` is true, using sanitized GitHub-flavored Markdown
502
+ with raw HTML and external embeds disabled. On failure, display the immutable
503
+ on-chain title and typed parameter diff plus the returned warning—never an
504
+ unverified replacement document. Rationale availability never controls
505
+ execution. `verifyDecodedParameterProposalDigest(...)` additionally reproduces
506
+ the program's canonical Borsh/SHA-256 digest for a fetched proposal account.
507
+
508
+ The other typed update constructors are `feeParameterUpdate(...)`,
509
+ `irmParameterUpdate(...)`, `emaHalfLivesParameterUpdate(...)`,
510
+ `dailyBorrowLimitParameterUpdate(...)`, `centerControllerParameterUpdate(...)`
511
+ and `insuranceDrawCapsParameterUpdate(...)`. Concentration parameters apply
512
+ immediately when the validated proposal executes, together with its other
513
+ updates; there is no concentration ramp or ramp-duration argument.
514
+ `canonicalParameterUpdates(...)` returns a set in the order the program
515
+ accepts and rejects a repeated family, and `updatedFamilyRevisions(...)` builds
516
+ the revision list a new proposal binds.
517
+
518
+ Support and lifecycle builders derive the proposal/support PDAs and all market
519
+ governance accounts:
80
520
 
81
521
  ```typescript
82
- const profileTx = await dusk.write.setReferralRecipientTransaction({
522
+ await dusk.write.supportParameterProposal({
523
+ supporter: wallet.publicKey,
524
+ market,
525
+ proposal,
526
+ amount: additionalSupport,
527
+ // The digest of the proposal the supporter reviewed, from its creation
528
+ // event or account; support fails unless it matches the proposal.
529
+ digest: proposalDigest,
530
+ });
531
+
532
+ await dusk.write.queueParameterProposal({ market, proposal });
533
+ await dusk.write.executeParameterProposal({ market, proposal });
534
+ await dusk.write.withdrawParameterSupport({
535
+ supporter: wallet.publicKey,
536
+ market,
537
+ proposal,
538
+ // Receives the proposal's rent, less its tombstone's, when the last
539
+ // supporter withdraws.
540
+ proposer,
541
+ });
542
+ ```
543
+
544
+ Each lifecycle method returns `{ proposal, proposalSupport?, instruction,
545
+ transaction }`. Fetch state with `dusk.get.parameterProposal(proposal)`,
546
+ `dusk.get.proposalSupportFor(proposal, supporter)`, or the matching helpers in
547
+ `dusk.get.pda`.
548
+
549
+ Support is burned from the holder's external yLP account and represented by a
550
+ proposal-specific virtual claim, so it cannot back multiple proposals. The
551
+ claim continues earning yLP yield. Withdrawal releases the requested amount,
552
+ credits accrued virtual yield to the owner, and remints only the released yLP.
553
+ A partial release retains the remaining claim. Collecting support can be withdrawn; queued support stays frozen until the proposal executes,
554
+ expires, or becomes stale. When the last supporter withdraws, the proposal
555
+ becomes a tombstone: the account keeps only its discriminator, which stops the
556
+ address from ever holding another proposal, and the rest of its rent returns
557
+ to the proposer.
558
+
559
+ hLP deposits and withdrawals use async composite builders because both
560
+ asset-denominated `YieldAccount` PDAs must exist before the liquidity
561
+ instruction runs. The SDK validates their owner, exact layout size, and Anchor
562
+ discriminator. If either account is missing or is only a prefunded System PDA,
563
+ it prepends the permissionless, idempotent initializer in the same transaction:
564
+
565
+ ```typescript
566
+ const { transaction, setupInstructions, baseYieldAccount, quoteYieldAccount } =
567
+ await dusk.write.depositSingleSided(
568
+ { depositAmount, minHlpAmount },
569
+ {
570
+ payer: owner,
571
+ owner,
572
+ market,
573
+ targetHlpMint,
574
+ baseMint,
575
+ quoteMint,
576
+ accounts: depositAccounts,
577
+ }
578
+ );
579
+
580
+ // setupInstructions is empty when both canonical accounts are already valid.
581
+ await provider.sendAndConfirm(transaction);
582
+ ```
583
+
584
+ `withdrawSingleSided(...)` has the same return shape and setup behavior. The
585
+ initializer is safe to compose unconditionally, including when a third party
586
+ has transferred lamports to the PDA address before initialization.
587
+
588
+ `harvest` accepts the LP owner, designated yield recipient, or independent
589
+ harvest authority for yLP and both hLP mints. Its `owner` account identifies
590
+ the LP holder; `caller` signs and must match that owner,
591
+ `YieldAccount.recipient`, or the optional `YieldAccount.harvestAuthority`.
592
+ An unrelated caller is rejected with `InvalidSigner`.
593
+
594
+ The LP owner sets or rotates a keeper with `setHarvestAuthority`, passing
595
+ `harvestAuthority: keeperPublicKey`, and revokes it with `harvestAuthority: null`.
596
+ New yield accounts start with no harvest authority. This changes who may
597
+ trigger payment without changing who receives it. Only the owner can update
598
+ either setting; changing the recipient does not clear the harvest authority.
599
+ Each yield account has its own configuration, so configure each underlying
600
+ asset and LP mint that the keeper should service.
601
+
602
+ ```typescript
603
+ // The LP owner signs this configuration transaction.
604
+ const transaction = await dusk.write.transaction(
605
+ "setHarvestAuthority",
606
+ { tokenKind: { ylp: {} }, harvestAuthority: keeperPublicKey },
607
+ { accounts: { market, owner, assetMint, lpMint, yieldAccount } }
608
+ );
609
+ await provider.sendAndConfirm(transaction);
610
+ // Pass harvestAuthority: null through the same instruction to revoke.
611
+ ```
612
+
613
+ For harvesting, set `caller` to the keeper and sign with its key. Neither the
614
+ owner nor recipient needs to sign. Derive `recipientAssetAccount` as the
615
+ current recipient's ATA using the underlying mint's token program; arbitrary
616
+ destinations are rejected. Create that ATA before harvesting if necessary.
617
+ The claim event records the LP owner, recipient, and caller separately, with
618
+ the caller in `metadata.signer`. `HarvestAuthorityUpdated` records delegation,
619
+ rotation, and revocation.
620
+
621
+ LP token accounts should be owned by a wallet that can sign withdrawals and
622
+ permission updates, or by a PDA whose controlling program invokes those Dusk
623
+ instructions with `invoke_signed`. SPL multisig accounts cannot sign those
624
+ instructions directly. PDA custody needs a controlling-program path to set
625
+ an independent keeper; the existing hLP order flow can still harvest using
626
+ the configured recipient.
627
+
628
+ ### Referral Interest Sharing
629
+
630
+ Futarchy first lists a referrer and configures its share of realized protocol
631
+ interest revenue:
632
+
633
+ ```typescript
634
+ const configureTx = await dusk.write.configureReferralPartnerTransaction({
635
+ authoritySigner: futarchySigner.publicKey,
636
+ referrer,
637
+ interestShareBps: 2_500,
638
+ active: true,
639
+ });
640
+ ```
641
+
642
+ The listed referrer may then designate the wallet that receives claims:
643
+
644
+ ```typescript
645
+ const partnerTx = await dusk.write.setReferralRecipientTransaction({
83
646
  authority: referrer.publicKey,
84
647
  recipient,
85
648
  });
86
649
  ```
87
650
 
88
- The referred-action builders derive the protocol-wide profile, create its
89
- per-mint ATA idempotently, apply the caller's fee-rate ceiling, and compose the
90
- setup and action instructions into one transaction:
651
+ The referred-action builders derive the partner and its per-market, per-mint
652
+ accrual account, initialize the accrual idempotently, and compose setup with the
653
+ debt-opening instruction:
91
654
 
92
655
  ```typescript
93
- const { transaction, referralProfile, referralVault } =
656
+ const { transaction, referralPartner, referralAccrual } =
94
657
  await dusk.write.referredBorrow(
95
658
  {
96
659
  borrowAmount,
@@ -100,24 +663,37 @@ const { transaction, referralProfile, referralVault } =
100
663
  {
101
664
  payer: borrower,
102
665
  referrer,
666
+ market,
103
667
  debtMint,
104
- maxAcceptableReferralFeeBps: 10,
105
668
  accounts: borrowAccounts,
106
669
  }
107
670
  );
108
671
  ```
109
672
 
110
- Claims always pay a token account owned by the profile's current recipient.
111
- The SDK resolves Token-2022 transfer-hook accounts when it builds the claim:
673
+ `referredOpenLeverage(...)` provides the equivalent leverage-opening flow.
674
+ Existing borrow debt sides and leverage positions retain their bound partner on
675
+ later debt increases. The program snapshots the partner share, capped by the
676
+ current runtime maximum, when the binding is created. Deactivation or later
677
+ rate/cap updates affect new bindings only. Referral does not change requested
678
+ principal, position debt, interest, health, or liquidation terms.
679
+
680
+ When interest is realized, the partner accrues a governed share of the DAO's
681
+ interest revenue. Claims always pay a token account owned by the partner's
682
+ current recipient:
112
683
 
113
684
  ```typescript
114
- const claimTx = await dusk.write.claimReferralFeesTransaction({
685
+ const claimTx = await dusk.write.claimReferralInterestTransaction({
115
686
  authority: referrer,
687
+ market,
116
688
  mint: debtMint,
117
689
  recipientTokenAccount,
118
690
  });
119
691
  ```
120
692
 
693
+ `referralBindingInterestShareBps(...)` computes the admission-time capped share.
694
+ Pass that stored share to `quoteReferralInterestShare(...)` to mirror the
695
+ on-chain floor rounding for realized interest.
696
+
121
697
  ## Get On-Chain State
122
698
 
123
699
  ```typescript
@@ -139,8 +715,13 @@ Available typed previews:
139
715
 
140
716
  - `previewMarket(market)`.
141
717
  - `previewSwap({ market, assetInMint, assetOutMint, exactAssetIn })`.
142
- - `previewBorrowCapacity({ market, collateralAssetMint, debtAssetMint, collateralAmount, projectedBorrowAmount, withReferral })`.
143
- - `previewBorrowPosition({ market, borrowPosition })`.
718
+ Its `amountOut` is the output vault debit after Dusk trading fees.
719
+ `outputTransferFee` is the fee withheld by the output mint at the simulated
720
+ epoch, and `netAmountOut` is the recipient credit used by the swap's
721
+ `minAssetOut` check. `grossAmountOut` is before Dusk trading fees.
722
+ - `previewBorrowCapacity({ market, collateralAssetMint, debtAssetMint, collateralAmount, projectedBorrowAmount })`.
723
+ - `previewBorrowPosition({ market, borrowPosition, baseMint, quoteMint })`.
724
+ - `previewBorrowPositionCapacity({ capacityKind, market, borrowPosition, collateralAssetMint, debtAssetMint, collateralChange, projectedBorrowAmount })`.
144
725
 
145
726
  `previewBorrowCapacity` exposes both the health-limited result of the on-chain
146
727
  binary search and the final limit after cash and daily-borrow constraints:
@@ -151,10 +732,8 @@ const capacity = await dusk.get.previewBorrowCapacity({
151
732
  collateralAssetMint: baseMint,
152
733
  debtAssetMint: quoteMint,
153
734
  collateralAmount,
154
- // Optional: quote the fee, CF, and health terms for this requested principal.
735
+ // Optional: quote CF and health terms for this requested principal.
155
736
  projectedBorrowAmount,
156
- withReferral: true,
157
- maxAcceptableReferralFeeBps: 10,
158
737
  });
159
738
 
160
739
  capacity.maxDebtByHealth;
@@ -162,9 +741,6 @@ capacity.maxDebtByCash;
162
741
  capacity.maxDebtByDailyLimit;
163
742
  capacity.maxDebt;
164
743
  capacity.maxBorrowAmount;
165
- capacity.referralOriginationFeeBps;
166
- capacity.projectedReferralFeeDebit;
167
- capacity.projectedReferralVaultCredit;
168
744
  capacity.maxCfBps;
169
745
  capacity.liquidationCfBps;
170
746
  capacity.projectedGlobalHealthContribution;
@@ -172,6 +748,46 @@ capacity.projectedGlobalMarketHealthBps;
172
748
  capacity.projectedEffectiveExistingDebtNad;
173
749
  ```
174
750
 
751
+ For an existing borrow account, use `previewBorrowPositionCapacity` instead of
752
+ adding its debt to `previewBorrowCapacity`. The account-aware preview accrues
753
+ interest and replaces the account's own market-health contribution, using the
754
+ same calculations as the borrow and withdrawal instructions.
755
+
756
+ ```typescript
757
+ const capacity = await dusk.get.previewBorrowPositionCapacity({
758
+ capacityKind: "borrow",
759
+ market,
760
+ borrowPosition,
761
+ collateralAssetMint: baseMint,
762
+ debtAssetMint: quoteMint,
763
+ collateralChange: new BN(0),
764
+ projectedBorrowAmount: null, // Maximum additional draw; BN(0) means no draw.
765
+ });
766
+
767
+ capacity.existingDebtAmount; // Accrued debt already owed.
768
+ capacity.maxBorrowAmount; // Additional vault debit in borrow mode.
769
+ capacity.projectedDebtAmount; // Existing debt plus the draw, with share rounding.
770
+ capacity.maxWithdrawAmount; // Collateral vault debit in withdraw mode.
771
+ capacity.borrowAllowed; // The requested draw is inside capacity limits.
772
+ ```
773
+
774
+ Choose `capacityKind: "borrow"` for borrowing or `"withdraw"` for collateral
775
+ withdrawal. Only that limit is calculated; the other field is `null`. This keeps
776
+ the preview within the transaction compute budget at ordinary token scales.
777
+ Withdrawal mode permits only a zero or omitted projected draw.
778
+
779
+ `collateralChange` is a signed raw-unit delta: a positive value is the **net**
780
+ collateral credit after inbound transfer fees; a negative value is a vault
781
+ withdrawal debit. Invalid withdrawals fail the preview. A zero draw preserves
782
+ the position's issued liquidation factor; a draw quotes the terms of that draw.
783
+ Withdrawal capacity is measured after the collateral delta and before any
784
+ additional borrowing. Outbound transfer fees may reduce wallet receipts.
785
+
786
+ The instruction reads market and position accounts without persisting its
787
+ hypothetical changes, including when submitted with writable account metas.
788
+ Capacity does not replace transaction-time permission, reduce-only, token
789
+ account, referral, slippage, or fresh deployment checks.
790
+
175
791
  ## Fetch Historical Data
176
792
 
177
793
  ```typescript
@@ -204,6 +820,58 @@ const program = createDuskProgram({ provider });
204
820
  `DUSK_PROGRAM_ID` is exported for integrations that prefer an explicit program
205
821
  name over the generic `PROGRAM_ID` constant.
206
822
 
823
+ ### TypeScript and the IDL size
824
+
825
+ The Dusk IDL carries over 150 types. Anchor's `IdlTypes`, `IdlAccounts`, and
826
+ `IdlEvents` decode every type eagerly, several passes deep, which exceeds
827
+ TypeScript's fixed instantiation budget and fails with "Type instantiation is
828
+ excessively deep and possibly infinite" wherever `Program<Dusk>` or the
829
+ exported account and event types are used. This repository rewrites the
830
+ installed Anchor declarations with a lazily recursive decoder from
831
+ `scripts/patch_anchor_idl_types.js` during `postinstall`. Consumers that type
832
+ against `Program<Dusk>` need the same rewrite of
833
+ `@coral-xyz/anchor/dist/*/program/namespace/types.d.ts` until Anchor changes
834
+ the decoder upstream; the rewrite applies unchanged to Anchor 0.31 and 0.32.
835
+
836
+ ## LP Mint Bootstrap
837
+
838
+ `initialize_market` takes three existing Token-2022 LP mints. Production builds
839
+ require their addresses to end in `yLP` (the yLP mint) and `hLP` (both hLP
840
+ mints). The SDK produces them as `create_with_seed` accounts of the creator,
841
+ so the creator is the only signer:
842
+
843
+ ```typescript
844
+ import {
845
+ createHookedLpMintWithSeedInstructions,
846
+ grindMarketLpMintSeeds,
847
+ lpMintRent,
848
+ marketLpTokenNaming,
849
+ } from "@omnipair/dusk-sdk";
850
+
851
+ const seeds = await grindMarketLpMintSeeds({ base: creator }); // vanity.omnipair.fi
852
+ const rent = await lpMintRent(connection);
853
+ const ylp = await createHookedLpMintWithSeedInstructions({
854
+ payer: creator, base: creator, seed: seeds.ylp.seed, mint: seeds.ylp.mint,
855
+ decimals, mintAuthority: market, transferHookProgramId: PROGRAM_ID, lamports: rent,
856
+ });
857
+
858
+ const naming = marketLpTokenNaming({ baseSymbol: "META", quoteSymbol: "USDC" });
859
+ // naming.ylp -> { name: "yMETA/USDC LP", symbol: "yMETA.USDC", description }
860
+ // naming.baseHlp -> { name: "hMETA", symbol: "hMETA.USDC", description }
861
+ // naming.quoteHlp -> { name: "hUSDC", symbol: "hUSDC.META", description }
862
+ ```
863
+
864
+ `grindLpMintSeed` asks the vanity server for a seed with `owner` set to
865
+ Token-2022 and re-derives the address locally before returning it; a server
866
+ that ground the wrong suffix or owner is rejected. Names are written once by
867
+ `initialize_market` and cannot be changed afterwards, so use `lpTokenNaming`
868
+ rather than ad-hoc strings. Pass the three names, symbols, and URIs through
869
+ `initializeMarketInstruction`; `marketCreationLookupTablePlan` and
870
+ `marketCreationV0Transaction` build the v0 transaction once the lookup table is
871
+ active. The metadata JSON and images that
872
+ the URIs point to are produced by `scripts/lp-metadata/` in the dusk
873
+ repository.
874
+
207
875
  ## ESM Compatibility
208
876
 
209
877
  This package ships strict ESM-compatible output. Relative module specifiers
@@ -212,3 +880,394 @@ include `.js` extensions in emitted files.
212
880
  ## License
213
881
 
214
882
  MIT
883
+
884
+
885
+ ## Token amounts and UI extensions
886
+
887
+ Dusk instruction amounts, token balances, and amount previews are raw integer
888
+ atoms (`BN`/`bigint`). The program supports Token-2022 group metadata,
889
+ `InterestBearingConfig`, and `ScaledUiAmount` on underlying assets. Group
890
+ metadata does not change settlement. Interest and UI multipliers change only
891
+ the displayed denomination; the SDK does not automatically apply them.
892
+
893
+ For these mints, dividing raw amounts by `10 ** decimals` alone is not a correct
894
+ wallet display. Use the Token-2022 program's `AmountToUiAmount` and
895
+ `UiAmountToAmount` instructions through RPC simulation with the current mint
896
+ state and clock. Refresh conversions after multiplier/rate updates or scheduled
897
+ changes take effect. Keep raw amounts as integers throughout transaction
898
+ construction; token-program UI conversion uses floating-point arithmetic and
899
+ must not be used as a lossless accounting round trip.
900
+
901
+ Dusk prices and price limits use fixed mint-decimal units, with nine-decimal NAD
902
+ precision, independently of UI multipliers. Convert UI prices at the client
903
+ boundary as well: if raw-decimal price is quote per base, displayed price is
904
+ `price * quote_display_multiplier / base_display_multiplier`. Interest-bearing
905
+ mints have a time-dependent display factor. Existing orders keep their original
906
+ raw price limits when the issuer changes the display. A display increase alone
907
+ does not create collateral or Dusk yield.
908
+
909
+ The token extension semantics are described in Solana's
910
+ [scaled UI amount](https://solana.com/docs/tokens/extensions/scaled-ui-amount) and
911
+ [interest-bearing token](https://solana.com/docs/tokens/extensions/interest-bearing-tokens)
912
+ documentation.
913
+
914
+
915
+ ## Shared virtual-book previews and simulation context
916
+
917
+ Use `dusk` for a `Dusk` client instance. The SDK owns native preview construction,
918
+ account decoding, concentration sampling, cumulative quote batching, and
919
+ fee-inclusive depth projection:
920
+
921
+ ```ts
922
+ const snapshot = await dusk.get.previewVirtualBook(market, {
923
+ minContextSlot: verifiedSlot,
924
+ groupingBps: 10,
925
+ signal,
926
+ });
927
+
928
+ // snapshot.book contains bid/ask prices, cumulative sizes, fees, and surcharge.
929
+ // snapshot.slot / firstQuoteSlot identify the actual simulation banks.
930
+ // snapshot.observedAt is the first request's start time, not delivery time.
931
+ // snapshot.account is the accrued market returned by simulation.
932
+ ```
933
+
934
+ These display previews use confirmed banks. Supported groupings are 5, 10, 25,
935
+ 50, and 100 bps. A capture uses one market preview and at most six batches of
936
+ four swap previews. Batches must agree on market, mint and authority state,
937
+ epoch, and start price, with a maximum eight-slot spread. Output amounts include
938
+ Token-2022 transfer fees at the simulated epoch and the program's size-dependent
939
+ fees. Depth is display data; use a fresh preview for a user's exact transaction.
940
+
941
+ Applications that bracket each stage with their own deployment checks can call
942
+ `dusk.get.previewVirtualBookSnapshot(market, options)` and
943
+ `dusk.get.previewVirtualBookQuotes(snapshot, options)` separately, then
944
+ `projectDuskVirtualBook(quotes)`. `previewVirtualBookBatch(snapshot, requests,
945
+ options)` is available for one to four explicit cumulative inputs.
946
+
947
+ For other preview workflows, retain full RPC provenance instead of only return
948
+ data:
949
+
950
+ ```ts
951
+ const result = await dusk.get.simulateWithContext([previewInstruction], {
952
+ minContextSlot: verifiedSlot,
953
+ accounts: [market, baseMint, quoteMint],
954
+ signal,
955
+ timeoutMs: 10_000,
956
+ });
957
+
958
+ result.context.slot; // Actual RPC simulation slot.
959
+ result.value.accounts; // Ordered post-simulation accounts from that bank.
960
+ result.value.returnData;
961
+ result.value.logs;
962
+ result.observedAt;
963
+ ```
964
+
965
+ The existing `get.previewSwap` and other decoded preview APIs remain compatible.
966
+ The SDK does not select deployments, attest program binaries, schedule refreshes,
967
+ set cache expiry, coordinate database locks, or stream to subscribers. Those
968
+ remain application responsibilities; validate deployment identity before and
969
+ after a capture. Cancellation and timeout bound the caller's wait; they do not
970
+ necessarily cancel an RPC request already sent over the transport.
971
+
972
+
973
+ ### Reusable governance balances and delegation
974
+
975
+ `dusk.governance` builds instructions and transactions; it never signs or submits.
976
+ Amounts are raw **yLP atoms**, not asset amounts or dollar values. Only direct yLP
977
+ is eligible; hLP vault holdings remain excluded. Deposited and committed shares
978
+ continue accruing swap fees and interest to their original owner.
979
+
980
+ ```ts
981
+ const deposit = await dusk.governance.deposit({ market, owner, amount: 100_000n });
982
+ const delegateTx = await dusk.governance.setDelegate({ market, owner, delegate });
983
+ // Owner signs both; delegate receives no token-transfer or yield-withdrawal authority.
984
+
985
+ const proposal = await dusk.governance.createProposal({
986
+ market, proposer: delegate, nonce: 1n, updates, metadata,
987
+ contributions: [{ owner, amount: 1_000n }, { owner: secondOwner, amount: 1_000n }],
988
+ });
989
+ // Delegate signs. Every contributing owner must have appointed this delegate.
990
+ // Combined sponsorship must meet the existing minimum atomically.
991
+
992
+ const support = await dusk.governance.supportProposal({
993
+ market, proposal: proposal.proposal, authority: delegate, digest,
994
+ contributions: [{ owner, amount: 5_000n }],
995
+ });
996
+ const release = await dusk.governance.withdrawSupport({
997
+ market, proposal: proposal.proposal, owner, authority: delegate, amount: 500n,
998
+ });
999
+ // Omit amount to release all. Released shares return to this owner's idle balance.
1000
+
1001
+ const revoke = await dusk.governance.setDelegate({ market, owner, delegate: null });
1002
+ const balance = await dusk.governance.getBalance(market, owner); // includes availableAmount
1003
+ const allocations = await dusk.governance.listSupport(market, owner);
1004
+ const withdraw = await dusk.governance.withdraw({ market, owner, amount: 500n });
1005
+ const claim = await dusk.governance.claimYield({ market, owner });
1006
+ // claim credits the owner's YieldAccounts; use the existing harvest flow to collect.
1007
+ ```
1008
+
1009
+ The owner can always act directly. One delegate per owner per market can create
1010
+ proposals, support proposals, or release collecting support. Replacing/revoking
1011
+ that delegate takes effect immediately, including for existing allocations.
1012
+ Delegate changes need only the owner and their governance balance; closing an
1013
+ empty wallet ATA cannot block revocation. Fund the balance before setting a delegate.
1014
+ Queued support stays frozen until execution, expiry, or staleness under the
1015
+ existing rules. Idle shares remain owner-withdrawable. The same shares cannot
1016
+ support multiple proposals simultaneously. Falling below the original sponsorship
1017
+ minimum cancels a collecting proposal. The final release leaves its permanent
1018
+ tombstone, refunding excess rent to the proposer; allocation rent returns to its
1019
+ original payer. Empty reusable balances remain open for future deposits.
1020
+
1021
+ Direct wallet support remains available through `dusk.write`. Its
1022
+ `withdrawParameterSupport({ ..., amount })` now supports partial withdrawals;
1023
+ omitting `amount` releases all. The on-chain instruction now takes
1024
+ `{ amount: Option<u64> }`, so raw instruction callers must update their encoding.
1025
+
1026
+ Combined builders sort owners canonically and reject duplicates. Large batches
1027
+ or long metadata may require a v0 transaction and a caller-provided address lookup
1028
+ table. Use the returned `instruction` to compose such a transaction; initial
1029
+ sponsorship cannot be split across multiple transactions. Existing queue and
1030
+ execute helpers work for proposals with direct, reusable, or mixed support.
1031
+
1032
+ ### Mutable transfer-fee notice monitoring
1033
+
1034
+ ```ts
1035
+ import { DuskLiquidations, transferFeeCredit } from "@omnipair/dusk-sdk";
1036
+ const liquidations = new DuskLiquidations(program, keeperPublicKey);
1037
+ const notice = await liquidations.transferFeeNotices({
1038
+ market, position, kind: "leverage", debtAsset: "quote",
1039
+ });
1040
+ // Each mint and Clock were read from the same RPC bank.
1041
+ console.log(notice.slot, notice.epoch, notice.collateral.phase);
1042
+ const actualReceipt = transferFeeCredit(grossCollateral, notice.collateral, "effective");
1043
+ const healthCredit = transferFeeCredit(grossCollateral, notice.collateral, "liquidation");
1044
+ ```
1045
+
1046
+ `fetchTransferFeeNotices(connection, mints, { minContextSlot })` also supports
1047
+ 1–99 mints per coherent request. Monitor both debt and collateral mint
1048
+ `refreshKey`s and poll epochs even when mint data does not change. `nextRecheckEpoch`
1049
+ is the next notice/activation boundary, not an instruction to wait until then.
1050
+ A change or cancellation invalidates prior health/payment estimates. Refresh the
1051
+ on-chain flash/emergency preview and simulate the complete transaction before
1052
+ signing; these helpers do not prove eligibility or promise a fill. Use effective
1053
+ fees for actual transfers, never a pending fee as a current payment fee.
1054
+
1055
+ See [the fee policy and keeper rollout dependency](../../docs/mutable-transfer-fees.md).
1056
+ #287160 has implemented notice-window mitigation; timely confirmed keeper execution
1057
+ remains an operational assumption. Fee-authority revocation is not a missing
1058
+ agreed fix.
1059
+
1060
+ ### hLP funding capacity
1061
+
1062
+ Use `dusk.get.previewHlpDepositCapacity({ market, baseMint, quoteMint, targetHlpMint })`
1063
+ to read the native entry status and gross/net funding ceilings. It accrues the
1064
+ market in a read-only simulation and prices the underlying yLP purchase and
1065
+ hedge using full live-reserve value, including public unpaid interest. These
1066
+ receivables remain excluded from swap-pricing reserves.
1067
+
1068
+ `Ready` and the capacity ceiling do not guarantee execution for every amount.
1069
+ Simulate the completed deposit transaction to check rounding, cash custody,
1070
+ transfer fees and slippage. Under concentration, an opposite-token-neutral
1071
+ hLP need not have a literal 2x gross-value/equity ratio.
1072
+
1073
+ ### Public-interest cash advance calculations
1074
+
1075
+ `quoteInterestAdvanceAmounts` computes the cash-capped gross advance, frozen
1076
+ protocol escrow, LP transfer debit and measured-fee-adjusted LP credit. Pass
1077
+ amounts as `bigint` and the current `TransferFeeNotice`; pending transfer fees
1078
+ are reported separately by that notice and do not replace the effective fee.
1079
+ `allocateRepaidInterest` splits measured repayment custody credit between
1080
+ fresh LP/protocol revenue and the already-frozen protocol portion. Already
1081
+ funded LP interest must be excluded from `freshGrossInterest`.
1082
+
1083
+ For transaction composition, use the vault-aware yield client:
1084
+
1085
+ ```ts
1086
+ const quote = await dusk.yield.previewFunding({ market, caller });
1087
+ const plan = await dusk.yield.buildHarvest({
1088
+ market, owner, caller, kind: "baseHlp", asset: "quote",
1089
+ // Optional per-asset gross advance caps, in raw atoms:
1090
+ maxBaseGross: 0n, maxQuoteGross: 1_000_000n,
1091
+ });
1092
+ // Simulate the complete plan.transaction before signing and sending.
1093
+ ```
1094
+
1095
+ `kind` accepts `ylp`, `baseHlp` and `quoteHlp`. The builder reads the owner's
1096
+ YieldAccount, respects its configured recipient and creates that recipient's
1097
+ ATA if needed. Existing yield accounts are required. Builders never sign or send.
1098
+ Set `fundAccruedInterest: false` to harvest existing funded claims without a new
1099
+ funding/rebalance attempt. `fundInstruction` is the standalone funding builder.
1100
+
1101
+ Funding moves only available cash. Newly earned hLP income first covers the
1102
+ vault-wide funding gap; existing funded holder claims are protected. The hedge
1103
+ reconstruction can change the AMM mark; the cash advance alone leaves swap
1104
+ reserves unchanged. `HlpInterestAllocated` distinguishes new holder yield from
1105
+ capital returned to reserves. Subtract its capital debits from gross
1106
+ `BorrowInterestPaid` credits when reconciling net interest-vault changes.
1107
+
1108
+ Repayment builders supply the canonical accounts needed for both hLP vaults.
1109
+ Raw callers must include the five existing hLP accounts followed by both asset
1110
+ mints and reserve vaults when fresh public interest is settled with active hLP.
1111
+ The Market layout is version 5 with `fees.publicInterestAdvance` on both sides,
1112
+ per-vault flash locks, and non-cash `reserves.flashReceivable`;
1113
+ use the regenerated IDL. It also records a frozen hLP mask and per-vault
1114
+ curve offsets; older snapshots are incompatible.
1115
+
1116
+
1117
+ ### Vault-wide hLP flash recovery
1118
+
1119
+ For a solvent vault, this is a **flash rescue** of its funding hedge. A positive
1120
+ funding gap can be quoted before the 112.5% critical-stress marker. Ordinary
1121
+ swaps can also earn a recovery bonus below that marker. The on-chain flash
1122
+ quote caps the discount to retain positive vault value;
1123
+ it may offer no discount for a tiny gap. A frozen vault can also quote a funded
1124
+ rescue after its gap falls. Full flash closeout remains restricted to insolvency
1125
+ at the current-slot symmetric EMA; the caller's fixed payment determines actual
1126
+ flash recovery.
1127
+
1128
+ ```ts
1129
+ const quote = await dusk.hlpLiquidations.preview({ market, targetAsset: "base" });
1130
+ const plan = await dusk.hlpLiquidations.buildFlash({
1131
+ market, targetAsset: "base", buyer,
1132
+ allowFull: false, // explicit opt-in is required for an insolvent full closure
1133
+ route: async ({ buyerCollateralAccount, repaymentVault, requiredPaymentCredit,
1134
+ collateralMint, debtMint, collateralTokenProgram, debtTokenProgram }) => {
1135
+ // Return an external route, a Dusk swap, or explicit inventory payment.
1136
+ // Deliver requiredPaymentCredit NET atoms into repaymentVault; gross up
1137
+ // its incoming transfer fee. The quote already includes vault→reserve fees.
1138
+ return buildRecoveryRoute({ buyerCollateralAccount, repaymentVault,
1139
+ requiredPaymentCredit, collateralMint, debtMint, collateralTokenProgram, debtTokenProgram });
1140
+ },
1141
+ });
1142
+ // Compile plan.instructions with a prepared address lookup table when needed.
1143
+ // Do not insert/reorder instructions: begin binds the exact settle index.
1144
+ ```
1145
+
1146
+ The helpers never sign, submit, or silently top up from the keeper's wallet.
1147
+ The quote is current-bank only. `maxPayment`, collateral limits, insurance and
1148
+ principal-loss caps protect the submitted plan against state drift. Prefix
1149
+ instructions must be supplied through `prefixInstructions` before building.
1150
+ An affected hLP cohort cannot mint/redeem between begin and settle; swaps and
1151
+ independent market operations remain composable subject to cash and accounting
1152
+ checks. The SDK's complete-plan simulator preserves bound instruction indices.
1153
+ `HlpFlashSettled.loss` separates principal recovery, principal insurance,
1154
+ principal writeoff and canceled interest; a partial recovery has an empty loss
1155
+ allocation. Native `HlpTerminalLiquidated.socializedLoss` now denotes principal
1156
+ loss only, with `interestCanceled` reported separately.
1157
+
1158
+ If an hLP vault has negative executable value, ordinary spot swaps continue.
1159
+ Only that vault's automatic hedge is frozen; the opposite vault remains active.
1160
+ `state.amm.frozenHlpMask` uses bit 1 for base hLP and bit 2 for quote hLP.
1161
+ The frozen vault cannot make an ordinary withdrawal that leaves its deficit to
1162
+ the other holders. A terminal close requires insolvency at the current-slot
1163
+ symmetric EMA, so a spot-only price move cannot write off the vault. Native
1164
+ recovery is then valued on the EMA-price, smoothed-depth concentrated reference
1165
+ curve with the configured fees; it does not use live spot reserves.
1166
+
1167
+ An eligible holder can build `hlpLiquidations.buildNativeCloseAndExit({ market,
1168
+ targetAsset, exit: { hlpAmount, options } })`. The helper places the permissionless
1169
+ native close before `withdrawSingleSided` in one transaction; `options` are the
1170
+ normal hLP withdrawal accounts and the owner signs. It burns the closed vault's
1171
+ receipts for zero principal payout. The flash builder also accepts `exit`,
1172
+ appending an owner-signed withdrawal after settlement. For a solvent rescue,
1173
+ set `exit.minTargetAmountOut` to protect the holder's payout. A terminal quote
1174
+ still requires `allowFull` and pays zero principal. A vault with only a
1175
+ transient spot deficit must recover or receive funded rescue before its holders
1176
+ can withdraw. Once its executable value recovers, a frozen vault can quote a
1177
+ funded flash rescue even if its debt gap has fallen below the ordinary rescue
1178
+ threshold; a fully covered gap uses a minimal zero-discount payment.
1179
+
1180
+ Spot swap previews use the same cash policy as execution. If paying all accrued
1181
+ hLP funding interest would consume the cash needed for trader output or the
1182
+ last reserve atom, Dusk requotes the swap while carrying both active hLP
1183
+ funding-interest amounts on their indexed debts. That swap pays no hLP funding
1184
+ interest and offers no hLP recovery bonus. A later swap with sufficient reserve
1185
+ cash can settle the carried interest. The trader's output still requires
1186
+ spendable reserve cash; this fallback does not create liquidity.
1187
+
1188
+ ### Restarting after a terminal hLP close
1189
+
1190
+ When a terminal close leaves old hLP receipts outstanding, a new deposit needs
1191
+ a fresh receipt mint. Create a zero-supply hooked hLP mint with the market as
1192
+ mint authority, then call `write.rotateHlpCohortInstruction` with the old and
1193
+ new mints, target side and Metaplex metadata. The old mint's transfer hook must
1194
+ be initialized first; `write.initializeLpTransferHookInstruction` accepts
1195
+ `tokenKind: "hlp"` when composing that setup without an RPC market fetch.
1196
+ Initialize the new mint's hook, then deposit using the new mint. The other hLP
1197
+ side and yLP mint do not rotate.
1198
+
1199
+ The old mint remains transferable but owns no new principal. Its holder yield
1200
+ indexes are frozen in `deriveHlpCohortAddress(market, oldMint)`. A holder can
1201
+ initialize an old mint's yield accounts with
1202
+ `write.initializeYieldAccountsInstruction({ ..., retired: true })`, claim
1203
+ funded yield through `yield.buildHarvest({ ..., retiredHlpMint: oldMint })`, and
1204
+ burn old receipts with `write.burnRetiredHlpReceiptInstruction`. If the asset
1205
+ has a Token-2022 transfer hook, pass its extra accounts as
1206
+ `transferHookAccounts` to the harvest builder. Burning never forfeits yield
1207
+ already checkpointed in the holder's yield accounts.
1208
+
1209
+
1210
+ ## yLP, jrLP and hLP
1211
+
1212
+ `yLP` is the default senior claim. `jrLP` owns productive first-loss capital;
1213
+ entering junior burns yLP and mints jrLP at their current values. `hLP` remains
1214
+ a hedged position backed by senior liquidity and cannot enter junior. Its own
1215
+ unpaid income remains in NAV, and collected income pays funding costs first.
1216
+
1217
+ ```ts
1218
+ const setup = await dusk.tranches.initialize({ market, payer });
1219
+ // Sign and submit setup.transaction once for this junior generation.
1220
+ const enter = await dusk.tranches.convert({
1221
+ market, owner,
1222
+ action: { kind: "enter", seniorAmount: 1_000_000n, minimumJunior: 990_000n },
1223
+ });
1224
+ // Sign and submit enter.transaction. Amounts are raw token atoms.
1225
+ const request = await dusk.tranches.convert({
1226
+ market, owner, action: { kind: "requestExit", additionalJunior: 500_000n },
1227
+ });
1228
+ ```
1229
+
1230
+ Exit requests escrow receipts. They continue earning junior income and taking
1231
+ losses during notice and the exercise window. After notice, `convertExit` burns
1232
+ the escrowed jrLP and mints yLP at its current value. It does not withdraw cash.
1233
+ Read the returned `exit` account for its actual `readyAt` and `expiresAt` slots;
1234
+ the configured crowding rule determines the notice. An expired request must be
1235
+ renewed or canceled. Conversion can also be blocked by an unsettled insolvent
1236
+ liquidation. A failed transaction does not silently extend a window.
1237
+
1238
+ Income earned before an ordinary LP transfers or converts remains with that
1239
+ holder. Each asset has separate public-loan and hLP-funding income histories.
1240
+ The SDK exposes bounded maintenance transactions; none are submitted implicitly:
1241
+
1242
+ 1. Before issuing income into a fully collected book, call
1243
+ `prepareDrainedIncomeBooks({ market, payer })` and submit its transactions.
1244
+ For `IncomeEpochNeedsRollover` on a partially paid book, use `rollIncome` for
1245
+ the affected book. The payer funds its immutable archive account.
1246
+ 2. For an existing yLP/jrLP holder, call
1247
+ `prepareHolderIncome({ market, owner, kind: "senior" | "junior" })`.
1248
+ Submit its transactions and repeat while `hasMore` is true. Each instruction
1249
+ processes at most eight archived epochs for one source.
1250
+ 3. Fetch again and build the transfer, conversion or harvest. A competing
1251
+ maintenance transaction can require another catch-up; builders do not
1252
+ guarantee that the market stays unchanged between fetch and submission.
1253
+
1254
+ Archived history has no fixed lifetime limit. A caller that pays archival rent
1255
+ can roll after settlement, so repayment/roll churn can increase other holders'
1256
+ catch-up work. Eight epochs per instruction bounds transaction work, not total
1257
+ history. Integrators should maintain active holders, retry stale plans and expose
1258
+ maintenance transactions in their UX; this mechanism does not guarantee a
1259
+ single-transaction exit for an inactive holder.
1260
+
1261
+ `checkpointIncome` also supports one asset/source batch and retired junior
1262
+ mints. Wiped receipts have no principal but may still own historical earnings.
1263
+ `burnRetired` removes those receipts without giving them new-generation capital.
1264
+
1265
+ The permanent junior seed receives income even without external jrLP holders.
1266
+ `fundSeed` moves its collected interest to reserve custody. `compoundSeed`
1267
+ reinvests balanced asset amounts without issuing senior tokens; unmatched assets
1268
+ remain seed-owned custody until a matching amount is available. These custody
1269
+ balances do not count as productive junior coverage until reinvested.
1270
+
1271
+ Rate defaults are exported as `RISK_RATE_DEFAULTS`; the market configuration and
1272
+ governance builders can override them. `riskCoverageSignalNad` uses one junior
1273
+ capital budget across both debt assets, with each asset's own utilization.