@cetusprotocol/dlmm-zap-sdk 0.0.1

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.
package/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # @cetusprotocol/zap-sdk
2
+
3
+ The SDK provides a Zap module for specialized liquidity operations with different modes to suit various trading strategies. This module enables users to perform complex liquidity operations with flexibility in how they want to manage their positions.
4
+
5
+ ## Getting Started
6
+
7
+ ## How to Use the Zap SDK ?
8
+
9
+ ### Installation
10
+
11
+ To start using the `Zap SDK`, you first need to install it in your TypeScript project:
12
+
13
+ npm link: <https://www.npmjs.com/package/@cetusprotocol/zap-sdk>
14
+
15
+ ```bash
16
+ npm install @cetusprotocol/zap-sdk
17
+ ```
18
+
19
+ ### Setup
20
+
21
+ Import the SDK into the TypeScript file where you intend to use it:
22
+
23
+ ```typescript
24
+ import { CetusZapSDK } from '@cetusprotocol/zap-sdk'
25
+ ```
26
+
27
+ ### Initializing the SDK
28
+
29
+ Initialize the SDK with the required configuration parameters. This typically includes setting up the network and API keys, if needed.
30
+
31
+ If you would like to use the mainnet network and the official Sui rpc url, you can do so as follows:
32
+
33
+ ```typescript
34
+ const sdk = CetusZapSDK.createSDK()
35
+ ```
36
+
37
+ If you wish to set your own full node URL or network (You have the option to select either 'mainnet' or 'testnet' for the network), you can do so as follows:
38
+
39
+ ```typescript
40
+ const env = 'mainnet'
41
+ const full_rpc_url = 'YOUR_FULL_NODE_URL'
42
+ const wallet = 'YOUR_WALLET_ADDRESS'
43
+
44
+ const sdk = CetusZapSDK.createSDK({ env })
45
+ ```
46
+
47
+ If you wish to set your own full node URL or SuiClient, you can do so as follows:
48
+
49
+ ```typescript
50
+ const sdk = CetusZapSDK.createSDK({ env, sui_client })
51
+ // or
52
+ const sdk = CetusZapSDK.createSDK({ env, full_rpc_url })
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ After linking your wallet, if you need use your wallet address to do something, you should set it by `sdk.setSenderAddress`.
58
+
59
+ ```typescript
60
+ const wallet = 'YOUR_WALLET_ADDRESS'
61
+
62
+ sdk.setSenderAddress(wallet)
63
+ ```
64
+
65
+ if you need to change your rpc url, you can do so as follows:
66
+
67
+ ```typescript
68
+ const new_rpc_url = 'YOUR_NEW_FULL_NODE_URL'
69
+
70
+ sdk.updateFullRpcUrl(new_rpc_url)
71
+ ```
72
+
73
+ ### Common Parameters
74
+
75
+ - `pool_id`: The ID of the liquidity pool
76
+ - `tick_lower` & `tick_upper`: Price range boundaries for the position
77
+ - `current_sqrt_price`: Current square root price of the pool
78
+ - `slippage`: Maximum acceptable price slippage (e.g., 0.01 for 1%)
79
+ - `coin_type_a` & `coin_type_b`: Coin type identifiers for the trading pair
80
+ - `coin_decimal_a` & `coin_decimal_b`: Decimal places for each coin type
81
+
82
+ ### 1. Deposit Operations
83
+
84
+ #### Deposit Mode-Specific Parameters
85
+
86
+ 1. **FixedOneSide**
87
+
88
+ - `fixed_amount`: Fixed amount to deposit
89
+ - `fixed_coin_a`: Boolean indicating whether to fix coin A (true) or coin B (false)
90
+
91
+ 2. **FlexibleBoth** (This feature will be supported in a future release, currently a placeholder)
92
+
93
+ - `coin_amount_a`: Amount of coin A to deposit
94
+ - `coin_amount_b`: Amount of coin B to deposit
95
+
96
+ 3. **OnlyCoinA/OnlyCoinB**
97
+ - `coin_amount`: Amount of single coin to deposit
98
+
99
+ #### Deposit Usage Example
100
+
101
+ ```typescript
102
+ // Initialize SDK and get pool information
103
+ const sdk = CetusZapSDK.createSDK({ env: 'mainnet' })
104
+
105
+ const pool_id = 'YOUR_POOL_ID'
106
+ const pool = await sdk.CetusClmmSDK.Pool.getPool(pool_id)
107
+
108
+ // Pre-calculate deposit amounts (example: FixedOneSide mode)
109
+ const result = await sdk.Zap.preCalculateDepositAmount(
110
+ {
111
+ pool_id,
112
+ tick_lower,
113
+ tick_upper,
114
+ current_sqrt_price: pool.current_sqrt_price.toString(),
115
+ slippage: 0.01,
116
+ },
117
+ {
118
+ mode: 'FixedOneSide',
119
+ fixed_amount: toDecimalsAmount(1, 6).toString(),
120
+ fixed_coin_a: false,
121
+ }
122
+ )
123
+
124
+ const pos_id = 'YOUR_POSITION_ID'
125
+ // Build and send transaction
126
+ const tx = await sdk.Zap.buildDepositPayload({
127
+ deposit_obj: result,
128
+ pool_id,
129
+ coin_type_a: pool.coin_type_a,
130
+ coin_type_b: pool.coin_type_b,
131
+ tick_lower,
132
+ tick_upper,
133
+ slippage: 0.01,
134
+ pos_obj: {
135
+ // Optional: Add to existing position
136
+ pos_id,
137
+ collect_fee: false,
138
+ collect_rewarder_types: [],
139
+ },
140
+ })
141
+
142
+ // Simulate or send the transaction
143
+ const sim_result = await sdk.FullClient.sendSimulationTransaction(tx, wallet)
144
+ ```
145
+
146
+ ### 2. Withdraw Operations
147
+
148
+ Withdrawals require an existing position in the pool.
149
+
150
+ #### Withdraw Mode-Specific Parameters
151
+
152
+ 1. **FixedOneSide**
153
+
154
+ - `fixed_amount`: Fixed amount to withdraw
155
+ - `fixed_coin_a`: Boolean indicating whether to withdraw coin A (true) or coin B (false)
156
+
157
+ 2. **OnlyCoinA/OnlyCoinB**
158
+ - `burn_liquidity`: Amount of liquidity to burn
159
+ - `available_liquidity`: Total available liquidity in the position
160
+
161
+ #### Withdraw Usage Example
162
+
163
+ ```typescript
164
+ // Get pool and position information
165
+ const pool = await sdk.CetusClmmSDK.Pool.getPool(pool_id)
166
+ const position = await sdk.CetusClmmSDK.Position.getPositionById(pos_id)
167
+
168
+ if (!pool || !position) {
169
+ throw new Error('Pool or Position not found')
170
+ }
171
+
172
+ // Pre-calculate withdrawal (example: OnlyCoinA mode)
173
+ const result = await sdk.Zap.preCalculateWithdrawAmount({
174
+ mode: 'OnlyCoinA',
175
+ pool_id,
176
+ tick_lower: position.tick_lower_index,
177
+ tick_upper: position.tick_upper_index,
178
+ current_sqrt_price: pool.current_sqrt_price.toString(),
179
+ burn_liquidity: '200000',
180
+ available_liquidity: position.liquidity.toString(),
181
+ coin_type_a: pool.coin_type_a,
182
+ coin_type_b: pool.coin_type_b,
183
+ coin_decimal_a: 6,
184
+ coin_decimal_b: 9,
185
+ })
186
+
187
+ // Build and send transaction
188
+ const tx = await sdk.Zap.buildWithdrawPayload({
189
+ withdraw_obj: result,
190
+ pool_id,
191
+ pos_id,
192
+ close_pos: false, // Whether to close the position
193
+ collect_fee: true, // Whether to collect accumulated fees
194
+ collect_rewarder_types: [], // Types of rewards to collect
195
+ coin_type_a: pool.coin_type_a,
196
+ coin_type_b: pool.coin_type_b,
197
+ tick_lower: position.tick_lower_index,
198
+ tick_upper: position.tick_upper_index,
199
+ slippage: 0.01,
200
+ })
201
+
202
+ // Simulate or send the transaction
203
+ const simulate_result = await sdk.FullClient.sendSimulationTransaction(tx, wallet)
204
+ ```
205
+
206
+ ## More About Cetus
207
+
208
+ Use the following links to learn more about Cetus:
209
+
210
+ Learn more about working with Cetus in the [Cetus Documentation](https://cetus-1.gitbook.io/cetus-docs).
211
+
212
+ Join the Cetus community on [Cetus Discord](https://discord.com/channels/1009749448022315008/1009751382783447072).
213
+
214
+ ## License
215
+
216
+ MIT
@@ -0,0 +1,319 @@
1
+ import { AggregatorClient } from '@cetusprotocol/aggregator-sdk';
2
+ import { StrategyType, BinAmount, BinLiquidityInfo, CetusDlmmSDK } from '@cetusprotocol/dlmm-sdk';
3
+ import { IModule, SdkWrapper, BaseSdkOptions, BaseError } from '@cetusprotocol/common-sdk';
4
+ import { TransactionObjectArgument, Transaction } from '@mysten/sui/transactions';
5
+ import Decimal from 'decimal.js';
6
+
7
+ /**
8
+ * Represents a pair of coins used in a financial context.
9
+ */
10
+ type CoinPairType = {
11
+ /**
12
+ * The address type of the coin a in the pair.
13
+ */
14
+ coin_type_a: SuiAddressType;
15
+ /**
16
+ * The address type of the coin b in the pair.
17
+ */
18
+ coin_type_b: SuiAddressType;
19
+ };
20
+
21
+ /**
22
+ * Represents a SUI address, which is a string.
23
+ */
24
+ type SuiAddressType = string;
25
+
26
+ declare const defaultSwapSlippage = 0.005;
27
+ /**
28
+ * Result of a swap operation containing amounts and price information
29
+ */
30
+ type SwapResult = {
31
+ swap_in_amount: string;
32
+ swap_out_amount: string;
33
+ route_obj?: any;
34
+ };
35
+ type BaseDepositOptions = {
36
+ pool_id: string;
37
+ strategy_type: StrategyType;
38
+ active_bin_of_pool?: BinAmount;
39
+ lower_bin_id: number;
40
+ upper_bin_id: number;
41
+ active_id: number;
42
+ bin_step: number;
43
+ };
44
+ type OnlyCoinDepositOptions = {
45
+ fix_amount_a: boolean;
46
+ coin_amount: string;
47
+ };
48
+ /**
49
+ * Result of a deposit calculation
50
+ */
51
+ type CalculationDepositResult = {
52
+ bin_infos: BinLiquidityInfo;
53
+ swap_result?: SwapResult;
54
+ fix_amount_a: boolean;
55
+ coin_amount: string;
56
+ };
57
+ /**
58
+ * Complete options for executing a deposit
59
+ */
60
+ type DepositOptions = {
61
+ deposit_obj: CalculationDepositResult;
62
+ slippage: number;
63
+ pool_id: string;
64
+ strategy_type: StrategyType;
65
+ lower_bin_id: number;
66
+ upper_bin_id: number;
67
+ active_id: number;
68
+ bin_step: number;
69
+ swap_slippage?: number;
70
+ pos_obj?: {
71
+ pos_id: string | TransactionObjectArgument;
72
+ collect_fee: boolean;
73
+ collect_rewarder_types: string[];
74
+ };
75
+ };
76
+ type WithdrawMode = 'OnlyCoinA' | 'OnlyCoinB' | 'Both';
77
+ type CalculationWithdrawOptions = {
78
+ remove_bin_range: BinAmount[];
79
+ active_id: number;
80
+ bin_step: number;
81
+ expected_receive_amount: string;
82
+ is_receive_coin_a: boolean;
83
+ mode: WithdrawMode;
84
+ } & CoinPairType;
85
+ type CalculationWithdrawAvailableAmountOptions = {
86
+ remove_bin_range: BinAmount[];
87
+ active_id: number;
88
+ bin_step: number;
89
+ is_receive_coin_a: boolean;
90
+ mode: WithdrawMode;
91
+ };
92
+ /**
93
+ * Result of a withdrawal calculation
94
+ */
95
+ type CalculationWithdrawResult = {
96
+ remove_liquidity_info: BinLiquidityInfo;
97
+ mode: WithdrawMode;
98
+ is_receive_coin_a?: boolean;
99
+ swap_result?: SwapResult;
100
+ expected_receive_amount: string;
101
+ remove_percent: string;
102
+ };
103
+ /**
104
+ * Complete options for executing a withdrawal
105
+ */
106
+ type WithdrawOptions = {
107
+ withdraw_obj: CalculationWithdrawResult;
108
+ swap_slippage?: number;
109
+ pool_id: string;
110
+ position_id: string;
111
+ active_id: number;
112
+ bin_step: number;
113
+ slippage: number;
114
+ reward_coins: string[];
115
+ collect_fee: boolean;
116
+ remove_percent?: number;
117
+ is_close_position: boolean;
118
+ } & CoinPairType;
119
+
120
+ /**
121
+ * ZapModule handles interactions with clmm pools within the system.
122
+ */
123
+ declare class ZapModule implements IModule<CetusDlmmZapSDK> {
124
+ protected _sdk: CetusDlmmZapSDK;
125
+ constructor(sdk: CetusDlmmZapSDK);
126
+ /**
127
+ * Returns the associated SDK instance
128
+ */
129
+ get sdk(): CetusDlmmZapSDK;
130
+ private calculateBalanceSwapAmountWithoutActiveId;
131
+ private calculateBalanceSwapAmount;
132
+ /**
133
+ * Pre-calculates the deposit amount based on the selected mode.
134
+ * @param options
135
+ * @param mode_options
136
+ * @returns
137
+ */
138
+ preCalculateDepositAmount(options: BaseDepositOptions, mode_options: OnlyCoinDepositOptions): Promise<CalculationDepositResult>;
139
+ buildDepositPayload(options: DepositOptions, tx?: Transaction): Promise<Transaction>;
140
+ findRouters(from: string, target: string, amount: string): Promise<SwapResult>;
141
+ calculateZapOutAvailableAmount(options: CalculationWithdrawAvailableAmountOptions): {
142
+ available_amount: string;
143
+ user_total_amount_a: string;
144
+ user_total_amount_b: string;
145
+ active_bin: BinAmount | undefined;
146
+ is_receive_coin_a: boolean;
147
+ };
148
+ preCalculateWithdrawAmount(options: CalculationWithdrawOptions): Promise<CalculationWithdrawResult>;
149
+ buildWithdrawPayload(options: WithdrawOptions): Promise<Transaction>;
150
+ }
151
+
152
+ /**
153
+ * Represents options and configurations for an SDK.
154
+ */
155
+ interface SdkOptions extends BaseSdkOptions {
156
+ /**
157
+ * The URL of the aggregator service.
158
+ */
159
+ aggregator_url: string;
160
+ /**
161
+ * A list of aggregator providers.
162
+ */
163
+ providers: string[];
164
+ /**
165
+ * A list of Pyth price ID.
166
+ */
167
+ pyth_urls?: string[];
168
+ }
169
+ /**
170
+ * The entry class of CetusDlmmZapSDK, which is almost responsible for all interactions with dlmm zap.
171
+ */
172
+ declare class CetusDlmmZapSDK extends SdkWrapper<SdkOptions> {
173
+ /**
174
+ * Module for managing vaults.
175
+ */
176
+ protected _zapModule: ZapModule;
177
+ protected _dlmmSDK: CetusDlmmSDK;
178
+ /**
179
+ * Client for interacting with the Aggregator service.
180
+ */
181
+ protected _aggregatorClient: AggregatorClient;
182
+ constructor(options: SdkOptions, dlmmSDK?: CetusDlmmSDK);
183
+ setSenderAddress(value: string): void;
184
+ getSenderAddress(validate?: boolean): string;
185
+ /**
186
+ * Updates the providers for the AggregatorClient.
187
+ * @param providers - The new providers to set.
188
+ */
189
+ updateProviders(providers: string[]): void;
190
+ updateFullRpcUrl(url: string): void;
191
+ /**
192
+ * Getter for the DlmmSDK property.
193
+ * @returns {CetusDlmmSDK} The DlmmSDK property value.
194
+ */
195
+ get DlmmSDK(): CetusDlmmSDK;
196
+ /**
197
+ * Getter for the AggregatorClient property.
198
+ * @returns {AggregatorClient} The AggregatorClient property value.
199
+ */
200
+ get AggregatorClient(): AggregatorClient;
201
+ /**
202
+ * Getter for the ZapModule property.
203
+ * @returns {ZapModule} The ZapModule property value.
204
+ */
205
+ get Zap(): ZapModule;
206
+ /**
207
+ * Static factory method to initialize the SDK
208
+ * @param options SDK initialization options
209
+ * @param clmm_sdk Optional CLMM SDK instance
210
+ * @returns An instance of CetusZapSDK
211
+ */
212
+ static createSDK(options: BaseSdkOptions, dlmm_sdk?: any): CetusDlmmZapSDK;
213
+ /**
214
+ * Create a custom SDK instance with the given options
215
+ * @param options The options for the SDK
216
+ * @returns An instance of CetusBurnSDK
217
+ */
218
+ static createCustomSDK<T extends BaseSdkOptions>(options: T & SdkOptions, dlmm_sdk?: CetusDlmmSDK): CetusDlmmZapSDK;
219
+ }
220
+
221
+ /**
222
+ * Calculate if there is enough liquidity amount for adding liquidity to a pool
223
+ * @param amount_a - Amount of token A
224
+ * @param amount_b - Amount of token B
225
+ * @param curr_sqrt_price - Current square root price of the pool
226
+ * @param lower_tick - Lower tick boundary of the position
227
+ * @param upper_tick - Upper tick boundary of the position
228
+ * @param slippage - Slippage tolerance for the calculation
229
+ * @param fix_amount_a - Whether to fix the amount of token A
230
+ * @returns Object containing:
231
+ * - is_enough_amount: Whether there is enough amount for the other token
232
+ * - use_amount_a: Amount of token A to be used
233
+ * - use_amount_b: Amount of token B to be used
234
+ * - liquidity: Calculated liquidity amount
235
+ * - amount_limit_a: Minimum amount limit for token A
236
+ * - amount_limit_b: Minimum amount limit for token B
237
+ * - remain_amount: Remaining amount of the non-fixed token
238
+ */
239
+ declare function calculateLiquidityAmountEnough(amount_a: string, amount_b: string, curr_sqrt_price: string, lower_tick: number, upper_tick: number, slippage: number, fix_amount_a: boolean): {
240
+ is_enough_amount: boolean;
241
+ use_amount_a: string;
242
+ use_amount_b: string;
243
+ liquidity: string;
244
+ amount_limit_a: string;
245
+ amount_limit_b: string;
246
+ remain_amount: Decimal;
247
+ };
248
+ /**
249
+ * Calculate the optimal side for adding liquidity based on current price and tick range
250
+ * @param amount_a - Amount of token A
251
+ * @param amount_b - Amount of token B
252
+ * @param curr_sqrt_price - Current square root price of the pool
253
+ * @param lower_tick - Lower tick boundary of the position
254
+ * @param upper_tick - Upper tick boundary of the position
255
+ * @param slippage - Slippage tolerance for the calculation
256
+ * @param fix_amount_a - Whether to fix the amount of token A
257
+ * @returns Object containing:
258
+ * - fix_liquidity_amount_a: Whether to fix token A amount
259
+ * - is_enough_amount: Whether there is enough amount for the other token
260
+ * - use_amount_a: Amount of token A to be used
261
+ * - use_amount_b: Amount of token B to be used
262
+ * - liquidity: Calculated liquidity amount
263
+ * - amount_limit_a: Minimum amount limit for token A
264
+ * - amount_limit_b: Minimum amount limit for token B
265
+ * - remain_amount: Remaining amount of the non-fixed token
266
+ */
267
+ declare function calculateLiquidityAmountSide(amount_a: string, amount_b: string, curr_sqrt_price: string, lower_tick: number, upper_tick: number, slippage: number, fix_amount_a: boolean): {
268
+ is_enough_amount: boolean;
269
+ use_amount_a: string;
270
+ use_amount_b: string;
271
+ liquidity: string;
272
+ amount_limit_a: string;
273
+ amount_limit_b: string;
274
+ remain_amount: Decimal;
275
+ fix_liquidity_amount_a: boolean;
276
+ };
277
+ /**
278
+ * Calculate the swap amount needed to achieve target ratio
279
+ * @param coin_amount - Total coin amount available
280
+ * @param fix_amount_a - Whether to fix token A amount (true) or token B amount (false)
281
+ * @param current_price - Current price:
282
+ * - When fix_amount_a = true: current_price = B/A (price of B in terms of A)
283
+ * - When fix_amount_a = false: current_price = A/B (price of A in terms of B)
284
+ * @param target_ratio - Target ratio to achieve:
285
+ * - When fix_amount_a = true: target_ratio = B/A
286
+ * - When fix_amount_a = false: target_ratio = A/B
287
+ * @param tolerance - Tolerance for the target ratio (default: 0.01)
288
+ * @returns Object containing:
289
+ * - swap_amount: Amount to swap
290
+ * - final_amount_a: Final amount of token A (remaining A when fix_amount_a=true, obtained A when fix_amount_a=false)
291
+ * - final_amount_b: Final amount of token B (obtained B when fix_amount_a=true, remaining B when fix_amount_a=false)
292
+ */
293
+ declare function calcExactSwapAmount(coin_amount: string, fix_amount_a: boolean, current_price: string, target_ratio: string): {
294
+ swap_amount: string;
295
+ final_amount_a: string;
296
+ final_amount_b: string;
297
+ };
298
+
299
+ declare const zapMainnet: SdkOptions;
300
+
301
+ declare const zapTestnet: SdkOptions;
302
+
303
+ declare enum ZapErrorCode {
304
+ UnsupportedDepositMode = "UnsupportedDepositMode",
305
+ PositionIdUndefined = "PositionIdUndefined",
306
+ ParameterError = "ParameterError",
307
+ ReachMaxIterations = "ReachMaxIterations",
308
+ BestLiquidityIsZero = "BestLiquidityIsZero",
309
+ SwapAmountError = "SwapAmountError",
310
+ AggregatorError = "AggregatorError"
311
+ }
312
+ declare class ZapError extends BaseError {
313
+ constructor(message: string, errorCode?: ZapErrorCode, details?: Record<string, any>);
314
+ static isZapErrorCode(e: any, code: ZapErrorCode): boolean;
315
+ }
316
+ declare const handleError: (code: ZapErrorCode, error: Error, details?: Record<string, any>) => never;
317
+ declare const handleMessageError: (code: ZapErrorCode, message: string, details?: Record<string, any>) => never;
318
+
319
+ export { type BaseDepositOptions, type CalculationDepositResult, type CalculationWithdrawAvailableAmountOptions, type CalculationWithdrawOptions, type CalculationWithdrawResult, CetusDlmmZapSDK, type DepositOptions, type OnlyCoinDepositOptions, type SdkOptions, type SwapResult, type WithdrawMode, type WithdrawOptions, ZapError, ZapErrorCode, ZapModule, calcExactSwapAmount, calculateLiquidityAmountEnough, calculateLiquidityAmountSide, CetusDlmmZapSDK as default, defaultSwapSlippage, handleError, handleMessageError, zapMainnet, zapTestnet };