@omnipair/dusk-sdk 2.0.2 → 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 (187) hide show
  1. package/README.md +1011 -16
  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 +71 -14
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +155 -28
  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 +3253 -378
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +130 -70
  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 +17175 -5862
  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/risk-pricing.d.ts +14 -0
  101. package/dist/risk-pricing.d.ts.map +1 -0
  102. package/dist/risk-pricing.js +25 -0
  103. package/dist/risk-pricing.js.map +1 -0
  104. package/dist/simulation.d.ts +45 -0
  105. package/dist/simulation.d.ts.map +1 -0
  106. package/dist/simulation.js +106 -0
  107. package/dist/simulation.js.map +1 -0
  108. package/dist/tranche-client.d.ts +121 -0
  109. package/dist/tranche-client.d.ts.map +1 -0
  110. package/dist/tranche-client.js +185 -0
  111. package/dist/tranche-client.js.map +1 -0
  112. package/dist/transfer-fees.d.ts +46 -0
  113. package/dist/transfer-fees.d.ts.map +1 -0
  114. package/dist/transfer-fees.js +76 -0
  115. package/dist/transfer-fees.js.map +1 -0
  116. package/dist/type-aliases.d.ts +271 -31
  117. package/dist/type-aliases.d.ts.map +1 -1
  118. package/dist/types_delegate.d.ts +6126 -0
  119. package/dist/types_delegate.d.ts.map +1 -0
  120. package/dist/types_delegate.js +2 -0
  121. package/dist/types_delegate.js.map +1 -0
  122. package/dist/types_v2.d.ts +17235 -5922
  123. package/dist/types_v2.d.ts.map +1 -1
  124. package/dist/virtual-book/index.d.ts +4 -0
  125. package/dist/virtual-book/index.d.ts.map +1 -0
  126. package/dist/virtual-book/index.js +4 -0
  127. package/dist/virtual-book/index.js.map +1 -0
  128. package/dist/virtual-book/market.d.ts +608 -0
  129. package/dist/virtual-book/market.d.ts.map +1 -0
  130. package/dist/virtual-book/market.js +59 -0
  131. package/dist/virtual-book/market.js.map +1 -0
  132. package/dist/virtual-book/projection.d.ts +44 -0
  133. package/dist/virtual-book/projection.d.ts.map +1 -0
  134. package/dist/virtual-book/projection.js +229 -0
  135. package/dist/virtual-book/projection.js.map +1 -0
  136. package/dist/virtual-book/quotes.d.ts +1241 -0
  137. package/dist/virtual-book/quotes.d.ts.map +1 -0
  138. package/dist/virtual-book/quotes.js +233 -0
  139. package/dist/virtual-book/quotes.js.map +1 -0
  140. package/dist/write.d.ts +517 -1
  141. package/dist/write.d.ts.map +1 -1
  142. package/dist/write.js +1172 -23
  143. package/dist/write.js.map +1 -1
  144. package/dist/yield-client.d.ts +51 -0
  145. package/dist/yield-client.d.ts.map +1 -0
  146. package/dist/yield-client.js +98 -0
  147. package/dist/yield-client.js.map +1 -0
  148. package/package.json +9 -2
  149. package/src/amounts.ts +13 -0
  150. package/src/constants.ts +236 -26
  151. package/src/delegate.ts +238 -0
  152. package/src/dusk.ts +28 -0
  153. package/src/get.ts +247 -82
  154. package/src/governance-client.ts +234 -0
  155. package/src/governance.ts +1422 -0
  156. package/src/hash.ts +15 -0
  157. package/src/hlp-liquidation-client.ts +195 -0
  158. package/src/idl_delegate.json +6119 -0
  159. package/src/idl_delegate.ts +3 -0
  160. package/src/idl_v2.json +17175 -5862
  161. package/src/index.ts +31 -0
  162. package/src/interest-accounting.ts +85 -0
  163. package/src/leverage-actions.ts +216 -0
  164. package/src/leverage-margins.ts +48 -0
  165. package/src/leverage-preview.ts +86 -0
  166. package/src/liquidation-client.ts +297 -0
  167. package/src/liquidation.ts +137 -0
  168. package/src/lp-naming.ts +127 -0
  169. package/src/lp-vanity.ts +135 -0
  170. package/src/market-bootstrap.ts +273 -0
  171. package/src/market-launch.ts +103 -0
  172. package/src/oracle.ts +120 -0
  173. package/src/preview.ts +53 -1
  174. package/src/protection.ts +112 -0
  175. package/src/risk-pricing.ts +28 -0
  176. package/src/simulation.ts +169 -0
  177. package/src/tranche-client.ts +187 -0
  178. package/src/transfer-fees.ts +99 -0
  179. package/src/type-aliases.ts +280 -31
  180. package/src/types_delegate.ts +6125 -0
  181. package/src/types_v2.ts +17174 -5861
  182. package/src/virtual-book/index.ts +3 -0
  183. package/src/virtual-book/market.ts +76 -0
  184. package/src/virtual-book/projection.ts +265 -0
  185. package/src/virtual-book/quotes.ts +308 -0
  186. package/src/write.ts +2073 -34
  187. package/src/yield-client.ts +117 -0
package/src/preview.ts CHANGED
@@ -5,31 +5,67 @@ import type { Dusk } from "./types_v2.js";
5
5
 
6
6
  const coder = new BorshCoder(IDL as unknown as Idl);
7
7
 
