@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/dist/write.js CHANGED
@@ -1,13 +1,19 @@
1
- import { getAccount, getMint, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
2
- import { SystemProgram, Transaction } from "@solana/web3.js";
1
+ import { deriveJuniorCohortAddress } from "./constants.js";
2
+ import { oracleComputeBudgetInstructions, oraclePolicy, oracleReadAccounts } from "./oracle.js";
3
+ import { getAssociatedTokenAddressSync, getMint, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, } from "@solana/spl-token";
4
+ import { SystemProgram, SYSVAR_INSTRUCTIONS_PUBKEY, Transaction, } from "@solana/web3.js";
3
5
  import { address, normalizeAccountKeys } from "./address.js";
4
- import { deriveReferralProfileAddress } from "./constants.js";
5
- import { buildReferralVaultSetupInstruction, referralVaultAddresses, resolveTransferHookAccountMetas, } from "./referral.js";
6
+ import { deriveBorrowPositionAddress, deriveEventAuthorityAddress, deriveFutarchyAuthorityAddress, deriveLeverageCollateralVaultAddress, deriveLeverageDelegationAddress, deriveLeveragePositionAddress, deriveMarketAddress, deriveMarketCollateralVaultAddress, deriveMarketInterestVaultAddress, deriveMarketReserveVaultAddress, deriveInsuranceAddress, deriveTokenMetadataAddress, TOKEN_METADATA_PROGRAM_ID, deriveReferralAccrualAddress, deriveParameterProposalAddress, deriveProposalSupportAddress, deriveYieldAccountAddress, deriveYieldTransferHookValidationAddress, deriveHlpCohortAddress, deriveReferralPartnerAddress, } from "./constants.js";
7
+ import { anchorParameterUpdate, assertProposalMetadata, canonicalParameterUpdates, parameterUpdateFromAnchor, governanceIntegerBN, } from "./governance.js";
8
+ import { assertReferralInterestShareBps, referralAccrualAddresses, resolveTransferHookAccountMetas, tokenProgramForMint, } from "./referral.js";
6
9
  export class DuskWrite {
7
10
  program;
8
11
  constructor(program) {
9
12
  this.program = program;
10
13
  }
14
+ fetchMarketAccount(market) {
15
+ return this.program.account.market.fetch(market);
16
+ }
11
17
  method(name, args) {
12
18
  const method = this.program.methods[name];
13
19
  if (!method) {
@@ -17,29 +23,797 @@ export class DuskWrite {
17
23
  }
18
24
  builder(name, args, options = {}) {
19
25
  let builder = this.method(name, args);
20
- if (options.accounts) {
21
- builder = builder.accounts(normalizeAccountKeys(options.accounts));
26
+ const instructionAccounts = this.program.idl.instructions?.find((instruction) => instruction.name === name)?.accounts;
27
+ const usesEventCpi = instructionAccounts?.some((account) => account.name === "eventAuthority") === true &&
28
+ instructionAccounts.some((account) => account.name === "program") === true;
29
+ if (options.accounts || usesEventCpi) {
30
+ const accounts = usesEventCpi
31
+ ? {
32
+ ...options.accounts,
33
+ eventAuthority: deriveEventAuthorityAddress(this.program.programId)[0],
34
+ program: this.program.programId,
35
+ }
36
+ : options.accounts;
37
+ builder = builder.accounts(normalizeAccountKeys(accounts));
22
38
  }
23
- if (options.remainingAccounts?.length) {
24
- builder = builder.remainingAccounts(options.remainingAccounts);
39
+ const remaining = [...(options.remainingAccounts ?? [])];
40
+ for (const meta of oracleReadAccounts(options.oraclePolicy)) {
41
+ if (!remaining.some(existing => existing.pubkey.equals(meta.pubkey)))
42
+ remaining.push(meta);
25
43
  }
44
+ if (remaining.length)
45
+ builder = builder.remainingAccounts(remaining);
46
+ const budgets = oracleComputeBudgetInstructions(options.oraclePolicy);
47
+ if (budgets.length)
48
+ builder = builder.preInstructions(budgets);
26
49
  return builder;
27
50
  }
28
- instruction(name, args, options) {
29
- return this.builder(name, args, options).instruction();
51
+ async instruction(name, args, options) {
52
+ return this.builder(name, args, await this.withOraclePolicy(name, options)).instruction();
53
+ }
54
+ async transaction(name, args, options) {
55
+ return this.builder(name, args, await this.withOraclePolicy(name, options)).transaction();
56
+ }
57
+ async rpc(name, args, options) {
58
+ return this.builder(name, args, await this.withOraclePolicy(name, options)).rpc();
59
+ }
60
+ async withOraclePolicy(name, options = {}) {
61
+ if (!ORACLE_READ_INSTRUCTIONS.has(name) || options.oraclePolicy)
62
+ return options;
63
+ const nested = options.accounts?.accounts;
64
+ const preview = options.accounts?.preview;
65
+ const market = options.accounts?.market ?? nested?.market ?? preview?.market;
66
+ if (!market)
67
+ return options;
68
+ if (name === "executeParameterProposal" && options.accounts?.proposal) {
69
+ const client = this.program.account.parameterProposal;
70
+ const proposal = await client.fetch(address(options.accounts.proposal));
71
+ const update = proposal.updates.map(parameterUpdateFromAnchor).find(update => update.kind === "oracle");
72
+ if (update?.kind === "oracle")
73
+ return { ...options, oraclePolicy: update.policy };
74
+ }
75
+ const state = await this.fetchMarketAccount(address(market));
76
+ return { ...options, oraclePolicy: state.oracle?.policy };
77
+ }
78
+ /**
79
+ * The hLP accounts an instruction must carry when hedged liquidity is live.
80
+ *
81
+ * Swap and openLeverage both require them, and their order is
82
+ * consensus-visible, so both take them from here rather than each assembling
83
+ * its own list.
84
+ */
85
+ /**
86
+ * The hLP settlement prefix an instruction must carry when the market has
87
+ * active hLP.
88
+ *
89
+ * Required by every leverage instruction that settles the market —
90
+ * open, close, increase and decrease — not only by open. Omitting it fails
91
+ * with `NotEnoughAccounts` at the point the program tries to read the
92
+ * prefix, which names neither leverage nor hLP and reads as a malformed
93
+ * call.
94
+ */
95
+ async hlpRemainingAccounts(marketAddress, marketSnapshot) {
96
+ const market = address(marketAddress);
97
+ const state = (marketSnapshot ?? await this.fetchMarketAccount(market));
98
+ const hlpActive = BigInt(state.baseHlpVault.hlpSupply.toString()) !== 0n ||
99
+ BigInt(state.quoteHlpVault.hlpSupply.toString()) !== 0n ||
100
+ BigInt(state.baseHlpVault.residualExposure.toString()) !== 0n ||
101
+ BigInt(state.quoteHlpVault.residualExposure.toString()) !== 0n;
102
+ if (!hlpActive)
103
+ return [];
104
+ return [
105
+ { pubkey: state.ylpMint, isSigner: false, isWritable: true },
106
+ { pubkey: state.baseHlpVault.ylpVault, isSigner: false, isWritable: true },
107
+ { pubkey: state.quoteHlpVault.ylpVault, isSigner: false, isWritable: true },
108
+ { pubkey: state.baseSide.interestVault, isSigner: false, isWritable: true },
109
+ { pubkey: state.quoteSide.interestVault, isSigner: false, isWritable: true },
110
+ // Fresh public-interest settlements rebalance both vaults. These keys
111
+ // usually duplicate fixed swap accounts; repayments need them explicitly.
112
+ { pubkey: state.baseSide.assetMint, isSigner: false, isWritable: false },
113
+ { pubkey: state.quoteSide.assetMint, isSigner: false, isWritable: false },
114
+ { pubkey: state.baseSide.reserveVault, isSigner: false, isWritable: true },
115
+ { pubkey: state.quoteSide.reserveVault, isSigner: false, isWritable: true },
116
+ ];
117
+ }
118
+ async swapBuilder(args, options) {
119
+ const market = address(options.market);
120
+ const state = (await this.fetchMarketAccount(market));
121
+ const hlpActive = BigInt(state.baseHlpVault.hlpSupply.toString()) !== 0n ||
122
+ BigInt(state.quoteHlpVault.hlpSupply.toString()) !== 0n ||
123
+ BigInt(state.baseHlpVault.residualExposure.toString()) !== 0n ||
124
+ BigInt(state.quoteHlpVault.residualExposure.toString()) !== 0n;
125
+ const prefix = hlpActive
126
+ ? [
127
+ { pubkey: state.ylpMint, isSigner: false, isWritable: true },
128
+ { pubkey: state.baseHlpVault.ylpVault, isSigner: false, isWritable: true },
129
+ { pubkey: state.quoteHlpVault.ylpVault, isSigner: false, isWritable: true },
130
+ { pubkey: state.baseSide.interestVault, isSigner: false, isWritable: true },
131
+ { pubkey: state.quoteSide.interestVault, isSigner: false, isWritable: true },
132
+ ]
133
+ : [];
134
+ return this.builder("swap", args, {
135
+ oraclePolicy: options.oraclePolicy ?? state.oracle?.policy,
136
+ accounts: {
137
+ ...options.accounts,
138
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
139
+ },
140
+ // Prefix order is consensus-visible. Hook accounts must remain a tail,
141
+ // including any deliberate duplicate pubkeys required by a hook meta list.
142
+ remainingAccounts: [...prefix, ...(options.remainingAccounts ?? [])],
143
+ });
144
+ }
145
+ async swapInstruction(args, options) {
146
+ return (await this.swapBuilder(args, options)).instruction();
147
+ }
148
+ async swapTransaction(args, options) {
149
+ return (await this.swapBuilder(args, options)).transaction();
150
+ }
151
+ async swapRpc(args, options) {
152
+ return (await this.swapBuilder(args, options)).rpc();
153
+ }
154
+ /**
155
+ * Swap, with accounts resolved from the market and the two mints.
156
+ *
157
+ * `swapInstruction` takes a prepared account map, which makes callers
158
+ * responsible for reconstructing the program's account set. This resolves it
159
+ * instead: reserve vaults derive from the market and mint, trader accounts
160
+ * default to the associated token account for the correct token program, and
161
+ * the hLP remaining-account prefix is still assembled by `swapBuilder`,
162
+ * whose ordering is consensus-visible.
163
+ */
164
+ async buildSwapInstruction(params) {
165
+ return (await this.buildSwapBuilder(params)).instruction();
166
+ }
167
+ async buildSwapTransaction(params) {
168
+ return (await this.buildSwapBuilder(params)).transaction();
169
+ }
170
+ /**
171
+ * Borrow against a position, with accounts resolved from the market and the
172
+ * two mints.
173
+ *
174
+ * The referral accounts are optional on chain and are omitted here: a borrow
175
+ * with no referrer should not have to name accounts it does not use. Use
176
+ * `referredBorrow` when a referrer is present.
177
+ */
178
+ async buildBorrowInstruction(params) {
179
+ const market = address(params.market);
180
+ const owner = address(params.owner);
181
+ const debtAssetMint = address(params.debtAssetMint);
182
+ const collateralAssetMint = address(params.collateralAssetMint);
183
+ if (debtAssetMint.equals(collateralAssetMint)) {
184
+ throw new Error("Borrow debt and collateral mints must differ");
185
+ }
186
+ const debtTokenProgram = await tokenProgramForMint(this.program.provider.connection, debtAssetMint);
187
+ return this.instruction("borrow", {
188
+ borrowAmount: governanceIntegerBN(params.borrowAmount, "borrowAmount"),
189
+ minDebtAmountOut: governanceIntegerBN(params.minDebtAmountOut, "minDebtAmountOut"),
190
+ minLiquidationCfBps: Number(params.minLiquidationCfBps ?? 0),
191
+ referrer: null,
192
+ }, {
193
+ accounts: {
194
+ market,
195
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
196
+ owner,
197
+ debtAssetMint,
198
+ collateralAssetMint,
199
+ reserveVault: address(params.reserveVault ??
200
+ deriveMarketReserveVaultAddress(market, debtAssetMint)[0]),
201
+ ownerDebtAccount: address(params.ownerDebtAccount ??
202
+ getAssociatedTokenAddressSync(debtAssetMint, owner, true, debtTokenProgram)),
203
+ borrowPosition: address(params.borrowPosition ??
204
+ deriveBorrowPositionAddress(market, owner, address(params.positionId))[0]),
205
+ referralPartner: null,
206
+ referralAccrual: null,
207
+ tokenProgram: TOKEN_PROGRAM_ID,
208
+ token2022Program: TOKEN_2022_PROGRAM_ID,
209
+ },
210
+ remainingAccounts: params.remainingAccounts,
211
+ });
212
+ }
213
+ async buildBorrowTransaction(params) {
214
+ const options = await this.withOraclePolicy("borrow", { accounts: { market: address(params.market) } });
215
+ return new Transaction().add(...oracleComputeBudgetInstructions(options.oraclePolicy), await this.buildBorrowInstruction(params));
216
+ }
217
+ /**
218
+ * Open a leverage position, with accounts resolved from the market, the
219
+ * position id and the two mints.
220
+ *
221
+ * Referral accounts are optional on chain and omitted here; use
222
+ * `referredOpenLeverage` when a referrer is present.
223
+ */
224
+ async buildOpenLeverageInstruction(params) {
225
+ const market = address(params.market);
226
+ const owner = address(params.owner);
227
+ const debtMint = address(params.debtMint);
228
+ const collateralMint = address(params.collateralMint);
229
+ if (debtMint.equals(collateralMint)) {
230
+ throw new Error("Leverage debt and collateral mints must differ");
231
+ }
232
+ if ("fundingAsset" in params && params.fundingAsset !== undefined && params.fundingAsset !== "debt")
233
+ throw new Error("Leverage funding must use the debt asset; swap other tokens before opening");
234
+ const positionId = address(params.positionId);
235
+ const debtTokenProgram = await tokenProgramForMint(this.program.provider.connection, debtMint);
236
+ const openArgs = {
237
+ positionId,
238
+ debtAsset: params.debtAsset === "quote" ? 1 : 0,
239
+ marginAmount: governanceIntegerBN(params.marginAmount, "marginAmount"),
240
+ multiplierBps: governanceIntegerBN(params.multiplierBps, "multiplierBps"),
241
+ minCollateralOut: governanceIntegerBN(params.minCollateralOut, "minCollateralOut"),
242
+ referrer: null,
243
+ positionOwner: null,
244
+ limitPriceNad: governanceIntegerBN(params.limitPriceNad ?? 0, "limitPriceNad"),
245
+ };
246
+ return this.instruction("openLeverage", openArgs, {
247
+ accounts: {
248
+ market,
249
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
250
+ owner,
251
+ payer: address(params.payer ?? owner),
252
+ leveragePosition: address(params.leveragePosition ??
253
+ deriveLeveragePositionAddress(market, owner, positionId)[0]),
254
+ debtMint,
255
+ collateralMint,
256
+ debtReserveVault: address(params.debtReserveVault ??
257
+ deriveMarketReserveVaultAddress(market, debtMint)[0]),
258
+ collateralReserveVault: address(params.collateralReserveVault ??
259
+ deriveMarketReserveVaultAddress(market, collateralMint)[0]),
260
+ leverageCollateralVault: address(params.leverageCollateralVault ??
261
+ deriveLeverageCollateralVaultAddress(market, collateralMint)[0]),
262
+ ownerDebtAccount: address(params.ownerDebtAccount ??
263
+ getAssociatedTokenAddressSync(debtMint, owner, true, debtTokenProgram)),
264
+ referralPartner: null,
265
+ referralAccrual: null,
266
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
267
+ tokenProgram: TOKEN_PROGRAM_ID,
268
+ token2022Program: TOKEN_2022_PROGRAM_ID,
269
+ systemProgram: SystemProgram.programId,
270
+ },
271
+ remainingAccounts: [
272
+ ...(await this.hlpRemainingAccounts(market)),
273
+ ...(params.remainingAccounts ?? []),
274
+ ],
275
+ });
276
+ }
277
+ async buildOpenLeverageTransaction(params) {
278
+ const options = await this.withOraclePolicy("openLeverage", { accounts: { market: address(params.market) } });
279
+ return new Transaction().add(...oracleComputeBudgetInstructions(options.oraclePolicy), await this.buildOpenLeverageInstruction(params));
280
+ }
281
+ /**
282
+ * Delegate a leverage position to a program that may act on it, which is how
283
+ * conditional orders (take-profit, stop-loss) are authorised.
284
+ */
285
+ async buildCreateLeverageDelegationInstruction(params) {
286
+ const market = address(params.market);
287
+ const leveragePosition = address(params.leveragePosition ??
288
+ deriveLeveragePositionAddress(market, address(params.owner), address(params.positionId), address(params.namespaceAuthority ?? params.owner))[0]);
289
+ return this.instruction("createLeverageDelegation", {
290
+ debtAsset: params.debtAsset === "quote" ? 1 : 0,
291
+ delegatedProgram: address(params.delegatedProgram),
292
+ approvedActions: Number(params.approvedActions),
293
+ }, {
294
+ accounts: {
295
+ market,
296
+ leveragePosition,
297
+ leverageDelegation: address(params.leverageDelegation ??
298
+ deriveLeverageDelegationAddress(leveragePosition)[0]),
299
+ owner: address(params.owner),
300
+ systemProgram: SystemProgram.programId,
301
+ },
302
+ remainingAccounts: params.remainingAccounts,
303
+ });
304
+ }
305
+ async buildCreateLeverageDelegationTransaction(params) {
306
+ return new Transaction().add(await this.buildCreateLeverageDelegationInstruction(params));
307
+ }
308
+ async buildSwapBuilder(params) {
309
+ const market = address(params.market);
310
+ const trader = address(params.trader);
311
+ const assetInMint = address(params.assetInMint);
312
+ const assetOutMint = address(params.assetOutMint);
313
+ if (assetInMint.equals(assetOutMint)) {
314
+ throw new Error("Swap input and output mints must differ");
315
+ }
316
+ const connection = this.program.provider.connection;
317
+ const [assetInProgram, assetOutProgram] = await Promise.all([
318
+ tokenProgramForMint(connection, assetInMint),
319
+ tokenProgramForMint(connection, assetOutMint),
320
+ ]);
321
+ return this.swapBuilder(
322
+ // A single positional SwapArgs struct: the generic builder spreads a
323
+ // non-array into one argument, so wrapping it in an outer object would
324
+ // serialize a struct of zeros and the program would reject the amount.
325
+ {
326
+ exactAssetIn: governanceIntegerBN(params.exactAssetIn, "exactAssetIn"),
327
+ minAssetOut: governanceIntegerBN(params.minAssetOut, "minAssetOut"),
328
+ }, {
329
+ market,
330
+ accounts: {
331
+ market,
332
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
333
+ trader,
334
+ assetInMint,
335
+ assetOutMint,
336
+ reserveInVault: address(params.reserveInVault ??
337
+ deriveMarketReserveVaultAddress(market, assetInMint)[0]),
338
+ reserveOutVault: address(params.reserveOutVault ??
339
+ deriveMarketReserveVaultAddress(market, assetOutMint)[0]),
340
+ traderAssetInAccount: address(params.traderAssetInAccount ??
341
+ getAssociatedTokenAddressSync(assetInMint, trader, true, assetInProgram)),
342
+ traderAssetOutAccount: address(params.traderAssetOutAccount ??
343
+ getAssociatedTokenAddressSync(assetOutMint, trader, true, assetOutProgram)),
344
+ tokenProgram: TOKEN_PROGRAM_ID,
345
+ token2022Program: TOKEN_2022_PROGRAM_ID,
346
+ },
347
+ remainingAccounts: params.remainingAccounts,
348
+ });
349
+ }
350
+ async initializeYieldAccountsInstruction(params) {
351
+ const payer = address(params.payer);
352
+ const owner = address(params.owner);
353
+ const market = address(params.market);
354
+ const lpMint = address(params.lpMint);
355
+ const baseMint = address(params.baseMint);
356
+ const quoteMint = address(params.quoteMint);
357
+ const tokenKind = params.tokenKind === "ylp" || params.tokenKind === 0 ? { ylp: {} } : params.tokenKind === "junior" || params.tokenKind === 2 ? { junior: {} } : { hlp: {} };
358
+ return this.instruction("initializeYieldAccounts", { owner, tokenKind }, {
359
+ accounts: {
360
+ payer,
361
+ market,
362
+ lpMint,
363
+ baseMint,
364
+ quoteMint,
365
+ baseYieldAccount: deriveYieldAccountAddress(market, owner, lpMint, baseMint, params.tokenKind, this.program.programId)[0],
366
+ quoteYieldAccount: deriveYieldAccountAddress(market, owner, lpMint, quoteMint, params.tokenKind, this.program.programId)[0],
367
+ systemProgram: SystemProgram.programId,
368
+ },
369
+ remainingAccounts: params.retired
370
+ ? [{ pubkey: (params.tokenKind === "junior" || params.tokenKind === 2 ? deriveJuniorCohortAddress : deriveHlpCohortAddress)(market, lpMint, this.program.programId)[0], isSigner: false, isWritable: false }]
371
+ : [],
372
+ });
373
+ }
374
+ async initializeYieldAccountsTransaction(params) {
375
+ return new Transaction().add(await this.initializeYieldAccountsInstruction(params));
376
+ }
377
+ async initializeLpTransferHookInstruction(params) {
378
+ const lpMint = address(params.lpMint);
379
+ const market = address(params.market);
380
+ let tokenKind = params.tokenKind;
381
+ if (tokenKind === undefined) {
382
+ const state = await this.fetchMarketAccount(market);
383
+ if (lpMint.equals(state.ylpMint))
384
+ tokenKind = "ylp";
385
+ else if (lpMint.equals(state.juniorMint))
386
+ tokenKind = "junior";
387
+ else if (lpMint.equals(state.baseSide.hlpMint) || lpMint.equals(state.quoteSide.hlpMint))
388
+ tokenKind = "hlp";
389
+ else
390
+ throw new Error("LP mint does not belong to the market");
391
+ }
392
+ const isHlp = tokenKind === "hlp" || tokenKind === 1;
393
+ return this.instruction("initializeLpTransferHook", undefined, {
394
+ accounts: {
395
+ payer: address(params.payer),
396
+ market,
397
+ lpMint,
398
+ validationAccount: deriveYieldTransferHookValidationAddress(lpMint, this.program.programId)[0],
399
+ systemProgram: SystemProgram.programId,
400
+ },
401
+ remainingAccounts: isHlp
402
+ ? [{ pubkey: deriveHlpCohortAddress(market, lpMint, this.program.programId)[0], isSigner: false, isWritable: true }]
403
+ : [],
404
+ });
405
+ }
406
+ async initializeLpTransferHookTransaction(params) {
407
+ return new Transaction().add(await this.initializeLpTransferHookInstruction(params));
408
+ }
409
+ /**
410
+ * Bring a market into existence.
411
+ *
412
+ * The three LP mints must already exist and carry the Dusk transfer hook —
413
+ * see `createHookedLpMintInstructions`. Every PDA is derived here rather
414
+ * than left to Anchor, because the market address depends on `paramsHash`,
415
+ * which is an argument rather than an account, and the vaults hang off the
416
+ * market in turn.
417
+ *
418
+ * `teamTreasury` and its wrapped-SOL account come from the futarchy
419
+ * authority, which must already be initialized on the deployment.
420
+ */
421
+ async initializeMarketInstruction(params) {
422
+ const baseMint = address(params.baseMint);
423
+ const quoteMint = address(params.quoteMint);
424
+ const paramsHash = Uint8Array.from(params.paramsHash);
425
+ if (paramsHash.length !== 32) {
426
+ throw new Error(`paramsHash must be 32 bytes, received ${paramsHash.length}`);
427
+ }
428
+ const [market] = deriveMarketAddress(baseMint, quoteMint, paramsHash);
429
+ const oracle = params.oracle == null ? null : oraclePolicy(params.oracle);
430
+ const bootstrapPriceNad = governanceIntegerBN(params.bootstrapPriceNad ?? 0, "bootstrapPriceNad");
431
+ if (oracle && oracle.lambdaBps > 0 && !bootstrapPriceNad.isZero())
432
+ throw new Error("Oracle-guided markets derive the initial price from the feed; omit bootstrapPriceNad");
433
+ return this.instruction("initializeMarket", {
434
+ config: anchorMarketConfig(params.config),
435
+ oracle,
436
+ paramsHash: [...paramsHash],
437
+ bootstrapPriceNad,
438
+ launchFeeProgressOffset: params.launchFeeProgressOffset ?? 0,
439
+ ylpMetadata: params.lpMetadata.ylp,
440
+ baseHlpMetadata: params.lpMetadata.baseHlp,
441
+ quoteHlpMetadata: params.lpMetadata.quoteHlp,
442
+ }, {
443
+ accounts: {
444
+ payer: address(params.payer),
445
+ baseMint,
446
+ quoteMint,
447
+ ylpMint: address(params.ylpMint),
448
+ baseHlpMint: address(params.baseHlpMint),
449
+ quoteHlpMint: address(params.quoteHlpMint),
450
+ ylpTokenMetadata: deriveTokenMetadataAddress(address(params.ylpMint))[0],
451
+ baseHlpTokenMetadata: deriveTokenMetadataAddress(address(params.baseHlpMint))[0],
452
+ quoteHlpTokenMetadata: deriveTokenMetadataAddress(address(params.quoteHlpMint))[0],
453
+ market,
454
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
455
+ baseReserveVault: deriveMarketReserveVaultAddress(market, baseMint)[0],
456
+ quoteReserveVault: deriveMarketReserveVaultAddress(market, quoteMint)[0],
457
+ baseCollateralVault: deriveMarketCollateralVaultAddress(market, baseMint)[0],
458
+ quoteCollateralVault: deriveMarketCollateralVaultAddress(market, quoteMint)[0],
459
+ baseInsuranceVault: deriveInsuranceAddress(market, baseMint)[0],
460
+ quoteInsuranceVault: deriveInsuranceAddress(market, quoteMint)[0],
461
+ baseInterestVault: deriveMarketInterestVaultAddress(market, baseMint)[0],
462
+ quoteInterestVault: deriveMarketInterestVaultAddress(market, quoteMint)[0],
463
+ teamTreasury: address(params.teamTreasury),
464
+ teamTreasuryWsolAccount: address(params.teamTreasuryWsolAccount),
465
+ systemProgram: SystemProgram.programId,
466
+ tokenProgram: TOKEN_PROGRAM_ID,
467
+ token2022Program: TOKEN_2022_PROGRAM_ID,
468
+ sysvarInstructions: SYSVAR_INSTRUCTIONS_PUBKEY,
469
+ tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
470
+ },
471
+ });
472
+ }
473
+ async initializeMarketTransaction(params) {
474
+ return new Transaction().add(await this.initializeMarketInstruction(params));
475
+ }
476
+ /**
477
+ * Donate to a market's insurance vault without receiving an LP claim.
478
+ * Does not fetch the market, so it can follow initialization in the same
479
+ * transaction. The program validates the selected side, mint and donor account.
480
+ */
481
+ async fortifyMarketInstruction(params) {
482
+ if (params.asset !== "base" && params.asset !== "quote") {
483
+ throw new Error('asset must be "base" or "quote"');
484
+ }
485
+ const amount = governanceIntegerBN(params.amount, "amount");
486
+ if (amount.isZero())
487
+ throw new Error("amount must be positive");
488
+ const donor = address(params.donor);
489
+ const market = address(params.market);
490
+ const assetMint = address(params.assetMint);
491
+ const assetTokenProgram = params.assetTokenProgram
492
+ ? address(params.assetTokenProgram)
493
+ : await tokenProgramForMint(this.program.provider.connection, assetMint);
494
+ if (!assetTokenProgram.equals(TOKEN_PROGRAM_ID) && !assetTokenProgram.equals(TOKEN_2022_PROGRAM_ID)) {
495
+ throw new Error("assetTokenProgram must be SPL Token or Token-2022");
496
+ }
497
+ const donorAssetAccount = params.donorAssetAccount
498
+ ? address(params.donorAssetAccount)
499
+ : getAssociatedTokenAddressSync(assetMint, donor, true, assetTokenProgram);
500
+ return this.instruction("fortifyMarket", { asset: params.asset === "base" ? 0 : 1, amount }, {
501
+ accounts: {
502
+ market,
503
+ donor,
504
+ assetMint,
505
+ donorAssetAccount,
506
+ insuranceVault: deriveInsuranceAddress(market, assetMint, this.program.programId)[0],
507
+ tokenProgram: TOKEN_PROGRAM_ID,
508
+ token2022Program: TOKEN_2022_PROGRAM_ID,
509
+ },
510
+ });
511
+ }
512
+ async fortifyMarketTransaction(params) {
513
+ return new Transaction().add(await this.fortifyMarketInstruction(params));
514
+ }
515
+ /** Burn-lock initial direct-yLP support and create one immutable proposal over one or more families. */
516
+ async createParameterProposal(params) {
517
+ assertProposalMetadata(params.metadata);
518
+ const proposer = address(params.proposer);
519
+ const market = address(params.market);
520
+ const state = await this.governanceMarketState(market);
521
+ const ylpMint = address(params.ylpMint ?? state.ylpMint);
522
+ const [proposal] = deriveParameterProposalAddress(market, proposer, params.nonce, this.program.programId);
523
+ const [proposalSupport] = deriveProposalSupportAddress(proposal, proposer, this.program.programId);
524
+ const proposerYlpAccount = address(params.holderYlpAccount ??
525
+ getAssociatedTokenAddressSync(ylpMint, proposer, true, TOKEN_2022_PROGRAM_ID));
526
+ const instruction = await this.instruction("createParameterProposal", {
527
+ nonce: governanceIntegerBN(params.nonce, "nonce"),
528
+ updates: canonicalParameterUpdates(params.updates).map(anchorParameterUpdate),
529
+ metadata: cloneProposalMetadata(params.metadata),
530
+ initialSupport: governanceIntegerBN(params.initialSupport, "initialSupport"),
531
+ }, {
532
+ accounts: {
533
+ proposer,
534
+ market,
535
+ proposal,
536
+ proposalSupport,
537
+ ylpMint,
538
+ proposerYlpAccount,
539
+ baseYieldAccount: address(params.baseYieldAccount ??
540
+ deriveYieldAccountAddress(market, proposer, ylpMint, state.baseSide.assetMint, "ylp", this.program.programId)[0]),
541
+ quoteYieldAccount: address(params.quoteYieldAccount ??
542
+ deriveYieldAccountAddress(market, proposer, ylpMint, state.quoteSide.assetMint, "ylp", this.program.programId)[0]),
543
+ baseHlpYlpVault: address(params.baseHlpYlpVault ?? state.baseHlpVault.ylpVault),
544
+ quoteHlpYlpVault: address(params.quoteHlpYlpVault ?? state.quoteHlpVault.ylpVault),
545
+ token2022Program: TOKEN_2022_PROGRAM_ID,
546
+ systemProgram: SystemProgram.programId,
547
+ },
548
+ });
549
+ return {
550
+ proposal,
551
+ proposalSupport,
552
+ instruction,
553
+ transaction: new Transaction().add(instruction),
554
+ };
555
+ }
556
+ /** Add burn-locked direct-yLP support; crossing strict majority queues atomically. */
557
+ async supportParameterProposal(params) {
558
+ const supporter = address(params.supporter);
559
+ const market = address(params.market);
560
+ const proposal = address(params.proposal);
561
+ const state = await this.governanceMarketState(market);
562
+ const ylpMint = address(params.ylpMint ?? state.ylpMint);
563
+ const [proposalSupport] = deriveProposalSupportAddress(proposal, supporter, this.program.programId);
564
+ const supporterYlpAccount = address(params.holderYlpAccount ??
565
+ getAssociatedTokenAddressSync(ylpMint, supporter, true, TOKEN_2022_PROGRAM_ID));
566
+ const instruction = await this.instruction("supportParameterProposal", { amount: governanceIntegerBN(params.amount, "amount"), digest: proposalDigestBytes(params.digest) }, {
567
+ accounts: {
568
+ supporter,
569
+ market,
570
+ proposal,
571
+ proposalSupport,
572
+ ylpMint,
573
+ supporterYlpAccount,
574
+ baseYieldAccount: address(params.baseYieldAccount ??
575
+ deriveYieldAccountAddress(market, supporter, ylpMint, state.baseSide.assetMint, "ylp", this.program.programId)[0]),
576
+ quoteYieldAccount: address(params.quoteYieldAccount ??
577
+ deriveYieldAccountAddress(market, supporter, ylpMint, state.quoteSide.assetMint, "ylp", this.program.programId)[0]),
578
+ baseHlpYlpVault: address(params.baseHlpYlpVault ?? state.baseHlpVault.ylpVault),
579
+ quoteHlpYlpVault: address(params.quoteHlpYlpVault ?? state.quoteHlpVault.ylpVault),
580
+ token2022Program: TOKEN_2022_PROGRAM_ID,
581
+ systemProgram: SystemProgram.programId,
582
+ },
583
+ });
584
+ return {
585
+ proposal,
586
+ proposalSupport,
587
+ instruction,
588
+ transaction: new Transaction().add(instruction),
589
+ };
590
+ }
591
+ /** Permissionlessly queue after the denominator falls below already-locked support. */
592
+ async queueParameterProposal(params) {
593
+ const market = address(params.market);
594
+ const proposal = address(params.proposal);
595
+ const state = await this.governanceMarketState(market);
596
+ const instruction = await this.instruction("queueParameterProposal", undefined, {
597
+ accounts: {
598
+ market,
599
+ proposal,
600
+ ylpMint: address(params.ylpMint ?? state.ylpMint),
601
+ baseHlpYlpVault: address(params.baseHlpYlpVault ?? state.baseHlpVault.ylpVault),
602
+ quoteHlpYlpVault: address(params.quoteHlpYlpVault ?? state.quoteHlpVault.ylpVault),
603
+ },
604
+ });
605
+ return { proposal, instruction, transaction: new Transaction().add(instruction) };
606
+ }
607
+ /** Execute inside the 7-day window. Standalone oracle policies can restore
608
+ * pricing during distress; other updates retain utilization/health guards. */
609
+ async executeParameterProposal(params) {
610
+ const market = address(params.market);
611
+ const proposal = address(params.proposal);
612
+ const state = await this.governanceMarketState(market);
613
+ const options = await this.withOraclePolicy("executeParameterProposal", {
614
+ accounts: {
615
+ market,
616
+ baseMint: address(state.baseSide.assetMint),
617
+ quoteMint: address(state.quoteSide.assetMint),
618
+ proposal,
619
+ },
620
+ });
621
+ const instruction = await this.instruction("executeParameterProposal", undefined, options);
622
+ const budgetPolicy = options.oraclePolicy?.lambdaBps
623
+ ? options.oraclePolicy : state.oracle?.policy;
624
+ return { proposal, instruction, transaction: new Transaction().add(...oracleComputeBudgetInstructions(budgetPolicy), instruction) };
625
+ }
626
+ /** Release all or part of direct support and credit earned yield to its owner. */
627
+ async withdrawParameterSupport(params) {
628
+ const supporter = address(params.supporter);
629
+ const market = address(params.market);
630
+ const proposal = address(params.proposal);
631
+ const state = await this.governanceMarketState(market);
632
+ const ylpMint = address(params.ylpMint ?? state.ylpMint);
633
+ const [proposalSupport] = deriveProposalSupportAddress(proposal, supporter, this.program.programId);
634
+ const supporterYlpAccount = address(params.supporterYlpAccount ??
635
+ getAssociatedTokenAddressSync(ylpMint, supporter, true, TOKEN_2022_PROGRAM_ID));
636
+ const instruction = await this.instruction("withdrawParameterSupport", { amount: params.amount === undefined ? null : governanceIntegerBN(params.amount, "amount") }, {
637
+ accounts: {
638
+ supporter,
639
+ market,
640
+ proposal,
641
+ proposer: address(params.proposer),
642
+ proposalSupport,
643
+ ylpMint,
644
+ supporterYlpAccount,
645
+ baseYieldAccount: address(params.baseYieldAccount ??
646
+ deriveYieldAccountAddress(market, supporter, ylpMint, state.baseSide.assetMint, "ylp", this.program.programId)[0]),
647
+ quoteYieldAccount: address(params.quoteYieldAccount ??
648
+ deriveYieldAccountAddress(market, supporter, ylpMint, state.quoteSide.assetMint, "ylp", this.program.programId)[0]),
649
+ token2022Program: TOKEN_2022_PROGRAM_ID,
650
+ },
651
+ });
652
+ return {
653
+ proposal,
654
+ proposalSupport,
655
+ instruction,
656
+ transaction: new Transaction().add(instruction),
657
+ };
658
+ }
659
+ async governanceMarketState(market) {
660
+ return (await this.fetchMarketAccount(market));
661
+ }
662
+ async hlpLiquidityAction(name, args, options) {
663
+ const payer = address(options.payer);
664
+ const owner = address(options.owner);
665
+ const market = address(options.market);
666
+ const lpMint = address(options.targetHlpMint);
667
+ const baseMint = address(options.baseMint);
668
+ const quoteMint = address(options.quoteMint);
669
+ const baseYieldAccount = deriveYieldAccountAddress(market, owner, lpMint, baseMint, "hlp", this.program.programId)[0];
670
+ const quoteYieldAccount = deriveYieldAccountAddress(market, owner, lpMint, quoteMint, "hlp", this.program.programId)[0];
671
+ const [baseYieldInfo, quoteYieldInfo] = await Promise.all([
672
+ this.program.provider.connection.getAccountInfo(baseYieldAccount),
673
+ this.program.provider.connection.getAccountInfo(quoteYieldAccount),
674
+ ]);
675
+ const yieldAccountDefinition = this.program.idl.accounts?.find((account) => account.name === "yieldAccount");
676
+ if (!yieldAccountDefinition) {
677
+ throw new Error("Dusk IDL is missing YieldAccount");
678
+ }
679
+ const yieldAccountSize = this.program.coder.accounts.size("yieldAccount");
680
+ const yieldAccountDiscriminator = Buffer.from(yieldAccountDefinition.discriminator);
681
+ const yieldAccountsReady = [baseYieldInfo, quoteYieldInfo].every((info) => info !== null &&
682
+ info.owner.equals(this.program.programId) &&
683
+ info.data.length === yieldAccountSize &&
684
+ info.data.subarray(0, yieldAccountDiscriminator.length).equals(yieldAccountDiscriminator));
685
+ const setupInstructions = yieldAccountsReady
686
+ ? []
687
+ : [
688
+ await this.initializeYieldAccountsInstruction({
689
+ payer,
690
+ owner,
691
+ market,
692
+ lpMint,
693
+ baseMint,
694
+ quoteMint,
695
+ tokenKind: "hlp",
696
+ }),
697
+ ];
698
+ const actionInstruction = await this.instruction(name, args, {
699
+ accounts: {
700
+ ...options.accounts,
701
+ market,
702
+ owner,
703
+ targetHlpMint: lpMint,
704
+ baseMint,
705
+ quoteMint,
706
+ baseYieldAccount,
707
+ quoteYieldAccount,
708
+ },
709
+ remainingAccounts: options.remainingAccounts,
710
+ oraclePolicy: options.oraclePolicy,
711
+ });
712
+ return {
713
+ baseYieldAccount,
714
+ quoteYieldAccount,
715
+ setupInstructions,
716
+ actionInstruction,
717
+ transaction: new Transaction().add(...setupInstructions, actionInstruction),
718
+ };
719
+ }
720
+ depositSingleSided(args, options) {
721
+ return this.hlpLiquidityAction("depositSingleSided", args, options);
722
+ }
723
+ withdrawSingleSided(args, options) {
724
+ return this.hlpLiquidityAction("withdrawSingleSided", args, options);
30
725
  }
31
- transaction(name, args, options) {
32
- return this.builder(name, args, options).transaction();
726
+ /** Begin a fresh hLP receipt cohort after the current vault has terminally closed. */
727
+ rotateHlpCohortInstruction(params) {
728
+ const market = address(params.market);
729
+ const oldHlpMint = address(params.oldHlpMint);
730
+ const newHlpMint = address(params.newHlpMint);
731
+ return this.instruction("rotateHlpCohort", {
732
+ targetAsset: params.targetAsset === "base" ? 0 : 1,
733
+ metadata: params.metadata,
734
+ }, {
735
+ accounts: {
736
+ payer: address(params.payer),
737
+ market,
738
+ oldHlpMint,
739
+ newHlpMint,
740
+ oldCohort: deriveHlpCohortAddress(market, oldHlpMint, this.program.programId)[0],
741
+ newTokenMetadata: deriveTokenMetadataAddress(newHlpMint)[0],
742
+ sysvarInstructions: SYSVAR_INSTRUCTIONS_PUBKEY,
743
+ token2022Program: TOKEN_2022_PROGRAM_ID,
744
+ tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
745
+ systemProgram: SystemProgram.programId,
746
+ },
747
+ });
33
748
  }
34
- rpc(name, args, options) {
35
- return this.builder(name, args, options).rpc();
749
+ /** Burn old hLP receipts after terminal closure while preserving earned yield. */
750
+ burnRetiredHlpReceiptInstruction(params) {
751
+ const market = address(params.market);
752
+ const owner = address(params.owner);
753
+ const retiredMint = address(params.retiredMint);
754
+ return this.instruction("burnRetiredHlpReceipt", {
755
+ amount: governanceIntegerBN(params.amount),
756
+ }, {
757
+ accounts: {
758
+ market,
759
+ owner,
760
+ retiredMint,
761
+ cohort: deriveHlpCohortAddress(market, retiredMint, this.program.programId)[0],
762
+ ownerHlpAccount: params.ownerHlpAccount
763
+ ? address(params.ownerHlpAccount)
764
+ : getAssociatedTokenAddressSync(retiredMint, owner, true, TOKEN_2022_PROGRAM_ID),
765
+ baseYieldAccount: deriveYieldAccountAddress(market, owner, retiredMint, address(params.baseMint), "hlp", this.program.programId)[0],
766
+ quoteYieldAccount: deriveYieldAccountAddress(market, owner, retiredMint, address(params.quoteMint), "hlp", this.program.programId)[0],
767
+ token2022Program: TOKEN_2022_PROGRAM_ID,
768
+ },
769
+ });
770
+ }
771
+ async configureReferralPartnerInstruction(params) {
772
+ assertReferralInterestShareBps(params.interestShareBps);
773
+ const referrer = address(params.referrer);
774
+ return this.instruction("configureReferralPartner", {
775
+ referrer,
776
+ interestShareBps: params.interestShareBps,
777
+ active: params.active,
778
+ }, {
779
+ accounts: {
780
+ authoritySigner: address(params.authoritySigner),
781
+ futarchyAuthority: params.futarchyAuthority ?? deriveFutarchyAuthorityAddress()[0],
782
+ referralPartner: deriveReferralPartnerAddress(referrer)[0],
783
+ systemProgram: SystemProgram.programId,
784
+ },
785
+ });
786
+ }
787
+ async configureReferralPartnerTransaction(params) {
788
+ return new Transaction().add(await this.configureReferralPartnerInstruction(params));
789
+ }
790
+ async initializeReferralAccrualInstruction(params) {
791
+ const referral = referralAccrualAddresses(params);
792
+ return this.instruction("initializeReferralAccrual", undefined, {
793
+ accounts: {
794
+ payer: address(params.payer),
795
+ referralPartner: referral.referralPartner,
796
+ market: address(params.market),
797
+ assetMint: address(params.assetMint),
798
+ referralAccrual: referral.referralAccrual,
799
+ systemProgram: SystemProgram.programId,
800
+ },
801
+ });
802
+ }
803
+ async initializeReferralAccrualTransaction(params) {
804
+ return new Transaction().add(await this.initializeReferralAccrualInstruction(params));
36
805
  }
37
806
  async referredAction(name, args, options) {
38
- const setup = await buildReferralVaultSetupInstruction({
39
- connection: this.program.provider.connection,
807
+ const referral = referralAccrualAddresses({
808
+ referrer: options.referrer,
809
+ market: options.market,
810
+ assetMint: options.debtMint,
811
+ });
812
+ const setupInstruction = await this.initializeReferralAccrualInstruction({
40
813
  payer: options.payer,
41
814
  referrer: options.referrer,
42
- mint: options.debtMint,
815
+ market: options.market,
816
+ assetMint: options.debtMint,
43
817
  });
44
818
  const hookAccounts = options.transferHookTransfers?.length
45
819
  ? await resolveTransferHookAccountMetas(this.program.provider.connection, options.transferHookTransfers)
@@ -47,21 +821,23 @@ export class DuskWrite {
47
821
  const actionInstruction = await this.instruction(name, {
48
822
  ...args,
49
823
  referrer: address(options.referrer),
50
- maxAcceptableReferralFeeBps: options.maxAcceptableReferralFeeBps,
51
824
  }, {
52
825
  accounts: {
53
826
  ...options.accounts,
54
- referralProfile: setup.referralProfile,
55
- referralVault: setup.referralVault,
827
+ referralPartner: referral.referralPartner,
828
+ referralAccrual: referral.referralAccrual,
829
+ ...(name === "openLeverage"
830
+ ? { instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY }
831
+ : {}),
56
832
  },
57
833
  remainingAccounts: mergeAccountMetas(options.remainingAccounts ?? [], hookAccounts),
58
834
  });
59
835
  return {
60
- referralProfile: setup.referralProfile,
61
- referralVault: setup.referralVault,
62
- setupInstruction: setup.instruction,
836
+ referralPartner: referral.referralPartner,
837
+ referralAccrual: referral.referralAccrual,
838
+ setupInstruction,
63
839
  actionInstruction,
64
- transaction: new Transaction().add(setup.instruction, actionInstruction),
840
+ transaction: new Transaction().add(setupInstruction, actionInstruction),
65
841
  };
66
842
  }
67
843
  referredBorrow(args, options) {
@@ -70,51 +846,54 @@ export class DuskWrite {
70
846
  referredOpenLeverage(args, options) {
71
847
  return this.referredAction("openLeverage", args, options);
72
848
  }
73
- referredIncreaseLeverage(args, options) {
74
- return this.referredAction("increaseLeverage", args, options);
75
- }
76
849
  async setReferralRecipientInstruction(params) {
77
850
  const authority = address(params.authority);
78
851
  return this.instruction("setReferralRecipient", { recipient: address(params.recipient) }, {
79
852
  accounts: {
80
853
  authority,
81
- referralProfile: deriveReferralProfileAddress(authority)[0],
82
- systemProgram: SystemProgram.programId,
854
+ referralPartner: deriveReferralPartnerAddress(authority)[0],
83
855
  },
84
856
  });
85
857
  }
86
858
  async setReferralRecipientTransaction(params) {
87
859
  return new Transaction().add(await this.setReferralRecipientInstruction(params));
88
860
  }
89
- async claimReferralFeesInstruction(params) {
861
+ async claimReferralInterestInstruction(params) {
90
862
  const authority = address(params.authority);
91
- const addresses = await referralVaultAddresses({
92
- connection: this.program.provider.connection,
863
+ const market = address(params.market);
864
+ const mintKey = address(params.mint);
865
+ const referral = referralAccrualAddresses({
93
866
  referrer: authority,
94
- mint: params.mint,
867
+ market,
868
+ assetMint: mintKey,
95
869
  });
870
+ const interestVault = address(params.interestVault ?? deriveMarketInterestVaultAddress(market, mintKey)[0]);
96
871
  const recipientTokenAccount = address(params.recipientTokenAccount);
97
- const [vaultAccount, mint] = await Promise.all([
98
- getAccount(this.program.provider.connection, addresses.referralVault, undefined, addresses.tokenProgram),
99
- getMint(this.program.provider.connection, address(params.mint), undefined, addresses.tokenProgram),
872
+ const tokenProgram = await tokenProgramForMint(this.program.provider.connection, mintKey);
873
+ const referralAccrual = this.program.account.referralAccrual;
874
+ const [accrual, mint] = await Promise.all([
875
+ referralAccrual.fetch(referral.referralAccrual),
876
+ getMint(this.program.provider.connection, mintKey, undefined, tokenProgram),
100
877
  ]);
101
878
  const hookAccounts = await resolveTransferHookAccountMetas(this.program.provider.connection, [
102
879
  {
103
- source: addresses.referralVault,
104
- mint: params.mint,
880
+ source: interestVault,
881
+ mint: mintKey,
105
882
  destination: recipientTokenAccount,
106
- authority: addresses.referralProfile,
107
- amount: vaultAccount.amount,
883
+ authority: market,
884
+ amount: accrual.amount,
108
885
  decimals: mint.decimals,
109
- tokenProgram: addresses.tokenProgram,
886
+ tokenProgram,
110
887
  },
111
888
  ]);
112
- return this.instruction("claimReferralFees", undefined, {
889
+ return this.instruction("claimReferralInterest", undefined, {
113
890
  accounts: {
891
+ market,
114
892
  authority,
115
- referralProfile: addresses.referralProfile,
116
- assetMint: address(params.mint),
117
- referralVault: addresses.referralVault,
893
+ referralPartner: referral.referralPartner,
894
+ assetMint: mintKey,
895
+ referralAccrual: referral.referralAccrual,
896
+ interestVault,
118
897
  recipientTokenAccount,
119
898
  tokenProgram: TOKEN_PROGRAM_ID,
120
899
  token2022Program: TOKEN_2022_PROGRAM_ID,
@@ -122,16 +901,518 @@ export class DuskWrite {
122
901
  remainingAccounts: mergeAccountMetas(params.remainingAccounts ?? [], hookAccounts),
123
902
  });
124
903
  }
125
- async claimReferralFeesTransaction(params) {
126
- return new Transaction().add(await this.claimReferralFeesInstruction(params));
904
+ async claimReferralInterestTransaction(params) {
905
+ return new Transaction().add(await this.claimReferralInterestInstruction(params));
906
+ }
907
+ /**
908
+ * Deposit collateral into a borrow position, creating it when `positionId` is
909
+ * new. Callers pass amounts in raw base units.
910
+ */
911
+ async depositCollateralInstruction(params) {
912
+ const market = address(params.market);
913
+ const owner = address(params.owner);
914
+ const assetMint = address(params.assetMint);
915
+ const positionId = address(params.positionId);
916
+ return this.instruction("depositCollateral", { positionId, depositAmount: governanceIntegerBN(params.depositAmount, "depositAmount") }, {
917
+ accounts: {
918
+ market,
919
+ owner,
920
+ assetMint,
921
+ collateralVault: address(params.collateralVault ??
922
+ deriveMarketCollateralVaultAddress(market, assetMint)[0]),
923
+ ownerAssetAccount: address(params.ownerAssetAccount),
924
+ borrowPosition: address(params.borrowPosition ??
925
+ deriveBorrowPositionAddress(market, owner, positionId)[0]),
926
+ tokenProgram: TOKEN_PROGRAM_ID,
927
+ token2022Program: TOKEN_2022_PROGRAM_ID,
928
+ },
929
+ remainingAccounts: params.remainingAccounts,
930
+ });
931
+ }
932
+ /** Donate to an existing borrow position. `owner` is the token payer. */
933
+ async donateCollateralInstruction(params) {
934
+ const market = address(params.market);
935
+ const assetMint = address(params.assetMint);
936
+ return this.instruction("donateCollateral", { depositAmount: governanceIntegerBN(params.depositAmount, "depositAmount") }, {
937
+ accounts: {
938
+ market, owner: address(params.owner), assetMint,
939
+ collateralVault: address(params.collateralVault ?? deriveMarketCollateralVaultAddress(market, assetMint)[0]),
940
+ ownerAssetAccount: address(params.ownerAssetAccount),
941
+ borrowPosition: address(params.borrowPosition ?? deriveBorrowPositionAddress(market, address(params.positionOwner ?? params.owner), address(params.positionId))[0]),
942
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
943
+ }, remainingAccounts: params.remainingAccounts,
944
+ });
945
+ }
946
+ /** Sweep both collateral balances and close a debt-free borrow position. */
947
+ async withdrawAllCollateralInstruction(params) {
948
+ const market = address(params.market);
949
+ const baseMint = address(params.baseMint);
950
+ const quoteMint = address(params.quoteMint);
951
+ return this.instruction("withdrawAllCollateral", {
952
+ minBaseOut: governanceIntegerBN(params.minBaseOut, "minBaseOut"),
953
+ minQuoteOut: governanceIntegerBN(params.minQuoteOut, "minQuoteOut"),
954
+ }, { accounts: {
955
+ market, owner: address(params.owner), baseMint, quoteMint,
956
+ borrowPosition: address(params.borrowPosition ?? deriveBorrowPositionAddress(market, address(params.owner), address(params.positionId))[0]),
957
+ baseCollateralVault: deriveMarketCollateralVaultAddress(market, baseMint)[0],
958
+ quoteCollateralVault: deriveMarketCollateralVaultAddress(market, quoteMint)[0],
959
+ ownerBaseAccount: address(params.ownerBaseAccount), ownerQuoteAccount: address(params.ownerQuoteAccount),
960
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
961
+ }, remainingAccounts: params.remainingAccounts });
962
+ }
963
+ /** Return all collateral after a complete leverage repayment and close the position. */
964
+ async withdrawRepaidLeverageInstruction(params) {
965
+ const market = address(params.market);
966
+ const collateralMint = address(params.collateralMint);
967
+ return this.instruction("withdrawRepaidLeverage", { minCollateralOut: governanceIntegerBN(params.minCollateralOut, "minCollateralOut") }, {
968
+ accounts: {
969
+ market, owner: address(params.owner), collateralMint,
970
+ leveragePosition: address(params.leveragePosition ?? deriveLeveragePositionAddress(market, address(params.owner), address(params.positionId), address(params.namespaceAuthority ?? params.owner))[0]),
971
+ collateralVault: deriveLeverageCollateralVaultAddress(market, collateralMint)[0],
972
+ ownerCollateralAccount: address(params.ownerCollateralAccount),
973
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
974
+ }, remainingAccounts: params.remainingAccounts,
975
+ });
976
+ }
977
+ async depositCollateralTransaction(params) {
978
+ return new Transaction().add(await this.depositCollateralInstruction(params));
979
+ }
980
+ /**
981
+ * Withdraw collateral. `minAssetAmountOut` and `minLiquidationCfBps` are the
982
+ * caller's slippage and health floors; the program rejects the withdrawal
983
+ * rather than silently returning less.
984
+ */
985
+ async withdrawCollateralInstruction(params) {
986
+ const market = address(params.market);
987
+ const owner = address(params.owner);
988
+ const assetMint = address(params.assetMint);
989
+ const positionId = address(params.positionId);
990
+ return this.instruction("withdrawCollateral", {
991
+ withdrawAmount: governanceIntegerBN(params.withdrawAmount, "withdrawAmount"),
992
+ minAssetAmountOut: governanceIntegerBN(params.minAssetAmountOut, "minAssetAmountOut"),
993
+ minLiquidationCfBps: params.minLiquidationCfBps,
994
+ }, {
995
+ accounts: {
996
+ market,
997
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
998
+ owner,
999
+ assetMint,
1000
+ collateralVault: address(params.collateralVault ??
1001
+ deriveMarketCollateralVaultAddress(market, assetMint)[0]),
1002
+ ownerAssetAccount: address(params.ownerAssetAccount),
1003
+ borrowPosition: address(params.borrowPosition ??
1004
+ deriveBorrowPositionAddress(market, owner, positionId)[0]),
1005
+ tokenProgram: TOKEN_PROGRAM_ID,
1006
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1007
+ },
1008
+ remainingAccounts: params.remainingAccounts,
1009
+ });
1010
+ }
1011
+ async withdrawCollateralTransaction(params) {
1012
+ return new Transaction().add(await this.withdrawCollateralInstruction(params));
1013
+ }
1014
+ /**
1015
+ * Repay anyone’s borrowed debt using `owner`’s tokens, without collateral rights.
1016
+ * Pass the wallet balance as `repayAmount` to clear a
1017
+ * position; the program repays at most the outstanding debt.
1018
+ */
1019
+ async repayInstruction(params) {
1020
+ const market = address(params.market);
1021
+ const owner = address(params.owner);
1022
+ const debtAssetMint = address(params.debtAssetMint);
1023
+ const positionId = address(params.positionId);
1024
+ const referralPartner = params.referralPartner
1025
+ ? address(params.referralPartner)
1026
+ : null;
1027
+ return this.instruction("repay", { repayAmount: governanceIntegerBN(params.repayAmount, "repayAmount") }, {
1028
+ accounts: {
1029
+ market,
1030
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
1031
+ owner,
1032
+ debtAssetMint,
1033
+ collateralAssetMint: address(params.collateralAssetMint),
1034
+ reserveVault: address(params.reserveVault ??
1035
+ deriveMarketReserveVaultAddress(market, debtAssetMint)[0]),
1036
+ interestVault: address(params.interestVault ??
1037
+ deriveMarketInterestVaultAddress(market, debtAssetMint)[0]),
1038
+ ownerDebtAccount: address(params.ownerDebtAccount),
1039
+ borrowPosition: address(params.borrowPosition ??
1040
+ deriveBorrowPositionAddress(market, address(params.positionOwner ?? params.owner), positionId)[0]),
1041
+ referralPartner,
1042
+ referralAccrual: referralPartner
1043
+ ? deriveReferralAccrualAddress(referralPartner, market, debtAssetMint)[0]
1044
+ : null,
1045
+ tokenProgram: TOKEN_PROGRAM_ID,
1046
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1047
+ },
1048
+ remainingAccounts: [...(await this.hlpRemainingAccounts(market)), ...(params.remainingAccounts ?? [])],
1049
+ });
1050
+ }
1051
+ async repayTransaction(params) {
1052
+ return new Transaction().add(await this.repayInstruction(params));
1053
+ }
1054
+ /**
1055
+ * Add balanced yLP liquidity. `minYlpAmount` is the caller's slippage floor;
1056
+ * the program rejects the deposit rather than minting fewer shares.
1057
+ */
1058
+ async addLiquidityInstruction(params) {
1059
+ const common = await this.resolveYlpAccounts(params);
1060
+ return this.instruction("addLiquidity", {
1061
+ baseDepositAmount: governanceIntegerBN(params.baseDepositAmount, "baseDepositAmount"),
1062
+ quoteDepositAmount: governanceIntegerBN(params.quoteDepositAmount, "quoteDepositAmount"),
1063
+ minYlpAmount: governanceIntegerBN(params.minYlpAmount, "minYlpAmount"),
1064
+ }, {
1065
+ accounts: {
1066
+ ...common,
1067
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
1068
+ },
1069
+ remainingAccounts: params.remainingAccounts,
1070
+ });
1071
+ }
1072
+ async addLiquidityTransaction(params) {
1073
+ return new Transaction().add(await this.addLiquidityInstruction(params));
1074
+ }
1075
+ /**
1076
+ * Burn yLP for the underlying pair. Both minimums are enforced by the
1077
+ * program, so a partially-filled withdrawal fails instead of silently
1078
+ * returning less of one side.
1079
+ */
1080
+ async removeLiquidityInstruction(params) {
1081
+ const common = await this.resolveYlpAccounts(params);
1082
+ return this.instruction("removeLiquidity", {
1083
+ ylpAmount: governanceIntegerBN(params.ylpAmount, "ylpAmount"),
1084
+ minBaseAmountOut: governanceIntegerBN(params.minBaseAmountOut, "minBaseAmountOut"),
1085
+ minQuoteAmountOut: governanceIntegerBN(params.minQuoteAmountOut, "minQuoteAmountOut"),
1086
+ }, { accounts: common, remainingAccounts: params.remainingAccounts });
1087
+ }
1088
+ async removeLiquidityTransaction(params) {
1089
+ return new Transaction().add(await this.removeLiquidityInstruction(params));
1090
+ }
1091
+ /**
1092
+ * Accounts shared by both balanced yLP instructions. Reserve vaults and yLP
1093
+ * yield accounts derive from the market; token programs resolve per mint so
1094
+ * a Token-2022 side needs no caller branching.
1095
+ */
1096
+ /** Borrow more against an open position and receive collateral. */
1097
+ async increaseLeverageInstruction(params) {
1098
+ return this.fundLeverageInstruction(params, 0n);
1099
+ }
1100
+ /** Add debt-token equity and optional borrowing to the same position. */
1101
+ async addToLeverageInstruction(params) {
1102
+ if (BigInt(params.marginAmount.toString()) <= 0n)
1103
+ throw new RangeError("marginAmount must be positive");
1104
+ return this.fundLeverageInstruction(params, params.marginAmount, params.ownerDebtAccount);
1105
+ }
1106
+ async addToLeverageTransaction(params) {
1107
+ return new Transaction().add(await this.addToLeverageInstruction(params));
1108
+ }
1109
+ async fundLeverageInstruction(params, marginAmount, ownerDebtAccount) {
1110
+ const core = await this.resolveLeverageAccounts(params);
1111
+ return this.instruction("increaseLeverage", {
1112
+ debtAsset: marketAssetIndex(params.debtAsset),
1113
+ debtAmount: governanceIntegerBN(params.debtAmount, "debtAmount"),
1114
+ marginAmount: governanceIntegerBN(marginAmount, "marginAmount"),
1115
+ minCollateralOut: governanceIntegerBN(params.minCollateralOut, "minCollateralOut"),
1116
+ }, {
1117
+ accounts: {
1118
+ market: core.market,
1119
+ futarchyAuthority: core.futarchyAuthority,
1120
+ positionOwner: core.positionOwner,
1121
+ leveragePosition: core.leveragePosition,
1122
+ debtMint: core.debtMint,
1123
+ collateralMint: core.collateralMint,
1124
+ debtReserveVault: core.debtReserveVault,
1125
+ collateralReserveVault: core.collateralReserveVault,
1126
+ leverageCollateralVault: core.leverageCollateralVault,
1127
+ owner: core.owner,
1128
+ ownerDebtAccount: ownerDebtAccount ? address(ownerDebtAccount) : null,
1129
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
1130
+ tokenProgram: core.tokenProgram,
1131
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1132
+ },
1133
+ remainingAccounts: [
1134
+ ...(await this.hlpRemainingAccounts(core.market)),
1135
+ ...(params.remainingAccounts ?? []),
1136
+ ],
1137
+ });
1138
+ }
1139
+ async increaseLeverageTransaction(params) {
1140
+ return new Transaction().add(await this.increaseLeverageInstruction(params));
1141
+ }
1142
+ /** Sell collateral to repay debt without closing the position. */
1143
+ async decreaseLeverageInstruction(params) {
1144
+ const core = await this.resolveLeverageAccounts(params);
1145
+ return this.instruction("decreaseLeverage", {
1146
+ debtAsset: marketAssetIndex(params.debtAsset),
1147
+ collateralAmount: governanceIntegerBN(params.collateralAmount, "collateralAmount"),
1148
+ minRepayOut: governanceIntegerBN(params.minRepayOut, "minRepayOut"),
1149
+ maxSurplusOut: governanceIntegerBN(params.maxSurplusOut ?? 0n, "maxSurplusOut"),
1150
+ }, {
1151
+ accounts: {
1152
+ market: core.market,
1153
+ futarchyAuthority: core.futarchyAuthority,
1154
+ positionOwner: core.positionOwner,
1155
+ leveragePosition: core.leveragePosition,
1156
+ debtMint: core.debtMint,
1157
+ collateralMint: core.collateralMint,
1158
+ debtReserveVault: core.debtReserveVault,
1159
+ collateralReserveVault: core.collateralReserveVault,
1160
+ debtInterestVault: core.debtInterestVault,
1161
+ ownerDebtAccount: address(params.ownerDebtAccount),
1162
+ leverageCollateralVault: core.leverageCollateralVault,
1163
+ referralPartner: core.referralPartner,
1164
+ referralAccrual: core.referralAccrual,
1165
+ owner: core.owner,
1166
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
1167
+ tokenProgram: core.tokenProgram,
1168
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1169
+ },
1170
+ remainingAccounts: [
1171
+ ...(await this.hlpRemainingAccounts(core.market)),
1172
+ ...(params.remainingAccounts ?? []),
1173
+ ],
1174
+ });
1175
+ }
1176
+ async decreaseLeverageTransaction(params) {
1177
+ return new Transaction().add(await this.decreaseLeverageInstruction(params));
1178
+ }
1179
+ /** Repay anyone’s leverage debt from `owner`’s tokens; collateral stays with the position owner. */
1180
+ async addLeverageMarginInstruction(params) {
1181
+ return this.repayLeverageInstruction(params);
1182
+ }
1183
+ /** Permissionless repayment without an unnecessary collateral-sale quote. */
1184
+ async repayLeverageInstruction(params) {
1185
+ return this.leverageRepaymentInstruction(params, "repayLeverage");
1186
+ }
1187
+ async leverageRepaymentInstruction(params, method) {
1188
+ const core = await this.resolveLeverageAccounts(params);
1189
+ return this.instruction(method, {
1190
+ debtAsset: marketAssetIndex(params.debtAsset),
1191
+ amount: governanceIntegerBN(params.amount, "amount"),
1192
+ }, {
1193
+ accounts: {
1194
+ market: core.market,
1195
+ futarchyAuthority: core.futarchyAuthority,
1196
+ positionOwner: core.positionOwner,
1197
+ leveragePosition: core.leveragePosition,
1198
+ debtMint: core.debtMint,
1199
+ collateralMint: core.collateralMint,
1200
+ debtReserveVault: core.debtReserveVault,
1201
+ debtInterestVault: core.debtInterestVault,
1202
+ ownerDebtAccount: address(params.ownerDebtAccount),
1203
+ referralPartner: core.referralPartner,
1204
+ referralAccrual: core.referralAccrual,
1205
+ owner: core.owner,
1206
+ tokenProgram: core.tokenProgram,
1207
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1208
+ },
1209
+ remainingAccounts: [...(await this.hlpRemainingAccounts(core.market)), ...(params.remainingAccounts ?? [])],
1210
+ });
1211
+ }
1212
+ async repayLeverageTransaction(params) {
1213
+ return new Transaction().add(await this.repayLeverageInstruction(params));
1214
+ }
1215
+ async addLeverageMarginTransaction(params) {
1216
+ return new Transaction().add(await this.repayLeverageInstruction(params));
1217
+ }
1218
+ /**
1219
+ * Owner-signed proportional partial/full close. Delegated closes use the delegate client.
1220
+ */
1221
+ async closeLeverageInstruction(params, marketSnapshot) {
1222
+ if ("collateralFunded" in params && params.collateralFunded === true)
1223
+ throw new Error("Collateral-funded leverage closes are no longer supported");
1224
+ const closeBps = params.closeBps ?? 10_000;
1225
+ if (!Number.isSafeInteger(closeBps) || closeBps <= 0 || closeBps > 10_000)
1226
+ throw new RangeError("closeBps must be between 1 and 10000");
1227
+ const core = await this.resolveLeverageAccounts(params);
1228
+ return this.instruction("closeLeverage", {
1229
+ debtAsset: marketAssetIndex(params.debtAsset),
1230
+ minAmountOut: governanceIntegerBN(params.minAmountOut, "minAmountOut"),
1231
+ closeBps,
1232
+ }, {
1233
+ accounts: {
1234
+ market: core.market,
1235
+ futarchyAuthority: core.futarchyAuthority,
1236
+ positionOwner: core.positionOwner,
1237
+ leveragePosition: core.leveragePosition,
1238
+ debtMint: core.debtMint,
1239
+ collateralMint: core.collateralMint,
1240
+ debtReserveVault: core.debtReserveVault,
1241
+ collateralReserveVault: core.collateralReserveVault,
1242
+ debtInterestVault: core.debtInterestVault,
1243
+ leverageCollateralVault: core.leverageCollateralVault,
1244
+ ownerDebtAccount: address(params.ownerDebtAccount),
1245
+ delegateFeeRecipient: params.delegateFeeRecipient
1246
+ ? address(params.delegateFeeRecipient)
1247
+ : null,
1248
+ delegateExecutorAccount: params.delegateExecutorAccount
1249
+ ? address(params.delegateExecutorAccount)
1250
+ : null,
1251
+ referralPartner: core.referralPartner,
1252
+ referralAccrual: core.referralAccrual,
1253
+ leverageDelegation: params.leverageDelegation
1254
+ ? address(params.leverageDelegation)
1255
+ : null,
1256
+ delegatedProgram: params.delegatedProgram
1257
+ ? address(params.delegatedProgram)
1258
+ : null,
1259
+ authority: address(params.authority ?? params.positionOwner),
1260
+ instructionsSysvar: SYSVAR_INSTRUCTIONS_PUBKEY,
1261
+ tokenProgram: core.tokenProgram,
1262
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1263
+ },
1264
+ remainingAccounts: [
1265
+ ...(await this.hlpRemainingAccounts(core.market, marketSnapshot)),
1266
+ ...(params.remainingAccounts ?? []),
1267
+ ],
1268
+ });
1269
+ }
1270
+ async closeLeverageTransaction(params) {
1271
+ return new Transaction().add(await this.closeLeverageInstruction(params));
1272
+ }
1273
+ /**
1274
+ * Accounts shared across the leverage lifecycle. Individual builders pass
1275
+ * through only the subset their instruction declares.
1276
+ */
1277
+ async resolveLeverageAccounts(params) {
1278
+ const market = address(params.market);
1279
+ const positionOwner = address(params.positionOwner);
1280
+ const debtMint = address(params.debtMint);
1281
+ const collateralMint = address(params.collateralMint);
1282
+ const positionId = address(params.positionId);
1283
+ const referralPartner = params.referralPartner
1284
+ ? address(params.referralPartner)
1285
+ : null;
1286
+ return {
1287
+ market,
1288
+ futarchyAuthority: deriveFutarchyAuthorityAddress()[0],
1289
+ positionOwner,
1290
+ owner: address(params.owner ?? params.positionOwner),
1291
+ leveragePosition: address(params.leveragePosition ??
1292
+ deriveLeveragePositionAddress(market, positionOwner, positionId, address(params.namespaceAuthority ?? params.positionOwner))[0]),
1293
+ debtMint,
1294
+ collateralMint,
1295
+ debtReserveVault: address(params.debtReserveVault ??
1296
+ deriveMarketReserveVaultAddress(market, debtMint)[0]),
1297
+ collateralReserveVault: address(params.collateralReserveVault ??
1298
+ deriveMarketReserveVaultAddress(market, collateralMint)[0]),
1299
+ debtInterestVault: address(params.debtInterestVault ??
1300
+ deriveMarketInterestVaultAddress(market, debtMint)[0]),
1301
+ leverageCollateralVault: address(params.leverageCollateralVault ??
1302
+ deriveLeverageCollateralVaultAddress(market, collateralMint)[0]),
1303
+ referralPartner,
1304
+ referralAccrual: referralPartner
1305
+ ? deriveReferralAccrualAddress(referralPartner, market, debtMint)[0]
1306
+ : null,
1307
+ tokenProgram: TOKEN_PROGRAM_ID,
1308
+ };
1309
+ }
1310
+ async resolveYlpAccounts(params) {
1311
+ const market = address(params.market);
1312
+ const owner = address(params.owner);
1313
+ const baseMint = address(params.baseMint);
1314
+ const quoteMint = address(params.quoteMint);
1315
+ const ylpMint = address(params.ylpMint);
1316
+ return {
1317
+ market,
1318
+ owner,
1319
+ baseMint,
1320
+ quoteMint,
1321
+ ylpMint,
1322
+ baseReserveVault: address(params.baseReserveVault ??
1323
+ deriveMarketReserveVaultAddress(market, baseMint)[0]),
1324
+ quoteReserveVault: address(params.quoteReserveVault ??
1325
+ deriveMarketReserveVaultAddress(market, quoteMint)[0]),
1326
+ ownerBaseAccount: address(params.ownerBaseAccount),
1327
+ ownerQuoteAccount: address(params.ownerQuoteAccount),
1328
+ ownerYlpAccount: address(params.ownerYlpAccount),
1329
+ baseYieldAccount: address(params.baseYieldAccount ??
1330
+ deriveYieldAccountAddress(market, owner, ylpMint, baseMint, "ylp", this.program.programId)[0]),
1331
+ quoteYieldAccount: address(params.quoteYieldAccount ??
1332
+ deriveYieldAccountAddress(market, owner, ylpMint, quoteMint, "ylp", this.program.programId)[0]),
1333
+ tokenProgram: TOKEN_PROGRAM_ID,
1334
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1335
+ };
127
1336
  }
128
1337
  }
1338
+ function marketAssetIndex(side) {
1339
+ if (side !== "base" && side !== "quote") {
1340
+ throw new Error(`debtAsset must be "base" or "quote", got ${String(side)}`);
1341
+ }
1342
+ return side === "base" ? 0 : 1;
1343
+ }
1344
+ /**
1345
+ * Widen a launch config into the shape Anchor expects: every `u64` as a BN,
1346
+ * every `u16` left as a number. Written out field by field rather than mapped,
1347
+ * so a field added to the program fails to compile here instead of silently
1348
+ * going missing.
1349
+ */
1350
+ function anchorMarketConfig(config) {
1351
+ const bn = (value, label) => governanceIntegerBN(value, label);
1352
+ return {
1353
+ swapFeeBps: config.swapFeeBps,
1354
+ divergenceFeeShareCapBps: config.divergenceFeeShareCapBps,
1355
+ volatilityFeeShareCapBps: config.volatilityFeeShareCapBps,
1356
+ targetHlpLeverageBps: config.targetHlpLeverageBps,
1357
+ settlementDivergenceBps: config.settlementDivergenceBps,
1358
+ emaHalfLifeMs: bn(config.emaHalfLifeMs, "emaHalfLifeMs"),
1359
+ directionalEmaHalfLifeMs: bn(config.directionalEmaHalfLifeMs, "directionalEmaHalfLifeMs"),
1360
+ curveDepthEmaHalfLifeMs: bn(config.curveDepthEmaHalfLifeMs, "curveDepthEmaHalfLifeMs"),
1361
+ maxDailyBorrowBps: config.maxDailyBorrowBps,
1362
+ globalHealthContributionCapBps: config.globalHealthContributionCapBps,
1363
+ borrowMarketHealthFloorBps: config.borrowMarketHealthFloorBps,
1364
+ amm: anchorIntegerFields(config.amm, AMM_U64_FIELDS),
1365
+ irm: anchorIntegerFields(config.irm, IRM_U64_FIELDS),
1366
+ startTime: bn(config.startTime, "startTime"),
1367
+ };
1368
+ }
1369
+ const AMM_U64_FIELDS = [
1370
+ "peakAmplificationNad",
1371
+ "centerEmaHalfLifeMs",
1372
+ "volatilityHalfLifeMs",
1373
+ "adjustmentThresholdNad",
1374
+ "adjustmentStepNad",
1375
+ "minAdjustmentIntervalSlots",
1376
+ "volatilityShockCapNad",
1377
+ "volatilityCapNad",
1378
+ "divergenceFeeCoefficientNad",
1379
+ "volatilityFeeCoefficientNad",
1380
+ "launchFeeDurationSeconds",
1381
+ "launchRateLimitReferenceNad",
1382
+ "launchRateLimitDurationSeconds",
1383
+ ];
1384
+ const IRM_U64_FIELDS = ["lowerSignalNad", "upperSignalNad", "halfLifeMs", "initialAprNad", "minimumAprNad", "maximumAprNad"];
1385
+ function anchorIntegerFields(source, wide) {
1386
+ const out = { ...source };
1387
+ for (const field of wide) {
1388
+ if (out[field] === undefined)
1389
+ continue;
1390
+ out[field] = governanceIntegerBN(out[field], field);
1391
+ }
1392
+ return out;
1393
+ }
129
1394
  function normalizeArgs(args) {
130
1395
  if (args === undefined) {
131
1396
  return [];
132
1397
  }
133
1398
  return Array.isArray(args) ? args : [args];
134
1399
  }
1400
+ function proposalDigestBytes(digest) {
1401
+ const bytes = Array.from(digest);
1402
+ if (bytes.length !== 32 || bytes.some((byte) => !Number.isInteger(byte) || byte < 0 || byte > 255)) {
1403
+ throw new Error("proposal digest must be 32 bytes");
1404
+ }
1405
+ return bytes;
1406
+ }
1407
+ function cloneProposalMetadata(metadata) {
1408
+ return {
1409
+ version: metadata.version,
1410
+ title: metadata.title,
1411
+ descriptionUri: metadata.descriptionUri,
1412
+ descriptionSha256: [...metadata.descriptionSha256],
1413
+ descriptionLen: metadata.descriptionLen,
1414
+ };
1415
+ }
135
1416
  function mergeAccountMetas(...groups) {
136
1417
  const merged = new Map();
137
1418
  for (const group of groups) {
@@ -147,4 +1428,47 @@ function mergeAccountMetas(...groups) {
147
1428
  }
148
1429
  return [...merged.values()];
149
1430
  }
1431
+ // Kept in step with the on-chain instruction binding boundary.
1432
+ const ORACLE_READ_INSTRUCTIONS = new Set([
1433
+ "addLiquidity",
1434
+ "openLiquidityGates",
1435
+ "removeLiquidity",
1436
+ "fundInterest",
1437
+ "harvest",
1438
+ "swap",
1439
+ "previewHlpFlash",
1440
+ "beginHlpFlash",
1441
+ "settleHlpFlash",
1442
+ "closeInsolventHlp",
1443
+ "beginFlashLiquidation",
1444
+ "previewFlashLiquidation",
1445
+ "previewFlashAmmLiquidation",
1446
+ "emergencyLiquidation",
1447
+ "previewEmergencyLiquidation",
1448
+ "previewLiquidationHealth",
1449
+ "settleFlashLiquidation",
1450
+ "depositCollateral",
1451
+ "withdrawCollateral",
1452
+ "borrow",
1453
+ "repay",
1454
+ "donateCollateral",
1455
+ "openLeverage",
1456
+ "closeLeverage",
1457
+ "delegatedCloseLeverage",
1458
+ "increaseLeverage",
1459
+ "decreaseLeverage",
1460
+ "addLeverageMargin",
1461
+ "repayLeverage",
1462
+ "previewHlpDepositCapacity",
1463
+ "previewMarket",
1464
+ "previewHlpOrderTrigger",
1465
+ "previewAddLiquidity",
1466
+ "previewSwap",
1467
+ "previewBorrowCapacity",
1468
+ "previewBorrowPositionCapacity",
1469
+ "previewBorrowPosition",
1470
+ "depositSingleSided",
1471
+ "withdrawSingleSided",
1472
+ "executeParameterProposal",
1473
+ ]);
150
1474
  //# sourceMappingURL=write.js.map