@haven-fi/solauto-sdk 1.0.582 → 1.0.583

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 (260) hide show
  1. package/dist/constants/solautoConstants.d.ts +1 -0
  2. package/dist/constants/solautoConstants.d.ts.map +1 -1
  3. package/dist/constants/solautoConstants.js +4 -10
  4. package/dist/generated/accounts/solautoPosition.js +2 -2
  5. package/dist/generated/errors/solauto.d.ts +14 -2
  6. package/dist/generated/errors/solauto.d.ts.map +1 -1
  7. package/dist/generated/errors/solauto.js +27 -5
  8. package/dist/generated/instructions/claimReferralFees.d.ts +1 -1
  9. package/dist/generated/instructions/claimReferralFees.d.ts.map +1 -1
  10. package/dist/generated/instructions/closePosition.d.ts +1 -1
  11. package/dist/generated/instructions/closePosition.d.ts.map +1 -1
  12. package/dist/generated/instructions/closePosition.js +2 -2
  13. package/dist/generated/instructions/marginfiOpenPosition.d.ts +1 -3
  14. package/dist/generated/instructions/marginfiOpenPosition.d.ts.map +1 -1
  15. package/dist/generated/instructions/marginfiOpenPosition.js +0 -1
  16. package/dist/generated/instructions/marginfiRebalance.d.ts +7 -3
  17. package/dist/generated/instructions/marginfiRebalance.d.ts.map +1 -1
  18. package/dist/generated/instructions/marginfiRebalance.js +3 -1
  19. package/dist/generated/types/index.d.ts +7 -1
  20. package/dist/generated/types/index.d.ts.map +1 -1
  21. package/dist/generated/types/index.js +7 -1
  22. package/dist/generated/types/positionData.d.ts +2 -2
  23. package/dist/generated/types/positionData.d.ts.map +1 -1
  24. package/dist/generated/types/positionData.js +1 -1
  25. package/dist/generated/types/positionState.d.ts +7 -7
  26. package/dist/generated/types/positionState.d.ts.map +1 -1
  27. package/dist/generated/types/positionState.js +3 -3
  28. package/dist/generated/types/{positionTokenUsage.d.ts → positionTokenState.d.ts} +6 -8
  29. package/dist/generated/types/positionTokenState.d.ts.map +1 -0
  30. package/dist/generated/types/{positionTokenUsage.js → positionTokenState.js} +6 -7
  31. package/dist/generated/types/rebalanceData.d.ts +7 -13
  32. package/dist/generated/types/rebalanceData.d.ts.map +1 -1
  33. package/dist/generated/types/rebalanceData.js +3 -6
  34. package/dist/generated/types/rebalanceDirection.d.ts +3 -2
  35. package/dist/generated/types/rebalanceDirection.d.ts.map +1 -1
  36. package/dist/generated/types/rebalanceDirection.js +3 -2
  37. package/dist/generated/types/rebalanceInstructionData.d.ts +27 -0
  38. package/dist/generated/types/rebalanceInstructionData.d.ts.map +1 -0
  39. package/dist/generated/types/rebalanceInstructionData.js +22 -0
  40. package/dist/generated/types/rebalanceStateValues.d.ts +27 -0
  41. package/dist/generated/types/rebalanceStateValues.d.ts.map +1 -0
  42. package/dist/generated/types/rebalanceStateValues.js +22 -0
  43. package/dist/generated/types/rebalanceStep.d.ts +15 -0
  44. package/dist/generated/types/rebalanceStep.d.ts.map +1 -0
  45. package/dist/generated/types/rebalanceStep.js +22 -0
  46. package/dist/generated/types/solautoRebalanceType.d.ts +4 -5
  47. package/dist/generated/types/solautoRebalanceType.d.ts.map +1 -1
  48. package/dist/generated/types/solautoRebalanceType.js +4 -5
  49. package/dist/generated/types/solautoSettingsParameters.d.ts +2 -15
  50. package/dist/generated/types/solautoSettingsParameters.d.ts.map +1 -1
  51. package/dist/generated/types/solautoSettingsParameters.js +1 -5
  52. package/dist/generated/types/solautoSettingsParametersInp.d.ts +1 -12
  53. package/dist/generated/types/solautoSettingsParametersInp.d.ts.map +1 -1
  54. package/dist/generated/types/solautoSettingsParametersInp.js +0 -3
  55. package/dist/generated/types/swapType.d.ts +15 -0
  56. package/dist/generated/types/swapType.d.ts.map +1 -0
  57. package/dist/generated/types/swapType.js +22 -0
  58. package/dist/generated/types/tokenBalanceChange.d.ts +21 -0
  59. package/dist/generated/types/tokenBalanceChange.d.ts.map +1 -0
  60. package/dist/generated/types/tokenBalanceChange.js +19 -0
  61. package/dist/generated/types/tokenBalanceChangeType.d.ts +18 -0
  62. package/dist/generated/types/tokenBalanceChangeType.d.ts.map +1 -0
  63. package/dist/generated/types/tokenBalanceChangeType.js +25 -0
  64. package/dist/generated/types/updatePositionData.d.ts +2 -2
  65. package/dist/generated/types/updatePositionData.d.ts.map +1 -1
  66. package/dist/generated/types/updatePositionData.js +1 -1
  67. package/dist/index.d.ts +8 -6
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +5 -5
  70. package/dist/marginfi-sdk/types/interestRateConfig.d.ts +3 -1
  71. package/dist/marginfi-sdk/types/interestRateConfig.d.ts.map +1 -1
  72. package/dist/marginfi-sdk/types/interestRateConfig.js +2 -1
  73. package/dist/services/flashLoans/flProviderAggregator.d.ts +19 -0
  74. package/dist/services/flashLoans/flProviderAggregator.d.ts.map +1 -0
  75. package/dist/services/flashLoans/flProviderAggregator.js +46 -0
  76. package/dist/services/flashLoans/flProviderBase.d.ts +23 -0
  77. package/dist/services/flashLoans/flProviderBase.d.ts.map +1 -0
  78. package/dist/services/flashLoans/flProviderBase.js +37 -0
  79. package/dist/services/flashLoans/index.d.ts +4 -0
  80. package/dist/services/flashLoans/index.d.ts.map +1 -0
  81. package/dist/services/flashLoans/index.js +19 -0
  82. package/dist/services/flashLoans/marginfiFlProvider.d.ts +25 -0
  83. package/dist/services/flashLoans/marginfiFlProvider.d.ts.map +1 -0
  84. package/dist/services/flashLoans/marginfiFlProvider.js +246 -0
  85. package/dist/services/index.d.ts +6 -0
  86. package/dist/services/index.d.ts.map +1 -0
  87. package/dist/services/index.js +21 -0
  88. package/dist/services/rebalance/index.d.ts +3 -0
  89. package/dist/services/rebalance/index.d.ts.map +1 -0
  90. package/dist/services/rebalance/index.js +18 -0
  91. package/dist/services/rebalance/rebalanceSwapManager.d.ts +30 -0
  92. package/dist/services/rebalance/rebalanceSwapManager.d.ts.map +1 -0
  93. package/dist/services/rebalance/rebalanceSwapManager.js +144 -0
  94. package/dist/services/rebalance/rebalanceTxBuilder.d.ts +22 -0
  95. package/dist/services/rebalance/rebalanceTxBuilder.d.ts.map +1 -0
  96. package/dist/services/rebalance/rebalanceTxBuilder.js +200 -0
  97. package/dist/services/rebalance/rebalanceValues.d.ts +31 -0
  98. package/dist/services/rebalance/rebalanceValues.d.ts.map +1 -0
  99. package/dist/services/rebalance/rebalanceValues.js +118 -0
  100. package/dist/services/rebalance/solautoFees.d.ts +13 -0
  101. package/dist/services/rebalance/solautoFees.d.ts.map +1 -0
  102. package/dist/services/rebalance/solautoFees.js +54 -0
  103. package/dist/services/solauto/index.d.ts +5 -0
  104. package/dist/services/solauto/index.d.ts.map +1 -0
  105. package/dist/{clients → services/solauto}/referralStateManager.d.ts +4 -5
  106. package/dist/services/solauto/referralStateManager.d.ts.map +1 -0
  107. package/dist/{clients → services/solauto}/referralStateManager.js +10 -12
  108. package/dist/services/solauto/solautoClient.d.ts +59 -0
  109. package/dist/services/solauto/solautoClient.d.ts.map +1 -0
  110. package/dist/{clients → services/solauto}/solautoClient.js +78 -109
  111. package/dist/services/solauto/solautoMarginfiClient.d.ts +34 -0
  112. package/dist/services/solauto/solautoMarginfiClient.d.ts.map +1 -0
  113. package/dist/services/solauto/solautoMarginfiClient.js +322 -0
  114. package/dist/{clients → services/solauto}/txHandler.d.ts +11 -2
  115. package/dist/services/solauto/txHandler.d.ts.map +1 -0
  116. package/dist/services/solauto/txHandler.js +38 -0
  117. package/dist/services/swap/index.d.ts +2 -0
  118. package/dist/services/swap/index.d.ts.map +1 -0
  119. package/dist/{utils/solauto → services/swap}/index.js +1 -2
  120. package/dist/services/swap/jupSwapManager.d.ts +37 -0
  121. package/dist/services/swap/jupSwapManager.d.ts.map +1 -0
  122. package/dist/services/swap/jupSwapManager.js +108 -0
  123. package/dist/services/transactions/index.d.ts.map +1 -0
  124. package/dist/{transactions → services/transactions}/transactionUtils.d.ts +3 -5
  125. package/dist/services/transactions/transactionUtils.d.ts.map +1 -0
  126. package/dist/{transactions → services/transactions}/transactionUtils.js +29 -137
  127. package/dist/{transactions → services/transactions}/transactionsManager.d.ts +4 -4
  128. package/dist/services/transactions/transactionsManager.d.ts.map +1 -0
  129. package/dist/{transactions → services/transactions}/transactionsManager.js +10 -8
  130. package/dist/solautoPosition/index.d.ts +4 -0
  131. package/dist/solautoPosition/index.d.ts.map +1 -0
  132. package/dist/solautoPosition/index.js +19 -0
  133. package/dist/solautoPosition/marginfiSolautoPositionEx.d.ts +14 -0
  134. package/dist/solautoPosition/marginfiSolautoPositionEx.d.ts.map +1 -0
  135. package/dist/solautoPosition/marginfiSolautoPositionEx.js +73 -0
  136. package/dist/solautoPosition/solautoPositionEx.d.ts +67 -0
  137. package/dist/solautoPosition/solautoPositionEx.d.ts.map +1 -0
  138. package/dist/solautoPosition/solautoPositionEx.js +143 -0
  139. package/dist/solautoPosition/utils.d.ts +17 -0
  140. package/dist/solautoPosition/utils.d.ts.map +1 -0
  141. package/dist/solautoPosition/utils.js +115 -0
  142. package/dist/types/solauto.d.ts +19 -1
  143. package/dist/types/solauto.d.ts.map +1 -1
  144. package/dist/utils/generalUtils.d.ts +1 -0
  145. package/dist/utils/generalUtils.d.ts.map +1 -1
  146. package/dist/utils/generalUtils.js +9 -1
  147. package/dist/utils/index.d.ts +1 -1
  148. package/dist/utils/index.d.ts.map +1 -1
  149. package/dist/utils/index.js +1 -1
  150. package/dist/utils/jitoUtils.d.ts.map +1 -1
  151. package/dist/utils/jupiterUtils.d.ts +3 -28
  152. package/dist/utils/jupiterUtils.d.ts.map +1 -1
  153. package/dist/utils/jupiterUtils.js +2 -73
  154. package/dist/utils/marginfiUtils.d.ts +4 -3
  155. package/dist/utils/marginfiUtils.d.ts.map +1 -1
  156. package/dist/utils/marginfiUtils.js +47 -18
  157. package/dist/utils/numberUtils.d.ts +3 -6
  158. package/dist/utils/numberUtils.d.ts.map +1 -1
  159. package/dist/utils/numberUtils.js +13 -48
  160. package/dist/utils/solanaUtils.js +2 -2
  161. package/dist/utils/{solauto/generalUtils.d.ts → solautoUtils.d.ts} +9 -16
  162. package/dist/utils/solautoUtils.d.ts.map +1 -0
  163. package/dist/utils/{solauto/generalUtils.js → solautoUtils.js} +48 -173
  164. package/local/createTokenAccounts.ts +1 -5
  165. package/local/logPositions.ts +22 -68
  166. package/local/shared.ts +29 -24
  167. package/local/txSandbox.ts +27 -0
  168. package/local/updateMarginfiLUT.ts +80 -4
  169. package/package.json +3 -6
  170. package/src/constants/solautoConstants.ts +4 -9
  171. package/src/generated/accounts/solautoPosition.ts +2 -2
  172. package/src/generated/errors/solauto.ts +45 -4
  173. package/src/generated/instructions/claimReferralFees.ts +1 -1
  174. package/src/generated/instructions/closePosition.ts +3 -3
  175. package/src/generated/instructions/marginfiOpenPosition.ts +0 -7
  176. package/src/generated/instructions/marginfiRebalance.ts +12 -3
  177. package/src/generated/types/index.ts +7 -1
  178. package/src/generated/types/positionData.ts +3 -3
  179. package/src/generated/types/positionState.ts +12 -12
  180. package/src/generated/types/{positionTokenUsage.ts → positionTokenState.ts} +13 -16
  181. package/src/generated/types/rebalanceData.ts +16 -27
  182. package/src/generated/types/rebalanceDirection.ts +1 -0
  183. package/src/generated/types/rebalanceInstructionData.ts +62 -0
  184. package/src/generated/types/rebalanceStateValues.ts +59 -0
  185. package/src/generated/types/rebalanceStep.ts +25 -0
  186. package/src/generated/types/solautoRebalanceType.ts +0 -1
  187. package/src/generated/types/solautoSettingsParameters.ts +4 -25
  188. package/src/generated/types/solautoSettingsParametersInp.ts +2 -24
  189. package/src/generated/types/swapType.ts +22 -0
  190. package/src/generated/types/tokenBalanceChange.ts +46 -0
  191. package/src/generated/types/tokenBalanceChangeType.ts +28 -0
  192. package/src/generated/types/updatePositionData.ts +3 -3
  193. package/src/index.ts +8 -8
  194. package/src/marginfi-sdk/types/interestRateConfig.ts +6 -2
  195. package/src/services/flashLoans/flProviderAggregator.ts +74 -0
  196. package/src/services/flashLoans/flProviderBase.ts +88 -0
  197. package/src/services/flashLoans/index.ts +3 -0
  198. package/src/services/flashLoans/marginfiFlProvider.ts +392 -0
  199. package/src/services/index.ts +5 -0
  200. package/src/services/rebalance/index.ts +2 -0
  201. package/src/services/rebalance/rebalanceSwapManager.ts +218 -0
  202. package/src/services/rebalance/rebalanceTxBuilder.ts +330 -0
  203. package/src/services/rebalance/rebalanceValues.ts +232 -0
  204. package/src/services/rebalance/solautoFees.ts +61 -0
  205. package/src/services/solauto/index.ts +4 -0
  206. package/src/{clients → services/solauto}/referralStateManager.ts +17 -31
  207. package/src/{clients → services/solauto}/solautoClient.ts +142 -205
  208. package/src/services/solauto/solautoMarginfiClient.ts +472 -0
  209. package/src/services/solauto/txHandler.ts +69 -0
  210. package/src/services/swap/index.ts +1 -0
  211. package/src/services/swap/jupSwapManager.ts +189 -0
  212. package/src/{transactions → services/transactions}/transactionUtils.ts +40 -280
  213. package/src/{transactions → services/transactions}/transactionsManager.ts +15 -10
  214. package/src/solautoPosition/index.ts +3 -0
  215. package/src/solautoPosition/marginfiSolautoPositionEx.ts +111 -0
  216. package/src/solautoPosition/solautoPositionEx.ts +281 -0
  217. package/src/solautoPosition/utils.ts +188 -0
  218. package/src/types/solauto.ts +30 -2
  219. package/src/utils/generalUtils.ts +9 -1
  220. package/src/utils/index.ts +2 -2
  221. package/src/utils/jitoUtils.ts +0 -4
  222. package/src/utils/jupiterUtils.ts +3 -164
  223. package/src/utils/marginfiUtils.ts +77 -43
  224. package/src/utils/numberUtils.ts +18 -77
  225. package/src/utils/solanaUtils.ts +1 -1
  226. package/src/utils/{solauto/generalUtils.ts → solautoUtils.ts} +66 -288
  227. package/tests/transactions/shared.ts +135 -0
  228. package/tests/transactions/solautoMarginfi.ts +8 -198
  229. package/tests/unit/accounts.ts +3 -10
  230. package/tests/unit/lookupTables.ts +23 -2
  231. package/tests/unit/rebalanceCalculations.ts +65 -343
  232. package/dist/clients/index.d.ts +0 -5
  233. package/dist/clients/index.d.ts.map +0 -1
  234. package/dist/clients/referralStateManager.d.ts.map +0 -1
  235. package/dist/clients/solautoClient.d.ts +0 -71
  236. package/dist/clients/solautoClient.d.ts.map +0 -1
  237. package/dist/clients/solautoMarginfiClient.d.ts +0 -51
  238. package/dist/clients/solautoMarginfiClient.d.ts.map +0 -1
  239. package/dist/clients/solautoMarginfiClient.js +0 -497
  240. package/dist/clients/txHandler.d.ts.map +0 -1
  241. package/dist/clients/txHandler.js +0 -23
  242. package/dist/generated/types/positionTokenUsage.d.ts.map +0 -1
  243. package/dist/transactions/index.d.ts.map +0 -1
  244. package/dist/transactions/transactionUtils.d.ts.map +0 -1
  245. package/dist/transactions/transactionsManager.d.ts.map +0 -1
  246. package/dist/utils/solauto/generalUtils.d.ts.map +0 -1
  247. package/dist/utils/solauto/index.d.ts +0 -3
  248. package/dist/utils/solauto/index.d.ts.map +0 -1
  249. package/dist/utils/solauto/rebalanceUtils.d.ts +0 -30
  250. package/dist/utils/solauto/rebalanceUtils.d.ts.map +0 -1
  251. package/dist/utils/solauto/rebalanceUtils.js +0 -287
  252. package/src/clients/index.ts +0 -4
  253. package/src/clients/solautoMarginfiClient.ts +0 -774
  254. package/src/clients/txHandler.ts +0 -38
  255. package/src/utils/solauto/index.ts +0 -2
  256. package/src/utils/solauto/rebalanceUtils.ts +0 -562
  257. package/dist/{clients → services/solauto}/index.js +2 -2
  258. /package/dist/{transactions → services/transactions}/index.d.ts +0 -0
  259. /package/dist/{transactions → services/transactions}/index.js +0 -0
  260. /package/src/{transactions → services/transactions}/index.ts +0 -0
