@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
@@ -0,0 +1,295 @@
1
+ import { fetchTransferFeeNotices } from "./transfer-fees.js";
2
+ import type { Program } from "@coral-xyz/anchor";
3
+ import { createAssociatedTokenAccountIdempotentInstruction, getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
4
+ import { ComputeBudgetProgram, PublicKey, SystemProgram, SYSVAR_INSTRUCTIONS_PUBKEY, type AccountMeta, type TransactionInstruction } from "@solana/web3.js";
5
+ import type { Dusk as DuskIdl } from "./types_v2.js";
6
+ import type { EmergencyLiquidationQuote, FlashAmmLiquidationQuote, FlashLiquidationQuote, LiquidationHealth } from "./type-aliases.js";
7
+ import { address, type AddressLike } from "./address.js";
8
+ import { DuskWrite } from "./write.js";
9
+ import { DuskGet } from "./get.js";
10
+ import { previewReturnDataBytes } from "./preview.js";
11
+ import { integerBN, type IntegerLike } from "./parameters.js";
12
+ import { tokenProgramForMint } from "./referral.js";
13
+ import { deriveFutarchyAuthorityAddress, deriveLeverageCollateralVaultAddress, deriveReferralAccrualAddress } from "./constants.js";
14
+ import { deriveLiquidationPaymentAddress, deriveLiquidationSessionAddress } from "./liquidation.js";
15
+
16
+ export type { FlashLiquidationQuote, FlashAmmLiquidationQuote, EmergencyLiquidationQuote };
17
+
18
+ export interface LiquidationPositionParams {
19
+ market: AddressLike;
20
+ position: AddressLike;
21
+ kind: "borrow" | "leverage";
22
+ debtAsset: "base" | "quote";
23
+ }
24
+
25
+ export interface FlashLiquidationParams extends LiquidationPositionParams {
26
+ buyer: AddressLike;
27
+ maxRepayment: IntegerLike;
28
+ full?: boolean;
29
+ /** Net escrow balance increase, including all outgoing transfer gross-ups. */
30
+ maxPayment?: IntegerLike;
31
+ /** Actual buyer receipt after collateral transfer fees. */
32
+ minCollateralCredit?: IntegerLike;
33
+ /** Final debt-token receipt when `settlement` is `duskAmm`. */
34
+ minBuyerCredit?: IntegerLike;
35
+ prefixInstructions?: readonly TransactionInstruction[];
36
+ /** Dusk execution sells the received collateral in the paired settle and
37
+ * nets debt principal internally. External settlement requires route payment. */
38
+ settlement?: "external" | "duskAmm";
39
+ /** Override when the route changes which hLP accounts settlement requires.
40
+ * Supply the complete ordered remaining-account list for the final state. */
41
+ settleRemainingAccounts?: readonly AccountMeta[];
42
+ /** Builds the collateral sale, inventory payment, or mixed route. The
43
+ * resulting instructions run after begin and before the exact paired settle.
44
+ */
45
+ route?: (context: FlashLiquidationRouteContext) => Promise<readonly TransactionInstruction[]> | readonly TransactionInstruction[];
46
+ }
47
+
48
+ export interface FlashLiquidationRouteContext {
49
+ session: PublicKey;
50
+ repaymentVault: PublicKey;
51
+ buyerCollateralAccount: PublicKey;
52
+ buyerDebtAccount: PublicKey;
53
+ collateralMint: PublicKey;
54
+ debtMint: PublicKey;
55
+ debtTokenProgram: PublicKey;
56
+ collateralTokenProgram: PublicKey;
57
+ /** Route must deliver at least this net spendable amount into repaymentVault. */
58
+ requiredPaymentCredit: bigint;
59
+ quote: FlashLiquidationQuote;
60
+ }
61
+
62
+ export interface EmergencyLiquidationParams extends LiquidationPositionParams {
63
+ caller: AddressLike;
64
+ collateralDebit: IntegerLike;
65
+ full?: boolean;
66
+ minRewardCredit?: IntegerLike;
67
+ minSwapOutput?: IntegerLike;
68
+ prefixInstructions?: readonly TransactionInstruction[];
69
+ }
70
+
71
+ function liquidationPrefix(instructions: readonly TransactionInstruction[] = []): TransactionInstruction[] {
72
+ const prefix = [...instructions];
73
+ if (!prefix.some(ix => ix.programId.equals(ComputeBudgetProgram.programId) && ix.data[0] === 1)) {
74
+ prefix.unshift(ComputeBudgetProgram.requestHeapFrame({ bytes: 256 * 1024 }));
75
+ }
76
+ if (!prefix.some(ix => ix.programId.equals(ComputeBudgetProgram.programId) && ix.data[0] === 2)) {
77
+ prefix.unshift(ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }));
78
+ }
79
+ return prefix;
80
+ }
81
+
82
+ /** Fixed-payment liquidation helpers. No method signs or sends a transaction,
83
+ * debits the owner's wallet, or chooses an external routing program.
84
+ */
85
+ export class DuskLiquidations {
86
+ readonly write: DuskWrite;
87
+ readonly get: DuskGet;
88
+
89
+ constructor(readonly program: Program<DuskIdl>, feePayer?: AddressLike) {
90
+ this.write = new DuskWrite(program);
91
+ this.get = new DuskGet(program, feePayer);
92
+ }
93
+
94
+ private async resolve(params: LiquidationPositionParams) {
95
+ if (params.kind !== "borrow" && params.kind !== "leverage") throw new Error("Invalid position kind");
96
+ if (params.debtAsset !== "base" && params.debtAsset !== "quote") throw new Error("Invalid debt asset");
97
+ const market = address(params.market);
98
+ const position = address(params.position);
99
+ const [state, positionState] = await Promise.all([
100
+ this.get.market(market),
101
+ params.kind === "borrow" ? this.get.borrowPosition(position) : this.get.leveragePosition(position),
102
+ ]);
103
+ if (!positionState.market.equals(market)) throw new Error("Position belongs to another market");
104
+ const debtAsset = params.debtAsset === "base" ? 0 : 1;
105
+ if ("debtAsset" in positionState && positionState.debtAsset !== debtAsset) throw new Error("Wrong leverage debt side");
106
+ const debtSide = debtAsset === 0 ? state.baseSide : state.quoteSide;
107
+ const collateralSide = debtAsset === 0 ? state.quoteSide : state.baseSide;
108
+ const readAccounts = { market, borrowPosition: params.kind === "borrow" ? position : null, leveragePosition: params.kind === "leverage" ? position : null, debtMint: debtSide.assetMint, collateralMint: collateralSide.assetMint };
109
+ return { market, position, state, positionState, debtSide, collateralSide, debtAsset, readAccounts };
110
+ }
111
+
112
+ /** Monitor both sides: collateral fees affect health, debt fees affect payment.
113
+ * Re-preview when refreshKey changes, including epoch changes without mint writes.
114
+ * This read does not prove eligibility or reserve a price for a later transaction.
115
+ */
116
+ async transferFeeNotices(params: LiquidationPositionParams, minContextSlot?: number) {
117
+ const r = await this.resolve(params);
118
+ const snapshot = await fetchTransferFeeNotices(this.program.provider.connection,
119
+ [r.debtSide.assetMint, r.collateralSide.assetMint], { minContextSlot });
120
+ return { slot: snapshot.slot, epoch: snapshot.epoch, debt: snapshot.mints[0], collateral: snapshot.mints[1] };
121
+ }
122
+
123
+ /** Simulate current health without committing any observation or timer. */
124
+ async previewHealth(params: LiquidationPositionParams): Promise<LiquidationHealth> {
125
+ const resolved = await this.resolve(params);
126
+ const instruction = await this.write.instruction("previewLiquidationHealth", [resolved.debtAsset], { accounts: resolved.readAccounts });
127
+ const returned = await this.get.simulateReturnData(instruction);
128
+ return this.program.coder.types.decode("liquidationHealth", previewReturnDataBytes(returned)) as LiquidationHealth;
129
+ }
130
+
131
+ /** Returns the executable discount after partial-health affordability checks.
132
+ * The health-based ceiling alone must not be used to construct a payment or route.
133
+ */
134
+ async preview(params: LiquidationPositionParams & { maxRepayment: IntegerLike; full?: boolean }): Promise<FlashLiquidationQuote> {
135
+ const resolved = await this.resolve(params);
136
+ const instruction = await this.write.instruction("previewFlashLiquidation", {
137
+ debtAsset: resolved.debtAsset, maxRepayment: integerBN(params.maxRepayment, "maxRepayment"), full: params.full ?? false,
138
+ }, { accounts: resolved.readAccounts });
139
+ const returned = await this.get.simulateReturnData(instruction);
140
+ return this.program.coder.types.decode("flashLiquidationQuote", previewReturnDataBytes(returned)) as FlashLiquidationQuote;
141
+ }
142
+
143
+ /** Preview the paired Dusk-AMM route through the buyer's final debt-token
144
+ * receipt. This includes both collateral transfers, AMM fees, liquidation
145
+ * distributions, and the final debt-token transfer fee.
146
+ */
147
+ async previewAmm(params: LiquidationPositionParams & { maxRepayment: IntegerLike; full?: boolean }): Promise<FlashAmmLiquidationQuote> {
148
+ const r = await this.resolve(params);
149
+ const instruction = await this.write.instruction("previewFlashAmmLiquidation", {
150
+ debtAsset: r.debtAsset, maxRepayment: integerBN(params.maxRepayment, "maxRepayment"), full: params.full ?? false,
151
+ }, { accounts: { preview: r.readAccounts, futarchyAuthority: deriveFutarchyAuthorityAddress(this.program.programId)[0] } });
152
+ const returned = await this.get.simulateReturnData(instruction);
153
+ return this.program.coder.types.decode("flashAmmLiquidationQuote", previewReturnDataBytes(returned)) as FlashAmmLiquidationQuote;
154
+ }
155
+
156
+ /** Emergency inventory settlement uses the symmetric price EMA and smoothed
157
+ * curve depth, including the configured concentration and full fee schedule.
158
+ * referencePriceNad is debt per collateral (1e9); referenceDepthNad is curve depth,
159
+ * not token atoms or TVL. swapOutput is credited settlement value, not a
160
+ * live-spot trade quote. Eligibility remains linear symmetric-EMA health.
161
+ * Full settlement requires either EMA insolvency or proof that no smaller
162
+ * reference-priced settlement can restore MM + 2 points.
163
+ * A useful below-target partial or external flash quote does not block it.
164
+ * Proof failure remains a rejection; a failed requested slice is not evidence.
165
+ */
166
+ async previewEmergency(params: LiquidationPositionParams & { collateralDebit: IntegerLike; full?: boolean }): Promise<EmergencyLiquidationQuote> {
167
+ const r = await this.resolve(params);
168
+ const instruction = await this.write.instruction("previewEmergencyLiquidation", {
169
+ debtAsset: r.debtAsset, collateralDebit: integerBN(params.collateralDebit, "collateralDebit"), full: params.full ?? false,
170
+ }, { accounts: { preview: r.readAccounts, futarchyAuthority: deriveFutarchyAuthorityAddress(this.program.programId)[0] } });
171
+ const returned = await this.get.simulateReturnData(instruction);
172
+ return this.program.coder.types.decode("emergencyLiquidationQuote", previewReturnDataBytes(returned)) as EmergencyLiquidationQuote;
173
+ }
174
+
175
+ /** EMA inventory liquidation with partial recovery or the approved full fallback.
176
+ * Uses the on-chain preview for sizing, full fees and loss allocation.
177
+ * The program nets principal, pays only funded cash amounts, reconciles real
178
+ * hLP balances and verifies the gates again during execution. The reference
179
+ * returned here identifies the preview's inputs; it is not locked on-chain.
180
+ * Explicit minimums protect the caller if the EMA/fee state changes.
181
+ */
182
+ async buildEmergency(params: EmergencyLiquidationParams) {
183
+ const r = await this.resolve(params);
184
+ const buyer = address(params.caller);
185
+ const [debtTokenProgram, collateralTokenProgram, quote, remainingAccounts] = await Promise.all([
186
+ tokenProgramForMint(this.program.provider.connection, r.debtSide.assetMint),
187
+ tokenProgramForMint(this.program.provider.connection, r.collateralSide.assetMint),
188
+ this.previewEmergency(params), this.write.hlpRemainingAccounts(r.market, r.state),
189
+ ]);
190
+ const buyerCollateralAccount = getAssociatedTokenAddressSync(r.collateralSide.assetMint, buyer, true, collateralTokenProgram);
191
+ const buyerRefundAccount = getAssociatedTokenAddressSync(r.debtSide.assetMint, buyer, true, debtTokenProgram);
192
+ const ownerDebtAccount = getAssociatedTokenAddressSync(r.debtSide.assetMint, r.positionState.owner, true, debtTokenProgram);
193
+ const prefix = liquidationPrefix(params.prefixInstructions);
194
+ const seen = new Set<string>();
195
+ for (const [account, mint, owner, token] of [
196
+ [buyerCollateralAccount, r.collateralSide.assetMint, buyer, collateralTokenProgram],
197
+ [buyerRefundAccount, r.debtSide.assetMint, buyer, debtTokenProgram],
198
+ [ownerDebtAccount, r.debtSide.assetMint, r.positionState.owner, debtTokenProgram],
199
+ ]) {
200
+ if (!seen.has(account.toBase58())) prefix.push(createAssociatedTokenAccountIdempotentInstruction(buyer, account, owner, mint, token));
201
+ seen.add(account.toBase58());
202
+ }
203
+ const p = r.positionState;
204
+ const partner = "referralPartner" in p ? p.referralPartner : r.debtAsset === 0 ? p.baseReferralPartner : p.quoteReferralPartner;
205
+ const referralPartner = partner.equals(PublicKey.default) ? null : partner;
206
+ const accounts = { ...r.readAccounts, buyer, buyerCollateralAccount, buyerRefundAccount, ownerDebtAccount,
207
+ collateralVault: params.kind === "borrow" ? r.collateralSide.collateralVault : deriveLeverageCollateralVaultAddress(r.market, r.collateralSide.assetMint, this.program.programId)[0],
208
+ reserveVault: r.debtSide.reserveVault, interestVault: r.debtSide.interestVault,
209
+ futarchyAuthority: deriveFutarchyAuthorityAddress(this.program.programId)[0], referralPartner,
210
+ referralAccrual: referralPartner ? deriveReferralAccrualAddress(referralPartner, r.market, r.debtSide.assetMint, this.program.programId)[0] : null,
211
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID, debtTokenProgram };
212
+ const instruction = await this.write.instruction("emergencyLiquidation", {
213
+ debtAsset: r.debtAsset, collateralDebit: integerBN(params.collateralDebit, "collateralDebit"), full: params.full ?? false,
214
+ minRewardCredit: integerBN(params.minRewardCredit ?? BigInt(quote.rewardCredit.toString()), "minRewardCredit"),
215
+ minSwapOutput: integerBN(params.minSwapOutput ?? BigInt(quote.swapOutput.toString()), "minSwapOutput"),
216
+ }, { accounts: { accounts, collateralReserveVault: r.collateralSide.reserveVault, instructions: SYSVAR_INSTRUCTIONS_PUBKEY }, remainingAccounts });
217
+ return {
218
+ quote, instruction, instructions: [...prefix, instruction],
219
+ reference: {
220
+ priceNad: BigInt(quote.referencePriceNad.toString()),
221
+ depthNad: BigInt(quote.referenceDepthNad.toString()),
222
+ },
223
+ callerDebtAccount: buyerRefundAccount, ownerDebtAccount,
224
+ };
225
+ }
226
+
227
+ /** Prefix + begin + caller's route + settle, with indices computed last.
228
+ * Do not subsequently prepend/insert instructions; build another plan.
229
+ * The persistent payment account retains withheld Token-2022 fees, avoiding
230
+ * an invalid close-account CPI when the mint charges transfer fees.
231
+ */
232
+ async buildFlash(params: FlashLiquidationParams) {
233
+ const internal = params.settlement === "duskAmm";
234
+ if (params.settlement !== undefined && params.settlement !== "external" && !internal) throw new Error("Invalid flash settlement venue");
235
+ if (!internal && !params.route) throw new Error("External settlement requires an explicit payment route");
236
+ const r = await this.resolve(params);
237
+ const buyer = address(params.buyer);
238
+ const [debtTokenProgram, collateralTokenProgram, preview] = await Promise.all([
239
+ tokenProgramForMint(this.program.provider.connection, r.debtSide.assetMint),
240
+ tokenProgramForMint(this.program.provider.connection, r.collateralSide.assetMint),
241
+ internal ? this.previewAmm(params) : this.preview(params),
242
+ ]);
243
+ const ammQuote = internal ? preview as FlashAmmLiquidationQuote : null;
244
+ const quote = ammQuote ? ammQuote.liquidation : preview as FlashLiquidationQuote;
245
+ const [session] = deriveLiquidationSessionAddress(r.position, this.program.programId);
246
+ const [repaymentVault] = deriveLiquidationPaymentAddress(r.position, r.debtSide.assetMint, this.program.programId);
247
+ const buyerCollateralAccount = getAssociatedTokenAddressSync(r.collateralSide.assetMint, buyer, true, collateralTokenProgram);
248
+ const buyerDebtAccount = getAssociatedTokenAddressSync(r.debtSide.assetMint, buyer, true, debtTokenProgram);
249
+ const ownerDebtAccount = getAssociatedTokenAddressSync(r.debtSide.assetMint, r.positionState.owner, true, debtTokenProgram);
250
+ const prefix = liquidationPrefix(params.prefixInstructions);
251
+ const seen = new Set<string>();
252
+ for (const [account, mint, owner, token] of [
253
+ [buyerCollateralAccount, r.collateralSide.assetMint, buyer, collateralTokenProgram],
254
+ [buyerDebtAccount, r.debtSide.assetMint, buyer, debtTokenProgram],
255
+ [ownerDebtAccount, r.debtSide.assetMint, r.positionState.owner, debtTokenProgram],
256
+ ]) {
257
+ if (!seen.has(account.toBase58())) prefix.push(createAssociatedTokenAccountIdempotentInstruction(buyer, account, owner, mint, token));
258
+ seen.add(account.toBase58());
259
+ }
260
+ const context: FlashLiquidationRouteContext = {
261
+ session, repaymentVault, buyerCollateralAccount, buyerDebtAccount, debtTokenProgram, collateralTokenProgram,
262
+ collateralMint: r.collateralSide.assetMint, debtMint: r.debtSide.assetMint,
263
+ requiredPaymentCredit: internal ? 0n : BigInt(quote.payment.toString()), quote,
264
+ };
265
+ const route = params.route ? [...await params.route(context)] : [];
266
+ const beginIndex = prefix.length;
267
+ const settleIndex = beginIndex + 1 + route.length;
268
+ if (settleIndex > 65_535) throw new RangeError("Too many instructions for the bound settle index");
269
+ const p = r.positionState;
270
+ const partner = "referralPartner" in p ? p.referralPartner : r.debtAsset === 0 ? p.baseReferralPartner : p.quoteReferralPartner;
271
+ const referralPartner = partner.equals(PublicKey.default) ? null : partner;
272
+ const accounts = {
273
+ ...r.readAccounts, buyer, buyerCollateralAccount, buyerRefundAccount: buyerDebtAccount, ownerDebtAccount,
274
+ collateralVault: params.kind === "borrow" ? r.collateralSide.collateralVault : deriveLeverageCollateralVaultAddress(r.market, r.collateralSide.assetMint, this.program.programId)[0],
275
+ reserveVault: r.debtSide.reserveVault, interestVault: r.debtSide.interestVault,
276
+ futarchyAuthority: deriveFutarchyAuthorityAddress(this.program.programId)[0], referralPartner,
277
+ referralAccrual: referralPartner ? deriveReferralAccrualAddress(referralPartner, r.market, r.debtSide.assetMint, this.program.programId)[0] : null,
278
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID, debtTokenProgram,
279
+ };
280
+ const common = { accounts, session, repaymentVault, instructions: SYSVAR_INSTRUCTIONS_PUBKEY };
281
+ const begin = await this.write.instruction("beginFlashLiquidation", {
282
+ position: r.position, debtAsset: r.debtAsset, maxRepayment: integerBN(params.maxRepayment, "maxRepayment"),
283
+ maxPayment: integerBN(params.maxPayment ?? BigInt(quote.payment.toString()), "maxPayment"),
284
+ minCollateralCredit: integerBN(params.minCollateralCredit ?? BigInt(quote.collateralCredit.toString()), "minCollateralCredit"),
285
+ minBuyerCredit: integerBN(internal ? params.minBuyerCredit ?? BigInt(ammQuote!.buyerCredit.toString()) : 0n, "minBuyerCredit"),
286
+ full: params.full ?? false, settleIndex,
287
+ }, { accounts: { ...common, systemProgram: SystemProgram.programId } });
288
+ const settle = await this.write.instruction("settleFlashLiquidation", [], {
289
+ accounts: { ...common, collateralReserveVault: internal ? r.collateralSide.reserveVault : null },
290
+ remainingAccounts: params.settleRemainingAccounts ? [...params.settleRemainingAccounts]
291
+ : internal ? await this.write.hlpRemainingAccounts(r.market, r.state) : [],
292
+ });
293
+ return { ...context, ammQuote, beginIndex, settleIndex, instructions: [...prefix, begin, ...route, settle], beginInstruction: begin, settleInstruction: settle };
294
+ }
295
+ }
@@ -0,0 +1,119 @@
1
+ import { PublicKey, TransactionMessage, VersionedTransaction, type AddressLookupTableAccount, type TransactionInstruction } from "@solana/web3.js";
2
+ import { DEFAULT_PROTOCOL_REVENUE_SHARE_BPS, DUSK_PROGRAM_ID } from "./constants.js";
3
+
4
+ const BPS = 10_000n;
5
+ const U64_MAX = (1n << 64n) - 1n;
6
+ const min = (a: bigint, b: bigint) => a < b ? a : b;
7
+ const max = (a: bigint, b: bigint) => a > b ? a : b;
8
+ const ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;
9
+
10
+ export const LIQUIDATION_POLICY = Object.freeze({
11
+ minimumDiscountBps: 50,
12
+ maximumDiscountBps: 500,
13
+ maximumEmergencyRewardBps: 100,
14
+ emergencyMaintenanceFractionBps: 7_000,
15
+ recoveryBufferBps: 200,
16
+ solventFeeBps: 300,
17
+ protocolFeeShareBps: DEFAULT_PROTOCOL_REVENUE_SHARE_BPS,
18
+ });
19
+
20
+ export interface LiquidationHealthInput {
21
+ /** Linear symmetric-EMA value, in debt token atoms, after eligibility fees. */
22
+ collateralValue: bigint;
23
+ /** Indexed position debt in the same token atoms. */
24
+ debt: bigint;
25
+ maintenanceBps: number;
26
+ }
27
+
28
+ function amount(value: bigint, name: string): void {
29
+ if (typeof value !== "bigint" || value < 0n || value > U64_MAX) {
30
+ throw new RangeError(`${name} must be an unsigned u64 bigint`);
31
+ }
32
+ }
33
+
34
+ /** Gates use exact products. Display equity is deliberately a separate value. */
35
+ export function liquidationHealth(input: LiquidationHealthInput) {
36
+ amount(input.collateralValue, "collateralValue");
37
+ amount(input.debt, "debt");
38
+ if (!Number.isSafeInteger(input.maintenanceBps) || input.maintenanceBps <= 0 || input.maintenanceBps >= 10_000) {
39
+ throw new RangeError("maintenanceBps must be between 1 and 9999");
40
+ }
41
+ const value = input.collateralValue;
42
+ const equity = value - input.debt;
43
+ const required = value * BigInt(input.maintenanceBps);
44
+ const eligible = input.debt > 0n && (equity <= 0n || equity * BPS <= required);
45
+ const emergencyAllowed = input.debt > 0n && (equity <= 0n || equity * BPS * 100n <= required * 70n);
46
+ const distressProgressBps = input.debt === 0n ? 0n : equity <= 0n ? BPS : max(0n, required - equity * BPS) * BPS / required;
47
+ const recoveryTargetReached = input.debt === 0n || (equity > 0n && equity * BPS >= value * BigInt(input.maintenanceBps + 200));
48
+ return { eligible, emergencyAllowed, referenceInsolvent: input.debt > 0n && equity <= 0n, recoveryTargetReached, distressProgressBps: Number(distressProgressBps), equityAtoms: equity, equityBps: value === 0n ? null : Number(equity * BPS / value) };
49
+ }
50
+
51
+ /** Current health determines incentives; emergency and full-close gates remain separate. A partial quote may select a smaller affordable discount (at least
52
+ * 50 bps). Use preview.rates.buyerDiscountBps for the actual payment terms.
53
+ */
54
+ export function liquidationIncentives(input: LiquidationHealthInput) {
55
+ const health = liquidationHealth(input);
56
+ if (!health.eligible) throw new Error("Position is not liquidatable");
57
+ const progress = BigInt(health.distressProgressBps);
58
+ const maximumBuyerDiscountBps = Number(50n + (450n * progress / BPS));
59
+ return {
60
+ maximumBuyerDiscountBps,
61
+ /** @deprecated This is the ceiling. Read the actual discount from preview. */
62
+ buyerDiscountBps: maximumBuyerDiscountBps,
63
+ emergencyRewardBps: Number((100n * progress / BPS)),
64
+ emergencyAllowed: health.emergencyAllowed,
65
+ };
66
+ }
67
+
68
+ /** Net fee atoms. Physical transfer-fee gross-ups are additional, separate costs. */
69
+ export function liquidationFeeAllocation(netDebtRepaid: bigint, surplusCap = U64_MAX) {
70
+ for (const [name, value] of Object.entries({ netDebtRepaid, surplusCap })) amount(value, name);
71
+ const total = min(netDebtRepaid * 300n / BPS, surplusCap);
72
+ const protocol = total * BigInt(LIQUIDATION_POLICY.protocolFeeShareBps) / BPS;
73
+ return { total, protocol, junior: total - protocol };
74
+ }
75
+
76
+ export function liquidationLossAllocation(principal: bigint, debt: bigint, recovery: bigint) {
77
+ for (const [name, value] of Object.entries({ principal, debt, recovery })) amount(value, name);
78
+ if (principal > debt) throw new RangeError("Principal exceeds debt");
79
+ const principalRepaid = min(principal, recovery);
80
+ const interestPaid = min(debt - principal, max(0n, recovery - principal));
81
+ return { principalRepaid, interestPaid, principalWrittenOff: principal - principalRepaid,
82
+ interestCanceled: debt - principal - interestPaid, surplus: max(0n, recovery - debt) };
83
+ }
84
+
85
+ export function deriveLiquidationSessionAddress(position: PublicKey, programId = DUSK_PROGRAM_ID): [PublicKey, number] {
86
+ return PublicKey.findProgramAddressSync([Buffer.from("liquidation-session"), position.toBuffer()], programId);
87
+ }
88
+
89
+ /** Gross a route's final debt-token transfer up to the preview's required
90
+ * escrow credit. This is the incoming transfer; the preview already budgets
91
+ * outgoing custody transfers. Use the mint's effective fee for the current
92
+ * epoch, and obtain a fresh quote if the epoch changes.
93
+ */
94
+ export function grossLiquidationPayment(netCredit: bigint, fee: { basisPoints: number; maximumFee: bigint }): bigint {
95
+ amount(netCredit, "netCredit");
96
+ amount(fee.maximumFee, "maximumFee");
97
+ if (!Number.isSafeInteger(fee.basisPoints) || fee.basisPoints < 0 || fee.basisPoints > 10_000) throw new RangeError("Invalid transfer fee");
98
+ if (netCredit === 0n || fee.basisPoints === 0 || fee.maximumFee === 0n) return netCredit;
99
+ const capped = netCredit + fee.maximumFee;
100
+ const gross = fee.basisPoints === 10_000 ? capped : min(capped, ceilDiv(netCredit * BPS, BPS - BigInt(fee.basisPoints)));
101
+ amount(gross, "grossPayment");
102
+ return gross;
103
+ }
104
+
105
+ export function deriveLiquidationPaymentAddress(position: PublicKey, debtMint: PublicKey, programId = DUSK_PROGRAM_ID): [PublicKey, number] {
106
+ return PublicKey.findProgramAddressSync([Buffer.from("liquidation-payment"), position.toBuffer(), debtMint.toBuffer()], programId);
107
+ }
108
+
109
+ /** Compile the already-bound instruction list without prepending instructions
110
+ * that would invalidate begin's settle index. Lookup tables must be active.
111
+ * The caller simulates, signs and submits; this helper never sends funds.
112
+ */
113
+ export function flashLiquidationV0Transaction(params: {
114
+ payer: PublicKey; recentBlockhash: string; instructions: readonly TransactionInstruction[];
115
+ lookupTables?: AddressLookupTableAccount[];
116
+ }): VersionedTransaction {
117
+ const message = new TransactionMessage({ payerKey: params.payer, recentBlockhash: params.recentBlockhash, instructions: [...params.instructions] }).compileToV0Message(params.lookupTables ?? []);
118
+ return new VersionedTransaction(message);
119
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Names and symbols for LP tokens.
3
+ *
4
+ * The program writes the names provided at `initialize_market`, and there is
5
+ * no instruction to change them afterwards, so the strings are decided once,
6
+ * here, for every market. No brand in the name: the token is identified by
7
+ * what it is and which market it belongs to.
8
+ *
9
+ * srLP name `META/USDC srLP` symbol `srME/US`
10
+ * jrLP name `META/USDC jrLP` symbol `jrME/US`
11
+ * base hLP name `META hLP` symbol `hMETA`
12
+ * quote hLP name `USDC hLP` symbol `hUSDC`
13
+ *
14
+ * Metaplex caps names at 32 and symbols at 10 bytes. Asset symbols are cleaned
15
+ * and restricted to ASCII before deterministic shortening, so character and
16
+ * byte limits cannot diverge.
17
+ */
18
+ import type { MarketLpMintKind } from "./market-bootstrap.js";
19
+
20
+ export const MAX_LP_NAME_LENGTH = 32;
21
+ export const MAX_LP_SYMBOL_LENGTH = 10;
22
+ export const MAX_LP_URI_LENGTH = 200;
23
+
24
+ export interface LpTokenNaming {
25
+ readonly name: string;
26
+ readonly symbol: string;
27
+ /** For the off-chain metadata JSON; not written on chain. */
28
+ readonly description: string;
29
+ }
30
+
31
+ export interface LpTokenNamingParams {
32
+ kind: MarketLpMintKind | "junior";
33
+ baseSymbol: string;
34
+ quoteSymbol: string;
35
+ }
36
+
37
+ function cleanSymbol(symbol: string): string {
38
+ const cleaned = symbol.trim().replace(/^\$+/, "").replace(/\s+/g, "");
39
+ if (cleaned.length === 0) {
40
+ throw new Error("asset symbol is empty");
41
+ }
42
+ if (!/^[\x21-\x7e]+$/.test(cleaned)) {
43
+ throw new Error("asset symbol must contain printable ASCII characters only");
44
+ }
45
+ return cleaned;
46
+ }
47
+
48
+ /** Trim two symbols, longest first, until their combined length fits. */
49
+ function fitPair(first: string, second: string, budget: number): [string, string] {
50
+ let a = first;
51
+ let b = second;
52
+ while (a.length + b.length > budget) {
53
+ if (a.length >= b.length && a.length > 1) {
54
+ a = a.slice(0, -1);
55
+ } else if (b.length > 1) {
56
+ b = b.slice(0, -1);
57
+ } else {
58
+ throw new Error(`cannot fit "${first}" and "${second}" into ${budget} characters`);
59
+ }
60
+ }
61
+ return [a, b];
62
+ }
63
+
64
+ export function lpTokenNaming(params: LpTokenNamingParams): LpTokenNaming {
65
+ const base = cleanSymbol(params.baseSymbol);
66
+ const quote = cleanSymbol(params.quoteSymbol);
67
+ const market = `${base}/${quote}`;
68
+
69
+ if (params.kind === "srlp" || params.kind === "junior") {
70
+ const junior = params.kind === "junior";
71
+ const symbolPrefix = junior ? "jr" : "sr";
72
+ const nameSuffix = junior ? " jrLP" : " srLP";
73
+ const [na, nb] = fitPair(base, quote, MAX_LP_NAME_LENGTH - 1 - nameSuffix.length);
74
+ const a = base.slice(0, 2).toUpperCase();
75
+ const b = quote.slice(0, 2).toUpperCase();
76
+ return {
77
+ name: `${na}/${nb}${nameSuffix}`,
78
+ symbol: `${symbolPrefix}${a}/${b}`,
79
+ description: junior
80
+ ? `Dusk jrLP for the ${market} market: productive first-loss liquidity with junior income and a notice period before conversion to srLP.`
81
+ : `Dusk srLP for the ${market} market: a senior share of pooled ${base} and ${quote} liquidity, protected by junior capital against covered credit losses.`,
82
+ };
83
+ }
84
+
85
+ const side = params.kind === "baseHlp" ? base : quote;
86
+ const other = params.kind === "baseHlp" ? quote : base;
87
+ return {
88
+ name: `${side.slice(0, MAX_LP_NAME_LENGTH - 4)} hLP`,
89
+ symbol: `h${side.slice(0, MAX_LP_SYMBOL_LENGTH - 1)}`,
90
+ description: `Dusk hLP for ${side} in the ${market} market: a hedged, 2x leveraged liquidity share funded from the ${other} side.`,
91
+ };
92
+ }
93
+
94
+ /** Naming for all four LP receipt kinds of one market. */
95
+ export function marketLpTokenNaming(
96
+ params: Omit<LpTokenNamingParams, "kind">,
97
+ ): Record<MarketLpMintKind | "junior", LpTokenNaming> {
98
+ return {
99
+ srlp: lpTokenNaming({ ...params, kind: "srlp" }),
100
+ junior: lpTokenNaming({ ...params, kind: "junior" }),
101
+ baseHlp: lpTokenNaming({ ...params, kind: "baseHlp" }),
102
+ quoteHlp: lpTokenNaming({ ...params, kind: "quoteHlp" }),
103
+ };
104
+ }
105
+
106
+ export interface LpTokenMetadataInput {
107
+ name: string;
108
+ symbol: string;
109
+ uri: string;
110
+ }
111
+
112
+ /** Match the on-chain Metaplex input contract before a transaction is built. */
113
+ export function assertLpTokenMetadata(metadata: LpTokenMetadataInput): void {
114
+ if (!metadata.name || !/^[\x20-\x7e]+$/.test(metadata.name) || metadata.name.length > MAX_LP_NAME_LENGTH) {
115
+ throw new Error(`LP token name must be printable ASCII and at most ${MAX_LP_NAME_LENGTH} bytes`);
116
+ }
117
+ if (!metadata.symbol || !/^[\x21-\x7e]+$/.test(metadata.symbol) || metadata.symbol.length > MAX_LP_SYMBOL_LENGTH) {
118
+ throw new Error(`LP token symbol must be printable ASCII and at most ${MAX_LP_SYMBOL_LENGTH} bytes`);
119
+ }
120
+ if (
121
+ !metadata.uri.startsWith("http")
122
+ || metadata.uri.length > MAX_LP_URI_LENGTH
123
+ || !/^[\x21-\x7e]+$/.test(metadata.uri)
124
+ ) {
125
+ throw new Error(`LP token URI must start with http and be at most ${MAX_LP_URI_LENGTH} bytes`);
126
+ }
127
+ }