@lavarage/sdk 7.5.6 → 7.5.8

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 (90) hide show
  1. package/.DS_Store +0 -0
  2. package/.gitignore +18 -1
  3. package/README.md +33 -0
  4. package/dist/index.d.mts +1396 -1
  5. package/dist/index.d.ts +1396 -1
  6. package/dist/index.js +287 -3
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +287 -3
  9. package/dist/index.mjs.map +1 -1
  10. package/docs/.nojekyll +1 -0
  11. package/docs/assets/hierarchy.js +1 -0
  12. package/docs/assets/highlight.css +92 -0
  13. package/docs/assets/icons.js +18 -0
  14. package/docs/assets/icons.svg +1 -0
  15. package/docs/assets/main.js +60 -0
  16. package/docs/assets/navigation.js +1 -0
  17. package/docs/assets/search.js +1 -0
  18. package/docs/assets/style.css +1633 -0
  19. package/docs/functions/borrowV1.html +1 -0
  20. package/docs/functions/borrowV2.html +1 -0
  21. package/docs/functions/closePositionEvm.html +9 -0
  22. package/docs/functions/closeTradeV1.html +17 -0
  23. package/docs/functions/closeTradeV2.html +18 -0
  24. package/docs/functions/createTpDelegate.html +17 -0
  25. package/docs/functions/getActiveLoanCountEvm.html +8 -0
  26. package/docs/functions/getActiveLoansBatchEvm.html +10 -0
  27. package/docs/functions/getAllPositions.html +17 -0
  28. package/docs/functions/getAvailableExposureEvm.html +9 -0
  29. package/docs/functions/getClosedPositions.html +7 -0
  30. package/docs/functions/getClosedPositionsEvm.html +9 -0
  31. package/docs/functions/getCollateralExposureEvm.html +9 -0
  32. package/docs/functions/getCollateralInfoEvm.html +9 -0
  33. package/docs/functions/getDelegateAccounts.html +13 -0
  34. package/docs/functions/getLiquidatedPositions.html +13 -0
  35. package/docs/functions/getLiquidatedPositionsEvm.html +9 -0
  36. package/docs/functions/getLoanEvm.html +9 -0
  37. package/docs/functions/getLoansByBorrowerEvm.html +9 -0
  38. package/docs/functions/getOffers.html +7 -0
  39. package/docs/functions/getOffersEvm.html +9 -0
  40. package/docs/functions/getOpenPositions.html +11 -0
  41. package/docs/functions/getOpeningFeeEvm.html +8 -0
  42. package/docs/functions/getPda.html +8 -0
  43. package/docs/functions/getPositionAccountPDA.html +9 -0
  44. package/docs/functions/getPositionsEvm.html +8 -0
  45. package/docs/functions/getProfitFeeEvm.html +8 -0
  46. package/docs/functions/getTokenBalanceEvm.html +8 -0
  47. package/docs/functions/getUserLoansEvm.html +9 -0
  48. package/docs/functions/lending.addToWithdrawalAccessList.html +1 -0
  49. package/docs/functions/lending.createOffer.html +15 -0
  50. package/docs/functions/lending.depositFunds.html +17 -0
  51. package/docs/functions/lending.getNodeWalletPDA.html +9 -0
  52. package/docs/functions/lending.getTradingPoolPDA.html +9 -0
  53. package/docs/functions/lending.getWithdrawalAccessList.html +1 -0
  54. package/docs/functions/lending.getWithdrawalAccessListPDA.html +1 -0
  55. package/docs/functions/lending.removeFromWithdrawalAccessList.html +1 -0
  56. package/docs/functions/lending.updateInterestRate.html +13 -0
  57. package/docs/functions/lending.updateMaxBorrow.html +13 -0
  58. package/docs/functions/lending.updateMaxExposure.html +13 -0
  59. package/docs/functions/lending.updateOffer.html +19 -0
  60. package/docs/functions/lending.withdrawFunds.html +20 -0
  61. package/docs/functions/lending.withdrawFundsV1.html +16 -0
  62. package/docs/functions/lending.withdrawFundsV2.html +19 -0
  63. package/docs/functions/liquidatePositionEvm.html +6 -0
  64. package/docs/functions/mergePositionV2.html +13 -0
  65. package/docs/functions/modifyTpDelegate.html +17 -0
  66. package/docs/functions/openPositionEvm.html +9 -0
  67. package/docs/functions/openTradeV1.html +26 -0
  68. package/docs/functions/openTradeV2.html +29 -0
  69. package/docs/functions/partialRepayV1.html +10 -0
  70. package/docs/functions/partialRepayV2.html +10 -0
  71. package/docs/functions/removeTpDelegate.html +13 -0
  72. package/docs/functions/splitPositionV2.html +13 -0
  73. package/docs/functions/updateMaxLendPerTokenBatchEvm.html +9 -0
  74. package/docs/hierarchy.html +1 -0
  75. package/docs/index.html +3 -0
  76. package/docs/modules/IDLV2.html +2 -0
  77. package/docs/modules/lending.html +1 -0
  78. package/docs/modules.html +4 -0
  79. package/docs/types/IDLV2.Lavarage.html +8 -0
  80. package/docs/types/Lavarage.html +8 -0
  81. package/docs/variables/IDL.html +1 -0
  82. package/docs/variables/IDLV2.IDL.html +1 -0
  83. package/docs-readme.md +5 -0
  84. package/evm.ts +308 -0
  85. package/idl/lavarage.ts +126 -0
  86. package/idl/lavaragev2.ts +166 -0
  87. package/index.ts +924 -113
  88. package/lending.ts +330 -1
  89. package/package.json +8 -5
  90. package/typedoc.json +23 -0
package/index.ts CHANGED
@@ -1,3 +1,17 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * @module Lavarage SDK
4
+ *
5
+ * The main entry point for the Lavarage SDK, providing functionality for interacting
6
+ * with the Lavarage DeFi protocol on both Solana and EVM chains.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { getPda, getPositionAccountPDA } from '@lavarage/sdk';
11
+ * import * as lending from '@lavarage/sdk/lending';
12
+ * ```
13
+ */
14
+
1
15
  import { BN, Program, ProgramAccount } from "@coral-xyz/anchor";
2
16
  import { Lavarage } from "./idl/lavarage";
3
17
  import { Lavarage as LavarageV2 } from "./idl/lavaragev2";
@@ -32,6 +46,7 @@ import {
32
46
  export * from "./evm";
33
47
  export * as lending from "./lending";
34
48
 
49
+
35
50
  type OptionalRPCResults = {
36
51
  addressLookupTableAccounts?: AccountInfo<Buffer>[];
37
52
  latestBlockhash?: string;
@@ -39,11 +54,50 @@ type OptionalRPCResults = {
39
54
  quoteMintAccountInfo?: AccountInfo<Buffer>;
40
55
  }
41
56
  const REFFERAL_VAULT_PROGRAM_ID = new PublicKey("FFe8xWs9iBdWB6vsxg8yBLirZHsbACFNbXqAM4K3fPPB");
57
+
58
+
59
+
60
+ /**
61
+ * Derives a Program Derived Address (PDA) for the given seed(s) and program ID
62
+ *
63
+ * @group Traders
64
+ * @category Utilities
65
+ *
66
+ * @param seed - Single buffer or array of buffers to use as seeds
67
+ * @param programId - The Solana program ID to derive the PDA from
68
+ * @returns The derived public key address
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * const seed = Buffer.from("position");
73
+ * const pda = getPda(seed, programId);
74
+ * ```
75
+ */
42
76
  export function getPda(seed: Buffer | Buffer[], programId: PublicKey) {
43
77
  const seedsBuffer = Array.isArray(seed) ? seed : [seed];
44
78
 
45
79
  return PublicKey.findProgramAddressSync(seedsBuffer, programId)[0];
46
80
  }
