@gala-chain/launchpad-sdk 3.31.0 → 4.0.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 (115) hide show
  1. package/API.md +524 -4
  2. package/CHANGELOG.md +92 -0
  3. package/EXAMPLES.md +845 -0
  4. package/README.md +421 -14
  5. package/dist/LaunchpadSDK.d.ts +435 -18
  6. package/dist/LaunchpadSDK.d.ts.map +1 -1
  7. package/dist/api/LaunchpadAPI.d.ts.map +1 -1
  8. package/dist/api/dto/TransferTokenDto.d.ts.map +1 -1
  9. package/dist/constants/version.generated.d.ts +1 -1
  10. package/dist/constants/version.generated.d.ts.map +1 -1
  11. package/dist/helpers/sdk.d.ts +1 -0
  12. package/dist/helpers/sdk.d.ts.map +1 -1
  13. package/dist/index.cjs.js +1 -1
  14. package/dist/index.d.ts +10 -3
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.esm.js +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/services/BaseService.d.ts +32 -3
  19. package/dist/services/BaseService.d.ts.map +1 -1
  20. package/dist/services/BundleService.d.ts.map +1 -1
  21. package/dist/services/CommentService.d.ts.map +1 -1
  22. package/dist/services/DexBackendClient.d.ts +46 -0
  23. package/dist/services/DexBackendClient.d.ts.map +1 -0
  24. package/dist/services/DexPoolService.d.ts +54 -12
  25. package/dist/services/DexPoolService.d.ts.map +1 -1
  26. package/dist/services/DexQuoteService.d.ts +288 -0
  27. package/dist/services/DexQuoteService.d.ts.map +1 -0
  28. package/dist/services/DexService.d.ts.map +1 -1
  29. package/dist/services/FaucetService.d.ts.map +1 -1
  30. package/dist/services/GSwapService.d.ts +519 -44
  31. package/dist/services/GSwapService.d.ts.map +1 -1
  32. package/dist/services/GalaChainGatewayClient.d.ts +89 -0
  33. package/dist/services/GalaChainGatewayClient.d.ts.map +1 -0
  34. package/dist/services/GalaChainService.d.ts +26 -0
  35. package/dist/services/GalaChainService.d.ts.map +1 -1
  36. package/dist/services/ImageService.d.ts.map +1 -1
  37. package/dist/services/PoolService.d.ts.map +1 -1
  38. package/dist/services/PoolStateManager.d.ts +176 -0
  39. package/dist/services/PoolStateManager.d.ts.map +1 -0
  40. package/dist/services/PriceHistoryService.d.ts +4 -5
  41. package/dist/services/PriceHistoryService.d.ts.map +1 -1
  42. package/dist/services/SignatureService.d.ts +15 -38
  43. package/dist/services/SignatureService.d.ts.map +1 -1
  44. package/dist/services/TokenClassKeyService.d.ts +3 -4
  45. package/dist/services/TokenClassKeyService.d.ts.map +1 -1
  46. package/dist/services/TokenMetadataCache.d.ts +2 -2
  47. package/dist/services/TokenMetadataCache.d.ts.map +1 -1
  48. package/dist/services/TokenMetadataService.d.ts +3 -3
  49. package/dist/services/TokenMetadataService.d.ts.map +1 -1
  50. package/dist/services/TokenResolverService.d.ts +2 -2
  51. package/dist/services/TokenResolverService.d.ts.map +1 -1
  52. package/dist/services/TradeService.d.ts.map +1 -1
  53. package/dist/services/UserService.d.ts.map +1 -1
  54. package/dist/services/WebSocketService.d.ts +100 -2
  55. package/dist/services/WebSocketService.d.ts.map +1 -1
  56. package/dist/services/__mocks__/logger.mock.d.ts +17 -0
  57. package/dist/services/__mocks__/logger.mock.d.ts.map +1 -0
  58. package/dist/types/common.d.ts +2 -0
  59. package/dist/types/common.d.ts.map +1 -1
  60. package/dist/types/composite-pool.dto.d.ts +103 -0
  61. package/dist/types/composite-pool.dto.d.ts.map +1 -0
  62. package/dist/types/dex-pool.dto.d.ts +56 -5
  63. package/dist/types/dex-pool.dto.d.ts.map +1 -1
  64. package/dist/types/dto.d.ts +6 -6
  65. package/dist/types/dto.d.ts.map +1 -1
  66. package/dist/types/eip712-types.d.ts +140 -0
  67. package/dist/types/eip712-types.d.ts.map +1 -0
  68. package/dist/types/galachain-api.types.d.ts +206 -0
  69. package/dist/types/galachain-api.types.d.ts.map +1 -0
  70. package/dist/types/gswap-responses.types.d.ts +366 -0
  71. package/dist/types/gswap-responses.types.d.ts.map +1 -0
  72. package/dist/types/gswap.dto.d.ts +58 -3
  73. package/dist/types/gswap.dto.d.ts.map +1 -1
  74. package/dist/types/launchpad.dto.d.ts +57 -0
  75. package/dist/types/launchpad.dto.d.ts.map +1 -1
  76. package/dist/types/pool-state-delta.dto.d.ts +246 -0
  77. package/dist/types/pool-state-delta.dto.d.ts.map +1 -0
  78. package/dist/types/pool-state-manager-config.dto.d.ts +103 -0
  79. package/dist/types/pool-state-manager-config.dto.d.ts.map +1 -0
  80. package/dist/utils/SignatureHelper.d.ts.map +1 -1
  81. package/dist/utils/auto-pagination.d.ts +206 -0
  82. package/dist/utils/auto-pagination.d.ts.map +1 -0
  83. package/dist/utils/bignumber-helpers.d.ts +336 -0
  84. package/dist/utils/bignumber-helpers.d.ts.map +1 -0
  85. package/dist/utils/bignumber-pool-cache.d.ts +169 -0
  86. package/dist/utils/bignumber-pool-cache.d.ts.map +1 -0
  87. package/dist/utils/composite-pool-converter.d.ts +121 -0
  88. package/dist/utils/composite-pool-converter.d.ts.map +1 -0
  89. package/dist/utils/errors.d.ts +86 -0
  90. package/dist/utils/errors.d.ts.map +1 -1
  91. package/dist/utils/http.d.ts.map +1 -1
  92. package/dist/utils/load-env.d.ts +31 -0
  93. package/dist/utils/load-env.d.ts.map +1 -0
  94. package/dist/utils/pool-pair-parser.d.ts +55 -0
  95. package/dist/utils/pool-pair-parser.d.ts.map +1 -0
  96. package/dist/utils/pool-state-validator.d.ts +207 -0
  97. package/dist/utils/pool-state-validator.d.ts.map +1 -0
  98. package/dist/utils/position-filters.d.ts +253 -0
  99. package/dist/utils/position-filters.d.ts.map +1 -0
  100. package/dist/utils/swap-delta-calculator.d.ts +231 -0
  101. package/dist/utils/swap-delta-calculator.d.ts.map +1 -0
  102. package/dist/utils/tick-crossing-handler.d.ts +250 -0
  103. package/dist/utils/tick-crossing-handler.d.ts.map +1 -0
  104. package/dist/utils/token-format-converter.d.ts +85 -6
  105. package/dist/utils/token-format-converter.d.ts.map +1 -1
  106. package/dist/utils/token-parser.d.ts +235 -0
  107. package/dist/utils/token-parser.d.ts.map +1 -0
  108. package/dist/utils/tokenNormalizer.d.ts +66 -0
  109. package/dist/utils/tokenNormalizer.d.ts.map +1 -1
  110. package/dist/utils/transfer-validation.d.ts.map +1 -1
  111. package/dist/utils/validation-helpers.d.ts +75 -0
  112. package/dist/utils/validation-helpers.d.ts.map +1 -1
  113. package/package.json +36 -15
  114. package/dist/utils/tokenFormatConverter.d.ts +0 -53
  115. package/dist/utils/tokenFormatConverter.d.ts.map +0 -1
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Auto-Pagination Utility
3
+ *
4
+ * Generic utility for automatically paginating through API results.
5
+ * Eliminates duplicate pagination logic across multiple services.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ import { Logger } from './Logger';
10
+ /**
11
+ * Result object from paginated API calls
12
+ * Expected structure for services using this utility
13
+ */
14
+ export interface PaginatedResult<T> {
15
+ /** Array of items returned from this page */
16
+ items: T[];
17
+ /** Current page number */
18
+ page: number;
19
+ /** Page size/limit for this request */
20
+ limit: number;
21
+ /** Total count of all items across all pages */
22
+ total: number;
23
+ /** Total number of pages available */
24
+ totalPages: number;
25
+ /** Whether there is a next page available */
26
+ hasNext: boolean;
27
+ /** Whether there is a previous page available */
28
+ hasPrevious: boolean;
29
+ }
30
+ /**
31
+ * Options for auto-pagination
32
+ */
33
+ export interface AutoPaginationOptions {
34
+ /** Maximum number of pages to fetch (safety limit to prevent infinite loops) */
35
+ maxPages?: number;
36
+ /** Logger instance for debug output */
37
+ logger?: Logger;
38
+ /** Page size to use for each request */
39
+ pageSize?: number;
40
+ }
41
+ /**
42
+ * Result object from auto-pagination
43
+ */
44
+ export interface AutoPaginationResult<T> {
45
+ /** All items from all pages combined */
46
+ items: T[];
47
+ /** Total count from the API (across all pages) */
48
+ total: number;
49
+ }
50
+ /**
51
+ * Generic auto-pagination handler
52
+ *
53
+ * Automatically iterates through all pages of paginated API results
54
+ * and combines them into a single array. Handles common patterns like:
55
+ * - Safety limits to prevent infinite loops
56
+ * - Empty result detection
57
+ * - Debug logging of pagination progress
58
+ * - Preserves total count from the API
59
+ *
60
+ * @typeParam T - Type of items being paginated
61
+ * @param fetchFn Function that fetches a single page of results
62
+ * @param options Pagination options (maxPages, logger, pageSize)
63
+ * @returns Promise<AutoPaginationResult> All items and total count from the API
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * const result = await autoPaginate(
68
+ * (page, limit) => service.fetchPools({ page, limit }),
69
+ * { maxPages: 1000, pageSize: 20, logger }
70
+ * );
71
+ * console.log(`Total: ${result.total}, Fetched: ${result.items.length}`);
72
+ * ```
73
+ *
74
+ * @since 3.32.0
75
+ */
76
+ export declare function autoPaginate<T>(fetchFn: (page: number, limit: number) => Promise<PaginatedResult<T>>, options?: AutoPaginationOptions): Promise<AutoPaginationResult<T>>;
77
+ /**
78
+ * Result object from bookmark-based API calls
79
+ * Returned by fetchFn in autoPaginateWithBookmark
80
+ */
81
+ export interface BookmarkPaginationResult<T> {
82
+ /** Array of items returned from this page */
83
+ items: T[];
84
+ /** Bookmark/cursor for fetching the next page
85
+ * - undefined: field was not present in API response
86
+ * - empty string "": API signals last page reached
87
+ * - non-empty string: bookmark to use for next request
88
+ */
89
+ nextBookmark: string | undefined;
90
+ }
91
+ /**
92
+ * Options for bookmark-based auto-pagination
93
+ * Used for APIs that use cursor-based pagination (bookmarks) instead of page numbers
94
+ */
95
+ export interface AutoPaginationWithBookmarkOptions {
96
+ /** Maximum number of pages to fetch (safety limit to prevent infinite loops) */
97
+ maxPages?: number;
98
+ /** Logger instance for debug output */
99
+ logger?: Logger;
100
+ /** Page size to use for each request */
101
+ pageSize?: number;
102
+ }
103
+ /**
104
+ * Bookmark-based auto-pagination handler
105
+ *
106
+ * Automatically iterates through all pages of bookmark-based paginated API results
107
+ * (cursor-based pagination) and combines them into a single array.
108
+ *
109
+ * Used for APIs that return bookmarks/cursors instead of page numbers (e.g., GSwap positions API).
110
+ * Handles common patterns like:
111
+ * - Safety limits to prevent infinite loops
112
+ * - Empty result detection
113
+ * - Debug logging of pagination progress
114
+ * - Proper bookmark extraction from API responses
115
+ * - Dual completion detection (no nextBookmark OR fewer items than requested)
116
+ *
117
+ * @typeParam T - Type of items being paginated
118
+ * @param fetchFn Function that fetches a single page and returns items with optional nextBookmark.
119
+ * Should return { items: T[], nextBookmark?: string }.
120
+ * If bookmark is undefined, fetches first page.
121
+ * @param options Pagination options (maxPages, logger, pageSize)
122
+ * @returns Promise<AutoPaginationResult> All items combined from all pages
123
+ *
124
+ * @example Basic usage with bookmark-returning API
125
+ * ```typescript
126
+ * const result = await autoPaginateWithBookmark(
127
+ * async (bookmark, pageSize) => {
128
+ * const response = await api.getPositions({ bookmark, limit: pageSize });
129
+ * return {
130
+ * items: response.positions,
131
+ * nextBookmark: response.metadata?.nextBookmark
132
+ * };
133
+ * },
134
+ * { maxPages: 1000, pageSize: 10, logger }
135
+ * );
136
+ * console.log(`Total fetched: ${result.items.length}`);
137
+ * ```
138
+ *
139
+ * @example Legacy: Returns items array directly (uses item count for completion)
140
+ * ```typescript
141
+ * const result = await autoPaginateWithBookmark(
142
+ * (bookmark, pageSize) => service.getPositions(walletAddress, pageSize, bookmark),
143
+ * { maxPages: 1000, pageSize: 10, logger }
144
+ * );
145
+ * ```
146
+ *
147
+ * @since 3.32.0
148
+ * @since 3.33.0 - Enhanced to support true bookmark-based pagination with BookmarkPaginationResult<T>
149
+ */
150
+ export declare function autoPaginateWithBookmark<T>(fetchFn: (bookmark: string | undefined, pageSize: number) => Promise<BookmarkPaginationResult<T> | T[]>, options?: AutoPaginationWithBookmarkOptions): Promise<AutoPaginationResult<T>>;
151
+ /**
152
+ * Build paginated result object for returning combined auto-paginated data
153
+ *
154
+ * Helper function to construct the standard paginated result structure
155
+ * when returning combined results from auto-pagination. Supports custom item
156
+ * key naming for service-specific result structures (pools, snapshots, etc.).
157
+ *
158
+ * Eliminates 5-7 line response object construction patterns found in:
159
+ * - DexPoolService.fetchAllDexPools() (lines 209-219)
160
+ * - PriceHistoryService.fetchAllPriceHistory() (lines 433-442)
161
+ * - Other services with similar patterns
162
+ *
163
+ * @typeParam T - Type of items in the result
164
+ * @param items Combined array of all items from all pages
165
+ * @param total Total count from last page (or sum of counts)
166
+ * @param itemsKey Optional field name for items (default: 'items'). Use for service-specific naming like 'pools', 'snapshots', 'comments'
167
+ * @returns PaginatedResult object with items flattened into a single "page"
168
+ *
169
+ * @example Basic usage (default 'items' key)
170
+ * ```typescript
171
+ * const allItems = await autoPaginate(fetchFn);
172
+ * return buildPaginatedResult(allItems.items, allItems.total);
173
+ * // Returns: { items, page: 1, limit, total, totalPages: 1, hasNext: false, hasPrevious: false }
174
+ * ```
175
+ *
176
+ * @example With custom items key (eliminates manual response construction)
177
+ * ```typescript
178
+ * // DexPoolService - before (7 lines)
179
+ * const result = buildPaginatedResult(paginationResult.items, paginationResult.total);
180
+ * return {
181
+ * pools: result.items,
182
+ * page: result.page,
183
+ * limit: result.limit,
184
+ * total: result.total,
185
+ * totalPages: result.totalPages,
186
+ * hasNext: result.hasNext,
187
+ * hasPrevious: result.hasPrevious,
188
+ * };
189
+ *
190
+ * // DexPoolService - after (1 line)
191
+ * return buildPaginatedResult(paginationResult.items, paginationResult.total, 'pools');
192
+ * ```
193
+ *
194
+ * @example Other service patterns
195
+ * ```typescript
196
+ * // PriceHistoryService
197
+ * return buildPaginatedResult(paginationResult.items, paginationResult.total, 'snapshots');
198
+ *
199
+ * // CommentService
200
+ * return buildPaginatedResult(allComments, totalCount, 'comments');
201
+ * ```
202
+ *
203
+ * @since 3.32.0 - itemsKey parameter added in 3.32.0 for response structure flexibility
204
+ */
205
+ export declare function buildPaginatedResult<T>(items: T[], total?: number, itemsKey?: 'items' | 'pools' | 'snapshots' | 'comments' | string): Record<string, any>;
206
+ //# sourceMappingURL=auto-pagination.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-pagination.d.ts","sourceRoot":"","sources":["../../src/utils/auto-pagination.ts"],"names":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ED;;;GAGG;AACH,MAAM,WAAW,iCAAiC;IAChD,gFAAgF;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uCAAuC;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wCAAwC;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAsB,wBAAwB,CAAC,CAAC,EAC9C,OAAO,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,wBAAwB,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EACvG,OAAO,GAAE,iCAAsC,GAC9C,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAqHlC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EACpC,KAAK,EAAE,CAAC,EAAE,EACV,KAAK,GAAE,MAAqB,EAC5B,QAAQ,GAAE,OAAO,GAAG,OAAO,GAAG,WAAW,GAAG,UAAU,GAAG,MAAgB,GACxE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAerB"}
@@ -0,0 +1,336 @@
1
+ /**
2
+ * BigNumber utility helpers for common calculations
3
+ *
4
+ * Consolidates repeated BigNumber patterns and operations to reduce
5
+ * code duplication across services, particularly in GSwapService.
6
+ *
7
+ * Common patterns extracted:
8
+ * - Slippage factor calculation
9
+ * - Min/max output calculation with slippage
10
+ * - Tick to sqrt ratio conversion (1.0001^(tick/2))
11
+ * - Price inversion
12
+ * - Safe BigNumber creation
13
+ *
14
+ * @internal
15
+ */
16
+ import BigNumber from 'bignumber.js';
17
+ /**
18
+ * Create a BigNumber from a numeric value with safe defaults
19
+ *
20
+ * @param value The value to convert
21
+ * @param defaultValue Value to use if input is null/undefined/zero-length string (default: "0")
22
+ * @returns BigNumber instance
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * const balance = toBigNumber(userData.balance || 0);
27
+ * const amount = toBigNumber(params.amount); // Uses "0" if undefined
28
+ * ```
29
+ */
30
+ export declare function toBigNumber(value: string | number | BigNumber | null | undefined, defaultValue?: string | number): BigNumber;
31
+ /**
32
+ * Create a BigNumber and immediately call toFixed()
33
+ *
34
+ * Convenience method for the pattern: `new BigNumber(value).toFixed()`
35
+ * Used for serializing calculated amounts back to strings.
36
+ *
37
+ * @param value The value to convert
38
+ * @param decimals Number of decimal places (default: undefined = max precision)
39
+ * @returns Fixed string representation
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const minOutput = toBigNumberFixed(calculated, 6); // "123.456789"
44
+ * const slippageAdjusted = toBigNumberFixed(amount.multipliedBy(0.99));
45
+ * ```
46
+ */
47
+ export declare function toBigNumberFixed(value: string | number | BigNumber | null | undefined, decimals?: number): string;
48
+ /**
49
+ * Calculate slippage-adjusted minimum output
50
+ *
51
+ * Consolidates the pattern:
52
+ * ```typescript
53
+ * const slippageFactor = new BigNumber(1).minus(slippageTolerance);
54
+ * const minOutput = estimatedOutput.multipliedBy(slippageFactor);
55
+ * ```
56
+ *
57
+ * @param estimatedOutput The estimated output amount
58
+ * @param slippageTolerance Slippage tolerance as decimal (e.g., 0.01 for 1%)
59
+ * @returns Minimum acceptable output after slippage
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const quote = await sdk.getSwapQuote('GALA', 'GUSDC', '100');
64
+ * const minOutput = calculateSlippageAdjustedAmount(
65
+ * quote.estimatedOutput,
66
+ * 0.01 // 1% slippage
67
+ * );
68
+ * await sdk.executeSwap(..., minOutput.toFixed());
69
+ * ```
70
+ */
71
+ export declare function calculateSlippageAdjustedAmount(estimatedOutput: string | number | BigNumber, slippageTolerance?: number): BigNumber;
72
+ /**
73
+ * Calculate slippage factor (1 - tolerance)
74
+ *
75
+ * Consolidates: `new BigNumber(1).minus(tolerance)`
76
+ * Used as multiplier for slippage calculations.
77
+ *
78
+ * @param tolerance Slippage tolerance as decimal (e.g., 0.01 for 1%)
79
+ * @returns Slippage factor (e.g., 0.99 for 1% tolerance)
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const factor = calculateSlippageFactor(0.01); // BigNumber(0.99)
84
+ * const minAmount = estimatedAmount.multipliedBy(factor);
85
+ * ```
86
+ */
87
+ export declare function calculateSlippageFactor(tolerance?: number): BigNumber;
88
+ /**
89
+ * Convert tick to sqrt ratio for liquidity calculations
90
+ *
91
+ * Re-exports tickToSqrtPrice from @gala-chain/dex for Uniswap V3 liquidity calculations.
92
+ * Maintained as a wrapper for backward compatibility.
93
+ *
94
+ * @param tick The tick value from the pool
95
+ * @returns Sqrt price in Q64.96 format
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const lowerSqrtRatio = tickToSqrtRatio(tickLower);
100
+ * const upperSqrtRatio = tickToSqrtRatio(tickUpper);
101
+ * const liquidityNeeded = calculateLiquidity(lowerSqrtRatio, upperSqrtRatio, ...);
102
+ * ```
103
+ *
104
+ * @deprecated This is a wrapper around @gala-chain/dex's tickToSqrtPrice.
105
+ * Consider importing tickToSqrtPrice directly for new code.
106
+ */
107
+ export declare function tickToSqrtRatio(tick: number): BigNumber;
108
+ /**
109
+ * Convert a price to tick (Uniswap V3 math)
110
+ *
111
+ * Calculates the tick index from a price using production-grade @gala-chain/dex math.
112
+ * Formula: tick = log_1.0001(price)
113
+ *
114
+ * @param price The price value to convert to a tick
115
+ * @returns Tick index (can be negative or positive)
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * const tick = priceToTick('1.5'); // Convert price 1.5 to tick
120
+ * const tickFloor = Math.floor(priceToTick('0.99')); // Round down for tickLower
121
+ * const tickCeil = Math.ceil(priceToTick('1.01')); // Round up for tickUpper
122
+ * ```
123
+ */
124
+ export declare function priceToTick(price: string | number | BigNumber): number;
125
+ /**
126
+ * Invert a price (calculate 1 / price)
127
+ *
128
+ * Consolidates: `new BigNumber(1).dividedBy(price)`
129
+ * Used for converting price direction (e.g., BTC/USD → USD/BTC).
130
+ *
131
+ * @param price The price to invert
132
+ * @param asFixed Whether to return as fixed string (default: false returns BigNumber)
133
+ * @returns Inverted price as BigNumber or string
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * const galuPrice = invertPrice('0.50'); // 2.0
138
+ * const displayPrice = invertPrice(price, true); // "2.0" (string)
139
+ * ```
140
+ */
141
+ export declare function invertPrice(price: string | number | BigNumber, asFixed?: boolean): BigNumber | string;
142
+ /**
143
+ * Q96 constant for Uniswap V3 calculations (2^96)
144
+ *
145
+ * Consolidates: `new BigNumber(2).pow(96)`
146
+ * Used in tick-based liquidity calculations.
147
+ *
148
+ * @returns Q96 value as BigNumber
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * const Q96 = getQ96Constant(); // 2^96
153
+ * const adjustedPrice = sqrtPrice.multipliedBy(sqrtPrice).dividedBy(Q96);
154
+ * ```
155
+ */
156
+ export declare function getQ96Constant(): BigNumber;
157
+ /**
158
+ * Find minimum of two BigNumber values
159
+ *
160
+ * Convenience wrapper for `BigNumber.min()` with safe input handling.
161
+ *
162
+ * @param a First value
163
+ * @param b Second value
164
+ * @returns The minimum value as BigNumber
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * const liquidity0 = calculateFromAmount0(...);
169
+ * const liquidity1 = calculateFromAmount1(...);
170
+ * const optimalLiquidity = minBigNumber(liquidity0, liquidity1);
171
+ * ```
172
+ */
173
+ export declare function minBigNumber(a: string | number | BigNumber, b: string | number | BigNumber): BigNumber;
174
+ /**
175
+ * Find maximum of two BigNumber values
176
+ *
177
+ * Convenience wrapper for `BigNumber.max()` with safe input handling.
178
+ *
179
+ * @param a First value
180
+ * @param b Second value
181
+ * @returns The maximum value as BigNumber
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * const amount0 = parseFloat(poolData.amount0);
186
+ * const amount1 = parseFloat(poolData.amount1);
187
+ * const maxAmount = maxBigNumber(amount0, amount1);
188
+ * ```
189
+ */
190
+ export declare function maxBigNumber(a: string | number | BigNumber, b: string | number | BigNumber): BigNumber;
191
+ /**
192
+ * Check if a value is zero
193
+ *
194
+ * Safe check for zero with BigNumber precision.
195
+ *
196
+ * @param value The value to check
197
+ * @returns true if value equals 0
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * if (isZero(amount)) {
202
+ * throw new Error('Amount cannot be zero');
203
+ * }
204
+ * ```
205
+ */
206
+ export declare function isZero(value: string | number | BigNumber): boolean;
207
+ /**
208
+ * Check if a value is positive
209
+ *
210
+ * @param value The value to check
211
+ * @returns true if value > 0
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * if (isPositive(balance)) {
216
+ * // user has funds
217
+ * }
218
+ * ```
219
+ */
220
+ export declare function isPositive(value: string | number | BigNumber): boolean;
221
+ /**
222
+ * Check if a value is negative
223
+ *
224
+ * @param value The value to check
225
+ * @returns true if value < 0
226
+ */
227
+ export declare function isNegative(value: string | number | BigNumber): boolean;
228
+ /**
229
+ * Check if value is between two bounds (inclusive)
230
+ *
231
+ * @param value The value to check
232
+ * @param min Lower bound (inclusive)
233
+ * @param max Upper bound (inclusive)
234
+ * @returns true if min <= value <= max
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * if (isBetween(price, minPrice, maxPrice)) {
239
+ * // price is in valid range
240
+ * }
241
+ * ```
242
+ */
243
+ export declare function isBetween(value: string | number | BigNumber, min: string | number | BigNumber, max: string | number | BigNumber): boolean;
244
+ /**
245
+ * Calculate percentage of a value
246
+ *
247
+ * @param value The base value
248
+ * @param percentage The percentage to calculate (e.g., 10 for 10%)
249
+ * @returns The percentage amount
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * const fee = calculatePercentage(amount, 0.3); // 0.3% fee
254
+ * const netAmount = amount.minus(fee);
255
+ * ```
256
+ */
257
+ export declare function calculatePercentage(value: string | number | BigNumber, percentage: number): BigNumber;
258
+ /**
259
+ * Increase a value by a percentage
260
+ *
261
+ * @param value The base value
262
+ * @param percentage The percentage to increase (e.g., 10 for 10% increase)
263
+ * @returns The increased value
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * const withSlippage = increaseByPercentage(amount, 1); // 1% increase
268
+ * ```
269
+ */
270
+ export declare function increaseByPercentage(value: string | number | BigNumber, percentage: number): BigNumber;
271
+ /**
272
+ * Decrease a value by a percentage
273
+ *
274
+ * @param value The base value
275
+ * @param percentage The percentage to decrease (e.g., 1 for 1% decrease)
276
+ * @returns The decreased value
277
+ *
278
+ * @example
279
+ * ```typescript
280
+ * const afterSlippage = decreaseByPercentage(amount, 1); // 1% decrease
281
+ * ```
282
+ */
283
+ export declare function decreaseByPercentage(value: string | number | BigNumber, percentage: number): BigNumber;
284
+ /**
285
+ * Validates that BigNumber values are strictly positive (> 0).
286
+ *
287
+ * Throws an error if any value is zero or negative. Provides clear error messages
288
+ * with parameter indices for debugging.
289
+ *
290
+ * @param values The values to validate
291
+ * @throws Error if any value is not positive
292
+ *
293
+ * @example
294
+ * ```typescript
295
+ * requirePositive(liquidity, amountIn); // Throws if either is <= 0
296
+ * requirePositive(amount); // Single value validation
297
+ * ```
298
+ */
299
+ export declare function requirePositive(...values: BigNumber[]): void;
300
+ /**
301
+ * Validates that BigNumber values are non-negative (>= 0).
302
+ *
303
+ * Throws an error if any value is negative. Allows zero values, unlike requirePositive.
304
+ * Useful for optional amounts that default to zero.
305
+ *
306
+ * @param values The values to validate
307
+ * @throws Error if any value is negative
308
+ *
309
+ * @example
310
+ * ```typescript
311
+ * requireNonNegative(fees, collectedFees); // Allows zero but not negative
312
+ * ```
313
+ */
314
+ export declare function requireNonNegative(...values: BigNumber[]): void;
315
+ /**
316
+ * Validates a BigNumber with a custom parameter name and optional context.
317
+ *
318
+ * Provides descriptive error messages for better debugging in specific use cases.
319
+ * Throws an error if value is not positive (> 0).
320
+ *
321
+ * @param value The value to validate
322
+ * @param paramName The parameter name for the error message
323
+ * @param context Optional additional context (e.g., "for swap operation")
324
+ * @throws Error with descriptive message if value is not positive
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * requirePositiveWithContext(amount, 'amountIn', 'for swap');
329
+ * // Throws: "amountIn must be positive for swap, got: 0"
330
+ *
331
+ * requirePositiveWithContext(liquidity, 'liquidity');
332
+ * // Throws: "liquidity must be positive, got: -1"
333
+ * ```
334
+ */
335
+ export declare function requirePositiveWithContext(value: BigNumber, paramName: string, context?: string): void;
336
+ //# sourceMappingURL=bignumber-helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bignumber-helpers.d.ts","sourceRoot":"","sources":["../../src/utils/bignumber-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,SAAS,MAAM,cAAc,CAAC;AAGrC;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,SAAS,EACrD,YAAY,GAAE,MAAM,GAAG,MAAY,GAClC,SAAS,CAKX;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,SAAS,EACrD,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,CAER;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EAC5C,iBAAiB,GAAE,MAAa,GAC/B,SAAS,CAIX;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,GAAE,MAAa,GAAG,SAAS,CAE3E;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAGvD;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,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