@hawksightco/hawk-sdk 1.3.265 → 1.3.266

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 (181) hide show
  1. package/dist/addresses.d.ts +37 -0
  2. package/dist/addresses.d.ts.map +1 -0
  3. package/dist/addresses.js +84 -0
  4. package/dist/anchor.d.ts +22 -0
  5. package/dist/anchor.d.ts.map +1 -0
  6. package/dist/anchor.js +121 -0
  7. package/dist/classes/AltStorage.d.ts +29 -0
  8. package/dist/classes/AltStorage.d.ts.map +1 -0
  9. package/dist/classes/AltStorage.js +58 -0
  10. package/dist/classes/Atomicity.d.ts +34 -0
  11. package/dist/classes/Atomicity.d.ts.map +1 -0
  12. package/dist/classes/Atomicity.js +110 -0
  13. package/dist/classes/Client.d.ts +35 -0
  14. package/dist/classes/Client.d.ts.map +1 -0
  15. package/dist/classes/Client.js +66 -0
  16. package/dist/classes/CombineTransactions.d.ts +11 -0
  17. package/dist/classes/CombineTransactions.d.ts.map +1 -0
  18. package/dist/classes/CombineTransactions.js +58 -0
  19. package/dist/classes/CreateTxMetadata.d.ts +100 -0
  20. package/dist/classes/CreateTxMetadata.d.ts.map +1 -0
  21. package/dist/classes/CreateTxMetadata.js +415 -0
  22. package/dist/classes/General.d.ts +87 -0
  23. package/dist/classes/General.d.ts.map +1 -0
  24. package/dist/classes/General.js +176 -0
  25. package/dist/classes/GeneralUtility.d.ts +79 -0
  26. package/dist/classes/GeneralUtility.d.ts.map +1 -0
  27. package/dist/classes/GeneralUtility.js +121 -0
  28. package/dist/classes/HawkAPI.d.ts +122 -0
  29. package/dist/classes/HawkAPI.d.ts.map +1 -0
  30. package/dist/classes/HawkAPI.js +169 -0
  31. package/dist/classes/Health.d.ts +29 -0
  32. package/dist/classes/Health.d.ts.map +1 -0
  33. package/dist/classes/Health.js +48 -0
  34. package/dist/classes/JupiterAlts.d.ts +37 -0
  35. package/dist/classes/JupiterAlts.d.ts.map +1 -0
  36. package/dist/classes/JupiterAlts.js +114 -0
  37. package/dist/classes/JupiterSwap.d.ts +21 -0
  38. package/dist/classes/JupiterSwap.d.ts.map +1 -0
  39. package/dist/classes/JupiterSwap.js +40 -0
  40. package/dist/classes/Logging.d.ts +13 -0
  41. package/dist/classes/Logging.d.ts.map +1 -0
  42. package/dist/classes/Logging.js +50 -0
  43. package/dist/classes/MultiTransaction.d.ts +75 -0
  44. package/dist/classes/MultiTransaction.d.ts.map +1 -0
  45. package/dist/classes/MultiTransaction.js +296 -0
  46. package/dist/classes/RaydiumSDK.d.ts +67 -0
  47. package/dist/classes/RaydiumSDK.d.ts.map +1 -0
  48. package/dist/classes/RaydiumSDK.js +206 -0
  49. package/dist/classes/Search.d.ts +100 -0
  50. package/dist/classes/Search.d.ts.map +1 -0
  51. package/dist/classes/Search.js +216 -0
  52. package/dist/classes/SimpleIxGenerator.d.ts +57 -0
  53. package/dist/classes/SimpleIxGenerator.d.ts.map +1 -0
  54. package/dist/classes/SimpleIxGenerator.js +62 -0
  55. package/dist/classes/SimplePdaGenerator.d.ts +28 -0
  56. package/dist/classes/SimplePdaGenerator.d.ts.map +1 -0
  57. package/dist/classes/SimplePdaGenerator.js +33 -0
  58. package/dist/classes/Transaction.d.ts +229 -0
  59. package/dist/classes/Transaction.d.ts.map +1 -0
  60. package/dist/classes/Transaction.js +643 -0
  61. package/dist/classes/Transaction2.d.ts +107 -0
  62. package/dist/classes/Transaction2.d.ts.map +1 -0
  63. package/dist/classes/Transaction2.js +249 -0
  64. package/dist/classes/Transaction3.d.ts +165 -0
  65. package/dist/classes/Transaction3.d.ts.map +1 -0
  66. package/dist/classes/Transaction3.js +416 -0
  67. package/dist/classes/TransactionBatchExecute.d.ts +163 -0
  68. package/dist/classes/TransactionBatchExecute.d.ts.map +1 -0
  69. package/dist/classes/TransactionBatchExecute.js +466 -0
  70. package/dist/classes/TransactionBatchExecute2.d.ts +99 -0
  71. package/dist/classes/TransactionBatchExecute2.d.ts.map +1 -0
  72. package/dist/classes/TransactionBatchExecute2.js +357 -0
  73. package/dist/classes/Transactions.d.ts +586 -0
  74. package/dist/classes/Transactions.d.ts.map +1 -0
  75. package/dist/classes/Transactions.js +7667 -0
  76. package/dist/classes/TxGenerator.d.ts +350 -0
  77. package/dist/classes/TxGenerator.d.ts.map +1 -0
  78. package/dist/classes/TxGenerator.js +1957 -0
  79. package/dist/classes/TxGeneratorAutomations.d.ts +186 -0
  80. package/dist/classes/TxGeneratorAutomations.d.ts.map +1 -0
  81. package/dist/classes/TxGeneratorAutomations.js +897 -0
  82. package/dist/classes/Util.d.ts +87 -0
  83. package/dist/classes/Util.d.ts.map +1 -0
  84. package/dist/classes/Util.js +148 -0
  85. package/dist/classes/account-cache/AccountCache.d.ts +54 -0
  86. package/dist/classes/account-cache/AccountCache.d.ts.map +1 -0
  87. package/dist/classes/account-cache/AccountCache.js +143 -0
  88. package/dist/classes/account-cache/MintCache.d.ts +33 -0
  89. package/dist/classes/account-cache/MintCache.d.ts.map +1 -0
  90. package/dist/classes/account-cache/MintCache.js +47 -0
  91. package/dist/classes/account-cache/TokenCache.d.ts +33 -0
  92. package/dist/classes/account-cache/TokenCache.d.ts.map +1 -0
  93. package/dist/classes/account-cache/TokenCache.js +47 -0
  94. package/dist/errors.d.ts +13 -0
  95. package/dist/errors.d.ts.map +1 -0
  96. package/dist/errors.js +96 -0
  97. package/dist/functions.d.ts +514 -0
  98. package/dist/functions.d.ts.map +1 -0
  99. package/dist/functions.js +1636 -0
  100. package/dist/hawksight.d.ts +53 -0
  101. package/dist/hawksight.d.ts.map +1 -0
  102. package/dist/hawksight.js +328 -0
  103. package/dist/hsToMeteora.d.ts +31 -0
  104. package/dist/hsToMeteora.d.ts.map +1 -0
  105. package/dist/hsToMeteora.js +3175 -0
  106. package/dist/idl/iyf-extension-idl.d.ts +14583 -0
  107. package/dist/idl/iyf-extension-idl.d.ts.map +1 -0
  108. package/dist/idl/iyf-extension-idl.js +14578 -0
  109. package/dist/idl/iyf-extension-wrapper.d.ts +112 -0
  110. package/dist/idl/iyf-extension-wrapper.d.ts.map +1 -0
  111. package/dist/idl/iyf-extension-wrapper.js +2 -0
  112. package/dist/idl/iyf-main-idl.d.ts +12078 -0
  113. package/dist/idl/iyf-main-idl.d.ts.map +1 -0
  114. package/dist/idl/iyf-main-idl.js +12073 -0
  115. package/dist/idl/iyf-main-wrapper.d.ts +112 -0
  116. package/dist/idl/iyf-main-wrapper.d.ts.map +1 -0
  117. package/dist/idl/iyf-main-wrapper.js +2 -0
  118. package/dist/idl/jupiter-idl.d.ts +3063 -0
  119. package/dist/idl/jupiter-idl.d.ts.map +1 -0
  120. package/dist/idl/jupiter-idl.js +3061 -0
  121. package/dist/idl/meteora-idl.d.ts +7371 -0
  122. package/dist/idl/meteora-idl.d.ts.map +1 -0
  123. package/dist/idl/meteora-idl.js +7372 -0
  124. package/dist/idl/orca-idl.d.ts +3833 -0
  125. package/dist/idl/orca-idl.d.ts.map +1 -0
  126. package/dist/idl/orca-idl.js +3834 -0
  127. package/dist/idl/raydium-idl.d.ts +3054 -0
  128. package/dist/idl/raydium-idl.d.ts.map +1 -0
  129. package/dist/idl/raydium-idl.js +3055 -0
  130. package/dist/index.d.ts +9 -0
  131. package/dist/index.d.ts.map +1 -0
  132. package/dist/index.js +31 -0
  133. package/dist/ixGenerator/IyfExtensionIxGenerator.d.ts +126 -0
  134. package/dist/ixGenerator/IyfExtensionIxGenerator.d.ts.map +1 -0
  135. package/dist/ixGenerator/IyfExtensionIxGenerator.js +467 -0
  136. package/dist/ixGenerator/IyfMainIxGenerator.d.ts +330 -0
  137. package/dist/ixGenerator/IyfMainIxGenerator.d.ts.map +1 -0
  138. package/dist/ixGenerator/IyfMainIxGenerator.js +1239 -0
  139. package/dist/ixGenerator/MeteoraDlmmIxGenerator.d.ts +685 -0
  140. package/dist/ixGenerator/MeteoraDlmmIxGenerator.d.ts.map +1 -0
  141. package/dist/ixGenerator/MeteoraDlmmIxGenerator.js +3005 -0
  142. package/dist/ixGenerator/OrcaIxGenerator.d.ts +119 -0
  143. package/dist/ixGenerator/OrcaIxGenerator.d.ts.map +1 -0
  144. package/dist/ixGenerator/OrcaIxGenerator.js +438 -0
  145. package/dist/ixGenerator/RaydiumIxGenerator.d.ts +99 -0
  146. package/dist/ixGenerator/RaydiumIxGenerator.d.ts.map +1 -0
  147. package/dist/ixGenerator/RaydiumIxGenerator.js +558 -0
  148. package/dist/ixGenerator/UtilIxGenerator.d.ts +20 -0
  149. package/dist/ixGenerator/UtilIxGenerator.d.ts.map +1 -0
  150. package/dist/ixGenerator/UtilIxGenerator.js +25 -0
  151. package/dist/meteora/index.d.ts +2 -0
  152. package/dist/meteora/index.d.ts.map +1 -0
  153. package/dist/meteora/index.js +17 -0
  154. package/dist/meteora/liquidityStrategy.d.ts +408 -0
  155. package/dist/meteora/liquidityStrategy.d.ts.map +1 -0
  156. package/dist/meteora/liquidityStrategy.js +1325 -0
  157. package/dist/meteora.d.ts +669 -0
  158. package/dist/meteora.d.ts.map +1 -0
  159. package/dist/meteora.js +1932 -0
  160. package/dist/orca.d.ts +57 -0
  161. package/dist/orca.d.ts.map +1 -0
  162. package/dist/orca.js +123 -0
  163. package/dist/pdaGenerator/HawksightPdaGenerator.d.ts +29 -0
  164. package/dist/pdaGenerator/HawksightPdaGenerator.d.ts.map +1 -0
  165. package/dist/pdaGenerator/HawksightPdaGenerator.js +75 -0
  166. package/dist/pdaGenerator/MeteoraPdaGenerator.d.ts +76 -0
  167. package/dist/pdaGenerator/MeteoraPdaGenerator.d.ts.map +1 -0
  168. package/dist/pdaGenerator/MeteoraPdaGenerator.js +166 -0
  169. package/dist/pdaGenerator/OrcaPdaGenerator.d.ts +23 -0
  170. package/dist/pdaGenerator/OrcaPdaGenerator.d.ts.map +1 -0
  171. package/dist/pdaGenerator/OrcaPdaGenerator.js +68 -0
  172. package/dist/pdaGenerator/RaydiumPdaGenerator.d.ts +49 -0
  173. package/dist/pdaGenerator/RaydiumPdaGenerator.d.ts.map +1 -0
  174. package/dist/pdaGenerator/RaydiumPdaGenerator.js +114 -0
  175. package/dist/pdaGenerator/UtilPdaGenerator.d.ts +8 -0
  176. package/dist/pdaGenerator/UtilPdaGenerator.d.ts.map +1 -0
  177. package/dist/pdaGenerator/UtilPdaGenerator.js +51 -0
  178. package/dist/types.d.ts +1104 -0
  179. package/dist/types.d.ts.map +1 -0
  180. package/dist/types.js +95 -0
  181. package/package.json +6 -5
