@byreal-io/byreal-clmm-sdk 0.2.0

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/LICENSE +21 -0
  2. package/README.md +341 -0
  3. package/dist/esm/client/chain.d.ts +227 -0
  4. package/dist/esm/client/chain.d.ts.map +1 -0
  5. package/dist/esm/client/chain.js +1123 -0
  6. package/dist/esm/client/chain.js.map +1 -0
  7. package/dist/esm/client/index.d.ts +4 -0
  8. package/dist/esm/client/index.d.ts.map +1 -0
  9. package/dist/esm/client/index.js +4 -0
  10. package/dist/esm/client/index.js.map +1 -0
  11. package/dist/esm/client/models.d.ts +160 -0
  12. package/dist/esm/client/models.d.ts.map +1 -0
  13. package/dist/esm/client/models.js +2 -0
  14. package/dist/esm/client/models.js.map +1 -0
  15. package/dist/esm/client/utils.d.ts +103 -0
  16. package/dist/esm/client/utils.d.ts.map +1 -0
  17. package/dist/esm/client/utils.js +238 -0
  18. package/dist/esm/client/utils.js.map +1 -0
  19. package/dist/esm/constants.d.ts +19 -0
  20. package/dist/esm/constants.d.ts.map +1 -0
  21. package/dist/esm/constants.js +27 -0
  22. package/dist/esm/constants.js.map +1 -0
  23. package/dist/esm/index.d.ts +5 -0
  24. package/dist/esm/index.d.ts.map +1 -0
  25. package/dist/esm/index.js +5 -0
  26. package/dist/esm/index.js.map +1 -0
  27. package/dist/esm/instructions/baseInstruction.d.ts +74 -0
  28. package/dist/esm/instructions/baseInstruction.d.ts.map +1 -0
  29. package/dist/esm/instructions/baseInstruction.js +577 -0
  30. package/dist/esm/instructions/baseInstruction.js.map +1 -0
  31. package/dist/esm/instructions/constants.d.ts +29 -0
  32. package/dist/esm/instructions/constants.d.ts.map +1 -0
  33. package/dist/esm/instructions/constants.js +32 -0
  34. package/dist/esm/instructions/constants.js.map +1 -0
  35. package/dist/esm/instructions/getRawData.d.ts +60 -0
  36. package/dist/esm/instructions/getRawData.d.ts.map +1 -0
  37. package/dist/esm/instructions/getRawData.js +105 -0
  38. package/dist/esm/instructions/getRawData.js.map +1 -0
  39. package/dist/esm/instructions/index.d.ts +9 -0
  40. package/dist/esm/instructions/index.d.ts.map +1 -0
  41. package/dist/esm/instructions/index.js +9 -0
  42. package/dist/esm/instructions/index.js.map +1 -0
  43. package/dist/esm/instructions/instruction.d.ts +137 -0
  44. package/dist/esm/instructions/instruction.d.ts.map +1 -0
  45. package/dist/esm/instructions/instruction.js +152 -0
  46. package/dist/esm/instructions/instruction.js.map +1 -0
  47. package/dist/esm/instructions/layout.d.ts +217 -0
  48. package/dist/esm/instructions/layout.d.ts.map +1 -0
  49. package/dist/esm/instructions/layout.js +203 -0
  50. package/dist/esm/instructions/layout.js.map +1 -0
  51. package/dist/esm/instructions/libs/marshmallow/bufferLayout.d.ts +107 -0
  52. package/dist/esm/instructions/libs/marshmallow/bufferLayout.d.ts.map +1 -0
  53. package/dist/esm/instructions/libs/marshmallow/bufferLayout.js +49 -0
  54. package/dist/esm/instructions/libs/marshmallow/bufferLayout.js.map +1 -0
  55. package/dist/esm/instructions/libs/marshmallow/index.d.ts +88 -0
  56. package/dist/esm/instructions/libs/marshmallow/index.d.ts.map +1 -0
  57. package/dist/esm/instructions/libs/marshmallow/index.js +256 -0
  58. package/dist/esm/instructions/libs/marshmallow/index.js.map +1 -0
  59. package/dist/esm/instructions/models.d.ts +39 -0
  60. package/dist/esm/instructions/models.d.ts.map +1 -0
  61. package/dist/esm/instructions/models.js +14 -0
  62. package/dist/esm/instructions/models.js.map +1 -0
  63. package/dist/esm/instructions/pda.d.ts +52 -0
  64. package/dist/esm/instructions/pda.d.ts.map +1 -0
  65. package/dist/esm/instructions/pda.js +47 -0
  66. package/dist/esm/instructions/pda.js.map +1 -0
  67. package/dist/esm/instructions/target/idl/byreal_amm_v3.json +7242 -0
  68. package/dist/esm/instructions/target/idl/byreal_amm_v3_test.json +7680 -0
  69. package/dist/esm/instructions/target/types/byreal_amm_v3.d.ts +5329 -0
  70. package/dist/esm/instructions/target/types/byreal_amm_v3.d.ts.map +1 -0
  71. package/dist/esm/instructions/target/types/byreal_amm_v3.js +2 -0
  72. package/dist/esm/instructions/target/types/byreal_amm_v3.js.map +1 -0
  73. package/dist/esm/instructions/target/types/raydium_amm_v3.d.ts +4149 -0
  74. package/dist/esm/instructions/target/types/raydium_amm_v3.d.ts.map +1 -0
  75. package/dist/esm/instructions/target/types/raydium_amm_v3.js +2 -0
  76. package/dist/esm/instructions/target/types/raydium_amm_v3.js.map +1 -0
  77. package/dist/esm/instructions/utils/binaryUtils.d.ts +11 -0
  78. package/dist/esm/instructions/utils/binaryUtils.d.ts.map +1 -0
  79. package/dist/esm/instructions/utils/binaryUtils.js +77 -0
  80. package/dist/esm/instructions/utils/binaryUtils.js.map +1 -0
  81. package/dist/esm/instructions/utils/fetchWalletTokenAccounts.d.ts +42 -0
  82. package/dist/esm/instructions/utils/fetchWalletTokenAccounts.d.ts.map +1 -0
  83. package/dist/esm/instructions/utils/fetchWalletTokenAccounts.js +63 -0
  84. package/dist/esm/instructions/utils/fetchWalletTokenAccounts.js.map +1 -0
  85. package/dist/esm/instructions/utils/getTickArrayBitmapExtension.d.ts +8 -0
  86. package/dist/esm/instructions/utils/getTickArrayBitmapExtension.d.ts.map +1 -0
  87. package/dist/esm/instructions/utils/getTickArrayBitmapExtension.js +22 -0
  88. package/dist/esm/instructions/utils/getTickArrayBitmapExtension.js.map +1 -0
  89. package/dist/esm/instructions/utils/getTickArrayInfo.d.ts +16 -0
  90. package/dist/esm/instructions/utils/getTickArrayInfo.d.ts.map +1 -0
  91. package/dist/esm/instructions/utils/getTickArrayInfo.js +75 -0
  92. package/dist/esm/instructions/utils/getTickArrayInfo.js.map +1 -0
  93. package/dist/esm/instructions/utils/index.d.ts +21 -0
  94. package/dist/esm/instructions/utils/index.d.ts.map +1 -0
  95. package/dist/esm/instructions/utils/index.js +21 -0
  96. package/dist/esm/instructions/utils/index.js.map +1 -0
  97. package/dist/esm/instructions/utils/liquidityMath.d.ts +30 -0
  98. package/dist/esm/instructions/utils/liquidityMath.d.ts.map +1 -0
  99. package/dist/esm/instructions/utils/liquidityMath.js +138 -0
  100. package/dist/esm/instructions/utils/liquidityMath.js.map +1 -0
  101. package/dist/esm/instructions/utils/mathUtils.d.ts +11 -0
  102. package/dist/esm/instructions/utils/mathUtils.d.ts.map +1 -0
  103. package/dist/esm/instructions/utils/mathUtils.js +36 -0
  104. package/dist/esm/instructions/utils/mathUtils.js.map +1 -0
  105. package/dist/esm/instructions/utils/models.d.ts +93 -0
  106. package/dist/esm/instructions/utils/models.d.ts.map +1 -0
  107. package/dist/esm/instructions/utils/models.js +13 -0
  108. package/dist/esm/instructions/utils/models.js.map +1 -0
  109. package/dist/esm/instructions/utils/poolStateUtils.d.ts +134 -0
  110. package/dist/esm/instructions/utils/poolStateUtils.d.ts.map +1 -0
  111. package/dist/esm/instructions/utils/poolStateUtils.js +137 -0
  112. package/dist/esm/instructions/utils/poolStateUtils.js.map +1 -0
  113. package/dist/esm/instructions/utils/poolUtils.d.ts +136 -0
  114. package/dist/esm/instructions/utils/poolUtils.d.ts.map +1 -0
  115. package/dist/esm/instructions/utils/poolUtils.js +219 -0
  116. package/dist/esm/instructions/utils/poolUtils.js.map +1 -0
  117. package/dist/esm/instructions/utils/position.d.ts +36 -0
  118. package/dist/esm/instructions/utils/position.d.ts.map +1 -0
  119. package/dist/esm/instructions/utils/position.js +86 -0
  120. package/dist/esm/instructions/utils/position.js.map +1 -0
  121. package/dist/esm/instructions/utils/sqrtPriceMath.d.ts +14 -0
  122. package/dist/esm/instructions/utils/sqrtPriceMath.d.ts.map +1 -0
  123. package/dist/esm/instructions/utils/sqrtPriceMath.js +168 -0
  124. package/dist/esm/instructions/utils/sqrtPriceMath.js.map +1 -0
  125. package/dist/esm/instructions/utils/swapMath.d.ts +48 -0
  126. package/dist/esm/instructions/utils/swapMath.d.ts.map +1 -0
  127. package/dist/esm/instructions/utils/swapMath.js +263 -0
  128. package/dist/esm/instructions/utils/swapMath.js.map +1 -0
  129. package/dist/esm/instructions/utils/tick.d.ts +106 -0
  130. package/dist/esm/instructions/utils/tick.d.ts.map +1 -0
  131. package/dist/esm/instructions/utils/tick.js +390 -0
  132. package/dist/esm/instructions/utils/tick.js.map +1 -0
  133. package/dist/esm/instructions/utils/tickArrayUtils.d.ts +50 -0
  134. package/dist/esm/instructions/utils/tickArrayUtils.d.ts.map +1 -0
  135. package/dist/esm/instructions/utils/tickArrayUtils.js +157 -0
  136. package/dist/esm/instructions/utils/tickArrayUtils.js.map +1 -0
  137. package/dist/esm/instructions/utils/tickMath.d.ts +18 -0
  138. package/dist/esm/instructions/utils/tickMath.d.ts.map +1 -0
  139. package/dist/esm/instructions/utils/tickMath.js +34 -0
  140. package/dist/esm/instructions/utils/tickMath.js.map +1 -0
  141. package/dist/esm/instructions/utils/tickarrayBitmap.d.ts +38 -0
  142. package/dist/esm/instructions/utils/tickarrayBitmap.d.ts.map +1 -0
  143. package/dist/esm/instructions/utils/tickarrayBitmap.js +157 -0
  144. package/dist/esm/instructions/utils/tickarrayBitmap.js.map +1 -0
  145. package/dist/esm/instructions/utils/transfer.d.ts +7 -0
  146. package/dist/esm/instructions/utils/transfer.d.ts.map +1 -0
  147. package/dist/esm/instructions/utils/transfer.js +78 -0
  148. package/dist/esm/instructions/utils/transfer.js.map +1 -0
  149. package/dist/esm/utils/accountInfo.d.ts +27 -0
  150. package/dist/esm/utils/accountInfo.d.ts.map +1 -0
  151. package/dist/esm/utils/accountInfo.js +80 -0
  152. package/dist/esm/utils/accountInfo.js.map +1 -0
  153. package/dist/esm/utils/checkV0TxSize.d.ts +8 -0
  154. package/dist/esm/utils/checkV0TxSize.d.ts.map +1 -0
  155. package/dist/esm/utils/checkV0TxSize.js +18 -0
  156. package/dist/esm/utils/checkV0TxSize.js.map +1 -0
  157. package/dist/esm/utils/estimateComputeUnits.d.ts +11 -0
  158. package/dist/esm/utils/estimateComputeUnits.d.ts.map +1 -0
  159. package/dist/esm/utils/estimateComputeUnits.js +48 -0
  160. package/dist/esm/utils/estimateComputeUnits.js.map +1 -0
  161. package/dist/esm/utils/generatePubKey.d.ts +10 -0
  162. package/dist/esm/utils/generatePubKey.d.ts.map +1 -0
  163. package/dist/esm/utils/generatePubKey.js +14 -0
  164. package/dist/esm/utils/generatePubKey.js.map +1 -0
  165. package/dist/esm/utils/index.d.ts +9 -0
  166. package/dist/esm/utils/index.d.ts.map +1 -0
  167. package/dist/esm/utils/index.js +11 -0
  168. package/dist/esm/utils/index.js.map +1 -0
  169. package/dist/esm/utils/token.d.ts +9 -0
  170. package/dist/esm/utils/token.d.ts.map +1 -0
  171. package/dist/esm/utils/token.js +16 -0
  172. package/dist/esm/utils/token.js.map +1 -0
  173. package/dist/esm/utils/transactionUtils.d.ts +84 -0
  174. package/dist/esm/utils/transactionUtils.d.ts.map +1 -0
  175. package/dist/esm/utils/transactionUtils.js +138 -0
  176. package/dist/esm/utils/transactionUtils.js.map +1 -0
  177. package/dist/esm/utils/validateAndParsePublicKey.d.ts +15 -0
  178. package/dist/esm/utils/validateAndParsePublicKey.d.ts.map +1 -0
  179. package/dist/esm/utils/validateAndParsePublicKey.js +42 -0
  180. package/dist/esm/utils/validateAndParsePublicKey.js.map +1 -0
  181. package/package.json +66 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Byreal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,341 @@
