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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +1085 -26
  2. package/dist/amounts.d.ts +9 -0
  3. package/dist/amounts.d.ts.map +1 -0
  4. package/dist/amounts.js +10 -0
  5. package/dist/amounts.js.map +1 -0
  6. package/dist/constants.d.ts +80 -33
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +175 -64
  9. package/dist/constants.js.map +1 -1
  10. package/dist/delegate.d.ts +94 -0
  11. package/dist/delegate.d.ts.map +1 -0
  12. package/dist/delegate.js +131 -0
  13. package/dist/delegate.js.map +1 -0
  14. package/dist/dusk.d.ts +14 -0
  15. package/dist/dusk.d.ts.map +1 -1
  16. package/dist/dusk.js +22 -0
  17. package/dist/dusk.js.map +1 -1
  18. package/dist/get.d.ts +3285 -237
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +140 -71
  21. package/dist/get.js.map +1 -1
  22. package/dist/governance-client.d.ts +169 -0
  23. package/dist/governance-client.d.ts.map +1 -0
  24. package/dist/governance-client.js +146 -0
  25. package/dist/governance-client.js.map +1 -0
  26. package/dist/governance.d.ts +313 -0
  27. package/dist/governance.d.ts.map +1 -0
  28. package/dist/governance.js +902 -0
  29. package/dist/governance.js.map +1 -0
  30. package/dist/hash.d.ts +9 -0
  31. package/dist/hash.d.ts.map +1 -0
  32. package/dist/hash.js +16 -0
  33. package/dist/hash.js.map +1 -0
  34. package/dist/hlp-liquidation-client.d.ts +106 -0
  35. package/dist/hlp-liquidation-client.d.ts.map +1 -0
  36. package/dist/hlp-liquidation-client.js +150 -0
  37. package/dist/hlp-liquidation-client.js.map +1 -0
  38. package/dist/idl_delegate.d.ts +3 -0
  39. package/dist/idl_delegate.d.ts.map +1 -0
  40. package/dist/idl_delegate.js +3 -0
  41. package/dist/idl_delegate.js.map +1 -0
  42. package/dist/idl_delegate.json +6119 -0
  43. package/dist/idl_v2.json +18372 -6121
  44. package/dist/index.d.ts +23 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +23 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interest-accounting.d.ts +49 -0
  49. package/dist/interest-accounting.d.ts.map +1 -0
  50. package/dist/interest-accounting.js +72 -0
  51. package/dist/interest-accounting.js.map +1 -0
  52. package/dist/leverage-actions.d.ts +122 -0
  53. package/dist/leverage-actions.d.ts.map +1 -0
  54. package/dist/leverage-actions.js +228 -0
  55. package/dist/leverage-actions.js.map +1 -0
  56. package/dist/leverage-margins.d.ts +12 -0
  57. package/dist/leverage-margins.d.ts.map +1 -0
  58. package/dist/leverage-margins.js +45 -0
  59. package/dist/leverage-margins.js.map +1 -0
  60. package/dist/leverage-preview.d.ts +587 -0
  61. package/dist/leverage-preview.d.ts.map +1 -0
  62. package/dist/leverage-preview.js +89 -0
  63. package/dist/leverage-preview.js.map +1 -0
  64. package/dist/liquidation-client.d.ts +230 -0
  65. package/dist/liquidation-client.d.ts.map +1 -0
  66. package/dist/liquidation-client.js +239 -0
  67. package/dist/liquidation-client.js.map +1 -0
  68. package/dist/liquidation.d.ts +78 -0
  69. package/dist/liquidation.d.ts.map +1 -0
  70. package/dist/liquidation.js +122 -0
  71. package/dist/liquidation.js.map +1 -0
  72. package/dist/lp-naming.d.ts +43 -0
  73. package/dist/lp-naming.d.ts.map +1 -0
  74. package/dist/lp-naming.js +81 -0
  75. package/dist/lp-naming.js.map +1 -0
  76. package/dist/lp-vanity.d.ts +33 -0
  77. package/dist/lp-vanity.d.ts.map +1 -0
  78. package/dist/lp-vanity.js +94 -0
  79. package/dist/lp-vanity.js.map +1 -0
  80. package/dist/market-bootstrap.d.ts +109 -0
  81. package/dist/market-bootstrap.d.ts.map +1 -0
  82. package/dist/market-bootstrap.js +158 -0
  83. package/dist/market-bootstrap.js.map +1 -0
  84. package/dist/market-launch.d.ts +45 -0
  85. package/dist/market-launch.d.ts.map +1 -0
  86. package/dist/market-launch.js +76 -0
  87. package/dist/market-launch.js.map +1 -0
  88. package/dist/oracle.d.ts +46 -0
  89. package/dist/oracle.d.ts.map +1 -0
  90. package/dist/oracle.js +103 -0
  91. package/dist/oracle.js.map +1 -0
  92. package/dist/preview.d.ts +39 -1
  93. package/dist/preview.d.ts.map +1 -1
  94. package/dist/preview.js +12 -0
  95. package/dist/preview.js.map +1 -1
  96. package/dist/protection.d.ts +48 -0
  97. package/dist/protection.d.ts.map +1 -0
  98. package/dist/protection.js +88 -0
  99. package/dist/protection.js.map +1 -0
  100. package/dist/referral.d.ts +28 -28
  101. package/dist/referral.d.ts.map +1 -1
  102. package/dist/referral.js +41 -33
  103. package/dist/referral.js.map +1 -1
  104. package/dist/risk-pricing.d.ts +14 -0
  105. package/dist/risk-pricing.d.ts.map +1 -0
  106. package/dist/risk-pricing.js +25 -0
  107. package/dist/risk-pricing.js.map +1 -0
  108. package/dist/simulation.d.ts +45 -0
  109. package/dist/simulation.d.ts.map +1 -0
  110. package/dist/simulation.js +106 -0
  111. package/dist/simulation.js.map +1 -0
  112. package/dist/tranche-client.d.ts +121 -0
  113. package/dist/tranche-client.d.ts.map +1 -0
  114. package/dist/tranche-client.js +185 -0
  115. package/dist/tranche-client.js.map +1 -0
  116. package/dist/transfer-fees.d.ts +46 -0
  117. package/dist/transfer-fees.d.ts.map +1 -0
  118. package/dist/transfer-fees.js +76 -0
  119. package/dist/transfer-fees.js.map +1 -0
  120. package/dist/type-aliases.d.ts +271 -30
  121. package/dist/type-aliases.d.ts.map +1 -1
  122. package/dist/types_delegate.d.ts +6126 -0
  123. package/dist/types_delegate.d.ts.map +1 -0
  124. package/dist/types_delegate.js +2 -0
  125. package/dist/types_delegate.js.map +1 -0
  126. package/dist/types_v2.d.ts +18105 -5854
  127. package/dist/types_v2.d.ts.map +1 -1
  128. package/dist/virtual-book/index.d.ts +4 -0
  129. package/dist/virtual-book/index.d.ts.map +1 -0
  130. package/dist/virtual-book/index.js +4 -0
  131. package/dist/virtual-book/index.js.map +1 -0
  132. package/dist/virtual-book/market.d.ts +608 -0
  133. package/dist/virtual-book/market.d.ts.map +1 -0
  134. package/dist/virtual-book/market.js +59 -0
  135. package/dist/virtual-book/market.js.map +1 -0
  136. package/dist/virtual-book/projection.d.ts +44 -0
  137. package/dist/virtual-book/projection.d.ts.map +1 -0
  138. package/dist/virtual-book/projection.js +229 -0
  139. package/dist/virtual-book/projection.js.map +1 -0
  140. package/dist/virtual-book/quotes.d.ts +1241 -0
  141. package/dist/virtual-book/quotes.d.ts.map +1 -0
  142. package/dist/virtual-book/quotes.js +233 -0
  143. package/dist/virtual-book/quotes.js.map +1 -0
  144. package/dist/write.d.ts +584 -14
  145. package/dist/write.d.ts.map +1 -1
  146. package/dist/write.js +1371 -47
  147. package/dist/write.js.map +1 -1
  148. package/dist/yield-client.d.ts +51 -0
  149. package/dist/yield-client.d.ts.map +1 -0
  150. package/dist/yield-client.js +98 -0
  151. package/dist/yield-client.js.map +1 -0
  152. package/package.json +9 -2
  153. package/src/amounts.ts +13 -0
  154. package/src/constants.ts +276 -111
  155. package/src/delegate.ts +238 -0
  156. package/src/dusk.ts +28 -0
  157. package/src/get.ts +267 -90
  158. package/src/governance-client.ts +234 -0
  159. package/src/governance.ts +1422 -0
  160. package/src/hash.ts +15 -0
  161. package/src/hlp-liquidation-client.ts +195 -0
  162. package/src/idl_delegate.json +6119 -0
  163. package/src/idl_delegate.ts +3 -0
  164. package/src/idl_v2.json +18372 -6121
  165. package/src/index.ts +31 -0
  166. package/src/interest-accounting.ts +85 -0
  167. package/src/leverage-actions.ts +216 -0
  168. package/src/leverage-margins.ts +48 -0
  169. package/src/leverage-preview.ts +86 -0
  170. package/src/liquidation-client.ts +297 -0
  171. package/src/liquidation.ts +137 -0
  172. package/src/lp-naming.ts +127 -0
  173. package/src/lp-vanity.ts +135 -0
  174. package/src/market-bootstrap.ts +273 -0
  175. package/src/market-launch.ts +103 -0
  176. package/src/oracle.ts +120 -0
  177. package/src/preview.ts +53 -1
  178. package/src/protection.ts +112 -0
  179. package/src/referral.ts +71 -71
  180. package/src/risk-pricing.ts +28 -0
  181. package/src/simulation.ts +169 -0
  182. package/src/tranche-client.ts +187 -0
  183. package/src/transfer-fees.ts +99 -0
  184. package/src/type-aliases.ts +280 -30
  185. package/src/types_delegate.ts +6125 -0
  186. package/src/types_v2.ts +18372 -6121
  187. package/src/virtual-book/index.ts +3 -0
  188. package/src/virtual-book/market.ts +76 -0
  189. package/src/virtual-book/projection.ts +265 -0
  190. package/src/virtual-book/quotes.ts +308 -0
  191. package/src/write.ts +2394 -67
  192. package/src/yield-client.ts +117 -0
