@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/README.md CHANGED
@@ -1,6 +1,149 @@
1
1
  # @omnipair/dusk-sdk
2
2
 
3
- TypeScript SDK for Omnipair Dusk (v2).
3
+ Current loss and fee specification: [junior-first credit loss waterfall](../../docs/CREDIT_LOSS_WATERFALL.md).
4
+
5
+ For volume, fee, and borrower-interest consumers, see the
6
+ [accounting event contract](../../programs/dusk/ACCOUNTING_EVENTS.md).
7
+ `SwapExecuted` covers spot and leverage AMM executions and the market state they
8
+ leave behind. `BorrowInterestAccrued`
9
+ separates credit, margin, and hLP accrual; `BorrowInterestPaid` reports actual
10
+ collections with the same source attribution. Typed events and their
11
+ `SwapOrigin`/`DebtSource` discriminants are exported from this package.
12
+
13
+ TypeScript SDK for Dusk, the Omnipair V2 protocol architecture. This package
14
+ targets Dusk market layout 11, including bounded oracle policies, aggregate leverage exposure and stored
15
+ position margin terms. Regenerate clients and use matching account layouts.
16
+
17
+ ## Bounded oracle markets
18
+
19
+ Market creation selects native or oracle-guided pricing in the same
20
+ `initializeMarket` instruction. In the SDK, omit `oracle` (or pass `null`) for
21
+ native pricing at λ = 0; pass an `OraclePolicyInput` to launch with that policy:
22
+
23
+ ```typescript
24
+ const instruction = await dusk.write.initializeMarketInstruction({
25
+ ...creationParams,
26
+ oracle: policy, // omit or use null for native pricing
27
+ });
28
+ ```
29
+
30
+ The creator does not send a separate oracle-configuration instruction. Creation
31
+ validates and stores the policy atomically with the market and its LP metadata;
32
+ `MarketCreated.oracle` reports the selected policy. Creation needs no live feed
33
+ account. First liquidity and subsequent price-sensitive operations authenticate
34
+ a current report when λ is positive. An invalid initial policy rolls back market
35
+ creation and the treasury creation charge.
36
+
37
+ Guided creation has no independent opening price: omit `bootstrapPriceNad` or
38
+ pass zero. The SDK and program reject a nonzero value when λ is positive.
39
+ `addLiquidityInstruction` takes two maximum gross spends. On the first guided
40
+ deposit the validated execution-time report sets their usable ratio; base is
41
+ rounded down and quote up to token atoms, and unused tokens stay in the owner's
42
+ wallet. The existing `minSrlpAmount` floor still applies. Native first deposits
43
+ keep their caller-selected ratio, and subsequent deposits remain proportional
44
+ to existing reserves. The first-deposit change preserves all wire layouts.
45
+
46
+ Every market can later activate an oracle, change its source/weight/cap, or return
47
+ to native pricing through the existing parameter-proposal lifecycle.
48
+ `parameterUpdate.oracle(policy)` creates the proposal update. Subsequent changes
49
+ are creation-only, including before first liquidity; no post-creation setter
50
+ remains. `oraclePolicy()` validates the wire format. Positive weights are
51
+ 1–9,999 bps and a nonempty policy's adjustment multiplier must exceed one;
52
+ there are no creation-time oracle ceilings or automatic outage-driven changes.
53
+ See [the implementation contract](../../docs/OP_GAMM_IMPLEMENTATION_STATUS.md)
54
+ for the coupled swap, lending and hLP behavior.
55
+
56
+ Use `marketCreationLookupTablePlan` and `marketCreationV0Transaction` for the
57
+ creation transaction. The latter rejects a packet larger than 1,232 bytes;
58
+ metadata and optional setup instructions must fit alongside the selected policy.
59
+ An address lookup table compresses account addresses, not metadata or policy
60
+ bytes. The launch scripts accept optional `DUSK_ORACLE_POLICY_JSON` using
61
+ `OraclePolicyInput` field names (base58 addresses, 32-byte feed-ID arrays and
62
+ string values for large integers); omission selects native pricing. They resolve
63
+ the stored policy's feeds and compute budget when seeding liquidity.
64
+
65
+ Raw Anchor callers must include `oracle: null` or a serialized policy. The
66
+ `initializeMarket` argument layout now starts with `paramsHash`, followed by
67
+ `config` and `oracle`; rebuild instruction encoders and event decoders using the
68
+ vendored IDL. The removed `configureInitialOracle` instruction and
69
+ `InitialOracleConfigured` event are replaced by creation parameters and
70
+ `MarketCreated.oracle`.
71
+
72
+ Provider and feed layout are independent: normalized direct pair
73
+ (`NORMALIZED_ORACLE_V1`, format 1), fully verified Pyth ratio (`PYTH_RATIO_V2`, 2),
74
+ fully verified Pyth direct pair (`PYTH_DIRECT_V3`, 3), or normalized ratio
75
+ (`NORMALIZED_RATIO_V4`, 4). One feed must actually quote the ordered market pair;
76
+ META/USD alone is not META/USDC. Two feeds must share a denomination and include
77
+ an observed quote-asset price. Ratio uncertainty is rounded outward and each leg
78
+ is authenticated and checked for age and publication skew. Layout 8 stores
79
+ per-leg counters/content hashes so independent updates cannot hide normalized
80
+ report equivocation or rollback. Do not decode layout-7 accounts with this SDK.
81
+ A market selects the provider, feed identities, age and confidence policy. The normalized provider
82
+ must serialize the exact Borsh `NormalizedOracleV1` envelope defined in
83
+ [oracle.rs](../../programs/dusk/src/oracle.rs), including the underlying source
84
+ observation time, both mints and a monotonically increasing nonzero sequence.
85
+ Dusk does not fetch an off-chain report or give Horus special authority.
86
+
87
+ High-level builders fetch the policy and append feed accounts after the existing
88
+ hLP/hook prefix. Positive-weight transaction builders add the compute and heap
89
+ budgets. When composing **raw instructions**, add
90
+ `oracleComputeBudgetInstructions(policy)` once before constructing any
91
+ index-bound flash plan; do not prepend instructions after binding its indices.
92
+ Resolve `oracleReadAccounts(policy)` for direct Anchor calls. Zero weight needs
93
+ neither feed accounts nor OP budgets. Simulate the whole transaction, including
94
+ any provider update and callback: a passing isolated price calculation does not
95
+ establish route feasibility.
96
+
97
+ A stale or invalid source rejects price-sensitive operations. Direct repayment
98
+ in the debt token and adding collateral remain possible without a valid price;
99
+ this does not permit a collateral sale or removal. Oracle updates change the
100
+ market reference but do not execute an hLP hedge by themselves.
101
+
102
+ ## Protocol revenue defaults
103
+
104
+ `DEFAULT_PROTOCOL_REVENUE_SHARE_BPS` is exported from the generated program IDL.
105
+ Its initial value is 2,000 bps (20%). It initializes the protocol share of base
106
+ swap fees and the separate additive borrower interest markup, and sets the
107
+ protocol share of liquidation fees. Dynamic swap
108
+ surcharges remain excluded. Liquidation's total charge is fixed at 3% of net debt
109
+ repaid, subject to available surplus; the shared constant sets the protocol's
110
+ share of that charge.
111
+
112
+ `initFutarchyAuthority` now accepts nullable `swapBps` and `interestBps`. Pass
113
+ `null` for the program default, or a number for an explicit override, including
114
+ zero. The FutarchyAuthority signer can subsequently change swap share or interest markup and the auction split.
115
+ The bootstrap script uses the program defaults when `DUSK_PROTOCOL_SWAP_BPS` and
116
+ `DUSK_PROTOCOL_INTEREST_BPS` are unset. Regenerate clients for this instruction change.
117
+ Changing the Rust default affects new authorities and liquidation allocations;
118
+ existing authorities retain their configured swap share and interest markup.
119
+
120
+ The initial auction split remains 100% fee auctions / 0% buybacks. Referral
121
+ commissions come out of the protocol interest share before the auction split.
122
+ The separate voluntary-order service charge and flat market-creation charge
123
+ are not revenue-share percentages and are outside this default.
124
+
125
+ ## Stored leverage margins
126
+
127
+ ```typescript
128
+ import { getStoredLeverageMargins } from "@omnipair/dusk-sdk";
129
+
130
+ const position = await dusk.get.leveragePosition(positionAddress);
131
+ const { initialMarginBps, maintenanceMarginBps } = getStoredLeverageMargins(position);
132
+ // Or fetch and decode in one call:
133
+ const margins = await dusk.get.leverageMargins(positionAddress);
134
+ ```
135
+
136
+ The helper reads the saved terms and applies the same conservative rate rounding
137
+ as Rust. It does not recalculate an existing position from live market crowding.
138
+ `admissionEquityCollateralNad` is collateral atoms times 1e9, not dollars or
139
+ debt-token atoms. These are required margin rates, not actual equity or an
140
+ executable leverage quote. Price and interest still change health. Simulate the
141
+ complete proposed transaction for openings, increases and withdrawals; executable
142
+ equity, cash and Token-2022 fees can impose tighter constraints.
143
+
144
+ `LeveragePositionOpened` and `LeveragePositionUpdated` include `marginTerms`.
145
+ Indexers should retain those fields per position and replace them on subsequent
146
+ position updates, rather than deriving old-position terms from current liquidity.
4
147
 