81
+ /**
82
+ * Generates a Position Account PDA for a specific offer and user
83
+ *
84
+ * @group Traders
85
+ * @category Utilities
86
+ *
87
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
88
+ * @param offer - The offer program account
89
+ * @param seed - Additional seed for uniqueness (typically a public key)
90
+ * @returns The Position Account PDA public key
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const positionPDA = getPositionAccountPDA(
95
+ * lavarageProgram,
96
+ * offerAccount,
97
+ * userPublicKey
98
+ * );
99
+ * ```
100
+ */
47
101
 
48
102
  export function getPositionAccountPDA(
49
103
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>,
@@ -60,6 +114,20 @@ export function getPositionAccountPDA(
60
114
  lavarageProgram.programId
61
115
  );
62
116
  }
117
+ /**
118
+ * Gets an associated token account or creates the instruction to create one if it doesn't exist
119
+ *
120
+ * @group Solana
121
+ * @category Token Accounts
122
+ * @internal
123
+ *
124
+ * @param lavarageProgram - The Lavarage program instance
125
+ * @param ownerPublicKey - The owner of the token account
126
+ * @param tokenAddress - The mint address of the token
127
+ * @param tokenProgram - Optional token program ID (defaults to TOKEN_PROGRAM_ID)
128
+ * @param confirmCreatedAddresses - Optional array of addresses to confirm creation of token accounts
129
+ * @returns Object containing the account address and creation instruction
130
+ */
63
131
 
64
132
  async function getTokenAccountOrCreateIfNotExists(
65
133
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>,
@@ -101,15 +169,72 @@ async function getTokenAccountOrCreateIfNotExists(
101
169
  instruction,
102
170
  };
103
171
  }
104
-
172
+ /**
173
+ * Re-exports all types and interfaces from the Lavarage V1 IDL
174
+ * @group Solana
175
+ */
105
176
  export * from "./idl/lavarage";
177
+ /**
178
+ * Namespace containing all types and interfaces from the Lavarage V2 IDL
179
+ * @group Solana
180
+ */
106
181
  export * as IDLV2 from "./idl/lavaragev2";
182
+ /**
183
+ * Fetches all available lending offers from the Lavarage protocol
184
+ *
185
+ * @group Traders
186
+ * @category Queries
187
+ *
188
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
189
+ * @returns Promise resolving to an array of all pool/offer accounts
190
+ *
191
+ * @example
192
+ * ```typescript
193
+ * // Fetch all offers
194
+ * const offers = await getOffers(lavarageProgram);
195
+ *
196
+ * // Process each offer
197
+ * offers.forEach(offer => {
198
+ * console.log('Offer:', offer.publicKey.toString());
199
+ * console.log('Data:', offer.account);
200
+ * });
201
+ * ```
202
+ */
107
203
 
108
204
  export const getOffers = (
109
205
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>
110
206
  ) => {
111
207
  return lavarageProgram.account.pool.all();
112
208
  };
209
+ /**
210
+ * Fetches all open positions from the Lavarage protocol
211
+ *
212
+ * This function filters for positions with a specific data structure size (178 bytes)
213
+ * and checks for positions that are currently open.
214
+ *
215
+ * @group Traders
216
+ * @category Queries
217
+ *
218
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
219
+ * @returns Promise resolving to an array of open position accounts
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * // Get all open positions
224
+ * const openPositions = await getOpenPositions(lavarageProgram);
225
+ *
226
+ * console.log(`Found ${openPositions.length} open positions`);
227
+ *
228
+ * // Filter positions by user
229
+ * const userPositions = openPositions.filter(pos =>
230
+ * pos.account.owner.equals(userPublicKey)
231
+ * );
232
+ * ```
233
+ *
234
+ * @remarks
235
+ * The function query only open positions
236
+ * without fetching closed or liquidated positions.
237
+ */
113
238
 
114
239
  export const getOpenPositions = (
115
240
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>
@@ -124,6 +249,30 @@ export const getOpenPositions = (
124
249
  },
125
250
  ]);
126
251
  };
252
+ /**
253
+ * Fetches all closed positions from the Lavarage protocol
254
+ *
255
+ *
256
+ * @group Traders
257
+ * @category Queries
258
+ *
259
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
260
+ * @returns Promise resolving to an array of all closed position accounts from all three states
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * // Get all closed positions
265
+ * const closedPositions = await getClosedPositions(lavarageProgram);
266
+ *
267
+ * console.log(`Found ${closedPositions.length} closed positions`);
268
+ *
269
+ * // Filter by specific user
270
+ * const userClosedPositions = closedPositions.filter(pos =>
271
+ * pos.account.owner.equals(userPublicKey)
272
+ * );
273
+ * ```
274
+ *
275
+ */
127
276
 
128
277
  export const getClosedPositions = async (
129
278
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>
@@ -171,6 +320,36 @@ export const getClosedPositions = async (
171
320
  ])
172
321
  );
173
322
  };
323
+ /**
324
+ * Fetches all liquidated positions from the Lavarage protocol
325
+ *
326
+ * Liquidated positions are positions that were forcefully closed due to
327
+ * insufficient collateral or health factor falling below the threshold.
328
+ *
329
+ * @group Traders
330
+ * @category Queries
331
+ *
332
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
333
+ * @returns Promise resolving to an array of liquidated position accounts
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * // Get all liquidated positions
338
+ * const liquidatedPositions = await getLiquidatedPositions(lavarageProgram);
339
+ *
340
+ * console.log(`Found ${liquidatedPositions.length} liquidated positions`);
341
+ *
342
+ * // Analyze liquidation data
343
+ * liquidatedPositions.forEach(pos => {
344
+ * console.log('Position:', pos.publicKey.toString());
345
+ * console.log('Liquidated amount:', pos.account.amount);
346
+ * });
347
+ * ```
348
+ *
349
+ *
350
+ * @see {@link getClosedPositions} - For other types of closed positions
351
+ * @see {@link getOpenPositions} - For currently active positions
352
+ */
174
353
 
175
354
  export const getLiquidatedPositions = (
176
355
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>
@@ -188,6 +367,40 @@ export const getLiquidatedPositions = (
188
367
  },
189
368
  ]);