@@ -0,0 +1,189 @@
1
+ import {
2
+ Signer,
3
+ TransactionBuilder,
4
+ transactionBuilder,
5
+ } from "@metaplex-foundation/umi";
6
+ import {
7
+ createJupiterApiClient,
8
+ QuoteResponse,
9
+ SwapInstructionsResponse,
10
+ } from "@jup-ag/api";
11
+ import { getWrappedInstruction } from "../../utils/solanaUtils";
12
+ import { fromBps, toBps } from "../../utils/numberUtils";
13
+ import { getTokenAccount } from "../../utils/accountUtils";
14
+ import { PublicKey } from "@solana/web3.js";
15
+ import {
16
+ consoleLog,
17
+ jupIxToSolanaIx,
18
+ retryWithExponentialBackoff,
19
+ } from "../../utils";
20
+ import { TransactionItemInputs } from "../../types";
21
+
22
+ export interface SwapInput {
23
+ inputMint: PublicKey;
24
+ outputMint: PublicKey;
25
+ amount: bigint;
26
+ exactIn?: boolean;
27
+ exactOut?: boolean;
28
+ }
29
+
30
+ export interface SwapParams extends SwapInput {
31
+ destinationWallet: PublicKey;
32
+ slippageIncFactor?: number;
33
+ wrapAndUnwrapSol?: boolean;
34
+ }
35
+
36
+ export interface JupSwapTransactionData {
37
+ jupQuote: QuoteResponse;
38
+ setupInstructions: TransactionBuilder;
39
+ swapIx: TransactionBuilder;
40
+ cleanupIx: TransactionBuilder;
41
+ lookupTableAddresses: string[];
42
+ }
43
+
44
+ export class JupSwapManager {
45
+ jupApi = createJupiterApiClient();
46
+
47
+ public jupQuote: QuoteResponse | undefined = undefined;
48
+
49
+ constructor(private signer: Signer) {}
50
+
51
+ public async getQuote(data: SwapInput): Promise<QuoteResponse> {
52
+ return await retryWithExponentialBackoff(
53
+ async (attemptNum: number) =>
54
+ await this.jupApi.quoteGet({
55
+ amount: Number(data.amount),
56
+ inputMint: data.inputMint.toString(),
57
+ outputMint: data.outputMint.toString(),
58
+ swapMode: data.exactOut
59
+ ? "ExactOut"
60
+ : data.exactIn
61
+ ? "ExactIn"
62
+ : undefined,
63
+ slippageBps: 10,
64
+ maxAccounts: !data.exactOut ? 15 + attemptNum * 5 : undefined,
65
+ }),
66
+ 3,
67
+ 200
68
+ );
69
+ }
70
+
71
+ private async getJupInstructions(
72
+ data: SwapParams
73
+ ): Promise<SwapInstructionsResponse> {
74
+ if (!this.jupQuote) {
75
+ throw new Error(
76
+ "Fetch a quote first before getting Jupiter instructions"
77
+ );
78
+ }
79
+
80
+ const instructions = await retryWithExponentialBackoff(
81
+ async () => {
82
+ const res = await this.jupApi.swapInstructionsPost({
83
+ swapRequest: {
84
+ userPublicKey: this.signer.publicKey.toString(),
85
+ quoteResponse: this.jupQuote!,
86
+ wrapAndUnwrapSol: data.wrapAndUnwrapSol ?? false,
87
+ useTokenLedger: !data.exactOut && !data.exactIn,
88
+ destinationTokenAccount: getTokenAccount(
89
+ data.destinationWallet,
90
+ data.outputMint
91
+ ).toString(),
92
+ },
93
+ });
94
+ if (!res) {
95
+ throw new Error("No instructions retrieved");
96
+ }
97
+ return res;
98
+ },
99
+ 4,
100
+ 200
101
+ );
102
+ if (!instructions.swapInstruction) {
103
+ throw new Error("No swap instruction was returned by Jupiter");
104
+ }
105
+ return instructions;
106
+ }
107
+
108
+ priceImpactBps() {
109
+ return Math.round(toBps(parseFloat(this.jupQuote!.priceImpactPct))) + 1;
110
+ }
111
+
112
+ private adaptSlippageToPriceImpact(slippageIncFactor: number) {
113
+ const finalPriceSlippageBps = Math.round(
114
+ Math.max(20, this.jupQuote!.slippageBps, this.priceImpactBps()) *
115
+ (1 + slippageIncFactor)
116
+ );
117
+ this.jupQuote!.slippageBps = finalPriceSlippageBps;
118
+ }
119
+
120
+ private addInAmountSlippagePadding() {
121
+ consoleLog("Raw inAmount:", this.jupQuote!.inAmount);
122
+ const inc = Math.max(
123
+ fromBps(this.priceImpactBps()) * 1.1,
124
+ fromBps(this.jupQuote!.slippageBps) * 0.1
125
+ );
126
+ consoleLog("Inc:", inc);
127
+ this.jupQuote!.inAmount = Math.round(
128
+ parseInt(this.jupQuote!.inAmount) +
129
+ parseInt(this.jupQuote!.inAmount) * inc
130
+ ).toString();
131
+ consoleLog("Increased inAmount:", this.jupQuote!.inAmount);
132
+ }
133
+
134
+ async getJupSwapTxData(data: SwapParams): Promise<JupSwapTransactionData> {
135
+ if (!this.jupQuote) {
136
+ this.jupQuote = await this.getQuote(data);
137
+ }
138
+
139
+ if (data.slippageIncFactor) {
140
+ this.adaptSlippageToPriceImpact(data.slippageIncFactor);
141
+ }
142
+ consoleLog("Quote:", this.jupQuote);
143
+
144
+ const instructions = await this.getJupInstructions(data);
145
+
146
+ if (data.exactOut) {
147
+ this.addInAmountSlippagePadding();
148
+ }
149
+
150
+ return {
151
+ jupQuote: this.jupQuote,
152
+ lookupTableAddresses: instructions.addressLookupTableAddresses,
153
+ setupInstructions: transactionBuilder(
154
+ (instructions.setupInstructions ?? []).map((ix) =>
155
+ getWrappedInstruction(this.signer, jupIxToSolanaIx(ix))
156
+ )
157
+ ),
158
+ swapIx: transactionBuilder([
159
+ getWrappedInstruction(
160
+ this.signer,
161
+ jupIxToSolanaIx(instructions.swapInstruction)
162
+ ),
163
+ ]),
164
+ cleanupIx: transactionBuilder(
165
+ instructions.cleanupInstruction
166
+ ? [
167
+ getWrappedInstruction(
168
+ this.signer,
169
+ jupIxToSolanaIx(instructions.cleanupInstruction)
170
+ ),
171
+ ]
172
+ : []
173
+ ),
174
+ };
175
+ }
176
+
177
+ async getSwapTx(data: SwapParams): Promise<TransactionItemInputs> {
178
+ const swapData = await this.getJupSwapTxData(data);
179
+
180
+ return {
181
+ tx: transactionBuilder().add([
182
+ swapData.setupInstructions,
183
+ swapData.swapIx,
184
+ swapData.cleanupIx,
185
+ ]),
186
+ lookupTableAddresses: swapData.lookupTableAddresses,
187
+ };
188
+ }
189
+ }
@@ -15,10 +15,9 @@ import {
15
15
  } from "@solana/spl-token";