5
148
  A `Dusk` instance is an enriched Anchor program facade. It exposes the raw
6
149
  Anchor program through `dusk.program`, alongside typed on-chain reads and
@@ -11,14 +154,139 @@ The package exports the generated Anchor IDL/types, PDA helpers, typed preview
11
154
  decoders, a small write/read facade over the Dusk program, and an indexer client
12
155
  for historical API data.
13
156
 
157
+ ## Flash and emergency liquidations
158
+
159
+ `get.simulateWithContext(plan.instructions, { requireReturnData: false, lookupTables })`
160
+ preserves the absolute begin/settle indices in a built flash plan. Existing
161
+ compute budgets are retained (or explicitly overridden in place). A flash plan
162
+ missing either budget is rejected rather than silently shifted. Ordinary
163
+ previews receive a budget prefix. Set `preserveInstructionIndices: true` for
164
+ other programs with index-bound plans. Do not prepend instructions after `buildFlash`; pass
165
+ setup instructions through its `prefixInstructions` argument instead.
166
+
167
+ The auction start/fill/backstop and old full leverage-liquidation instructions
168
+ have been replaced. Use `dusk.liquidations` for either borrowing or leverage:
169
+
170
+ ```typescript
171
+ const position = { market, position: positionAddress, kind: "leverage" as const,
172
+ debtAsset: "quote" as const };
173
+ // Read-only simulation; no registration transaction is required.
174
+ const health = await dusk.liquidations.previewHealth(position);
175
+ const quote = await dusk.liquidations.preview({ ...position, maxRepayment: 1_000_000n });
176
+ const plan = await dusk.liquidations.buildFlash({
177
+ ...position, buyer, maxRepayment: 1_000_000n,
178
+ route: async (ctx) => {
179
+ // Return instructions that sell collateral or pay from buyer inventory.
180
+ // Deliver ctx.requiredPaymentCredit NET into ctx.repaymentVault.
181
+ // grossLiquidationPayment() handles the incoming token transfer fee.
182
+ return buildPaymentRoute(ctx);
183
+ },
184
+ });
185
+ // Compile plan.instructions unchanged, using flashLiquidationV0Transaction()
186
+ // with the necessary address lookup tables, then simulate, sign and submit.
187
+ ```
188
+
189
+ `settlement: "duskAmm"` instead sells the flashed collateral in the paired settle,
190
+ with debt principal netted internally and no escrow-payment instruction. The
191
+ buyer must retain the flashed collateral until settle. Its return transfer can
192
+ incur another collateral token fee. Settlement rejects an AMM quote that cannot
193
+ fund the fixed obligation; it never silently debits the owner's wallet.
194
+ If the route changes active hLP accounts, pass the complete final-state account
195
+ list through `settleRemainingAccounts`; the default resolves the current market.
196
+
197
+ `previewEmergency()` and `buildEmergency()` accept `collateralDebit` and `full`.
198
+
199
+ Emergency internal settlement uses **symmetric EMA price and smoothed curve depth**,
200
+ with the market's concentration. Both preview and settlement report
201
+ `referencePriceNad` (debt per collateral at 1e9 scale) and `referenceDepthNad` (normalized
202
+ curve depth, not TVL). `buildEmergency()` also returns these as bigint
203
+ `reference.priceNad` / `reference.depthNad`. `swapOutput` is the debt value credited
204
+ by this inventory settlement; it is not a live-spot execution quote. The pool
205
+ receives real collateral and reduces the loan, with funded cash payouts and real
206
+ hLP reconciliation. Normal flash routes, including `settlement: "duskAmm"`, retain
207
+ their venue's executable quotes.
208
+
209
+ The full fee schedule remains: launch price and divergence use the reference
210
+ curve; volatility uses the existing accumulator and decay. Thus changed fee
211
+ history can change net proceeds even when price/depth EMAs are unchanged. Live
212
+ spot/depth are not substituted into reference sizing or its full-close proof.
213
+ Use a fresh preview and simulate the complete transaction. The returned reference
214
+ is not a lock; the builder's minimum-output/reward arguments still apply.
215
+
216
+ They enforce the emergency EMA-health gate (equity at or below 70% of MM).
217
+ A full reference-priced settlement needs nonpositive EMA equity or the program's conservative proof
218
+ that no smaller reference-priced settlement can restore MM +2 percentage points after all costs.
219
+ A useful below-target partial or an external flash opportunity does not veto
220
+ this fallback. Full normal swap fees, rewards and loss accounting still apply.
221
+ Failure to certify, including proof-budget exhaustion, rejects full closure.
222
+ Smaller improving fills remain available. Preview and simulate the intended
223
+ operation: a failed slice is not full-close permission. There is no configurable
224
+ minimum remaining debt.
225
+
226
+ Ordinary `preview({ full: true })` / `buildFlash({ full: true })` retain the
227
+ stricter no-improving-partial certificate. An accepted full `previewEmergency`
228
+ quote does not authorize a full ordinary flash fill. Both builders use their
229
+ respective on-chain previews; do not infer permission from the incentive helper.
230
+
231
+ Builders return unsigned instructions and owner-owned payout accounts. Prefix
232
+ instructions belong in the builder request: inserting instructions afterwards
233
+ invalidates the bound settle index. Helpers include ATA setup, a 256 KiB heap,
234
+ a 1.4M compute-unit limit and required hLP accounts. A compute-unit limit supplied
235
+ in the prefix overrides the default; set the priority price there as needed.
236
+ The session closes at settle. Its payment token account persists for reuse,
237
+ including withheld Token-2022 fees; preexisting token donations do not count as
238
+ payment and are not refunded to the next buyer.
239
+
240
+ The 0.5%–5% ramp sets a maximum buyer discount. Partial quotes choose the highest
241
+ whole-basis-point discount within that range that improves health after the
242
+ 3% repayment charge and collateral transfer costs. If none works, the partial
243
+ rejects. Read the actual rate from `quote.rates.buyerDiscountBps`; use
244
+ `liquidationIncentives(...).maximumBuyerDiscountBps` only for the ceiling. The
245
+ legacy helper field `buyerDiscountBps` remains a deprecated alias for that ceiling.
246
+ Position-health previews also report the ceiling, not an executable purchase.
247
+
248
+ Market creation has no minimum remaining-debt setting. Partial `maxRepayment`
249
+ requests retain at least one debt share; small remainders are allowed when the
250
+ fill improves health. A request beyond the first MM+2 recovery crossing rejects;
251
+ request a smaller amount. Emergency collateral slices also respect health
252
+ improvement and a conservative recovery cap. The bound includes base swap fees and
253
+ checks surviving AMM amounts against actual execution costs. A bounded search
254
+ can still refuse a target crossing when it cannot certify the result;
255
+ useful below-target slices remain permitted. Preview acceptance does not reserve
256
+ liquidity or guarantee keeper profitability. Simulate the complete transaction.
257
+
258
+ `liquidationHealth`, `liquidationIncentives`, `liquidationFeeAllocation`,
259
+ and `liquidationLossAllocation` use integer atoms
260
+ and mirror the policy arithmetic. They do not replace the on-chain execution
261
+ preview. Incentives depend only on current health; there is no time ramp or
262
+ stored distress episode. `liquidationIncentives` takes only the health input.
263
+
264
+ Indexers should consume `FlashLiquidationBegun`, `FlashLiquidationSettled`,
265
+ `EmergencyLiquidationSettled`. AMM settlement also emits
266
+ `SwapExecuted`; external purchases do not generate Dusk swap volume. For emergency
267
+ settlement, its start price/output describe the reference-priced debt offset;
268
+ its final reserve/spot snapshots describe the actual pool. Correlate it with
269
+ `EmergencyLiquidationSettled` rather than treating it as a live execution quote. Collected
270
+ interest retains `BorrowInterestPaid`/referral events. A terminal settlement
271
+ clears the debt leg but leaves position rent to the existing owner cleanup path.
272
+ `previewBorrowPosition` reports `liquidationHealth`, `liquidationRates` and
273
+ `liquidationDistress`; obsolete auction penalty and repayment-cap fields are gone.
274
+
14
275
  ## Install