@@ -0,0 +1,3005 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.MeteoraDlmmIxGenerator = exports.StrategyType = void 0;
49
+ exports.mapOldStrategyTypeToNew = mapOldStrategyTypeToNew;
50
+ exports.buildBaseClosePosition2AutomationIx = buildBaseClosePosition2AutomationIx;
51
+ const web3 = __importStar(require("@solana/web3.js"));
52
+ const anchor_1 = require("../anchor");
53
+ const functions_1 = require("../functions");
54
+ const addresses_1 = require("../addresses");
55
+ const meteora_1 = require("../meteora");
56
+ const dlmm_1 = __importDefault(require("@meteora-ag/dlmm"));
57
+ const types_1 = require("../types");
58
+ const bn_js_1 = __importDefault(require("bn.js"));
59
+ const AccountCache_1 = require("../classes/account-cache/AccountCache");
60
+ const MintCache_1 = require("../classes/account-cache/MintCache");
61
+ const util = __importStar(require("../functions"));
62
+ /**
63
+ * Meteora event authority
64
+ */
65
+ const METEORA_EVENT_AUTHORITY = new web3.PublicKey('D1ZN9Wj1fRSUQfCjhvnu1hqDMT7hzjzBBpi12nVniYD6');
66
+ /**
67
+ * Meteora Program ID
68
+ */
69
+ const METEORA_DLMM_PROGRAM = new web3.PublicKey('LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo');
70
+ var StrategyType;
71
+ (function (StrategyType) {
72
+ StrategyType[StrategyType["Spot"] = 0] = "Spot";
73
+ StrategyType[StrategyType["Curve"] = 1] = "Curve";
74
+ StrategyType[StrategyType["BidAsk"] = 2] = "BidAsk";
75
+ })(StrategyType || (exports.StrategyType = StrategyType = {}));
76
+ // Backwards-compatible mapping from old StrategyType to new StrategyType
77
+ function mapOldStrategyTypeToNew(oldStrategyType) {
78
+ // Handle the old enum values (0-8) and map them to the new simplified enum
79
+ switch (oldStrategyType) {
80
+ case 0: // SpotOneSide
81
+ case 3: // SpotBalanced
82
+ case 6: // SpotImBalanced
83
+ return StrategyType.Spot;
84
+ case 1: // CurveOneSide
85
+ case 4: // CurveBalanced
86
+ case 7: // CurveImBalanced
87
+ return StrategyType.Curve;
88
+ case 2: // BidAskOneSide
89
+ case 5: // BidAskBalanced
90
+ case 8: // BidAskImBalanced
91
+ return StrategyType.BidAsk;
92
+ default:
93
+ // Default fallback
94
+ return StrategyType.Spot;
95
+ }
96
+ }
97
+ function buildBaseClosePosition2AutomationIx({ userPda, hawksightAuthority, authority, position, lbPair, fuelAccount, isHawkRefund, }) {
98
+ return new web3.TransactionInstruction({
99
+ data: Buffer.concat([
100
+ Buffer.from(util.sighash('meteora_dlmm_base_close_position_automation', undefined, true)),
101
+ Buffer.from([isHawkRefund ? 1 : 0]),
102
+ ]),
103
+ keys: [
104
+ { pubkey: userPda, isSigner: false, isWritable: false },
105
+ { pubkey: hawksightAuthority, isSigner: true, isWritable: true },
106
+ { pubkey: authority, isSigner: false, isWritable: true },
107
+ { pubkey: position, isSigner: false, isWritable: true },
108
+ { pubkey: lbPair, isSigner: false, isWritable: true },
109
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false },
110
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
111
+ { pubkey: fuelAccount, isSigner: false, isWritable: true },
112
+ ],
113
+ programId: addresses_1.IYF_EXTENSION,
114
+ });
115
+ }
116
+ /**
117
+ * Meteora related instructions executed via iyf extension or iyf main
118
+ */
119
+ class MeteoraDlmmIxGenerator {
120
+ constructor(ix, pda) {
121
+ this.ix = ix;
122
+ this.pda = pda;
123
+ }
124
+ /**
125
+ * Initialize a Meteora DLMM position via IYF Main's meteora dynamic CPI.
126
+ *
127
+ * This is the raw Meteora initializePosition instruction invoked through IYF Main.
128
+ *
129
+ * @param connection - Solana connection
130
+ * @param params - Initialize position parameters (Meteora-aligned: lowerBinId, width)
131
+ * @returns TransactionInstruction for initializing the position
132
+ */
133
+ initializePosition(_a) {
134
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, lowerBinId, width, }) {
135
+ // Initialize anchor
136
+ anchor_1.Anchor.initialize(connection);
137
+ // Generate user PDA
138
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
139
+ // Build instruction data: sighash + lowerBinId (i32) + width (i32)
140
+ const lowerBinIdBuffer = Buffer.alloc(4);
141
+ lowerBinIdBuffer.writeInt32LE(lowerBinId, 0);
142
+ const widthBuffer = Buffer.alloc(4);
143
+ widthBuffer.writeInt32LE(width, 0);
144
+ // Build raw Meteora instruction (accounts only - no hawksight wrapper accounts)
145
+ // meteoraDynamicCpi will prepend userPda and authority
146
+ const meteoraIx = new web3.TransactionInstruction({
147
+ data: Buffer.concat([
148
+ Buffer.from(util.sighash('initialize_position')),
149
+ lowerBinIdBuffer,
150
+ widthBuffer,
151
+ ]),
152
+ keys: [
153
+ { pubkey: userWallet, isSigner: false, isWritable: true }, // payer (Mutable, Signer - signed by IYF Main)
154
+ { pubkey: position, isSigner: true, isWritable: true }, // position (Mutable, Signer)
155
+ { pubkey: lbPair, isSigner: false, isWritable: false }, // lbPair
156
+ { pubkey: userPda, isSigner: false, isWritable: false }, // owner (Signer - signed by IYF Main)
157
+ {
158
+ pubkey: web3.SystemProgram.programId,
159
+ isSigner: false,
160
+ isWritable: false,
161
+ }, // systemProgram
162
+ { pubkey: web3.SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }, // rent
163
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false }, // eventAuthority (PDA)
164
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // program
165
+ ],
166
+ programId: METEORA_DLMM_PROGRAM,
167
+ });
168
+ return yield this.ix.iyfMain.meteoraDynamicCpi({
169
+ connection,
170
+ userWallet,
171
+ meteoraIx,
172
+ });
173
+ });
174
+ }
175
+ initializePositionAutomation(connection_1, _a) {
176
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, lowerBinId, upperBinId, }) {
177
+ // Initialize anchor
178
+ anchor_1.Anchor.initialize(connection);
179
+ // Generate user pda
180
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
181
+ // Generate instruction
182
+ const width = upperBinId - lowerBinId + 1;
183
+ // @ts-ignore
184
+ const iyfExtensionIx = yield anchor_1.Anchor.instance()
185
+ .iyfExtension.methods.meteoraDlmmInitializePositionAutomation(lowerBinId, width)
186
+ .accounts({
187
+ farm: addresses_1.USDC_FARM,
188
+ userPda,
189
+ authority: userWallet,
190
+ iyfProgram: addresses_1.IYF_MAIN,
191
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
192
+ position,
193
+ lbPair,
194
+ systemProgram: web3.SystemProgram.programId,
195
+ rent: web3.SYSVAR_RENT_PUBKEY,
196
+ eventAuthority: METEORA_EVENT_AUTHORITY,
197
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
198
+ })
199
+ .instruction();
200
+ // Set position to writable
201
+ iyfExtensionIx.keys = iyfExtensionIx.keys.map(meta => {
202
+ if (meta.pubkey === position) {
203
+ meta.isWritable = true;
204
+ }
205
+ return meta;
206
+ });
207
+ return this.ix.iyfMain.iyfExtensionExecute(connection, {
208
+ userWallet,
209
+ iyfExtensionIx,
210
+ });
211
+ });
212
+ }
213
+ initializePositionRelativeAutomation(connection_1, _a) {
214
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, relativeLowerBinId, width, useFuelAccount, }) {
215
+ // Initialize anchor
216
+ anchor_1.Anchor.initialize(connection);
217
+ // Width > 70 is invalid (will error on-chain)
218
+ if (width > 70) {
219
+ throw new Error('Width exceeds maximum allowed 70 bins');
220
+ }
221
+ // Generate user pda
222
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
223
+ // Generate instruction
224
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
225
+ userPda,
226
+ authority: addresses_1.HS_AUTHORITY,
227
+ ix: new web3.TransactionInstruction({
228
+ data: Buffer.concat([
229
+ Buffer.from(util.sighash('meteora_dlmm_initialize_position_relative_automation')),
230
+ new bn_js_1.default(relativeLowerBinId).toTwos(16).toArrayLike(Buffer, 'le', 2),
231
+ Buffer.from([width]),
232
+ ]),
233
+ keys: [
234
+ { pubkey: userPda, isSigner: false, isWritable: false },
235
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: false },
236
+ { pubkey: position, isSigner: true, isWritable: true },
237
+ { pubkey: lbPair, isSigner: false, isWritable: true },
238
+ {
239
+ pubkey: web3.SystemProgram.programId,
240
+ isSigner: false,
241
+ isWritable: false,
242
+ },
243
+ {
244
+ pubkey: web3.SYSVAR_RENT_PUBKEY,
245
+ isSigner: false,
246
+ isWritable: false,
247
+ },
248
+ {
249
+ pubkey: METEORA_EVENT_AUTHORITY,
250
+ isSigner: false,
251
+ isWritable: true,
252
+ },
253
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: true },
254
+ ...(useFuelAccount
255
+ ? [
256
+ {
257
+ pubkey: (0, functions_1.generateFuelAccount)(userWallet),
258
+ isSigner: false,
259
+ isWritable: true,
260
+ },
261
+ ]
262
+ : []),
263
+ ],
264
+ programId: addresses_1.IYF_EXTENSION,
265
+ }),
266
+ });
267
+ });
268
+ }
269
+ /**
270
+ * Add liquidity to an existing Meteora DLMM position using strategy parameters.
271
+ * This is the automation version that uses V2 execution (meteora_dlmm_deposit_2_automation).
272
+ *
273
+ * Key differences from depositAutomation:
274
+ * - Uses iyfExtensionExecuteV2 with Anchor-based instruction building
275
+ * - Supports remainingAccountsInfo for Token2022 transfer hooks
276
+ * - Authority is HS_AUTHORITY (automation wallet)
277
+ * - Does not require binArrayLower/binArrayUpper (bin arrays are auto-derived or created separately)
278
+ *
279
+ * @param connection - Solana connection
280
+ * @param params - AddLiquidityByStrategy2AutomationParams parameters
281
+ * @returns TransactionInstruction for adding liquidity
282
+ */
283
+ meteoraDlmmDepositRelativeAutomation(_a) {
284
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, activeId, relativeBinRange, strategyType, optionalTokenXAmount, optionalTokenYAmount, checkRange, remainingAccountsInfo, pdaTokenType, positionIsSigner = false, }) {
285
+ var _b, _c, _d, _e;
286
+ // Initialize anchor
287
+ anchor_1.Anchor.initialize(connection);
288
+ // Derive reserves from the ACTUAL lbPair (not the one passed in, which may be incorrect)
289
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
290
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
291
+ // Derive bin array bitmap extension from actual lb_pair and check if it exists
292
+ const derivedBinArrayBitmapExtension = this.pda.meteora.deriveBinArrayBitmapExtension(lbPair);
293
+ const binArrayBitmapExtensionInfo = yield connection.getAccountInfo(derivedBinArrayBitmapExtension);
294
+ const actualBinArrayBitmapExtension = binArrayBitmapExtensionInfo
295
+ ? derivedBinArrayBitmapExtension
296
+ : METEORA_DLMM_PROGRAM;
297
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
298
+ // Determine user token accounts based on pdaTokenType
299
+ let userTokenX;
300
+ let userTokenY;
301
+ if (pdaTokenType === types_1.TokenType.LTA) {
302
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
303
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
304
+ }
305
+ else if (pdaTokenType === types_1.TokenType.STA) {
306
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
307
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
308
+ }
309
+ else {
310
+ // Default: ATA
311
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
312
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
313
+ }
314
+ // Serialize RemainingAccountsInfo as Vec<u8> (Borsh format)
315
+ // This is passed directly to the on-chain instruction which forwards it to Meteora
316
+ // For SPL tokens (non-Token2022), we still need to provide the slices structure with length=0
317
+ // This matches what Meteora SDK's getPotentialToken2022IxDataAndAccounts returns
318
+ // AccountsType enum: 0=TransferHookX, 1=TransferHookY, 2=TransferHookReward
319
+ const defaultSlices = [
320
+ { accountsType: 0, length: 0 }, // TransferHookX with 0 accounts
321
+ { accountsType: 1, length: 0 }, // TransferHookY with 0 accounts
322
+ ];
323
+ const remainingAccountsInfoSerialized = this.serializeRemainingAccountsInfo({
324
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : defaultSlices,
325
+ });
326
+ const lowerBinId = activeId + relativeBinRange.lowerRange;
327
+ const upperBinId = activeId + relativeBinRange.upperRange;
328
+ // Derive bin arrays needed for the deposit range using the lbPair from position
329
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, lowerBinId, upperBinId);
330
+ const binArrayAccounts = binArrays.map(binArray => ({
331
+ pubkey: binArray,
332
+ isSigner: false,
333
+ isWritable: true,
334
+ }));
335
+ // Build remaining accounts: Token2022 transfer hook accounts first (described by remainingAccountsInfo),
336
+ // then bin arrays (not described - Meteora expects them at the end after transfer hooks)
337
+ const remainingAccounts = [
338
+ ...((_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : []),
339
+ ...binArrayAccounts,
340
+ ];
341
+ const remainingAccountsInfoLength = Buffer.alloc(4);
342
+ remainingAccountsInfoLength.writeUInt32LE(remainingAccountsInfoSerialized.length, 0);
343
+ const relativeLowerRange = Buffer.alloc(2);
344
+ relativeLowerRange.writeInt16LE(relativeBinRange.lowerRange, 0);
345
+ const relativeUpperRange = Buffer.alloc(2);
346
+ relativeUpperRange.writeInt16LE(relativeBinRange.upperRange, 0);
347
+ const checkLowerRange = Buffer.alloc(4);
348
+ checkLowerRange.writeInt32LE((_d = checkRange === null || checkRange === void 0 ? void 0 : checkRange.lowerRange) !== null && _d !== void 0 ? _d : 0, 0);
349
+ const checkUpperRange = Buffer.alloc(4);
350
+ checkUpperRange.writeInt32LE((_e = checkRange === null || checkRange === void 0 ? void 0 : checkRange.upperRange) !== null && _e !== void 0 ? _e : 0, 0);
351
+ const optionalTokenXAmountBuffer = optionalTokenXAmount
352
+ ? Buffer.concat([
353
+ Buffer.from([1]),
354
+ Buffer.from(optionalTokenXAmount.toArrayLike(Buffer, 'le', 8)),
355
+ ])
356
+ : Buffer.from([0]);
357
+ const optionalTokenYAmountBuffer = optionalTokenYAmount
358
+ ? Buffer.concat([
359
+ Buffer.from([1]),
360
+ Buffer.from(optionalTokenYAmount.toArrayLike(Buffer, 'le', 8)),
361
+ ])
362
+ : Buffer.from([0]);
363
+ const remainingAccountsInfoSerializedWithLength = Buffer.concat([
364
+ remainingAccountsInfoLength,
365
+ remainingAccountsInfoSerialized,
366
+ ]);
367
+ // Use Anchor to serialize the instruction (ensures proper Borsh serialization)
368
+ // @ts-ignore
369
+ const depositIx = new web3.TransactionInstruction({
370
+ data: Buffer.concat([
371
+ Buffer.from(util.sighash('meteora_dlmm_deposit_relative_automation')),
372
+ relativeLowerRange,
373
+ relativeUpperRange,
374
+ Buffer.from([strategyType]),
375
+ optionalTokenXAmountBuffer,
376
+ optionalTokenYAmountBuffer,
377
+ Buffer.from(!!checkRange
378
+ ? Buffer.concat([
379
+ Buffer.from([1]),
380
+ checkLowerRange,
381
+ checkUpperRange,
382
+ ])
383
+ : Buffer.from([0])),
384
+ remainingAccountsInfoSerializedWithLength,
385
+ ]),
386
+ keys: [
387
+ { pubkey: userPda, isSigner: false, isWritable: false },
388
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: false },
389
+ { pubkey: position, isSigner: positionIsSigner, isWritable: true },
390
+ { pubkey: lbPair, isSigner: false, isWritable: true },
391
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
392
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
393
+ { pubkey: reserveX, isSigner: false, isWritable: true },
394
+ { pubkey: reserveY, isSigner: false, isWritable: true },
395
+ { pubkey: tokenXMint, isSigner: false, isWritable: false },
396
+ { pubkey: tokenYMint, isSigner: false, isWritable: false },
397
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false },
398
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false },
399
+ {
400
+ pubkey: actualBinArrayBitmapExtension,
401
+ isSigner: false,
402
+ isWritable: true,
403
+ },
404
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: true },
405
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: true },
406
+ ...remainingAccounts,
407
+ ],
408
+ programId: addresses_1.IYF_EXTENSION,
409
+ });
410
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
411
+ userPda,
412
+ authority: addresses_1.HS_AUTHORITY,
413
+ ix: depositIx,
414
+ });
415
+ });
416
+ }
417
+ redepositAutomation(connection_1, _a) {
418
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, relativeLowerBinId, relativeUpperBinId, strategyType, checkRange, }) {
419
+ // Initialize anchor
420
+ anchor_1.Anchor.initialize(connection);
421
+ // Meteora utility function
422
+ const fn = new meteora_1.MeteoraFunctions(this.ix);
423
+ // Generate user pda
424
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
425
+ // Get meteora pool
426
+ const lbPairInfo = yield anchor_1.Anchor.instance().meteoraProgram.account.lbPair.fetch(lbPair);
427
+ const tokenXMint = lbPairInfo.tokenXMint;
428
+ const tokenYMint = lbPairInfo.tokenYMint;
429
+ const reserveX = lbPairInfo.reserveX;
430
+ const reserveY = lbPairInfo.reserveY;
431
+ const userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint);
432
+ const userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint);
433
+ const activeBinId = lbPairInfo.activeId;
434
+ const MAX_BIN_ARRAY_SIZE = new bn_js_1.default(anchor_1.Anchor.instance().meteoraProgram.idl.constants[1].value);
435
+ // Get min and max bin id values from checkRange threshold
436
+ const { minBinId, maxBinId } = checkRange;
437
+ let _checkRange = [minBinId, maxBinId];
438
+ // Note: relative lower & upper bins can be positive or negative
439
+ const expectedMinBinId = activeBinId + relativeLowerBinId;
440
+ const expectedMaxBinId = activeBinId + relativeUpperBinId;
441
+ if (expectedMaxBinId < expectedMinBinId) {
442
+ throw new Error('Invalid bin range');
443
+ }
444
+ // get min and max bin +- 3
445
+ // this is to ensure that we allow for some buffer
446
+ let lowerTickArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, expectedMinBinId - 3, expectedMinBinId + 3);
447
+ let upperTickArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, expectedMaxBinId - 3, expectedMaxBinId + 3);
448
+ // Merge and remove duplicates
449
+ // it will handle overlapping tick arrays
450
+ // if lower is 1 2 3 4 5 6 7 and upper is 3 4 5 6 7 8 9
451
+ // we want to merge it to 1 2 3 4 5 6 7 8 9
452
+ const tickArrays = [
453
+ ...new Set([...lowerTickArrays, ...upperTickArrays]),
454
+ ];
455
+ // comment out for reference
456
+ // const lowerBinArrayIndex = fn.binIdToBinArrayIndex(MAX_BIN_ARRAY_SIZE, new BN(activeBinId - relativeLowerBinId));
457
+ // const binArrayLower = fn.deriveBinArray(lbPair, lowerBinArrayIndex);
458
+ // const binArrayUpper = fn.deriveBinArray(lbPair, lowerBinArrayIndex.add(new BN(1)));
459
+ // comment out for reference
460
+ // let _checkRange: null | [number, number];
461
+ // if (!!checkRange) {
462
+ // const { minBinId, maxBinId } = checkRange;
463
+ // _checkRange = [minBinId, maxBinId];
464
+ // } else {
465
+ // _checkRange = null;
466
+ // }
467
+ // Generate instruction
468
+ return this.ix.iyfMain.iyfExtensionExecute(connection, {
469
+ userWallet,
470
+ // @ts-ignore
471
+ iyfExtensionIx: yield anchor_1.Anchor.instance()
472
+ .iyfExtension.methods.meteoraDlmmRedepositAutomation(relativeLowerBinId, relativeUpperBinId, mapOldStrategyTypeToNew(strategyType), _checkRange)
473
+ .accounts({
474
+ farm: addresses_1.USDC_FARM,
475
+ userPda,
476
+ authority: userWallet,
477
+ iyfProgram: addresses_1.IYF_MAIN,
478
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
479
+ position,
480
+ lbPair,
481
+ userTokenX,
482
+ userTokenY,
483
+ reserveX,
484
+ reserveY,
485
+ tokenXMint,
486
+ tokenYMint,
487
+ // binArrayLower,
488
+ // binArrayUpper,
489
+ systemProgram: web3.SystemProgram.programId,
490
+ tokenProgram: addresses_1.TOKEN_PROGRAM_ID,
491
+ rent: web3.SYSVAR_RENT_PUBKEY,
492
+ eventAuthority: METEORA_EVENT_AUTHORITY,
493
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
494
+ })
495
+ .remainingAccounts(tickArrays.map((pubkey) => {
496
+ return { pubkey, isSigner: false, isWritable: true };
497
+ }))
498
+ .instruction(),
499
+ });
500
+ });
501
+ }
502
+ redepositAutomation2(connection_1, _a) {
503
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, relativeLowerBinId, relativeUpperBinId, strategyType, checkRange, targetActiveBin, }) {
504
+ try {
505
+ console.log('=== REDEPOSIT AUTOMATION 2 START ===');
506
+ console.log('Parameters:', {
507
+ userWallet: userWallet.toString(),
508
+ lbPair: lbPair.toString(),
509
+ position: position.toString(),
510
+ relativeLowerBinId,
511
+ relativeUpperBinId,
512
+ strategyType,
513
+ checkRange,
514
+ });
515
+ // Initialize anchor
516
+ anchor_1.Anchor.initialize(connection);
517
+ // Meteora utility function
518
+ // const fn = new MeteoraFunctions(this.ix);
519
+ // Generate user pda
520
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
521
+ console.log('User PDA generated:', userPda.toString());
522
+ // Get meteora pool
523
+ console.log('Fetching LB pair info...');
524
+ const lbPairInfo = yield anchor_1.Anchor.instance().meteoraProgram.account.lbPair.fetch(lbPair);
525
+ const tokenXMint = lbPairInfo.tokenXMint;
526
+ const tokenYMint = lbPairInfo.tokenYMint;
527
+ const mintAInfo = AccountCache_1.AccountCache.get(tokenXMint);
528
+ const mintBInfo = AccountCache_1.AccountCache.get(tokenYMint);
529
+ const tokenProgramA = mintAInfo === null || mintAInfo === void 0 ? void 0 : mintAInfo.info.owner;
530
+ const tokenProgramB = mintBInfo === null || mintBInfo === void 0 ? void 0 : mintBInfo.info.owner;
531
+ const reserveX = lbPairInfo.reserveX;
532
+ const reserveY = lbPairInfo.reserveY;
533
+ const userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, mintAInfo === null || mintAInfo === void 0 ? void 0 : mintAInfo.info.owner);
534
+ const userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, mintBInfo === null || mintBInfo === void 0 ? void 0 : mintBInfo.info.owner);
535
+ let activeBinId = lbPairInfo.activeId;
536
+ if (!!targetActiveBin) {
537
+ activeBinId = targetActiveBin;
538
+ }
539
+ console.log('LB pair info:', {
540
+ tokenXMint: tokenXMint.toString(),
541
+ tokenYMint: tokenYMint.toString(),
542
+ activeBinId: activeBinId.toString(),
543
+ });
544
+ // const MAX_BIN_ARRAY_SIZE = new BN(Anchor.instance().meteoraProgram.idl.constants[1].value);
545
+ // Get min and max bin id values from checkRange threshold
546
+ const { minBinId, maxBinId } = checkRange;
547
+ let _checkRange = [minBinId, maxBinId];
548
+ // Note: relative lower & upper bins can be positive or negative
549
+ const expectedMinBinId = activeBinId + relativeLowerBinId;
550
+ const expectedMaxBinId = activeBinId + relativeUpperBinId;
551
+ console.log('Bin calculations:', {
552
+ activeBinId: activeBinId.toString(),
553
+ relativeLowerBinId,
554
+ relativeUpperBinId,
555
+ expectedMinBinId,
556
+ expectedMaxBinId,
557
+ });
558
+ if (expectedMaxBinId < expectedMinBinId) {
559
+ throw new Error('Invalid bin range');
560
+ }
561
+ // get min and max bin +- 3
562
+ // this is to ensure that we allow for some buffer
563
+ // let lowerTickArrays = fn.findMeteoraTickArrays(lbPair, expectedMinBinId - 3, expectedMinBinId + 3);
564
+ // let upperTickArrays = fn.findMeteoraTickArrays(lbPair, expectedMaxBinId - 3, expectedMaxBinId + 3);
565
+ // Merge and remove duplicates
566
+ // it will handle overlapping tick arrays
567
+ // if lower is 1 2 3 4 5 6 7 and upper is 3 4 5 6 7 8 9
568
+ // we want to merge it to 1 2 3 4 5 6 7 8 9
569
+ // const tickArrays: web3.PublicKey[] = [...new Set([...lowerTickArrays, ...upperTickArrays])];
570
+ // comment out for reference
571
+ // const lowerBinArrayIndex = fn.binIdToBinArrayIndex(MAX_BIN_ARRAY_SIZE, new BN(activeBinId - relativeLowerBinId));
572
+ // const binArrayLower = fn.deriveBinArray(lbPair, lowerBinArrayIndex);
573
+ // const binArrayUpper = fn.deriveBinArray(lbPair, lowerBinArrayIndex.add(new BN(1)));
574
+ // comment out for reference
575
+ // let _checkRange: null | [number, number];
576
+ // if (!!checkRange) {
577
+ // const { minBinId, maxBinId } = checkRange;
578
+ // _checkRange = [minBinId, maxBinId];
579
+ // } else {
580
+ // _checkRange = null;
581
+ // }
582
+ console.log('Creating DLMM instance...');
583
+ let DLMM = yield this.dlmm(connection, lbPair);
584
+ console.log('Calling addLiquidityByStrategy...');
585
+ const addLiquidityByStrategyTx = yield DLMM.dlmm.initializePositionAndAddLiquidityByStrategy({
586
+ positionPubKey: position,
587
+ totalXAmount: new bn_js_1.default(0),
588
+ totalYAmount: new bn_js_1.default(0),
589
+ strategy: {
590
+ minBinId: expectedMinBinId,
591
+ maxBinId: expectedMaxBinId,
592
+ strategyType: mapOldStrategyTypeToNew(strategyType),
593
+ },
594
+ user: userWallet,
595
+ });
596
+ console.log('addLiquidityByStrategy completed, instruction count:', addLiquidityByStrategyTx.instructions.length);
597
+ // const addLiquidityByStrategyIxs = addLiquidityByStrategyTx.instructions.filter((ix) => ix.programId.equals(METEORA_DLMM_PROGRAM))
598
+ console.log('Filtering instructions for add_liquidity_by_strategy2...');
599
+ const addLiquidityByStrategyIx = addLiquidityByStrategyTx.instructions.filter(ix => {
600
+ return (ix.programId.equals(METEORA_DLMM_PROGRAM) &&
601
+ ix.data
602
+ .subarray(0, 8)
603
+ .equals(Buffer.from([3, 221, 149, 218, 111, 141, 118, 213])));
604
+ })[0];
605
+ const binArrayBitmapExtension = addLiquidityByStrategyIx.keys[2].pubkey;
606
+ if (!addLiquidityByStrategyIx) {
607
+ throw new Error('add_liquidity_by_strategy2 instruction not found in transaction');
608
+ }
609
+ console.log('Found add_liquidity_by_strategy2 instruction');
610
+ // Log the instruction structure for debugging
611
+ console.log('Instruction keys count:', addLiquidityByStrategyIx.keys.length);
612
+ console.log('Instruction data length:', addLiquidityByStrategyIx.data.length);
613
+ // Find the correct slice point for remaining accounts
614
+ // The remaining accounts typically start after the main accounts (usually around index 10-15)
615
+ const remainingAccountStartIndex = Math.min(14, addLiquidityByStrategyIx.keys.length);
616
+ const remainingAccountMeta = addLiquidityByStrategyIx.keys.slice(remainingAccountStartIndex);
617
+ const strategyParametersStrategyType = addLiquidityByStrategyIx.data[32];
618
+ // const strategyParametersParameters: number[] = new Array(64).fill(0);
619
+ // index 97 onwards are remaining accounts info
620
+ const remainingAccountsInfo = addLiquidityByStrategyIx.data.subarray(97);
621
+ console.log('Remaining accounts start index:', remainingAccountStartIndex);
622
+ console.log('Remaining accounts count:', remainingAccountMeta.length);
623
+ console.log('Remaining accounts info length:', remainingAccountsInfo.length);
624
+ // // Generate IX via extension contract
625
+ // const data = this.ix.data.subarray(8);
626
+ // const activeId = data.subarray(16, 20).readInt32LE();
627
+ // const maxActiveBinSlippage = data.subarray(20, 24).readInt32LE();
628
+ // const strategyParametersMinBinId = data.subarray(24, 28).readInt32LE();
629
+ // const strategyParametersMaxBinId = data.subarray(28, 32).readInt32LE();
630
+ // const strategyParametersStrategyType = data[32];
631
+ // const strategyParametersParameters = Array.from(data.subarray(33, 97));
632
+ // const remainingAccountsInfo = this.ix.data.subarray(97);
633
+ console.log('old strategy type', strategyType);
634
+ console.log('new strategy type', mapOldStrategyTypeToNew(strategyType));
635
+ console.log('strategyParametersStrategyType', strategyParametersStrategyType);
636
+ // Log the first few keys to understand the structure
637
+ console.log('First 5 instruction keys:', addLiquidityByStrategyIx.keys.slice(0, 5).map((key, i) => ({
638
+ index: i,
639
+ pubkey: key.pubkey.toString(),
640
+ isSigner: key.isSigner,
641
+ isWritable: key.isWritable,
642
+ })));
643
+ console.log('Creating extension instruction...');
644
+ // @ts-ignore
645
+ const extensionIx = yield anchor_1.Anchor.instance()
646
+ .iyfExtension.methods.meteoraDlmmRedepositAutomation2(relativeLowerBinId, relativeUpperBinId, strategyType, _checkRange,
647
+ // strategyParametersParameters,
648
+ remainingAccountsInfo)
649
+ .accounts({
650
+ userPda,
651
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
652
+ position,
653
+ lbPair,
654
+ userTokenX,
655
+ userTokenY,
656
+ reserveX,
657
+ reserveY,
658
+ tokenXMint,
659
+ tokenYMint,
660
+ systemProgram: web3.SystemProgram.programId,
661
+ tokenXProgram: tokenProgramA,
662
+ tokenYProgram: tokenProgramB,
663
+ rent: web3.SYSVAR_RENT_PUBKEY,
664
+ eventAuthority: METEORA_EVENT_AUTHORITY,
665
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
666
+ binArrayBitmapExtension,
667
+ })
668
+ .remainingAccounts(remainingAccountMeta.length > 0 ? remainingAccountMeta : [])
669
+ .instruction();
670
+ // Patch binArrayBitmapExtension writable flag: writable only when it's a real PDA, not the program ID placeholder
671
+ const bitmapKey = extensionIx.keys.find(k => k.pubkey.equals(binArrayBitmapExtension));
672
+ if (bitmapKey) {
673
+ bitmapKey.isWritable =
674
+ !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM);
675
+ }
676
+ console.log('Extension instruction created:', {
677
+ keysCount: extensionIx.keys.length,
678
+ dataLength: extensionIx.data.length,
679
+ programId: extensionIx.programId.toString(),
680
+ });
681
+ // Generate instruction
682
+ console.log('Calling iyfExtensionExecuteV2 with:', {
683
+ authority: userWallet.toString(),
684
+ extensionIxKeysCount: extensionIx.keys.length,
685
+ extensionIxProgramId: extensionIx.programId.toString(),
686
+ });
687
+ const sighash = util.sighash('meteora_dlmm_redeposit_automation_2');
688
+ extensionIx.data.set(sighash, 0);
689
+ const ix = yield this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
690
+ userPda,
691
+ authority: addresses_1.HS_AUTHORITY,
692
+ ix: extensionIx,
693
+ });
694
+ console.log('ix data length:', ix.data.length);
695
+ return ix;
696
+ console.log('=== REDEPOSIT AUTOMATION 2 SUCCESS ===');
697
+ }
698
+ catch (error) {
699
+ console.error('=== REDEPOSIT AUTOMATION 2 ERROR ===');
700
+ console.error('Error type:', error instanceof Error ? error.constructor.name : typeof error);
701
+ console.error('Error message:', error instanceof Error ? error.message : String(error));
702
+ console.error('Error stack:', error instanceof Error ? error.stack : 'No stack trace');
703
+ console.error('Full error object:', error);
704
+ console.error('=== END REDEPOSIT ERROR LOG ===');
705
+ throw error;
706
+ }
707
+ });
708
+ }
709
+ relativeOpenAutomation(connection_1, _a) {
710
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, relativeLowerBinId, relativeUpperBinId, strategyType, checkRange, targetActiveBin, userTokenXAmount, userTokenYAmount, useFuelAccount, pdaTokenType, }) {
711
+ try {
712
+ // Initialize anchor
713
+ anchor_1.Anchor.initialize(connection);
714
+ // Generate user pda
715
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
716
+ // Get meteora pool
717
+ const lbPairInfo = yield anchor_1.Anchor.instance().meteoraProgram.account.lbPair.fetch(lbPair);
718
+ const tokenXMint = lbPairInfo.tokenXMint;
719
+ const tokenYMint = lbPairInfo.tokenYMint;
720
+ // Fetch and cache mint accounts so AccountCache.get() returns the token programs
721
+ yield MintCache_1.MintCache.instance(connection)
722
+ .getBatchedMultipleAccountsInfo([tokenXMint, tokenYMint])
723
+ .waitForResult();
724
+ const mintAInfo = AccountCache_1.AccountCache.get(tokenXMint);
725
+ const mintBInfo = AccountCache_1.AccountCache.get(tokenYMint);
726
+ const tokenProgramA = mintAInfo === null || mintAInfo === void 0 ? void 0 : mintAInfo.info.owner;
727
+ const tokenProgramB = mintBInfo === null || mintBInfo === void 0 ? void 0 : mintBInfo.info.owner;
728
+ const reserveX = lbPairInfo.reserveX;
729
+ const reserveY = lbPairInfo.reserveY;
730
+ // Generate user token accounts based on pdaTokenType
731
+ let userTokenX;
732
+ let userTokenY;
733
+ if (pdaTokenType === types_1.TokenType.STA) {
734
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
735
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
736
+ }
737
+ else if (pdaTokenType === types_1.TokenType.LTA) {
738
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
739
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
740
+ }
741
+ else {
742
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenProgramA);
743
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenProgramB);
744
+ }
745
+ let activeBinId = lbPairInfo.activeId;
746
+ if (!!targetActiveBin) {
747
+ activeBinId = targetActiveBin;
748
+ }
749
+ // Get min and max bin id values from checkRange threshold
750
+ const { minBinId, maxBinId } = checkRange;
751
+ let _checkRange = [minBinId, maxBinId];
752
+ // Note: relative lower & upper bins can be positive or negative
753
+ const expectedMinBinId = activeBinId + relativeLowerBinId;
754
+ const expectedMaxBinId = activeBinId + relativeUpperBinId;
755
+ if (expectedMaxBinId < expectedMinBinId) {
756
+ throw new Error('Invalid bin range');
757
+ }
758
+ let DLMM = yield this.dlmm(connection, lbPair);
759
+ const addLiquidityByStrategyTx = yield DLMM.dlmm.initializePositionAndAddLiquidityByStrategy({
760
+ positionPubKey: position,
761
+ totalXAmount: new bn_js_1.default(0),
762
+ totalYAmount: new bn_js_1.default(0),
763
+ strategy: {
764
+ minBinId: expectedMinBinId,
765
+ maxBinId: expectedMaxBinId,
766
+ strategyType: mapOldStrategyTypeToNew(strategyType),
767
+ },
768
+ user: userWallet,
769
+ });
770
+ const addLiquidityByStrategyIx = addLiquidityByStrategyTx.instructions.filter(ix => {
771
+ return (ix.programId.equals(METEORA_DLMM_PROGRAM) &&
772
+ ix.data
773
+ .subarray(0, 8)
774
+ .equals(Buffer.from([3, 221, 149, 218, 111, 141, 118, 213])));
775
+ })[0];
776
+ const binArrayBitmapExtension = addLiquidityByStrategyIx.keys[2].pubkey;
777
+ if (!addLiquidityByStrategyIx) {
778
+ throw new Error('add_liquidity_by_strategy2 instruction not found in transaction');
779
+ }
780
+ const remainingAccountStartIndex = Math.min(14, addLiquidityByStrategyIx.keys.length);
781
+ const remainingAccountMeta = addLiquidityByStrategyIx.keys.slice(remainingAccountStartIndex);
782
+ const remainingAccountsInfo = addLiquidityByStrategyIx.data.subarray(97);
783
+ // @ts-ignore
784
+ const extensionIx = yield anchor_1.Anchor.instance()
785
+ .iyfExtension.methods.meteoraDlmmRelativeOpenAutomation(relativeLowerBinId, relativeUpperBinId, strategyType, userTokenXAmount !== null && userTokenXAmount !== void 0 ? userTokenXAmount : null, userTokenYAmount !== null && userTokenYAmount !== void 0 ? userTokenYAmount : null, _checkRange, remainingAccountsInfo)
786
+ .accounts({
787
+ userPda,
788
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
789
+ position,
790
+ lbPair,
791
+ userTokenX,
792
+ userTokenY,
793
+ reserveX,
794
+ reserveY,
795
+ tokenXMint,
796
+ tokenYMint,
797
+ systemProgram: web3.SystemProgram.programId,
798
+ tokenXProgram: tokenProgramA,
799
+ tokenYProgram: tokenProgramB,
800
+ rent: web3.SYSVAR_RENT_PUBKEY,
801
+ eventAuthority: METEORA_EVENT_AUTHORITY,
802
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
803
+ binArrayBitmapExtension,
804
+ fuelAccount: (0, functions_1.generateFuelAccount)(addresses_1.HS_AUTHORITY),
805
+ })
806
+ .remainingAccounts(remainingAccountMeta.length > 0 ? remainingAccountMeta : [])
807
+ .instruction();
808
+ // Patch binArrayBitmapExtension writable flag: writable only when it's a real PDA, not the program ID placeholder
809
+ const bitmapKey = extensionIx.keys.find(k => k.pubkey.equals(binArrayBitmapExtension));
810
+ if (bitmapKey) {
811
+ bitmapKey.isWritable =
812
+ !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM);
813
+ }
814
+ // Set the correct sighash for the new instruction
815
+ const sighash = util.sighash('meteora_dlmm_relative_open_automation');
816
+ extensionIx.data.set(sighash, 0);
817
+ const ix = yield this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
818
+ userPda,
819
+ authority: addresses_1.HS_AUTHORITY,
820
+ ix: extensionIx,
821
+ });
822
+ return ix;
823
+ }
824
+ catch (error) {
825
+ console.error('=== RELATIVE OPEN AUTOMATION ERROR ===');
826
+ console.error('Error message:', error instanceof Error ? error.message : String(error));
827
+ throw error;
828
+ }
829
+ });
830
+ }
831
+ claimFee(connection, params) {
832
+ return __awaiter(this, void 0, void 0, function* () {
833
+ // Initialize anchor
834
+ anchor_1.Anchor.initialize(connection);
835
+ return new web3.TransactionInstruction({
836
+ data: Buffer.from([]),
837
+ keys: [],
838
+ programId: web3.SystemProgram.programId,
839
+ });
840
+ });
841
+ }
842
+ claimFee2(connection_1, _a) {
843
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, tokenMintX, tokenMintY, tokenProgramX, tokenProgramY, lowerBinId, upperBinId, }) {
844
+ // Initialize anchor
845
+ anchor_1.Anchor.initialize(connection);
846
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
847
+ const reserveX = this.pda.meteora.deriveReserve(tokenMintX, lbPair);
848
+ const reserveY = this.pda.meteora.deriveReserve(tokenMintY, lbPair);
849
+ const userTokenX = (0, functions_1.generateAta)(userPda, tokenMintX, tokenProgramX);
850
+ const userTokenY = (0, functions_1.generateAta)(userPda, tokenMintY, tokenProgramY);
851
+ const ownerFeeX = (0, functions_1.generateAta)(addresses_1.SITE_FEE_OWNER, tokenMintX, tokenProgramX);
852
+ const ownerFeeY = (0, functions_1.generateAta)(addresses_1.SITE_FEE_OWNER, tokenMintY, tokenProgramY);
853
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, lowerBinId, upperBinId);
854
+ const sighash = util.sighash('meteora_dlmm_claim_fee_2');
855
+ const minBinId = Buffer.alloc(4);
856
+ const maxBinId = Buffer.alloc(4);
857
+ const remainingAccountsInfo = Buffer.from(new Uint8Array([0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
858
+ minBinId.writeInt32LE(lowerBinId, 0);
859
+ maxBinId.writeInt32LE(upperBinId, 0);
860
+ return yield this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
861
+ userPda,
862
+ authority: userWallet,
863
+ ix: new web3.TransactionInstruction({
864
+ data: Buffer.concat([
865
+ new Uint8Array(sighash),
866
+ new Uint8Array(minBinId),
867
+ new Uint8Array(maxBinId),
868
+ new Uint8Array(remainingAccountsInfo),
869
+ ]),
870
+ keys: [
871
+ { pubkey: userPda, isSigner: false, isWritable: false },
872
+ { pubkey: userWallet, isSigner: true, isWritable: false },
873
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
874
+ { pubkey: lbPair, isSigner: false, isWritable: true },
875
+ { pubkey: position, isSigner: false, isWritable: true },
876
+ { pubkey: reserveX, isSigner: false, isWritable: true },
877
+ { pubkey: reserveY, isSigner: false, isWritable: true },
878
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
879
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
880
+ { pubkey: tokenMintX, isSigner: false, isWritable: false },
881
+ { pubkey: tokenMintY, isSigner: false, isWritable: false },
882
+ { pubkey: tokenProgramX, isSigner: false, isWritable: false },
883
+ { pubkey: tokenProgramY, isSigner: false, isWritable: false },
884
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false },
885
+ {
886
+ pubkey: METEORA_EVENT_AUTHORITY,
887
+ isSigner: false,
888
+ isWritable: false,
889
+ },
890
+ { pubkey: ownerFeeX, isSigner: false, isWritable: true },
891
+ { pubkey: ownerFeeY, isSigner: false, isWritable: true },
892
+ ...binArrays.map(binArray => ({
893
+ pubkey: binArray,
894
+ isSigner: false,
895
+ isWritable: true,
896
+ })),
897
+ ],
898
+ programId: addresses_1.IYF_EXTENSION,
899
+ }),
900
+ });
901
+ });
902
+ }
903
+ claimReward(connection, params) {
904
+ return __awaiter(this, void 0, void 0, function* () {
905
+ // Initialize anchor
906
+ anchor_1.Anchor.initialize(connection);
907
+ return new web3.TransactionInstruction({
908
+ data: Buffer.from([]),
909
+ keys: [],
910
+ programId: web3.SystemProgram.programId,
911
+ });
912
+ });
913
+ }
914
+ claimReward2(connection_1, _a) {
915
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, rewardIndex, rewardMint, rewardVault, tokenProgram, lowerBinId, upperBinId, }) {
916
+ // Initialize anchor
917
+ anchor_1.Anchor.initialize(connection);
918
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
919
+ const userTokenAccount = (0, functions_1.generateAta)(userPda, rewardMint);
920
+ const ownerFee = (0, functions_1.generateAta)(addresses_1.SITE_FEE_OWNER, rewardMint, tokenProgram);
921
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, lowerBinId, upperBinId);
922
+ const sighash = util.sighash('meteora_dlmm_claim_reward_2');
923
+ const minBinId = Buffer.alloc(4);
924
+ const maxBinId = Buffer.alloc(4);
925
+ const remainingAccountsInfo = Buffer.from(new Uint8Array([
926
+ 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00,
927
+ ]));
928
+ minBinId.writeInt32LE(lowerBinId, 0);
929
+ maxBinId.writeInt32LE(upperBinId, 0);
930
+ return yield this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
931
+ userPda,
932
+ authority: userWallet,
933
+ ix: new web3.TransactionInstruction({
934
+ data: Buffer.concat([
935
+ new Uint8Array(sighash),
936
+ new Uint8Array([rewardIndex]),
937
+ new Uint8Array(minBinId),
938
+ new Uint8Array(maxBinId),
939
+ new Uint8Array(remainingAccountsInfo),
940
+ ]),
941
+ keys: [
942
+ { pubkey: userPda, isSigner: false, isWritable: false },
943
+ { pubkey: userWallet, isSigner: true, isWritable: false },
944
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
945
+ { pubkey: lbPair, isSigner: false, isWritable: true },
946
+ { pubkey: position, isSigner: false, isWritable: true },
947
+ { pubkey: rewardVault, isSigner: false, isWritable: true },
948
+ { pubkey: rewardMint, isSigner: false, isWritable: true },
949
+ { pubkey: userTokenAccount, isSigner: false, isWritable: true },
950
+ { pubkey: tokenProgram, isSigner: false, isWritable: true },
951
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false },
952
+ {
953
+ pubkey: METEORA_EVENT_AUTHORITY,
954
+ isSigner: false,
955
+ isWritable: false,
956
+ },
957
+ { pubkey: ownerFee, isSigner: false, isWritable: true },
958
+ ...binArrays.map(binArray => ({
959
+ pubkey: binArray,
960
+ isSigner: false,
961
+ isWritable: true,
962
+ })),
963
+ ],
964
+ programId: addresses_1.IYF_EXTENSION,
965
+ }),
966
+ });
967
+ });
968
+ }
969
+ /**
970
+ * Claim fees from a Meteora DLMM position via IYF Extension for automation.
971
+ *
972
+ * This is the automation version that uses HS_AUTHORITY as the signer.
973
+ *
974
+ * @param connection - Solana connection
975
+ * @param params - ClaimFee2AutomationParams parameters
976
+ * @returns TransactionInstruction for the claim_fee2 automation operation
977
+ */
978
+ claimFee2Automation(connection_1, _a) {
979
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, tokenMintX, tokenMintY, tokenProgramX, tokenProgramY, lowerBinId, upperBinId, pdaTokenType, remainingAccountsInfo, }) {
980
+ var _b, _c;
981
+ // Initialize anchor
982
+ anchor_1.Anchor.initialize(connection);
983
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
984
+ const reserveX = this.pda.meteora.deriveReserve(tokenMintX, lbPair);
985
+ const reserveY = this.pda.meteora.deriveReserve(tokenMintY, lbPair);
986
+ // Generate user token accounts based on pdaTokenType
987
+ let userTokenX;
988
+ let userTokenY;
989
+ if (pdaTokenType === types_1.TokenType.LTA) {
990
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenMintX);
991
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenMintY);
992
+ }
993
+ else if (pdaTokenType === types_1.TokenType.STA) {
994
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenMintX);
995
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenMintY);
996
+ }
997
+ else {
998
+ // Default: ATA
999
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenMintX, tokenProgramX);
1000
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenMintY, tokenProgramY);
1001
+ }
1002
+ const ownerFeeX = (0, functions_1.generateAta)(addresses_1.SITE_FEE_OWNER, tokenMintX, tokenProgramX);
1003
+ const ownerFeeY = (0, functions_1.generateAta)(addresses_1.SITE_FEE_OWNER, tokenMintY, tokenProgramY);
1004
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, lowerBinId, upperBinId);
1005
+ const sighash = util.sighash('meteora_dlmm_claim_fee_2_automation');
1006
+ const minBinId = Buffer.alloc(4);
1007
+ const maxBinId = Buffer.alloc(4);
1008
+ minBinId.writeInt32LE(lowerBinId, 0);
1009
+ maxBinId.writeInt32LE(upperBinId, 0);
1010
+ // Serialize RemainingAccountsInfo with Vec<u8> length prefix for Anchor
1011
+ const remainingAccountsInfoContent = this.serializeRemainingAccountsInfo({
1012
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : [],
1013
+ });
1014
+ // For Anchor Vec<u8> parameter, we need to prepend the length as u32 LE
1015
+ const remainingAccountsInfoVec = Buffer.alloc(4 + remainingAccountsInfoContent.length);
1016
+ remainingAccountsInfoVec.writeUInt32LE(remainingAccountsInfoContent.length, 0);
1017
+ remainingAccountsInfoContent.copy(remainingAccountsInfoVec, 4);
1018
+ return yield this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
1019
+ userPda,
1020
+ authority: addresses_1.HS_AUTHORITY,
1021
+ ix: new web3.TransactionInstruction({
1022
+ data: Buffer.concat([
1023
+ new Uint8Array(sighash),
1024
+ new Uint8Array(minBinId),
1025
+ new Uint8Array(maxBinId),
1026
+ new Uint8Array(remainingAccountsInfoVec),
1027
+ ]),
1028
+ keys: [
1029
+ { pubkey: userPda, isSigner: false, isWritable: false },
1030
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: false },
1031
+ { pubkey: lbPair, isSigner: false, isWritable: true },
1032
+ { pubkey: position, isSigner: false, isWritable: true },
1033
+ { pubkey: reserveX, isSigner: false, isWritable: true },
1034
+ { pubkey: reserveY, isSigner: false, isWritable: true },
1035
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
1036
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
1037
+ { pubkey: tokenMintX, isSigner: false, isWritable: false },
1038
+ { pubkey: tokenMintY, isSigner: false, isWritable: false },
1039
+ { pubkey: tokenProgramX, isSigner: false, isWritable: false },
1040
+ { pubkey: tokenProgramY, isSigner: false, isWritable: false },
1041
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false },
1042
+ {
1043
+ pubkey: METEORA_EVENT_AUTHORITY,
1044
+ isSigner: false,
1045
+ isWritable: false,
1046
+ },
1047
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1048
+ { pubkey: ownerFeeX, isSigner: false, isWritable: true },
1049
+ { pubkey: ownerFeeY, isSigner: false, isWritable: true },
1050
+ ...binArrays.map(binArray => ({
1051
+ pubkey: binArray,
1052
+ isSigner: false,
1053
+ isWritable: true,
1054
+ })),
1055
+ // Transfer hook accounts (if any)
1056
+ ...((_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : []),
1057
+ ],
1058
+ programId: addresses_1.IYF_EXTENSION,
1059
+ }),
1060
+ });
1061
+ });
1062
+ }
1063
+ /**
1064
+ * Claim rewards from a Meteora DLMM position via IYF Extension for automation.
1065
+ *
1066
+ * This is the automation version that uses HS_AUTHORITY as the signer.
1067
+ *
1068
+ * @param connection - Solana connection
1069
+ * @param params - ClaimReward2AutomationParams parameters
1070
+ * @returns TransactionInstruction for the claim_reward2 automation operation
1071
+ */
1072
+ claimReward2Automation(connection_1, _a) {
1073
+ return __awaiter(this, arguments, void 0, function* (connection, { userWallet, lbPair, position, rewardIndex, rewardMint, rewardVault, tokenProgram, lowerBinId, upperBinId, pdaTokenType, remainingAccountsInfo, }) {
1074
+ var _b, _c;
1075
+ // Initialize anchor
1076
+ anchor_1.Anchor.initialize(connection);
1077
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1078
+ // Generate user token account based on pdaTokenType
1079
+ let userTokenAccount;
1080
+ if (pdaTokenType === types_1.TokenType.LTA) {
1081
+ userTokenAccount = (0, functions_1.generateLimitToken)(userPda, rewardMint);
1082
+ }
1083
+ else if (pdaTokenType === types_1.TokenType.STA) {
1084
+ userTokenAccount = (0, functions_1.generateUserPdaStorageAccount)(userPda, rewardMint);
1085
+ }
1086
+ else {
1087
+ // Default: ATA
1088
+ userTokenAccount = (0, functions_1.generateAta)(userPda, rewardMint, tokenProgram);
1089
+ }
1090
+ const ownerFee = (0, functions_1.generateAta)(addresses_1.SITE_FEE_OWNER, rewardMint, tokenProgram);
1091
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, lowerBinId, upperBinId);
1092
+ const sighash = util.sighash('meteora_dlmm_claim_reward_2_automation');
1093
+ const minBinId = Buffer.alloc(4);
1094
+ const maxBinId = Buffer.alloc(4);
1095
+ minBinId.writeInt32LE(lowerBinId, 0);
1096
+ maxBinId.writeInt32LE(upperBinId, 0);
1097
+ // Serialize RemainingAccountsInfo with Vec<u8> length prefix for Anchor
1098
+ const remainingAccountsInfoContent = this.serializeRemainingAccountsInfo({
1099
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : [],
1100
+ });
1101
+ // For Anchor Vec<u8> parameter, we need to prepend the length as u32 LE
1102
+ const remainingAccountsInfoVec = Buffer.alloc(4 + remainingAccountsInfoContent.length);
1103
+ remainingAccountsInfoVec.writeUInt32LE(remainingAccountsInfoContent.length, 0);
1104
+ remainingAccountsInfoContent.copy(remainingAccountsInfoVec, 4);
1105
+ // Serialize rewardIndex as u64 (8 bytes, little endian)
1106
+ const rewardIndexBuffer = Buffer.alloc(8);
1107
+ rewardIndexBuffer.writeBigUInt64LE(BigInt(rewardIndex), 0);
1108
+ return yield this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
1109
+ userPda,
1110
+ authority: addresses_1.HS_AUTHORITY,
1111
+ ix: new web3.TransactionInstruction({
1112
+ data: Buffer.concat([
1113
+ new Uint8Array(sighash),
1114
+ new Uint8Array(rewardIndexBuffer),
1115
+ new Uint8Array(minBinId),
1116
+ new Uint8Array(maxBinId),
1117
+ new Uint8Array(remainingAccountsInfoVec),
1118
+ ]),
1119
+ keys: [
1120
+ { pubkey: userPda, isSigner: false, isWritable: false },
1121
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: false },
1122
+ { pubkey: lbPair, isSigner: false, isWritable: true },
1123
+ { pubkey: position, isSigner: false, isWritable: true },
1124
+ { pubkey: rewardVault, isSigner: false, isWritable: true },
1125
+ { pubkey: rewardMint, isSigner: false, isWritable: true },
1126
+ { pubkey: userTokenAccount, isSigner: false, isWritable: true },
1127
+ { pubkey: tokenProgram, isSigner: false, isWritable: true },
1128
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false },
1129
+ {
1130
+ pubkey: METEORA_EVENT_AUTHORITY,
1131
+ isSigner: false,
1132
+ isWritable: false,
1133
+ },
1134
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1135
+ { pubkey: ownerFee, isSigner: false, isWritable: true },
1136
+ ...binArrays.map(binArray => ({
1137
+ pubkey: binArray,
1138
+ isSigner: false,
1139
+ isWritable: true,
1140
+ })),
1141
+ // Transfer hook accounts (if any)
1142
+ ...((_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : []),
1143
+ ],
1144
+ programId: addresses_1.IYF_EXTENSION,
1145
+ }),
1146
+ });
1147
+ });
1148
+ }
1149
+ depositAutomation(connection, params) {
1150
+ return __awaiter(this, void 0, void 0, function* () {
1151
+ // Initialize anchor
1152
+ anchor_1.Anchor.initialize(connection);
1153
+ const userPda = (0, functions_1.generateUserPda)(params.userWallet);
1154
+ let userTokenX;
1155
+ let userTokenY;
1156
+ if (params.tokenType === types_1.TokenType.LTA) {
1157
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, params.tokenXMint);
1158
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, params.tokenYMint);
1159
+ }
1160
+ else if (params.tokenType === types_1.TokenType.STA) {
1161
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, params.tokenXMint);
1162
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, params.tokenYMint);
1163
+ }
1164
+ else {
1165
+ userTokenX = (0, functions_1.generateAta)(userPda, params.tokenXMint);
1166
+ userTokenY = (0, functions_1.generateAta)(userPda, params.tokenYMint);
1167
+ }
1168
+ // @ts-ignore
1169
+ const ix = yield anchor_1.Anchor.instance()
1170
+ .iyfExtension.methods.meteoraDlmmDepositAutomation(params.activeId, params.maxActiveBinSlippage, params.strategyParametersMinBinId, params.strategyParametersMaxBinId, params.strategyParametersStrategyType, params.strategyParametersParameters)
1171
+ .accounts({
1172
+ farm: addresses_1.USDC_FARM,
1173
+ userPda,
1174
+ authority: params.userWallet,
1175
+ iyfProgram: addresses_1.IYF_MAIN,
1176
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
1177
+ position: params.position,
1178
+ lbPair: params.lbPair,
1179
+ binArrayBitmapExtension: params.binArrayBitmapExtension,
1180
+ userTokenX,
1181
+ userTokenY,
1182
+ reserveX: params.reserveX,
1183
+ reserveY: params.reserveY,
1184
+ tokenXMint: params.tokenXMint,
1185
+ tokenYMint: params.tokenYMint,
1186
+ binArrayLower: params.binArrayLower,
1187
+ binArrayUpper: params.binArrayUpper,
1188
+ tokenXProgram: params.tokenXProgram,
1189
+ tokenYProgram: params.tokenYProgram,
1190
+ eventAuthority: METEORA_EVENT_AUTHORITY,
1191
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
1192
+ })
1193
+ .instruction();
1194
+ // Patch binArrayBitmapExtension writable flag: writable only when it's a real PDA, not the program ID placeholder
1195
+ const bitmapKey = ix.keys.find(k => k.pubkey.equals(params.binArrayBitmapExtension));
1196
+ if (bitmapKey) {
1197
+ bitmapKey.isWritable =
1198
+ !params.binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM);
1199
+ }
1200
+ return yield this.ix.iyfMain.iyfExtensionExecute(connection, {
1201
+ userWallet: params.userWallet,
1202
+ iyfExtensionIx: ix,
1203
+ });
1204
+ });
1205
+ }
1206
+ depositWithAmountAutomation(connection, params) {
1207
+ return __awaiter(this, void 0, void 0, function* () {
1208
+ // Initialize anchor
1209
+ anchor_1.Anchor.initialize(connection);
1210
+ const userPda = (0, functions_1.generateUserPda)(params.userWallet);
1211
+ let userTokenX;
1212
+ let userTokenY;
1213
+ if (params.tokenType === types_1.TokenType.LTA) {
1214
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, params.tokenXMint);
1215
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, params.tokenYMint);
1216
+ }
1217
+ else if (params.tokenType === types_1.TokenType.STA) {
1218
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, params.tokenXMint);
1219
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, params.tokenYMint);
1220
+ }
1221
+ else {
1222
+ userTokenX = (0, functions_1.generateAta)(userPda, params.tokenXMint);
1223
+ userTokenY = (0, functions_1.generateAta)(userPda, params.tokenYMint);
1224
+ }
1225
+ // @ts-ignore
1226
+ const ix = yield anchor_1.Anchor.instance()
1227
+ .iyfExtension.methods.meteoraDlmmDepositWithAmountAutomation(params.activeId, params.maxActiveBinSlippage, params.strategyParametersMinBinId, params.strategyParametersMaxBinId, params.strategyParametersStrategyType, params.strategyParametersParameters, params.userTokenXAmount, params.userTokenYAmount)
1228
+ .accounts({
1229
+ farm: addresses_1.USDC_FARM,
1230
+ userPda,
1231
+ authority: params.userWallet,
1232
+ iyfProgram: addresses_1.IYF_MAIN,
1233
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
1234
+ position: params.position,
1235
+ lbPair: params.lbPair,
1236
+ binArrayBitmapExtension: params.binArrayBitmapExtension,
1237
+ userTokenX,
1238
+ userTokenY,
1239
+ reserveX: params.reserveX,
1240
+ reserveY: params.reserveY,
1241
+ tokenXMint: params.tokenXMint,
1242
+ tokenYMint: params.tokenYMint,
1243
+ binArrayLower: params.binArrayLower,
1244
+ binArrayUpper: params.binArrayUpper,
1245
+ tokenXProgram: params.tokenXProgram,
1246
+ tokenYProgram: params.tokenYProgram,
1247
+ eventAuthority: METEORA_EVENT_AUTHORITY,
1248
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
1249
+ })
1250
+ .instruction();
1251
+ // Patch binArrayBitmapExtension writable flag: writable only when it's a real PDA, not the program ID placeholder
1252
+ const bitmapKey = ix.keys.find(k => k.pubkey.equals(params.binArrayBitmapExtension));
1253
+ if (bitmapKey) {
1254
+ bitmapKey.isWritable =
1255
+ !params.binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM);
1256
+ }
1257
+ return yield this.ix.iyfMain.iyfExtensionExecute(connection, {
1258
+ userWallet: params.userWallet,
1259
+ iyfExtensionIx: ix,
1260
+ });
1261
+ });
1262
+ }
1263
+ /**
1264
+ * Add liquidity to an existing Meteora DLMM position using strategy parameters.
1265
+ * This is the automation version that uses V2 execution (meteora_dlmm_deposit_2_automation).
1266
+ *
1267
+ * Key differences from depositAutomation:
1268
+ * - Uses iyfExtensionExecuteV2 with Anchor-based instruction building
1269
+ * - Supports remainingAccountsInfo for Token2022 transfer hooks
1270
+ * - Authority is HS_AUTHORITY (automation wallet)
1271
+ * - Does not require binArrayLower/binArrayUpper (bin arrays are auto-derived or created separately)
1272
+ *
1273
+ * @param connection - Solana connection
1274
+ * @param params - AddLiquidityByStrategy2AutomationParams parameters
1275
+ * @returns TransactionInstruction for adding liquidity
1276
+ */
1277
+ addLiquidityByStrategy2Automation(connection, params) {
1278
+ return __awaiter(this, void 0, void 0, function* () {
1279
+ var _a, _b, _c, _d, _e, _f;
1280
+ // Initialize anchor
1281
+ anchor_1.Anchor.initialize(connection);
1282
+ // Derive reserves from the ACTUAL lbPair (not the one passed in, which may be incorrect)
1283
+ const actualReserveX = this.pda.meteora.deriveReserve(params.tokenXMint, params.lbPair);
1284
+ const actualReserveY = this.pda.meteora.deriveReserve(params.tokenYMint, params.lbPair);
1285
+ const userPda = (0, functions_1.generateUserPda)(params.userWallet);
1286
+ // Determine user token accounts based on pdaTokenType
1287
+ let userTokenX;
1288
+ let userTokenY;
1289
+ if (params.pdaTokenType === types_1.TokenType.LTA) {
1290
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, params.tokenXMint);
1291
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, params.tokenYMint);
1292
+ }
1293
+ else if (params.pdaTokenType === types_1.TokenType.STA) {
1294
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, params.tokenXMint);
1295
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, params.tokenYMint);
1296
+ }
1297
+ else {
1298
+ // Default: ATA
1299
+ userTokenX = (0, functions_1.generateAta)(userPda, params.tokenXMint, params.tokenXProgram);
1300
+ userTokenY = (0, functions_1.generateAta)(userPda, params.tokenYMint, params.tokenYProgram);
1301
+ }
1302
+ // Derive bin array bitmap extension
1303
+ const lowerBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(params.strategyParametersMinBinId));
1304
+ const upperBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(params.strategyParametersMaxBinId));
1305
+ const binArrayBitmapExtension = this.isOverflowDefaultBinArrayBitmap(lowerBinArrayIndex) ||
1306
+ this.isOverflowDefaultBinArrayBitmap(upperBinArrayIndex)
1307
+ ? this.pda.meteora.deriveBinArrayBitmapExtension(params.lbPair)
1308
+ : METEORA_DLMM_PROGRAM;
1309
+ // Serialize RemainingAccountsInfo as Vec<u8> (Borsh format)
1310
+ // This is passed directly to the on-chain instruction which forwards it to Meteora
1311
+ // For SPL tokens (non-Token2022), we still need to provide the slices structure with length=0
1312
+ // This matches what Meteora SDK's getPotentialToken2022IxDataAndAccounts returns
1313
+ // AccountsType enum: 0=TransferHookX, 1=TransferHookY, 2=TransferHookReward
1314
+ const defaultSlices = [
1315
+ { accountsType: 0, length: 0 }, // TransferHookX with 0 accounts
1316
+ { accountsType: 1, length: 0 }, // TransferHookY with 0 accounts
1317
+ ];
1318
+ const remainingAccountsInfoSerialized = this.serializeRemainingAccountsInfo({
1319
+ slices: (_b = (_a = params.remainingAccountsInfo) === null || _a === void 0 ? void 0 : _a.slices) !== null && _b !== void 0 ? _b : defaultSlices,
1320
+ });
1321
+ // Use strategy parameters directly as absolute bin IDs
1322
+ // strategyParametersMinBinId and strategyParametersMaxBinId are ABSOLUTE bin IDs, not deltas from activeId
1323
+ const lowerBinId = params.strategyParametersMinBinId;
1324
+ const upperBinId = params.strategyParametersMaxBinId;
1325
+ // Derive bin arrays needed for the deposit range using the lbPair from position
1326
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(params.lbPair, lowerBinId, upperBinId);
1327
+ const binArrayAccounts = binArrays.map(binArray => ({
1328
+ pubkey: binArray,
1329
+ isSigner: false,
1330
+ isWritable: true,
1331
+ }));
1332
+ // Build remaining accounts: Token2022 transfer hook accounts first (described by remainingAccountsInfo),
1333
+ // then bin arrays (not described - Meteora expects them at the end after transfer hooks)
1334
+ const remainingAccounts = [
1335
+ ...((_d = (_c = params.remainingAccountsInfo) === null || _c === void 0 ? void 0 : _c.accounts) !== null && _d !== void 0 ? _d : []),
1336
+ ...binArrayAccounts,
1337
+ ];
1338
+ // Use Anchor to serialize the instruction (ensures proper Borsh serialization)
1339
+ // @ts-ignore
1340
+ const depositIx = yield anchor_1.Anchor.instance()
1341
+ .iyfExtension.methods.meteoraDlmmDeposit2Automation((_e = params.userTokenXAmount) !== null && _e !== void 0 ? _e : null, // Option<u64>
1342
+ (_f = params.userTokenYAmount) !== null && _f !== void 0 ? _f : null, // Option<u64>
1343
+ params.activeId, params.maxActiveBinSlippage, params.strategyParametersMinBinId, params.strategyParametersMaxBinId, params.strategyParametersStrategyType, params.strategyParametersParameters, Buffer.from(remainingAccountsInfoSerialized))
1344
+ .accounts({
1345
+ userPda,
1346
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
1347
+ position: params.position,
1348
+ lbPair: params.lbPair,
1349
+ binArrayBitmapExtension,
1350
+ userTokenX,
1351
+ userTokenY,
1352
+ reserveX: actualReserveX,
1353
+ reserveY: actualReserveY,
1354
+ tokenXMint: params.tokenXMint,
1355
+ tokenYMint: params.tokenYMint,
1356
+ tokenXProgram: params.tokenXProgram,
1357
+ tokenYProgram: params.tokenYProgram,
1358
+ eventAuthority: METEORA_EVENT_AUTHORITY,
1359
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
1360
+ memoProgram: addresses_1.MEMO_PROGRAM,
1361
+ })
1362
+ .remainingAccounts(remainingAccounts)
1363
+ .instruction();
1364
+ // Patch binArrayBitmapExtension writable flag: writable only when it's a real PDA, not the program ID placeholder
1365
+ const bitmapKey = depositIx.keys.find(k => k.pubkey.equals(binArrayBitmapExtension));
1366
+ if (bitmapKey) {
1367
+ bitmapKey.isWritable =
1368
+ !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM);
1369
+ }
1370
+ // Override sighash: Anchor's TypeScript client generates a different sighash than what
1371
+ // the on-chain program expects. We need to manually set the correct sighash.
1372
+ const sighash = util.sighash('meteora_dlmm_deposit_2_automation');
1373
+ depositIx.data.set(sighash, 0);
1374
+ // Generate instruction via IYF Main ExecuteV2
1375
+ // @ts-ignore
1376
+ const ix = yield anchor_1.Anchor.instance()
1377
+ .iyfMain.methods.iyfExtensionExecuteV2(depositIx.data)
1378
+ .accounts({
1379
+ userPda,
1380
+ authority: addresses_1.HS_AUTHORITY,
1381
+ iyfExtensionProgram: addresses_1.IYF_EXTENSION,
1382
+ })
1383
+ .remainingAccounts(depositIx.keys.slice(2))
1384
+ .instruction();
1385
+ return ix;
1386
+ });
1387
+ }
1388
+ oneSideDeposit(connection, params) {
1389
+ return __awaiter(this, void 0, void 0, function* () {
1390
+ // Initialize anchor
1391
+ anchor_1.Anchor.initialize(connection);
1392
+ return new web3.TransactionInstruction({
1393
+ data: Buffer.from([]),
1394
+ keys: [],
1395
+ programId: web3.SystemProgram.programId,
1396
+ });
1397
+ });
1398
+ }
1399
+ withdrawAutomation(connection, params) {
1400
+ return __awaiter(this, void 0, void 0, function* () {
1401
+ // Initialize anchor
1402
+ anchor_1.Anchor.initialize(connection);
1403
+ return new web3.TransactionInstruction({
1404
+ data: Buffer.from([]),
1405
+ keys: [],
1406
+ programId: web3.SystemProgram.programId,
1407
+ });
1408
+ });
1409
+ }
1410
+ closePositionAutomation(connection, params) {
1411
+ return __awaiter(this, void 0, void 0, function* () {
1412
+ // Initialize anchor
1413
+ anchor_1.Anchor.initialize(connection);
1414
+ return new web3.TransactionInstruction({
1415
+ data: Buffer.from([]),
1416
+ keys: [],
1417
+ programId: web3.SystemProgram.programId,
1418
+ });
1419
+ });
1420
+ }
1421
+ /**
1422
+ * Close an empty Meteora DLMM position via IYF Extension for automation.
1423
+ *
1424
+ * This is the automation version that uses HS_AUTHORITY as the signer.
1425
+ *
1426
+ * @param params - ClosePositionIfEmptyAutomationParams parameters
1427
+ * @returns TransactionInstruction for the close_position_if_empty automation operation
1428
+ */
1429
+ closePosition2Automation(_a) {
1430
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, lbPair, useFuelAccount, }) {
1431
+ // Initialize Anchor
1432
+ anchor_1.Anchor.initialize(connection);
1433
+ // Generate user PDA
1434
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1435
+ // Optional fuel account - use userPda as placeholder if not using fuel account
1436
+ // (userPda is already writable, while System Program cannot be writable)
1437
+ const fuelAccount = useFuelAccount
1438
+ ? (0, functions_1.generateFuelAccount)(userWallet)
1439
+ : userPda;
1440
+ // Generate instruction via IYF Extension
1441
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
1442
+ userPda,
1443
+ authority: addresses_1.HS_AUTHORITY,
1444
+ ix: new web3.TransactionInstruction({
1445
+ data: Buffer.from(util.sighash('meteora_dlmm_close_position_automation_v2', undefined, true)),
1446
+ keys: [
1447
+ { pubkey: userPda, isSigner: false, isWritable: false },
1448
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: true },
1449
+ { pubkey: position, isSigner: false, isWritable: true },
1450
+ { pubkey: lbPair, isSigner: false, isWritable: true },
1451
+ {
1452
+ pubkey: METEORA_EVENT_AUTHORITY,
1453
+ isSigner: false,
1454
+ isWritable: false,
1455
+ },
1456
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1457
+ { pubkey: fuelAccount, isSigner: false, isWritable: true },
1458
+ ],
1459
+ programId: addresses_1.IYF_EXTENSION,
1460
+ }),
1461
+ });
1462
+ });
1463
+ }
1464
+ baseClosePosition2Automation(_a) {
1465
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, lbPair, useFuelAccount, isHawkRefund = false, }) {
1466
+ anchor_1.Anchor.initialize(connection);
1467
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1468
+ const fuelAccount = useFuelAccount
1469
+ ? (0, functions_1.generateFuelAccount)(userWallet)
1470
+ : userPda;
1471
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
1472
+ userPda,
1473
+ authority: addresses_1.HS_AUTHORITY,
1474
+ ix: buildBaseClosePosition2AutomationIx({
1475
+ userPda,
1476
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
1477
+ authority: userWallet,
1478
+ position,
1479
+ lbPair,
1480
+ fuelAccount,
1481
+ isHawkRefund,
1482
+ }),
1483
+ });
1484
+ });
1485
+ }
1486
+ limitCloseAutomation(connection, params) {
1487
+ return __awaiter(this, void 0, void 0, function* () {
1488
+ // Initialize anchor
1489
+ anchor_1.Anchor.initialize(connection);
1490
+ return new web3.TransactionInstruction({
1491
+ data: Buffer.from([]),
1492
+ keys: [],
1493
+ programId: web3.SystemProgram.programId,
1494
+ });
1495
+ });
1496
+ }
1497
+ /**
1498
+ * Meteora IDL
1499
+ *
1500
+ * @param connection
1501
+ * @returns
1502
+ */
1503
+ meteora(connection) {
1504
+ return __awaiter(this, void 0, void 0, function* () {
1505
+ return yield meteora_1.MeteoraDLMM.program(connection);
1506
+ });
1507
+ }
1508
+ /**
1509
+ * Meteora IDL
1510
+ *
1511
+ * @param connection
1512
+ * @returns
1513
+ */
1514
+ dlmm(connection, poolAddress) {
1515
+ return __awaiter(this, void 0, void 0, function* () {
1516
+ console.log('dlmm method called with:', {
1517
+ connection: connection ? 'valid' : 'undefined',
1518
+ poolAddress: poolAddress.toString(),
1519
+ ix: this.ix ? 'valid' : 'undefined',
1520
+ });
1521
+ if (!connection) {
1522
+ throw new Error('Connection is undefined in dlmm method');
1523
+ }
1524
+ if (!this.ix) {
1525
+ throw new Error('this.ix is undefined in dlmm method');
1526
+ }
1527
+ return yield meteora_1.MeteoraDLMM.create(connection, poolAddress, this.ix);
1528
+ });
1529
+ }
1530
+ limitOrderCloseV2(_a) {
1531
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, lbPair, tokenXMint, tokenYMint, reserveX, reserveY, tokenXProgram, tokenYProgram, useFuelAccount, param, minBinId, maxBinId, binArrays, }) {
1532
+ // Initialize Anchor
1533
+ anchor_1.Anchor.initialize(connection);
1534
+ // Generate user PDA
1535
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1536
+ // Generate limit tokens
1537
+ const limitTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
1538
+ const limitTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
1539
+ // Generate authority token accounts
1540
+ const authorityTokenX = (0, functions_1.generateAta)(userWallet, tokenXMint, tokenXProgram);
1541
+ const authorityTokenY = (0, functions_1.generateAta)(userWallet, tokenYMint, tokenYProgram);
1542
+ // Generate fee accounts
1543
+ const { ownerFeeX, ownerFeeY } = (0, functions_1.generateHawksightFeeAccounts)(tokenXMint, tokenYMint, tokenXProgram, tokenYProgram);
1544
+ // Create instruction
1545
+ // @ts-ignore
1546
+ const limitOrderCloseV2Ix = yield anchor_1.Anchor.instance()
1547
+ .iyfExtension.methods.limitOrderClose2(param, minBinId, maxBinId)
1548
+ .accounts({
1549
+ userPda,
1550
+ hawksightAuthority: addresses_1.HS_AUTHORITY,
1551
+ authority: userWallet,
1552
+ position,
1553
+ lbPair,
1554
+ binArrayBitmapExtension: METEORA_DLMM_PROGRAM,
1555
+ limitTokenX,
1556
+ limitTokenY,
1557
+ authorityTokenX,
1558
+ authorityTokenY,
1559
+ systemProgram: web3.SystemProgram.programId,
1560
+ reserveX,
1561
+ reserveY,
1562
+ tokenXMint,
1563
+ tokenYMint,
1564
+ tokenXProgram,
1565
+ tokenYProgram,
1566
+ rent: web3.SYSVAR_RENT_PUBKEY,
1567
+ eventAuthority: METEORA_EVENT_AUTHORITY,
1568
+ memoProgram: addresses_1.MEMO_PROGRAM,
1569
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
1570
+ ownerFeeX,
1571
+ ownerFeeY,
1572
+ fuelAccount: useFuelAccount
1573
+ ? (0, functions_1.generateFuelAccount)(userWallet)
1574
+ : web3.SystemProgram.programId,
1575
+ })
1576
+ .remainingAccounts(binArrays.map(pubkey => ({
1577
+ pubkey,
1578
+ isSigner: false,
1579
+ isWritable: true,
1580
+ })))
1581
+ .instruction();
1582
+ const sighash = util.sighash('limit_order_close_2', undefined, true);
1583
+ limitOrderCloseV2Ix.data.set(sighash, 0);
1584
+ // Return the instruction directly (no wrapper needed for Meteora IX Generator)
1585
+ return limitOrderCloseV2Ix;
1586
+ });
1587
+ }
1588
+ meteoraDlmmLimitCloseAutomationV2(_a) {
1589
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, lbPair, tokenXMint, tokenYMint, reserveX, reserveY, tokenXProgram, tokenYProgram, pdaTokenType, param, minBinId, maxBinId, isHawkRefund, useFuelAccount, binArrays, }) {
1590
+ // Initialize Anchor
1591
+ anchor_1.Anchor.initialize(connection);
1592
+ const authority = userWallet;
1593
+ const hawksightAuthority = addresses_1.HS_AUTHORITY;
1594
+ // Generate user PDA
1595
+ const userPda = (0, functions_1.generateUserPda)(userWallet, addresses_1.USDC_FARM);
1596
+ // Generate user token accounts based on pdaTokenType
1597
+ let userTokenX;
1598
+ let userTokenY;
1599
+ if (pdaTokenType === types_1.TokenType.STA) {
1600
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
1601
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
1602
+ }
1603
+ else if (pdaTokenType === types_1.TokenType.LTA) {
1604
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
1605
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
1606
+ }
1607
+ else {
1608
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
1609
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
1610
+ }
1611
+ // Generate fee accounts
1612
+ const { ownerFeeX, ownerFeeY } = (0, functions_1.generateHawksightFeeAccounts)(tokenXMint, tokenYMint, tokenXProgram, tokenYProgram);
1613
+ // Create instruction
1614
+ // @ts-ignore
1615
+ const meteoraDlmmLimitCloseAutomationV2Ix = yield anchor_1.Anchor.instance()
1616
+ .iyfExtension.methods.meteoraDlmmLimitCloseAutomationV2(param, minBinId, maxBinId, isHawkRefund)
1617
+ .accounts({
1618
+ userPda,
1619
+ hawksightAuthority,
1620
+ authority,
1621
+ position,
1622
+ lbPair,
1623
+ binArrayBitmapExtension: METEORA_DLMM_PROGRAM,
1624
+ userTokenX,
1625
+ userTokenY,
1626
+ reserveX,
1627
+ reserveY,
1628
+ tokenXMint,
1629
+ tokenYMint,
1630
+ tokenXProgram,
1631
+ tokenYProgram,
1632
+ eventAuthority: METEORA_EVENT_AUTHORITY,
1633
+ memoProgram: addresses_1.MEMO_PROGRAM,
1634
+ meteoraDlmmProgram: METEORA_DLMM_PROGRAM,
1635
+ ownerFeeX,
1636
+ ownerFeeY,
1637
+ fuelAccount: useFuelAccount
1638
+ ? (0, functions_1.generateFuelAccount)(userWallet)
1639
+ : web3.SystemProgram.programId,
1640
+ })
1641
+ .remainingAccounts(binArrays.map(pubkey => ({
1642
+ pubkey,
1643
+ isSigner: false,
1644
+ isWritable: true,
1645
+ })))
1646
+ .instruction();
1647
+ // Return the instruction directly (no wrapper needed for Meteora IX Generator)
1648
+ return meteoraDlmmLimitCloseAutomationV2Ix;
1649
+ });
1650
+ }
1651
+ /**
1652
+ * Generates raw meteora instruction that initializes a meteora pool
1653
+ *
1654
+ * @param param0
1655
+ * @returns
1656
+ */
1657
+ initializeLbPair2Raw(_a) {
1658
+ return __awaiter(this, arguments, void 0, function* ({ connection, funder, tokenMintX, tokenMintY, tokenProgramX, tokenProgramY, presetParameter, activeId, }) {
1659
+ // Initialize anchor
1660
+ anchor_1.Anchor.initialize(connection);
1661
+ const tokenX = tokenMintX;
1662
+ const tokenY = tokenMintY;
1663
+ const lbPair = this.pda.meteora.deriveLbPairWithPresetParamWithIndexKey(presetParameter, tokenX, tokenY);
1664
+ const reserveX = this.pda.meteora.deriveReserve(tokenX, lbPair);
1665
+ const reserveY = this.pda.meteora.deriveReserve(tokenY, lbPair);
1666
+ const oracle = this.pda.meteora.deriveOracle(lbPair);
1667
+ const activeBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(activeId));
1668
+ const binArrayBitmapExtension = this.isOverflowDefaultBinArrayBitmap(activeBinArrayIndex)
1669
+ ? this.pda.meteora.deriveBinArrayBitmapExtension(lbPair)
1670
+ : METEORA_DLMM_PROGRAM;
1671
+ return new web3.TransactionInstruction({
1672
+ data: Buffer.concat([
1673
+ Buffer.from(util.sighash('initialize_lb_pair_2')),
1674
+ Buffer.from([activeId]),
1675
+ Buffer.from(Array(96).fill(0)),
1676
+ ]),
1677
+ keys: [
1678
+ { pubkey: funder, isSigner: true, isWritable: true },
1679
+ { pubkey: lbPair, isSigner: false, isWritable: true },
1680
+ { pubkey: reserveX, isSigner: false, isWritable: true },
1681
+ { pubkey: reserveY, isSigner: false, isWritable: true },
1682
+ {
1683
+ pubkey: binArrayBitmapExtension,
1684
+ isSigner: false,
1685
+ isWritable: !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
1686
+ },
1687
+ { pubkey: tokenMintX, isSigner: false, isWritable: false },
1688
+ { pubkey: tokenMintY, isSigner: false, isWritable: false },
1689
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1690
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1691
+ { pubkey: tokenProgramX, isSigner: false, isWritable: false },
1692
+ { pubkey: tokenProgramY, isSigner: false, isWritable: false },
1693
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1694
+ ],
1695
+ programId: METEORA_DLMM_PROGRAM,
1696
+ });
1697
+ });
1698
+ }
1699
+ isOverflowDefaultBinArrayBitmap(binArrayIndex) {
1700
+ const [minBinArrayIndex, maxBinArrayIndex] = this.internalBitmapRange();
1701
+ return (binArrayIndex.gt(maxBinArrayIndex) || binArrayIndex.lt(minBinArrayIndex));
1702
+ }
1703
+ internalBitmapRange() {
1704
+ const lowerBinArrayIndex = new bn_js_1.default(512).neg();
1705
+ const upperBinArrayIndex = new bn_js_1.default(512).sub(new bn_js_1.default(1));
1706
+ return [lowerBinArrayIndex, upperBinArrayIndex];
1707
+ }
1708
+ binIdToBinArrayIndex(binId) {
1709
+ const { div: idx, mod } = binId.divmod(new bn_js_1.default(70));
1710
+ return binId.isNeg() && !mod.isZero() ? idx.sub(new bn_js_1.default(1)) : idx;
1711
+ }
1712
+ meteoraDlmmCreatePoolAndPosition(_a) {
1713
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, presetParameter, tokenMintX, tokenMintY, tokenProgramX, tokenProgramY, activeId, lowerBinId, upperBinId, strategyType, binStep, baseFactor, baseFeePowerFactor, }) {
1714
+ // Initialize anchor
1715
+ anchor_1.Anchor.initialize(connection);
1716
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1717
+ const userTokenX = (0, functions_1.generateAta)(userPda, tokenMintX, tokenProgramX);
1718
+ const userTokenY = (0, functions_1.generateAta)(userPda, tokenMintY, tokenProgramY);
1719
+ // Try to get existing LB pair first
1720
+ let lbPair;
1721
+ try {
1722
+ lbPair = yield dlmm_1.default.getPairPubkeyIfExists(connection, tokenMintX, tokenMintY, binStep, baseFactor, baseFeePowerFactor);
1723
+ }
1724
+ catch (error) {
1725
+ // If getPairPubkeyIfExists fails, set lbPair to null to trigger fallback
1726
+ lbPair = null;
1727
+ }
1728
+ // If no existing pair found or error occurred, derive it with preset parameters
1729
+ if (!lbPair) {
1730
+ lbPair = this.pda.meteora.deriveLbPairWithPresetParamWithIndexKey(presetParameter, tokenMintX, tokenMintY);
1731
+ }
1732
+ const reserveX = this.pda.meteora.deriveReserve(tokenMintX, lbPair);
1733
+ const reserveY = this.pda.meteora.deriveReserve(tokenMintY, lbPair);
1734
+ const oracle = this.pda.meteora.deriveOracle(lbPair);
1735
+ const hawkfiPayer = this.pda.hawksight.generateHawkfiPayer();
1736
+ return new web3.TransactionInstruction({
1737
+ data: Buffer.concat([
1738
+ Buffer.from(util.sighash('meteora_dlmm_create_pool_and_position')),
1739
+ new bn_js_1.default(activeId).toTwos(32).toArrayLike(Buffer, 'le', 4),
1740
+ new bn_js_1.default(lowerBinId).toTwos(32).toArrayLike(Buffer, 'le', 4),
1741
+ new bn_js_1.default(upperBinId).toTwos(32).toArrayLike(Buffer, 'le', 4),
1742
+ Buffer.from([strategyType]),
1743
+ ]),
1744
+ keys: [
1745
+ { pubkey: userPda, isSigner: false, isWritable: false },
1746
+ { pubkey: userWallet, isSigner: true, isWritable: true },
1747
+ { pubkey: hawkfiPayer, isSigner: false, isWritable: true },
1748
+ { pubkey: position, isSigner: true, isWritable: true },
1749
+ { pubkey: lbPair, isSigner: false, isWritable: true },
1750
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
1751
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
1752
+ { pubkey: reserveX, isSigner: false, isWritable: true },
1753
+ { pubkey: reserveY, isSigner: false, isWritable: true },
1754
+ { pubkey: oracle, isSigner: false, isWritable: true },
1755
+ { pubkey: presetParameter, isSigner: false, isWritable: false },
1756
+ { pubkey: tokenMintX, isSigner: false, isWritable: false },
1757
+ { pubkey: tokenMintY, isSigner: false, isWritable: false },
1758
+ { pubkey: tokenProgramX, isSigner: false, isWritable: false },
1759
+ { pubkey: tokenProgramY, isSigner: false, isWritable: false },
1760
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false },
1761
+ { pubkey: web3.SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false },
1762
+ {
1763
+ pubkey: web3.SystemProgram.programId,
1764
+ isSigner: false,
1765
+ isWritable: false,
1766
+ },
1767
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1768
+ ...(() => {
1769
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, lowerBinId, upperBinId);
1770
+ return binArrays.map(pubkey => ({
1771
+ pubkey,
1772
+ isSigner: false,
1773
+ isWritable: true,
1774
+ }));
1775
+ })(),
1776
+ ],
1777
+ programId: addresses_1.IYF_MAIN,
1778
+ });
1779
+ });
1780
+ }
1781
+ meteoraDlmmInitializeBinArray(_a) {
1782
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, lowerBinId, upperBinId, }) {
1783
+ // Initialize anchor
1784
+ anchor_1.Anchor.initialize(connection);
1785
+ // Generate user PDA
1786
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1787
+ // Generate hawkfi payer
1788
+ const hawkfiPayer = this.pda.hawksight.generateHawkfiPayer();
1789
+ return new web3.TransactionInstruction({
1790
+ data: Buffer.concat([
1791
+ Buffer.from(util.sighash('meteora_dlmm_init_bin_arrays')),
1792
+ new bn_js_1.default(lowerBinId).toTwos(32).toArrayLike(Buffer, 'le', 4),
1793
+ new bn_js_1.default(upperBinId).toTwos(32).toArrayLike(Buffer, 'le', 4),
1794
+ ]),
1795
+ keys: [
1796
+ { pubkey: userPda, isSigner: false, isWritable: false },
1797
+ { pubkey: userWallet, isSigner: true, isWritable: true },
1798
+ { pubkey: hawkfiPayer, isSigner: false, isWritable: true },
1799
+ { pubkey: lbPair, isSigner: false, isWritable: true },
1800
+ {
1801
+ pubkey: web3.SystemProgram.programId,
1802
+ isSigner: false,
1803
+ isWritable: false,
1804
+ },
1805
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1806
+ ...(() => {
1807
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, lowerBinId, upperBinId);
1808
+ return binArrays.map(pubkey => ({
1809
+ pubkey,
1810
+ isSigner: false,
1811
+ isWritable: true,
1812
+ }));
1813
+ })(),
1814
+ ],
1815
+ programId: addresses_1.IYF_MAIN,
1816
+ });
1817
+ });
1818
+ }
1819
+ /**
1820
+ * Initialize bin arrays for Meteora DLMM pool, invoked through meteora dlmm program
1821
+ * which means initialization is paid by the user.
1822
+ *
1823
+ * @param connection - Solana connection
1824
+ * @param userWallet - User wallet public key
1825
+ * @param lbPair - LB pair public key
1826
+ * @param lowerBinId - Lower bin ID
1827
+ * @param upperBinId - Upper bin ID
1828
+ * @returns
1829
+ */
1830
+ meteoraDlmmInitializeBinArrayDefault(_a) {
1831
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, lowerBinId, upperBinId, }) {
1832
+ // Initialize anchor
1833
+ anchor_1.Anchor.initialize(connection);
1834
+ const funder = userWallet;
1835
+ const systemProgram = web3.SystemProgram.programId;
1836
+ const tickIndices = meteora_1.MeteoraFunctions.findMeteoraTickArrayIndices(lowerBinId, upperBinId);
1837
+ const upperTickIndex = tickIndices[tickIndices.length - 1].add(new bn_js_1.default(1));
1838
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, lowerBinId, upperBinId);
1839
+ const ixs = binArrays.map((binArray, i) => {
1840
+ const index = tickIndices[i] !== undefined ? tickIndices[i] : upperTickIndex;
1841
+ return new web3.TransactionInstruction({
1842
+ data: Buffer.concat([
1843
+ Buffer.from(util.sighash('initialize_bin_array')),
1844
+ new bn_js_1.default(index).toTwos(64).toArrayLike(Buffer, 'le', 8),
1845
+ ]),
1846
+ keys: [
1847
+ { pubkey: lbPair, isSigner: false, isWritable: false },
1848
+ { pubkey: binArray, isSigner: false, isWritable: true },
1849
+ { pubkey: funder, isSigner: true, isWritable: true },
1850
+ { pubkey: systemProgram, isSigner: false, isWritable: true },
1851
+ ],
1852
+ programId: METEORA_DLMM_PROGRAM,
1853
+ });
1854
+ });
1855
+ return ixs;
1856
+ });
1857
+ }
1858
+ syncWithMarketPrice(_a) {
1859
+ return __awaiter(this, arguments, void 0, function* ({ connection, lbPair, marketPrice, owner, skipCanSyncCheck = false, }) {
1860
+ var _b;
1861
+ // Initialize anchor
1862
+ anchor_1.Anchor.initialize(connection);
1863
+ // Create DLMM instance
1864
+ const dlmmInstance = yield this.dlmm(connection, lbPair);
1865
+ // Get active bin
1866
+ const activeBin = yield dlmmInstance.dlmm.getActiveBin();
1867
+ // Check if sync is possible
1868
+ if (!skipCanSyncCheck) {
1869
+ const canSync = dlmmInstance.dlmm.canSyncWithMarketPrice(marketPrice, activeBin.binId);
1870
+ if (!canSync) {
1871
+ return { canSync: false, instruction: null };
1872
+ }
1873
+ }
1874
+ // Get sync transaction
1875
+ const tx = yield dlmmInstance.dlmm.syncWithMarketPrice(marketPrice, owner);
1876
+ // Extract the goToABin instruction (raw Meteora instruction)
1877
+ const instruction = (_b = tx.instructions.find(ix => ix.programId.equals(METEORA_DLMM_PROGRAM))) !== null && _b !== void 0 ? _b : null;
1878
+ return { canSync: true, instruction };
1879
+ });
1880
+ }
1881
+ /**
1882
+ * Increase the length of a Meteora DLMM position via IYF Main's meteora dynamic CPI.
1883
+ *
1884
+ * This instruction can only extend for up to 10kb in size, thus this instruction needs to be called
1885
+ * multiple times.
1886
+ *
1887
+ * This is the raw Meteora initializePosition instruction invoked through IYF Main.
1888
+ *
1889
+ * @param connection - Solana connection
1890
+ * @param params - Increase position length parameters
1891
+ * @returns TransactionInstruction for initializing the position
1892
+ */
1893
+ increasePositionLength(_a) {
1894
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, lengthToAdd, side, }) {
1895
+ // Initialize anchor
1896
+ anchor_1.Anchor.initialize(connection);
1897
+ // Generate user PDA
1898
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1899
+ // Build instruction data: sighash + lengthToAdd (u16) + side (u8)
1900
+ const lengthToAddBuffer = Buffer.alloc(2);
1901
+ lengthToAddBuffer.writeUInt16LE(lengthToAdd, 0);
1902
+ const sideBuffer = Buffer.alloc(1);
1903
+ sideBuffer.writeUInt8(side, 0);
1904
+ // Build raw Meteora instruction (accounts only - no hawksight wrapper accounts)
1905
+ // meteoraDynamicCpi will prepend userPda and authority
1906
+ const meteoraIx = new web3.TransactionInstruction({
1907
+ data: Buffer.concat([
1908
+ Buffer.from(util.sighash('increase_position_length')),
1909
+ lengthToAddBuffer,
1910
+ sideBuffer,
1911
+ ]),
1912
+ keys: [
1913
+ { pubkey: userWallet, isSigner: false, isWritable: true }, // funder (Mutable, Signer - signed by IYF Main)
1914
+ { pubkey: lbPair, isSigner: false, isWritable: false }, // lbPair
1915
+ { pubkey: position, isSigner: true, isWritable: true }, // position (Mutable, Signer)
1916
+ { pubkey: userPda, isSigner: false, isWritable: false }, // owner (Signer - signed by IYF Main)
1917
+ {
1918
+ pubkey: web3.SystemProgram.programId,
1919
+ isSigner: false,
1920
+ isWritable: false,
1921
+ }, // systemProgram (required for realloc)
1922
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false }, // eventAuthority (PDA)
1923
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // Meteora DLMM program
1924
+ ],
1925
+ programId: METEORA_DLMM_PROGRAM,
1926
+ });
1927
+ return yield this.ix.iyfMain.meteoraDynamicCpi({
1928
+ connection,
1929
+ userWallet,
1930
+ meteoraIx,
1931
+ });
1932
+ });
1933
+ }
1934
+ increasePositionLengthAutomation(_a) {
1935
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, lengthToAdd, side, useFuelAccount, }) {
1936
+ // Initialize anchor
1937
+ anchor_1.Anchor.initialize(connection);
1938
+ // Generate user PDA
1939
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
1940
+ // Build instruction data: sighash + lengthToAdd (u16) + side (u8)
1941
+ const lengthToAddBuffer = Buffer.alloc(2);
1942
+ lengthToAddBuffer.writeUInt16LE(lengthToAdd, 0);
1943
+ const sideBuffer = Buffer.alloc(1);
1944
+ sideBuffer.writeUInt8(side, 0);
1945
+ const fuelAccount = useFuelAccount
1946
+ ? (0, functions_1.generateFuelAccount)(userWallet)
1947
+ : web3.SystemProgram.programId;
1948
+ // Generate instruction
1949
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
1950
+ userPda,
1951
+ authority: addresses_1.HS_AUTHORITY,
1952
+ ix: new web3.TransactionInstruction({
1953
+ data: Buffer.concat([
1954
+ Buffer.from(util.sighash('meteora_dlmm_increase_position_length_automation')),
1955
+ lengthToAddBuffer,
1956
+ sideBuffer,
1957
+ ]),
1958
+ keys: [
1959
+ { pubkey: userPda, isSigner: false, isWritable: false },
1960
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: true },
1961
+ { pubkey: lbPair, isSigner: false, isWritable: false },
1962
+ { pubkey: position, isSigner: false, isWritable: true },
1963
+ {
1964
+ pubkey: METEORA_EVENT_AUTHORITY,
1965
+ isSigner: false,
1966
+ isWritable: false,
1967
+ },
1968
+ {
1969
+ pubkey: web3.SystemProgram.programId,
1970
+ isSigner: false,
1971
+ isWritable: false,
1972
+ },
1973
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
1974
+ {
1975
+ pubkey: fuelAccount,
1976
+ isSigner: false,
1977
+ isWritable: useFuelAccount !== null && useFuelAccount !== void 0 ? useFuelAccount : false,
1978
+ },
1979
+ ],
1980
+ programId: addresses_1.IYF_EXTENSION,
1981
+ }),
1982
+ });
1983
+ });
1984
+ }
1985
+ /**
1986
+ * Create a Meteora DLMM rebalance_liquidity instruction via IYF Main's meteora dynamic CPI.
1987
+ *
1988
+ * The rebalance_liquidity instruction allows for complex liquidity management including:
1989
+ * - Removing liquidity from specific bin ranges
1990
+ * - Adding liquidity to new bin ranges
1991
+ * - Claiming fees and rewards
1992
+ * - All in a single atomic transaction
1993
+ *
1994
+ * @param params - RebalanceLiquidityIxParams containing all necessary accounts and parameters
1995
+ * @returns TransactionInstruction for the rebalance_liquidity operation
1996
+ */
1997
+ rebalanceLiquidity(_a) {
1998
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, lbPair, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, activeId, pdaTokenType, maxActiveBinSlippage, shouldClaimFee, shouldClaimReward, minWithdrawXAmount, maxDepositXAmount, minWithdrawYAmount, maxDepositYAmount, removeLiquidityParams, addLiquidityParams, shrinkMode, }) {
1999
+ // Initialize Anchor
2000
+ anchor_1.Anchor.initialize(connection);
2001
+ // Generate user PDA
2002
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2003
+ // Generate user token accounts based on pdaTokenType
2004
+ let userTokenX;
2005
+ let userTokenY;
2006
+ if (pdaTokenType === types_1.TokenType.LTA) {
2007
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
2008
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
2009
+ }
2010
+ else if (pdaTokenType === types_1.TokenType.STA) {
2011
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
2012
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
2013
+ }
2014
+ else {
2015
+ // Default: ATA
2016
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
2017
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
2018
+ }
2019
+ // Derive bin array bitmap extension
2020
+ const lowerBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(activeId + addLiquidityParams[0].minDeltaId));
2021
+ const upperBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(activeId + addLiquidityParams[0].maxDeltaId));
2022
+ const binArrayBitmapExtension = this.isOverflowDefaultBinArrayBitmap(lowerBinArrayIndex) ||
2023
+ this.isOverflowDefaultBinArrayBitmap(upperBinArrayIndex)
2024
+ ? this.pda.meteora.deriveBinArrayBitmapExtension(lbPair)
2025
+ : METEORA_DLMM_PROGRAM;
2026
+ // Derive reserves
2027
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
2028
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
2029
+ // Derive bin arrays based on activeId, minDeltaId, and maxDeltaId
2030
+ const lowerBinId = activeId + addLiquidityParams[0].minDeltaId;
2031
+ const upperBinId = activeId + addLiquidityParams[0].maxDeltaId;
2032
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, lowerBinId, upperBinId);
2033
+ // Serialize RebalanceLiquidityParams
2034
+ const rebalanceParamsData = this.serializeRebalanceLiquidityParams({
2035
+ activeId,
2036
+ maxActiveBinSlippage,
2037
+ shouldClaimFee,
2038
+ shouldClaimReward,
2039
+ minWithdrawXAmount,
2040
+ maxDepositXAmount,
2041
+ minWithdrawYAmount,
2042
+ maxDepositYAmount,
2043
+ shrinkMode,
2044
+ removeLiquidityParams,
2045
+ addLiquidityParams,
2046
+ });
2047
+ // Serialize RemainingAccountsInfo (default empty for now - no transfer hooks)
2048
+ const remainingAccountsInfo = this.serializeRemainingAccountsInfo({
2049
+ slices: [],
2050
+ });
2051
+ // Build instruction data: sighash + RebalanceLiquidityParams + RemainingAccountsInfo
2052
+ const instructionData = Buffer.concat([
2053
+ Buffer.from(util.sighash('rebalance_liquidity')),
2054
+ rebalanceParamsData,
2055
+ remainingAccountsInfo,
2056
+ ]);
2057
+ // Build raw Meteora instruction
2058
+ const meteoraIx = new web3.TransactionInstruction({
2059
+ data: instructionData,
2060
+ keys: [
2061
+ { pubkey: position, isSigner: false, isWritable: true }, // position (Mutable)
2062
+ { pubkey: lbPair, isSigner: false, isWritable: true }, // lbPair (Mutable)
2063
+ {
2064
+ pubkey: binArrayBitmapExtension,
2065
+ isSigner: false,
2066
+ isWritable: !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
2067
+ }, // binArrayBitmapExtension
2068
+ { pubkey: userTokenX, isSigner: false, isWritable: true }, // userTokenX (Mutable)
2069
+ { pubkey: userTokenY, isSigner: false, isWritable: true }, // userTokenY (Mutable)
2070
+ { pubkey: reserveX, isSigner: false, isWritable: true }, // reserveX (Mutable)
2071
+ { pubkey: reserveY, isSigner: false, isWritable: true }, // reserveY (Mutable)
2072
+ { pubkey: tokenXMint, isSigner: false, isWritable: false }, // tokenXMint
2073
+ { pubkey: tokenYMint, isSigner: false, isWritable: false }, // tokenYMint
2074
+ { pubkey: userPda, isSigner: false, isWritable: false }, // sender (Signer - signed by IYF Main)
2075
+ { pubkey: userWallet, isSigner: false, isWritable: true }, // rentReceiver (Mutable)
2076
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false }, // tokenXProgram
2077
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false }, // tokenYProgram
2078
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false }, // memoProgram
2079
+ {
2080
+ pubkey: web3.SystemProgram.programId,
2081
+ isSigner: false,
2082
+ isWritable: false,
2083
+ }, // systemProgram
2084
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false }, // eventAuthority
2085
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // program
2086
+ // Bin arrays as remaining accounts
2087
+ ...binArrays.map(pubkey => ({
2088
+ pubkey,
2089
+ isSigner: false,
2090
+ isWritable: true,
2091
+ })),
2092
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // program
2093
+ ],
2094
+ programId: METEORA_DLMM_PROGRAM,
2095
+ });
2096
+ return yield this.ix.iyfMain.meteoraDynamicCpi({
2097
+ connection,
2098
+ userWallet,
2099
+ meteoraIx,
2100
+ });
2101
+ });
2102
+ }
2103
+ /**
2104
+ * Serialize RebalanceLiquidityParams to match Rust struct layout
2105
+ */
2106
+ serializeRebalanceLiquidityParams(params) {
2107
+ var _a;
2108
+ const buffers = [];
2109
+ // activeId (i32)
2110
+ const activeIdBuf = Buffer.alloc(4);
2111
+ activeIdBuf.writeInt32LE(params.activeId, 0);
2112
+ buffers.push(activeIdBuf);
2113
+ // maxActiveBinSlippage (u16)
2114
+ const slippageBuf = Buffer.alloc(2);
2115
+ slippageBuf.writeUInt16LE(params.maxActiveBinSlippage, 0);
2116
+ buffers.push(slippageBuf);
2117
+ // shouldClaimFee (bool as u8)
2118
+ buffers.push(Buffer.from([params.shouldClaimFee ? 1 : 0]));
2119
+ // shouldClaimReward (bool as u8)
2120
+ buffers.push(Buffer.from([params.shouldClaimReward ? 1 : 0]));
2121
+ // minWithdrawXAmount (u64)
2122
+ buffers.push(params.minWithdrawXAmount.toArrayLike(Buffer, 'le', 8));
2123
+ // maxDepositXAmount (u64)
2124
+ buffers.push(params.maxDepositXAmount.toArrayLike(Buffer, 'le', 8));
2125
+ // minWithdrawYAmount (u64)
2126
+ buffers.push(params.minWithdrawYAmount.toArrayLike(Buffer, 'le', 8));
2127
+ // maxDepositYAmount (u64)
2128
+ buffers.push(params.maxDepositYAmount.toArrayLike(Buffer, 'le', 8));
2129
+ // shrink_mode (u8) + padding [u8; 31]
2130
+ const paddingBuf = Buffer.alloc(32, 0);
2131
+ paddingBuf[0] = (_a = params.shrinkMode) !== null && _a !== void 0 ? _a : types_1.ShrinkMode.NoShrinkBoth;
2132
+ buffers.push(paddingBuf);
2133
+ // removeLiquidityParams Vec (length as u32, then each RemoveLiquidityParams)
2134
+ const removeLenBuf = Buffer.alloc(4);
2135
+ removeLenBuf.writeUInt32LE(params.removeLiquidityParams.length, 0);
2136
+ buffers.push(removeLenBuf);
2137
+ for (const removeParam of params.removeLiquidityParams) {
2138
+ // minBinId: Option<i32>
2139
+ if (removeParam.minBinId !== undefined) {
2140
+ buffers.push(Buffer.from([1])); // Some
2141
+ const minBinIdBuf = Buffer.alloc(4);
2142
+ minBinIdBuf.writeInt32LE(removeParam.minBinId, 0);
2143
+ buffers.push(minBinIdBuf);
2144
+ }
2145
+ else {
2146
+ buffers.push(Buffer.from([0])); // None
2147
+ }
2148
+ // maxBinId: Option<i32>
2149
+ if (removeParam.maxBinId !== undefined) {
2150
+ buffers.push(Buffer.from([1])); // Some
2151
+ const maxBinIdBuf = Buffer.alloc(4);
2152
+ maxBinIdBuf.writeInt32LE(removeParam.maxBinId, 0);
2153
+ buffers.push(maxBinIdBuf);
2154
+ }
2155
+ else {
2156
+ buffers.push(Buffer.from([0])); // None
2157
+ }
2158
+ // bps (u16)
2159
+ const bpsBuf = Buffer.alloc(2);
2160
+ bpsBuf.writeUInt16LE(removeParam.bps, 0);
2161
+ buffers.push(bpsBuf);
2162
+ // padding [u8; 16]
2163
+ buffers.push(Buffer.alloc(16, 0));
2164
+ }
2165
+ // addLiquidityParams Vec (length as u32, then each AddLiquidityParams)
2166
+ const addLenBuf = Buffer.alloc(4);
2167
+ addLenBuf.writeUInt32LE(params.addLiquidityParams.length, 0);
2168
+ buffers.push(addLenBuf);
2169
+ for (const addParam of params.addLiquidityParams) {
2170
+ // minDeltaId (i32)
2171
+ const minDeltaIdBuf = Buffer.alloc(4);
2172
+ minDeltaIdBuf.writeInt32LE(addParam.minDeltaId, 0);
2173
+ buffers.push(minDeltaIdBuf);
2174
+ // maxDeltaId (i32)
2175
+ const maxDeltaIdBuf = Buffer.alloc(4);
2176
+ maxDeltaIdBuf.writeInt32LE(addParam.maxDeltaId, 0);
2177
+ buffers.push(maxDeltaIdBuf);
2178
+ // x0 (u64)
2179
+ buffers.push(addParam.x0.toArrayLike(Buffer, 'le', 8));
2180
+ // y0 (u64)
2181
+ buffers.push(addParam.y0.toArrayLike(Buffer, 'le', 8));
2182
+ // deltaX (u64)
2183
+ buffers.push(addParam.deltaX.toArrayLike(Buffer, 'le', 8));
2184
+ // deltaY (u64)
2185
+ buffers.push(addParam.deltaY.toArrayLike(Buffer, 'le', 8));
2186
+ // bitFlag (u8)
2187
+ buffers.push(Buffer.from([addParam.bitFlag]));
2188
+ // favorXInActiveId (bool as u8)
2189
+ buffers.push(Buffer.from([addParam.favorXInActiveId ? 1 : 0]));
2190
+ // padding [u8; 16]
2191
+ buffers.push(Buffer.alloc(16, 0));
2192
+ }
2193
+ return Buffer.concat(buffers);
2194
+ }
2195
+ /**
2196
+ * Serialize RemainingAccountsInfo to match Rust struct layout
2197
+ *
2198
+ * The format is a Borsh Vec of AccountsTypeSlice:
2199
+ * - [slices_count: u32] - number of slices
2200
+ * - For each slice: [accountsType: u8 (or u8+u8 for TransferHookMultiReward)][length: u8]
2201
+ *
2202
+ * This is passed directly to Anchor methods which wrap it in another Vec<u8>.
2203
+ */
2204
+ serializeRemainingAccountsInfo(info) {
2205
+ const buffers = [];
2206
+ // Vec length (u32) - number of slices
2207
+ const lenBuf = Buffer.alloc(4);
2208
+ lenBuf.writeUInt32LE(info.slices.length, 0);
2209
+ buffers.push(lenBuf);
2210
+ // Serialize each slice
2211
+ for (const slice of info.slices) {
2212
+ // AccountsType enum (varies in size)
2213
+ if (slice.accountsType === 3 && slice.multiRewardIndex !== undefined) {
2214
+ // TransferHookMultiReward(u8)
2215
+ buffers.push(Buffer.from([3, slice.multiRewardIndex]));
2216
+ }
2217
+ else {
2218
+ buffers.push(Buffer.from([slice.accountsType]));
2219
+ }
2220
+ // length (u8)
2221
+ buffers.push(Buffer.from([slice.length]));
2222
+ }
2223
+ return Buffer.concat(buffers);
2224
+ }
2225
+ /**
2226
+ * Remove liquidity from a bin range in a Meteora DLMM position via IYF Main's meteora dynamic CPI.
2227
+ *
2228
+ * This instruction withdraws liquidity from the specified bin range.
2229
+ * The bin arrays for the range are automatically derived and included as remaining accounts.
2230
+ *
2231
+ * @param params - RemoveLiquidityByRange2 parameters
2232
+ * @returns TransactionInstruction for the remove_liquidity_by_range2 operation
2233
+ */
2234
+ removeLiquidityByRange2(_a) {
2235
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, fromBinId, toBinId, bpsToRemove, pdaTokenType, remainingAccountsInfo: remainingAccountsInfoParam, }) {
2236
+ var _b, _c;
2237
+ // Initialize Anchor
2238
+ anchor_1.Anchor.initialize(connection);
2239
+ // Generate user PDA
2240
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2241
+ // Generate user token accounts based on pdaTokenType
2242
+ let userTokenX;
2243
+ let userTokenY;
2244
+ if (pdaTokenType === types_1.TokenType.LTA) {
2245
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
2246
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
2247
+ }
2248
+ else if (pdaTokenType === types_1.TokenType.STA) {
2249
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
2250
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
2251
+ }
2252
+ else {
2253
+ // Default: ATA
2254
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
2255
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
2256
+ }
2257
+ // Derive bin array bitmap extension
2258
+ const lowerBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(fromBinId));
2259
+ const upperBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(toBinId));
2260
+ const binArrayBitmapExtension = this.isOverflowDefaultBinArrayBitmap(lowerBinArrayIndex) ||
2261
+ this.isOverflowDefaultBinArrayBitmap(upperBinArrayIndex)
2262
+ ? this.pda.meteora.deriveBinArrayBitmapExtension(lbPair)
2263
+ : METEORA_DLMM_PROGRAM;
2264
+ // Derive reserves
2265
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
2266
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
2267
+ // Derive bin arrays for the range
2268
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, fromBinId, toBinId);
2269
+ // Build instruction data: sighash + fromBinId(i32) + toBinId(i32) + bpsToRemove(u16) + remainingAccountsInfo
2270
+ const fromBinIdBuffer = Buffer.alloc(4);
2271
+ fromBinIdBuffer.writeInt32LE(fromBinId, 0);
2272
+ const toBinIdBuffer = Buffer.alloc(4);
2273
+ toBinIdBuffer.writeInt32LE(toBinId, 0);
2274
+ const bpsToRemoveBuffer = Buffer.alloc(2);
2275
+ bpsToRemoveBuffer.writeUInt16LE(bpsToRemove, 0);
2276
+ // Serialize RemainingAccountsInfo
2277
+ // Use provided remainingAccountsInfo or default to empty slices (no transfer hooks)
2278
+ // Note: Bin arrays are passed as regular remaining accounts, NOT in slices
2279
+ const remainingAccountsInfoSerialized = this.serializeRemainingAccountsInfo({
2280
+ slices: (_b = remainingAccountsInfoParam === null || remainingAccountsInfoParam === void 0 ? void 0 : remainingAccountsInfoParam.slices) !== null && _b !== void 0 ? _b : [],
2281
+ });
2282
+ const instructionData = Buffer.concat([
2283
+ Buffer.from(util.sighash('remove_liquidity_by_range2', undefined, true)),
2284
+ fromBinIdBuffer,
2285
+ toBinIdBuffer,
2286
+ bpsToRemoveBuffer,
2287
+ remainingAccountsInfoSerialized,
2288
+ ]);
2289
+ // Build raw Meteora instruction
2290
+ // Account order from IDL: position, lbPair, binArrayBitmapExtension, userTokenX, userTokenY,
2291
+ // reserveX, reserveY, tokenXMint, tokenYMint, sender, tokenXProgram, tokenYProgram,
2292
+ // memoProgram, eventAuthority, program + bin arrays as remaining accounts + transfer hook accounts
2293
+ const meteoraIx = new web3.TransactionInstruction({
2294
+ data: instructionData,
2295
+ keys: [
2296
+ { pubkey: position, isSigner: false, isWritable: true }, // position (Mutable)
2297
+ { pubkey: lbPair, isSigner: false, isWritable: true }, // lbPair (Mutable)
2298
+ {
2299
+ pubkey: binArrayBitmapExtension,
2300
+ isSigner: false,
2301
+ isWritable: !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
2302
+ }, // binArrayBitmapExtension (optional, writable when real PDA)
2303
+ { pubkey: userTokenX, isSigner: false, isWritable: true }, // userTokenX (Mutable)
2304
+ { pubkey: userTokenY, isSigner: false, isWritable: true }, // userTokenY (Mutable)
2305
+ { pubkey: reserveX, isSigner: false, isWritable: true }, // reserveX (Mutable)
2306
+ { pubkey: reserveY, isSigner: false, isWritable: true }, // reserveY (Mutable)
2307
+ { pubkey: tokenXMint, isSigner: false, isWritable: false }, // tokenXMint
2308
+ { pubkey: tokenYMint, isSigner: false, isWritable: false }, // tokenYMint
2309
+ { pubkey: userPda, isSigner: false, isWritable: false }, // sender (Signer - signed by IYF Main)
2310
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false }, // tokenXProgram
2311
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false }, // tokenYProgram
2312
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false }, // memoProgram
2313
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false }, // eventAuthority
2314
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // program
2315
+ // Bin arrays as remaining accounts
2316
+ ...binArrays.map(pubkey => ({
2317
+ pubkey,
2318
+ isSigner: false,
2319
+ isWritable: true,
2320
+ })),
2321
+ // Transfer hook accounts (if any) - order must match slices order
2322
+ ...((_c = remainingAccountsInfoParam === null || remainingAccountsInfoParam === void 0 ? void 0 : remainingAccountsInfoParam.accounts) !== null && _c !== void 0 ? _c : []),
2323
+ ],
2324
+ programId: METEORA_DLMM_PROGRAM,
2325
+ });
2326
+ return yield this.ix.iyfMain.meteoraDynamicCpi({
2327
+ connection,
2328
+ userWallet,
2329
+ meteoraIx,
2330
+ });
2331
+ });
2332
+ }
2333
+ /**
2334
+ * Close an empty Meteora DLMM position via IYF Main's meteora dynamic CPI.
2335
+ *
2336
+ * This instruction closes a position and returns the rent to the user.
2337
+ * The position must be empty (no liquidity) for this to succeed.
2338
+ *
2339
+ * @param params - ClosePosition2 parameters
2340
+ * @returns TransactionInstruction for the close_position2 operation
2341
+ */
2342
+ closePosition2(_a) {
2343
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, }) {
2344
+ // Initialize Anchor
2345
+ anchor_1.Anchor.initialize(connection);
2346
+ // Generate user PDA
2347
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2348
+ // Build instruction data: sighash only (no args)
2349
+ const instructionData = Buffer.from(util.sighash('close_position2', undefined, true));
2350
+ // Build raw Meteora instruction
2351
+ // Account order from IDL: position, sender, rentReceiver, eventAuthority, program
2352
+ const meteoraIx = new web3.TransactionInstruction({
2353
+ data: instructionData,
2354
+ keys: [
2355
+ { pubkey: position, isSigner: false, isWritable: true }, // position (Mutable)
2356
+ { pubkey: userPda, isSigner: false, isWritable: false }, // sender (Signer - signed by IYF Main)
2357
+ { pubkey: userWallet, isSigner: false, isWritable: true }, // rentReceiver (Mutable)
2358
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false }, // eventAuthority
2359
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // program
2360
+ ],
2361
+ programId: METEORA_DLMM_PROGRAM,
2362
+ });
2363
+ return yield this.ix.iyfMain.meteoraDynamicCpi({
2364
+ connection,
2365
+ userWallet,
2366
+ meteoraIx,
2367
+ });
2368
+ });
2369
+ }
2370
+ /**
2371
+ * Close a Meteora DLMM position only if it is empty via IYF Main's meteora dynamic CPI.
2372
+ *
2373
+ * This instruction is similar to closePosition2 but will fail silently if the position
2374
+ * still has liquidity. This is useful for safely attempting to close a position without
2375
+ * knowing its current state.
2376
+ *
2377
+ * @param params - ClosePositionIfEmpty parameters
2378
+ * @returns TransactionInstruction for the close_position_if_empty operation
2379
+ */
2380
+ closePositionIfEmpty(_a) {
2381
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, }) {
2382
+ // Initialize Anchor
2383
+ anchor_1.Anchor.initialize(connection);
2384
+ // Generate user PDA
2385
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2386
+ // Build instruction data: sighash only (no args)
2387
+ const instructionData = Buffer.from(util.sighash('close_position_if_empty'));
2388
+ // Build raw Meteora instruction
2389
+ // Account order from IDL: position, sender, rentReceiver, eventAuthority, program
2390
+ const meteoraIx = new web3.TransactionInstruction({
2391
+ data: instructionData,
2392
+ keys: [
2393
+ { pubkey: position, isSigner: false, isWritable: true }, // position (Mutable)
2394
+ { pubkey: userPda, isSigner: false, isWritable: false }, // sender (Signer - signed by IYF Main)
2395
+ { pubkey: userWallet, isSigner: false, isWritable: true }, // rentReceiver (Mutable)
2396
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: false }, // eventAuthority
2397
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false }, // program
2398
+ ],
2399
+ programId: METEORA_DLMM_PROGRAM,
2400
+ });
2401
+ return yield this.ix.iyfMain.meteoraDynamicCpi({
2402
+ connection,
2403
+ userWallet,
2404
+ meteoraIx,
2405
+ });
2406
+ });
2407
+ }
2408
+ /**
2409
+ * Rebalance liquidity in a Meteora DLMM position via IYF Extension for automation.
2410
+ *
2411
+ * This is the automation version that uses HS_AUTHORITY as the signer.
2412
+ * Wraps via iyfExtensionExecuteV2 instead of meteoraDynamicCpi.
2413
+ *
2414
+ * @param params - RebalanceLiquidityIxParams containing all necessary accounts and parameters
2415
+ * @returns TransactionInstruction for the rebalance_liquidity automation operation
2416
+ */
2417
+ rebalanceLiquidityAutomation(_a) {
2418
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, position, lbPair, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, activeId, pdaTokenType, maxActiveBinSlippage, shouldClaimFee, shouldClaimReward, minWithdrawXAmount, maxDepositXAmount, minWithdrawYAmount, maxDepositYAmount, removeLiquidityParams, addLiquidityParams, shrinkMode, rewardInfos, remainingAccountsInfo, }) {
2419
+ var _b, _c;
2420
+ // Initialize Anchor
2421
+ anchor_1.Anchor.initialize(connection);
2422
+ // Generate user PDA
2423
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2424
+ // Generate user token accounts based on pdaTokenType
2425
+ let userTokenX;
2426
+ let userTokenY;
2427
+ if (pdaTokenType === types_1.TokenType.LTA) {
2428
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
2429
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
2430
+ }
2431
+ else if (pdaTokenType === types_1.TokenType.STA) {
2432
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
2433
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
2434
+ }
2435
+ else {
2436
+ // Default: ATA
2437
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
2438
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
2439
+ }
2440
+ // Collect all bin IDs from both remove and add params
2441
+ const allBinIds = [];
2442
+ for (const p of removeLiquidityParams) {
2443
+ if (p.minBinId !== undefined && p.maxBinId !== undefined) {
2444
+ allBinIds.push(p.minBinId, p.maxBinId);
2445
+ }
2446
+ else {
2447
+ if (p.minBinId === undefined) {
2448
+ throw new Error(`rebalanceLiquidityAutomation: removeLiquidityParams.minBinid is not optional.`);
2449
+ }
2450
+ else {
2451
+ throw new Error(`rebalanceLiquidityAutomation: removeLiquidityParams.maxBinId is not optional.`);
2452
+ }
2453
+ }
2454
+ }
2455
+ for (const p of addLiquidityParams) {
2456
+ allBinIds.push(activeId + p.minDeltaId, activeId + p.maxDeltaId);
2457
+ }
2458
+ if (allBinIds.length === 0) {
2459
+ throw new Error('rebalanceLiquidityAutomation: both removeLiquidityParams and addLiquidityParams are empty');
2460
+ }
2461
+ const minBinId = Math.min(...allBinIds);
2462
+ const maxBinId = Math.max(...allBinIds);
2463
+ // Derive bin array bitmap extension
2464
+ const lowerBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(minBinId));
2465
+ const upperBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(maxBinId));
2466
+ const binArrayBitmapExtension = this.isOverflowDefaultBinArrayBitmap(lowerBinArrayIndex) ||
2467
+ this.isOverflowDefaultBinArrayBitmap(upperBinArrayIndex)
2468
+ ? this.pda.meteora.deriveBinArrayBitmapExtension(lbPair)
2469
+ : METEORA_DLMM_PROGRAM;
2470
+ // Derive reserves
2471
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
2472
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
2473
+ let binArrays;
2474
+ const lowerBinId = minBinId;
2475
+ const upperBinId = maxBinId;
2476
+ binArrays = this.pda.meteora.deriveBinArrays(lbPair, lowerBinId, upperBinId);
2477
+ // Build reward remaining accounts if shouldClaimReward and rewardInfos provided
2478
+ const rewardRemainingAccounts = [];
2479
+ if (shouldClaimReward && rewardInfos && rewardInfos.length > 0) {
2480
+ console.log(`[rebalanceLiquidityAutomation] Building reward accounts for ${rewardInfos.length} reward(s)`);
2481
+ for (const reward of rewardInfos) {
2482
+ // User reward token account (ATA or STA based on pdaTokenType)
2483
+ let userRewardToken = (0, functions_1.generateUserPdaStorageAccount)(userPda, reward.rewardMint);
2484
+ console.log(`[rebalanceLiquidityAutomation] Reward: vault=${reward.rewardVault.toString()}, userToken=${userRewardToken.toString()}, mint=${reward.rewardMint.toString()}, program=${reward.rewardTokenProgram.toString()}`);
2485
+ // Add reward accounts in order: vault, userToken, mint, tokenProgram
2486
+ rewardRemainingAccounts.push({ pubkey: reward.rewardVault, isSigner: false, isWritable: true }, { pubkey: userRewardToken, isSigner: false, isWritable: true }, { pubkey: reward.rewardMint, isSigner: false, isWritable: false }, {
2487
+ pubkey: reward.rewardTokenProgram,
2488
+ isSigner: false,
2489
+ isWritable: false,
2490
+ });
2491
+ }
2492
+ console.log(`[rebalanceLiquidityAutomation] Total reward remaining accounts: ${rewardRemainingAccounts.length}`);
2493
+ }
2494
+ else if (shouldClaimReward) {
2495
+ console.log(`[rebalanceLiquidityAutomation] shouldClaimReward=true but no rewardInfos provided!`);
2496
+ }
2497
+ // Serialize RebalanceLiquidityParams
2498
+ const rebalanceParamsData = this.serializeRebalanceLiquidityParams({
2499
+ activeId,
2500
+ maxActiveBinSlippage,
2501
+ shouldClaimFee,
2502
+ shouldClaimReward,
2503
+ minWithdrawXAmount,
2504
+ maxDepositXAmount,
2505
+ minWithdrawYAmount,
2506
+ maxDepositYAmount,
2507
+ shrinkMode,
2508
+ removeLiquidityParams,
2509
+ addLiquidityParams,
2510
+ });
2511
+ // Serialize RemainingAccountsInfo from passed parameter or use empty slices
2512
+ const serializedRemainingAccountsInfo = this.serializeRemainingAccountsInfo({
2513
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : [],
2514
+ });
2515
+ // Build instruction data: sighash + RebalanceLiquidityParams + RemainingAccountsInfo
2516
+ // The handler takes two typed Anchor args (not Vec<u8>), so no length prefix needed.
2517
+ const instructionData = Buffer.concat([
2518
+ Buffer.from(util.sighash('meteora_dlmm_rebalance_liquidity_automation')),
2519
+ rebalanceParamsData,
2520
+ serializedRemainingAccountsInfo,
2521
+ ]);
2522
+ // Generate instruction via IYF Extension
2523
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
2524
+ userPda,
2525
+ authority: addresses_1.HS_AUTHORITY,
2526
+ ix: new web3.TransactionInstruction({
2527
+ data: instructionData,
2528
+ keys: [
2529
+ { pubkey: userPda, isSigner: false, isWritable: false },
2530
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: true },
2531
+ { pubkey: position, isSigner: false, isWritable: true },
2532
+ { pubkey: lbPair, isSigner: false, isWritable: true },
2533
+ {
2534
+ pubkey: binArrayBitmapExtension,
2535
+ isSigner: false,
2536
+ isWritable: !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
2537
+ },
2538
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
2539
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
2540
+ { pubkey: reserveX, isSigner: false, isWritable: true },
2541
+ { pubkey: reserveY, isSigner: false, isWritable: true },
2542
+ { pubkey: tokenXMint, isSigner: false, isWritable: false },
2543
+ { pubkey: tokenYMint, isSigner: false, isWritable: false },
2544
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false },
2545
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false },
2546
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false },
2547
+ {
2548
+ pubkey: web3.SystemProgram.programId,
2549
+ isSigner: false,
2550
+ isWritable: false,
2551
+ },
2552
+ {
2553
+ pubkey: METEORA_EVENT_AUTHORITY,
2554
+ isSigner: false,
2555
+ isWritable: false,
2556
+ },
2557
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
2558
+ // Transfer hook accounts (from fetchRemainingAccountsInfo)
2559
+ ...((_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : []),
2560
+ // Bin arrays as remaining accounts
2561
+ ...binArrays.map(pubkey => ({
2562
+ pubkey,
2563
+ isSigner: false,
2564
+ isWritable: true,
2565
+ })),
2566
+ // Boundary account
2567
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
2568
+ // Reward accounts after boundary account
2569
+ ...rewardRemainingAccounts,
2570
+ ],
2571
+ programId: addresses_1.IYF_EXTENSION,
2572
+ }),
2573
+ });
2574
+ });
2575
+ }
2576
+ /**
2577
+ * Remove liquidity from a bin range in a Meteora DLMM position via IYF Extension for automation.
2578
+ *
2579
+ * This is the automation version that uses HS_AUTHORITY as the signer.
2580
+ * Supports larger bin ranges (not limited to 70-bin chunks).
2581
+ *
2582
+ * @param params - RemoveLiquidityByRange2AutomationParams parameters
2583
+ * @returns TransactionInstruction for the remove_liquidity_by_range2 automation operation
2584
+ */
2585
+ removeLiquidityByRange2Automation(_a) {
2586
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, fromBinId, toBinId, bpsToRemove, pdaTokenType, remainingAccountsInfo, }) {
2587
+ var _b, _c;
2588
+ // Initialize Anchor
2589
+ anchor_1.Anchor.initialize(connection);
2590
+ // Generate user PDA
2591
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2592
+ // Generate user token accounts based on pdaTokenType
2593
+ let userTokenX;
2594
+ let userTokenY;
2595
+ if (pdaTokenType === types_1.TokenType.LTA) {
2596
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
2597
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
2598
+ }
2599
+ else if (pdaTokenType === types_1.TokenType.STA) {
2600
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
2601
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
2602
+ }
2603
+ else {
2604
+ // Default: ATA
2605
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
2606
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
2607
+ }
2608
+ // Derive bin array bitmap extension
2609
+ const lowerBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(fromBinId));
2610
+ const upperBinArrayIndex = this.binIdToBinArrayIndex(new bn_js_1.default(toBinId));
2611
+ const binArrayBitmapExtension = this.isOverflowDefaultBinArrayBitmap(lowerBinArrayIndex) ||
2612
+ this.isOverflowDefaultBinArrayBitmap(upperBinArrayIndex)
2613
+ ? this.pda.meteora.deriveBinArrayBitmapExtension(lbPair)
2614
+ : METEORA_DLMM_PROGRAM;
2615
+ // Derive reserves
2616
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
2617
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
2618
+ // Derive bin arrays for the range
2619
+ const binArrays = this.pda.meteora.deriveBinArrays(lbPair, fromBinId, toBinId);
2620
+ // Build instruction data: fromBinId(i32) + toBinId(i32) + bpsToRemove(u16) + remainingAccountsInfo
2621
+ const fromBinIdBuffer = Buffer.alloc(4);
2622
+ fromBinIdBuffer.writeInt32LE(fromBinId, 0);
2623
+ const toBinIdBuffer = Buffer.alloc(4);
2624
+ toBinIdBuffer.writeInt32LE(toBinId, 0);
2625
+ const bpsToRemoveBuffer = Buffer.alloc(2);
2626
+ bpsToRemoveBuffer.writeUInt16LE(bpsToRemove, 0);
2627
+ // Serialize RemainingAccountsInfo
2628
+ const remainingAccountsInfoSerialized = this.serializeRemainingAccountsInfo({
2629
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : [],
2630
+ });
2631
+ const instructionData = Buffer.concat([
2632
+ fromBinIdBuffer,
2633
+ toBinIdBuffer,
2634
+ bpsToRemoveBuffer,
2635
+ remainingAccountsInfoSerialized,
2636
+ ]);
2637
+ // For Anchor Vec<u8> parameter, we need to prepend the length as u32 LE
2638
+ const instructionDataVec = Buffer.alloc(4 + instructionData.length);
2639
+ instructionDataVec.writeUInt32LE(instructionData.length, 0);
2640
+ instructionData.copy(instructionDataVec, 4);
2641
+ // Generate instruction via IYF Extension
2642
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
2643
+ userPda,
2644
+ authority: addresses_1.HS_AUTHORITY,
2645
+ ix: new web3.TransactionInstruction({
2646
+ data: Buffer.concat([
2647
+ Buffer.from(util.sighash('meteora_dlmm_withdraw_2_automation')),
2648
+ instructionDataVec,
2649
+ ]),
2650
+ keys: [
2651
+ { pubkey: userPda, isSigner: false, isWritable: false },
2652
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: true },
2653
+ { pubkey: position, isSigner: false, isWritable: true },
2654
+ { pubkey: lbPair, isSigner: false, isWritable: true },
2655
+ {
2656
+ pubkey: binArrayBitmapExtension,
2657
+ isSigner: false,
2658
+ isWritable: !binArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
2659
+ },
2660
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
2661
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
2662
+ { pubkey: reserveX, isSigner: false, isWritable: true },
2663
+ { pubkey: reserveY, isSigner: false, isWritable: true },
2664
+ { pubkey: tokenXMint, isSigner: false, isWritable: false },
2665
+ { pubkey: tokenYMint, isSigner: false, isWritable: false },
2666
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false },
2667
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false },
2668
+ {
2669
+ pubkey: METEORA_EVENT_AUTHORITY,
2670
+ isSigner: false,
2671
+ isWritable: false,
2672
+ },
2673
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: false },
2674
+ { pubkey: addresses_1.MEMO_PROGRAM, isSigner: false, isWritable: false },
2675
+ // Bin arrays as remaining accounts
2676
+ ...binArrays.map(pubkey => ({
2677
+ pubkey,
2678
+ isSigner: false,
2679
+ isWritable: true,
2680
+ })),
2681
+ // Transfer hook accounts (if any)
2682
+ ...((_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : []),
2683
+ ],
2684
+ programId: addresses_1.IYF_EXTENSION,
2685
+ }),
2686
+ });
2687
+ });
2688
+ }
2689
+ addLiquidity2Automation(_a) {
2690
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, layers, checkRange, userTokenXAmount, userTokenYAmount, chunkLowerOffset, chunkUpperOffset, remainingAccountsInfo, pdaTokenType, lowerBinId, upperBinId, }) {
2691
+ var _b, _c;
2692
+ anchor_1.Anchor.initialize(connection);
2693
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
2694
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
2695
+ const derivedBinArrayBitmapExtension = this.pda.meteora.deriveBinArrayBitmapExtension(lbPair);
2696
+ const binArrayBitmapExtensionInfo = yield connection.getAccountInfo(derivedBinArrayBitmapExtension);
2697
+ const actualBinArrayBitmapExtension = binArrayBitmapExtensionInfo
2698
+ ? derivedBinArrayBitmapExtension
2699
+ : METEORA_DLMM_PROGRAM;
2700
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2701
+ let userTokenX;
2702
+ let userTokenY;
2703
+ if (pdaTokenType === types_1.TokenType.LTA) {
2704
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
2705
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
2706
+ }
2707
+ else if (pdaTokenType === types_1.TokenType.STA) {
2708
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
2709
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
2710
+ }
2711
+ else {
2712
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
2713
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
2714
+ }
2715
+ // --- Serialize instruction data ---
2716
+ const sighash = Buffer.from(util.sighash('meteora_dlmm_add_liquidity_2_automation'));
2717
+ layers.forEach((layer, index) => {
2718
+ const validateByteField = (fieldName, value, maxValue) => {
2719
+ if (!Number.isInteger(value) || value < 0 || value > maxValue) {
2720
+ throw new Error(`layers[${index}].${fieldName} must be an integer between 0 and ${maxValue}`);
2721
+ }
2722
+ };
2723
+ validateByteField('strategyTypeX', layer.strategyTypeX, 255);
2724
+ validateByteField('strategyTypeY', layer.strategyTypeY, 255);
2725
+ validateByteField('percentageX', layer.percentageX, 100);
2726
+ validateByteField('percentageY', layer.percentageY, 100);
2727
+ });
2728
+ // Vec<HybridLayer>: u32 length + 4 u8s per layer
2729
+ const layersLenBuf = Buffer.alloc(4);
2730
+ layersLenBuf.writeUInt32LE(layers.length, 0);
2731
+ const layersBuf = Buffer.concat([
2732
+ layersLenBuf,
2733
+ ...layers.map(l => Buffer.from([
2734
+ l.strategyTypeX,
2735
+ l.strategyTypeY,
2736
+ l.percentageX,
2737
+ l.percentageY,
2738
+ ])),
2739
+ ]);
2740
+ // Option<[i32; 2]> check_range
2741
+ const checkRangeBuf = checkRange
2742
+ ? (() => {
2743
+ const buf = Buffer.alloc(9);
2744
+ buf.writeUInt8(1, 0);
2745
+ buf.writeInt32LE(checkRange.lowerRange, 1);
2746
+ buf.writeInt32LE(checkRange.upperRange, 5);
2747
+ return buf;
2748
+ })()
2749
+ : Buffer.from([0]);
2750
+ // Option<u64> user_token_x_amount
2751
+ const xAmountBuf = userTokenXAmount
2752
+ ? Buffer.concat([
2753
+ Buffer.from([1]),
2754
+ Buffer.from(userTokenXAmount.toArrayLike(Buffer, 'le', 8)),
2755
+ ])
2756
+ : Buffer.from([0]);
2757
+ // Option<u64> user_token_y_amount
2758
+ const yAmountBuf = userTokenYAmount
2759
+ ? Buffer.concat([
2760
+ Buffer.from([1]),
2761
+ Buffer.from(userTokenYAmount.toArrayLike(Buffer, 'le', 8)),
2762
+ ])
2763
+ : Buffer.from([0]);
2764
+ // Option<i32> chunk_lower_offset
2765
+ const chunkLowerBuf = chunkLowerOffset !== undefined
2766
+ ? (() => {
2767
+ const b = Buffer.alloc(5);
2768
+ b.writeUInt8(1, 0);
2769
+ b.writeInt32LE(chunkLowerOffset, 1);
2770
+ return b;
2771
+ })()
2772
+ : Buffer.from([0]);
2773
+ // Option<i32> chunk_upper_offset
2774
+ const chunkUpperBuf = chunkUpperOffset !== undefined
2775
+ ? (() => {
2776
+ const b = Buffer.alloc(5);
2777
+ b.writeUInt8(1, 0);
2778
+ b.writeInt32LE(chunkUpperOffset, 1);
2779
+ return b;
2780
+ })()
2781
+ : Buffer.from([0]);
2782
+ // Vec<u8> remaining_accounts_info — needs u32 Vec length prefix (like depositRelativeAutomation)
2783
+ const defaultSlices = [
2784
+ { accountsType: 0, length: 0 },
2785
+ { accountsType: 1, length: 0 },
2786
+ ];
2787
+ const remainingAccountsInfoSerialized = this.serializeRemainingAccountsInfo({
2788
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : defaultSlices,
2789
+ });
2790
+ const raiLenBuf = Buffer.alloc(4);
2791
+ raiLenBuf.writeUInt32LE(remainingAccountsInfoSerialized.length, 0);
2792
+ const remainingAccountsInfoWithLength = Buffer.concat([
2793
+ raiLenBuf,
2794
+ remainingAccountsInfoSerialized,
2795
+ ]);
2796
+ // --- Bin arrays ---
2797
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, lowerBinId, upperBinId);
2798
+ const binArrayAccounts = binArrays.map(binArray => ({
2799
+ pubkey: binArray,
2800
+ isSigner: false,
2801
+ isWritable: true,
2802
+ }));
2803
+ const transferHookAccounts = (_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : [];
2804
+ // --- Assemble instruction ---
2805
+ // Account order matches contract MeteoraDlmmAddLiquidity2Automation (meteora.rs:3699)
2806
+ // Same order as meteoraDlmmDepositRelativeAutomation (line 809)
2807
+ const ix = new web3.TransactionInstruction({
2808
+ data: Buffer.concat([
2809
+ sighash,
2810
+ layersBuf,
2811
+ checkRangeBuf,
2812
+ xAmountBuf,
2813
+ yAmountBuf,
2814
+ chunkLowerBuf,
2815
+ chunkUpperBuf,
2816
+ remainingAccountsInfoWithLength,
2817
+ ]),
2818
+ keys: [
2819
+ { pubkey: userPda, isSigner: false, isWritable: false },
2820
+ { pubkey: addresses_1.HS_AUTHORITY, isSigner: true, isWritable: true },
2821
+ { pubkey: position, isSigner: false, isWritable: true },
2822
+ { pubkey: lbPair, isSigner: false, isWritable: true },
2823
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
2824
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
2825
+ { pubkey: reserveX, isSigner: false, isWritable: true },
2826
+ { pubkey: reserveY, isSigner: false, isWritable: true },
2827
+ { pubkey: tokenXMint, isSigner: false, isWritable: false },
2828
+ { pubkey: tokenYMint, isSigner: false, isWritable: false },
2829
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false },
2830
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false },
2831
+ {
2832
+ pubkey: actualBinArrayBitmapExtension,
2833
+ isSigner: false,
2834
+ isWritable: !actualBinArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
2835
+ },
2836
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: true },
2837
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: true },
2838
+ ...transferHookAccounts,
2839
+ ...binArrayAccounts,
2840
+ ],
2841
+ programId: addresses_1.IYF_EXTENSION,
2842
+ });
2843
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
2844
+ userPda,
2845
+ authority: addresses_1.HS_AUTHORITY,
2846
+ ix,
2847
+ });
2848
+ });
2849
+ }
2850
+ /**
2851
+ * FE-callable mirror of addLiquidity2Automation.
2852
+ * Same hybrid-layer add-liquidity flow, but signed by the user's wallet
2853
+ * instead of HS_AUTHORITY (sighash: meteora_dlmm_add_liquidity_2).
2854
+ */
2855
+ addLiquidity2(_a) {
2856
+ return __awaiter(this, arguments, void 0, function* ({ connection, userWallet, lbPair, position, tokenXMint, tokenYMint, tokenXProgram, tokenYProgram, layers, checkRange, userTokenXAmount, userTokenYAmount, chunkLowerOffset, chunkUpperOffset, remainingAccountsInfo, pdaTokenType, lowerBinId, upperBinId, }) {
2857
+ var _b, _c;
2858
+ anchor_1.Anchor.initialize(connection);
2859
+ const reserveX = this.pda.meteora.deriveReserve(tokenXMint, lbPair);
2860
+ const reserveY = this.pda.meteora.deriveReserve(tokenYMint, lbPair);
2861
+ const derivedBinArrayBitmapExtension = this.pda.meteora.deriveBinArrayBitmapExtension(lbPair);
2862
+ const binArrayBitmapExtensionInfo = yield connection.getAccountInfo(derivedBinArrayBitmapExtension);
2863
+ const actualBinArrayBitmapExtension = binArrayBitmapExtensionInfo
2864
+ ? derivedBinArrayBitmapExtension
2865
+ : METEORA_DLMM_PROGRAM;
2866
+ const userPda = (0, functions_1.generateUserPda)(userWallet);
2867
+ let userTokenX;
2868
+ let userTokenY;
2869
+ if (pdaTokenType === types_1.TokenType.LTA) {
2870
+ userTokenX = (0, functions_1.generateLimitToken)(userPda, tokenXMint);
2871
+ userTokenY = (0, functions_1.generateLimitToken)(userPda, tokenYMint);
2872
+ }
2873
+ else if (pdaTokenType === types_1.TokenType.STA) {
2874
+ userTokenX = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenXMint);
2875
+ userTokenY = (0, functions_1.generateUserPdaStorageAccount)(userPda, tokenYMint);
2876
+ }
2877
+ else {
2878
+ userTokenX = (0, functions_1.generateAta)(userPda, tokenXMint, tokenXProgram);
2879
+ userTokenY = (0, functions_1.generateAta)(userPda, tokenYMint, tokenYProgram);
2880
+ }
2881
+ const sighash = Buffer.from(util.sighash('meteora_dlmm_add_liquidity_2'));
2882
+ layers.forEach((layer, index) => {
2883
+ const validateByteField = (fieldName, value, maxValue) => {
2884
+ if (!Number.isInteger(value) || value < 0 || value > maxValue) {
2885
+ throw new Error(`layers[${index}].${fieldName} must be an integer between 0 and ${maxValue}`);
2886
+ }
2887
+ };
2888
+ validateByteField('strategyTypeX', layer.strategyTypeX, 255);
2889
+ validateByteField('strategyTypeY', layer.strategyTypeY, 255);
2890
+ validateByteField('percentageX', layer.percentageX, 100);
2891
+ validateByteField('percentageY', layer.percentageY, 100);
2892
+ });
2893
+ const layersLenBuf = Buffer.alloc(4);
2894
+ layersLenBuf.writeUInt32LE(layers.length, 0);
2895
+ const layersBuf = Buffer.concat([
2896
+ layersLenBuf,
2897
+ ...layers.map(l => Buffer.from([
2898
+ l.strategyTypeX,
2899
+ l.strategyTypeY,
2900
+ l.percentageX,
2901
+ l.percentageY,
2902
+ ])),
2903
+ ]);
2904
+ const checkRangeBuf = checkRange
2905
+ ? (() => {
2906
+ const buf = Buffer.alloc(9);
2907
+ buf.writeUInt8(1, 0);
2908
+ buf.writeInt32LE(checkRange.lowerRange, 1);
2909
+ buf.writeInt32LE(checkRange.upperRange, 5);
2910
+ return buf;
2911
+ })()
2912
+ : Buffer.from([0]);
2913
+ const xAmountBuf = userTokenXAmount
2914
+ ? Buffer.concat([
2915
+ Buffer.from([1]),
2916
+ Buffer.from(userTokenXAmount.toArrayLike(Buffer, 'le', 8)),
2917
+ ])
2918
+ : Buffer.from([0]);
2919
+ const yAmountBuf = userTokenYAmount
2920
+ ? Buffer.concat([
2921
+ Buffer.from([1]),
2922
+ Buffer.from(userTokenYAmount.toArrayLike(Buffer, 'le', 8)),
2923
+ ])
2924
+ : Buffer.from([0]);
2925
+ const chunkLowerBuf = chunkLowerOffset !== undefined
2926
+ ? (() => {
2927
+ const b = Buffer.alloc(5);
2928
+ b.writeUInt8(1, 0);
2929
+ b.writeInt32LE(chunkLowerOffset, 1);
2930
+ return b;
2931
+ })()
2932
+ : Buffer.from([0]);
2933
+ const chunkUpperBuf = chunkUpperOffset !== undefined
2934
+ ? (() => {
2935
+ const b = Buffer.alloc(5);
2936
+ b.writeUInt8(1, 0);
2937
+ b.writeInt32LE(chunkUpperOffset, 1);
2938
+ return b;
2939
+ })()
2940
+ : Buffer.from([0]);
2941
+ const defaultSlices = [
2942
+ { accountsType: 0, length: 0 },
2943
+ { accountsType: 1, length: 0 },
2944
+ ];
2945
+ const remainingAccountsInfoSerialized = this.serializeRemainingAccountsInfo({
2946
+ slices: (_b = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.slices) !== null && _b !== void 0 ? _b : defaultSlices,
2947
+ });
2948
+ const raiLenBuf = Buffer.alloc(4);
2949
+ raiLenBuf.writeUInt32LE(remainingAccountsInfoSerialized.length, 0);
2950
+ const remainingAccountsInfoWithLength = Buffer.concat([
2951
+ raiLenBuf,
2952
+ remainingAccountsInfoSerialized,
2953
+ ]);
2954
+ const binArrays = meteora_1.MeteoraFunctions.findMeteoraTickArrays(lbPair, lowerBinId, upperBinId);
2955
+ const binArrayAccounts = binArrays.map(binArray => ({
2956
+ pubkey: binArray,
2957
+ isSigner: false,
2958
+ isWritable: true,
2959
+ }));
2960
+ const transferHookAccounts = (_c = remainingAccountsInfo === null || remainingAccountsInfo === void 0 ? void 0 : remainingAccountsInfo.accounts) !== null && _c !== void 0 ? _c : [];
2961
+ const ix = new web3.TransactionInstruction({
2962
+ data: Buffer.concat([
2963
+ sighash,
2964
+ layersBuf,
2965
+ checkRangeBuf,
2966
+ xAmountBuf,
2967
+ yAmountBuf,
2968
+ chunkLowerBuf,
2969
+ chunkUpperBuf,
2970
+ remainingAccountsInfoWithLength,
2971
+ ]),
2972
+ keys: [
2973
+ { pubkey: userPda, isSigner: false, isWritable: false },
2974
+ { pubkey: userWallet, isSigner: true, isWritable: true },
2975
+ { pubkey: position, isSigner: false, isWritable: true },
2976
+ { pubkey: lbPair, isSigner: false, isWritable: true },
2977
+ { pubkey: userTokenX, isSigner: false, isWritable: true },
2978
+ { pubkey: userTokenY, isSigner: false, isWritable: true },
2979
+ { pubkey: reserveX, isSigner: false, isWritable: true },
2980
+ { pubkey: reserveY, isSigner: false, isWritable: true },
2981
+ { pubkey: tokenXMint, isSigner: false, isWritable: false },
2982
+ { pubkey: tokenYMint, isSigner: false, isWritable: false },
2983
+ { pubkey: tokenXProgram, isSigner: false, isWritable: false },
2984
+ { pubkey: tokenYProgram, isSigner: false, isWritable: false },
2985
+ {
2986
+ pubkey: actualBinArrayBitmapExtension,
2987
+ isSigner: false,
2988
+ isWritable: !actualBinArrayBitmapExtension.equals(METEORA_DLMM_PROGRAM),
2989
+ },
2990
+ { pubkey: METEORA_EVENT_AUTHORITY, isSigner: false, isWritable: true },
2991
+ { pubkey: METEORA_DLMM_PROGRAM, isSigner: false, isWritable: true },
2992
+ ...transferHookAccounts,
2993
+ ...binArrayAccounts,
2994
+ ],
2995
+ programId: addresses_1.IYF_EXTENSION,
2996
+ });
2997
+ return this.ix.iyfMain.iyfExtensionExecuteV2(connection, {
2998
+ userPda,
2999
+ authority: userWallet,
3000
+ ix,
3001
+ });
3002
+ });
3003
+ }
3004
+ }
3005
+ exports.MeteoraDlmmIxGenerator = MeteoraDlmmIxGenerator;