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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +1085 -26
  2. package/dist/amounts.d.ts +9 -0
  3. package/dist/amounts.d.ts.map +1 -0
  4. package/dist/amounts.js +10 -0
  5. package/dist/amounts.js.map +1 -0
  6. package/dist/constants.d.ts +80 -33
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +175 -64
  9. package/dist/constants.js.map +1 -1
  10. package/dist/delegate.d.ts +94 -0
  11. package/dist/delegate.d.ts.map +1 -0
  12. package/dist/delegate.js +131 -0
  13. package/dist/delegate.js.map +1 -0
  14. package/dist/dusk.d.ts +14 -0
  15. package/dist/dusk.d.ts.map +1 -1
  16. package/dist/dusk.js +22 -0
  17. package/dist/dusk.js.map +1 -1
  18. package/dist/get.d.ts +3285 -237
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +140 -71
  21. package/dist/get.js.map +1 -1
  22. package/dist/governance-client.d.ts +169 -0
  23. package/dist/governance-client.d.ts.map +1 -0
  24. package/dist/governance-client.js +146 -0
  25. package/dist/governance-client.js.map +1 -0
  26. package/dist/governance.d.ts +313 -0
  27. package/dist/governance.d.ts.map +1 -0
  28. package/dist/governance.js +902 -0
  29. package/dist/governance.js.map +1 -0
  30. package/dist/hash.d.ts +9 -0
  31. package/dist/hash.d.ts.map +1 -0
  32. package/dist/hash.js +16 -0
  33. package/dist/hash.js.map +1 -0
  34. package/dist/hlp-liquidation-client.d.ts +106 -0
  35. package/dist/hlp-liquidation-client.d.ts.map +1 -0
  36. package/dist/hlp-liquidation-client.js +150 -0
  37. package/dist/hlp-liquidation-client.js.map +1 -0
  38. package/dist/idl_delegate.d.ts +3 -0
  39. package/dist/idl_delegate.d.ts.map +1 -0
  40. package/dist/idl_delegate.js +3 -0
  41. package/dist/idl_delegate.js.map +1 -0
  42. package/dist/idl_delegate.json +6119 -0
  43. package/dist/idl_v2.json +18372 -6121
  44. package/dist/index.d.ts +23 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +23 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interest-accounting.d.ts +49 -0
  49. package/dist/interest-accounting.d.ts.map +1 -0
  50. package/dist/interest-accounting.js +72 -0
  51. package/dist/interest-accounting.js.map +1 -0
  52. package/dist/leverage-actions.d.ts +122 -0
  53. package/dist/leverage-actions.d.ts.map +1 -0
  54. package/dist/leverage-actions.js +228 -0
  55. package/dist/leverage-actions.js.map +1 -0
  56. package/dist/leverage-margins.d.ts +12 -0
  57. package/dist/leverage-margins.d.ts.map +1 -0
  58. package/dist/leverage-margins.js +45 -0
  59. package/dist/leverage-margins.js.map +1 -0
  60. package/dist/leverage-preview.d.ts +587 -0
  61. package/dist/leverage-preview.d.ts.map +1 -0
  62. package/dist/leverage-preview.js +89 -0
  63. package/dist/leverage-preview.js.map +1 -0
  64. package/dist/liquidation-client.d.ts +230 -0
  65. package/dist/liquidation-client.d.ts.map +1 -0
  66. package/dist/liquidation-client.js +239 -0
  67. package/dist/liquidation-client.js.map +1 -0
  68. package/dist/liquidation.d.ts +78 -0
  69. package/dist/liquidation.d.ts.map +1 -0
  70. package/dist/liquidation.js +122 -0
  71. package/dist/liquidation.js.map +1 -0
  72. package/dist/lp-naming.d.ts +43 -0
  73. package/dist/lp-naming.d.ts.map +1 -0
  74. package/dist/lp-naming.js +81 -0
  75. package/dist/lp-naming.js.map +1 -0
  76. package/dist/lp-vanity.d.ts +33 -0
  77. package/dist/lp-vanity.d.ts.map +1 -0
  78. package/dist/lp-vanity.js +94 -0
  79. package/dist/lp-vanity.js.map +1 -0
  80. package/dist/market-bootstrap.d.ts +109 -0
  81. package/dist/market-bootstrap.d.ts.map +1 -0
  82. package/dist/market-bootstrap.js +158 -0
  83. package/dist/market-bootstrap.js.map +1 -0
  84. package/dist/market-launch.d.ts +45 -0
  85. package/dist/market-launch.d.ts.map +1 -0
  86. package/dist/market-launch.js +76 -0
  87. package/dist/market-launch.js.map +1 -0
  88. package/dist/oracle.d.ts +46 -0
  89. package/dist/oracle.d.ts.map +1 -0
  90. package/dist/oracle.js +103 -0
  91. package/dist/oracle.js.map +1 -0
  92. package/dist/preview.d.ts +39 -1
  93. package/dist/preview.d.ts.map +1 -1
  94. package/dist/preview.js +12 -0
  95. package/dist/preview.js.map +1 -1
  96. package/dist/protection.d.ts +48 -0
  97. package/dist/protection.d.ts.map +1 -0
  98. package/dist/protection.js +88 -0
  99. package/dist/protection.js.map +1 -0
  100. package/dist/referral.d.ts +28 -28
  101. package/dist/referral.d.ts.map +1 -1
  102. package/dist/referral.js +41 -33
  103. package/dist/referral.js.map +1 -1
  104. package/dist/risk-pricing.d.ts +14 -0
  105. package/dist/risk-pricing.d.ts.map +1 -0
  106. package/dist/risk-pricing.js +25 -0
  107. package/dist/risk-pricing.js.map +1 -0
  108. package/dist/simulation.d.ts +45 -0
  109. package/dist/simulation.d.ts.map +1 -0
  110. package/dist/simulation.js +106 -0
  111. package/dist/simulation.js.map +1 -0
  112. package/dist/tranche-client.d.ts +121 -0
  113. package/dist/tranche-client.d.ts.map +1 -0
  114. package/dist/tranche-client.js +185 -0
  115. package/dist/tranche-client.js.map +1 -0
  116. package/dist/transfer-fees.d.ts +46 -0
  117. package/dist/transfer-fees.d.ts.map +1 -0
  118. package/dist/transfer-fees.js +76 -0
  119. package/dist/transfer-fees.js.map +1 -0
  120. package/dist/type-aliases.d.ts +271 -30
  121. package/dist/type-aliases.d.ts.map +1 -1
  122. package/dist/types_delegate.d.ts +6126 -0
  123. package/dist/types_delegate.d.ts.map +1 -0
  124. package/dist/types_delegate.js +2 -0
  125. package/dist/types_delegate.js.map +1 -0
  126. package/dist/types_v2.d.ts +18105 -5854
  127. package/dist/types_v2.d.ts.map +1 -1
  128. package/dist/virtual-book/index.d.ts +4 -0
  129. package/dist/virtual-book/index.d.ts.map +1 -0
  130. package/dist/virtual-book/index.js +4 -0
  131. package/dist/virtual-book/index.js.map +1 -0
  132. package/dist/virtual-book/market.d.ts +608 -0
  133. package/dist/virtual-book/market.d.ts.map +1 -0
  134. package/dist/virtual-book/market.js +59 -0
  135. package/dist/virtual-book/market.js.map +1 -0
  136. package/dist/virtual-book/projection.d.ts +44 -0
  137. package/dist/virtual-book/projection.d.ts.map +1 -0
  138. package/dist/virtual-book/projection.js +229 -0
  139. package/dist/virtual-book/projection.js.map +1 -0
  140. package/dist/virtual-book/quotes.d.ts +1241 -0
  141. package/dist/virtual-book/quotes.d.ts.map +1 -0
  142. package/dist/virtual-book/quotes.js +233 -0
  143. package/dist/virtual-book/quotes.js.map +1 -0
  144. package/dist/write.d.ts +584 -14
  145. package/dist/write.d.ts.map +1 -1
  146. package/dist/write.js +1371 -47
  147. package/dist/write.js.map +1 -1
  148. package/dist/yield-client.d.ts +51 -0
  149. package/dist/yield-client.d.ts.map +1 -0
  150. package/dist/yield-client.js +98 -0
  151. package/dist/yield-client.js.map +1 -0
  152. package/package.json +9 -2
  153. package/src/amounts.ts +13 -0
  154. package/src/constants.ts +276 -111
  155. package/src/delegate.ts +238 -0
  156. package/src/dusk.ts +28 -0
  157. package/src/get.ts +267 -90
  158. package/src/governance-client.ts +234 -0
  159. package/src/governance.ts +1422 -0
  160. package/src/hash.ts +15 -0
  161. package/src/hlp-liquidation-client.ts +195 -0
  162. package/src/idl_delegate.json +6119 -0
  163. package/src/idl_delegate.ts +3 -0
  164. package/src/idl_v2.json +18372 -6121
  165. package/src/index.ts +31 -0
  166. package/src/interest-accounting.ts +85 -0
  167. package/src/leverage-actions.ts +216 -0
  168. package/src/leverage-margins.ts +48 -0
  169. package/src/leverage-preview.ts +86 -0
  170. package/src/liquidation-client.ts +297 -0
  171. package/src/liquidation.ts +137 -0
  172. package/src/lp-naming.ts +127 -0
  173. package/src/lp-vanity.ts +135 -0
  174. package/src/market-bootstrap.ts +273 -0
  175. package/src/market-launch.ts +103 -0
  176. package/src/oracle.ts +120 -0
  177. package/src/preview.ts +53 -1
  178. package/src/protection.ts +112 -0
  179. package/src/referral.ts +71 -71
  180. package/src/risk-pricing.ts +28 -0
  181. package/src/simulation.ts +169 -0
  182. package/src/tranche-client.ts +187 -0
  183. package/src/transfer-fees.ts +99 -0
  184. package/src/type-aliases.ts +280 -30
  185. package/src/types_delegate.ts +6125 -0
  186. package/src/types_v2.ts +18372 -6121
  187. package/src/virtual-book/index.ts +3 -0
  188. package/src/virtual-book/market.ts +76 -0
  189. package/src/virtual-book/projection.ts +265 -0
  190. package/src/virtual-book/quotes.ts +308 -0
  191. package/src/write.ts +2394 -67
  192. package/src/yield-client.ts +117 -0
package/src/write.ts CHANGED
@@ -1,13 +1,62 @@
1
+ import { deriveJuniorCohortAddress } from "./constants.js";
2
+ import { oracleComputeBudgetInstructions, oraclePolicy, oracleReadAccounts, type OraclePolicyInput } from "./oracle.js";
1
3
  import type { Program } from "@coral-xyz/anchor";