190
369
  };
370
+ /**
371
+ * Fetches all positions from the Lavarage protocol
372
+ *
373
+ * This function retrieves all position accounts regardless of their state (open, closed, liquidated).
374
+ *
375
+ * @group Traders
376
+ * @category Queries
377
+ *
378
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
379
+ * @returns Promise resolving to an array of position accounts
380
+ *
381
+ * @example
382
+ * ```typescript
383
+ * // Get all positions
384
+ * const allPositions = await getAllPositions(lavarageProgram);
385
+ *
386
+ * console.log(`Found ${allPositions.length} total positions`);
387
+ *
388
+ * // Filter positions by user
389
+ * const userPositions = allPositions.filter(pos =>
390
+ * pos.account.owner.equals(userPublicKey)
391
+ * );
392
+ * ```
393
+ *
394
+ * @remarks
395
+ * Unlike other position query functions, this returns ALL positions without
396
+ * filtering by status. Use more specific functions like `getOpenPositions`,
397
+ * `getClosedPositions`, or `getLiquidatedPositions` if you only need positions
398
+ * with a specific status.
399
+ *
400
+ * @see {@link getOpenPositions} - For only open positions
401
+ * @see {@link getClosedPositions} - For only closed positions
402
+ * @see {@link getLiquidatedPositions} - For only liquidated positions
403
+ */
191
404
 