15
276
 
16
277
  ```bash
17
- npm install @omnipair/dusk-sdk
278
+ npm install @omnipair/dusk-sdk@next
18
279
  # or
19
- yarn add @omnipair/dusk-sdk
280
+ yarn add @omnipair/dusk-sdk@next
20
281
  ```
21
282
 
283
+ A version reaches npm once the programs it describes are deployed. Its dist-tag
284
+ names the deployment: `next` and `devnet` follow devnet, and `latest` moves only
285
+ with mainnet releases, so until the first one it still points at the early
286
+ 2.0.2 build. Pin an exact version, such as `2.16.0-next.20261102`, to match one
287
+ deployment's program interface. Maintainers publish by tagging the deployed
288
+ commit, as described in [Publishing the SDK](../../scripts/v2/README.md#publishing-the-sdk).
289
+
22
290
  ## Dusk Client
23
291
 
24
292
  ```typescript
@@ -26,7 +294,7 @@ import { AnchorProvider } from "@coral-xyz/anchor";
26
294
  import { Connection } from "@solana/web3.js";
27
295
  import { Dusk } from "@omnipair/dusk-sdk";
28
296
 
29
- const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed");
297
+ const connection = new Connection(process.env.SOLANA_RPC_URL!, "confirmed");
30
298
  const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });
31
299
 
32
300
  const dusk = new Dusk({
@@ -63,12 +331,7 @@ const ix = await dusk.write.swapInstruction(
63
331
  traderAssetOutAccount,
64
332
  tokenProgram,
65
333
  token2022Program,
66
- eventAuthority,
67
- program: dusk.program.programId,
68
334
  },
69
- remainingAccounts: [
70
- // Token-2022 transfer-hook extras only. The SDK preserves this tail.
71
- ],
72
335
  }
73
336
  );
74
337
  ```
@@ -76,47 +339,172 @@ const ix = await dusk.write.swapInstruction(
76
339
  `swapBuilder(...)`, `swapInstruction(...)`, `swapTransaction(...)`, and
77
340
  `swapRpc(...)` fetch the market before building the swap. Whenever either hLP
78
341
  side has nonzero supply or residual exposure, they prepend the canonical
79
- five-account prefix exactly once: `[yLP mint, base hLP yLP vault, quote hLP yLP
80
- vault, base interest vault, quote interest vault]`. Caller-provided Token-2022
81
- transfer-hook extras remain after that prefix.
342
+ five-account prefix exactly once: `[srLP mint, base hLP srLP vault, quote hLP srLP
343
+ vault, base interest vault, quote interest vault]`. Caller-provided remaining
344
+ accounts remain after that prefix.
345
+
346
+ The write client supplies the canonical event-CPI authority and Dusk program
347
+ accounts for instructions that emit CPI events.
82
348
 
83
349
  `write.builder(...)`, `write.transaction(...)`, and `write.rpc(...)` expose the
84
350
  same generic path for every Dusk instruction in the IDL.
85
351
 
86
- hLP deposits and withdrawals use async composite builders because both
87
- asset-denominated `YieldAccount` PDAs must exist before the liquidity
88
- instruction runs. The SDK validates their owner, exact layout size, and Anchor
89
- discriminator. If either account is missing or is only a prefunded System PDA,
90
- it prepends the permissionless, idempotent initializer in the same transaction:
352
+ ### Leverage funding
353
+
354
+ Leverage positions accept margin only in the debt token: USDC for a META long,
355
+ META for a META short. `buildOpenLeverageInstruction` swaps the credited margin
356
+ plus borrowing into the opposite token held as collateral. `closeLeverageInstruction`
357
+ sells exposure, repays the debt and returns the residual in the debt token.
358
+ An application can swap a different wallet token into the required funding token
359
+ before opening; the protocol has no optional collateral-funded mode.
360
+
361
+ ### Position actions
362
+
363
+ See [the position action contract](../../docs/LEVERAGE_POSITION_ACTIONS.md) for
364
+ amount units, rounding and the six agreed controls. All sizing is in the debt
365
+ token on both market directions; neither token needs to be a stablecoin.
366
+
367
+ - `increaseLeverageInstruction`: borrow and buy, with no wallet funding.
368
+ - `addToLeverageInstruction`: swap `marginAmount` (gross debt-token funding) plus
369
+ `debtAmount` into held collateral. Select leverage for the whole resulting
370
+ position; `planLeverageIncrease` defaults to its current leverage.
371
+ - `addLeverageMarginInstruction` / `repayLeverageInstruction`: repay debt without
372
+ swapping held collateral. No standalone margin withdrawal is supported.
373
+ - `decreaseLeverageInstruction`: sell collateral into repayment, including full
374
+ repayment to 1x. `maxSurplusOut` defaults to zero and explicitly bounds any
375
+ gross surplus returned to the owner's debt-token account.
376
+ - `closeLeverageInstruction`: `closeBps` selects a proportional owner partial
377
+ close; omit it for a full close. `minAmountOut` is net wallet receipt.
378
+
379
+ `leverageActionMetrics`, `planLeverageIncrease`, `planLeverageDecrease`,
380
+ `planLeverageRepayAll`, `leverageRepaymentQuote`, `leverageCloseSlice` and
381
+ `leverageClosePercentage` support linked controls with bigint arithmetic.
382
+ Sizing callbacks must use same-snapshot, fee-adjusted internal quotes. For a
383
+ final executable check, simulate the actual action:
384
+
385
+ ```ts
386
+ const ix = await dusk.write.addToLeverageInstruction({
387
+ ...positionAccounts,
388
+ ownerDebtAccount,
389
+ marginAmount: 100_000_000n,
390
+ debtAmount: 200_000_000n,
391
+ minCollateralOut,
392
+ });
393
+ const preview = await dusk.get.previewLeverageAction({
394
+ market, leveragePosition, instructions: [ix], feePayer: owner,
395
+ });
396
+ // Review preview.walletFlows, preview.metrics, and preview.marginTerms.
397
+ // Simulation never submits or signs the transaction.
398
+ ```
399
+
400
+ Metrics returned by this preview use the symmetric EMA, before any hypothetical
401
+ liquidation costs. They are not executable close payout or liquidation eligibility;
402
+ the actual action's wallet flows come from its simulated settlement events.
403
+
404
+ ### Swap and LP Transfer Events
405
+
406
+ `SwapExecuted` records the market immediately after a completed trade: the
407
+ internal srLP supply and, per side, a `MarketSideSnapshot` with the spot price
408
+ and price EMA exactly as `preview_market` reports them for the same state and
409
+ slot, plus the swap-fee and interest growth indexes. `start_price_nad` is the
410
+ Base price actually used to quote that trade, after any pending controller
411
+ step. Swap events provide historical execution and post-swap observations;
412
+ they are not a continuous live-price feed. For a prospective quote, use
413
+ `preview_swap` with the intended input and current state rather than treating
414
+ the last event's post-swap spot as the next trade's starting price.
415
+
416
+ `LpTransferred` reports each srLP or hLP transfer through the Dusk transfer
417
+ hook as an ordinary CPI event. `buildLpTransferHookAccountMetas` includes the
418
+ event authority the hook needs; Token-2022 ignores it for mints initialized
419
+ with the earlier seven-entry list, which transfer without a receipt.
420
+ `buildLpTransferHookValidationAccountData({ ..., legacyLayout: true })`
421
+ encodes that earlier list.
422
+
423
+ ### Market operator
424
+
425
+ `dusk.operator` builds transactions without signing or submitting them. The
426
+ operator starts as the deployer. LP balances confer no authority in Dusk.
427
+ An external governance program may own the role using a signer PDA; its voting
428
+ and token economics remain outside the core program.
91
429
 
92
430
  ```typescript
93
- const { transaction, setupInstructions, baseYieldAccount, quoteYieldAccount } =
94
- await dusk.write.depositSingleSided(
95
- { depositAmount, minHlpAmount },
96
- {
97
- payer: owner,
98
- owner,
99
- market,
100
- targetHlpMint,
101
- baseMint,
102
- quoteMint,
103
- accounts: depositAccounts,
104
- }
105
- );
431
+ import { feeParameterUpdate, createProposalMetadata } from "@omnipair/dusk-sdk";
432
+ const metadata = await createProposalMetadata({
433
+ title: "Update swap fees", markdown, descriptionUri: "ipfs://pinned-description",
434
+ });
435
+ const announcement = await dusk.operator.announce({
436
+ market, operator, payer, metadata,
437
+ updates: [feeParameterUpdate(nextFeeProfile)],
438
+ });
439
+ // operator signs; a separate funded payer pays account rent.
440
+ const pending = await dusk.operator.proposal(announcement.proposal);
441
+ const verified = await dusk.operator.verifyDigest(pending);
442
+ // After pending.executeAfterSlot, anyone may execute within the window.
443
+ const execution = await dusk.operator.execute({market, proposal: announcement.proposal});
444
+ const cancellation = await dusk.operator.cancel({market, proposal: announcement.proposal, operator});
445
+ ```
446
+
447
+ The announcement waits **4,752,000 scheduled slots** (maximum junior notice plus
448
+ one protocol day), then has a seven-day scheduled-slot execution window. There
449
+ is one current bundle per market. Replacing it restarts the full notice; stale,
450
+ executed or expired accounts may be closed to their original payer with
451
+ `dusk.operator.resolve`. Pending changes never lock LP receipts or exits.
452
+
453
+ To transfer authority, announce `nextOperator`; execution also requires
454
+ `acceptingOperator` to sign. A governance program accepts through CPI using its
455
+ PDA. An explicit all-zero next authority permanently renounces control; there
456
+ is no LP election or automatic deployer fallback. The monotonically increasing
457
+ nonce prevents reusing a closed announcement address.
458
+
459
+ Use `feeParameterUpdate`, `concentrationParameterUpdate`, `irmParameterUpdate`,
460
+ `emaHalfLivesParameterUpdate`, `dailyBorrowLimitParameterUpdate`,
461
+ `centerControllerParameterUpdate` and `trancheParameterUpdate` for the seven
462
+ mutable families. Updates are canonicalized and execute atomically. The oracle
463
+ policy and initial APR cannot appear in an operator update. APR has a fixed 1%
464
+ floor, no selectable ceiling, and a 12-hour–30-day half-life. The centering update
465
+ contains only the adaptive minimum step; concentration always retains the
466
+ funded EMA controller.
106
467
 
107
- // setupInstructions is empty when both canonical accounts are already valid.
108
- await provider.sendAndConfirm(transaction);
468
+ A concentration update includes `rampDurationSlots` (default/minimum 432,000).
469
+ Positive targets obey the 0.1×–10× rule; zero-width transitions still require the
470
+ announced guarded ramp. Swaps lazily attempt intermediate geometry. A rejected
471
+ step leaves the existing curve usable and does not prevent repayment or exits.
472
+
473
+ `createProposalMetadata` / `uploadProposalMetadata` verify exact UTF-8 Markdown,
474
+ length and SHA-256 before building metadata. `tryFetchProposalDescription`
475
+ returns verified content or a warning. Render verified Markdown with sanitized
476
+ GitHub-flavored Markdown and raw HTML disabled. Description availability never
477
+ controls execution. `verifyDigest` reproduces the on-chain Borsh commitment
478
+ using the generated account layout.
479
+
480
+ Operator interest revenue is 0–50% of base interest, set at creation or changed
481
+ by a timed bundle. There is no operator swap revenue. The separate global
482
+ FutarchyAuthority markup is added on top of base interest. Each market closes
483
+ the old interval before adopting the latest global setting at its next checkpoint.
484
+ The stored `debt.*RateAtTargetNad` is base APR. Apply the market's cached
485
+ `protocolInterestMarkupBps` when displaying total borrower APR; the borrow
486
+ index already includes that markup, so do not add it again to indexed debt.
487
+ For $100 base interest, 30% operator share and 20% markup: LPs receive $70,
488
+ the operator $30 and the protocol $20; the borrower pays $120.
489
+
490
+ ```ts
491
+ const claim = await dusk.operator.claim({market, assetMint, payer});
492
+ // For an earlier recipient, pass its sealed revenueEpoch.
109
493
  ```
110
494
 
111
- `withdrawSingleSided(...)` has the same return shape and setup behavior. The
112
- initializer is safe to compose unconditionally, including when a third party
113
- has transferred lamports to the PDA address before initialization.
495
+ Fees are earned on collection. A handoff preserves already collected cash for
496
+ the previous recipient; later payments belong to the new one. `execute` returns
497
+ `setupInstructions` for a recipient archive when needed. Its `transaction`
498
+ already includes them; PDA forwarding must prepend them before forwarding
499
+ `instruction`. Neither claims nor swaps call the external governance program.
114
500
 
115
- LP token accounts should be owned by a wallet that can sign Dusk instructions,
116
- or by a PDA whose controlling program invokes Dusk with `invoke_signed`. SPL
117
- multisig-owned LP accounts are unsupported: Token-2022 transfers can checkpoint
118
- yield to that owner, but the multisig account itself cannot sign Dusk's claim or
119
- recipient-update instruction.
501
+ Virtual-reserve fields and signed debt/collateral event deltas use 128-bit
502
+ values. Keep decoded balances as `BN` or `bigint`; token transfer amounts still
503
+ use the unsigned 64-bit SPL domain. Extreme accrual saturates coherently across
504
+ debt and receivable books and advances its checkpoint without deferring excess
505
+ interest. This introduces no configurable APR cap.
506
+
507
+ See [operator policy and protection details](../../docs/MARKET_OPERATOR.md).
120
508
 
121
509
  ### Referral Interest Sharing
122
510
 
@@ -172,7 +560,7 @@ principal, position debt, interest, health, or liquidation terms.
172
560
 
173
561
  When interest is realized, the partner accrues a governed share of the DAO's
174
562
  interest revenue. Claims always pay a token account owned by the partner's
175
- current recipient, and the SDK resolves Token-2022 transfer-hook accounts:
563
+ current recipient:
176
564
 
177
565
  ```typescript
178
566
  const claimTx = await dusk.write.claimReferralInterestTransaction({
@@ -208,8 +596,13 @@ Available typed previews:
208
596
 
209
597
  - `previewMarket(market)`.
210
598
  - `previewSwap({ market, assetInMint, assetOutMint, exactAssetIn })`.
599
+ Its `amountOut` is the output vault debit after Dusk trading fees.
600
+ `outputTransferFee` is the fee withheld by the output mint at the simulated
601
+ epoch, and `netAmountOut` is the recipient credit used by the swap's
602
+ `minAssetOut` check. `grossAmountOut` is before Dusk trading fees.
211
603
  - `previewBorrowCapacity({ market, collateralAssetMint, debtAssetMint, collateralAmount, projectedBorrowAmount })`.
212
- - `previewBorrowPosition({ market, borrowPosition })`.
604
+ - `previewBorrowPosition({ market, borrowPosition, baseMint, quoteMint })`.
605
+ - `previewBorrowPositionCapacity({ capacityKind, market, borrowPosition, collateralAssetMint, debtAssetMint, collateralChange, projectedBorrowAmount })`.
213
606
 
214
607
  `previewBorrowCapacity` exposes both the health-limited result of the on-chain
215
608
  binary search and the final limit after cash and daily-borrow constraints:
@@ -236,6 +629,46 @@ capacity.projectedGlobalMarketHealthBps;
236
629
  capacity.projectedEffectiveExistingDebtNad;
237
630
  ```
238
631
 
632
+ For an existing borrow account, use `previewBorrowPositionCapacity` instead of
633
+ adding its debt to `previewBorrowCapacity`. The account-aware preview accrues
634
+ interest and replaces the account's own market-health contribution, using the
635
+ same calculations as the borrow and withdrawal instructions.
636
+
637
+ ```typescript
638
+ const capacity = await dusk.get.previewBorrowPositionCapacity({
639
+ capacityKind: "borrow",
640
+ market,
641
+ borrowPosition,
642
+ collateralAssetMint: baseMint,
643
+ debtAssetMint: quoteMint,
644
+ collateralChange: new BN(0),
645
+ projectedBorrowAmount: null, // Maximum additional draw; BN(0) means no draw.
646
+ });
647
+
648
+ capacity.existingDebtAmount; // Accrued debt already owed.
649
+ capacity.maxBorrowAmount; // Additional vault debit in borrow mode.
650
+ capacity.projectedDebtAmount; // Existing debt plus the draw, with share rounding.
651
+ capacity.maxWithdrawAmount; // Collateral vault debit in withdraw mode.
652
+ capacity.borrowAllowed; // The requested draw is inside capacity limits.
653
+ ```
654
+
655
+ Choose `capacityKind: "borrow"` for borrowing or `"withdraw"` for collateral
656
+ withdrawal. Only that limit is calculated; the other field is `null`. This keeps
657
+ the preview within the transaction compute budget at ordinary token scales.
658
+ Withdrawal mode permits only a zero or omitted projected draw.
659
+
660
+ `collateralChange` is a signed raw-unit delta: a positive value is the **net**
661
+ collateral credit after inbound transfer fees; a negative value is a vault
662
+ withdrawal debit. Invalid withdrawals fail the preview. A zero draw preserves
663
+ the position's issued liquidation factor; a draw quotes the terms of that draw.
664
+ Withdrawal capacity is measured after the collateral delta and before any
665
+ additional borrowing. Outbound transfer fees may reduce wallet receipts.
666
+
667
+ The instruction reads market and position accounts without persisting its
668
+ hypothetical changes, including when submitted with writable account metas.
669
+ Capacity does not replace transaction-time permission, reduce-only, token
670
+ account, referral, slippage, or fresh deployment checks.
671
+
239
672
  ## Fetch Historical Data
240
673
 
241
674
  ```typescript
@@ -268,6 +701,58 @@ const program = createDuskProgram({ provider });
268
701
  `DUSK_PROGRAM_ID` is exported for integrations that prefer an explicit program
269
702
  name over the generic `PROGRAM_ID` constant.
270
703
 
704
+ ### TypeScript and the IDL size
705
+
706
+ The Dusk IDL carries over 150 types. Anchor's `IdlTypes`, `IdlAccounts`, and
707
+ `IdlEvents` decode every type eagerly, several passes deep, which exceeds
708
+ TypeScript's fixed instantiation budget and fails with "Type instantiation is
709
+ excessively deep and possibly infinite" wherever `Program<Dusk>` or the
710
+ exported account and event types are used. This repository rewrites the
711
+ installed Anchor declarations with a lazily recursive decoder from
712
+ `scripts/patch_anchor_idl_types.js` during `postinstall`. Consumers that type
713
+ against `Program<Dusk>` need the same rewrite of
714
+ `@coral-xyz/anchor/dist/*/program/namespace/types.d.ts` until Anchor changes
715
+ the decoder upstream; the rewrite applies unchanged to Anchor 0.31 and 0.32.
716
+
717
+ ## LP Mint Bootstrap
718
+
719
+ `initialize_market` takes three existing Token-2022 LP mints. Production builds
720
+ require their addresses to end in `srLP` (the srLP mint) and `hLP` (both hLP
721
+ mints). The SDK produces them as `create_with_seed` accounts of the creator,
722
+ so the creator is the only signer:
723
+
724
+ ```typescript
725
+ import {
726
+ createHookedLpMintWithSeedInstructions,
727
+ grindMarketLpMintSeeds,
728
+ lpMintRent,
729
+ marketLpTokenNaming,
730
+ } from "@omnipair/dusk-sdk";
731
+
732
+ const seeds = await grindMarketLpMintSeeds({ base: creator }); // vanity.omnipair.fi
733
+ const rent = await lpMintRent(connection);
734
+ const srlp = await createHookedLpMintWithSeedInstructions({
735
+ payer: creator, base: creator, seed: seeds.srlp.seed, mint: seeds.srlp.mint,
736
+ decimals, mintAuthority: market, transferHookProgramId: PROGRAM_ID, lamports: rent,
737
+ });
738
+
739
+ const naming = marketLpTokenNaming({ baseSymbol: "META", quoteSymbol: "USDC" });
740
+ // naming.srlp -> { name: "META/USDC srLP", symbol: "srME/US", description }
741
+ // naming.baseHlp -> { name: "hMETA", symbol: "hMETA.USDC", description }
742
+ // naming.quoteHlp -> { name: "hUSDC", symbol: "hUSDC.META", description }
743
+ ```
744
+
745
+ `grindLpMintSeed` asks the vanity server for a seed with `owner` set to
746
+ Token-2022 and re-derives the address locally before returning it; a server
747
+ that ground the wrong suffix or owner is rejected. Names are written once by
748
+ `initialize_market` and cannot be changed afterwards, so use `lpTokenNaming`
749
+ rather than ad-hoc strings. Pass the three names, symbols, and URIs through
750
+ `initializeMarketInstruction`; `marketCreationLookupTablePlan` and
751
+ `marketCreationV0Transaction` build the v0 transaction once the lookup table is
752
+ active. The metadata JSON and images that
753
+ the URIs point to are produced by `scripts/lp-metadata/` in the dusk
754
+ repository.
755
+
271
756
  ## ESM Compatibility
272
757
 
273
758
  This package ships strict ESM-compatible output. Relative module specifiers
@@ -276,3 +761,339 @@ include `.js` extensions in emitted files.
276
761
  ## License
277
762
 
278
763
  MIT
764
+
765
+ ## Token amounts and UI extensions
766
+
767
+ Dusk instruction amounts, token balances, and amount previews are raw integer
768
+ atoms (`BN`/`bigint`). The program supports Token-2022 group metadata,
769
+ `InterestBearingConfig`, and `ScaledUiAmount` on underlying assets. Group
770
+ metadata does not change settlement. Interest and UI multipliers change only
771
+ the displayed denomination; the SDK does not automatically apply them.
772
+
773
+ For these mints, dividing raw amounts by `10 ** decimals` alone is not a correct
774
+ wallet display. Use the Token-2022 program's `AmountToUiAmount` and
775
+ `UiAmountToAmount` instructions through RPC simulation with the current mint
776
+ state and clock. Refresh conversions after multiplier/rate updates or scheduled
777
+ changes take effect. Keep raw amounts as integers throughout transaction
778
+ construction; token-program UI conversion uses floating-point arithmetic and
779
+ must not be used as a lossless accounting round trip.
780
+
781
+ Dusk prices and price limits use fixed mint-decimal units, with nine-decimal NAD
782
+ precision, independently of UI multipliers. Convert UI prices at the client
783
+ boundary as well: if raw-decimal price is quote per base, displayed price is
784
+ `price * quote_display_multiplier / base_display_multiplier`. Interest-bearing
785
+ mints have a time-dependent display factor. Existing orders keep their original
786
+ raw price limits when the issuer changes the display. A display increase alone
787
+ does not create collateral or Dusk yield.
788
+
789
+ The token extension semantics are described in Solana's
790
+ [scaled UI amount](https://solana.com/docs/tokens/extensions/scaled-ui-amount) and
791
+ [interest-bearing token](https://solana.com/docs/tokens/extensions/interest-bearing-tokens)
792
+ documentation.
793
+
794
+ ## Shared virtual-book previews and simulation context
795
+
796
+ Use `dusk` for a `Dusk` client instance. The SDK owns native preview construction,
797
+ account decoding, concentration sampling, cumulative quote batching, and
798
+ fee-inclusive depth projection:
799
+
800
+ ```ts
801
+ const snapshot = await dusk.get.previewVirtualBook(market, {
802
+ minContextSlot: verifiedSlot,
803
+ groupingBps: 10,
804
+ signal,
805
+ });
806
+
807
+ // snapshot.book contains bid/ask prices, cumulative sizes, fees, and surcharge.
808
+ // snapshot.slot / firstQuoteSlot identify the actual simulation banks.
809
+ // snapshot.observedAt is the first request's start time, not delivery time.
810
+ // snapshot.account is the accrued market returned by simulation.
811
+ ```
812
+
813
+ These display previews use confirmed banks. Supported groupings are 5, 10, 25,
814
+ 50, and 100 bps. A capture uses one market preview and at most six batches of
815
+ four swap previews. Batches must agree on market, mint and authority state,
816
+ epoch, and start price, with a maximum eight-slot spread. Output amounts include
817
+ Token-2022 transfer fees at the simulated epoch and the program's size-dependent
818
+ fees. Depth is display data; use a fresh preview for a user's exact transaction.
819
+
820
+ Applications that bracket each stage with their own deployment checks can call
821
+ `dusk.get.previewVirtualBookSnapshot(market, options)` and
822
+ `dusk.get.previewVirtualBookQuotes(snapshot, options)` separately, then
823
+ `projectDuskVirtualBook(quotes)`. `previewVirtualBookBatch(snapshot, requests,
824
+ options)` is available for one to four explicit cumulative inputs.
825
+
826
+ For other preview workflows, retain full RPC provenance instead of only return
827
+ data:
828
+
829
+ ```ts
830
+ const result = await dusk.get.simulateWithContext([previewInstruction], {
831
+ minContextSlot: verifiedSlot,
832
+ accounts: [market, baseMint, quoteMint],
833
+ signal,
834
+ timeoutMs: 10_000,
835
+ });
836
+
837
+ result.context.slot; // Actual RPC simulation slot.
838
+ result.value.accounts; // Ordered post-simulation accounts from that bank.
839
+ result.value.returnData;
840
+ result.value.logs;
841
+ result.observedAt;
842
+ ```
843
+
844
+ The existing `get.previewSwap` and other decoded preview APIs remain compatible.
845
+ The SDK does not select deployments, attest program binaries, schedule refreshes,
846
+ set cache expiry, coordinate database locks, or stream to subscribers. Those
847
+ remain application responsibilities; validate deployment identity before and
848
+ after a capture. Cancellation and timeout bound the caller's wait; they do not
849
+ necessarily cancel an RPC request already sent over the transport.
850
+
851
+ ### Mutable transfer-fee notice monitoring
852
+
853
+ ```ts
854
+ import { DuskLiquidations, transferFeeCredit } from "@omnipair/dusk-sdk";
855
+ const liquidations = new DuskLiquidations(program, keeperPublicKey);
856
+ const notice = await liquidations.transferFeeNotices({
857
+ market, position, kind: "leverage", debtAsset: "quote",
858
+ });
859
+ // Each mint and Clock were read from the same RPC bank.
860
+ console.log(notice.slot, notice.epoch, notice.collateral.phase);
861
+ const actualReceipt = transferFeeCredit(grossCollateral, notice.collateral, "effective");
862
+ const healthCredit = transferFeeCredit(grossCollateral, notice.collateral, "liquidation");
863
+ ```
864
+
865
+ `fetchTransferFeeNotices(connection, mints, { minContextSlot })` also supports
866
+ 1–99 mints per coherent request. Monitor both debt and collateral mint
867
+ `refreshKey`s and poll epochs even when mint data does not change. `nextRecheckEpoch`
868
+ is the next notice/activation boundary, not an instruction to wait until then.
869
+ A change or cancellation invalidates prior health/payment estimates. Refresh the
870
+ on-chain flash/emergency preview and simulate the complete transaction before
871
+ signing; these helpers do not prove eligibility or promise a fill. Use effective
872
+ fees for actual transfers, never a pending fee as a current payment fee.
873
+
874
+ See [the fee policy and keeper rollout dependency](../../docs/mutable-transfer-fees.md).
875
+ #287160 has implemented notice-window mitigation; timely confirmed keeper execution
876
+ remains an operational assumption. Fee-authority revocation is not a missing
877
+ agreed fix.
878
+
879
+ ### hLP funding capacity
880
+
881
+ Use `dusk.get.previewHlpDepositCapacity({ market, baseMint, quoteMint, targetHlpMint })`
882
+ to read the native entry status and gross/net funding ceilings. It accrues the
883
+ market in a read-only simulation and prices the underlying srLP purchase and
884
+ hedge using full live-reserve value, including public unpaid interest. These
885
+ receivables remain excluded from swap-pricing reserves.
886
+
887
+ `Ready` and the capacity ceiling do not guarantee execution for every amount.
888
+ Simulate the completed deposit transaction to check rounding, cash custody,
889
+ transfer fees and slippage. Under concentration, an opposite-token-neutral
890
+ hLP need not have a literal 2x gross-value/equity ratio.
891
+
892
+ ### Public-interest cash advance calculations
893
+
894
+ `quoteInterestAdvanceAmounts` computes the cash-capped gross advance, frozen
895
+ protocol escrow, LP transfer debit and measured-fee-adjusted LP credit. Pass
896
+ amounts as `bigint` and the current `TransferFeeNotice`; pending transfer fees
897
+ are reported separately by that notice and do not replace the effective fee.
898
+ `allocateRepaidInterest` splits measured repayment custody credit between
899
+ fresh LP/protocol revenue and the already-frozen protocol portion. Already
900
+ funded LP interest must be excluded from `freshGrossInterest`.
901
+
902
+ For transaction composition, use the vault-aware yield client:
903
+
904
+ ```ts
905
+ const quote = await dusk.yield.previewFunding({ market, caller });
906
+ const plan = await dusk.yield.buildHarvest({
907
+ market, owner, caller, kind: "baseHlp", asset: "quote",
908
+ // Optional per-asset gross advance caps, in raw atoms:
909
+ maxBaseGross: 0n, maxQuoteGross: 1_000_000n,
910
+ });
911
+ // Simulate the complete plan.transaction before signing and sending.
912
+ ```
913
+
914
+ `kind` accepts `srlp`, `baseHlp` and `quoteHlp`. The builder reads the owner's
915
+ YieldAccount, respects its configured recipient and creates that recipient's
916
+ ATA if needed. Existing yield accounts are required. Builders never sign or send.
917
+ Set `fundAccruedInterest: false` to harvest existing funded claims without a new
918
+ funding/rebalance attempt. `fundInstruction` is the standalone funding builder.
919
+
920
+ Funding moves only available cash. Newly earned hLP income first covers the
921
+ vault-wide funding gap; existing funded holder claims are protected. The hedge
922
+ reconstruction can change the AMM mark; the cash advance alone leaves swap
923
+ reserves unchanged. `HlpInterestAllocated` distinguishes new holder yield from
924
+ capital returned to reserves. Subtract its capital debits from gross
925
+ `BorrowInterestPaid` credits when reconciling net interest-vault changes.
926
+
927
+ Repayment builders supply the canonical accounts needed for both hLP vaults.
928
+ Raw callers must include the five existing hLP accounts followed by both asset
929
+ mints and reserve vaults when fresh public interest is settled with active hLP.
930
+ The Market layout is version 11 with `fees.publicInterestAdvance` on both sides,
931
+ per-vault flash locks, and non-cash `reserves.flashReceivable`;
932
+ use the regenerated IDL. It also records a frozen hLP mask and per-vault
933
+ curve offsets; older snapshots are incompatible.
934
+
935
+ ### Vault-wide hLP flash recovery
936
+
937
+ For a solvent vault, this is a **flash rescue** of its funding hedge. A positive
938
+ funding gap can be quoted before the 112.5% critical-stress marker. Ordinary
939
+ swaps can also earn a recovery bonus below that marker. The on-chain flash
940
+ quote caps the discount to retain positive vault value;
941
+ it may offer no discount for a tiny gap. A frozen vault can also quote a funded
942
+ rescue after its gap falls. Full flash closeout remains restricted to insolvency
943
+ at the current-slot symmetric EMA; the caller's fixed payment determines actual
944
+ flash recovery.
945
+
946
+ ```ts
947
+ const quote = await dusk.hlpLiquidations.preview({ market, targetAsset: "base" });
948
+ const plan = await dusk.hlpLiquidations.buildFlash({
949
+ market, targetAsset: "base", buyer,
950
+ allowFull: false, // explicit opt-in is required for an insolvent full closure
951
+ route: async ({ buyerCollateralAccount, repaymentVault, requiredPaymentCredit,
952
+ collateralMint, debtMint, collateralTokenProgram, debtTokenProgram }) => {
953
+ // Return an external route, a Dusk swap, or explicit inventory payment.
954
+ // Deliver requiredPaymentCredit NET atoms into repaymentVault; gross up
955
+ // its incoming transfer fee. The quote already includes vault→reserve fees.
956
+ return buildRecoveryRoute({ buyerCollateralAccount, repaymentVault,
957
+ requiredPaymentCredit, collateralMint, debtMint, collateralTokenProgram, debtTokenProgram });
958
+ },
959
+ });
960
+ // Compile plan.instructions with a prepared address lookup table when needed.
961
+ // Do not insert/reorder instructions: begin binds the exact settle index.
962
+ ```
963
+
964
+ The helpers never sign, submit, or silently top up from the keeper's wallet.
965
+ The quote is current-bank only. `maxPayment`, collateral limits and
966
+ principal-loss caps protect the submitted plan against state drift. Prefix
967
+ instructions must be supplied through `prefixInstructions` before building.
968
+ An affected hLP cohort cannot mint/redeem between begin and settle; swaps and
969
+ independent market operations remain composable subject to cash and accounting
970
+ checks. The SDK's complete-plan simulator preserves bound instruction indices.
971
+ `HlpFlashSettled.loss` separates principal recovery,
972
+ principal writeoff and canceled interest; a partial recovery has an empty loss
973
+ allocation. Native `HlpTerminalLiquidated.socializedLoss` now denotes principal
974
+ loss only, with `interestCanceled` reported separately.
975
+
976
+ If an hLP vault has negative executable value, ordinary spot swaps continue.
977
+ Only that vault's automatic hedge is frozen; the opposite vault remains active.
978
+ `state.amm.frozenHlpMask` uses bit 1 for base hLP and bit 2 for quote hLP.
979
+ The frozen vault cannot make an ordinary withdrawal that leaves its deficit to
980
+ the other holders. A terminal close requires insolvency at the current-slot
981
+ symmetric EMA, so a spot-only price move cannot write off the vault. Native
982
+ recovery is then valued on the EMA-price, smoothed-depth concentrated reference
983
+ curve with the configured fees; it does not use live spot reserves.
984
+
985
+ An eligible holder can build `hlpLiquidations.buildNativeCloseAndExit({ market,
986
+ targetAsset, exit: { hlpAmount, options } })`. The helper places the permissionless
987
+ native close before `withdrawSingleSided` in one transaction; `options` are the
988
+ normal hLP withdrawal accounts and the owner signs. It burns the closed vault's
989
+ receipts for zero principal payout. The flash builder also accepts `exit`,
990
+ appending an owner-signed withdrawal after settlement. For a solvent rescue,
991
+ set `exit.minTargetAmountOut` to protect the holder's payout. A terminal quote
992
+ still requires `allowFull` and pays zero principal. A vault with only a
993
+ transient spot deficit must recover or receive funded rescue before its holders
994
+ can withdraw. Once its executable value recovers, a frozen vault can quote a
995
+ funded flash rescue even if its debt gap has fallen below the ordinary rescue
996
+ threshold; a fully covered gap uses a minimal zero-discount payment.
997
+
998
+ Spot swap previews use the same cash policy as execution. If paying all accrued
999
+ hLP funding interest would consume the cash needed for trader output or the
1000
+ last reserve atom, Dusk requotes the swap while carrying both active hLP
1001
+ funding-interest amounts on their indexed debts. That swap pays no hLP funding
1002
+ interest and offers no hLP recovery bonus. A later swap with sufficient reserve
1003
+ cash can settle the carried interest. The trader's output still requires
1004
+ spendable reserve cash; this fallback does not create liquidity.
1005
+
1006
+ ### Restarting after a terminal hLP close
1007
+
1008
+ When a terminal close leaves old hLP receipts outstanding, a new deposit needs
1009
+ a fresh receipt mint. Create a zero-supply hooked hLP mint with the market as
1010
+ mint authority, then call `write.rotateHlpCohortInstruction` with the old and
1011
+ new mints, target side and Metaplex metadata. The old mint's transfer hook must
1012
+ be initialized first; `write.initializeLpTransferHookInstruction` accepts
1013
+ `tokenKind: "hlp"` when composing that setup without an RPC market fetch.
1014
+ Initialize the new mint's hook, then deposit using the new mint. The other hLP
1015
+ side and srLP mint do not rotate.
1016
+
1017
+ The old mint remains transferable but owns no new principal. Its holder yield
1018
+ indexes are frozen in `deriveHlpCohortAddress(market, oldMint)`. A holder can
1019
+ initialize an old mint's yield accounts with
1020
+ `write.initializeYieldAccountsInstruction({ ..., retired: true })`, claim
1021
+ funded yield through `yield.buildHarvest({ ..., retiredHlpMint: oldMint })`, and
1022
+ burn old receipts with `write.burnRetiredHlpReceiptInstruction`. If the asset
1023
+ has a Token-2022 transfer hook, pass its extra accounts as
1024
+ `transferHookAccounts` to the harvest builder. Burning never forfeits yield
1025
+ already checkpointed in the holder's yield accounts.
1026
+
1027
+ ## srLP, jrLP and hLP
1028
+
1029
+ `srLP` is the default senior claim. `jrLP` owns productive first-loss capital;
1030
+ entering junior burns srLP and mints jrLP at their current values. `hLP` remains
1031
+ a hedged position backed by senior liquidity and cannot enter junior. Its own
1032
+ unpaid income remains in NAV, and collected income pays funding costs first.
1033
+
1034
+ ```ts
1035
+ const setup = await dusk.tranches.initialize({ market, payer });
1036
+ // Sign and submit setup.transaction once for this junior generation.
1037
+ const enter = await dusk.tranches.convert({
1038
+ market, owner,
1039
+ action: { kind: "enter", seniorAmount: 1_000_000n, minimumJunior: 990_000n },
1040
+ });
1041
+ // Sign and submit enter.transaction. Amounts are raw token atoms.
1042
+ const request = await dusk.tranches.convert({
1043
+ market, owner, action: { kind: "requestExit", additionalJunior: 500_000n },
1044
+ });
1045
+ ```
1046
+
1047
+ Exit requests escrow receipts. They continue earning junior income and taking
1048
+ losses during notice and the exercise window. After notice, `convertExit` burns
1049
+ the escrowed jrLP and mints srLP at its current value. It does not withdraw cash.
1050
+ Read the returned `exit` account for its actual `readyAt` and `expiresAt` slots;
1051
+ the configured crowding rule determines the notice. An expired request must be
1052
+ renewed or canceled. Conversion can also be blocked by an unsettled insolvent
1053
+ liquidation. A failed transaction does not silently extend a window.
1054
+
1055
+ Income earned before an ordinary LP transfers or converts remains with that
1056
+ holder. Each asset has separate public-loan and hLP-funding income histories.
1057
+ The SDK exposes bounded maintenance transactions; none are submitted implicitly:
1058
+
1059
+ 1. Before issuing income into a fully collected book, call
1060
+ `prepareDrainedIncomeBooks({ market, payer })` and submit its transactions.
1061
+ For `IncomeEpochNeedsRollover` on a partially paid book, use `rollIncome` for
1062
+ the affected book. The payer funds its immutable archive account.
1063
+ 2. For an existing srLP/jrLP holder, call
1064
+ `prepareHolderIncome({ market, owner, kind: "senior" | "junior" })`.
1065
+ Submit its transactions and repeat while `hasMore` is true. Each instruction
1066
+ processes at most eight archived epochs for one source.
1067
+ 3. Fetch again and build the transfer, conversion or harvest. A competing
1068
+ maintenance transaction can require another catch-up; builders do not
1069
+ guarantee that the market stays unchanged between fetch and submission.
1070
+
1071
+ Archived history has no fixed lifetime limit. A caller that pays archival rent
1072
+ can roll after settlement, so repayment/roll churn can increase other holders'
1073
+ catch-up work. Eight epochs per instruction bounds transaction work, not total
1074
+ history. Integrators should maintain active holders, retry stale plans and expose
1075
+ maintenance transactions in their UX; this mechanism does not guarantee a
1076
+ single-transaction exit for an inactive holder.
1077
+
1078
+ `checkpointIncome` also supports one asset/source batch and retired junior
1079
+ mints. Wiped receipts have no principal but may still own historical earnings.
1080
+ `burnRetired` removes those receipts without giving them new-generation capital.
1081
+
1082
+ The permanent junior seed receives income even without external jrLP holders.
1083
+ `fundSeed` moves its collected interest to reserve custody. `compoundSeed`
1084
+ reinvests balanced asset amounts without issuing senior tokens; unmatched assets
1085
+ remain seed-owned custody until a matching amount is available. These custody
1086
+ balances do not count as productive junior coverage until reinvested.
1087
+
1088
+ Rate defaults are exported as `RISK_RATE_DEFAULTS`; the market configuration and
1089
+ creation helpers can override initial terms; the operator can tune future dynamics after notice. `riskCoverageSignalNad` uses one junior
1090
+ capital budget across both debt assets, with each asset's own utilization.
1091
+
1092
+ The operator can appoint a parameter manager using a timed announcement with
1093
+ `nextManager`. Managers cannot change ownership, manager appointments, revenue
1094
+ recipients or the operator interest share, and cannot replace an operator's
1095
+ pending announcement. `dusk.operator.removeManager({market, operator})` revokes
1096
+ the manager immediately and invalidates its pending bundle. Operator-authored
1097
+ bundles are preserved. Every ownership transfer clears the manager; it cannot
1098
+ be retained or replaced in the handoff bundle. The successor appoints a manager
1099
+ through a separate full-notice announcement.