2
- import { getAccount, getMint, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
3
- import { SystemProgram, Transaction, type AccountMeta, type TransactionInstruction } from "@solana/web3.js";
4
+ import {
5
+ getAssociatedTokenAddressSync,
6
+ getMint,
7
+ TOKEN_2022_PROGRAM_ID,
8
+ TOKEN_PROGRAM_ID,
9
+ } from "@solana/spl-token";
10
+ import {
11
+ SystemProgram,
12
+ SYSVAR_INSTRUCTIONS_PUBKEY,
13
+ Transaction,
14
+ type AccountMeta,
15
+ type PublicKey,
16
+ type TransactionInstruction,
17
+ } from "@solana/web3.js";
4
18
 
5
19
  import { address, normalizeAccountKeys, type AddressLike } from "./address.js";
6
- import { deriveReferralProfileAddress } from "./constants.js";
20
+ import { type MarketLaunchConfig } from "./market-bootstrap.js";
21
+ import type { Market } from "./type-aliases.js";
22
+ import {
23
+ deriveBorrowPositionAddress,
24
+ deriveEventAuthorityAddress,
25
+ deriveFutarchyAuthorityAddress,
26
+ deriveLeverageCollateralVaultAddress,
27
+ deriveLeverageDelegationAddress,
28
+ deriveLeveragePositionAddress,
29
+ deriveMarketAddress,
30
+ deriveMarketCollateralVaultAddress,
31
+ deriveMarketInterestVaultAddress,
32
+ deriveMarketReserveVaultAddress,
33
+ deriveInsuranceAddress,
34
+ deriveTokenMetadataAddress,
35
+ TOKEN_METADATA_PROGRAM_ID,
36
+ deriveReferralAccrualAddress,
37
+ deriveParameterProposalAddress,
38
+ deriveProposalSupportAddress,
39
+ deriveYieldAccountAddress,
40
+ deriveYieldTransferHookValidationAddress,
41
+ deriveHlpCohortAddress,
42
+ deriveReferralPartnerAddress,
43
+ type YieldTokenKind,
44
+ } from "./constants.js";
7
45
  import {
8
- buildReferralVaultSetupInstruction,
9
- referralVaultAddresses,
46
+ anchorParameterUpdate,
47
+ assertProposalMetadata,
48
+ canonicalParameterUpdates,
49
+ parameterUpdateFromAnchor,
50
+ governanceIntegerBN,
51
+ type GovernanceIntegerLike,
52
+ type ParameterUpdate,
53
+ type ProposalMetadataV1,
54
+ } from "./governance.js";
55
+ import {
56
+ assertReferralInterestShareBps,
57
+ referralAccrualAddresses,
10
58
  resolveTransferHookAccountMetas,
59
+ tokenProgramForMint,
11
60
  type TransferHookTransfer,
12
61
  } from "./referral.js";
13
62
  import type { Dusk } from "./types_v2.js";
@@ -17,32 +66,148 @@ export type DuskInstructionArgs = unknown[] | unknown | undefined;
17
66
  export type DuskAccounts = Record<string, unknown>;
18
67
 
19
68
  export interface DuskBuildOptions {
69
+ /** Explicit source policy for offline builders; async builders resolve it from the market. */
70
+ oraclePolicy?: OraclePolicyInput;
20
71
  accounts?: DuskAccounts;
21
72
  remainingAccounts?: AccountMeta[];
22
73
  }
23
74
 
24
- export type ReferredActionName = "borrow" | "openLeverage" | "increaseLeverage";
75
+ export interface SwapBuildOptions extends DuskBuildOptions {
76
+ accounts: DuskAccounts;
77
+ market: AddressLike;
78
+ }
79
+
80
+ export interface FortifyMarketParams {
81
+ donor: AddressLike;
82
+ market: AddressLike;
83
+ asset: "base" | "quote";
84
+ assetMint: AddressLike;
85
+ /** Gross donation in raw token atoms; transfer fees reduce insurance credit. */
86
+ amount: GovernanceIntegerLike;
87
+ /** Defaults to the donor's ATA for the asset's token program. */
88
+ donorAssetAccount?: AddressLike;
89
+ /** Supply the mint owner to avoid an RPC read when building the instruction. */
90
+ assetTokenProgram?: AddressLike;
91
+ }
92
+
93
+ export type ReferredActionName = "borrow" | "openLeverage";
25
94
 
26
95
  export interface ReferredActionOptions extends DuskBuildOptions {
27
96
  accounts: DuskAccounts;
28
97
  payer: AddressLike;
29
98
  referrer: AddressLike;
99
+ market: AddressLike;
30
100
  debtMint: AddressLike;
31
- maxAcceptableReferralFeeBps: number;
32
101
  transferHookTransfers?: readonly TransferHookTransfer[];
33
102
  }
34
103
 
35
104
  export interface ReferredActionBuild {
36
- referralProfile: ReturnType<typeof deriveReferralProfileAddress>[0];
37
- referralVault: ReturnType<typeof deriveReferralProfileAddress>[0];
105
+ referralPartner: ReturnType<typeof deriveReferralPartnerAddress>[0];
106
+ referralAccrual: ReturnType<typeof deriveReferralPartnerAddress>[0];
38
107
  setupInstruction: TransactionInstruction;
39
108
  actionInstruction: TransactionInstruction;
40
109
  transaction: Transaction;
41
110
  }
42
111
 
112
+ export interface HlpLiquidityBuildOptions extends DuskBuildOptions {
113
+ accounts: DuskAccounts;
114
+ payer: AddressLike;
115
+ owner: AddressLike;
116
+ market: AddressLike;
117
+ targetHlpMint: AddressLike;
118
+ baseMint: AddressLike;
119
+ quoteMint: AddressLike;
120
+ }
121
+
122
+ export interface HlpLiquidityBuild {
123
+ baseYieldAccount: AccountMeta["pubkey"];
124
+ quoteYieldAccount: AccountMeta["pubkey"];
125
+ setupInstructions: TransactionInstruction[];
126
+ actionInstruction: TransactionInstruction;
127
+ transaction: Transaction;
128
+ }
129
+
130
+ export interface GovernanceMarketAccountOverrides {
131
+ ylpMint?: AddressLike;
132
+ baseHlpYlpVault?: AddressLike;
133
+ quoteHlpYlpVault?: AddressLike;
134
+ }
135
+
136
+ export interface GovernanceHolderAccountOverrides extends GovernanceMarketAccountOverrides {
137
+ holderYlpAccount?: AddressLike;
138
+ baseYieldAccount?: AddressLike;
139
+ quoteYieldAccount?: AddressLike;
140
+ }
141
+
142
+ export interface CreateParameterProposalParams extends GovernanceHolderAccountOverrides {
143
+ proposer: AddressLike;
144
+ market: AddressLike;
145
+ nonce: GovernanceIntegerLike;
146
+ /**
147
+ * One to seven updates, at most one per family. They are sent in ascending
148
+ * family order and execute together under one sponsorship and one vote.
149
+ */
150
+ updates: readonly ParameterUpdate[];
151
+ metadata: ProposalMetadataV1;
152
+ initialSupport: GovernanceIntegerLike;
153
+ }
154
+
155
+ export interface SupportParameterProposalParams extends GovernanceHolderAccountOverrides {
156
+ supporter: AddressLike;
157
+ market: AddressLike;
158
+ proposal: AddressLike;
159
+ amount: GovernanceIntegerLike;
160
+ /**
161
+ * Digest of the proposal the supporter reviewed. The program rejects the
162
+ * support if the account at `proposal` holds a different proposal.
163
+ */
164
+ digest: Uint8Array | readonly number[];
165
+ }
166
+
167
+ export interface QueueParameterProposalParams extends GovernanceMarketAccountOverrides {
168
+ market: AddressLike;
169
+ proposal: AddressLike;
170
+ }
171
+
172
+ export interface ExecuteParameterProposalParams {
173
+ market: AddressLike;
174
+ proposal: AddressLike;
175
+ }
176
+
177
+ export interface WithdrawParameterSupportParams {
178
+ /** Omit to withdraw all support; otherwise release this many yLP atoms. */
179
+ amount?: GovernanceIntegerLike;
180
+ supporter: AddressLike;
181
+ market: AddressLike;
182
+ proposal: AddressLike;
183
+ /** The proposal's creator; receives its rent when the last supporter withdraws. */
184
+ proposer: AddressLike;
185
+ ylpMint?: AddressLike;
186
+ supporterYlpAccount?: AddressLike;
187
+ baseYieldAccount?: AddressLike;
188
+ quoteYieldAccount?: AddressLike;
189
+ }
190
+
191
+ export interface ParameterGovernanceBuild {
192
+ proposal: PublicKey;
193
+ proposalSupport?: PublicKey;
194
+ instruction: TransactionInstruction;
195
+ transaction: Transaction;
196
+ }
197
+
198
+ interface GovernanceMarketState {
199
+ oracle?: { policy: OraclePolicyInput };
200
+ ylpMint: PublicKey;
201
+ baseSide: { assetMint: PublicKey };
202
+ quoteSide: { assetMint: PublicKey };
203
+ baseHlpVault: { ylpVault: PublicKey };
204
+ quoteHlpVault: { ylpVault: PublicKey };
205
+ }
206
+
43
207
  type AnchorMethodBuilder = {
44
208
  accounts(accounts: DuskAccounts): AnchorMethodBuilder;
45
209
  remainingAccounts(accounts: AccountMeta[]): AnchorMethodBuilder;
210
+ preInstructions(instructions: TransactionInstruction[]): AnchorMethodBuilder;
46
211
  instruction(): Promise<TransactionInstruction>;
47
212
  transaction(): Promise<Transaction>;
48
213
  rpc(): Promise<string>;
@@ -53,6 +218,12 @@ type AnchorMethods = Record<string, (...args: unknown[]) => AnchorMethodBuilder>
53
218
  export class DuskWrite {
54
219
  constructor(readonly program: Program<Dusk>) {}
55
220
 
221
+ private fetchMarketAccount(market: PublicKey): Promise<unknown> {
222
+ return (this.program as unknown as {
223
+ account: { market: { fetch(address: PublicKey): Promise<unknown> } };
224
+ }).account.market.fetch(market);
225
+ }
226
+
56
227
  method(name: DuskInstructionName, args?: DuskInstructionArgs): AnchorMethodBuilder {
57
228
  const method = (this.program.methods as unknown as AnchorMethods)[name];
58
229
  if (!method) {
@@ -67,33 +238,1203 @@ export class DuskWrite {
67
238
  options: DuskBuildOptions = {}
68
239
  ): AnchorMethodBuilder {
69
240
  let builder = this.method(name, args);
70
- if (options.accounts) {
71
- builder = builder.accounts(normalizeAccountKeys(options.accounts));
241
+ const instructionAccounts = this.program.idl.instructions?.find(
242
+ (instruction) => instruction.name === name
243
+ )?.accounts;
244
+ const usesEventCpi =
245
+ instructionAccounts?.some((account) => account.name === "eventAuthority") === true &&
246
+ instructionAccounts.some((account) => account.name === "program") === true;
247
+ if (options.accounts || usesEventCpi) {
248
+ const accounts = usesEventCpi
249
+ ? {
250
+ ...options.accounts,
251
+ eventAuthority: deriveEventAuthorityAddress(this.program.programId)[0],
252
+ program: this.program.programId,
253
+ }
254
+ : options.accounts!;
255
+ builder = builder.accounts(normalizeAccountKeys(accounts));
72
256
  }
73
- if (options.remainingAccounts?.length) {
74
- builder = builder.remainingAccounts(options.remainingAccounts);
257
+ const remaining = [...(options.remainingAccounts ?? [])];
258
+ for (const meta of oracleReadAccounts(options.oraclePolicy)) {
259
+ if (!remaining.some(existing => existing.pubkey.equals(meta.pubkey))) remaining.push(meta);
75
260
  }
261
+ if (remaining.length) builder = builder.remainingAccounts(remaining);
262
+ const budgets = oracleComputeBudgetInstructions(options.oraclePolicy);
263
+ if (budgets.length) builder = builder.preInstructions(budgets);
76
264
  return builder;
77
265
  }
78
266
 
79
- instruction(
267
+ async instruction(
80
268
  name: DuskInstructionName,
81
269
  args?: DuskInstructionArgs,
82
270
  options?: DuskBuildOptions
83
271
  ): Promise<TransactionInstruction> {
84
- return this.builder(name, args, options).instruction();
272
+ return this.builder(name, args, await this.withOraclePolicy(name, options)).instruction();
273
+ }
274
+
275
+ async transaction(
276
+ name: DuskInstructionName,
277
+ args?: DuskInstructionArgs,
278
+ options?: DuskBuildOptions
279
+ ): Promise<Transaction> {
280
+ return this.builder(name, args, await this.withOraclePolicy(name, options)).transaction();
281
+ }
282
+
283
+ async rpc(name: DuskInstructionName, args?: DuskInstructionArgs, options?: DuskBuildOptions) {
284
+ return this.builder(name, args, await this.withOraclePolicy(name, options)).rpc();
285
+ }
286
+
287
+ private async withOraclePolicy(name: DuskInstructionName, options: DuskBuildOptions = {}): Promise<DuskBuildOptions> {
288
+ if (!ORACLE_READ_INSTRUCTIONS.has(name) || options.oraclePolicy) return options;
289
+ const nested = options.accounts?.accounts as DuskAccounts | undefined;
290
+ const preview = options.accounts?.preview as DuskAccounts | undefined;
291
+ const market = options.accounts?.market ?? nested?.market ?? preview?.market;
292
+ if (!market) return options;
293
+ if (name === "executeParameterProposal" && options.accounts?.proposal) {
294
+ const client = (this.program.account as unknown as Record<string, {
295
+ fetch(key: PublicKey): Promise<{updates: unknown[]}>;
296
+ }>).parameterProposal;
297
+ const proposal = await client!.fetch(address(options.accounts.proposal as AddressLike));
298
+ const update = proposal.updates.map(parameterUpdateFromAnchor).find(update => update.kind === "oracle");
299
+ if (update?.kind === "oracle") return {...options, oraclePolicy: update.policy};
300
+ }
301
+ const state = await this.fetchMarketAccount(address(market as AddressLike)) as { oracle?: {policy: OraclePolicyInput} };
302
+ return {...options, oraclePolicy: state.oracle?.policy};
303
+ }
304
+
305
+ /**
306
+ * The hLP accounts an instruction must carry when hedged liquidity is live.
307
+ *
308
+ * Swap and openLeverage both require them, and their order is
309
+ * consensus-visible, so both take them from here rather than each assembling
310
+ * its own list.
311
+ */
312
+ /**
313
+ * The hLP settlement prefix an instruction must carry when the market has
314
+ * active hLP.
315
+ *
316
+ * Required by every leverage instruction that settles the market —
317
+ * open, close, increase and decrease — not only by open. Omitting it fails
318
+ * with `NotEnoughAccounts` at the point the program tries to read the
319
+ * prefix, which names neither leverage nor hLP and reads as a malformed
320
+ * call.
321
+ */
322
+ async hlpRemainingAccounts(
323
+ marketAddress: AddressLike,
324
+ marketSnapshot?: Market
325
+ ): Promise<AccountMeta[]> {
326
+ const market = address(marketAddress);
327
+ const state = (marketSnapshot ?? await this.fetchMarketAccount(market)) as {
328
+ ylpMint: AccountMeta["pubkey"];
329
+ baseSide: { interestVault: AccountMeta["pubkey"]; assetMint: AccountMeta["pubkey"]; reserveVault: AccountMeta["pubkey"] };
330
+ quoteSide: { interestVault: AccountMeta["pubkey"]; assetMint: AccountMeta["pubkey"]; reserveVault: AccountMeta["pubkey"] };
331
+ baseHlpVault: {
332
+ hlpSupply: { toString(): string };
333
+ residualExposure: { toString(): string };
334
+ ylpVault: AccountMeta["pubkey"];
335
+ };
336
+ quoteHlpVault: {
337
+ hlpSupply: { toString(): string };
338
+ residualExposure: { toString(): string };
339
+ ylpVault: AccountMeta["pubkey"];
340
+ };
341
+ };
342
+ const hlpActive =
343
+ BigInt(state.baseHlpVault.hlpSupply.toString()) !== 0n ||
344
+ BigInt(state.quoteHlpVault.hlpSupply.toString()) !== 0n ||
345
+ BigInt(state.baseHlpVault.residualExposure.toString()) !== 0n ||
346
+ BigInt(state.quoteHlpVault.residualExposure.toString()) !== 0n;
347
+ if (!hlpActive) return [];
348
+ return [
349
+ { pubkey: state.ylpMint, isSigner: false, isWritable: true },
350
+ { pubkey: state.baseHlpVault.ylpVault, isSigner: false, isWritable: true },
351
+ { pubkey: state.quoteHlpVault.ylpVault, isSigner: false, isWritable: true },
352
+ { pubkey: state.baseSide.interestVault, isSigner: false, isWritable: true },
353
+ { pubkey: state.quoteSide.interestVault, isSigner: false, isWritable: true },
354
+ // Fresh public-interest settlements rebalance both vaults. These keys
355
+ // usually duplicate fixed swap accounts; repayments need them explicitly.
356
+ { pubkey: state.baseSide.assetMint, isSigner: false, isWritable: false },
357
+ { pubkey: state.quoteSide.assetMint, isSigner: false, isWritable: false },
358
+ { pubkey: state.baseSide.reserveVault, isSigner: false, isWritable: true },
359
+ { pubkey: state.quoteSide.reserveVault, isSigner: false, isWritable: true },
360
+ ];
361
+ }
362
+
363
+ async swapBuilder(
364
+ args: Record<string, unknown>,
365
+ options: SwapBuildOptions
366
+ ): Promise<AnchorMethodBuilder> {
367
+ const market = address(options.market);
368
+ const state = (await this.fetchMarketAccount(market)) as {
369
+ ylpMint: AccountMeta["pubkey"];
370
+ baseSide: { interestVault: AccountMeta["pubkey"] };
371
+ quoteSide: { interestVault: AccountMeta["pubkey"] };
372
+ baseHlpVault: {
373
+ hlpSupply: { toString(): string };
374
+ residualExposure: { toString(): string };
375
+ ylpVault: AccountMeta["pubkey"];
376
+ };
377
+ quoteHlpVault: {
378
+ hlpSupply: { toString(): string };
379
+ residualExposure: { toString(): string };
380
+ ylpVault: AccountMeta["pubkey"];
381
+ };
382
+ };
383
+ const hlpActive =
384
+ BigInt(state.baseHlpVault.hlpSupply.toString()) !== 0n ||
385
+ BigInt(state.quoteHlpVault.hlpSupply.toString()) !== 0n ||
386
+ BigInt(state.baseHlpVault.residualExposure.toString()) !== 0n ||
387
+ BigInt(state.quoteHlpVault.residualExposure.toString()) !== 0n;
388
+ const prefix: AccountMeta[] = hlpActive
389
+ ? [
390
+ { pubkey: state.ylpMint, isSigner: false, isWritable: true },
391
+ { pubkey: state.baseHlpVault.ylpVault, isSigner: false, isWritable: true },
392
+ { pubkey: state.quoteHlpVault.ylpVault, isSigner: false, isWritable: true },
393
+ { pubkey: state.baseSide.interestVault, isSigner: false, isWritable: true },
394
+ { pubkey: state.quoteSide.interestVault, isSigner: false, isWritable: true },
395
+ ]
396
+ : [];
397
+
398
+ return this.builder("swap", args, {
399
+ oraclePolicy: options.oraclePolicy ?? (state as typeof state & {oracle?: {policy: OraclePolicyInput}}).oracle?.policy,
400
+ accounts: {
401
+ ...options.accounts,
402
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
403
+ },
404
+ // Prefix order is consensus-visible. Hook accounts must remain a tail,
405
+ // including any deliberate duplicate pubkeys required by a hook meta list.
406
+ remainingAccounts: [...prefix, ...(options.remainingAccounts ?? [])],
407
+ });
408
+ }
409
+
410
+ async swapInstruction(args: Record<string, unknown>, options: SwapBuildOptions) {
411
+ return (await this.swapBuilder(args, options)).instruction();
412
+ }
413
+
414
+ async swapTransaction(args: Record<string, unknown>, options: SwapBuildOptions) {
415
+ return (await this.swapBuilder(args, options)).transaction();
416
+ }
417
+
418
+ async swapRpc(args: Record<string, unknown>, options: SwapBuildOptions) {
419
+ return (await this.swapBuilder(args, options)).rpc();
420
+ }
421
+
422
+ /**
423
+ * Swap, with accounts resolved from the market and the two mints.
424
+ *
425
+ * `swapInstruction` takes a prepared account map, which makes callers
426
+ * responsible for reconstructing the program's account set. This resolves it
427
+ * instead: reserve vaults derive from the market and mint, trader accounts
428
+ * default to the associated token account for the correct token program, and
429
+ * the hLP remaining-account prefix is still assembled by `swapBuilder`,
430
+ * whose ordering is consensus-visible.
431
+ */
432
+ async buildSwapInstruction(
433
+ params: SwapParams
434
+ ): Promise<TransactionInstruction> {
435
+ return (await this.buildSwapBuilder(params)).instruction();
436
+ }
437
+
438
+ async buildSwapTransaction(params: SwapParams): Promise<Transaction> {
439
+ return (await this.buildSwapBuilder(params)).transaction();
440
+ }
441
+
442
+ /**
443
+ * Borrow against a position, with accounts resolved from the market and the
444
+ * two mints.
445
+ *
446
+ * The referral accounts are optional on chain and are omitted here: a borrow
447
+ * with no referrer should not have to name accounts it does not use. Use
448
+ * `referredBorrow` when a referrer is present.
449
+ */
450
+ async buildBorrowInstruction(
451
+ params: BorrowParams
452
+ ): Promise<TransactionInstruction> {
453
+ const market = address(params.market);
454
+ const owner = address(params.owner);
455
+ const debtAssetMint = address(params.debtAssetMint);
456
+ const collateralAssetMint = address(params.collateralAssetMint);
457
+
458
+ if (debtAssetMint.equals(collateralAssetMint)) {
459
+ throw new Error("Borrow debt and collateral mints must differ");
460
+ }
461
+
462
+ const debtTokenProgram = await tokenProgramForMint(
463
+ this.program.provider.connection,
464
+ debtAssetMint
465
+ );
466
+
467
+ return this.instruction(
468
+ "borrow" as DuskInstructionName,
469
+ {
470
+ borrowAmount: governanceIntegerBN(params.borrowAmount, "borrowAmount"),
471
+ minDebtAmountOut: governanceIntegerBN(
472
+ params.minDebtAmountOut,
473
+ "minDebtAmountOut"
474
+ ),
475
+ minLiquidationCfBps: Number(params.minLiquidationCfBps ?? 0),
476
+ referrer: null,
477
+ },
478
+ {
479
+ accounts: {
480
+ market,
481
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
482
+ owner,
483
+ debtAssetMint,
484
+ collateralAssetMint,
485
+ reserveVault: address(
486
+ params.reserveVault ??
487
+ deriveMarketReserveVaultAddress(market, debtAssetMint)[0]
488
+ ),
489
+ ownerDebtAccount: address(
490
+ params.ownerDebtAccount ??
491
+ getAssociatedTokenAddressSync(
492
+ debtAssetMint,
493
+ owner,
494
+ true,
495
+ debtTokenProgram
496
+ )
497
+ ),
498
+ borrowPosition: address(
499
+ params.borrowPosition ??
500
+ deriveBorrowPositionAddress(market, owner, address(params.positionId))[0]
501
+ ),
502
+ referralPartner: null,
503
+ referralAccrual: null,
504
+ tokenProgram: TOKEN_PROGRAM_ID,
505
+ token2022Program: TOKEN_2022_PROGRAM_ID,
506
+ },
507
+ remainingAccounts: params.remainingAccounts,
508
+ }
509
+ );
510
+ }
511
+
512
+ async buildBorrowTransaction(params: BorrowParams): Promise<Transaction> {
513
+ const options = await this.withOraclePolicy("borrow", { accounts: {market: address(params.market)} });
514
+ return new Transaction().add(...oracleComputeBudgetInstructions(options.oraclePolicy),
515
+ await this.buildBorrowInstruction(params));
516
+ }
517
+
518
+ /**
519
+ * Open a leverage position, with accounts resolved from the market, the
520
+ * position id and the two mints.
521
+ *
522
+ * Referral accounts are optional on chain and omitted here; use
523
+ * `referredOpenLeverage` when a referrer is present.
524
+ */
525
+ async buildOpenLeverageInstruction(
526
+ params: OpenLeverageParams
527
+ ): Promise<TransactionInstruction> {
528
+ const market = address(params.market);
529
+ const owner = address(params.owner);
530
+ const debtMint = address(params.debtMint);
531
+ const collateralMint = address(params.collateralMint);
532
+
533
+ if (debtMint.equals(collateralMint)) {
534
+ throw new Error("Leverage debt and collateral mints must differ");
535
+ }
536
+
537
+ if ("fundingAsset" in params && params.fundingAsset !== undefined && params.fundingAsset !== "debt")
538
+ throw new Error("Leverage funding must use the debt asset; swap other tokens before opening");
539
+ const positionId = address(params.positionId);
540
+ const debtTokenProgram = await tokenProgramForMint(
541
+ this.program.provider.connection,
542
+ debtMint
543
+ );
544
+
545
+ const openArgs = {
546
+ positionId,
547
+ debtAsset: params.debtAsset === "quote" ? 1 : 0,
548
+ marginAmount: governanceIntegerBN(params.marginAmount, "marginAmount"),
549
+ multiplierBps: governanceIntegerBN(
550
+ params.multiplierBps,
551
+ "multiplierBps"
552
+ ),
553
+ minCollateralOut: governanceIntegerBN(
554
+ params.minCollateralOut,
555
+ "minCollateralOut"
556
+ ),
557
+ referrer: null,
558
+ positionOwner: null,
559
+ limitPriceNad: governanceIntegerBN(
560
+ params.limitPriceNad ?? 0,
561
+ "limitPriceNad"
562
+ ),
563
+ };
564
+ return this.instruction(
565
+ "openLeverage",
566
+ openArgs,
567
+ {
568
+ accounts: {
569
+ market,
570
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
571
+ owner,
572
+ payer: address(params.payer ?? owner),
573
+ leveragePosition: address(
574
+ params.leveragePosition ??
575
+ deriveLeveragePositionAddress(market, owner, positionId)[0]
576
+ ),
577
+ debtMint,
578
+ collateralMint,
579
+ debtReserveVault: address(
580
+ params.debtReserveVault ??
581
+ deriveMarketReserveVaultAddress(market, debtMint)[0]
582
+ ),
583
+ collateralReserveVault: address(
584
+ params.collateralReserveVault ??
585
+ deriveMarketReserveVaultAddress(market, collateralMint)[0]
586
+ ),
587
+ leverageCollateralVault: address(
588
+ params.leverageCollateralVault ??
589
+ deriveLeverageCollateralVaultAddress(market, collateralMint)[0]
590
+ ),
591
+ ownerDebtAccount: address(
592
+ params.ownerDebtAccount ??
593
+ getAssociatedTokenAddressSync(
594
+ debtMint,
595
+ owner,
596
+ true,
597
+ debtTokenProgram
598
+ )
599
+ ),
600
+ referralPartner: null,
601
+ referralAccrual: null,
602
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
603
+ tokenProgram: TOKEN_PROGRAM_ID,
604
+ token2022Program: TOKEN_2022_PROGRAM_ID,
605
+ systemProgram: SystemProgram.programId,
606
+ },
607
+ remainingAccounts: [
608
+ ...(await this.hlpRemainingAccounts(market)),
609
+ ...(params.remainingAccounts ?? []),
610
+ ],
611
+ }
612
+ );
613
+ }
614
+
615
+ async buildOpenLeverageTransaction(
616
+ params: OpenLeverageParams
617
+ ): Promise<Transaction> {
618
+ const options = await this.withOraclePolicy("openLeverage", { accounts: {market: address(params.market)} });
619
+ return new Transaction().add(...oracleComputeBudgetInstructions(options.oraclePolicy),
620
+ await this.buildOpenLeverageInstruction(params)
621
+ );
622
+ }
623
+
624
+ /**
625
+ * Delegate a leverage position to a program that may act on it, which is how
626
+ * conditional orders (take-profit, stop-loss) are authorised.
627
+ */
628
+ async buildCreateLeverageDelegationInstruction(
629
+ params: CreateLeverageDelegationParams
630
+ ): Promise<TransactionInstruction> {
631
+ const market = address(params.market);
632
+ const leveragePosition = address(
633
+ params.leveragePosition ??
634
+ deriveLeveragePositionAddress(market, address(params.owner), address(params.positionId), address(params.namespaceAuthority ?? params.owner))[0]
635
+ );
636
+
637
+ return this.instruction(
638
+ "createLeverageDelegation" as DuskInstructionName,
639
+ {
640
+ debtAsset: params.debtAsset === "quote" ? 1 : 0,
641
+ delegatedProgram: address(params.delegatedProgram),
642
+ approvedActions: Number(params.approvedActions),
643
+ },
644
+ {
645
+ accounts: {
646
+ market,
647
+ leveragePosition,
648
+ leverageDelegation: address(
649
+ params.leverageDelegation ??
650
+ deriveLeverageDelegationAddress(leveragePosition)[0]
651
+ ),
652
+ owner: address(params.owner),
653
+ systemProgram: SystemProgram.programId,
654
+ },
655
+ remainingAccounts: params.remainingAccounts,
656
+ }
657
+ );
658
+ }
659
+
660
+ async buildCreateLeverageDelegationTransaction(
661
+ params: CreateLeverageDelegationParams
662
+ ): Promise<Transaction> {
663
+ return new Transaction().add(
664
+ await this.buildCreateLeverageDelegationInstruction(params)
665
+ );
666
+ }
667
+
668
+ private async buildSwapBuilder(params: SwapParams) {
669
+ const market = address(params.market);
670
+ const trader = address(params.trader);
671
+ const assetInMint = address(params.assetInMint);
672
+ const assetOutMint = address(params.assetOutMint);
673
+
674
+ if (assetInMint.equals(assetOutMint)) {
675
+ throw new Error("Swap input and output mints must differ");
676
+ }
677
+
678
+ const connection = this.program.provider.connection;
679
+ const [assetInProgram, assetOutProgram] = await Promise.all([
680
+ tokenProgramForMint(connection, assetInMint),
681
+ tokenProgramForMint(connection, assetOutMint),
682
+ ]);
683
+
684
+ return this.swapBuilder(
685
+ // A single positional SwapArgs struct: the generic builder spreads a
686
+ // non-array into one argument, so wrapping it in an outer object would
687
+ // serialize a struct of zeros and the program would reject the amount.
688
+ {
689
+ exactAssetIn: governanceIntegerBN(params.exactAssetIn, "exactAssetIn"),
690
+ minAssetOut: governanceIntegerBN(params.minAssetOut, "minAssetOut"),
691
+ },
692
+ {
693
+ market,
694
+ accounts: {
695
+ market,
696
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
697
+ trader,
698
+ assetInMint,
699
+ assetOutMint,
700
+ reserveInVault: address(
701
+ params.reserveInVault ??
702
+ deriveMarketReserveVaultAddress(market, assetInMint)[0]
703
+ ),
704
+ reserveOutVault: address(
705
+ params.reserveOutVault ??
706
+ deriveMarketReserveVaultAddress(market, assetOutMint)[0]
707
+ ),
708
+ traderAssetInAccount: address(
709
+ params.traderAssetInAccount ??
710
+ getAssociatedTokenAddressSync(
711
+ assetInMint,
712
+ trader,
713
+ true,
714
+ assetInProgram
715
+ )
716
+ ),
717
+ traderAssetOutAccount: address(
718
+ params.traderAssetOutAccount ??
719
+ getAssociatedTokenAddressSync(
720
+ assetOutMint,
721
+ trader,
722
+ true,
723
+ assetOutProgram
724
+ )
725
+ ),
726
+ tokenProgram: TOKEN_PROGRAM_ID,
727
+ token2022Program: TOKEN_2022_PROGRAM_ID,
728
+ },
729
+ remainingAccounts: params.remainingAccounts,
730
+ }
731
+ );
732
+ }
733
+
734
+ async initializeYieldAccountsInstruction(params: {
735
+ payer: AddressLike;
736
+ owner: AddressLike;
737
+ market: AddressLike;
738
+ lpMint: AddressLike;
739
+ baseMint: AddressLike;
740
+ quoteMint: AddressLike;
741
+ tokenKind: YieldTokenKind;
742
+ /** Supply the retired mint's cohort when initializing claims after rotation. */
743
+ retired?: boolean;
744
+ }): Promise<TransactionInstruction> {
745
+ const payer = address(params.payer);
746
+ const owner = address(params.owner);
747
+ const market = address(params.market);
748
+ const lpMint = address(params.lpMint);
749
+ const baseMint = address(params.baseMint);
750
+ const quoteMint = address(params.quoteMint);
751
+ const tokenKind = params.tokenKind === "ylp" || params.tokenKind === 0 ? { ylp: {} } : params.tokenKind === "junior" || params.tokenKind === 2 ? { junior: {} } : { hlp: {} };
752
+ return this.instruction("initializeYieldAccounts" as DuskInstructionName, { owner, tokenKind }, {
753
+ accounts: {
754
+ payer,
755
+ market,
756
+ lpMint,
757
+ baseMint,
758
+ quoteMint,
759
+ baseYieldAccount: deriveYieldAccountAddress(
760
+ market,
761
+ owner,
762
+ lpMint,
763
+ baseMint,
764
+ params.tokenKind,
765
+ this.program.programId
766
+ )[0],
767
+ quoteYieldAccount: deriveYieldAccountAddress(
768
+ market,
769
+ owner,
770
+ lpMint,
771
+ quoteMint,
772
+ params.tokenKind,
773
+ this.program.programId
774
+ )[0],
775
+ systemProgram: SystemProgram.programId,
776
+ },
777
+ remainingAccounts: params.retired
778
+ ? [{ pubkey: (params.tokenKind === "junior" || params.tokenKind === 2 ? deriveJuniorCohortAddress : deriveHlpCohortAddress)(market, lpMint, this.program.programId)[0], isSigner: false, isWritable: false }]
779
+ : [],
780
+ });
781
+ }
782
+
783
+ async initializeYieldAccountsTransaction(
784
+ params: Parameters<DuskWrite["initializeYieldAccountsInstruction"]>[0]
785
+ ): Promise<Transaction> {
786
+ return new Transaction().add(await this.initializeYieldAccountsInstruction(params));
787
+ }
788
+
789
+ async initializeLpTransferHookInstruction(params: {
790
+ payer: AddressLike;
791
+ market: AddressLike;
792
+ lpMint: AddressLike;
793
+ /** Pass this when composing market creation and hook setup in one transaction. */
794
+ tokenKind?: YieldTokenKind;
795
+ }): Promise<TransactionInstruction> {
796
+ const lpMint = address(params.lpMint);
797
+ const market = address(params.market);
798
+ let tokenKind = params.tokenKind;
799
+ if (tokenKind === undefined) {
800
+ const state = await this.fetchMarketAccount(market) as Market;
801
+ if (lpMint.equals(state.ylpMint)) tokenKind = "ylp";
802
+ else if (lpMint.equals(state.juniorMint)) tokenKind = "junior";
803
+ else if (lpMint.equals(state.baseSide.hlpMint) || lpMint.equals(state.quoteSide.hlpMint)) tokenKind = "hlp";
804
+ else throw new Error("LP mint does not belong to the market");
805
+ }
806
+ const isHlp = tokenKind === "hlp" || tokenKind === 1;
807
+ return this.instruction("initializeLpTransferHook" as DuskInstructionName, undefined, {
808
+ accounts: {
809
+ payer: address(params.payer),
810
+ market,
811
+ lpMint,
812
+ validationAccount: deriveYieldTransferHookValidationAddress(lpMint, this.program.programId)[0],
813
+ systemProgram: SystemProgram.programId,
814
+ },
815
+ remainingAccounts: isHlp
816
+ ? [{ pubkey: deriveHlpCohortAddress(market, lpMint, this.program.programId)[0], isSigner: false, isWritable: true }]
817
+ : [],
818
+ });
819
+ }
820
+
821
+ async initializeLpTransferHookTransaction(
822
+ params: Parameters<DuskWrite["initializeLpTransferHookInstruction"]>[0]
823
+ ): Promise<Transaction> {
824
+ return new Transaction().add(await this.initializeLpTransferHookInstruction(params));
825
+ }
826
+
827
+ /**
828
+ * Bring a market into existence.
829
+ *
830
+ * The three LP mints must already exist and carry the Dusk transfer hook —
831
+ * see `createHookedLpMintInstructions`. Every PDA is derived here rather
832
+ * than left to Anchor, because the market address depends on `paramsHash`,
833
+ * which is an argument rather than an account, and the vaults hang off the
834
+ * market in turn.
835
+ *
836
+ * `teamTreasury` and its wrapped-SOL account come from the futarchy
837
+ * authority, which must already be initialized on the deployment.
838
+ */
839
+ async initializeMarketInstruction(params: {
840
+ payer: AddressLike;
841
+ baseMint: AddressLike;
842
+ quoteMint: AddressLike;
843
+ ylpMint: AddressLike;
844
+ baseHlpMint: AddressLike;
845
+ quoteHlpMint: AddressLike;
846
+ teamTreasury: AddressLike;
847
+ teamTreasuryWsolAccount: AddressLike;
848
+ paramsHash: Uint8Array | Buffer | number[];
849
+ config: MarketLaunchConfig;
850
+ /** Installed atomically at creation. Omit or pass null for native pricing.
851
+ * Guided first liquidity derives its ratio from the validated current feed. */
852
+ oracle?: OraclePolicyInput | null;
853
+ /** Native launch-adapter price in NAD. Guided creation requires zero. */
854
+ bootstrapPriceNad?: GovernanceIntegerLike;
855
+ launchFeeProgressOffset?: number;
856
+ lpMetadata: {
857
+ ylp: { name: string; symbol: string; uri: string };
858
+ baseHlp: { name: string; symbol: string; uri: string };
859
+ quoteHlp: { name: string; symbol: string; uri: string };
860
+ };
861
+ }): Promise<TransactionInstruction> {
862
+ const baseMint = address(params.baseMint);
863
+ const quoteMint = address(params.quoteMint);
864
+ const paramsHash = Uint8Array.from(params.paramsHash);
865
+ if (paramsHash.length !== 32) {
866
+ throw new Error(`paramsHash must be 32 bytes, received ${paramsHash.length}`);
867
+ }
868
+ const [market] = deriveMarketAddress(baseMint, quoteMint, paramsHash);
869
+ const oracle = params.oracle == null ? null : oraclePolicy(params.oracle);
870
+ const bootstrapPriceNad = governanceIntegerBN(params.bootstrapPriceNad ?? 0, "bootstrapPriceNad");
871
+ if (oracle && oracle.lambdaBps > 0 && !bootstrapPriceNad.isZero())
872
+ throw new Error("Oracle-guided markets derive the initial price from the feed; omit bootstrapPriceNad");
873
+ return this.instruction(
874
+ "initializeMarket" as DuskInstructionName,
875
+ {
876
+ config: anchorMarketConfig(params.config),
877
+ oracle,
878
+ paramsHash: [...paramsHash],
879
+ bootstrapPriceNad,
880
+ launchFeeProgressOffset: params.launchFeeProgressOffset ?? 0,
881
+ ylpMetadata: params.lpMetadata.ylp,
882
+ baseHlpMetadata: params.lpMetadata.baseHlp,
883
+ quoteHlpMetadata: params.lpMetadata.quoteHlp,
884
+ },
885
+ {
886
+ accounts: {
887
+ payer: address(params.payer),
888
+ baseMint,
889
+ quoteMint,
890
+ ylpMint: address(params.ylpMint),
891
+ baseHlpMint: address(params.baseHlpMint),
892
+ quoteHlpMint: address(params.quoteHlpMint),
893
+ ylpTokenMetadata: deriveTokenMetadataAddress(address(params.ylpMint))[0],
894
+ baseHlpTokenMetadata: deriveTokenMetadataAddress(address(params.baseHlpMint))[0],
895
+ quoteHlpTokenMetadata: deriveTokenMetadataAddress(address(params.quoteHlpMint))[0],
896
+ market,
897
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
898
+ baseReserveVault: deriveMarketReserveVaultAddress(market, baseMint)[0],
899
+ quoteReserveVault: deriveMarketReserveVaultAddress(market, quoteMint)[0],
900
+ baseCollateralVault: deriveMarketCollateralVaultAddress(market, baseMint)[0],
901
+ quoteCollateralVault: deriveMarketCollateralVaultAddress(market, quoteMint)[0],
902
+ baseInsuranceVault: deriveInsuranceAddress(market, baseMint)[0],
903
+ quoteInsuranceVault: deriveInsuranceAddress(market, quoteMint)[0],
904
+ baseInterestVault: deriveMarketInterestVaultAddress(market, baseMint)[0],
905
+ quoteInterestVault: deriveMarketInterestVaultAddress(market, quoteMint)[0],
906
+ teamTreasury: address(params.teamTreasury),
907
+ teamTreasuryWsolAccount: address(params.teamTreasuryWsolAccount),
908
+ systemProgram: SystemProgram.programId,
909
+ tokenProgram: TOKEN_PROGRAM_ID,
910
+ token2022Program: TOKEN_2022_PROGRAM_ID,
911
+ sysvarInstructions: SYSVAR_INSTRUCTIONS_PUBKEY,
912
+ tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
913
+ },
914
+ }
915
+ );
916
+ }
917
+
918
+ async initializeMarketTransaction(
919
+ params: Parameters<DuskWrite["initializeMarketInstruction"]>[0]
920
+ ): Promise<Transaction> {
921
+ return new Transaction().add(await this.initializeMarketInstruction(params));
922
+ }
923
+
924
+ /**
925
+ * Donate to a market's insurance vault without receiving an LP claim.
926
+ * Does not fetch the market, so it can follow initialization in the same
927
+ * transaction. The program validates the selected side, mint and donor account.
928
+ */
929
+ async fortifyMarketInstruction(params: FortifyMarketParams): Promise<TransactionInstruction> {
930
+ if (params.asset !== "base" && params.asset !== "quote") {
931
+ throw new Error('asset must be "base" or "quote"');
932
+ }
933
+ const amount = governanceIntegerBN(params.amount, "amount");
934
+ if (amount.isZero()) throw new Error("amount must be positive");
935
+ const donor = address(params.donor);
936
+ const market = address(params.market);
937
+ const assetMint = address(params.assetMint);
938
+ const assetTokenProgram = params.assetTokenProgram
939
+ ? address(params.assetTokenProgram)
940
+ : await tokenProgramForMint(this.program.provider.connection, assetMint);
941
+ if (!assetTokenProgram.equals(TOKEN_PROGRAM_ID) && !assetTokenProgram.equals(TOKEN_2022_PROGRAM_ID)) {
942
+ throw new Error("assetTokenProgram must be SPL Token or Token-2022");
943
+ }
944
+ const donorAssetAccount = params.donorAssetAccount
945
+ ? address(params.donorAssetAccount)
946
+ : getAssociatedTokenAddressSync(assetMint, donor, true, assetTokenProgram);
947
+ return this.instruction("fortifyMarket", { asset: params.asset === "base" ? 0 : 1, amount }, {
948
+ accounts: {
949
+ market,
950
+ donor,
951
+ assetMint,
952
+ donorAssetAccount,
953
+ insuranceVault: deriveInsuranceAddress(market, assetMint, this.program.programId)[0],
954
+ tokenProgram: TOKEN_PROGRAM_ID,
955
+ token2022Program: TOKEN_2022_PROGRAM_ID,
956
+ },
957
+ });
958
+ }
959
+
960
+ async fortifyMarketTransaction(params: FortifyMarketParams): Promise<Transaction> {
961
+ return new Transaction().add(await this.fortifyMarketInstruction(params));
962
+ }
963
+
964
+ /** Burn-lock initial direct-yLP support and create one immutable proposal over one or more families. */
965
+ async createParameterProposal(
966
+ params: CreateParameterProposalParams
967
+ ): Promise<ParameterGovernanceBuild> {
968
+ assertProposalMetadata(params.metadata);
969
+ const proposer = address(params.proposer);
970
+ const market = address(params.market);
971
+ const state = await this.governanceMarketState(market);
972
+ const ylpMint = address(params.ylpMint ?? state.ylpMint);
973
+ const [proposal] = deriveParameterProposalAddress(
974
+ market,
975
+ proposer,
976
+ params.nonce,
977
+ this.program.programId
978
+ );
979
+ const [proposalSupport] = deriveProposalSupportAddress(
980
+ proposal,
981
+ proposer,
982
+ this.program.programId
983
+ );
984
+ const proposerYlpAccount = address(
985
+ params.holderYlpAccount ??
986
+ getAssociatedTokenAddressSync(ylpMint, proposer, true, TOKEN_2022_PROGRAM_ID)
987
+ );
988
+ const instruction = await this.instruction(
989
+ "createParameterProposal" as DuskInstructionName,
990
+ {
991
+ nonce: governanceIntegerBN(params.nonce, "nonce"),
992
+ updates: canonicalParameterUpdates(params.updates).map(anchorParameterUpdate),
993
+ metadata: cloneProposalMetadata(params.metadata),
994
+ initialSupport: governanceIntegerBN(params.initialSupport, "initialSupport"),
995
+ },
996
+ {
997
+ accounts: {
998
+ proposer,
999
+ market,
1000
+ proposal,
1001
+ proposalSupport,
1002
+ ylpMint,
1003
+ proposerYlpAccount,
1004
+ baseYieldAccount: address(
1005
+ params.baseYieldAccount ??
1006
+ deriveYieldAccountAddress(
1007
+ market,
1008
+ proposer,
1009
+ ylpMint,
1010
+ state.baseSide.assetMint,
1011
+ "ylp",
1012
+ this.program.programId
1013
+ )[0]
1014
+ ),
1015
+ quoteYieldAccount: address(
1016
+ params.quoteYieldAccount ??
1017
+ deriveYieldAccountAddress(
1018
+ market,
1019
+ proposer,
1020
+ ylpMint,
1021
+ state.quoteSide.assetMint,
1022
+ "ylp",
1023
+ this.program.programId
1024
+ )[0]
1025
+ ),
1026
+ baseHlpYlpVault: address(params.baseHlpYlpVault ?? state.baseHlpVault.ylpVault),
1027
+ quoteHlpYlpVault: address(params.quoteHlpYlpVault ?? state.quoteHlpVault.ylpVault),
1028
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1029
+ systemProgram: SystemProgram.programId,
1030
+ },
1031
+ }
1032
+ );
1033
+ return {
1034
+ proposal,
1035
+ proposalSupport,
1036
+ instruction,
1037
+ transaction: new Transaction().add(instruction),
1038
+ };
1039
+ }
1040
+
1041
+ /** Add burn-locked direct-yLP support; crossing strict majority queues atomically. */
1042
+ async supportParameterProposal(
1043
+ params: SupportParameterProposalParams
1044
+ ): Promise<ParameterGovernanceBuild> {
1045
+ const supporter = address(params.supporter);
1046
+ const market = address(params.market);
1047
+ const proposal = address(params.proposal);
1048
+ const state = await this.governanceMarketState(market);
1049
+ const ylpMint = address(params.ylpMint ?? state.ylpMint);
1050
+ const [proposalSupport] = deriveProposalSupportAddress(
1051
+ proposal,
1052
+ supporter,
1053
+ this.program.programId
1054
+ );
1055
+ const supporterYlpAccount = address(
1056
+ params.holderYlpAccount ??
1057
+ getAssociatedTokenAddressSync(ylpMint, supporter, true, TOKEN_2022_PROGRAM_ID)
1058
+ );
1059
+ const instruction = await this.instruction(
1060
+ "supportParameterProposal" as DuskInstructionName,
1061
+ { amount: governanceIntegerBN(params.amount, "amount"), digest: proposalDigestBytes(params.digest) },
1062
+ {
1063
+ accounts: {
1064
+ supporter,
1065
+ market,
1066
+ proposal,
1067
+ proposalSupport,
1068
+ ylpMint,
1069
+ supporterYlpAccount,
1070
+ baseYieldAccount: address(
1071
+ params.baseYieldAccount ??
1072
+ deriveYieldAccountAddress(
1073
+ market,
1074
+ supporter,
1075
+ ylpMint,
1076
+ state.baseSide.assetMint,
1077
+ "ylp",
1078
+ this.program.programId
1079
+ )[0]
1080
+ ),
1081
+ quoteYieldAccount: address(
1082
+ params.quoteYieldAccount ??
1083
+ deriveYieldAccountAddress(
1084
+ market,
1085
+ supporter,
1086
+ ylpMint,
1087
+ state.quoteSide.assetMint,
1088
+ "ylp",
1089
+ this.program.programId
1090
+ )[0]
1091
+ ),
1092
+ baseHlpYlpVault: address(params.baseHlpYlpVault ?? state.baseHlpVault.ylpVault),
1093
+ quoteHlpYlpVault: address(params.quoteHlpYlpVault ?? state.quoteHlpVault.ylpVault),
1094
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1095
+ systemProgram: SystemProgram.programId,
1096
+ },
1097
+ }
1098
+ );
1099
+ return {
1100
+ proposal,
1101
+ proposalSupport,
1102
+ instruction,
1103
+ transaction: new Transaction().add(instruction),
1104
+ };
1105
+ }
1106
+
1107
+ /** Permissionlessly queue after the denominator falls below already-locked support. */
1108
+ async queueParameterProposal(
1109
+ params: QueueParameterProposalParams
1110
+ ): Promise<ParameterGovernanceBuild> {
1111
+ const market = address(params.market);
1112
+ const proposal = address(params.proposal);
1113
+ const state = await this.governanceMarketState(market);
1114
+ const instruction = await this.instruction(
1115
+ "queueParameterProposal" as DuskInstructionName,
1116
+ undefined,
1117
+ {
1118
+ accounts: {
1119
+ market,
1120
+ proposal,
1121
+ ylpMint: address(params.ylpMint ?? state.ylpMint),
1122
+ baseHlpYlpVault: address(params.baseHlpYlpVault ?? state.baseHlpVault.ylpVault),
1123
+ quoteHlpYlpVault: address(params.quoteHlpYlpVault ?? state.quoteHlpVault.ylpVault),
1124
+ },
1125
+ }
1126
+ );
1127
+ return { proposal, instruction, transaction: new Transaction().add(instruction) };
1128
+ }
1129
+
1130
+ /** Execute inside the 7-day window. Standalone oracle policies can restore
1131
+ * pricing during distress; other updates retain utilization/health guards. */
1132
+ async executeParameterProposal(
1133
+ params: ExecuteParameterProposalParams
1134
+ ): Promise<ParameterGovernanceBuild> {
1135
+ const market = address(params.market);
1136
+ const proposal = address(params.proposal);
1137
+ const state = await this.governanceMarketState(market);
1138
+ const options = await this.withOraclePolicy("executeParameterProposal", {
1139
+ accounts: {
1140
+ market,
1141
+ baseMint: address(state.baseSide.assetMint),
1142
+ quoteMint: address(state.quoteSide.assetMint),
1143
+ proposal,
1144
+ },
1145
+ });
1146
+ const instruction = await this.instruction("executeParameterProposal", undefined, options);
1147
+ const budgetPolicy = options.oraclePolicy?.lambdaBps
1148
+ ? options.oraclePolicy : state.oracle?.policy;
1149
+ return { proposal, instruction, transaction: new Transaction().add(
1150
+ ...oracleComputeBudgetInstructions(budgetPolicy), instruction,
1151
+ ) };
1152
+ }
1153
+
1154
+ /** Release all or part of direct support and credit earned yield to its owner. */
1155
+ async withdrawParameterSupport(
1156
+ params: WithdrawParameterSupportParams
1157
+ ): Promise<ParameterGovernanceBuild> {
1158
+ const supporter = address(params.supporter);
1159
+ const market = address(params.market);
1160
+ const proposal = address(params.proposal);
1161
+ const state = await this.governanceMarketState(market);
1162
+ const ylpMint = address(params.ylpMint ?? state.ylpMint);
1163
+ const [proposalSupport] = deriveProposalSupportAddress(
1164
+ proposal,
1165
+ supporter,
1166
+ this.program.programId
1167
+ );
1168
+ const supporterYlpAccount = address(
1169
+ params.supporterYlpAccount ??
1170
+ getAssociatedTokenAddressSync(ylpMint, supporter, true, TOKEN_2022_PROGRAM_ID)
1171
+ );
1172
+ const instruction = await this.instruction(
1173
+ "withdrawParameterSupport" as DuskInstructionName,
1174
+ { amount: params.amount === undefined ? null : governanceIntegerBN(params.amount, "amount") },
1175
+ {
1176
+ accounts: {
1177
+ supporter,
1178
+ market,
1179
+ proposal,
1180
+ proposer: address(params.proposer),
1181
+ proposalSupport,
1182
+ ylpMint,
1183
+ supporterYlpAccount,
1184
+ baseYieldAccount: address(
1185
+ params.baseYieldAccount ??
1186
+ deriveYieldAccountAddress(
1187
+ market,
1188
+ supporter,
1189
+ ylpMint,
1190
+ state.baseSide.assetMint,
1191
+ "ylp",
1192
+ this.program.programId
1193
+ )[0]
1194
+ ),
1195
+ quoteYieldAccount: address(
1196
+ params.quoteYieldAccount ??
1197
+ deriveYieldAccountAddress(
1198
+ market,
1199
+ supporter,
1200
+ ylpMint,
1201
+ state.quoteSide.assetMint,
1202
+ "ylp",
1203
+ this.program.programId
1204
+ )[0]
1205
+ ),
1206
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1207
+ },
1208
+ }
1209
+ );
1210
+ return {
1211
+ proposal,
1212
+ proposalSupport,
1213
+ instruction,
1214
+ transaction: new Transaction().add(instruction),
1215
+ };
1216
+ }
1217
+
1218
+ private async governanceMarketState(market: PublicKey): Promise<GovernanceMarketState> {
1219
+ return (await this.fetchMarketAccount(market)) as GovernanceMarketState;
1220
+ }
1221
+
1222
+ async hlpLiquidityAction(
1223
+ name: "depositSingleSided" | "withdrawSingleSided",
1224
+ args: Record<string, unknown>,
1225
+ options: HlpLiquidityBuildOptions
1226
+ ): Promise<HlpLiquidityBuild> {
1227
+ const payer = address(options.payer);
1228
+ const owner = address(options.owner);
1229
+ const market = address(options.market);
1230
+ const lpMint = address(options.targetHlpMint);
1231
+ const baseMint = address(options.baseMint);
1232
+ const quoteMint = address(options.quoteMint);
1233
+ const baseYieldAccount = deriveYieldAccountAddress(
1234
+ market,
1235
+ owner,
1236
+ lpMint,
1237
+ baseMint,
1238
+ "hlp",
1239
+ this.program.programId
1240
+ )[0];
1241
+ const quoteYieldAccount = deriveYieldAccountAddress(
1242
+ market,
1243
+ owner,
1244
+ lpMint,
1245
+ quoteMint,
1246
+ "hlp",
1247
+ this.program.programId
1248
+ )[0];
1249
+ const [baseYieldInfo, quoteYieldInfo] = await Promise.all([
1250
+ this.program.provider.connection.getAccountInfo(baseYieldAccount),
1251
+ this.program.provider.connection.getAccountInfo(quoteYieldAccount),
1252
+ ]);
1253
+ const yieldAccountDefinition = this.program.idl.accounts?.find(
1254
+ (account) => account.name === "yieldAccount"
1255
+ );
1256
+ if (!yieldAccountDefinition) {
1257
+ throw new Error("Dusk IDL is missing YieldAccount");
1258
+ }
1259
+ const yieldAccountSize = this.program.coder.accounts.size("yieldAccount");
1260
+ const yieldAccountDiscriminator = Buffer.from(yieldAccountDefinition.discriminator);
1261
+ const yieldAccountsReady = [baseYieldInfo, quoteYieldInfo].every(
1262
+ (info) =>
1263
+ info !== null &&
1264
+ info.owner.equals(this.program.programId) &&
1265
+ info.data.length === yieldAccountSize &&
1266
+ info.data.subarray(0, yieldAccountDiscriminator.length).equals(yieldAccountDiscriminator)
1267
+ );
1268
+ const setupInstructions =
1269
+ yieldAccountsReady
1270
+ ? []
1271
+ : [
1272
+ await this.initializeYieldAccountsInstruction({
1273
+ payer,
1274
+ owner,
1275
+ market,
1276
+ lpMint,
1277
+ baseMint,
1278
+ quoteMint,
1279
+ tokenKind: "hlp",
1280
+ }),
1281
+ ];
1282
+ const actionInstruction = await this.instruction(name, args, {
1283
+ accounts: {
1284
+ ...options.accounts,
1285
+ market,
1286
+ owner,
1287
+ targetHlpMint: lpMint,
1288
+ baseMint,
1289
+ quoteMint,
1290
+ baseYieldAccount,
1291
+ quoteYieldAccount,
1292
+ },
1293
+ remainingAccounts: options.remainingAccounts,
1294
+ oraclePolicy: options.oraclePolicy,
1295
+ });
1296
+ return {
1297
+ baseYieldAccount,
1298
+ quoteYieldAccount,
1299
+ setupInstructions,
1300
+ actionInstruction,
1301
+ transaction: new Transaction().add(...setupInstructions, actionInstruction),
1302
+ };
1303
+ }
1304
+
1305
+ depositSingleSided(args: Record<string, unknown>, options: HlpLiquidityBuildOptions) {
1306
+ return this.hlpLiquidityAction("depositSingleSided", args, options);
1307
+ }
1308
+
1309
+ withdrawSingleSided(args: Record<string, unknown>, options: HlpLiquidityBuildOptions) {
1310
+ return this.hlpLiquidityAction("withdrawSingleSided", args, options);
1311
+ }
1312
+
1313
+ /** Begin a fresh hLP receipt cohort after the current vault has terminally closed. */
1314
+ rotateHlpCohortInstruction(params: {
1315
+ payer: AddressLike;
1316
+ market: AddressLike;
1317
+ oldHlpMint: AddressLike;
1318
+ newHlpMint: AddressLike;
1319
+ targetAsset: "base" | "quote";
1320
+ metadata: { name: string; symbol: string; uri: string };
1321
+ }): Promise<TransactionInstruction> {
1322
+ const market = address(params.market);
1323
+ const oldHlpMint = address(params.oldHlpMint);
1324
+ const newHlpMint = address(params.newHlpMint);
1325
+ return this.instruction("rotateHlpCohort" as DuskInstructionName, {
1326
+ targetAsset: params.targetAsset === "base" ? 0 : 1,
1327
+ metadata: params.metadata,
1328
+ }, {
1329
+ accounts: {
1330
+ payer: address(params.payer),
1331
+ market,
1332
+ oldHlpMint,
1333
+ newHlpMint,
1334
+ oldCohort: deriveHlpCohortAddress(market, oldHlpMint, this.program.programId)[0],
1335
+ newTokenMetadata: deriveTokenMetadataAddress(newHlpMint)[0],
1336
+ sysvarInstructions: SYSVAR_INSTRUCTIONS_PUBKEY,
1337
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1338
+ tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
1339
+ systemProgram: SystemProgram.programId,
1340
+ },
1341
+ });
1342
+ }
1343
+
1344
+ /** Burn old hLP receipts after terminal closure while preserving earned yield. */
1345
+ burnRetiredHlpReceiptInstruction(params: {
1346
+ market: AddressLike;
1347
+ owner: AddressLike;
1348
+ retiredMint: AddressLike;
1349
+ baseMint: AddressLike;
1350
+ quoteMint: AddressLike;
1351
+ amount: GovernanceIntegerLike;
1352
+ ownerHlpAccount?: AddressLike;
1353
+ }): Promise<TransactionInstruction> {
1354
+ const market = address(params.market);
1355
+ const owner = address(params.owner);
1356
+ const retiredMint = address(params.retiredMint);
1357
+ return this.instruction("burnRetiredHlpReceipt" as DuskInstructionName, {
1358
+ amount: governanceIntegerBN(params.amount),
1359
+ }, {
1360
+ accounts: {
1361
+ market,
1362
+ owner,
1363
+ retiredMint,
1364
+ cohort: deriveHlpCohortAddress(market, retiredMint, this.program.programId)[0],
1365
+ ownerHlpAccount: params.ownerHlpAccount
1366
+ ? address(params.ownerHlpAccount)
1367
+ : getAssociatedTokenAddressSync(retiredMint, owner, true, TOKEN_2022_PROGRAM_ID),
1368
+ baseYieldAccount: deriveYieldAccountAddress(
1369
+ market, owner, retiredMint, address(params.baseMint), "hlp", this.program.programId
1370
+ )[0],
1371
+ quoteYieldAccount: deriveYieldAccountAddress(
1372
+ market, owner, retiredMint, address(params.quoteMint), "hlp", this.program.programId
1373
+ )[0],
1374
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1375
+ },
1376
+ });
1377
+ }
1378
+
1379
+ async configureReferralPartnerInstruction(params: {
1380
+ authoritySigner: AddressLike;
1381
+ referrer: AddressLike;
1382
+ interestShareBps: number;
1383
+ active: boolean;
1384
+ futarchyAuthority?: AddressLike;
1385
+ }): Promise<TransactionInstruction> {
1386
+ assertReferralInterestShareBps(params.interestShareBps);
1387
+ const referrer = address(params.referrer);
1388
+ return this.instruction(
1389
+ "configureReferralPartner",
1390
+ {
1391
+ referrer,
1392
+ interestShareBps: params.interestShareBps,
1393
+ active: params.active,
1394
+ },
1395
+ {
1396
+ accounts: {
1397
+ authoritySigner: address(params.authoritySigner),
1398
+ futarchyAuthority:
1399
+ params.futarchyAuthority ?? deriveFutarchyAuthorityAddress()[0],
1400
+ referralPartner: deriveReferralPartnerAddress(referrer)[0],
1401
+ systemProgram: SystemProgram.programId,
1402
+ },
1403
+ }
1404
+ );
85
1405
  }
86
1406
 
87
- transaction(
88
- name: DuskInstructionName,
89
- args?: DuskInstructionArgs,
90
- options?: DuskBuildOptions
1407
+ async configureReferralPartnerTransaction(
1408
+ params: Parameters<DuskWrite["configureReferralPartnerInstruction"]>[0]
91
1409
  ): Promise<Transaction> {
92
- return this.builder(name, args, options).transaction();
1410
+ return new Transaction().add(await this.configureReferralPartnerInstruction(params));
1411
+ }
1412
+
1413
+ async initializeReferralAccrualInstruction(params: {
1414
+ payer: AddressLike;
1415
+ referrer: AddressLike;
1416
+ market: AddressLike;
1417
+ assetMint: AddressLike;
1418
+ }): Promise<TransactionInstruction> {
1419
+ const referral = referralAccrualAddresses(params);
1420
+ return this.instruction("initializeReferralAccrual", undefined, {
1421
+ accounts: {
1422
+ payer: address(params.payer),
1423
+ referralPartner: referral.referralPartner,
1424
+ market: address(params.market),
1425
+ assetMint: address(params.assetMint),
1426
+ referralAccrual: referral.referralAccrual,
1427
+ systemProgram: SystemProgram.programId,
1428
+ },
1429
+ });
93
1430
  }
94
1431
 
95
- rpc(name: DuskInstructionName, args?: DuskInstructionArgs, options?: DuskBuildOptions) {
96
- return this.builder(name, args, options).rpc();
1432
+ async initializeReferralAccrualTransaction(
1433
+ params: Parameters<DuskWrite["initializeReferralAccrualInstruction"]>[0]
1434
+ ): Promise<Transaction> {
1435
+ return new Transaction().add(
1436
+ await this.initializeReferralAccrualInstruction(params)
1437
+ );
97
1438
  }
98
1439
 
99
1440
  async referredAction(
@@ -101,11 +1442,16 @@ export class DuskWrite {
101
1442
  args: Record<string, unknown>,
102
1443
  options: ReferredActionOptions
103
1444
  ): Promise<ReferredActionBuild> {
104
- const setup = await buildReferralVaultSetupInstruction({
105
- connection: this.program.provider.connection,
1445
+ const referral = referralAccrualAddresses({
1446
+ referrer: options.referrer,
1447
+ market: options.market,
1448
+ assetMint: options.debtMint,
1449
+ });
1450
+ const setupInstruction = await this.initializeReferralAccrualInstruction({
106
1451
  payer: options.payer,
107
1452
  referrer: options.referrer,
108
- mint: options.debtMint,
1453
+ market: options.market,
1454
+ assetMint: options.debtMint,
109
1455
  });
110
1456
  const hookAccounts = options.transferHookTransfers?.length
111
1457
  ? await resolveTransferHookAccountMetas(
@@ -118,23 +1464,25 @@ export class DuskWrite {
118
1464
  {
119
1465
  ...args,
120
1466
  referrer: address(options.referrer),
121
- maxAcceptableReferralFeeBps: options.maxAcceptableReferralFeeBps,
122
1467
  },
123
1468
  {
124
1469
  accounts: {
125
1470
  ...options.accounts,
126
- referralProfile: setup.referralProfile,
127
- referralVault: setup.referralVault,
1471
+ referralPartner: referral.referralPartner,
1472
+ referralAccrual: referral.referralAccrual,
1473
+ ...(name === "openLeverage"
1474
+ ? { instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY }
1475
+ : {}),
128
1476
  },
129
1477
  remainingAccounts: mergeAccountMetas(options.remainingAccounts ?? [], hookAccounts),
130
1478
  }
131
1479
  );
132
1480
  return {
133
- referralProfile: setup.referralProfile,
134
- referralVault: setup.referralVault,
135
- setupInstruction: setup.instruction,
1481
+ referralPartner: referral.referralPartner,
1482
+ referralAccrual: referral.referralAccrual,
1483
+ setupInstruction,
136
1484
  actionInstruction,
137
- transaction: new Transaction().add(setup.instruction, actionInstruction),
1485
+ transaction: new Transaction().add(setupInstruction, actionInstruction),
138
1486
  };
139
1487
  }
140
1488
 
@@ -146,10 +1494,6 @@ export class DuskWrite {
146
1494
  return this.referredAction("openLeverage", args, options);
147
1495
  }
148
1496
 
149
- referredIncreaseLeverage(args: Record<string, unknown>, options: ReferredActionOptions) {
150
- return this.referredAction("increaseLeverage", args, options);
151
- }
152
-
153
1497
  async setReferralRecipientInstruction(params: {
154
1498
  authority: AddressLike;
155
1499
  recipient: AddressLike;
@@ -161,8 +1505,7 @@ export class DuskWrite {
161
1505
  {
162
1506
  accounts: {
163
1507
  authority,
164
- referralProfile: deriveReferralProfileAddress(authority)[0],
165
- systemProgram: SystemProgram.programId,
1508
+ referralPartner: deriveReferralPartnerAddress(authority)[0],
166
1509
  },
167
1510
  }
168
1511
  );
@@ -175,53 +1518,68 @@ export class DuskWrite {
175
1518
  return new Transaction().add(await this.setReferralRecipientInstruction(params));
176
1519
  }
177
1520
 
178
- async claimReferralFeesInstruction(params: {
1521
+ async claimReferralInterestInstruction(params: {
179
1522
  authority: AddressLike;
1523
+ market: AddressLike;
180
1524
  mint: AddressLike;
1525
+ interestVault?: AddressLike;
181
1526
  recipientTokenAccount: AddressLike;
182
1527
  remainingAccounts?: AccountMeta[];
183
1528
  }): Promise<TransactionInstruction> {
184
1529
  const authority = address(params.authority);
185
- const addresses = await referralVaultAddresses({
186
- connection: this.program.provider.connection,
1530
+ const market = address(params.market);
1531
+ const mintKey = address(params.mint);
1532
+ const referral = referralAccrualAddresses({
187
1533
  referrer: authority,
188
- mint: params.mint,
1534
+ market,
1535
+ assetMint: mintKey,
189
1536
  });
1537
+ const interestVault = address(
1538
+ params.interestVault ?? deriveMarketInterestVaultAddress(market, mintKey)[0]
1539
+ );
190
1540
  const recipientTokenAccount = address(params.recipientTokenAccount);
191
- const [vaultAccount, mint] = await Promise.all([
192
- getAccount(
193
- this.program.provider.connection,
194
- addresses.referralVault,
195
- undefined,
196
- addresses.tokenProgram
197
- ),
1541
+ const tokenProgram = await tokenProgramForMint(
1542
+ this.program.provider.connection,
1543
+ mintKey
1544
+ );
1545
+ const referralAccrual = (this.program as unknown as {
1546
+ account: {
1547
+ referralAccrual: {
1548
+ fetch(address: PublicKey): Promise<{ amount: { toString(): string } }>;
1549
+ };
1550
+ };
1551
+ }).account.referralAccrual;
1552
+ const [accrual, mint] = await Promise.all([
1553
+ referralAccrual.fetch(referral.referralAccrual),
198
1554
  getMint(
199
1555
  this.program.provider.connection,
200
- address(params.mint),
1556
+ mintKey,
201
1557
  undefined,
202
- addresses.tokenProgram
1558
+ tokenProgram
203
1559
  ),
204
1560
  ]);
205
1561
  const hookAccounts = await resolveTransferHookAccountMetas(
206
1562
  this.program.provider.connection,
207
1563
  [
208
1564
  {
209
- source: addresses.referralVault,
210
- mint: params.mint,
1565
+ source: interestVault,
1566
+ mint: mintKey,
211
1567
  destination: recipientTokenAccount,
212
- authority: addresses.referralProfile,
213
- amount: vaultAccount.amount,
1568
+ authority: market,
1569
+ amount: accrual.amount,
214
1570
  decimals: mint.decimals,
215
- tokenProgram: addresses.tokenProgram,
1571
+ tokenProgram,
216
1572
  },
217
1573
  ]
218
1574
  );
219
- return this.instruction("claimReferralFees", undefined, {
1575
+ return this.instruction("claimReferralInterest", undefined, {
220
1576
  accounts: {
1577
+ market,
221
1578
  authority,
222
- referralProfile: addresses.referralProfile,
223
- assetMint: address(params.mint),
224
- referralVault: addresses.referralVault,
1579
+ referralPartner: referral.referralPartner,
1580
+ assetMint: mintKey,
1581
+ referralAccrual: referral.referralAccrual,
1582
+ interestVault,
225
1583
  recipientTokenAccount,
226
1584
  tokenProgram: TOKEN_PROGRAM_ID,
227
1585
  token2022Program: TOKEN_2022_PROGRAM_ID,
@@ -230,14 +1588,900 @@ export class DuskWrite {
230
1588
  });
231
1589
  }
232
1590
 
233
- async claimReferralFeesTransaction(params: {
234
- authority: AddressLike;
235
- mint: AddressLike;
236
- recipientTokenAccount: AddressLike;
237
- remainingAccounts?: AccountMeta[];
238
- }): Promise<Transaction> {
239
- return new Transaction().add(await this.claimReferralFeesInstruction(params));
1591
+ async claimReferralInterestTransaction(
1592
+ params: Parameters<DuskWrite["claimReferralInterestInstruction"]>[0]
1593
+ ): Promise<Transaction> {
1594
+ return new Transaction().add(
1595
+ await this.claimReferralInterestInstruction(params)
1596
+ );
1597
+ }
1598
+
1599
+ /**
1600
+ * Deposit collateral into a borrow position, creating it when `positionId` is
1601
+ * new. Callers pass amounts in raw base units.
1602
+ */
1603
+ async depositCollateralInstruction(
1604
+ params: DepositCollateralParams
1605
+ ): Promise<TransactionInstruction> {
1606
+ const market = address(params.market);
1607
+ const owner = address(params.owner);
1608
+ const assetMint = address(params.assetMint);
1609
+ const positionId = address(params.positionId);
1610
+ return this.instruction(
1611
+ "depositCollateral" as DuskInstructionName,
1612
+ { positionId, depositAmount: governanceIntegerBN(params.depositAmount, "depositAmount") },
1613
+ {
1614
+ accounts: {
1615
+ market,
1616
+ owner,
1617
+ assetMint,
1618
+ collateralVault: address(
1619
+ params.collateralVault ??
1620
+ deriveMarketCollateralVaultAddress(market, assetMint)[0]
1621
+ ),
1622
+ ownerAssetAccount: address(params.ownerAssetAccount),
1623
+ borrowPosition: address(
1624
+ params.borrowPosition ??
1625
+ deriveBorrowPositionAddress(market, owner, positionId)[0]
1626
+ ),
1627
+ tokenProgram: TOKEN_PROGRAM_ID,
1628
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1629
+ },
1630
+ remainingAccounts: params.remainingAccounts,
1631
+ }
1632
+ );
1633
+ }
1634
+
1635
+ /** Donate to an existing borrow position. `owner` is the token payer. */
1636
+ async donateCollateralInstruction(params: DepositCollateralParams): Promise<TransactionInstruction> {
1637
+ const market = address(params.market);
1638
+ const assetMint = address(params.assetMint);
1639
+ return this.instruction("donateCollateral" as DuskInstructionName,
1640
+ { depositAmount: governanceIntegerBN(params.depositAmount, "depositAmount") }, {
1641
+ accounts: {
1642
+ market, owner: address(params.owner), assetMint,
1643
+ collateralVault: address(params.collateralVault ?? deriveMarketCollateralVaultAddress(market, assetMint)[0]),
1644
+ ownerAssetAccount: address(params.ownerAssetAccount),
1645
+ borrowPosition: address(params.borrowPosition ?? deriveBorrowPositionAddress(market, address(params.positionOwner ?? params.owner), address(params.positionId))[0]),
1646
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
1647
+ }, remainingAccounts: params.remainingAccounts,
1648
+ });
1649
+ }
1650
+
1651
+ /** Sweep both collateral balances and close a debt-free borrow position. */
1652
+ async withdrawAllCollateralInstruction(params: WithdrawAllCollateralParams): Promise<TransactionInstruction> {
1653
+ const market = address(params.market);
1654
+ const baseMint = address(params.baseMint);
1655
+ const quoteMint = address(params.quoteMint);
1656
+ return this.instruction("withdrawAllCollateral" as DuskInstructionName, {
1657
+ minBaseOut: governanceIntegerBN(params.minBaseOut, "minBaseOut"),
1658
+ minQuoteOut: governanceIntegerBN(params.minQuoteOut, "minQuoteOut"),
1659
+ }, { accounts: {
1660
+ market, owner: address(params.owner), baseMint, quoteMint,
1661
+ borrowPosition: address(params.borrowPosition ?? deriveBorrowPositionAddress(market, address(params.owner), address(params.positionId))[0]),
1662
+ baseCollateralVault: deriveMarketCollateralVaultAddress(market, baseMint)[0],
1663
+ quoteCollateralVault: deriveMarketCollateralVaultAddress(market, quoteMint)[0],
1664
+ ownerBaseAccount: address(params.ownerBaseAccount), ownerQuoteAccount: address(params.ownerQuoteAccount),
1665
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
1666
+ }, remainingAccounts: params.remainingAccounts });
1667
+ }
1668
+
1669
+ /** Return all collateral after a complete leverage repayment and close the position. */
1670
+ async withdrawRepaidLeverageInstruction(params: WithdrawRepaidLeverageParams): Promise<TransactionInstruction> {
1671
+ const market = address(params.market);
1672
+ const collateralMint = address(params.collateralMint);
1673
+ return this.instruction("withdrawRepaidLeverage" as DuskInstructionName,
1674
+ { minCollateralOut: governanceIntegerBN(params.minCollateralOut, "minCollateralOut") }, {
1675
+ accounts: {
1676
+ market, owner: address(params.owner), collateralMint,
1677
+ leveragePosition: address(params.leveragePosition ?? deriveLeveragePositionAddress(market, address(params.owner), address(params.positionId), address(params.namespaceAuthority ?? params.owner))[0]),
1678
+ collateralVault: deriveLeverageCollateralVaultAddress(market, collateralMint)[0],
1679
+ ownerCollateralAccount: address(params.ownerCollateralAccount),
1680
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
1681
+ }, remainingAccounts: params.remainingAccounts,
1682
+ });
1683
+ }
1684
+
1685
+ async depositCollateralTransaction(
1686
+ params: DepositCollateralParams
1687
+ ): Promise<Transaction> {
1688
+ return new Transaction().add(
1689
+ await this.depositCollateralInstruction(params)
1690
+ );
1691
+ }
1692
+
1693
+ /**
1694
+ * Withdraw collateral. `minAssetAmountOut` and `minLiquidationCfBps` are the
1695
+ * caller's slippage and health floors; the program rejects the withdrawal
1696
+ * rather than silently returning less.
1697
+ */
1698
+ async withdrawCollateralInstruction(
1699
+ params: WithdrawCollateralParams
1700
+ ): Promise<TransactionInstruction> {
1701
+ const market = address(params.market);
1702
+ const owner = address(params.owner);
1703
+ const assetMint = address(params.assetMint);
1704
+ const positionId = address(params.positionId);
1705
+ return this.instruction(
1706
+ "withdrawCollateral" as DuskInstructionName,
1707
+ {
1708
+ withdrawAmount: governanceIntegerBN(params.withdrawAmount, "withdrawAmount"),
1709
+ minAssetAmountOut: governanceIntegerBN(params.minAssetAmountOut, "minAssetAmountOut"),
1710
+ minLiquidationCfBps: params.minLiquidationCfBps,
1711
+ },
1712
+ {
1713
+ accounts: {
1714
+ market,
1715
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
1716
+ owner,
1717
+ assetMint,
1718
+ collateralVault: address(
1719
+ params.collateralVault ??
1720
+ deriveMarketCollateralVaultAddress(market, assetMint)[0]
1721
+ ),
1722
+ ownerAssetAccount: address(params.ownerAssetAccount),
1723
+ borrowPosition: address(
1724
+ params.borrowPosition ??
1725
+ deriveBorrowPositionAddress(market, owner, positionId)[0]
1726
+ ),
1727
+ tokenProgram: TOKEN_PROGRAM_ID,
1728
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1729
+ },
1730
+ remainingAccounts: params.remainingAccounts,
1731
+ }
1732
+ );
1733
+ }
1734
+
1735
+ async withdrawCollateralTransaction(
1736
+ params: WithdrawCollateralParams
1737
+ ): Promise<Transaction> {
1738
+ return new Transaction().add(
1739
+ await this.withdrawCollateralInstruction(params)
1740
+ );
1741
+ }
1742
+
1743
+ /**
1744
+ * Repay anyone’s borrowed debt using `owner`’s tokens, without collateral rights.
1745
+ * Pass the wallet balance as `repayAmount` to clear a
1746
+ * position; the program repays at most the outstanding debt.
1747
+ */
1748
+ async repayInstruction(params: RepayParams): Promise<TransactionInstruction> {
1749
+ const market = address(params.market);
1750
+ const owner = address(params.owner);
1751
+ const debtAssetMint = address(params.debtAssetMint);
1752
+ const positionId = address(params.positionId);
1753
+ const referralPartner = params.referralPartner
1754
+ ? address(params.referralPartner)
1755
+ : null;
1756
+ return this.instruction(
1757
+ "repay" as DuskInstructionName,
1758
+ { repayAmount: governanceIntegerBN(params.repayAmount, "repayAmount") },
1759
+ {
1760
+ accounts: {
1761
+ market,
1762
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
1763
+ owner,
1764
+ debtAssetMint,
1765
+ collateralAssetMint: address(params.collateralAssetMint),
1766
+ reserveVault: address(
1767
+ params.reserveVault ??
1768
+ deriveMarketReserveVaultAddress(market, debtAssetMint)[0]
1769
+ ),
1770
+ interestVault: address(
1771
+ params.interestVault ??
1772
+ deriveMarketInterestVaultAddress(market, debtAssetMint)[0]
1773
+ ),
1774
+ ownerDebtAccount: address(params.ownerDebtAccount),
1775
+ borrowPosition: address(
1776
+ params.borrowPosition ??
1777
+ deriveBorrowPositionAddress(market, address(params.positionOwner ?? params.owner), positionId)[0]
1778
+ ),
1779
+ referralPartner,
1780
+ referralAccrual: referralPartner
1781
+ ? deriveReferralAccrualAddress(
1782
+ referralPartner,
1783
+ market,
1784
+ debtAssetMint
1785
+ )[0]
1786
+ : null,
1787
+ tokenProgram: TOKEN_PROGRAM_ID,
1788
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1789
+ },
1790
+ remainingAccounts: [...(await this.hlpRemainingAccounts(market)), ...(params.remainingAccounts ?? [])],
1791
+ }
1792
+ );
1793
+ }
1794
+
1795
+ async repayTransaction(params: RepayParams): Promise<Transaction> {
1796
+ return new Transaction().add(await this.repayInstruction(params));
1797
+ }
1798
+
1799
+ /**
1800
+ * Add balanced yLP liquidity. `minYlpAmount` is the caller's slippage floor;
1801
+ * the program rejects the deposit rather than minting fewer shares.
1802
+ */
1803
+ async addLiquidityInstruction(
1804
+ params: AddLiquidityParams
1805
+ ): Promise<TransactionInstruction> {
1806
+ const common = await this.resolveYlpAccounts(params);
1807
+ return this.instruction(
1808
+ "addLiquidity" as DuskInstructionName,
1809
+ {
1810
+ baseDepositAmount: governanceIntegerBN(
1811
+ params.baseDepositAmount,
1812
+ "baseDepositAmount"
1813
+ ),
1814
+ quoteDepositAmount: governanceIntegerBN(
1815
+ params.quoteDepositAmount,
1816
+ "quoteDepositAmount"
1817
+ ),
1818
+ minYlpAmount: governanceIntegerBN(params.minYlpAmount, "minYlpAmount"),
1819
+ },
1820
+ {
1821
+ accounts: {
1822
+ ...common,
1823
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
1824
+ },
1825
+ remainingAccounts: params.remainingAccounts,
1826
+ }
1827
+ );
1828
+ }
1829
+
1830
+ async addLiquidityTransaction(
1831
+ params: AddLiquidityParams
1832
+ ): Promise<Transaction> {
1833
+ return new Transaction().add(await this.addLiquidityInstruction(params));
1834
+ }
1835
+
1836
+ /**
1837
+ * Burn yLP for the underlying pair. Both minimums are enforced by the
1838
+ * program, so a partially-filled withdrawal fails instead of silently
1839
+ * returning less of one side.
1840
+ */
1841
+ async removeLiquidityInstruction(
1842
+ params: RemoveLiquidityParams
1843
+ ): Promise<TransactionInstruction> {
1844
+ const common = await this.resolveYlpAccounts(params);
1845
+ return this.instruction(
1846
+ "removeLiquidity" as DuskInstructionName,
1847
+ {
1848
+ ylpAmount: governanceIntegerBN(params.ylpAmount, "ylpAmount"),
1849
+ minBaseAmountOut: governanceIntegerBN(
1850
+ params.minBaseAmountOut,
1851
+ "minBaseAmountOut"
1852
+ ),
1853
+ minQuoteAmountOut: governanceIntegerBN(
1854
+ params.minQuoteAmountOut,
1855
+ "minQuoteAmountOut"
1856
+ ),
1857
+ },
1858
+ { accounts: common, remainingAccounts: params.remainingAccounts }
1859
+ );
1860
+ }
1861
+
1862
+ async removeLiquidityTransaction(
1863
+ params: RemoveLiquidityParams
1864
+ ): Promise<Transaction> {
1865
+ return new Transaction().add(await this.removeLiquidityInstruction(params));
1866
+ }
1867
+
1868
+ /**
1869
+ * Accounts shared by both balanced yLP instructions. Reserve vaults and yLP
1870
+ * yield accounts derive from the market; token programs resolve per mint so
1871
+ * a Token-2022 side needs no caller branching.
1872
+ */
1873
+ /** Borrow more against an open position and receive collateral. */
1874
+ async increaseLeverageInstruction(params: IncreaseLeverageParams): Promise<TransactionInstruction> {
1875
+ return this.fundLeverageInstruction(params, 0n);
1876
+ }
1877
+
1878
+ /** Add debt-token equity and optional borrowing to the same position. */
1879
+ async addToLeverageInstruction(params: AddToLeverageParams): Promise<TransactionInstruction> {
1880
+ if (BigInt(params.marginAmount.toString()) <= 0n) throw new RangeError("marginAmount must be positive");
1881
+ return this.fundLeverageInstruction(params, params.marginAmount, params.ownerDebtAccount);
1882
+ }
1883
+
1884
+ async addToLeverageTransaction(params: AddToLeverageParams): Promise<Transaction> {
1885
+ return new Transaction().add(await this.addToLeverageInstruction(params));
1886
+ }
1887
+
1888
+ private async fundLeverageInstruction(
1889
+ params: IncreaseLeverageParams, marginAmount: RawAmount, ownerDebtAccount?: AddressLike
1890
+ ): Promise<TransactionInstruction> {
1891
+ const core = await this.resolveLeverageAccounts(params);
1892
+ return this.instruction(
1893
+ "increaseLeverage" as DuskInstructionName,
1894
+ {
1895
+ debtAsset: marketAssetIndex(params.debtAsset),
1896
+ debtAmount: governanceIntegerBN(params.debtAmount, "debtAmount"),
1897
+ marginAmount: governanceIntegerBN(marginAmount, "marginAmount"),
1898
+ minCollateralOut: governanceIntegerBN(
1899
+ params.minCollateralOut,
1900
+ "minCollateralOut"
1901
+ ),
1902
+ },
1903
+ {
1904
+ accounts: {
1905
+ market: core.market,
1906
+ futarchyAuthority: core.futarchyAuthority,
1907
+ positionOwner: core.positionOwner,
1908
+ leveragePosition: core.leveragePosition,
1909
+ debtMint: core.debtMint,
1910
+ collateralMint: core.collateralMint,
1911
+ debtReserveVault: core.debtReserveVault,
1912
+ collateralReserveVault: core.collateralReserveVault,
1913
+ leverageCollateralVault: core.leverageCollateralVault,
1914
+ owner: core.owner,
1915
+ ownerDebtAccount: ownerDebtAccount ? address(ownerDebtAccount) : null,
1916
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
1917
+ tokenProgram: core.tokenProgram,
1918
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1919
+ },
1920
+ remainingAccounts: [
1921
+ ...(await this.hlpRemainingAccounts(core.market)),
1922
+ ...(params.remainingAccounts ?? []),
1923
+ ],
1924
+ }
1925
+ );
1926
+ }
1927
+
1928
+ async increaseLeverageTransaction(
1929
+ params: IncreaseLeverageParams
1930
+ ): Promise<Transaction> {
1931
+ return new Transaction().add(
1932
+ await this.increaseLeverageInstruction(params)
1933
+ );
1934
+ }
1935
+
1936
+ /** Sell collateral to repay debt without closing the position. */
1937
+ async decreaseLeverageInstruction(
1938
+ params: DecreaseLeverageParams
1939
+ ): Promise<TransactionInstruction> {
1940
+ const core = await this.resolveLeverageAccounts(params);
1941
+ return this.instruction(
1942
+ "decreaseLeverage" as DuskInstructionName,
1943
+ {
1944
+ debtAsset: marketAssetIndex(params.debtAsset),
1945
+ collateralAmount: governanceIntegerBN(
1946
+ params.collateralAmount,
1947
+ "collateralAmount"
1948
+ ),
1949
+ minRepayOut: governanceIntegerBN(params.minRepayOut, "minRepayOut"),
1950
+ maxSurplusOut: governanceIntegerBN(params.maxSurplusOut ?? 0n, "maxSurplusOut"),
1951
+ },
1952
+ {
1953
+ accounts: {
1954
+ market: core.market,
1955
+ futarchyAuthority: core.futarchyAuthority,
1956
+ positionOwner: core.positionOwner,
1957
+ leveragePosition: core.leveragePosition,
1958
+ debtMint: core.debtMint,
1959
+ collateralMint: core.collateralMint,
1960
+ debtReserveVault: core.debtReserveVault,
1961
+ collateralReserveVault: core.collateralReserveVault,
1962
+ debtInterestVault: core.debtInterestVault,
1963
+ ownerDebtAccount: address(params.ownerDebtAccount),
1964
+ leverageCollateralVault: core.leverageCollateralVault,
1965
+ referralPartner: core.referralPartner,
1966
+ referralAccrual: core.referralAccrual,
1967
+ owner: core.owner,
1968
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
1969
+ tokenProgram: core.tokenProgram,
1970
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1971
+ },
1972
+ remainingAccounts: [
1973
+ ...(await this.hlpRemainingAccounts(core.market)),
1974
+ ...(params.remainingAccounts ?? []),
1975
+ ],
1976
+ }
1977
+ );
1978
+ }
1979
+
1980
+ async decreaseLeverageTransaction(
1981
+ params: DecreaseLeverageParams
1982
+ ): Promise<Transaction> {
1983
+ return new Transaction().add(
1984
+ await this.decreaseLeverageInstruction(params)
1985
+ );
1986
+ }
1987
+
1988
+ /** Repay anyone’s leverage debt from `owner`’s tokens; collateral stays with the position owner. */
1989
+ async addLeverageMarginInstruction(params: LeverageMarginParams): Promise<TransactionInstruction> {
1990
+ return this.repayLeverageInstruction(params);
1991
+ }
1992
+
1993
+ /** Permissionless repayment without an unnecessary collateral-sale quote. */
1994
+ async repayLeverageInstruction(params: LeverageMarginParams): Promise<TransactionInstruction> {
1995
+ return this.leverageRepaymentInstruction(params, "repayLeverage");
1996
+ }
1997
+
1998
+ private async leverageRepaymentInstruction(
1999
+ params: LeverageMarginParams, method: "addLeverageMargin" | "repayLeverage"
2000
+ ): Promise<TransactionInstruction> {
2001
+ const core = await this.resolveLeverageAccounts(params);
2002
+ return this.instruction(
2003
+ method as DuskInstructionName,
2004
+ {
2005
+ debtAsset: marketAssetIndex(params.debtAsset),
2006
+ amount: governanceIntegerBN(params.amount, "amount"),
2007
+ },
2008
+ {
2009
+ accounts: {
2010
+ market: core.market,
2011
+ futarchyAuthority: core.futarchyAuthority,
2012
+ positionOwner: core.positionOwner,
2013
+ leveragePosition: core.leveragePosition,
2014
+ debtMint: core.debtMint,
2015
+ collateralMint: core.collateralMint,
2016
+ debtReserveVault: core.debtReserveVault,
2017
+ debtInterestVault: core.debtInterestVault,
2018
+ ownerDebtAccount: address(params.ownerDebtAccount),
2019
+ referralPartner: core.referralPartner,
2020
+ referralAccrual: core.referralAccrual,
2021
+ owner: core.owner,
2022
+ tokenProgram: core.tokenProgram,
2023
+ token2022Program: TOKEN_2022_PROGRAM_ID,
2024
+ },
2025
+ remainingAccounts: [...(await this.hlpRemainingAccounts(core.market)), ...(params.remainingAccounts ?? [])],
2026
+ }
2027
+ );
2028
+ }
2029
+
2030
+ async repayLeverageTransaction(params: LeverageMarginParams): Promise<Transaction> {
2031
+ return new Transaction().add(await this.repayLeverageInstruction(params));
2032
+ }
2033
+
2034
+ async addLeverageMarginTransaction(
2035
+ params: LeverageMarginParams
2036
+ ): Promise<Transaction> {
2037
+ return new Transaction().add(
2038
+ await this.repayLeverageInstruction(params)
2039
+ );
2040
+ }
2041
+
2042
+ /**
2043
+ * Owner-signed proportional partial/full close. Delegated closes use the delegate client.
2044
+ */
2045
+ async closeLeverageInstruction(
2046
+ params: CloseLeverageParams,
2047
+ marketSnapshot?: Market
2048
+ ): Promise<TransactionInstruction> {
2049
+ if ("collateralFunded" in params && params.collateralFunded === true)
2050
+ throw new Error("Collateral-funded leverage closes are no longer supported");
2051
+ const closeBps = params.closeBps ?? 10_000;
2052
+ if (!Number.isSafeInteger(closeBps) || closeBps <= 0 || closeBps > 10_000)
2053
+ throw new RangeError("closeBps must be between 1 and 10000");
2054
+ const core = await this.resolveLeverageAccounts(params);
2055
+ return this.instruction(
2056
+ "closeLeverage",
2057
+ {
2058
+ debtAsset: marketAssetIndex(params.debtAsset),
2059
+ minAmountOut: governanceIntegerBN(params.minAmountOut, "minAmountOut"),
2060
+ closeBps,
2061
+ },
2062
+ {
2063
+ accounts: {
2064
+ market: core.market,
2065
+ futarchyAuthority: core.futarchyAuthority,
2066
+ positionOwner: core.positionOwner,
2067
+ leveragePosition: core.leveragePosition,
2068
+ debtMint: core.debtMint,
2069
+ collateralMint: core.collateralMint,
2070
+ debtReserveVault: core.debtReserveVault,
2071
+ collateralReserveVault: core.collateralReserveVault,
2072
+ debtInterestVault: core.debtInterestVault,
2073
+ leverageCollateralVault: core.leverageCollateralVault,
2074
+ ownerDebtAccount: address(params.ownerDebtAccount),
2075
+ delegateFeeRecipient: params.delegateFeeRecipient
2076
+ ? address(params.delegateFeeRecipient)
2077
+ : null,
2078
+ delegateExecutorAccount: params.delegateExecutorAccount
2079
+ ? address(params.delegateExecutorAccount)
2080
+ : null,
2081
+ referralPartner: core.referralPartner,
2082
+ referralAccrual: core.referralAccrual,
2083
+ leverageDelegation: params.leverageDelegation
2084
+ ? address(params.leverageDelegation)
2085
+ : null,
2086
+ delegatedProgram: params.delegatedProgram
2087
+ ? address(params.delegatedProgram)
2088
+ : null,
2089
+ authority: address(params.authority ?? params.positionOwner),
2090
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
2091
+ tokenProgram: core.tokenProgram,
2092
+ token2022Program: TOKEN_2022_PROGRAM_ID,
2093
+ },
2094
+ remainingAccounts: [
2095
+ ...(await this.hlpRemainingAccounts(core.market, marketSnapshot)),
2096
+ ...(params.remainingAccounts ?? []),
2097
+ ],
2098
+ }
2099
+ );
2100
+ }
2101
+
2102
+ async closeLeverageTransaction(
2103
+ params: CloseLeverageParams
2104
+ ): Promise<Transaction> {
2105
+ return new Transaction().add(await this.closeLeverageInstruction(params));
2106
+ }
2107
+
2108
+ /**
2109
+ * Accounts shared across the leverage lifecycle. Individual builders pass
2110
+ * through only the subset their instruction declares.
2111
+ */
2112
+ private async resolveLeverageAccounts(params: LeverageAccounts) {
2113
+ const market = address(params.market);
2114
+ const positionOwner = address(params.positionOwner);
2115
+ const debtMint = address(params.debtMint);
2116
+ const collateralMint = address(params.collateralMint);
2117
+ const positionId = address(params.positionId);
2118
+ const referralPartner = params.referralPartner
2119
+ ? address(params.referralPartner)
2120
+ : null;
2121
+ return {
2122
+ market,
2123
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
2124
+ positionOwner,
2125
+ owner: address(params.owner ?? params.positionOwner),
2126
+ leveragePosition: address(
2127
+ params.leveragePosition ??
2128
+ deriveLeveragePositionAddress(market, positionOwner, positionId, address(params.namespaceAuthority ?? params.positionOwner))[0]
2129
+ ),
2130
+ debtMint,
2131
+ collateralMint,
2132
+ debtReserveVault: address(
2133
+ params.debtReserveVault ??
2134
+ deriveMarketReserveVaultAddress(market, debtMint)[0]
2135
+ ),
2136
+ collateralReserveVault: address(
2137
+ params.collateralReserveVault ??
2138
+ deriveMarketReserveVaultAddress(market, collateralMint)[0]
2139
+ ),
2140
+ debtInterestVault: address(
2141
+ params.debtInterestVault ??
2142
+ deriveMarketInterestVaultAddress(market, debtMint)[0]
2143
+ ),
2144
+ leverageCollateralVault: address(
2145
+ params.leverageCollateralVault ??
2146
+ deriveLeverageCollateralVaultAddress(market, collateralMint)[0]
2147
+ ),
2148
+ referralPartner,
2149
+ referralAccrual: referralPartner
2150
+ ? deriveReferralAccrualAddress(referralPartner, market, debtMint)[0]
2151
+ : null,
2152
+ tokenProgram: TOKEN_PROGRAM_ID,
2153
+ };
2154
+ }
2155
+
2156
+ private async resolveYlpAccounts(params: YlpLiquidityAccounts) {
2157
+ const market = address(params.market);
2158
+ const owner = address(params.owner);
2159
+ const baseMint = address(params.baseMint);
2160
+ const quoteMint = address(params.quoteMint);
2161
+ const ylpMint = address(params.ylpMint);
2162
+ return {
2163
+ market,
2164
+ owner,
2165
+ baseMint,
2166
+ quoteMint,
2167
+ ylpMint,
2168
+ baseReserveVault: address(
2169
+ params.baseReserveVault ??
2170
+ deriveMarketReserveVaultAddress(market, baseMint)[0]
2171
+ ),
2172
+ quoteReserveVault: address(
2173
+ params.quoteReserveVault ??
2174
+ deriveMarketReserveVaultAddress(market, quoteMint)[0]
2175
+ ),
2176
+ ownerBaseAccount: address(params.ownerBaseAccount),
2177
+ ownerQuoteAccount: address(params.ownerQuoteAccount),
2178
+ ownerYlpAccount: address(params.ownerYlpAccount),
2179
+ baseYieldAccount: address(
2180
+ params.baseYieldAccount ??
2181
+ deriveYieldAccountAddress(
2182
+ market,
2183
+ owner,
2184
+ ylpMint,
2185
+ baseMint,
2186
+ "ylp",
2187
+ this.program.programId
2188
+ )[0]
2189
+ ),
2190
+ quoteYieldAccount: address(
2191
+ params.quoteYieldAccount ??
2192
+ deriveYieldAccountAddress(
2193
+ market,
2194
+ owner,
2195
+ ylpMint,
2196
+ quoteMint,
2197
+ "ylp",
2198
+ this.program.programId
2199
+ )[0]
2200
+ ),
2201
+ tokenProgram: TOKEN_PROGRAM_ID,
2202
+ token2022Program: TOKEN_2022_PROGRAM_ID,
2203
+ };
2204
+ }
2205
+ }
2206
+
2207
+ /** Raw base-unit amount. Accepts bigint to keep callers off floating point. */
2208
+ export type RawAmount = bigint | number | string;
2209
+
2210
+ interface LendingPositionAccounts {
2211
+ market: AddressLike;
2212
+ owner: AddressLike;
2213
+ /** Beneficiary when a different wallet pays for this position. */
2214
+ positionOwner?: AddressLike;
2215
+ /** Position discriminator; the borrow position PDA derives from it. */
2216
+ positionId: AddressLike;
2217
+ borrowPosition?: AddressLike;
2218
+ remainingAccounts?: AccountMeta[];
2219
+ }
2220
+
2221
+ export interface DepositCollateralParams extends LendingPositionAccounts {
2222
+ assetMint: AddressLike;
2223
+ ownerAssetAccount: AddressLike;
2224
+ depositAmount: RawAmount;
2225
+ collateralVault?: AddressLike;
2226
+ }
2227
+
2228
+ export interface WithdrawCollateralParams extends LendingPositionAccounts {
2229
+ assetMint: AddressLike;
2230
+ ownerAssetAccount: AddressLike;
2231
+ withdrawAmount: RawAmount;
2232
+ minAssetAmountOut: RawAmount;
2233
+ /** Health floor enforced by the program, in basis points. */
2234
+ minLiquidationCfBps: number;
2235
+ collateralVault?: AddressLike;
2236
+ }
2237
+
2238
+ export interface RepayParams extends LendingPositionAccounts {
2239
+ debtAssetMint: AddressLike;
2240
+ collateralAssetMint: AddressLike;
2241
+ ownerDebtAccount: AddressLike;
2242
+ repayAmount: RawAmount;
2243
+ /** Omit when the position has no referrer. */
2244
+ referralPartner?: AddressLike | null;
2245
+ reserveVault?: AddressLike;
2246
+ interestVault?: AddressLike;
2247
+ }
2248
+
2249
+ /** Which side of the pair carries the debt. */
2250
+ export type MarketAssetSide = "base" | "quote";
2251
+
2252
+ function marketAssetIndex(side: MarketAssetSide): number {
2253
+ if (side !== "base" && side !== "quote") {
2254
+ throw new Error(`debtAsset must be "base" or "quote", got ${String(side)}`);
2255
+ }
2256
+ return side === "base" ? 0 : 1;
2257
+ }
2258
+
2259
+ interface LeverageAccounts {
2260
+ market: AddressLike;
2261
+ positionOwner: AddressLike;
2262
+ /** Position discriminator; the leverage position PDA derives from it. */
2263
+ positionId: AddressLike;
2264
+ debtMint: AddressLike;
2265
+ collateralMint: AddressLike;
2266
+ debtAsset: MarketAssetSide;
2267
+ /** Signer when it differs from the position owner. */
2268
+ owner?: AddressLike;
2269
+ /** Signer that originally funded the position, if different from its owner. */
2270
+ namespaceAuthority?: AddressLike;
2271
+ leveragePosition?: AddressLike;
2272
+ debtReserveVault?: AddressLike;
2273
+ collateralReserveVault?: AddressLike;
2274
+ debtInterestVault?: AddressLike;
2275
+ leverageCollateralVault?: AddressLike;
2276
+ referralPartner?: AddressLike | null;
2277
+ remainingAccounts?: AccountMeta[];
2278
+ }
2279
+
2280
+ export interface IncreaseLeverageParams extends LeverageAccounts {
2281
+ debtAmount: RawAmount;
2282
+ minCollateralOut: RawAmount;
2283
+ }
2284
+
2285
+ export interface AddToLeverageParams extends IncreaseLeverageParams {
2286
+ /** Gross wallet funding in the borrowed token. */
2287
+ marginAmount: RawAmount;
2288
+ ownerDebtAccount: AddressLike;
2289
+ }
2290
+
2291
+ export interface DecreaseLeverageParams extends LeverageAccounts {
2292
+ collateralAmount: RawAmount;
2293
+ minRepayOut: RawAmount;
2294
+ /** Owner-owned debt-token account for unused repayment output. */
2295
+ ownerDebtAccount: AddressLike;
2296
+ /** Gross surplus limit; defaults to zero. Use a bounded value for 1x rounding. */
2297
+ maxSurplusOut?: RawAmount;
2298
+ }
2299
+
2300
+ export interface LeverageMarginParams extends LeverageAccounts {
2301
+ amount: RawAmount;
2302
+ ownerDebtAccount: AddressLike;
2303
+ }
2304
+
2305
+ export interface CloseLeverageParams extends LeverageAccounts {
2306
+ /** Minimum net wallet payout after all transfer fees. */
2307
+ minAmountOut: RawAmount;
2308
+ /** Percentage of the entire position to remove. Default 10000 closes all. */
2309
+ closeBps?: number;
2310
+ /** Payout account owned by the position owner. */
2311
+ ownerDebtAccount: AddressLike;
2312
+ /** Required for delegated closes; the two accounts receive bounded fees. */
2313
+ delegateFeeRecipient?: AddressLike | null;
2314
+ delegateExecutorAccount?: AddressLike | null;
2315
+ /** Delegated settlement; omit these for an owner-signed close. */
2316
+ leverageDelegation?: AddressLike | null;
2317
+ delegatedProgram?: AddressLike | null;
2318
+ authority?: AddressLike;
2319
+ }
2320
+
2321
+ interface YlpLiquidityAccounts {
2322
+ market: AddressLike;
2323
+ owner: AddressLike;
2324
+ baseMint: AddressLike;
2325
+ quoteMint: AddressLike;
2326
+ ylpMint: AddressLike;
2327
+ ownerBaseAccount: AddressLike;
2328
+ ownerQuoteAccount: AddressLike;
2329
+ ownerYlpAccount: AddressLike;
2330
+ baseReserveVault?: AddressLike;
2331
+ quoteReserveVault?: AddressLike;
2332
+ baseYieldAccount?: AddressLike;
2333
+ quoteYieldAccount?: AddressLike;
2334
+ remainingAccounts?: AccountMeta[];
2335
+ }
2336
+
2337
+ /** Which side of the market a leverage position borrows. */
2338
+ export type LeverageDebtAsset = "base" | "quote";
2339
+
2340
+ /** Opening leverage funded in the debt asset; margin plus borrowing buys collateral. */
2341
+ export interface OpenLeverageParams {
2342
+ market: AddressLike;
2343
+ owner: AddressLike;
2344
+ positionId: AddressLike;
2345
+ debtAsset: LeverageDebtAsset;
2346
+ debtMint: AddressLike;
2347
+ collateralMint: AddressLike;
2348
+ marginAmount: RawAmount;
2349
+ /** Leverage multiplier in basis points; 20000 is two times. */
2350
+ multiplierBps: RawAmount;
2351
+ minCollateralOut: RawAmount;
2352
+ /** Zero means no limit price. */
2353
+ limitPriceNad?: RawAmount;
2354
+ payer?: AddressLike;
2355
+ ownerDebtAccount?: AddressLike;
2356
+ leveragePosition?: AddressLike;
2357
+ debtReserveVault?: AddressLike;
2358
+ collateralReserveVault?: AddressLike;
2359
+ leverageCollateralVault?: AddressLike;
2360
+ remainingAccounts?: AccountMeta[];
2361
+ }
2362
+
2363
+ /** Authorising a program to act on a leverage position. */
2364
+ export interface CreateLeverageDelegationParams {
2365
+ market: AddressLike;
2366
+ owner: AddressLike;
2367
+ namespaceAuthority?: AddressLike;
2368
+ positionId: AddressLike;
2369
+ debtAsset: LeverageDebtAsset;
2370
+ delegatedProgram: AddressLike;
2371
+ /** Bit flags for the actions the delegate may perform. */
2372
+ approvedActions: number;
2373
+ leveragePosition?: AddressLike;
2374
+ leverageDelegation?: AddressLike;
2375
+ remainingAccounts?: AccountMeta[];
2376
+ }
2377
+
2378
+ /** A borrow described by its market, position and mints. */
2379
+ export interface BorrowParams {
2380
+ market: AddressLike;
2381
+ owner: AddressLike;
2382
+ /** Position discriminator; the borrow position PDA derives from it. */
2383
+ positionId: AddressLike;
2384
+ debtAssetMint: AddressLike;
2385
+ collateralAssetMint: AddressLike;
2386
+ borrowAmount: RawAmount;
2387
+ /** Slippage floor on the debt actually opened. */
2388
+ minDebtAmountOut: RawAmount;
2389
+ minLiquidationCfBps?: number;
2390
+ ownerDebtAccount?: AddressLike;
2391
+ reserveVault?: AddressLike;
2392
+ borrowPosition?: AddressLike;
2393
+ remainingAccounts?: AccountMeta[];
2394
+ }
2395
+
2396
+ /** A swap described by its market and mints rather than by an account map. */
2397
+ export interface SwapParams {
2398
+ market: AddressLike;
2399
+ trader: AddressLike;
2400
+ assetInMint: AddressLike;
2401
+ assetOutMint: AddressLike;
2402
+ exactAssetIn: RawAmount;
2403
+ /** Slippage floor; the program rejects a fill below it. */
2404
+ minAssetOut: RawAmount;
2405
+ traderAssetInAccount?: AddressLike;
2406
+ traderAssetOutAccount?: AddressLike;
2407
+ reserveInVault?: AddressLike;
2408
+ reserveOutVault?: AddressLike;
2409
+ remainingAccounts?: AccountMeta[];
2410
+ }
2411
+
2412
+ export interface AddLiquidityParams extends YlpLiquidityAccounts {
2413
+ /** Maximum gross spend. Guided first deposits pair at the current validated
2414
+ * oracle price; unused amounts remain with the owner. Native seeding uses
2415
+ * both amounts to establish the initial ratio. */
2416
+ baseDepositAmount: RawAmount;
2417
+ quoteDepositAmount: RawAmount;
2418
+ /** Slippage floor on minted yLP shares. */
2419
+ minYlpAmount: RawAmount;
2420
+ }
2421
+
2422
+ export interface RemoveLiquidityParams extends YlpLiquidityAccounts {
2423
+ ylpAmount: RawAmount;
2424
+ minBaseAmountOut: RawAmount;
2425
+ minQuoteAmountOut: RawAmount;
2426
+ }
2427
+
2428
+ /**
2429
+ * Widen a launch config into the shape Anchor expects: every `u64` as a BN,
2430
+ * every `u16` left as a number. Written out field by field rather than mapped,
2431
+ * so a field added to the program fails to compile here instead of silently
2432
+ * going missing.
2433
+ */
2434
+ function anchorMarketConfig(config: MarketLaunchConfig): Record<string, unknown> {
2435
+ const bn = (value: GovernanceIntegerLike, label: string) => governanceIntegerBN(value, label);
2436
+ return {
2437
+ swapFeeBps: config.swapFeeBps,
2438
+ divergenceFeeShareCapBps: config.divergenceFeeShareCapBps,
2439
+ volatilityFeeShareCapBps: config.volatilityFeeShareCapBps,
2440
+ targetHlpLeverageBps: config.targetHlpLeverageBps,
2441
+ settlementDivergenceBps: config.settlementDivergenceBps,
2442
+ emaHalfLifeMs: bn(config.emaHalfLifeMs, "emaHalfLifeMs"),
2443
+ directionalEmaHalfLifeMs: bn(
2444
+ config.directionalEmaHalfLifeMs,
2445
+ "directionalEmaHalfLifeMs"
2446
+ ),
2447
+ curveDepthEmaHalfLifeMs: bn(config.curveDepthEmaHalfLifeMs, "curveDepthEmaHalfLifeMs"),
2448
+ maxDailyBorrowBps: config.maxDailyBorrowBps,
2449
+ globalHealthContributionCapBps: config.globalHealthContributionCapBps,
2450
+ borrowMarketHealthFloorBps: config.borrowMarketHealthFloorBps,
2451
+ amm: anchorIntegerFields(config.amm, AMM_U64_FIELDS),
2452
+ irm: anchorIntegerFields(config.irm, IRM_U64_FIELDS),
2453
+ startTime: bn(config.startTime, "startTime"),
2454
+ };
2455
+ }
2456
+
2457
+ const AMM_U64_FIELDS = [
2458
+ "peakAmplificationNad",
2459
+ "centerEmaHalfLifeMs",
2460
+ "volatilityHalfLifeMs",
2461
+ "adjustmentThresholdNad",
2462
+ "adjustmentStepNad",
2463
+ "minAdjustmentIntervalSlots",
2464
+ "volatilityShockCapNad",
2465
+ "volatilityCapNad",
2466
+ "divergenceFeeCoefficientNad",
2467
+ "volatilityFeeCoefficientNad",
2468
+ "launchFeeDurationSeconds",
2469
+ "launchRateLimitReferenceNad",
2470
+ "launchRateLimitDurationSeconds",
2471
+ ] as const;
2472
+
2473
+ const IRM_U64_FIELDS = ["lowerSignalNad", "upperSignalNad", "halfLifeMs", "initialAprNad", "minimumAprNad", "maximumAprNad"] as const;
2474
+
2475
+ function anchorIntegerFields(
2476
+ source: Record<string, unknown>,
2477
+ wide: readonly string[]
2478
+ ): Record<string, unknown> {
2479
+ const out: Record<string, unknown> = { ...source };
2480
+ for (const field of wide) {
2481
+ if (out[field] === undefined) continue;
2482
+ out[field] = governanceIntegerBN(out[field] as GovernanceIntegerLike, field);
240
2483
  }
2484
+ return out;
241
2485
  }
242
2486
 
243
2487
  function normalizeArgs(args: DuskInstructionArgs): unknown[] {
@@ -247,6 +2491,24 @@ function normalizeArgs(args: DuskInstructionArgs): unknown[] {
247
2491
  return Array.isArray(args) ? args : [args];
248
2492
  }
249
2493
 
2494
+ function proposalDigestBytes(digest: Uint8Array | readonly number[]): number[] {
2495
+ const bytes = Array.from(digest);
2496
+ if (bytes.length !== 32 || bytes.some((byte) => !Number.isInteger(byte) || byte < 0 || byte > 255)) {
2497
+ throw new Error("proposal digest must be 32 bytes");
2498
+ }
2499
+ return bytes;
2500
+ }
2501
+
2502
+ function cloneProposalMetadata(metadata: ProposalMetadataV1): ProposalMetadataV1 {
2503
+ return {
2504
+ version: metadata.version,
2505
+ title: metadata.title,
2506
+ descriptionUri: metadata.descriptionUri,
2507
+ descriptionSha256: [...metadata.descriptionSha256],
2508
+ descriptionLen: metadata.descriptionLen,
2509
+ };
2510
+ }
2511
+
250
2512
  function mergeAccountMetas(...groups: readonly AccountMeta[][]): AccountMeta[] {
251
2513
  const merged = new Map<string, AccountMeta>();
252
2514
  for (const group of groups) {
@@ -262,3 +2524,68 @@ function mergeAccountMetas(...groups: readonly AccountMeta[][]): AccountMeta[] {
262
2524
  }
263
2525
  return [...merged.values()];
264
2526
  }
2527
+
2528
+ export interface WithdrawAllCollateralParams extends LendingPositionAccounts {
2529
+ baseMint: AddressLike;
2530
+ quoteMint: AddressLike;
2531
+ ownerBaseAccount: AddressLike;
2532
+ ownerQuoteAccount: AddressLike;
2533
+ minBaseOut: RawAmount;
2534
+ minQuoteOut: RawAmount;
2535
+ }
2536
+
2537
+ export interface WithdrawRepaidLeverageParams {
2538
+ market: AddressLike;
2539
+ owner: AddressLike;
2540
+ namespaceAuthority?: AddressLike;
2541
+ positionId: AddressLike;
2542
+ leveragePosition?: AddressLike;
2543
+ collateralMint: AddressLike;
2544
+ ownerCollateralAccount: AddressLike;
2545
+ minCollateralOut: RawAmount;
2546
+ remainingAccounts?: AccountMeta[];
2547
+ }
2548
+
2549
+ // Kept in step with the on-chain instruction binding boundary.
2550
+ const ORACLE_READ_INSTRUCTIONS = new Set<string>([
2551
+ "addLiquidity",
2552
+ "openLiquidityGates",
2553
+ "removeLiquidity",
2554
+ "fundInterest",
2555
+ "harvest",
2556
+ "swap",
2557
+ "previewHlpFlash",
2558
+ "beginHlpFlash",
2559
+ "settleHlpFlash",
2560
+ "closeInsolventHlp",
2561
+ "beginFlashLiquidation",
2562
+ "previewFlashLiquidation",
2563
+ "previewFlashAmmLiquidation",
2564
+ "emergencyLiquidation",
2565
+ "previewEmergencyLiquidation",
2566
+ "previewLiquidationHealth",
2567
+ "settleFlashLiquidation",
2568
+ "depositCollateral",
2569
+ "withdrawCollateral",
2570
+ "borrow",
2571
+ "repay",
2572
+ "donateCollateral",
2573
+ "openLeverage",
2574
+ "closeLeverage",
2575
+ "delegatedCloseLeverage",
2576
+ "increaseLeverage",
2577
+ "decreaseLeverage",
2578
+ "addLeverageMargin",
2579
+ "repayLeverage",
2580
+ "previewHlpDepositCapacity",
2581
+ "previewMarket",
2582
+ "previewHlpOrderTrigger",
2583
+ "previewAddLiquidity",
2584
+ "previewSwap",
2585
+ "previewBorrowCapacity",
2586
+ "previewBorrowPositionCapacity",
2587
+ "previewBorrowPosition",
2588
+ "depositSingleSided",
2589
+ "withdrawSingleSided",
2590
+ "executeParameterProposal",
2591
+ ]);