192
405
  export const getAllPositions = (
193
406
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>
@@ -630,6 +843,57 @@ export const borrowV2 = async (
630
843
  return tx;
631
844
  };
632
845
 
846
+ /**
847
+ * Opens a leveraged trading position on Lavarage V1
848
+ *
849
+ * This function executes a complete leveraged trade by:
850
+ * 1. Borrowing funds from the lending pool based on leverage
851
+ * 2. Swapping tokens through Jupiter DEX
852
+ * 3. Depositing the swapped tokens as collateral
853
+ *
854
+ * @group Traders
855
+ * @category Trading
856
+ *
857
+ * @param lavarageProgram - The Lavarage V1 program instance
858
+ * @param offer - The lending offer containing terms (interest rate, collateral type, node wallet)
859
+ * @param jupInstruction - Jupiter swap instructions including setup and swap details
860
+ * @param marginSOL - The user's margin amount in SOL (as BN)
861
+ * @param leverage - The leverage multiplier (e.g., 2 for 2x leverage)
862
+ * @param randomSeed - A keypair used to generate unique position account address
863
+ * @param tokenProgram - The SPL token program ID
864
+ * @param partnerFeeRecipient - Optional wallet to receive partner fees
865
+ * @param partnerFeeMarkup - Optional partner fee amount in basis points
866
+ * @param computeBudgetMicroLamports - Optional compute budget for priority fees
867
+ *
868
+ * @returns A versioned transaction ready to be signed and sent
869
+ *
870
+ * @example
871
+ * ```typescript
872
+ * // Open a 2x leveraged position with 1 SOL margin
873
+ * const marginSOL = new BN(1_000_000_000); // 1 SOL in lamports
874
+ * const leverage = 2;
875
+ * const randomSeed = Keypair.generate();
876
+ *
877
+ * const tx = await openTradeV1(
878
+ * lavarageProgram,
879
+ * offerAccount,
880
+ * jupiterInstructions,
881
+ * marginSOL,
882
+ * leverage,
883
+ * randomSeed,
884
+ * TOKEN_PROGRAM_ID
885
+ * );
886
+ *
887
+ * // Sign and send transaction
888
+ * const signature = await sendAndConfirmTransaction(connection, tx, [wallet, randomSeed]);
889
+ * ```
890
+ *
891
+ * @remarks
892
+ * - The function creates token accounts if they don't exist
893
+ *
894
+ * @throws Will throw if token accounts cannot be created or if Jupiter instructions are invalid
895
+ */
896
+
633
897
  export const openTradeV1 = async (
634
898
  lavarageProgram: Program<Lavarage>,
635
899
  offer: ProgramAccount<{
@@ -935,6 +1199,62 @@ export const openTradeV1 = async (
935
1199
  return tx;
936
1200
  };
937
1201
 
1202
+ /**
1203
+ * Opens a leveraged trading position on Lavarage V2
1204
+ *
1205
+ * This function executes a complete leveraged trade similar to V1, but with
1206
+ * enhanced support for multiple quote tokens (not limited to SOL).
1207
+ * The process includes:
1208
+ * 1. Borrowing funds from the lending pool based on leverage
1209
+ * 2. Swapping tokens through Jupiter DEX
1210
+ * 3. Depositing the swapped tokens as collateral
1211
+ *
1212
+ * @group Traders
1213
+ * @category Trading
1214
+ *
1215
+ * @param lavarageProgram - The Lavarage V2 program instance
1216
+ * @param offer - The lending offer containing terms (interest rate, collateral type, node wallet)
1217
+ * @param jupInstruction - Jupiter swap instructions including setup and swap details
1218
+ * @param marginSOL - The user's margin amount in SOL (as BN)
1219
+ * @param leverage - The leverage multiplier (e.g., 2 for 2x leverage)
1220
+ * @param randomSeed - A keypair used to generate unique position account address
1221
+ * @param quoteToken - The quote token mint address (e.g., USDC, USDT, or SOL)
1222
+ * @param tokenProgram - The SPL token program ID for the collateral token
1223
+ * @param partnerFeeRecipient - Optional wallet to receive partner fees
1224
+ * @param partnerFeeMarkup - Optional partner fee amount in basis points
1225
+ * @param computeBudgetMicroLamports - Optional compute budget for priority fees
1226
+ *
1227
+ * @returns A versioned transaction ready to be signed and sent
1228
+ *
1229
+ * @example
1230
+ * ```typescript
1231
+ * // Open a 3x leveraged position with USDC as quote token
1232
+ * const marginSOL = new BN(1_000_000_000); // 1 SOL equivalent
1233
+ * const leverage = 3;
1234
+ * const randomSeed = Keypair.generate();
1235
+ * const usdcMint = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
1236
+ *
1237
+ * const tx = await openTradeV2(
1238
+ * lavarageProgram,
1239
+ * offerAccount,
1240
+ * jupiterInstructions,
1241
+ * marginSOL,
1242
+ * leverage,
1243
+ * randomSeed,
1244
+ * usdcMint, // Quote token
1245
+ * TOKEN_PROGRAM_ID
1246
+ * );
1247
+ *
1248
+ * // Sign and send transaction
1249
+ * const signature = await sendAndConfirmTransaction(connection, tx, [wallet, randomSeed]);
1250
+ * ```
1251
+ *
1252
+ * @remarks
1253
+ * - V2 supports multiple quote tokens while V1 only supports SOL
1254
+ *
1255
+ * @see {@link openTradeV1} - The V1 version limited to SOL as quote token
1256
+ */
1257
+
938
1258
  export const openTradeV2 = async (
939
1259
  lavarageProgram: Program<LavarageV2>,
940
1260
  offer: ProgramAccount<{
@@ -1324,6 +1644,49 @@ export const openTradeV2 = async (
1324
1644
  return tx;
1325
1645
  };
1326
1646
 
1647
+ /**
1648
+ * Creates a take-profit delegate for automated position closing
1649
+ *
1650
+ *
1651
+ * @group Traders
1652
+ * @category Automation
1653
+ *
1654
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
1655
+ * @param position - The position account to set take-profit for
1656
+ * @param tpPrice - The target price at which to take profit (as BN)
1657
+ * @param tpTolerence - Price tolerance/slippage allowed when executing (as BN)
1658
+ * @param prioFee - Priority fee in microlamports for transaction execution
1659
+ * @param quoteToken - The quote token mint address (e.g., USDC, SOL)
1660
+ * @param partnerFeeRecipient - Optional wallet to receive partner fees
1661
+ *
1662
+ * @returns A versioned transaction to create the take-profit delegate
1663
+ *
1664
+ * @example
1665
+ * ```typescript
1666
+ * // Set take-profit at $150 for a position
1667
+ * const position = await getPositionAccount(positionPubkey);
1668
+ * const tpPrice = new BN(150 * 1e6); // $150 with 6 decimals
1669
+ * const tolerance = new BN(1 * 1e6); // $1 tolerance
1670
+ * const prioFee = new BN(100000); // 0.1 SOL priority fee
1671
+ *
1672
+ * const tx = await createTpDelegate(
1673
+ * lavarageProgram,
1674
+ * position,
1675
+ * tpPrice,
1676
+ * tolerance,
1677
+ * prioFee,
1678
+ * usdcMint
1679
+ * );
1680
+ *
1681
+ * // Sign and send
1682
+ * const signature = await sendAndConfirmTransaction(connection, tx, [wallet]);
1683
+ * console.log('Take-profit delegate created:', signature);
1684
+ * ```
1685
+ *
1686
+ * @see {@link modifyTpDelegate} - Modify take-profit settings
1687
+ * @see {@link removeTpDelegate} - Remove take-profit without replacement
1688
+ */
1689
+
1327
1690
  export const createTpDelegate = async (
1328
1691
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>,
1329
1692
  position: ProgramAccount<{
@@ -1390,6 +1753,39 @@ export const createTpDelegate = async (
1390
1753
  return new VersionedTransaction(messageV0);
1391
1754
  };
1392
1755
 
1756
+ /**
1757
+ * Modifies take-profit setting for an existing position.
1758
+ *
1759
+ *
1760
+ * @group Traders
1761
+ * @category Automation
1762
+ *
1763
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
1764
+ * @param position - The position account to modify take-profit for
1765
+ * @param tpPrice - The new target price for take-profit (as BN)
1766
+ * @param tpTolerence - The new price tolerance/slippage allowed (as BN)
1767
+ * @param prioFee - Priority fee in microlamports for transaction execution
1768
+ * @param quoteToken - The quote token mint address (e.g., USDC, SOL)
1769
+ * @param partnerFeeRecipient - Optional wallet to receive partner fees
1770
+ *
1771
+ * @returns Transaction to update the take-profit settings.
1772
+ *
1773
+ * @example
1774
+ * ```typescript
1775
+ * const tx = await modifyTpDelegate(
1776
+ * program,
1777
+ * position,
1778
+ * new BN(160 * 1e6), // New target: $160
1779
+ * new BN(2 * 1e6), // Tolerance: $2
1780
+ * new BN(100000), // Priority fee
1781
+ * usdcMint
1782
+ * );
1783
+ * ```
1784
+ *
1785
+ * @see {@link createTpDelegate} - Initial creation of take-profit
1786
+ * @see {@link removeTpDelegate} - Remove take-profit without replacement
1787
+ */
1788
+
1393
1789
  export const modifyTpDelegate = async (
1394
1790
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>,
1395
1791
  position: ProgramAccount<{
@@ -1466,6 +1862,33 @@ export const modifyTpDelegate = async (
1466
1862
  return new VersionedTransaction(messageV0);
1467
1863
  };
1468
1864
 
1865
+ /**
1866
+ * Removes take-profit settings from a position
1867
+ *
1868
+ * @group Traders
1869
+ * @category Automation
1870
+ *
1871
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
1872
+ * @param position - The position account to remove take-profit from
1873
+ * @param prioFee - Priority fee in microlamports for transaction execution
1874
+ *
1875
+ * @returns Transaction to remove take-profit settings
1876
+ *
1877
+ * @example
1878
+ * ```typescript
1879
+ * const tx = await removeTpDelegate(
1880
+ * lavarageProgram,
1881
+ * position,
1882
+ * new BN(100000) // Priority fee
1883
+ * );
1884
+ *
1885
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
1886
+ * ```
1887
+ *
1888
+ * @see {@link createTpDelegate} - Initial creation of take-profit
1889
+ * @see {@link modifyTpDelegate} - Modify existing take-profit settings
1890
+ */
1891
+
1469
1892
  export const removeTpDelegate = async (
1470
1893
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>,
1471
1894
  position: ProgramAccount<{
@@ -1504,6 +1927,32 @@ export const removeTpDelegate = async (
1504
1927
 
1505
1928
  return new VersionedTransaction(messageV0);
1506
1929
  };
1930
+ /**
1931
+ * Partially repays a position on Lavarage V1
1932
+ *
1933
+ * @group Traders
1934
+ * @category Trading
1935
+ *
1936
+ * @param lavarageProgram - The Lavarage V1 program instance
1937
+ * @param position - The position account to partially repay
1938
+ * @param repaymentBps - Repayment amount in basis points (10000 = 100%)
1939
+ *
1940
+ * @returns Transaction for partial repayment
1941
+ *
1942
+ * @example
1943
+ * ```typescript
1944
+ * // Repay 50% of the position
1945
+ * const tx = await partialRepayV1(
1946
+ * lavarageProgram,
1947
+ * position,
1948
+ * 5000 // 50% in basis points
1949
+ * );
1950
+ *
1951
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
1952
+ * ```
1953
+ *
1954
+ * @see {@link partialRepayV2} - The V2 version supporting multiple quote tokens
1955
+ */
1507
1956
 
1508
1957
  export const partialRepayV1 = async (
1509
1958
  lavarageProgram: Program<Lavarage>,
@@ -1540,6 +1989,32 @@ export const partialRepayV1 = async (
1540
1989
  return new VersionedTransaction(messageV0);
1541
1990
  };
1542
1991
 
1992
+ /**
1993
+ * Partially repays a position on Lavarage V2
1994
+ *
1995
+ * @group Traders
1996
+ * @category Trading
1997
+ *
1998
+ * @param lavarageProgram - The Lavarage V2 program instance
1999
+ * @param position - The position account to partially repay
2000
+ * @param repaymentBps - Repayment amount in basis points (10000 = 100%)
2001
+ *
2002
+ * @returns Transaction for partial repayment
2003
+ *
2004
+ * @example
2005
+ * ```typescript
2006
+ * // Repay 30% of the position
2007
+ * const tx = await partialRepayV2(
2008
+ * lavarageProgram,
2009
+ * position,
2010
+ * 3000 // 30% in basis points
2011
+ * );
2012
+ *
2013
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
2014
+ * ```
2015
+ *
2016
+ * @see {@link partialRepayV1} - The V1 version supporting SOL as quote token
2017
+ */
1543
2018
  export const partialRepayV2 = async (
1544
2019
  lavarageProgram: Program<LavarageV2>,
1545
2020
  position: ProgramAccount<{
@@ -1591,6 +2066,40 @@ export const partialRepayV2 = async (
1591
2066
  return new VersionedTransaction(messageV0);
1592
2067
  };
1593
2068
 
2069
+ /**
2070
+ * Closes a trading position on Lavarage V1
2071
+ *
2072
+ * @group Traders
2073
+ * @category Trading
2074
+ *
2075
+ * @param lavarageProgram - The Lavarage V1 program instance
2076
+ * @param position - The position account to close
2077
+ * @param offer - The offer/pool account associated with the position
2078
+ * @param jupInstruction - Jupiter swap instructions and quote for closing
2079
+ * @param partnerFeeRecipient - Optional wallet to receive partner fees
2080
+ * @param partnerFeeMarkup - Optional partner fee amount in basis points
2081
+ * @param computeBudgetMicroLamports - Optional compute budget for priority fees
2082
+ *
2083
+ * @returns Transaction to close the position
2084
+ *
2085
+ * @example
2086
+ * ```typescript
2087
+ * const jupQuote = await getJupiterQuote(...);
2088
+ * const tx = await closeTradeV1(
2089
+ * lavarageProgram,
2090
+ * position,
2091
+ * offer,
2092
+ * jupQuote,
2093
+ * partnerWallet, // optional
2094
+ * 100, // optional fee in bps
2095
+ * 150000 // optional priority fee
2096
+ * );
2097
+ *
2098
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
2099
+ * ```
2100
+ * @see {@link openTradeV1} - The V1 version for opening positions
2101
+ * @see {@link partialRepayV1} - Partial repayments on V1
2102
+ */
1594
2103
  export const closeTradeV1 = async (
1595
2104
  lavarageProgram: Program<Lavarage>,
1596
2105
  position: ProgramAccount<{
@@ -1890,6 +2399,42 @@ export const closeTradeV1 = async (
1890
2399
  return tx;
1891
2400
  };
1892
2401
 
2402
+ /**
2403
+ * Closes a trading position on Lavarage V2
2404
+ *
2405
+ * @group Traders
2406
+ * @category Trading
2407
+ *
2408
+ * @param lavarageProgram - The Lavarage V2 program instance
2409
+ * @param position - The position account to close
2410
+ * @param offer - The offer/pool account associated with the position
2411
+ * @param jupInstruction - Jupiter swap instructions and quote for closing
2412
+ * @param quoteToken - The quote token mint address for this position
2413
+ * @param partnerFeeRecipient - Optional wallet to receive partner fees
2414
+ * @param partnerFeeMarkup - Optional partner fee amount in basis points
2415
+ * @param computeBudgetMicroLamports - Optional compute budget for priority fees
2416
+ *
2417
+ * @returns Transaction to close the position
2418
+ *
2419
+ * @example
2420
+ * ```typescript
2421
+ * const jupQuote = await getJupiterQuote(...);
2422
+ * const tx = await closeTradeV2(
2423
+ * lavarageProgram,
2424
+ * position,
2425
+ * offer,
2426
+ * jupQuote,
2427
+ * usdcMint, // quote token
2428
+ * partnerWallet, // optional
2429
+ * 100, // optional fee in bps
2430
+ * 150000 // optional priority fee
2431
+ * );
2432
+ *
2433
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
2434
+ * ```
2435
+ * @see {@link openTradeV2} - The V2 version for opening positions
2436
+ * @see {@link partialRepayV2} - Partial repay a V2 position
2437
+ */
1893
2438
  export const closeTradeV2 = async (
1894
2439
  lavarageProgram: Program<LavarageV2>,
1895
2440
  position: ProgramAccount<{
@@ -1919,8 +2464,12 @@ export const closeTradeV2 = async (
1919
2464
  computeBudgetMicroLamports?: number,
1920
2465
  platformFeeRecipient?: PublicKey,
1921
2466
  splitTransactions?: boolean,
2467
+ discountBps?: number,
2468
+ referralBps?: number,
1922
2469
  ) => {
1923
2470
  let partnerFeeMarkupAsPkey;
2471
+ const referralVaultProgram = new Program<UserVault>(userVaultIDL, REFFERAL_VAULT_PROGRAM_ID, lavarageProgram.provider);
2472
+
1924
2473
  if (partnerFeeMarkup) {
1925
2474
  const feeBuffer = Buffer.alloc(8);
1926
2475
  feeBuffer.writeBigUInt64LE(BigInt(partnerFeeMarkup));
@@ -2011,6 +2560,60 @@ export const closeTradeV2 = async (
2011
2560
  const { blockhash } =
2012
2561
  await lavarageProgram.provider.connection.getLatestBlockhash("finalized");
2013
2562
 
2563
+ const useReferral = discountBps !== undefined && referralBps !== undefined;
2564
+
2565
+ // Check if partner fee recipient vault and token account need to be created
2566
+ let partnerFeeRecipientVaultCreateIx: TransactionInstruction | undefined;
2567
+ let partnerFeeRecipientTokenAccountCreateIx: TransactionInstruction | undefined;
2568
+ let userVaultPda: PublicKey | undefined;
2569
+
2570
+ if (partnerFeeRecipient && partnerFeeMarkupAsPkey && referralVaultProgram) {
2571
+ // Derive the userVault PDA
2572
+ [userVaultPda] = PublicKey.findProgramAddressSync(
2573
+ [Buffer.from("user_vault"), new PublicKey(partnerFeeRecipient).toBuffer()],
2574
+ referralVaultProgram.programId
2575
+ );
2576
+
2577
+ // Get the vault's associated token account
2578
+ const vaultTokenAccount = getAssociatedTokenAddressSync(
2579
+ quoteToken,
2580
+ userVaultPda,
2581
+ true, // allowOwnerOffCurve for PDA
2582
+ quoteTokenProgram
2583
+ );
2584
+
2585
+ // Check both accounts at the same time
2586
+ const [vaultAccountInfo, vaultTokenAccountInfo] = await lavarageProgram.provider.connection.getMultipleAccountsInfo([
2587
+ userVaultPda,
2588
+ vaultTokenAccount
2589
+ ]);
2590
+
2591
+ // Create vault if it doesn't exist
2592
+ if (!vaultAccountInfo) {
2593
+ partnerFeeRecipientVaultCreateIx = await referralVaultProgram.methods
2594
+ .initializeVault()
2595
+ .accountsStrict({
2596
+ userVault: userVaultPda,
2597
+ user: partnerFeeRecipient!,
2598
+ funder: lavarageProgram.provider.publicKey!,
2599
+ systemProgram: SystemProgram.programId,
2600
+ })
2601
+ .instruction();
2602
+ }
2603
+
2604
+ // Create token account if it doesn't exist
2605
+ if (!vaultTokenAccountInfo) {
2606
+ partnerFeeRecipientTokenAccountCreateIx = createAssociatedTokenAccountIdempotentInstruction(
2607
+ lavarageProgram.provider.publicKey!,
2608
+ vaultTokenAccount,
2609
+ userVaultPda,
2610
+ quoteToken,
2611
+ quoteTokenProgram,
2612
+ ASSOCIATED_TOKEN_PROGRAM_ID
2613
+ );
2614
+ }
2615
+ }
2616
+
2014
2617
  const closePositionIx = await lavarageProgram.methods
2015
2618
  .tradingCloseBorrowCollateral()
2016
2619
  .accountsStrict({
@@ -2031,119 +2634,227 @@ export const closeTradeV2 = async (
2031
2634
  let repaySolIx: TransactionInstruction | null = null;
2032
2635
  let jupiterIxs: TransactionInstruction[] = [];
2033
2636
  if (jupInstruction.instructions == undefined) {
2034
- repaySolIx = await lavarageProgram.methods
2035
- .tradingCloseRepaySol(
2036
- new BN(jupInstruction.quoteResponse.outAmount),
2037
- new BN(9997)
2038
- )
2039
- .accountsStrict({
2040
- nodeWallet: pool.account.nodeWallet,
2041
- positionAccount: positionAccountPDA,
2042
- tradingPool: poolPubKey,
2043
- trader: lavarageProgram.provider.publicKey!,
2044
- systemProgram: SystemProgram.programId,
2045
- clock: SYSVAR_CLOCK_PUBKEY,
2046
- randomAccountAsId: position.account.seed,
2047
- feeTokenAccount: getAssociatedTokenAddressSync(
2048
- quoteToken,
2049
- new PublicKey("6JfTobDvwuwZxZP6FR5JPmjdvQ4h4MovkEVH2FPsMSrF"),
2050
- false,
2051
- quoteTokenProgram
2052
- ),
2053
- fromTokenAccount: getAssociatedTokenAddressSync(
2054
- quoteToken,
2055
- lavarageProgram.provider.publicKey!,
2056
- false,
2057
- quoteTokenProgram
2058
- ),
2059
- tokenProgram: quoteTokenProgram!,
2060
- toTokenAccount: getAssociatedTokenAddressSync(
2061
- quoteToken,
2062
- pool.account.nodeWallet,
2063
- true,
2064
- quoteTokenProgram
2065
- ),
2066
- mint: quoteToken,
2067
- })
2068
- .remainingAccounts(
2069
- partnerFeeRecipient && partnerFeeMarkupAsPkey
2070
- ? [
2071
- {
2072
- pubkey: getAssociatedTokenAddressSync(
2073
- quoteToken,
2074
- partnerFeeRecipient,
2075
- false,
2076
- quoteTokenProgram
2077
- ),
2078
- isSigner: false,
2079
- isWritable: true,
2080
- },
2081
- {
2082
- pubkey: partnerFeeMarkupAsPkey,
2083
- isSigner: false,
2084
- isWritable: false,
2085
- },
2086
- ]
2087
- : []
2088
- )
2089
- .instruction();
2637
+ repaySolIx = useReferral
2638
+ ? await lavarageProgram.methods
2639
+ .tradingCloseRepaySolWithReferral(
2640
+ new BN(jupInstruction.quoteResponse.outAmount),
2641
+ new BN(9997),
2642
+ new BN(discountBps),
2643
+ new BN(referralBps)
2644
+ )
2645
+ .accountsStrict({
2646
+ nodeWallet: pool.account.nodeWallet,
2647
+ positionAccount: positionAccountPDA,
2648
+ tradingPool: poolPubKey,
2649
+ trader: lavarageProgram.provider.publicKey!,
2650
+ systemProgram: SystemProgram.programId,
2651
+ clock: SYSVAR_CLOCK_PUBKEY,
2652
+ randomAccountAsId: position.account.seed,
2653
+ feeTokenAccount: getAssociatedTokenAddressSync(
2654
+ quoteToken,
2655
+ new PublicKey("6JfTobDvwuwZxZP6FR5JPmjdvQ4h4MovkEVH2FPsMSrF"),
2656
+ false,
2657
+ quoteTokenProgram
2658
+ ),
2659
+ fromTokenAccount: getAssociatedTokenAddressSync(
2660
+ quoteToken,
2661
+ lavarageProgram.provider.publicKey!,
2662
+ false,
2663
+ quoteTokenProgram
2664
+ ),
2665
+ tokenProgram: quoteTokenProgram!,
2666
+ toTokenAccount: getAssociatedTokenAddressSync(
2667
+ quoteToken,
2668
+ pool.account.nodeWallet,
2669
+ true,
2670
+ quoteTokenProgram
2671
+ ),
2672
+ mint: quoteToken,
2673
+ })
2674
+ .remainingAccounts(
2675
+ partnerFeeRecipient && partnerFeeMarkupAsPkey && userVaultPda
2676
+ ? [
2677
+ {
2678
+ pubkey: getAssociatedTokenAddressSync(
2679
+ quoteToken,
2680
+ userVaultPda,
2681
+ true, // allowOwnerOffCurve for PDA
2682
+ quoteTokenProgram
2683
+ ),
2684
+ isSigner: false,
2685
+ isWritable: true,
2686
+ }
2687
+ ]
2688
+ : []
2689
+ )
2690
+ .instruction()
2691
+ : await lavarageProgram.methods
2692
+ .tradingCloseRepaySol(
2693
+ new BN(jupInstruction.quoteResponse.outAmount),
2694
+ new BN(9997)
2695
+ )
2696
+ .accountsStrict({
2697
+ nodeWallet: pool.account.nodeWallet,
2698
+ positionAccount: positionAccountPDA,
2699
+ tradingPool: poolPubKey,
2700
+ trader: lavarageProgram.provider.publicKey!,
2701
+ systemProgram: SystemProgram.programId,
2702
+ clock: SYSVAR_CLOCK_PUBKEY,
2703
+ randomAccountAsId: position.account.seed,
2704
+ feeTokenAccount: getAssociatedTokenAddressSync(
2705
+ quoteToken,
2706
+ new PublicKey("6JfTobDvwuwZxZP6FR5JPmjdvQ4h4MovkEVH2FPsMSrF"),
2707
+ false,
2708
+ quoteTokenProgram
2709
+ ),
2710
+ fromTokenAccount: getAssociatedTokenAddressSync(
2711
+ quoteToken,
2712
+ lavarageProgram.provider.publicKey!,
2713
+ false,
2714
+ quoteTokenProgram
2715
+ ),
2716
+ tokenProgram: quoteTokenProgram!,
2717
+ toTokenAccount: getAssociatedTokenAddressSync(
2718
+ quoteToken,
2719
+ pool.account.nodeWallet,
2720
+ true,
2721
+ quoteTokenProgram
2722
+ ),
2723
+ mint: quoteToken,
2724
+ })
2725
+ .remainingAccounts(
2726
+ partnerFeeRecipient && partnerFeeMarkupAsPkey
2727
+ ? [
2728
+ {
2729
+ pubkey: getAssociatedTokenAddressSync(
2730
+ quoteToken,
2731
+ partnerFeeRecipient,
2732
+ false,
2733
+ quoteTokenProgram
2734
+ ),
2735
+ isSigner: false,
2736
+ isWritable: true,
2737
+ },
2738
+ {
2739
+ pubkey: partnerFeeMarkupAsPkey,
2740
+ isSigner: false,
2741
+ isWritable: false,
2742
+ },
2743
+ ]
2744
+ : []
2745
+ )
2746
+ .instruction();
2090
2747
  } else {
2091
- repaySolIx = await lavarageProgram.methods
2092
- .tradingCloseRepaySol(
2093
- new BN(jupInstruction.quoteResponse.outAmount),
2094
- new BN(9998)
2095
- )
2096
- .accountsStrict({
2097
- nodeWallet: pool.account.nodeWallet,
2098
- positionAccount: positionAccountPDA,
2099
- tradingPool: poolPubKey,
2100
- trader: lavarageProgram.provider.publicKey!,
2101
- systemProgram: SystemProgram.programId,
2102
- clock: SYSVAR_CLOCK_PUBKEY,
2103
- randomAccountAsId: position.account.seed,
2104
- feeTokenAccount: getAssociatedTokenAddressSync(
2105
- quoteToken,
2106
- new PublicKey("6JfTobDvwuwZxZP6FR5JPmjdvQ4h4MovkEVH2FPsMSrF"),
2107
- false,
2108
- quoteTokenProgram
2109
- ),
2110
- fromTokenAccount: getAssociatedTokenAddressSync(
2111
- quoteToken,
2112
- lavarageProgram.provider.publicKey!,
2113
- false,
2114
- quoteTokenProgram
2115
- ),
2116
- tokenProgram: quoteTokenProgram!,
2117
- toTokenAccount: getAssociatedTokenAddressSync(
2118
- quoteToken,
2119
- pool.account.nodeWallet,
2120
- true,
2121
- quoteTokenProgram
2122
- ),
2123
- mint: quoteToken,
2124
- })
2125
- .remainingAccounts(
2126
- partnerFeeRecipient && partnerFeeMarkupAsPkey
2127
- ? [
2128
- {
2129
- pubkey: getAssociatedTokenAddressSync(
2130
- quoteToken,
2131
- partnerFeeRecipient,
2132
- false,
2133
- quoteTokenProgram
2134
- ),
2135
- isSigner: false,
2136
- isWritable: true,
2137
- },
2138
- {
2139
- pubkey: partnerFeeMarkupAsPkey,
2140
- isSigner: false,
2141
- isWritable: false,
2142
- },
2143
- ]
2144
- : []
2145
- )
2146
- .instruction();
2748
+ repaySolIx = useReferral
2749
+ ? await lavarageProgram.methods
2750
+ .tradingCloseRepaySolWithReferral(
2751
+ new BN(jupInstruction.quoteResponse.outAmount),
2752
+ new BN(9998),
2753
+ new BN(discountBps),
2754
+ new BN(referralBps)
2755
+ )
2756
+ .accountsStrict({
2757
+ nodeWallet: pool.account.nodeWallet,
2758
+ positionAccount: positionAccountPDA,
2759
+ tradingPool: poolPubKey,
2760
+ trader: lavarageProgram.provider.publicKey!,
2761
+ systemProgram: SystemProgram.programId,
2762
+ clock: SYSVAR_CLOCK_PUBKEY,
2763
+ randomAccountAsId: position.account.seed,
2764
+ feeTokenAccount: getAssociatedTokenAddressSync(
2765
+ quoteToken,
2766
+ new PublicKey("6JfTobDvwuwZxZP6FR5JPmjdvQ4h4MovkEVH2FPsMSrF"),
2767
+ false,
2768
+ quoteTokenProgram
2769
+ ),
2770
+ fromTokenAccount: getAssociatedTokenAddressSync(
2771
+ quoteToken,
2772
+ lavarageProgram.provider.publicKey!,
2773
+ false,
2774
+ quoteTokenProgram
2775
+ ),
2776
+ tokenProgram: quoteTokenProgram!,
2777
+ toTokenAccount: getAssociatedTokenAddressSync(
2778
+ quoteToken,
2779
+ pool.account.nodeWallet,
2780
+ true,
2781
+ quoteTokenProgram
2782
+ ),
2783
+ mint: quoteToken,
2784
+ })
2785
+ .remainingAccounts(
2786
+ partnerFeeRecipient && partnerFeeMarkupAsPkey && userVaultPda
2787
+ ? [
2788
+ {
2789
+ pubkey: getAssociatedTokenAddressSync(
2790
+ quoteToken,
2791
+ userVaultPda,
2792
+ true, // allowOwnerOffCurve for PDA
2793
+ quoteTokenProgram
2794
+ ),
2795
+ isSigner: false,
2796
+ isWritable: true,
2797
+ }
2798
+ ]
2799
+ : []
2800
+ )
2801
+ .instruction()
2802
+ : await lavarageProgram.methods
2803
+ .tradingCloseRepaySol(
2804
+ new BN(jupInstruction.quoteResponse.outAmount),
2805
+ new BN(9998)
2806
+ )
2807
+ .accountsStrict({
2808
+ nodeWallet: pool.account.nodeWallet,
2809
+ positionAccount: positionAccountPDA,
2810
+ tradingPool: poolPubKey,
2811
+ trader: lavarageProgram.provider.publicKey!,
2812
+ systemProgram: SystemProgram.programId,
2813
+ clock: SYSVAR_CLOCK_PUBKEY,
2814
+ randomAccountAsId: position.account.seed,
2815
+ feeTokenAccount: getAssociatedTokenAddressSync(
2816
+ quoteToken,
2817
+ new PublicKey("6JfTobDvwuwZxZP6FR5JPmjdvQ4h4MovkEVH2FPsMSrF"),
2818
+ false,
2819
+ quoteTokenProgram
2820
+ ),
2821
+ fromTokenAccount: getAssociatedTokenAddressSync(
2822
+ quoteToken,
2823
+ lavarageProgram.provider.publicKey!,
2824
+ false,
2825
+ quoteTokenProgram
2826
+ ),
2827
+ tokenProgram: quoteTokenProgram!,
2828
+ toTokenAccount: getAssociatedTokenAddressSync(
2829
+ quoteToken,
2830
+ pool.account.nodeWallet,
2831
+ true,
2832
+ quoteTokenProgram
2833
+ ),
2834
+ mint: quoteToken,
2835
+ })
2836
+ .remainingAccounts(
2837
+ partnerFeeRecipient && partnerFeeMarkupAsPkey
2838
+ ? [
2839
+ {
2840
+ pubkey: getAssociatedTokenAddressSync(
2841
+ quoteToken,
2842
+ partnerFeeRecipient,
2843
+ false,
2844
+ quoteTokenProgram
2845
+ ),
2846
+ isSigner: false,
2847
+ isWritable: true,
2848
+ },
2849
+ {
2850
+ pubkey: partnerFeeMarkupAsPkey,
2851
+ isSigner: false,
2852
+ isWritable: false,
2853
+ },
2854
+ ]
2855
+ : []
2856
+ )
2857
+ .instruction();
2147
2858
  const {
2148
2859
  setupInstructions,
2149
2860
  swapInstruction: swapInstructionPayload,
@@ -2184,6 +2895,8 @@ export const closeTradeV2 = async (
2184
2895
 
2185
2896
  if (splitTransactions) {
2186
2897
  const setUpInstructions = [
2898
+ partnerFeeRecipientVaultCreateIx,
2899
+ partnerFeeRecipientTokenAccountCreateIx,
2187
2900
  jupInstruction.instructions && platformFeeRecipientAccount?.instruction ? platformFeeRecipientAccount.instruction : null,
2188
2901
  createAssociatedTokenAccountInstruction,
2189
2902
  ].filter((i) => !!i);
@@ -2220,6 +2933,8 @@ export const closeTradeV2 = async (
2220
2933
  }
2221
2934
 
2222
2935
  const allInstructions = [
2936
+ partnerFeeRecipientVaultCreateIx,
2937
+ partnerFeeRecipientTokenAccountCreateIx,
2223
2938
  jupInstruction.instructions && platformFeeRecipientAccount?.instruction ? platformFeeRecipientAccount.instruction : null,
2224
2939
  createAssociatedTokenAccountInstruction,
2225
2940
  jupInstruction.instructions?.tokenLedgerInstruction
@@ -2244,6 +2959,38 @@ export const closeTradeV2 = async (
2244
2959
  return tx;
2245
2960
  };
2246
2961
 
2962
+ /**
2963
+ * Retrieves delegate accounts for automated position management
2964
+ *
2965
+ * @group Traders
2966
+ * @category Queries
2967
+ *
2968
+ * @param lavarageProgram - The Lavarage program instance (V1 or V2)
2969
+ * @param userPubKey - Optional user public key to filter delegates
2970
+ *
2971
+ * @returns Array of delegate accounts with parsed price data
2972
+ *
2973
+ * @example
2974
+ * ```typescript
2975
+ * // Get all delegates for a specific user
2976
+ * const userDelegates = await getDelegateAccounts(
2977
+ * lavarageProgram,
2978
+ * userPublicKey
2979
+ * );
2980
+ *
2981
+ * // Get all delegates (no filter)
2982
+ * const allDelegates = await getDelegateAccounts(lavarageProgram);
2983
+ *
2984
+ * // Access parsed data
2985
+ * userDelegates.forEach(delegate => {
2986
+ * console.log('TP Price:', delegate.parsed.tpPrice.toString());
2987
+ * console.log('Threshold:', delegate.parsed.tpThreshold.toString());
2988
+ * });
2989
+ * ```
2990
+ * @see {@link createTpDelegate} - Create a new take-profit delegate
2991
+ * @see {@link modifyTpDelegate} - Modify existing take-profit settings
2992
+ * @see {@link removeTpDelegate} - Remove take-profit settings
2993
+ */
2247
2994
  export const getDelegateAccounts = async (
2248
2995
  lavarageProgram: Program<Lavarage> | Program<LavarageV2>,
2249
2996
  userPubKey?: PublicKey
@@ -2280,6 +3027,39 @@ const getQuoteCurrencySpecificAddressLookupTable = (quoteCurrency: string) => {
2280
3027
  }
2281
3028
  };
2282
3029
 
3030
+ /**
3031
+ * Splits a position into two separate positions on Lavarage V2
3032
+ *
3033
+ * @group Traders
3034
+ * @category PositionManagement
3035
+ *
3036
+ * @param lavarageProgram - The Lavarage V2 or V1 program instance
3037
+ * @param position - The original position to split
3038
+ * @param offer - The offer/pool account associated with the position
3039
+ * @param quoteToken - The quote token mint address
3040
+ * @param propotionBps - Split ratio in basis points (5000 = 50/50 split)
3041
+ * @param computeBudgetMicroLamports - Optional compute budget for priority fees
3042
+ *
3043
+ * @returns Object containing transaction and new position addresses
3044
+ *
3045
+ * @example
3046
+ * ```typescript
3047
+ * // Split position 70/30
3048
+ * const result = await splitPositionV2(
3049
+ * lavarageProgram,
3050
+ * position,
3051
+ * offer,
3052
+ * usdcMint,
3053
+ * 7000 // 70% to first position, 30% to second
3054
+ * );
3055
+ *
3056
+ * const tx = result.transaction;
3057
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
3058
+ *
3059
+ * console.log('New positions:', result.newPositionAddresses);
3060
+ * ```
3061
+ * @see {@link mergePositionV2} - Merge two positions into one
3062
+ */
2283
3063
  export const splitPositionV2 = async (
2284
3064
  lavarageProgram: Program<LavarageV2> | Program<Lavarage>,
2285
3065
  position: ProgramAccount<{
@@ -2409,6 +3189,37 @@ export const splitPositionV2 = async (
2409
3189
  };
2410
3190
  };
2411
3191
 
3192
+ /**
3193
+ * Merges two positions into a single position on Lavarage V2
3194
+ *
3195
+ * @group Traders
3196
+ * @category PositionManagement
3197
+ *
3198
+ * @param lavarageProgram - The Lavarage V2 program instance
3199
+ * @param position1 - The first position to merge
3200
+ * @param position2 - The second position to merge
3201
+ * @param offer - The offer/pool account (must be same for both positions)
3202
+ * @param quoteToken - The quote token mint address
3203
+ * @param computeBudgetMicroLamports - Optional compute budget for priority fees
3204
+ *
3205
+ * @returns Transaction to merge the positions
3206
+ *
3207
+ * @example
3208
+ * ```typescript
3209
+ * // Merge two positions into one
3210
+ * const tx = await mergePositionV2(
3211
+ * lavarageProgram,
3212
+ * position1,
3213
+ * position2,
3214
+ * offer,
3215
+ * usdcMint
3216
+ * );
3217
+ *
3218
+ * await sendAndConfirmTransaction(connection, tx, [wallet]);
3219
+ * ```
3220
+ *
3221
+ * @see {@link splitPositionV2} - Split a position into two
3222
+ */
2412
3223
  export const mergePositionV2 = async (
2413
3224
  lavarageProgram: Program<LavarageV2>,
2414
3225
  position1: ProgramAccount<{