8
- type DuskPreviewTypes = IdlTypes<Dusk>;
8
+ type PreviewTypeNamed<N extends Dusk["types"][number]["name"]> = Extract<
9
+ Dusk["types"][number],
10
+ { name: N }
11
+ >;
12
+ type DuskPreviewIdl = {
13
+ address: Dusk["address"];
14
+ metadata: Dusk["metadata"];
15
+ instructions: [];
16
+ types: [
17
+ PreviewTypeNamed<"liquidationHealth">,
18
+ PreviewTypeNamed<"liquidationRates">,
19
+ PreviewTypeNamed<"addLiquidityPreview">,
20
+ PreviewTypeNamed<"borrowCapacityPreview">,
21
+ PreviewTypeNamed<"borrowPositionCapacityPreview">,
22
+ PreviewTypeNamed<"borrowPositionPreview">,
23
+ PreviewTypeNamed<"hlpDepositCapacityPreview">,
24
+ PreviewTypeNamed<"hlpDepositStatus">,
25
+ PreviewTypeNamed<"hlpOrderTriggerPreview">,
26
+ PreviewTypeNamed<"marketAsset">,
27
+ PreviewTypeNamed<"marketHealth">,
28
+ PreviewTypeNamed<"marketPreview">,
29
+ PreviewTypeNamed<"positionDebtSidePreview">,
30
+ PreviewTypeNamed<"previewAmm">,
31
+ PreviewTypeNamed<"previewSide">,
32
+ PreviewTypeNamed<"swapPreview">,
33
+ ];
34
+ };
35
+ type DuskPreviewTypes = IdlTypes<DuskPreviewIdl>;
9
36
 
37
+ export type HlpDepositCapacityPreview = DuskPreviewTypes["hlpDepositCapacityPreview"];
10
38
  export type MarketPreview = DuskPreviewTypes["marketPreview"];
11
39
  export type AddLiquidityPreview = DuskPreviewTypes["addLiquidityPreview"];
12
40
  export type SwapPreview = DuskPreviewTypes["swapPreview"];
13
41
  export type BorrowCapacityPreview = DuskPreviewTypes["borrowCapacityPreview"];
42
+ export type BorrowPositionCapacityPreview = DuskPreviewTypes["borrowPositionCapacityPreview"];
14
43
  export type BorrowPositionPreview = DuskPreviewTypes["borrowPositionPreview"];
44
+ export type HlpOrderTriggerPreview = DuskPreviewTypes["hlpOrderTriggerPreview"];
15
45
 
16
46
  export const PREVIEW_RETURN_TYPES = {
47
+ previewHlpDepositCapacity: "HlpDepositCapacityPreview",
17
48
  previewMarket: "MarketPreview",
18
49
  previewAddLiquidity: "AddLiquidityPreview",
19
50
  previewSwap: "SwapPreview",
20
51
  previewBorrowCapacity: "BorrowCapacityPreview",
21
52
  previewBorrowPosition: "BorrowPositionPreview",
53
+ previewBorrowPositionCapacity: "BorrowPositionCapacityPreview",
54
+ previewHlpOrderTrigger: "HlpOrderTriggerPreview",
22
55
  } as const;
23
56
 
24
57
  export type PreviewInstructionName = keyof typeof PREVIEW_RETURN_TYPES;
25
58
  export type PreviewReturnTypeName = (typeof PREVIEW_RETURN_TYPES)[PreviewInstructionName];
26
59
 
27
60
  type PreviewReturnByIdlType = {
61
+ HlpDepositCapacityPreview: HlpDepositCapacityPreview;
28
62
  MarketPreview: MarketPreview;
29
63
  AddLiquidityPreview: AddLiquidityPreview;
30
64
  SwapPreview: SwapPreview;
31
65
  BorrowCapacityPreview: BorrowCapacityPreview;
32
66
  BorrowPositionPreview: BorrowPositionPreview;
67
+ BorrowPositionCapacityPreview: BorrowPositionCapacityPreview;
68
+ HlpOrderTriggerPreview: HlpOrderTriggerPreview;
33
69
  };
34
70
 
35
71
  export type PreviewReturnForType<T extends PreviewReturnTypeName> = PreviewReturnByIdlType[T];
@@ -81,6 +117,12 @@ export function decodePreviewSwapReturnData(returnData: PreviewReturnData): Swap
81
117
  return decodePreviewReturnData("SwapPreview", returnData);
82
118
  }
83
119
 