16
16
  import {
17
17
  InvalidRebalanceConditionError,
18
- LendingPlatform,
19
- RebalanceDirection,
20
18
  SolautoAction,
21
19
  SolautoRebalanceType,
20
+ SwapType,
22
21
  TokenType,
23
22
  convertReferralFees,
24
23
  createSolautoProgram,
@@ -27,36 +26,20 @@ import {
27
26
  getSolautoErrorFromCode,
28
27
  isSolautoAction,
29
28
  solautoAction,
30
- } from "../generated";
31
- import { SolautoClient } from "../clients/solautoClient";
29
+ } from "../../generated";
30
+ import { SolautoClient } from "../solauto/solautoClient";
32
31
  import {
33
32
  closeTokenAccountUmiIx,
34
33
  createAssociatedTokenAccountUmiIx,
35
34
  systemTransferUmiIx,
36
- } from "../utils/solanaUtils";
37
- import { getJupSwapTransaction } from "../utils/jupiterUtils";
38
- import {
39
- getFlashLoanDetails,
40
- getFlashLoanRequirements,
41
- getJupSwapRebalanceDetails,
42
- getRebalanceValues,
43
- } from "../utils/solauto/rebalanceUtils";
35
+ } from "../../utils/solanaUtils";
44
36
  import {
45
37
  consoleLog,
46
- currentUnixSeconds,
47
38
  getSolanaAccountCreated,
48
39
  rpcAccountCreated,
49
- } from "../utils/generalUtils";
50
- import { SolautoMarginfiClient } from "../clients/solautoMarginfiClient";
51
- import {
52
- getMaxLiqUtilizationRateBps,
53
- uint8ArrayToBigInt,
54
- } from "../utils/numberUtils";
55
- import {
56
- eligibleForRebalance,
57
- positionStateWithLatestPrices,
58
- } from "../utils/solauto/generalUtils";
59
- import { getTokenAccount, getTokenAccountData } from "../utils/accountUtils";
40
+ } from "../../utils/generalUtils";
41
+ import { uint8ArrayToBigInt } from "../../utils/numberUtils";
42
+ import { getTokenAccount, getTokenAccountData } from "../../utils/accountUtils";
60
43
  import {
61
44
  createMarginfiProgram,
62
45
  getLendingAccountBorrowInstructionDataSerializer,
@@ -65,17 +48,16 @@ import {
65
48
  getLendingAccountWithdrawInstructionDataSerializer,
66
49
  getMarginfiErrorFromCode,
67
50
  MARGINFI_PROGRAM_ID,
68
- } from "../marginfi-sdk";
69
- import { ReferralStateManager } from "../clients";
51
+ } from "../../marginfi-sdk";
52
+ import { JupSwapManager, ReferralStateManager } from "..";
70
53
  import {
71
54
  createJupiterProgram,
72
55
  getJupiterErrorFromCode,
73
56
  JUPITER_PROGRAM_ID,
74
- } from "../jupiter-sdk";
75
- import { PRICES } from "../constants";
76
- import { TransactionItemInputs } from "../types";
77
- import { safeGetPrice } from "../utils";
78
- import { BundleSimulationError } from "../types/transactions";
57
+ } from "../../jupiter-sdk";
58
+ import { TransactionItemInputs } from "../../types";
59
+ import { isMarginfiClient } from "../../utils";
60
+ import { BundleSimulationError } from "../../types/transactions";
79
61
 