package/src/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
+ }
package/src/referral.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  import {
2
- createAssociatedTokenAccountIdempotentInstruction,
3
2
  createTransferCheckedWithTransferHookInstruction,
4
- getAssociatedTokenAddressSync,
5
3
  getMint,
6
4
  getTransferHook,
7
5
  TOKEN_2022_PROGRAM_ID,
@@ -12,52 +10,72 @@ import {
12
10
  type AccountMeta,
13
11
  type Commitment,
14
12
  type Connection,
15
- type TransactionInstruction,
16
13
  } from "@solana/web3.js";
17
14
 
18
15
  import { address, type AddressLike } from "./address.js";
19
- import { deriveReferralProfileAddress } from "./constants.js";
16
+ import {
17
+ deriveReferralAccrualAddress,
18
+ deriveReferralPartnerAddress,
19
+ } from "./constants.js";
20
20
 
21
- export const DEFAULT_REFERRAL_ORIGINATION_FEE_BPS = 10;
22
- export const MAX_REFERRAL_ORIGINATION_FEE_BPS = 25;
21
+ export const REFERRAL_BPS_DENOMINATOR = 10_000;
22
+ export const MAX_REFERRAL_INTEREST_SHARE_BPS = REFERRAL_BPS_DENOMINATOR;
23
23
 
24
24
  export type IntegerLike = bigint | number | string | { toString(): string };
25
25
 
26
- export interface ReferralFeeQuote {
27
- requestedPrincipal: bigint;
28
- configuredFeeBps: number;
29
- feeDebit: bigint;
30
- grossDebt: bigint;
26
+ export interface ReferralInterestQuote {
27
+ interestPaid: bigint;
28
+ interestVaultCredit: bigint;
29
+ protocolInterestRevenue: bigint;
30
+ interestShareBps: number;
31
+ referralAmount: bigint;
32
+ }
33
+
34
+ export function referralBindingInterestShareBps(params: {
35
+ configuredShareBps: number;
36
+ maxShareBps: number;
37
+ active?: boolean;
38
+ }): number {
39
+ assertReferralInterestShareBps(params.configuredShareBps);
40
+ assertReferralInterestShareBps(params.maxShareBps);
41
+ if (params.active === false) throw new Error("Referral partner is inactive");
42
+ return Math.min(params.configuredShareBps, params.maxShareBps);
31
43
  }
32
44
 
33
- export function quoteReferralOriginationFee(
34
- requestedPrincipal: IntegerLike,
35
- configuredFeeBps: number
36
- ): ReferralFeeQuote {
37
- assertReferralFeeBps(configuredFeeBps);
38
- const requested = BigInt(requestedPrincipal.toString());
39
- if (requested < 0n) {
40
- throw new Error("requestedPrincipal must be non-negative");
45
+ export function quoteReferralInterestShare(params: {
46
+ interestPaid: IntegerLike;
47
+ interestVaultCredit?: IntegerLike;
48
+ protocolInterestBps: number;
49
+ interestShareBps: number;
50
+ }): ReferralInterestQuote {
51
+ assertBps(params.protocolInterestBps, "protocol interest share");
52
+ assertReferralInterestShareBps(params.interestShareBps);
53
+ const interestPaid = BigInt(params.interestPaid.toString());
54
+ if (interestPaid < 0n) throw new Error("interestPaid must be non-negative");
55
+ const interestVaultCredit = BigInt(
56
+ (params.interestVaultCredit ?? params.interestPaid).toString()
57
+ );
58
+ if (interestVaultCredit < 0n || interestVaultCredit > interestPaid) {
59
+ throw new Error("interestVaultCredit must be between 0 and interestPaid");
41
60
  }
42
- const feeDebit = (requested * BigInt(configuredFeeBps) + 9_999n) / 10_000n;
61
+
62
+ const protocolInterestRevenue =
63
+ (interestVaultCredit * BigInt(params.protocolInterestBps)) /
64
+ BigInt(REFERRAL_BPS_DENOMINATOR);
65
+ const referralAmount =
66
+ (protocolInterestRevenue * BigInt(params.interestShareBps)) /
67
+ BigInt(REFERRAL_BPS_DENOMINATOR);
43
68
  return {
44
- requestedPrincipal: requested,
45
- configuredFeeBps,
46
- feeDebit,
47
- grossDebt: requested + feeDebit,
69
+ interestPaid,
70
+ interestVaultCredit,
71
+ protocolInterestRevenue,
72
+ interestShareBps: params.interestShareBps,
73
+ referralAmount,
48
74
  };
49
75
  }
50
76
 
51
- export function assertReferralFeeBps(configuredFeeBps: number): void {
52
- if (
53
- !Number.isInteger(configuredFeeBps) ||
54
- configuredFeeBps < 0 ||
55
- configuredFeeBps > MAX_REFERRAL_ORIGINATION_FEE_BPS
56
- ) {
57
- throw new Error(
58
- `referral origination fee must be between 0 and ${MAX_REFERRAL_ORIGINATION_FEE_BPS} bps`
59
- );
60
- }
77
+ export function assertReferralInterestShareBps(shareBps: number): void {
78
+ assertBps(shareBps, "referral interest share");
61
79
  }
62
80
 
63
81
  export async function tokenProgramForMint(
@@ -76,50 +94,32 @@ export async function tokenProgramForMint(
76
94
  throw new Error(`Unsupported mint owner: ${account.owner.toBase58()}`);
77
95
  }
78
96
 
79
- export interface ReferralVaultAddresses {
80
- referralProfile: PublicKey;
81
- referralVault: PublicKey;
82
- tokenProgram: PublicKey;
97
+ export interface ReferralAccrualAddresses {
98
+ referralPartner: PublicKey;
99
+ referralAccrual: PublicKey;
83
100
  }
84
101
 
85
- export async function referralVaultAddresses(params: {
86
- connection: Connection;
102
+ export function referralAccrualAddresses(params: {
87
103
  referrer: AddressLike;
88
- mint: AddressLike;
89
- commitment?: Commitment;
90
- }): Promise<ReferralVaultAddresses> {
104
+ market: AddressLike;
105
+ assetMint: AddressLike;
106
+ }): ReferralAccrualAddresses {
91
107
  const referrer = address(params.referrer);
92
- const mint = address(params.mint);
93
- const [referralProfile] = deriveReferralProfileAddress(referrer);
94
- const tokenProgram = await tokenProgramForMint(params.connection, mint, params.commitment);
95
- const referralVault = getAssociatedTokenAddressSync(
96
- mint,
97
- referralProfile,
98
- true,
99
- tokenProgram
108
+ const market = address(params.market);
109
+ const assetMint = address(params.assetMint);
110
+ const [referralPartner] = deriveReferralPartnerAddress(referrer);
111
+ const [referralAccrual] = deriveReferralAccrualAddress(
112
+ referralPartner,
113
+ market,
114
+ assetMint
100
115
  );
101
- return { referralProfile, referralVault, tokenProgram };
116
+ return { referralPartner, referralAccrual };
102
117
  }
103
118
 
104
- export async function buildReferralVaultSetupInstruction(params: {
105
- connection: Connection;
106
- payer: AddressLike;
107
- referrer: AddressLike;
108
- mint: AddressLike;
109
- commitment?: Commitment;
110
- }): Promise<ReferralVaultAddresses & { instruction: TransactionInstruction }> {
111
- const mint = address(params.mint);
112
- const addresses = await referralVaultAddresses(params);
113
- return {
114
- ...addresses,
115
- instruction: createAssociatedTokenAccountIdempotentInstruction(
116
- address(params.payer),
117
- addresses.referralVault,
118
- addresses.referralProfile,
119
- mint,
120
- addresses.tokenProgram
121
- ),
122
- };
119
+ function assertBps(value: number, label: string): void {
120
+ if (!Number.isInteger(value) || value < 0 || value > REFERRAL_BPS_DENOMINATOR) {
121
+ throw new Error(`${label} must be between 0 and ${REFERRAL_BPS_DENOMINATOR} bps`);
122
+ }
123
123
  }
124
124
 
125
125
  export interface TransferHookTransfer {
@@ -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
+ }