120
+ export function decodePreviewHlpOrderTriggerReturnData(
121
+ returnData: PreviewReturnData
122
+ ): HlpOrderTriggerPreview {
123
+ return decodePreviewReturnData("HlpOrderTriggerPreview", returnData);
124
+ }
125
+
84
126
  export function decodePreviewBorrowCapacityReturnData(
85
127
  returnData: PreviewReturnData
86
128
  ): BorrowCapacityPreview {
@@ -137,3 +179,13 @@ function camelizeKey(key: string): string {
137
179
  const snakeToCamel = key.replace(/_([a-z0-9])/g, (_, char: string) => char.toUpperCase());
138
180
  return snakeToCamel.charAt(0).toLowerCase() + snakeToCamel.slice(1);
139
181
  }
182
+
183
+ export function decodePreviewBorrowPositionCapacityReturnData(returnData: PreviewReturnData): BorrowPositionCapacityPreview {
184
+ return decodePreviewReturnData("BorrowPositionCapacityPreview", returnData);
185
+ }
186
+
187
+ export function decodePreviewHlpDepositCapacityReturnData(
188
+ returnData: PreviewReturnData
189
+ ): HlpDepositCapacityPreview {
190
+ return decodePreviewReturnData("HlpDepositCapacityPreview", returnData);
191
+ }
@@ -0,0 +1,112 @@
1
+ import type { IdlTypes } from "@coral-xyz/anchor";
2
+ import { PublicKey, type AccountMeta } from "@solana/web3.js";
3
+ import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";
4
+ import { SystemProgram } from "@solana/web3.js";
5
+ import type { LeverageDelegate } from "./types_delegate.js";
6
+ import { type LeverageDelegateProgram, LEVERAGE_DELEGATE_PROGRAM_ID } from "./delegate.js";
7
+ import { DUSK_PROGRAM_ID, deriveEventAuthorityAddress } from "./constants.js";
8
+ import { governanceIntegerBN } from "./governance.js";
9
+ import { DuskWrite, type RawAmount } from "./write.js";
10
+ import { createDuskProgram } from "./program.js";
11
+ import { oracleReadAccounts } from "./oracle.js";
12
+
13
+ export const PROTECTION_ACTION = { borrowRepay: 0, borrowCollateral: 1, leverageRepay: 2 } as const;
14
+
15
+ export function deriveProtectionOrderAddress(owner: PublicKey, orderId: RawAmount,
16
+ programId = LEVERAGE_DELEGATE_PROGRAM_ID): [PublicKey, number] {
17
+ return PublicKey.findProgramAddressSync([Buffer.from("protection_order"), owner.toBuffer(),
18
+ governanceIntegerBN(orderId, "orderId").toArrayLike(Buffer, "le", 8)], programId);
19
+ }
20
+
21
+ type MethodAccounts<T extends keyof LeverageDelegateProgram["methods"]> =
22
+ Parameters<ReturnType<LeverageDelegateProgram["methods"][T]>["accountsStrict"]>[0];
23
+ type CreateAccounts = Omit<MethodAccounts<"createProtectionOrder">,
24
+ "order" | "duskEventAuthority" | "duskProgram" | "token2022Program" | "systemProgram"> & { owner: PublicKey };
25
+ type ManageAccounts = Omit<MethodAccounts<"fundProtectionOrder">, "token2022Program">;
26
+ type ExecuteAccounts = Omit<MethodAccounts<"executeProtectionOrder">,
27
+ "duskEventAuthority" | "duskProgram" | "tokenProgram" | "token2022Program">;
28
+ type CreateArgs = IdlTypes<LeverageDelegate>["createProtectionOrderArgs"];
29
+
30
+ /** All amounts use raw token units. Health 10000 is the liquidation boundary. */
31
+ export type CreateProtectionOrderParams = {
32
+ [K in keyof CreateArgs]: CreateArgs[K] extends number ? number : RawAmount;
33
+ };
34
+
35
+ /** Fund recurring protection for an existing borrowing or leverage position.
36
+ * Setup the order's LP ATA, asset ATAs and both yield accounts first. LP transfers
37
+ * require buildLpTransferHookAccountMetas. The sponsor remains yield recipient.
38
+ * Execution needs a keeper token balance to advance repayment; LP redemption
39
+ * reimburses that balance atomically. Insufficient redemption liquidity reverts.
40
+ */
41
+ export class DuskProtectionOrders {
42
+ constructor(readonly program: LeverageDelegateProgram) {}
43
+
44
+ private async oracleAccounts(market: PublicKey, remaining: AccountMeta[]) {
45
+ const dusk = createDuskProgram({ connection: this.program.provider.connection });
46
+ const state = await dusk.account.market.fetch(market);
47
+ const accounts = [...remaining];
48
+ for (const meta of oracleReadAccounts(state.oracle.policy)) {
49
+ if (!accounts.some(account => account.pubkey.equals(meta.pubkey))) accounts.push(meta);
50
+ }
51
+ return accounts;
52
+ }
53
+
54
+ async createInstruction(params: CreateProtectionOrderParams, accounts: CreateAccounts,
55
+ remainingAccounts: AccountMeta[] = []) {
56
+ const order = deriveProtectionOrderAddress(new PublicKey(accounts.owner), params.orderId, this.program.programId)[0];
57
+ const args: CreateArgs = {
58
+ ...params,
59
+ orderId: governanceIntegerBN(params.orderId, "orderId"),
60
+ lpAmount: governanceIntegerBN(params.lpAmount, "lpAmount"),
61
+ maxLpPerExecution: governanceIntegerBN(params.maxLpPerExecution, "maxLpPerExecution"),
62
+ maxPaymentPerExecution: governanceIntegerBN(params.maxPaymentPerExecution, "maxPaymentPerExecution"),
63
+ minPaymentPerLpNad: governanceIntegerBN(params.minPaymentPerLpNad, "minPaymentPerLpNad"),
64
+ triggerHealthBps: governanceIntegerBN(params.triggerHealthBps, "triggerHealthBps"),
65
+ targetHealthBps: governanceIntegerBN(params.targetHealthBps, "targetHealthBps"),
66
+ expiresAt: governanceIntegerBN(params.expiresAt, "expiresAt"),
67
+ };
68
+ return this.program.methods.createProtectionOrder(args).accountsStrict({ ...accounts, order,
69
+ duskProgram: DUSK_PROGRAM_ID, duskEventAuthority: deriveEventAuthorityAddress()[0],
70
+ token2022Program: TOKEN_2022_PROGRAM_ID, systemProgram: SystemProgram.programId,
71
+ }).remainingAccounts(remainingAccounts).instruction();
72
+ }
73
+
74
+ async previewInstruction(accounts: MethodAccounts<"previewProtectionOrder">, remainingAccounts: AccountMeta[] = []) {
75
+ return this.program.methods.previewProtectionOrder().accountsStrict(accounts)
76
+ .remainingAccounts(await this.oracleAccounts(new PublicKey(accounts.market), remainingAccounts)).instruction();
77
+ }
78
+
79
+ async fundInstruction(lpAmount: RawAmount, accounts: ManageAccounts, remainingAccounts: AccountMeta[] = []) {
80
+ return this.program.methods.fundProtectionOrder({ lpAmount: governanceIntegerBN(lpAmount, "lpAmount") })
81
+ .accountsStrict({ ...accounts, token2022Program: TOKEN_2022_PROGRAM_ID }).remainingAccounts(remainingAccounts).instruction();
82
+ }
83
+
84
+ async cancelInstruction(accounts: ManageAccounts, remainingAccounts: AccountMeta[] = []) {
85
+ return this.program.methods.cancelProtectionOrder().accountsStrict({ ...accounts, token2022Program: TOKEN_2022_PROGRAM_ID })
86
+ .remainingAccounts(remainingAccounts).instruction();
87
+ }
88
+
89
+ /** LP redemptions may need an address lookup table and a larger heap frame.
90
+ * Simulate the complete transaction with the current native market state.
91
+ * LP proceeds must cover payment, the full keeper reward, and the additional
92
+ * 10 bps protocol fee. Supply protocolFee from orderProtocolFeeAccounts.
93
+ */
94
+ async executeInstruction(params: { lpAmount: RawAmount; paymentAmount: RawAmount },
95
+ accounts: ExecuteAccounts, remainingAccounts: AccountMeta[] = []) {
96
+ const write = new DuskWrite(createDuskProgram({ connection: this.program.provider.connection }));
97
+ const order = await this.program.account.protectionOrder.fetch(accounts.order);
98
+ const prefix = order.action === PROTECTION_ACTION.borrowCollateral
99
+ ? [] : await write.hlpRemainingAccounts(accounts.market);
100
+ // Keep the canonical prefix first even when callers supply transfer-hook
101
+ // accounts. Existing callers may already provide that same prefix.
102
+ const hasPrefix = prefix.length > 0 && prefix.every((meta, i) =>
103
+ remainingAccounts[i]?.pubkey.equals(meta.pubkey) && remainingAccounts[i]?.isWritable === meta.isWritable);
104
+ const completeRemaining = hasPrefix ? remainingAccounts : [...prefix, ...remainingAccounts];
105
+ const remaining = await this.oracleAccounts(new PublicKey(accounts.market), completeRemaining);
106
+ return this.program.methods.executeProtectionOrder({ lpAmount: governanceIntegerBN(params.lpAmount, "lpAmount"),
107
+ paymentAmount: governanceIntegerBN(params.paymentAmount, "paymentAmount") })
108
+ .accountsStrict({ ...accounts, duskProgram: DUSK_PROGRAM_ID, duskEventAuthority: deriveEventAuthorityAddress()[0],
109
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID })
110
+ .remainingAccounts(remaining).instruction();
111
+ }
112
+ }
@@ -0,0 +1,28 @@
1
+ /** Creation defaults. Governance may replace each market's controller. */
2
+ export const RISK_RATE_DEFAULTS = Object.freeze({
3
+ lowerSignalNad: 50_000_000,
4
+ upperSignalNad: 62_500_000,
5
+ halfLifeMs: 14 * 24 * 60 * 60 * 1_000,
6
+ initialAprNad: 40_000_000,
7
+ minimumAprNad: 20_000_000,
8
+ maximumAprNad: 0,
9
+ borrowUtilizationLimitBps: 8_000,
10
+ });
11
+
12
+ /** Values use one common numeraire. Returns null when this asset has no debt.
13
+ * This is the controller's coverage/cash signal, not a default probability. */
14
+ export function riskCoverageSignalNad(
15
+ juniorFundedValue: bigint,
16
+ totalCoveredDebtValue: bigint,
17
+ assetDebt: bigint,
18
+ assetCash: bigint
19
+ ): bigint | null {
20
+ if ([juniorFundedValue, totalCoveredDebtValue, assetDebt, assetCash].some(v => v < 0n)) {
21
+ throw new Error("Coverage inputs cannot be negative");
22
+ }
23
+ if (assetDebt === 0n) return null;
24
+ if (totalCoveredDebtValue === 0n) throw new Error("Covered debt value is zero for an indebted asset");
25
+ // Match the native bps utilization input, including its floor rounding.
26
+ const utilizationBps = assetDebt * 10_000n / (assetDebt + assetCash);
27
+ return juniorFundedValue * ((10_000n - utilizationBps) * 100_000n) / totalCoveredDebtValue;
28
+ }
@@ -0,0 +1,169 @@
1
+ import type { Program } from "@coral-xyz/anchor";
2
+ import {
3
+ ComputeBudgetProgram,
4
+ PublicKey,
5
+ Transaction,
6
+ VersionedTransaction,
7
+ TransactionMessage,
8
+ type AddressLookupTableAccount,
9
+ type Commitment,
10
+ type TransactionInstruction,
11
+ type RpcResponseAndContext,
12
+ type SimulatedTransactionResponse,
13
+ } from "@solana/web3.js";
14
+ import { address, DEFAULT_READONLY_PUBLIC_KEY, type AddressLike } from "./address.js";
15
+ import type { Dusk } from "./types_v2.js";
16
+
17
+ export interface SimulateOptions {
18
+ feePayer?: AddressLike;
19
+ commitment?: Commitment;
20
+ /** Defaults to 1,400,000 units to accommodate heavier native previews. */
21
+ computeUnitLimit?: number;
22
+ /** Defaults to 256 KiB for native preview intermediate state. */
23
+ heapFrameBytes?: number;
24
+ }
25
+
26
+ export interface PreviewSimulationOptions extends SimulateOptions {
27
+ /** Require a complete budget prefix when other programs bind instruction
28
+ * indices. Dusk flash-liquidation plans are detected automatically. */
29
+ preserveInstructionIndices?: boolean;
30
+ /** Optional active lookup tables for larger position-action transactions. */
31
+ lookupTables?: AddressLookupTableAccount[];
32
+ /** Include CPI events when previewing an actual state-changing instruction. */
33
+ innerInstructions?: boolean;
34
+ /** Reject a bank older than this observed slot. */
35
+ minContextSlot?: number;
36
+ /** Post-simulation accounts, in exactly this order and from the same bank. */
37
+ accounts?: readonly AddressLike[];
38
+ signal?: AbortSignal;
39
+ /** Bounds the caller's wait; the transport may finish an in-flight RPC later. */
40
+ timeoutMs?: number;
41
+ /** Set false when simulating an instruction that succeeds without return data. */
42
+ requireReturnData?: boolean;
43
+ }
44
+
45
+ /** Keeps the actual RPC slot, logs and account snapshots beside return data. */
46
+ export type DuskPreviewSimulation = RpcResponseAndContext<SimulatedTransactionResponse> & {
47
+ /** Request start, so slow simulation never makes old data appear fresh. */
48
+ observedAt: number;
49
+ accountKeys: readonly PublicKey[];
50
+ };
51
+
52
+ export class DuskSimulationError extends Error {
53
+ constructor(
54
+ message: string,
55
+ readonly simulation: RpcResponseAndContext<SimulatedTransactionResponse>
56
+ ) {
57
+ super(message);
58
+ this.name = "DuskSimulationError";
59
+ }
60
+ }
61
+
62
+ export class DuskPreviewTimeoutError extends Error {
63
+ constructor() {
64
+ super("Dusk preview timed out");
65
+ this.name = "DuskPreviewTimeoutError";
66
+ }
67
+ }
68
+
69
+ export async function simulatePreviewWithContext(
70
+ program: Program<Dusk>,
71
+ instructions: readonly TransactionInstruction[],
72
+ options: PreviewSimulationOptions = {}
73
+ ): Promise<DuskPreviewSimulation> {
74
+ options.signal?.throwIfAborted();
75
+ const timeoutMs = options.timeoutMs ?? 10_000;
76
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
77
+ throw new Error("Invalid preview timeout");
78
+ if (
79
+ options.minContextSlot !== undefined &&
80
+ (!Number.isSafeInteger(options.minContextSlot) || options.minContextSlot < 0)
81
+ )
82
+ throw new Error("Invalid preview minimum slot");
83
+ if (!instructions.length) throw new Error("A preview requires an instruction");
84
+ // A complete flash plan already has its budgets and absolute settle index.
85
+ // Ordinary previews still need a budget prefix: placing budgets after the
86
+ // preview overwrites Solana's final return-data program ID.
87
+ const simulationInstructions = [...instructions];
88
+ const missingBudgets: TransactionInstruction[] = [];
89
+ const flashDiscriminators = program.idl?.instructions.filter(ix =>
90
+ ix.name === "beginFlashLiquidation" || ix.name === "beginHlpFlash").map(ix => Buffer.from(ix.discriminator)) ?? [];
91
+ const bindsIndices = options.preserveInstructionIndices || instructions.some(ix =>
92
+ ix.programId.equals(program.programId) && flashDiscriminators.some(tag => ix.data.subarray(0, 8).equals(tag)));
93
+ for (const [tag, explicit, budget] of [
94
+ [1, options.heapFrameBytes, ComputeBudgetProgram.requestHeapFrame({ bytes: options.heapFrameBytes ?? 256 * 1024 })],
95
+ [2, options.computeUnitLimit, ComputeBudgetProgram.setComputeUnitLimit({ units: options.computeUnitLimit ?? 1_400_000 })],
96
+ ] as const) {
97
+ const matches = simulationInstructions.flatMap((ix, index) =>
98
+ ix.programId.equals(ComputeBudgetProgram.programId) && ix.data[0] === tag ? [index] : []);
99
+ if (matches.length > 1) throw new Error("Duplicate compute-budget instruction in preview plan");
100
+ if (!matches.length) missingBudgets.push(budget);
101
+ else if (explicit !== undefined) simulationInstructions[matches[0]!] = budget;
102
+ }
103
+ if (bindsIndices && missingBudgets.length)
104
+ throw new Error("Index-bound simulation requires planned heap and compute budgets; use buildFlash or include them before binding indices");
105
+ const transaction = new Transaction().add(...missingBudgets, ...simulationInstructions);
106
+ transaction.feePayer = address(
107
+ options.feePayer ?? program.provider.publicKey ?? DEFAULT_READONLY_PUBLIC_KEY
108
+ );
109
+ transaction.recentBlockhash = PublicKey.default.toBase58();
110
+ const message = options.lookupTables?.length
111
+ ? new TransactionMessage({ payerKey: transaction.feePayer, recentBlockhash: transaction.recentBlockhash,
112
+ instructions: transaction.instructions }).compileToV0Message(options.lookupTables)
113
+ : transaction.compileMessage();
114
+ const wire = new VersionedTransaction(message);
115
+ const keys = message.version === "legacy" ? message.getAccountKeys()
116
+ : message.getAccountKeys({ addressLookupTableAccounts: options.lookupTables ?? [] });
117
+ const accountKeys = Array.from({ length: keys.length }, (_, index) => keys.get(index)!);
118
+ if (wire.serialize().length > 1232)
119
+ throw new Error("Preview exceeds the transaction packet limit");
120
+ const accounts = options.accounts?.map((account) => address(account).toBase58());
121
+ const observedAt = Date.now();
122
+ let timer: ReturnType<typeof setTimeout> | undefined;
123
+ let cancel = () => {};
124
+ const deadline = new Promise<never>((_, reject) => {
125
+ cancel = () =>
126
+ reject(options.signal?.reason ?? new DOMException("Preview cancelled", "AbortError"));
127
+ options.signal?.addEventListener("abort", cancel, { once: true });
128
+ timer = setTimeout(() => reject(new DuskPreviewTimeoutError()), timeoutMs);
129
+ });
130
+ try {
131
+ const connection = program.provider.connection;
132
+ const simulation = await Promise.race([
133
+ connection.simulateTransaction(wire, {
134
+ commitment: options.commitment ?? connection.commitment,
135
+ sigVerify: false,
136
+ replaceRecentBlockhash: true,
137
+ ...(options.innerInstructions ? { innerInstructions: true } : {}),
138
+ ...(options.minContextSlot === undefined ? {} : { minContextSlot: options.minContextSlot }),
139
+ ...(accounts === undefined
140
+ ? {}
141
+ : { accounts: { encoding: "base64", addresses: accounts } }),
142
+ }),
143
+ deadline,
144
+ ]);
145
+ options.signal?.throwIfAborted();
146
+ if (simulation.value.err) {
147
+ const tail = simulation.value.logs?.slice(-8).join("\n");
148
+ throw new DuskSimulationError(`Dusk simulation failed: ${JSON.stringify(simulation.value.err)}${tail ? `\n${tail}` : ""}`, simulation);
149
+ }
150
+ if (options.requireReturnData !== false && !simulation.value.returnData)
151
+ throw new DuskSimulationError("Dusk simulation did not return data", simulation);
152
+ if (options.requireReturnData !== false && simulation.value.returnData && simulation.value.returnData.programId !== program.programId.toBase58())
153
+ throw new DuskSimulationError(
154
+ "Dusk simulation returned data from a different program",
155
+ simulation
156
+ );
157
+ if (
158
+ !Number.isSafeInteger(simulation.context.slot) ||
159
+ simulation.context.slot < (options.minContextSlot ?? 0)
160
+ )
161
+ throw new DuskSimulationError("Dusk simulation returned a stale or invalid slot", simulation);
162
+ if (accounts && simulation.value.accounts?.length !== accounts.length)
163
+ throw new DuskSimulationError("Dusk simulation returned incomplete accounts", simulation);
164
+ return { ...simulation, observedAt, accountKeys };
165
+ } finally {
166
+ clearTimeout(timer);
167
+ options.signal?.removeEventListener("abort", cancel);
168
+ }
169
+ }
@@ -0,0 +1,187 @@
1
+ import type { Program } from "@coral-xyz/anchor";
2
+ import { PublicKey, SystemProgram, Transaction, SYSVAR_INSTRUCTIONS_PUBKEY, type AccountMeta } from "@solana/web3.js";
3
+ import { createAssociatedTokenAccountIdempotentInstruction, getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
4
+ import { address, type AddressLike } from "./address.js";
5
+ import { deriveJuniorMintAddress, deriveJuniorCohortAddress, deriveJuniorExitAddress, deriveYieldAccountAddress, deriveIncomeEpochAddress, deriveTokenMetadataAddress, TOKEN_METADATA_PROGRAM_ID } from "./constants.js";
6
+ import { governanceIntegerBN, type GovernanceIntegerLike } from "./governance.js";
7
+ import { assertLpTokenMetadata, type LpTokenMetadataInput } from "./lp-naming.js";
8
+ import { DuskWrite } from "./write.js";
9
+ import type { Dusk as DuskIdl } from "./types_v2.js";
10
+
11
+ export type TrancheAction =
12
+ | { kind: "enter"; seniorAmount: GovernanceIntegerLike; minimumJunior: GovernanceIntegerLike }
13
+ | { kind: "requestExit"; additionalJunior: GovernanceIntegerLike }
14
+ | { kind: "convertExit"; minimumSenior: GovernanceIntegerLike }
15
+ | { kind: "cancelExit" };
16
+
17
+ /** yLP/jrLP builders. Conversion changes ownership of existing pool capital;
18
+ * redeeming cash is a separate ordinary-LP withdrawal. Builders never submit. */
19
+ export class DuskTranches {
20
+ readonly write: DuskWrite;
21
+ constructor(readonly program: Program<DuskIdl>) { this.write = new DuskWrite(program); }
22
+
23
+ /** Archive a settled income denomination before further issuance overflows
24
+ * or restarts a fully paid book. This does not claim anyone's income. */
25
+ async rollIncome(params: { market: AddressLike; payer: AddressLike; bookIndex: number }) {
26
+ const market = address(params.market), payer = address(params.payer);
27
+ const state = await this.program.account.market.fetch(market);
28
+ const { bookIndex } = params;
29
+ if (!Number.isInteger(bookIndex) || bookIndex < 0 || bookIndex > 3) throw new Error("bookIndex must be 0–3");
30
+ const book = state.income.books[bookIndex];
31
+ if (book.units.lte(book.unpaid)) throw new Error("Income book has no settled units to roll");
32
+ if (!state.income.pending[bookIndex].isZero()) throw new Error("Income custody settlement is pending");
33
+ const incomeEpoch = deriveIncomeEpochAddress(market, bookIndex, book.epoch, this.program.programId)[0];
34
+ const instruction = await this.write.instruction("rollIncomeEpoch", { bookIndex, epoch: book.epoch }, { accounts: {
35
+ payer, market, incomeEpoch, systemProgram: SystemProgram.programId,
36
+ } });
37
+ return { incomeEpoch, instruction, transaction: new Transaction().add(instruction) };
38
+ }
39
+
40
+ /** Prepare one bounded history catch-up per source. Submit and fetch again
41
+ * while hasMore is true, before transferring, converting or harvesting. */
42
+ async checkpointIncome(params: { market: AddressLike; owner: AddressLike; kind: "senior" | "junior"; asset: "base" | "quote"; retiredJuniorMint?: AddressLike }) {
43
+ const market = address(params.market), owner = address(params.owner);
44
+ if (params.kind !== "junior" && params.retiredJuniorMint) throw new Error("Only junior has retired generations");
45
+ const state = await this.program.account.market.fetch(market);
46
+ const lpMint = params.kind === "senior" ? state.ylpMint : params.retiredJuniorMint ? address(params.retiredJuniorMint) : state.juniorMint;
47
+ const assetIndex = params.asset === "base" ? 0 : 1;
48
+ const assetMint = assetIndex === 0 ? state.baseSide.assetMint : state.quoteSide.assetMint;
49
+ const yieldAccount = deriveYieldAccountAddress(market, owner, lpMint, assetMint, params.kind === "senior" ? "ylp" : "junior", this.program.programId)[0];
50
+ const holder = await this.program.account.yieldAccount.fetch(yieldAccount);
51
+ if (!holder.incomeInitialized) throw new Error("Initialize the holder's income ledger before catch-up");
52
+ const ownerLp = getAssociatedTokenAddressSync(lpMint, owner, true, TOKEN_2022_PROGRAM_ID);
53
+ const instructions = [];
54
+ let hasMore = false;
55
+ for (let source = 0; source < 2; source++) {
56
+ const bookIndex = assetIndex + source * 2;
57
+ const epoch = BigInt(holder.income[source].epoch.toString());
58
+ const liveEpoch = BigInt(state.income.books[bookIndex].epoch.toString());
59
+ if (epoch > liveEpoch) throw new Error("Holder income epoch exceeds market epoch");
60
+ const count = Number(liveEpoch - epoch > 8n ? 8n : liveEpoch - epoch);
61
+ const remainingAccounts: AccountMeta[] = [];
62
+ if (params.kind === "junior" && !lpMint.equals(state.juniorMint)) remainingAccounts.push({ pubkey: deriveJuniorCohortAddress(market, lpMint, this.program.programId)[0], isSigner: false, isWritable: false });
63
+ for (let i = 0; i < count; i++) remainingAccounts.push({ pubkey: deriveIncomeEpochAddress(market, bookIndex, epoch + BigInt(i), this.program.programId)[0], isSigner: false, isWritable: false });
64
+ instructions.push(await this.write.instruction("checkpointIncome", { source }, { accounts: { market, lpMint, ownerLp, yieldAccount }, remainingAccounts }));
65
+ hasMore ||= epoch + BigInt(count) < liveEpoch;
66
+ }
67
+ return { instructions, hasMore, yieldAccount };
68
+ }
69
+
70
+ /** Prepare bounded, separate transactions to catch up both assets before a
71
+ * yLP/jrLP transfer, exit or claim. No transaction is sent by this method.
72
+ * If hasMore is true, submit these batches and call again. A concurrent epoch
73
+ * roll can also require another fetch; never discard the holder's old claim. */
74
+ async prepareHolderIncome(params: { market: AddressLike; owner: AddressLike; kind: "senior" | "junior"; retiredJuniorMint?: AddressLike }) {
75
+ const transactions: Transaction[] = [];
76
+ let hasMore = false;
77
+ for (const asset of ["base", "quote"] as const) {
78
+ const batch = await this.checkpointIncome({ ...params, asset });
79
+ transactions.push(...batch.instructions.map(ix => new Transaction().add(ix)));
80
+ hasMore ||= batch.hasMore;
81
+ }
82
+ return { transactions, hasMore };
83
+ }
84
+
85
+ /** Archive drained books before another operation issues income. This is a
86
+ * market-wide maintenance step, separate from catching up individual holders.
87
+ * A numerically exhausted, partially paid book can be rolled explicitly with
88
+ * rollIncome after IncomeEpochNeedsRollover. The payer funds archival rent. */
89
+ async prepareDrainedIncomeBooks(params: { market: AddressLike; payer: AddressLike }) {
90
+ const state = await this.program.account.market.fetch(address(params.market));
91
+ const transactions: Transaction[] = [];
92
+ for (let bookIndex = 0; bookIndex < 4; bookIndex++) {
93
+ const book = state.income.books[bookIndex];
94
+ if (!book.units.isZero() && book.unpaid.isZero()) {
95
+ transactions.push((await this.rollIncome({ ...params, bookIndex })).transaction);
96
+ }
97
+ }
98
+ return { transactions };
99
+ }
100
+
101
+ /** A retired receipt has zero principal but can still own earned income. */
102
+ async burnRetired(params: { market: AddressLike; owner: AddressLike; retiredMint: AddressLike; amount: GovernanceIntegerLike }) {
103
+ const market = address(params.market), owner = address(params.owner), retiredMint = address(params.retiredMint);
104
+ const state = await this.program.account.market.fetch(market);
105
+ if (retiredMint.equals(state.juniorMint)) throw new Error("Cannot burn an active generation through the retired-receipt path");
106
+ const exitAddress = deriveJuniorExitAddress(market, owner, retiredMint, this.program.programId)[0];
107
+ const exitState = await this.program.account.juniorExitAccount.fetchNullable(exitAddress);
108
+ const instruction = await this.write.instruction("burnRetiredJunior", { amount: governanceIntegerBN(params.amount, "amount") }, { accounts: {
109
+ market, owner, retiredMint, cohort: deriveJuniorCohortAddress(market, retiredMint, this.program.programId)[0],
110
+ ownerJunior: getAssociatedTokenAddressSync(retiredMint, owner, true, TOKEN_2022_PROGRAM_ID),
111
+ baseYield: deriveYieldAccountAddress(market, owner, retiredMint, state.baseSide.assetMint, "junior", this.program.programId)[0],
112
+ quoteYield: deriveYieldAccountAddress(market, owner, retiredMint, state.quoteSide.assetMint, "junior", this.program.programId)[0],
113
+ exit: exitState ? exitAddress : null, token2022Program: TOKEN_2022_PROGRAM_ID,
114
+ } });
115
+ return { instruction, transaction: new Transaction().add(instruction) };
116
+ }
117
+
118
+ async fundSeed(params: { market: AddressLike; asset: "base" | "quote"; remainingAccounts?: AccountMeta[] }) {
119
+ const market = address(params.market);
120
+ const state = await this.program.account.market.fetch(market);
121
+ const side = params.asset === "base" ? state.baseSide : state.quoteSide;
122
+ const instruction = await this.write.instruction("fundJuniorSeed", undefined, { accounts: {
123
+ market, assetMint: side.assetMint, reserveVault: side.reserveVault, interestVault: side.interestVault,
124
+ tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
125
+ }, remainingAccounts: params.remainingAccounts });
126
+ return { instruction, transaction: new Transaction().add(instruction) };
127
+ }
128
+
129
+ async compoundSeed(params: { market: AddressLike }) {
130
+ const market = address(params.market);
131
+ const state = await this.program.account.market.fetch(market);
132
+ const instruction = await this.write.instruction("compoundJuniorSeed", undefined, { accounts: { market, juniorMint: state.juniorMint } });
133
+ return { instruction, transaction: new Transaction().add(instruction) };
134
+ }
135
+
136
+ async initialize(params: { market: AddressLike; payer: AddressLike; metadata: LpTokenMetadataInput }) {
137
+ const market = address(params.market), payer = address(params.payer);
138
+ assertLpTokenMetadata(params.metadata);
139
+ const state = await this.program.account.market.fetch(market);
140
+ const first = state.juniorMint.equals(PublicKey.default);
141
+ if (!first && !state.tranches.juniorReserveShares.isZero()) throw new Error("Current junior capital is not wiped out");
142
+ const generation = BigInt(state.tranches.generation.toString()) + (first ? 0n : 1n);
143
+ const juniorMint = deriveJuniorMintAddress(market, generation, this.program.programId)[0];
144
+ const cohort = deriveJuniorCohortAddress(market, juniorMint, this.program.programId)[0];
145
+ const initialize = await this.write.instruction("initializeJunior", {
146
+ generation: governanceIntegerBN(generation, "generation"),
147
+ metadata: params.metadata,
148
+ }, { accounts: {
149
+ payer, market, juniorMint, cohort,
150
+ tokenMetadata: deriveTokenMetadataAddress(juniorMint)[0], sysvarInstructions: SYSVAR_INSTRUCTIONS_PUBKEY, tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
151
+ previousCohort: first ? null : deriveJuniorCohortAddress(market, state.juniorMint, this.program.programId)[0],
152
+ token2022Program: TOKEN_2022_PROGRAM_ID, systemProgram: SystemProgram.programId,
153
+ } });
154
+ const hook = await this.write.initializeLpTransferHookInstruction({ payer, market, lpMint: juniorMint, tokenKind: "junior" });
155
+ return { juniorMint, cohort, generation, instructions: [initialize, hook], transaction: new Transaction().add(initialize, hook) };
156
+ }
157
+
158
+ async convert(params: { market: AddressLike; owner: AddressLike; action: TrancheAction }) {
159
+ const market = address(params.market), owner = address(params.owner);
160
+ const state = await this.program.account.market.fetch(market);
161
+ if (state.juniorMint.equals(PublicKey.default)) throw new Error("Initialize the junior mint first");
162
+ const seniorMint = state.ylpMint, juniorMint = state.juniorMint;
163
+ const ownerSenior = getAssociatedTokenAddressSync(seniorMint, owner, true, TOKEN_2022_PROGRAM_ID);
164
+ const ownerJunior = getAssociatedTokenAddressSync(juniorMint, owner, true, TOKEN_2022_PROGRAM_ID);
165
+ const exit = deriveJuniorExitAddress(market, owner, juniorMint, this.program.programId)[0];
166
+ const action = params.action.kind === "enter"
167
+ ? { enter: { seniorAmount: governanceIntegerBN(params.action.seniorAmount, "seniorAmount"), minimumJunior: governanceIntegerBN(params.action.minimumJunior, "minimumJunior") } }
168
+ : params.action.kind === "requestExit"
169
+ ? { requestExit: { additionalJunior: governanceIntegerBN(params.action.additionalJunior, "additionalJunior") } }
170
+ : params.action.kind === "convertExit"
171
+ ? { convertExit: { minimumSenior: governanceIntegerBN(params.action.minimumSenior, "minimumSenior") } }
172
+ : { cancelExit: {} };
173
+ const ix = await this.write.instruction("convertTranche", action, { accounts: {
174
+ owner, market, seniorMint, juniorMint, ownerSenior, ownerJunior, exit,
175
+ seniorBaseYield: deriveYieldAccountAddress(market, owner, seniorMint, state.baseSide.assetMint, "ylp", this.program.programId)[0],
176
+ seniorQuoteYield: deriveYieldAccountAddress(market, owner, seniorMint, state.quoteSide.assetMint, "ylp", this.program.programId)[0],
177
+ juniorBaseYield: deriveYieldAccountAddress(market, owner, juniorMint, state.baseSide.assetMint, "junior", this.program.programId)[0],
178
+ juniorQuoteYield: deriveYieldAccountAddress(market, owner, juniorMint, state.quoteSide.assetMint, "junior", this.program.programId)[0],
179
+ token2022Program: TOKEN_2022_PROGRAM_ID, systemProgram: SystemProgram.programId,
180
+ } });
181
+ const instructions = [
182
+ createAssociatedTokenAccountIdempotentInstruction(owner, ownerSenior, owner, seniorMint, TOKEN_2022_PROGRAM_ID),
183
+ createAssociatedTokenAccountIdempotentInstruction(owner, ownerJunior, owner, juniorMint, TOKEN_2022_PROGRAM_ID), ix,
184
+ ];
185
+ return { instructions, transaction: new Transaction().add(...instructions), exit, seniorMint, juniorMint };
186
+ }
187
+ }