80
62
  interface wSolTokenUsage {
81
63
  wSolTokenAccount: PublicKey;
@@ -91,8 +73,8 @@ function getWSolUsage(
91
73
  },
92
74
  cancellingDcaIn?: TokenType
93
75
  ): wSolTokenUsage | undefined {
94
- const supplyIsWsol = client.supplyMint.equals(NATIVE_MINT);
95
- const debtIsWsol = client.debtMint.equals(NATIVE_MINT);
76
+ const supplyIsWsol = client.solautoPosition.supplyMint().equals(NATIVE_MINT);
77
+ const debtIsWsol = client.solautoPosition.debtMint().equals(NATIVE_MINT);
96
78
  if (!supplyIsWsol && !debtIsWsol) {
97
79
  return undefined;
98
80
  }
@@ -156,22 +138,19 @@ async function transactionChoresBefore(
156
138
  }
157
139
 
158
140
  if (client.selfManaged) {
159
- if (client.solautoPositionData === null) {
160
- chores = chores.add(client.openPosition());
161
- } else if (
162
- client.lendingPlatform === LendingPlatform.Marginfi &&
163
- !(await getSolanaAccountCreated(
164
- client.umi,
165
- (client as SolautoMarginfiClient).marginfiAccountPk
166
- ))
141
+ if (
142
+ isMarginfiClient(client) &&
143
+ !(await getSolanaAccountCreated(client.umi, client.marginfiAccountPk))
167
144
  ) {
168
145
  chores = chores.add(
169
- (client as SolautoMarginfiClient).marginfiAccountInitialize(
170
- (client as SolautoMarginfiClient).marginfiAccount as Signer
171
- )
146
+ client.marginfiAccountInitialize(client.marginfiAccount as Signer)
172
147
  );
173
148
  }
174
149
  // TODO: PF
150
+
151
+ if (!client.solautoPosition.exists()) {
152
+ chores = chores.add(client.openPositionIx());
153
+ }
175
154
  }
176
155
 
177
156
  const wSolUsage = getWSolUsage(
@@ -250,8 +229,8 @@ async function transactionChoresBefore(
250
229
  client.signer,
251
230
  toWeb3JsPublicKey(client.signer.publicKey),
252
231
  isSolautoAction("Withdraw", solautoAction)
253
- ? client.supplyMint
254
- : client.debtMint
232
+ ? client.solautoPosition.supplyMint()
233
+ : client.solautoPosition.debtMint()
255
234
  )
256
235
  );
257
236
  accountsGettingCreated.push(tokenAccount.toString());
@@ -280,11 +259,6 @@ export async function rebalanceChoresBefore(
280
259
  client.referredBySupplyTa() && usesAccount(client.referredBySupplyTa()!);
281
260
  const checkReferralDebtTa =
282
261
  client.referredByDebtTa() && usesAccount(client.referredByDebtTa()!);
283
- const checkIntermediaryMfiAccount =
284
- client.lendingPlatform === LendingPlatform.Marginfi &&
285
- usesAccount(
286
- (client as SolautoMarginfiClient).intermediaryMarginfiAccountPk
287
- );
288
262
  const checkSignerSupplyTa = usesAccount(client.signerSupplyTa);
289
263
  const checkSignerDebtTa = usesAccount(client.signerDebtTa);
290
264
 
@@ -293,24 +267,14 @@ export async function rebalanceChoresBefore(
293
267
  checkReferralSupplyTa ? client.referredBySupplyTa() : PublicKey.default,
294
268
  ],
295
269
  ...[checkReferralDebtTa ? client.referredByDebtTa() : PublicKey.default],
296
- ...[
297
- checkIntermediaryMfiAccount
298
- ? (client as SolautoMarginfiClient).intermediaryMarginfiAccountPk
299
- : PublicKey.default,
300
- ],
301
270
  ...[checkSignerSupplyTa ? client.signerSupplyTa : PublicKey.default],
302
271
  ...[checkSignerDebtTa ? client.signerDebtTa : PublicKey.default],
303
272
  ];
304
273
 
305
- const [
306
- referredBySupplyTa,
307
- referredByDebtTa,
308
- intermediaryMarginfiAccount,
309
- signerSupplyTa,
310
- signerDebtTa,
311
- ] = await client.umi.rpc.getAccounts(
312
- accountsNeeded.map((x) => publicKey(x ?? PublicKey.default))
313
- );
274
+ const [referredBySupplyTa, referredByDebtTa, signerSupplyTa, signerDebtTa] =
275
+ await client.umi.rpc.getAccounts(
276
+ accountsNeeded.map((x) => publicKey(x ?? PublicKey.default))
277
+ );
314
278
 
315
279
  let chores = transactionBuilder();
316
280
 
@@ -320,7 +284,7 @@ export async function rebalanceChoresBefore(
320
284
  createAssociatedTokenAccountUmiIx(
321
285
  client.signer,
322
286
  client.referredByState!,
323
- client.supplyMint
287
+ client.solautoPosition.supplyMint()
324
288
  )
325
289
  );
326
290
  }
@@ -331,19 +295,7 @@ export async function rebalanceChoresBefore(
331
295
  createAssociatedTokenAccountUmiIx(
332
296
  client.signer,
333
297
  client.referredByState!,
334
- client.debtMint
335
- )
336
- );
337
- }
338
-
339
- if (
340
- checkIntermediaryMfiAccount &&
341
- !rpcAccountCreated(intermediaryMarginfiAccount)
342
- ) {
343
- client.log("Creating intermediary marginfi account");
344
- chores = chores.add(
345
- (client as SolautoMarginfiClient).marginfiAccountInitialize(
346
- (client as SolautoMarginfiClient).intermediaryMarginfiAccountSigner!
298
+ client.solautoPosition.debtMint()
347
299
  )
348
300
  );
349
301
  }