1
+ # Byreal CLMM SDK
2
+
3
+ Solana concentrated liquidity market maker SDK for Byreal protocol.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @byreal-io/byreal-clmm-sdk
9
+ # or
10
+ yarn add @byreal-io/byreal-clmm-sdk
11
+ # or
12
+ pnpm add @byreal-io/byreal-clmm-sdk
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ### Initialize SDK
18
+
19
+ ```typescript
20
+ import { Connection, Keypair, PublicKey } from '@solana/web3.js';
21
+ import { Chain, BYREAL_CLMM_PROGRAM_ID } from '@byreal-io/byreal-clmm-sdk';
22
+
23
+ // Setup connection
24
+ const connection = new Connection('https://api.mainnet-beta.solana.com');
25
+ const wallet = Keypair.fromSecretKey(/* your secret key */);
26
+
27
+ // Initialize Chain instance
28
+ const chain = new Chain({
29
+ connection,
30
+ programId: BYREAL_CLMM_PROGRAM_ID,
31
+ });
32
+
33
+ // Signer callback for transactions
34
+ const signerCallback = async (tx) => {
35
+ tx.sign([wallet]);
36
+ return tx;
37
+ };
38
+ ```
39
+
40
+ ## Core Features
41
+
42
+ ### 1. Get Position Info
43
+
44
+ Query user positions and view liquidity details.
45
+
46
+ ```typescript
47
+ import { PublicKey } from '@solana/web3.js';
48
+
49
+ // Get all positions for a user
50
+ const userAddress = new PublicKey('your-wallet-address');
51
+ const positionList = await chain.getRawPositionInfoListByUserAddress(userAddress);
52
+
53
+ // Get detailed info for specific position
54
+ const nftMints = positionList.map((position) => position.nftMint);
55
+
56
+ for (const nftMint of nftMints) {
57
+ const positionInfo = await chain.getPositionInfoByNftMint(nftMint);
58
+
59
+ if (!positionInfo) continue;
60
+
61
+ const { uiPriceLower, uiPriceUpper, tokenA, tokenB } = positionInfo;
62
+
63
+ console.log(`NFT: ${nftMint.toBase58()}`);
64
+ console.log(`Price Range: ${uiPriceLower} - ${uiPriceUpper}`);
65
+ console.log(`TokenA Amount: ${tokenA.uiAmount}`);
66
+ console.log(`TokenA Fees: ${tokenA.uiFeeAmount}`);
67
+ console.log(`TokenB Amount: ${tokenB.uiAmount}`);
68
+ console.log(`TokenB Fees: ${tokenB.uiFeeAmount}`);
69
+ }
70
+ ```
71
+
72
+ ### 2. Create Position
73
+
74
+ Create a new liquidity position within a specific price range.
75
+
76
+ ```typescript
77
+ import BN from 'bn.js';
78
+ import { Decimal } from 'decimal.js';
79
+ import { TickMath } from '@byreal-io/byreal-clmm-sdk';
80
+
81
+ // Step 1: Get pool info
82
+ const poolId = new PublicKey('your-pool-address');
83
+ const poolInfo = await chain.getRawPoolInfoByPoolId(poolId);
84
+
85
+ // Step 2: Define price range and align to ticks
86
+ const userStartPrice = '0.998';
87
+ const userEndPrice = '1.002';
88
+
89
+ const priceInTickLower = TickMath.getTickAlignedPriceDetails(
90
+ new Decimal(userStartPrice),
91
+ poolInfo.tickSpacing,
92
+ poolInfo.mintDecimalsA,
93
+ poolInfo.mintDecimalsB
94
+ );
95
+
96
+ const priceInTickUpper = TickMath.getTickAlignedPriceDetails(
97
+ new Decimal(userEndPrice),
98
+ poolInfo.tickSpacing,
99
+ poolInfo.mintDecimalsA,
100
+ poolInfo.mintDecimalsB
101
+ );
102
+
103
+ // Step 3: Calculate required amounts
104
+ const base = 'MintA'; // Which token to use as base
105
+ const baseAmount = new BN(2 * 10 ** poolInfo.mintDecimalsA);
106
+
107
+ // Calculate the amount of TokenB needed
108
+ const amountB = chain.getAmountBFromAmountA({
109
+ priceLower: priceInTickLower.price,
110
+ priceUpper: priceInTickUpper.price,
111
+ amountA: baseAmount,
112
+ poolInfo,
113
+ });
114
+
115
+ // Add 2% slippage
116
+ const amountBWithSlippage = new BN(amountB).mul(new BN(10000 * (1 + 0.02))).div(new BN(10000));
117
+
118
+ // Step 4: Create position
119
+ const txid = await chain.createPosition({
120
+ userAddress,
121
+ poolInfo,
122
+ tickLower: priceInTickLower.tick,
123
+ tickUpper: priceInTickUpper.tick,
124
+ base,
125
+ baseAmount,
126
+ otherAmountMax: amountBWithSlippage,
127
+ signerCallback,
128
+ });
129
+
130
+ console.log('Position created:', txid);
131
+ ```
132
+
133
+ ### 3. Remove Liquidity
134
+
135
+ Remove all liquidity and close the position.
136
+
137
+ ```typescript
138
+ import { PublicKey } from '@solana/web3.js';
139
+
140
+ const nftMint = new PublicKey('your-position-nft-mint');
141
+
142
+ const txid = await chain.decreaseFullLiquidity({
143
+ userAddress,
144
+ nftMint,
145
+ signerCallback,
146
+ });
147
+
148
+ console.log('Liquidity removed:', txid);
149
+ ```
150
+
151
+ ### 4. Collect Fees
152
+
153
+ Collect accumulated fees from a position.
154
+
155
+ ```typescript
156
+ import { PublicKey } from '@solana/web3.js';
157
+
158
+ const nftMint = new PublicKey('your-position-nft-mint');
159
+
160
+ const txid = await chain.collectFees({
161
+ userAddress,
162
+ nftMint,
163
+ signerCallback,
164
+ });
165
+
166
+ console.log('Fees collected:', txid);
167
+ ```
168
+
169
+ ### 5. Swap Tokens
170
+
171
+ Swap tokens using the concentrated liquidity pool.
172
+
173
+ #### Exact Input Swap
174
+
175
+ Specify input amount, get estimated output.
176
+
177
+ ```typescript
178
+ import BN from 'bn.js';
179
+
180
+ // Get pool info
181
+ const poolInfo = await chain.getRawPoolInfoByPoolId(poolId);
182
+
183
+ // Define input amount
184
+ const amountIn = new BN(1 * 10 ** poolInfo.mintDecimalsA);
185
+
186
+ // Step 1: Get quote
187
+ const quoteReturn = await chain.qouteSwap({
188
+ poolInfo,
189
+ slippage: 0.01, // 1% slippage
190
+ inputTokenMint: poolInfo.mintA, // Swap from TokenA
191
+ amountIn,
192
+ });
193
+
194
+ console.log('Expected output:', quoteReturn.expectedAmountOut.toString());
195
+ console.log('Min output:', quoteReturn.minAmountOut.toString());
196
+ console.log('Execution price:', quoteReturn.executionPrice.toString());
197
+ console.log('Fee:', quoteReturn.feeAmount.toString());
198
+
199
+ // Step 2: Execute swap
200
+ const txid = await chain.swap({
201
+ poolInfo,
202
+ quoteReturn,
203
+ userAddress,
204
+ signerCallback,
205
+ });
206
+
207
+ console.log('Swap executed:', txid);
208
+ ```
209
+
210
+ #### Exact Output Swap
211
+
212
+ Specify desired output amount, get required input.
213
+
214
+ ```typescript
215
+ import BN from 'bn.js';
216
+
217
+ const poolInfo = await chain.getRawPoolInfoByPoolId(poolId);
218
+ const amountOut = new BN(1 * 10 ** poolInfo.mintDecimalsB);
219
+
220
+ // Get quote for exact output
221
+ const quoteReturn = await chain.quoteSwapExactOut({
222
+ poolInfo,
223
+ slippage: 0.01,
224
+ outputTokenMint: poolInfo.mintB, // Want to receive TokenB
225
+ amountOut,
226
+ });
227
+
228
+ console.log('Expected input:', quoteReturn.expectedAmountIn.toString());
229
+ console.log('Max input:', quoteReturn.maxAmountIn.toString());
230
+
231
+ // Execute swap
232
+ const txid = await chain.swapExactOut({
233
+ poolInfo,
234
+ quoteReturn,
235
+ userAddress,
236
+ signerCallback,
237
+ });
238
+
239
+ console.log('Swap executed:', txid);
240
+ ```
241
+
242
+ ## Utility Functions
243
+
244
+ ### Price and Tick Conversions
245
+
246
+ ```typescript
247
+ import { TickMath, SqrtPriceMath } from '@byreal-io/byreal-clmm-sdk';
248
+ import { Decimal } from 'decimal.js';
249
+
250
+ // Align price to valid tick
251
+ const priceDetails = TickMath.getTickAlignedPriceDetails(new Decimal('1.0025'), tickSpacing, decimalsA, decimalsB);
252
+ // Returns: { tick, price, sqrtPriceX64 }
253
+
254
+ // Tick to price
255
+ const price = TickMath.getPriceFromTick(tick, decimalsA, decimalsB);
256
+
257
+ // Price to tick
258
+ const tick = SqrtPriceMath.getTickFromPrice(price, decimalsA, decimalsB);
259
+
260
+ // Get position PDA from NFT mint
261
+ import { getPdaPersonalPositionAddress } from '@byreal-io/byreal-clmm-sdk';
262
+
263
+ const { publicKey: positionPda } = getPdaPersonalPositionAddress(programId, nftMint);
264
+ ```
265
+
266
+ ## Type Definitions
267
+
268
+ ### SignerCallback
269
+
270
+ Transaction signing callback for wallet integration.
271
+
272
+ ```typescript
273
+ import { Transaction } from '@solana/web3.js';
274
+
275
+ type SignerCallback = (tx: Transaction) => Promise<Transaction>;
276
+ ```
277
+
278
+ ### Common Types
279
+
280
+ ```typescript
281
+ // Position info with UI-friendly values
282
+ interface PositionInfo {
283
+ nftMint: PublicKey;
284
+ poolId: PublicKey;
285
+ uiPriceLower: string; // Human-readable lower price
286
+ uiPriceUpper: string; // Human-readable upper price
287
+ tokenA: {
288
+ address: PublicKey;
289
+ uiAmount: string; // Current liquidity amount
290
+ uiFeeAmount: string; // Accumulated fees
291
+ decimals: number;
292
+ };
293
+ tokenB: {
294
+ address: PublicKey;
295
+ uiAmount: string;
296
+ uiFeeAmount: string;
297
+ decimals: number;
298
+ };
299
+ }
300
+
301
+ // Swap quote result
302
+ interface SwapQuoteReturn {
303
+ allTrade: boolean; // Whether full amount can be traded
304
+ expectedAmountOut: BN; // Expected output amount
305
+ minAmountOut: BN; // Min output with slippage
306
+ amountIn: BN; // Input amount
307
+ feeAmount: BN; // Swap fee
308
+ executionPrice: Decimal; // Actual execution price
309
+ remainingAccounts: PublicKey[]; // Required tick array accounts
310
+ }
311
+ ```
312
+
313
+ ## Examples
314
+
315
+ More examples are available in the [examples](./examples) directory:
316
+
317
+ - Position management: `07_create_position_*.ts`, `15_add_liquidity.ts`
318
+ - Liquidity removal: `08_decrease_liquidity.ts`, `13_decrease_full_liquidity.ts`
319
+ - Fee collection: `14_collect_fees.ts`, `17_collect_all_fees.ts`
320
+ - Swapping: `21_swap_a_to_b.ts`, `22_swap_b_to_a.ts`
321
+ - APR calculations: `18_calculate_apr*.ts`
322
+
323
+ ## Development
324
+
325
+ ```bash
326
+ # Install dependencies
327
+ npm install
328
+
329
+ # Build
330
+ npm run build
331
+
332
+ # Run tests
333
+ npm test
334
+
335
+ # Run playground examples
336
+ bun run src/playgrounds/03_get_raw_pool_info.ts
337
+ ```
338
+
339
+ ## License
340
+
341
+ MIT
@@ -0,0 +1,227 @@
1
+ import { MintLayout } from '@solana/spl-token';
2
+ import { Connection, PublicKey, VersionedTransaction, TransactionInstruction } from '@solana/web3.js';
3
+ import BN from 'bn.js';
4
+ import { IPoolLayoutWithId, IPersonalPositionLayout, ITokenInfo } from '../instructions/index.js';
5
+ import { IAddLiquidityParams, IClosePositionParams, ICollectFeesParams, ICreatePoolParams, IQuoteSwapExactOutParams, IQuoteSwapExactOutReturn, ISwapExactOutParams, ICreatePositionParams, IDecreaseFullLiquidityParams, IDecreaseLiquidityParams, IInstructionReturn, ParamsWithSignerCallback, ICollectAllFeesParams, SignerCallback, IGetPositionInfoByNftMintReturn, ICalculateCreatePositionFee, IQouteSwapParams, IQouteSwapReturn, ISwapParams } from './models.js';
6
+ import { alignPriceToTickPrice, calculateApr, calculateRewardApr, calculateRangeAprs, getAmountAFromAmountB, getAmountBFromAmountA } from './utils.js';
7
+ export declare class Chain {
8
+ connection: Connection;
9
+ programId: PublicKey;
10
+ private rentFeeCache;
11
+ /**
12
+ * Constructor
13
+ * @param params.connection Solana chain connection object
14
+ * @param params.programId CLMM program ID, default is CLMM_PROGRAM_ID
15
+ */
16
+ constructor(params: {
17
+ connection: Connection;
18
+ programId?: PublicKey;
19
+ });
20
+ /**
21
+ * Get all CLMM position information for a specified account
22
+ * @param userAddress User wallet address
23
+ * @returns Promise<IPersonalPositionLayout[]> Position information list
24
+ */
25
+ getRawPositionInfoListByUserAddress(userAddress: PublicKey): Promise<IPersonalPositionLayout[]>;
26
+ /**
27
+ * Get the corresponding position information based on the NFT mint address
28
+ * @param nftMint NFT mint address
29
+ * @returns Promise<IPersonalPositionLayout | null> Position information
30
+ */
31
+ getRawPositionInfoByNftMint(nftMint: PublicKey): Promise<IPersonalPositionLayout | null>;
32
+ /**
33
+ * Get the corresponding pool information based on the pool address
34
+ * @param poolId Pool address or PublicKey
35
+ * @returns Promise<IPoolLayoutWithId> Pool information
36
+ */
37
+ getRawPoolInfoByPoolId(poolId: string | PublicKey): Promise<IPoolLayoutWithId>;
38
+ /**
39
+ * Get the corresponding token information based on the token mint address
40
+ * @param mintAddress Token mint address
41
+ * @returns Promise<...> Token information
42
+ */
43
+ getRawTokenInfoByMint(mintAddress: PublicKey): Promise<(ReturnType<typeof MintLayout.decode> & {
44
+ owner: PublicKey;
45
+ }) | null>;
46
+ /**
47
+ * Get the simplified token information (including address, precision, and programId)
48
+ * @param mintAddress Token mint address
49
+ * @returns Promise<ITokenInfo>
50
+ */
51
+ getTokenInfoByMint(mintAddress: PublicKey): Promise<ITokenInfo>;
52
+ /**
53
+ * Get the detailed position information, including price range, token amount, fee, etc.
54
+ * @param nftMint NFT mint address
55
+ * @returns Promise<{...}> Detailed position information
56
+ */
57
+ getPositionInfoByNftMint(nftMint: PublicKey): Promise<IGetPositionInfoByNftMintReturn | null>;
58
+ /**
59
+ * Create position instructions on the chain (does not directly send transactions)
60
+ * @param params Parameters required for creating a position
61
+ * @returns IInstructionReturn Contains instructions, signers, and transaction objects
62
+ */
63
+ createPositionInstructions(params: ICreatePositionParams): Promise<IInstructionReturn>;
64
+ /**
65
+ * Calculate the rent fee required for creating a position
66
+ *
67
+ * @param params Parameters required for creating a position and options
68
+ */
69
+ calculateCreatePositionFee(params: ICreatePositionParams & {
70
+ useCache?: boolean;
71
+ }): Promise<ICalculateCreatePositionFee>;
72
+ /**
73
+ * Create a new position and send a transaction
74
+ * @param params Parameters required for creating a position, including a signature callback
75
+ * @returns Promise<string> Transaction signature
76
+ */
77
+ createPosition(params: ParamsWithSignerCallback<ICreatePositionParams>): Promise<string>;
78
+ /**
79
+ * Close the specified position (only when the liquidity is 0, it can be closed)
80
+ * @param params.userAddress User wallet address
81
+ * @param params.nftMint NFT mint address
82
+ * @returns IInstructionReturn Contains instructions and transaction objects
83
+ */
84
+ closePositionInstructions(params: IClosePositionParams): Promise<IInstructionReturn>;
85
+ /**
86
+ * Close the specified position and send a transaction
87
+ * @param params.userAddress User wallet address
88
+ * @param params.nftMint NFT mint address
89
+ * @param params.signerCallback Signature callback
90
+ * @returns Promise<string> Transaction signature
91
+ */
92
+ closePosition(params: {
93
+ userAddress: PublicKey;
94
+ nftMint: PublicKey;
95
+ signerCallback: SignerCallback;
96
+ }): Promise<string>;
97
+ /**
98
+ * Partially remove position liquidity, generate chain instructions
99
+ * @param params Contains user, position, removed liquidity amount, slippage, etc.
100
+ * @returns IInstructionReturn
101
+ */
102
+ decreaseLiquidityInstructions(params: IDecreaseLiquidityParams): Promise<IInstructionReturn>;
103
+ /**
104
+ * Partially remove position liquidity and send a transaction
105
+ * @param params Contains signature callback, etc.
106
+ * @returns Promise<string> Transaction signature
107
+ */
108
+ decreaseLiquidity(params: ParamsWithSignerCallback<IDecreaseLiquidityParams>): Promise<string>;
109
+ /**
110
+ * Remove all position liquidity (optional to automatically close position)
111
+ * @param params.closePosition Whether to close position automatically
112
+ * @param params Other parameters are the same as decreaseLiquidityInstructions
113
+ * @returns IInstructionReturn
114
+ */
115
+ decreaseFullLiquidityInstructions(params: IDecreaseFullLiquidityParams): Promise<IInstructionReturn>;
116
+ /**
117
+ * Remove all position liquidity and send a transaction
118
+ * @param params Contains signature callback, etc.
119
+ * @returns Promise<string> Transaction signature
120
+ */
121
+ decreaseFullLiquidity(params: ParamsWithSignerCallback<IDecreaseFullLiquidityParams>): Promise<string>;
122
+ /**
123
+ * Collect fees for a single position (essentially removing 0 liquidity)
124
+ * @param params Contains user, position, etc.
125
+ * @returns IInstructionReturn
126
+ */
127
+ collectFeesInstructions(params: ICollectFeesParams): Promise<IInstructionReturn>;
128
+ /**
129
+ * Collect fees for all positions of a user, automatically batch to avoid exceeding transaction size limit
130
+ * @param params.userAddress User wallet address
131
+ * @param params.nftMintList NFT mint list
132
+ * @returns { instructionsList, transactions } Batch instructions and transaction objects
133
+ */
134
+ collectAllPositionFeesInstructions(params: ICollectAllFeesParams): Promise<{
135
+ instructionsList: TransactionInstruction[][];
136
+ transactions: VersionedTransaction[];
137
+ }>;
138
+ /**
139
+ * Collect fees for a single position and send a transaction
140
+ * @param params Contains signature callback, etc.
141
+ * @returns Promise<string> Transaction signature
142
+ */
143
+ collectFees(params: ParamsWithSignerCallback<ICollectFeesParams>): Promise<string>;
144
+ /**
145
+ * Add liquidity to an existing position, generate chain instructions
146
+ * @param params Contains user, position, liquidity amount, etc.
147
+ * @returns IInstructionReturn
148
+ */
149
+ addLiquidityInstructions(params: IAddLiquidityParams): Promise<IInstructionReturn>;
150
+ /**
151
+ * Add liquidity to an existing position and send a transaction
152
+ * @param params Contains signature callback, etc.
153
+ * @returns Promise<string> Transaction signature
154
+ */
155
+ addLiquidity(params: ParamsWithSignerCallback<IAddLiquidityParams>): Promise<string>;
156
+ /**
157
+ * Create pool instructions
158
+ * @param params Create pool parameters
159
+ * @returns IInstructionReturn
160
+ */
161
+ createPoolInstructions(params: ICreatePoolParams): Promise<IInstructionReturn>;
162
+ /**
163
+ * Create a new pool and send a transaction
164
+ * @param params Contains signature callback, etc.
165
+ * @returns Promise<string> Transaction signature
166
+ */
167
+ createPool(params: ParamsWithSignerCallback<ICreatePoolParams>): Promise<string>;
168
+ qouteSwap(params: IQouteSwapParams): Promise<IQouteSwapReturn>;
169
+ swapInstructions(params: ISwapParams): Promise<IInstructionReturn>;
170
+ /**
171
+ * Create swap exact out instructions
172
+ * @param params Contains pool info, quote return, and user address
173
+ * @returns IInstructionReturn
174
+ */
175
+ swapExactOutInstructions(params: {
176
+ poolInfo: IPoolLayoutWithId;
177
+ quoteReturn: IQuoteSwapExactOutReturn;
178
+ userAddress: PublicKey;
179
+ }): Promise<IInstructionReturn>;
180
+ swap(params: ParamsWithSignerCallback<ISwapParams>): Promise<string>;
181
+ /**
182
+ * Execute swap exact out transaction
183
+ * @param params Contains signature callback, etc.
184
+ * @returns Promise<string> Transaction signature
185
+ */
186
+ swapExactOut(params: ParamsWithSignerCallback<ISwapExactOutParams>): Promise<string>;
187
+ /**
188
+ * Quote swap exact output - calculate required input amount for desired output
189
+ * @param params Quote parameters including output amount and slippage
190
+ * @returns Quote result with expected input amount and other swap details
191
+ */
192
+ quoteSwapExactOut(params: IQuoteSwapExactOutParams): Promise<IQuoteSwapExactOutReturn>;
193
+ /**
194
+ * Handle SOL/WSOL packaging logic, automatically generate related instructions
195
+ *
196
+ * @param params.userAddress User wallet address
197
+ * @param params.mintA Pool tokenA mint
198
+ * @param params.mintB Pool tokenB mint
199
+ * @param params.amountA Optional, tokenA quantity
200
+ * @param params.amountB Optional, tokenB quantity
201
+ * @param params.rentExemptLamports Optional, WSOL account rent exemption lamports
202
+ * @returns tokenAccountA/B, pre-instructions, post-instructions
203
+ */
204
+ handleTokenAccount(params: {
205
+ userAddress: PublicKey;
206
+ mintA: PublicKey;
207
+ mintB: PublicKey;
208
+ amountA?: BN;
209
+ amountB?: BN;
210
+ rentExemptLamports?: number;
211
+ }): Promise<{
212
+ tokenAccountA: PublicKey;
213
+ tokenAccountB: PublicKey;
214
+ tokenProgramIdA: PublicKey;
215
+ tokenProgramIdB: PublicKey;
216
+ preInstructions: TransactionInstruction[];
217
+ endInstructions: TransactionInstruction[];
218
+ }>;
219
+ private estimateRentFee;
220
+ calculateApr: typeof calculateApr;
221
+ calculateRewardApr: typeof calculateRewardApr;
222
+ calculateRangeAprs: typeof calculateRangeAprs;
223
+ alignPriceToTickPrice: typeof alignPriceToTickPrice;
224
+ getAmountBFromAmountA: typeof getAmountBFromAmountA;
225
+ getAmountAFromAmountB: typeof getAmountAFromAmountB;
226
+ }
227
+ //# sourceMappingURL=chain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chain.d.ts","sourceRoot":"","sources":["../../../src/client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