@@ -358,7 +310,7 @@ export async function rebalanceChoresBefore(
358
310
  createAssociatedTokenAccountUmiIx(
359
311
  client.signer,
360
312
  toWeb3JsPublicKey(client.signer.publicKey),
361
- client.supplyMint
313
+ client.solautoPosition.supplyMint()
362
314
  )
363
315
  );
364
316
  accountsGettingCreated.push(signerSupplyTa.publicKey.toString());
@@ -374,7 +326,7 @@ export async function rebalanceChoresBefore(
374
326
  createAssociatedTokenAccountUmiIx(
375
327
  client.signer,
376
328
  toWeb3JsPublicKey(client.signer.publicKey),
377
- client.debtMint
329
+ client.solautoPosition.debtMint()
378
330
  )
379
331
  );
380
332
  accountsGettingCreated.push(signerDebtTa.publicKey.toString());
@@ -421,9 +373,11 @@ function getRebalanceInstructions(
421
373
  try {
422
374
  const serializer = getMarginfiRebalanceInstructionDataSerializer();
423
375
  const discriminator = serializer.serialize({
424
- targetInAmountBaseUnit: 0,
425
- rebalanceType: SolautoRebalanceType.None,
376
+ swapInAmountBaseUnit: 0,
377
+ rebalanceType: SolautoRebalanceType.Regular,
378
+ swapType: SwapType.ExactIn,
426
379
  targetLiqUtilizationRateBps: 0,
380
+ flashLoanFeeBps: null,
427
381
  })[0];
428
382
  const [data, _] = serializer.deserialize(x.data);
429
383
  if (data.discriminator === discriminator) {
@@ -599,201 +553,6 @@ export async function getTransactionChores(
599
553
  return [choresBefore, choresAfter];
600
554
  }
601
555
 
602
- export async function requiresRefreshBeforeRebalance(client: SolautoClient) {
603
- const neverRefreshedBefore =
604
- client.solautoPositionData &&
605
- client.solautoPositionData.state.supply.amountCanBeUsed.baseUnit ===
606
- BigInt(0) &&
607
- client.solautoPositionData.state.debt.amountCanBeUsed.baseUnit ===
608
- BigInt(0);
609
- const aboveMaxLtv =
610
- client.solautoPositionState!.liqUtilizationRateBps >
611
- getMaxLiqUtilizationRateBps(
612
- client.solautoPositionState!.maxLtvBps,
613
- client.solautoPositionState!.liqThresholdBps,
614
- 0.01
615
- );
616
-
617
- if (aboveMaxLtv || neverRefreshedBefore) {
618
- return true;
619
- } else if (client.solautoPositionData && !client.selfManaged) {
620
- if (
621
- client.contextUpdates.supplyAdjustment > BigInt(0) ||
622
- client.contextUpdates.debtAdjustment > BigInt(0)
623
- ) {
624
- return false;
625
- }
626
-
627
- const oldStateWithLatestPrices = await positionStateWithLatestPrices(
628
- client.solautoPositionData.state,
629
- PRICES[client.supplyMint.toString()].price,
630
- PRICES[client.debtMint.toString()].price
631
- );
632
- const utilizationRateDiff = Math.abs(
633
- (client.solautoPositionState?.liqUtilizationRateBps ?? 0) -
634
- oldStateWithLatestPrices.liqUtilizationRateBps
635
- );
636
-
637
- client.log("Liq utilization rate diff:", utilizationRateDiff);
638
- if (
639
- client.contextUpdates.supplyAdjustment === BigInt(0) &&
640
- client.contextUpdates.debtAdjustment === BigInt(0) &&
641
- utilizationRateDiff >= 10
642
- ) {
643
- client.log(
644
- "Choosing to refresh before rebalance. Utilization rate diff:",
645
- utilizationRateDiff
646
- );
647
- return true;
648
- }
649
- }
650
-
651
- // Rebalance ix will already refresh internally if position is self managed, has automation to update, or position state last updated >= 1 day ago
652
-
653
- client.log("Not refreshing before rebalance");
654
- return false;
655
- }
656
-
657
- export async function buildSolautoRebalanceTransaction(
658
- client: SolautoClient,
659
- targetLiqUtilizationRateBps?: number,
660
- attemptNum?: number
661
- ): Promise<TransactionItemInputs | undefined> {
662
- client.solautoPositionState = await client.getFreshPositionState();
663
- const supplyPrice = safeGetPrice(client.supplyMint) ?? 0;
664
- const debtPrice = safeGetPrice(client.debtMint) ?? 0;
665
-
666
- if (
667
- (client.solautoPositionState?.supply.amountUsed.baseUnit === BigInt(0) &&
668
- client.contextUpdates.supplyAdjustment === BigInt(0)) ||
669
- (targetLiqUtilizationRateBps === undefined &&
670
- !eligibleForRebalance(
671
- client.solautoPositionState!,
672
- client.solautoPositionSettings(),
673
- client.solautoPositionActiveDca(),
674
- currentUnixSeconds(),
675
- supplyPrice,
676
- debtPrice
677
- ))
678
- ) {
679
- client.log("Not eligible for a rebalance");
680
- return undefined;
681
- }
682
-
683
- const values = getRebalanceValues(
684
- client.solautoPositionState!,
685
- client.solautoPositionSettings(),
686
- client.solautoPositionActiveDca(),
687
- currentUnixSeconds(),
688
- supplyPrice,
689
- debtPrice,
690
- targetLiqUtilizationRateBps
691
- );
692
- client.log("Rebalance values: ", values);
693
-
694
- const flRequirements = await getFlashLoanRequirements(
695
- client,
696
- values,
697
- attemptNum
698
- );
699
- const swapDetails = await getJupSwapRebalanceDetails(
700
- client,
701
- values,
702
- flRequirements,
703
- targetLiqUtilizationRateBps,
704
- attemptNum
705
- );
706
- const { jupQuote, lookupTableAddresses, setupInstructions, swapIx } =
707
- await getJupSwapTransaction(client.signer, swapDetails, attemptNum);
708
-
709
- const flashLoan = flRequirements
710
- ? getFlashLoanDetails(client, flRequirements, values, jupQuote)
711
- : undefined;
712
-
713
- let tx = transactionBuilder();
714
-
715
- if (await requiresRefreshBeforeRebalance(client)) {
716
- tx = tx.add(client.refresh());
717
- }
718
-
719
- if (flashLoan) {
720
- client.log("Flash loan details: ", flashLoan);
721
- const addFirstRebalance = values.amountUsdToDcaIn > 0;
722
-
723
- const rebalanceThenSwap =
724
- values.rebalanceDirection === RebalanceDirection.Repay &&
725
- flashLoan.useDebtLiquidity;
726
-
727
- const rebalanceType = addFirstRebalance
728
- ? SolautoRebalanceType.DoubleRebalanceWithFL
729
- : rebalanceThenSwap
730
- ? SolautoRebalanceType.FLRebalanceThenSwap
731
- : SolautoRebalanceType.FLSwapThenRebalance;
732
-
733
- client.log("Rebalance type:", rebalanceType);
734
- const firstRebalance = client.rebalance(
735
- "A",
736
- jupQuote,
737
- rebalanceType,
738
- values,
739
- flashLoan,
740
- targetLiqUtilizationRateBps
741
- );
742
- const lastRebalance = client.rebalance(
743
- "B",
744
- jupQuote,
745
- rebalanceType,
746
- values,
747
- flashLoan,
748
- targetLiqUtilizationRateBps
749
- );
750
-
751
- const flashBorrowDest = getTokenAccount(
752
- rebalanceThenSwap
753
- ? client.solautoPosition
754
- : toWeb3JsPublicKey(client.signer.publicKey),
755
- rebalanceThenSwap ? swapDetails.outputMint : swapDetails.inputMint
756
- );
757
-
758
- tx = tx.add([
759
- setupInstructions,
760
- client.flashBorrow(rebalanceType, flashLoan, flashBorrowDest),
761
- ...(addFirstRebalance ? [firstRebalance] : []),
762
- ...(rebalanceThenSwap
763
- ? [lastRebalance, swapIx]
764
- : [swapIx, lastRebalance]),
765
- client.flashRepay(flashLoan),
766
- ]);
767
- } else {
768
- const rebalanceType = SolautoRebalanceType.Regular;
769
- tx = tx.add([
770
- setupInstructions,
771
- client.rebalance(
772
- "A",
773
- jupQuote,
774
- rebalanceType,
775
- values,
776
- undefined,
777
- targetLiqUtilizationRateBps
778
- ),
779
- swapIx,
780
- client.rebalance(
781
- "B",
782
- jupQuote,
783
- rebalanceType,
784
- values,
785
- undefined,
786
- targetLiqUtilizationRateBps
787
- ),
788
- ]);
789
- }
790
-
791
- return {
792
- tx,
793
- lookupTableAddresses,
794
- };
795
- }
796
-
797
556
  export async function convertReferralFeesToDestination(
798
557
  referralManager: ReferralStateManager,
799
558
  tokenAccount: PublicKey,
@@ -807,8 +566,9 @@ export async function convertReferralFeesToDestination(
807
566
  return undefined;
808
567
  }
809
568
 
810
- const { lookupTableAddresses, setupInstructions, swapIx } =
811
- await getJupSwapTransaction(referralManager.umi.identity, {
569
+ const jupSwapManager = new JupSwapManager(referralManager.umi.identity);
570
+ const { lookupTableAddresses, setupInstructions, swapIx, cleanupIx } =
571
+ await jupSwapManager.getJupSwapTxData({
812
572
  amount: tokenAccountData.amount,
813
573
  destinationWallet: referralManager.referralState,
814
574
  inputMint: tokenAccountData.mint,
@@ -5,33 +5,33 @@ import {
5
5
  TransactionBuilder,
6
6
  Umi,
7
7
  } from "@metaplex-foundation/umi";
8
- import { SolautoClient } from "../clients/solautoClient";
8
+ import { SolautoClient } from "../solauto/solautoClient";
9
9
  import {
10
10
  addTxOptimizations,
11
11
  getAddressLookupInputs,
12
12
  sendSingleOptimizedTransaction,
13
- } from "../utils/solanaUtils";
13
+ } from "../../utils/solanaUtils";
14
14
  import {
15
15
  consoleLog,
16
16
  ErrorsToThrow,
17
17
  retryWithExponentialBackoff,
18
- } from "../utils/generalUtils";
18
+ } from "../../utils/generalUtils";
19
19
  import { getErrorInfo, getTransactionChores } from "./transactionUtils";
20
20
  import {
21
21
  PriorityFeeSetting,
22
22
  priorityFeeSettingValues,
23
23
  TransactionItemInputs,
24
24
  TransactionRunType,
25
- } from "../types";
26
- import { ReferralStateManager, TxHandler } from "../clients";
25
+ } from "../../types";
26
+ import { ReferralStateManager, TxHandler } from "..";
27
27
  import {
28
28
  PublicKey,
29
29
  TransactionExpiredBlockheightExceededError,
30
30
  } from "@solana/web3.js";
31
- import { SWITCHBOARD_PRICE_FEED_IDS } from "../constants/switchboardConstants";
32
- import { buildSwbSubmitResponseTx, getSwitchboardFeedData } from "../utils";
33
- import { sendJitoBundledTransactions } from "../utils/jitoUtils";
34
- import { SOLAUTO_PROD_PROGRAM, SOLAUTO_TEST_PROGRAM } from "../constants";
31
+ import { SWITCHBOARD_PRICE_FEED_IDS } from "../../constants/switchboardConstants";
32
+ import { buildSwbSubmitResponseTx, getSwitchboardFeedData } from "../../utils";
33
+ import { sendJitoBundledTransactions } from "../../utils/jitoUtils";
34
+ import { SOLAUTO_PROD_PROGRAM, SOLAUTO_TEST_PROGRAM } from "../../constants";
35
35
 
36
36
  const CHORES_TX_NAME = "account chores";
37
37
  const MAX_SUPPORTED_ACCOUNT_LOCKS = 64;
@@ -416,11 +416,15 @@ export class TransactionsManager {
416
416
  }
417
417
 
418
418
  private async updateLut(tx: TransactionBuilder, newLut: boolean) {
419
+ const lutInputs = await getAddressLookupInputs(
420
+ this.txHandler.umi,
421
+ this.txHandler.defaultLookupTables()
422
+ );
419
423
  const updateLutTxName = `${newLut ? "create" : "update"} lookup table`;
420
424
  await retryWithExponentialBackoff(
421
425
  async (attemptNum, prevError) =>
422
426
  await this.sendTransaction(
423
- tx,
427
+ tx.setAddressLookupTables(lutInputs),
424
428
  updateLutTxName,
425
429
  attemptNum,
426
430
  this.getUpdatedPriorityFeeSetting(prevError, attemptNum),
@@ -430,6 +434,7 @@ export class TransactionsManager {
430
434
  150,
431
435
  this.errorsToThrow
432
436
  );
437
+ await this.txHandler.refetchReferralState();
433
438
  }
434
439
 
435
440
  public async clientSend(
@@ -0,0 +1,3 @@
1
+ export * from "./solautoPositionEx";
2
+ export * from "./marginfiSolautoPositionEx";
3
+ export * from "./utils";