@gala-chain/gswap-sdk 0.0.0-preview

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.
@@ -0,0 +1,921 @@
1
+ import BigNumber from 'bignumber.js';
2
+ import { EventEmitter } from 'events';
3
+
4
+ type Branding<BrandT> = {
5
+ _type: BrandT;
6
+ };
7
+ type Brand<T, BrandT> = T & Branding<BrandT>;
8
+
9
+ type NumericAmount = string | number | BigNumber;
10
+ type SqrtPrice = Brand<BigNumber, 'SqrtPrice'>;
11
+ type SqrtPriceIn = Brand<NumericAmount, 'SqrtPriceIn'> | SqrtPrice;
12
+ type Price = Brand<BigNumber, 'Price'>;
13
+ type PriceIn = Brand<NumericAmount, 'PriceIn'> | Price;
14
+
15
+ interface GalaChainTokenClassKey {
16
+ collection: string;
17
+ category: string;
18
+ type: string;
19
+ additionalKey: string;
20
+ }
21
+
22
+ /**
23
+ * Result from getting a price quote for a token swap.
24
+ * Contains pricing information and impact analysis for the proposed trade.
25
+ */
26
+ interface GetQuoteResult {
27
+ /** Raw amount of token0 that would be involved in the swap (ordered by token address) */
28
+ amount0: BigNumber;
29
+ /** Raw amount of token1 that would be involved in the swap (ordered by token address) */
30
+ amount1: BigNumber;
31
+ /** Current square root price of the pool before the trade */
32
+ currentPoolSqrtPrice: SqrtPrice;
33
+ /** New square root price of the pool after the trade would execute */
34
+ newPoolSqrtPrice: SqrtPrice;
35
+ /** Amount of the input token (the token being sold) */
36
+ inTokenAmount: BigNumber;
37
+ /** Amount of the output token (the token being bought) */
38
+ outTokenAmount: BigNumber;
39
+ /** Current price of the pool (how many output tokens per input token) */
40
+ currentPrice: Price;
41
+ /** New price of the pool after the trade (how many output tokens per input token) */
42
+ newPrice: Price;
43
+ /** Price impact of the trade as a percentage (e.g., 0.05 for 0.05% impact) */
44
+ priceImpact: BigNumber;
45
+ /** Fee tier of the pool used for this quote (e.g., 500 for 0.05%, 3000 for 0.3%) */
46
+ feeTier: number;
47
+ }
48
+ /**
49
+ * Result from getting all liquidity positions for a user.
50
+ * Contains summary information about each position owned by the wallet.
51
+ */
52
+ interface GetUserPositionsResult {
53
+ /** Unique hash identifier for the liquidity pool */
54
+ poolHash: string;
55
+ /** Unique identifier for this specific liquidity position */
56
+ positionId: string;
57
+ /** Token class key for the first token in the pair */
58
+ token0ClassKey: GalaChainTokenClassKey;
59
+ /** Token class key for the second token in the pair */
60
+ token1ClassKey: GalaChainTokenClassKey;
61
+ /** URL or path to the image/icon for token0 */
62
+ token0Img: string;
63
+ /** URL or path to the image/icon for token1 */
64
+ token1Img: string;
65
+ /** Symbol/ticker for token0 (e.g., "GALA") */
66
+ token0Symbol: string;
67
+ /** Symbol/ticker for token1 (e.g., "USDC") */
68
+ token1Symbol: string;
69
+ /** Fee tier of the pool (e.g., 500 for 0.05%, 3000 for 0.3%) */
70
+ fee: number;
71
+ /** Amount of liquidity provided in this position */
72
+ liquidity: BigNumber;
73
+ /** Lower tick boundary of the position's price range */
74
+ tickLower: number;
75
+ /** Upper tick boundary of the position's price range */
76
+ tickUpper: number;
77
+ /** Timestamp when the position was created */
78
+ createdAt: string;
79
+ }
80
+ /**
81
+ * Result from getting detailed information about a specific liquidity position.
82
+ * Contains comprehensive data about position state, fees, and token information.
83
+ */
84
+ interface GetPositionResult {
85
+ /** Fee tier of the pool (e.g., 500 for 0.05%, 3000 for 0.3%) */
86
+ fee: number;
87
+ /** Fee growth inside the position's tick range for token0 since position creation */
88
+ feeGrowthInside0Last: BigNumber;
89
+ /** Fee growth inside the position's tick range for token1 since position creation */
90
+ feeGrowthInside1Last: BigNumber;
91
+ /** Amount of liquidity provided in this position */
92
+ liquidity: BigNumber;
93
+ /** Unique hash identifier for the liquidity pool */
94
+ poolHash: string;
95
+ /** Unique identifier for this specific liquidity position */
96
+ positionId: string;
97
+ /** Lower tick boundary of the position's price range */
98
+ tickLower: number;
99
+ /** Upper tick boundary of the position's price range */
100
+ tickUpper: number;
101
+ /** Token class key for the first token in the pair (ordered by token address) */
102
+ token0ClassKey: GalaChainTokenClassKey;
103
+ /** Token class key for the second token in the pair (ordered by token address) */
104
+ token1ClassKey: GalaChainTokenClassKey;
105
+ /** Amount of token0 fees accumulated and owed to the position owner */
106
+ tokensOwed0: BigNumber;
107
+ /** Amount of token1 fees accumulated and owed to the position owner */
108
+ tokensOwed1: BigNumber;
109
+ }
110
+ /**
111
+ * Represents a single asset (token) in a user's wallet.
112
+ * Contains token metadata and balance information.
113
+ */
114
+ interface UserAsset {
115
+ /** URL to the token's icon/image */
116
+ image: string;
117
+ /** Human-readable name of the token */
118
+ name: string;
119
+ /** Number of decimal places this token uses */
120
+ decimals: number;
121
+ /** Whether this token has been verified/approved */
122
+ verify: boolean;
123
+ /** Trading symbol for the token */
124
+ symbol: string;
125
+ /** User's balance of this token as a decimal string */
126
+ quantity: string;
127
+ }
128
+ /**
129
+ * Result from getting a user's asset balances.
130
+ * Contains paginated list of tokens and their balances.
131
+ */
132
+ interface GetUserAssetsResult {
133
+ /** Array of tokens owned by the user */
134
+ tokens: UserAsset[];
135
+ /** Total number of different tokens the user owns */
136
+ count: number;
137
+ }
138
+
139
+ type FetchReturnValue = Awaited<ReturnType<typeof fetch>>;
140
+ interface HTTPResponse {
141
+ ok: FetchReturnValue['ok'];
142
+ status: FetchReturnValue['status'];
143
+ json: FetchReturnValue['json'];
144
+ text: FetchReturnValue['text'];
145
+ }
146
+ type HttpRequestor = (uri: string, options?: Parameters<typeof fetch>[1]) => Promise<HTTPResponse>;
147
+
148
+ declare class HttpClient {
149
+ private readonly httpRequestor;
150
+ constructor(httpRequestor?: HttpRequestor);
151
+ private sendRequest;
152
+ sendPostRequest<TReturnType>(baseUrl: string, basePath: string, endpoint: string, body: unknown): Promise<TReturnType>;
153
+ sendGetRequest<TReturnType>(baseUrl: string, basePath: string, endpoint: string, params?: Record<string, string>): Promise<TReturnType>;
154
+ }
155
+
156
+ /**
157
+ * Service for handling user asset operations.
158
+ * Provides functionality to retrieve user token balances and asset information.
159
+ */
160
+ declare class Assets {
161
+ private readonly dexBackendBaseUrl;
162
+ private readonly httpClient;
163
+ constructor(dexBackendBaseUrl: string, httpClient: HttpClient);
164
+ /**
165
+ * Gets all token assets owned by a user with their balances.
166
+ * @param ownerAddress - The wallet address to get assets for.
167
+ * @param page - Page number for pagination (default: 1).
168
+ * @param limit - Maximum number of assets to return per page (default: 10).
169
+ * @returns User assets including token information and balances.
170
+ * @example
171
+ * ```typescript
172
+ * const assets = await assetsService.getUserAssets('eth|123...abc', 1, 20);
173
+ * console.log(`User has ${assets.count} different tokens`);
174
+ * assets.tokens.forEach(token => {
175
+ * console.log(`${token.symbol}: ${token.quantity}`);
176
+ * });
177
+ * ```
178
+ */
179
+ getUserAssets(ownerAddress: string, page?: number, limit?: number): Promise<GetUserAssetsResult>;
180
+ }
181
+
182
+ /**
183
+ * @hideconstructor
184
+ * Represents a pending blockchain transaction.
185
+ *
186
+ * Usage: Call `wait()` immediately after receiving the PendingTransaction
187
+ * to ensure proper event handling:
188
+ *```typescript
189
+ * const pendingTx = await gSwap.swap(...);
190
+ * const result = await pendingTx.wait(); // Call immediately - if you delay then the event may be missed
191
+ *```
192
+ */
193
+ declare class PendingTransaction {
194
+ readonly transactionId: string;
195
+ readonly message: string;
196
+ readonly error: boolean;
197
+ private readonly waitDelegate;
198
+ constructor(transactionId: string, message: string, error: boolean, waitDelegate: () => Promise<void>);
199
+ /**
200
+ * Waits for the transaction to be confirmed.
201
+ * This should be called immediately after receiving the PendingTransaction
202
+ * to ensure proper event handling. If you delay calling this method and the
203
+ * transaction confirms before you call this method, an error will be thrown.
204
+ *
205
+ * @returns A promise that resolves when the transaction is confirmed.
206
+ */
207
+ wait(): Promise<void>;
208
+ }
209
+
210
+ /**
211
+ * A transaction signing interface. See {@link PrivateKeySigner} and {@link GalaWalletSigner} for implementations.
212
+ */
213
+ interface GalaChainSigner {
214
+ signObject: <TObjectType extends Record<string, unknown>>(methodName: string, object: TObjectType) => Promise<TObjectType & {
215
+ signature: string;
216
+ }>;
217
+ }
218
+ /**
219
+ * A signing implementation that uses a private key string to sign requests.
220
+ */
221
+ declare class PrivateKeySigner implements GalaChainSigner {
222
+ private readonly keyBuffer;
223
+ constructor(privateKey: string);
224
+ signObject<TObjectType extends Record<string, unknown>>(_methodName: string, obj: TObjectType): Promise<TObjectType & {
225
+ signature: string;
226
+ }>;
227
+ }
228
+ /**
229
+ * A signing implementation that uses Gala Wallet to sign requests.
230
+ */
231
+ declare class GalaWalletSigner implements GalaChainSigner {
232
+ readonly walletAddress: string;
233
+ constructor(walletAddress: string);
234
+ signObject<TObjectType extends Record<string, unknown>>(methodName: string, obj: TObjectType): Promise<TObjectType & {
235
+ signature: string;
236
+ }>;
237
+ private static generateEIP712Types;
238
+ }
239
+
240
+ declare class Bundler {
241
+ private readonly bundlerBaseUrl;
242
+ private readonly bundlingAPIBasePath;
243
+ private readonly transactionWaitTimeoutMs;
244
+ private readonly signer;
245
+ private readonly httpClient;
246
+ constructor(bundlerBaseUrl: string, bundlingAPIBasePath: string, transactionWaitTimeoutMs: number, signer: GalaChainSigner | undefined, httpClient: HttpClient);
247
+ signObject<TInputType extends Record<string, unknown>>(methodName: string, toSign: TInputType): Promise<TInputType & {
248
+ signature: string;
249
+ }>;
250
+ sendBundlerRequest(method: string, body: Record<string, unknown>, stringsInstructions: string[]): Promise<PendingTransaction>;
251
+ hasSigner(): boolean;
252
+ }
253
+
254
+ interface BundlerResponse {
255
+ status: 'PROCESSED' | 'FAILED' | 'PENDING';
256
+ data?: string;
257
+ error?: string;
258
+ }
259
+ interface BundlerRequest {
260
+ data: string;
261
+ message: string;
262
+ error: boolean;
263
+ }
264
+ declare abstract class TradeEventEmitter extends EventEmitter {
265
+ abstract connect(): Promise<void>;
266
+ abstract disconnect(): void;
267
+ abstract isConnected(): boolean;
268
+ }
269
+ declare class EventSocketClient extends TradeEventEmitter {
270
+ private socket;
271
+ private readonly bundlerUrl;
272
+ constructor(bundlerUrl: string);
273
+ connect(): Promise<void>;
274
+ disconnect(): void;
275
+ isConnected(): boolean;
276
+ }
277
+
278
+ /**
279
+ * Service for handling real-time event streaming and socket connections.
280
+ * Manages the global socket connection for transaction status updates.
281
+ */
282
+ declare class Events {
283
+ private globalSocketClient?;
284
+ private globalWaitHelper;
285
+ private connectionPromise?;
286
+ static readonly instance: Events;
287
+ static tradeEventEmitterConstructor: new (url: string) => TradeEventEmitter;
288
+ /**
289
+ * Establishes a global socket connection for real-time event streaming.
290
+ * This connection is shared across all service instances.
291
+ * @param bundlerBaseUrl - Optional bundler base URL. If not provided, uses default.
292
+ * @returns The connected EventSocketClient.
293
+ * @example
294
+ * ```typescript
295
+ * await eventsService.connectEventSocket();
296
+ *
297
+ * // Socket is now available for transaction updates
298
+ * ```
299
+ */
300
+ connectEventSocket(bundlerBaseUrl?: string): Promise<TradeEventEmitter>;
301
+ /**
302
+ * Disconnects the global socket connection and cleans up resources.
303
+ */
304
+ disconnectEventSocket(): void;
305
+ /**
306
+ * Checks if the global socket connection is active.
307
+ * @returns True if connected, false otherwise.
308
+ */
309
+ eventSocketConnected(): boolean;
310
+ /**
311
+ * Registers a transaction ID for waiting and timeout handling.
312
+ * @param txId - The transaction ID to register.
313
+ * @param timeoutMs - Timeout in milliseconds.
314
+ */
315
+ registerTxId(txId: string, timeoutMs: number): void;
316
+ /**
317
+ * Waits for a transaction to complete.
318
+ * @param txId - The transaction ID to wait for.
319
+ * @returns Promise that resolves when the transaction completes.
320
+ */
321
+ wait(txId: string): Promise<void>;
322
+ /**
323
+ * Internal handler for socket messages.
324
+ * @param response - The bundler response.
325
+ * @param txId - The transaction ID.
326
+ */
327
+ private internalHandleSocketMessage;
328
+ }
329
+
330
+ interface QuoteExactAmountRawResponse {
331
+ amount0: string;
332
+ amount1: string;
333
+ currentSqrtPrice: string;
334
+ newSqrtPrice: string;
335
+ }
336
+ interface QuoteExactAmountResponse {
337
+ amount0: BigNumber;
338
+ amount1: BigNumber;
339
+ currentSqrtPrice: SqrtPrice;
340
+ newSqrtPrice: SqrtPrice;
341
+ }
342
+ interface GetPoolDataRawResponse {
343
+ bitmap: Record<string, string>;
344
+ fee: number;
345
+ feeGrowthGlobal0: string;
346
+ feeGrowthGlobal1: string;
347
+ grossPoolLiquidity: string;
348
+ liquidity: string;
349
+ maxLiquidityPerTick: string;
350
+ protocolFees: number;
351
+ protocolFeesToken0: string;
352
+ protocolFeesToken1: string;
353
+ sqrtPrice: string;
354
+ tickSpacing: number;
355
+ token0: string;
356
+ token0ClassKey: {
357
+ additionalKey: string;
358
+ category: string;
359
+ collection: string;
360
+ type: string;
361
+ };
362
+ token1: string;
363
+ token1ClassKey: {
364
+ additionalKey: string;
365
+ category: string;
366
+ collection: string;
367
+ type: string;
368
+ };
369
+ }
370
+ interface GetPoolDataResponse {
371
+ bitmap: Record<string, string>;
372
+ fee: number;
373
+ feeGrowthGlobal0: BigNumber;
374
+ feeGrowthGlobal1: BigNumber;
375
+ grossPoolLiquidity: BigNumber;
376
+ liquidity: BigNumber;
377
+ maxLiquidityPerTick: BigNumber;
378
+ protocolFees: number;
379
+ protocolFeesToken0: BigNumber;
380
+ protocolFeesToken1: BigNumber;
381
+ sqrtPrice: SqrtPrice;
382
+ tickSpacing: number;
383
+ token0: string;
384
+ token0ClassKey: {
385
+ additionalKey: string;
386
+ category: string;
387
+ collection: string;
388
+ type: string;
389
+ };
390
+ token1: string;
391
+ token1ClassKey: {
392
+ additionalKey: string;
393
+ category: string;
394
+ collection: string;
395
+ type: string;
396
+ };
397
+ }
398
+ interface TransactionPendingResponse {
399
+ data: string;
400
+ message: string;
401
+ error: boolean;
402
+ }
403
+
404
+ declare class Pools {
405
+ private readonly gatewayBaseUrl;
406
+ private readonly dexContractBasePath;
407
+ private readonly httpClient;
408
+ constructor(gatewayBaseUrl: string, dexContractBasePath: string, httpClient: HttpClient);
409
+ /**
410
+ * Gets pool data for a specific token pair and fee tier.
411
+ */
412
+ getPoolData(token0: GalaChainTokenClassKey | string, token1: GalaChainTokenClassKey | string, fee: number): Promise<GetPoolDataResponse>;
413
+ /**
414
+ * Calculates the nearest valid tick value for a given price.
415
+ */
416
+ calculateTicksForPrice(price: PriceIn, tickSpacing: number): number;
417
+ calculatePriceForTicks(tick: number): Price;
418
+ /**
419
+ * Calculates the current spot price of a pool based on sqrt price.
420
+ * Price is defined as the amount of outToken you would receive for 1 inToken.
421
+ */
422
+ calculateSpotPrice(inToken: GalaChainTokenClassKey | string, outToken: GalaChainTokenClassKey | string, poolSqrtPrice: SqrtPriceIn): BigNumber;
423
+ }
424
+
425
+ /**
426
+ * Fee tiers for pools.
427
+ */
428
+ declare enum FEE_TIER {
429
+ /** 0.05% fee tier */
430
+ PERCENT_00_05 = 500,
431
+ /** 0.3% fee tier */
432
+ PERCENT_00_30 = 3000,
433
+ /** 1.0% fee tier */
434
+ PERCENT_01_00 = 10000
435
+ }
436
+
437
+ /**
438
+ * Handles position management operations for liquidity positions.
439
+ */
440
+ declare class Positions {
441
+ private readonly gatewayBaseUrl;
442
+ private readonly dexContractBasePath;
443
+ private readonly options?;
444
+ private readonly httpClient;
445
+ private readonly bundlerService;
446
+ private readonly poolService;
447
+ constructor(gatewayBaseUrl: string, dexContractBasePath: string, bundlerService: Bundler, poolService: Pools, httpClient: HttpClient, options?: {
448
+ walletAddress?: string | undefined;
449
+ } | undefined);
450
+ /**
451
+ * Get all liquidity positions for a specific wallet address.
452
+ * @param ownerAddress - The wallet address to get positions for.
453
+ * @param limit - Maximum number of positions to return.
454
+ * @param bookmark - Pagination bookmark for retrieving additional results. If you call this function and it returns a bookmark that is not an empty string, you can pass that bookmark as this parameter in a subsequent call to fetch the next page.
455
+ * @returns User positions and pagination bookmark
456
+ * @example
457
+ * ```typescript
458
+ * const positions = await gSwap.positions.getUserPositions('eth|123...abc');
459
+ * console.log(positions);
460
+ * ```
461
+ */
462
+ getUserPositions(ownerAddress: string, limit?: number, bookmark?: string): Promise<{
463
+ bookmark: string;
464
+ positions: GetUserPositionsResult[];
465
+ }>;
466
+ /**
467
+ * Gets detailed information about a specific liquidity position.
468
+ * @param ownerAddress - The wallet address that owns the position.
469
+ * @param position - Position parameters including tokens, fee, and tick range.
470
+ * @param position.token0ClassKey - The first token in the position.
471
+ * @param position.token1ClassKey - The second token in the position.
472
+ * @param position.fee - The pool fee tier.
473
+ * @param position.tickLower - The lower tick of the position range.
474
+ * @param position.tickUpper - The upper tick of the position range.
475
+ * @returns Detailed position information.
476
+ * @example
477
+ * ```typescript
478
+ * const position = await gSwap.positions.getPosition('eth|123...abc', {
479
+ * token0ClassKey: 'GALA|Unit|none|none',
480
+ * token1ClassKey: 'GUSDC|Unit|none|none',
481
+ * fee: 500,
482
+ * tickLower: -6000,
483
+ * tickUpper: 6000
484
+ * });
485
+ * console.log('Position:', position);
486
+ * ```
487
+ */
488
+ getPosition(ownerAddress: string, position: {
489
+ token0ClassKey: GalaChainTokenClassKey | string;
490
+ token1ClassKey: GalaChainTokenClassKey | string;
491
+ fee: number;
492
+ tickLower: number;
493
+ tickUpper: number;
494
+ }): Promise<GetPositionResult>;
495
+ /**
496
+ * Gets detailed information about a liquidity position by its ID.
497
+ * @param ownerAddress - The wallet address that owns the position.
498
+ * @param positionId - The unique identifier of the position.
499
+ * @returns Detailed position information, or undefined if not found.
500
+ * @example
501
+ * ```typescript
502
+ * const position = await gSwap.positions.getPositionById('eth|123...abc', 'position-uuid-123');
503
+ * if (position) {
504
+ * console.log('Position found:', position);
505
+ * } else {
506
+ * console.log('Position not found');
507
+ * }
508
+ * ```
509
+ */
510
+ getPositionById(ownerAddress: string, positionId: string): Promise<GetPositionResult | undefined>;
511
+ /**
512
+ * Creates a new position or adds liquidity to a position, using a specific tick range. Consider using `addLiquidityByPrice()` instead unless you want to use ticks directly.
513
+ * @param args - Parameters for adding liquidity.
514
+ * @param args.walletAddress - The wallet address adding liquidity.
515
+ * @param args.positionId - The position identifier. If you're creating a new position, this should be an empty string.
516
+ * @param args.token0 - The first token in the pair.
517
+ * @param args.token1 - The second token in the pair.
518
+ * @param args.fee - The pool fee tier.
519
+ * @param args.tickLower - The lower tick of the position range.
520
+ * @param args.tickUpper - The upper tick of the position range.
521
+ * @param args.amount0Desired - Desired (also maximum) amount of token0 to add.
522
+ * @param args.amount1Desired - Desired (also maximum) amount of token1 to add.
523
+ * @param args.amount0Min - Minimum amount of token0 to add (slippage protection).
524
+ * @param args.amount1Min - Minimum amount of token1 to add (slippage protection).
525
+ * @returns Pending transaction.
526
+ * @example
527
+ * ```typescript
528
+ * const result = await gSwap.positions.addLiquidityByTicks({
529
+ * walletAddress: 'eth|123...abc',
530
+ * positionId: '',
531
+ * token0: 'GALA|Unit|none|none',
532
+ * token1: 'GUSDC|Unit|none|none',
533
+ * fee: 500,
534
+ * tickSpacing: 10,
535
+ * tickLower: -6000,
536
+ * tickUpper: 6000,
537
+ * amount0Desired: '100',
538
+ * amount1Desired: '50',
539
+ * amount0Min: '95',
540
+ * amount1Min: '47.5'
541
+ * });
542
+ * console.log('Liquidity added:', result);
543
+ * ```
544
+ */
545
+ addLiquidityByTicks(args: {
546
+ walletAddress?: string;
547
+ positionId: string;
548
+ token0: GalaChainTokenClassKey | string;
549
+ token1: GalaChainTokenClassKey | string;
550
+ fee: FEE_TIER;
551
+ tickLower: number;
552
+ tickUpper: number;
553
+ amount0Desired: NumericAmount;
554
+ amount1Desired: NumericAmount;
555
+ amount0Min: NumericAmount;
556
+ amount1Min: NumericAmount;
557
+ }): Promise<PendingTransaction>;
558
+ /**
559
+ * Creates a new position or adds liquidity to a position, using a specified price range. Note that this method automatically converts your minPrice and maxPrice to ticks, rounding down if necessary.
560
+ * @param args - Parameters for adding liquidity.
561
+ * @param args.walletAddress - The wallet address adding liquidity.
562
+ * @param args.positionId - The position identifier. This should be an empty string if you are creating a new position.
563
+ * @param args.token0 - The first token in the pair.
564
+ * @param args.token1 - The second token in the pair.
565
+ * @param args.fee - The pool fee tier.
566
+ * @param args.tickSpacing - The tick spacing for the pool.
567
+ * @param args.minPrice - The minimum price for the position range.
568
+ * @param args.maxPrice - The maximum price for the position range.
569
+ * @param args.amount0Desired - Desired (also maximum) amount of token0 to add.
570
+ * @param args.amount1Desired - Desired (also maximum) amount of token1 to add.
571
+ * @param args.amount0Min - Minimum amount of token0 to add (slippage protection).
572
+ * @param args.amount1Min - Minimum amount of token1 to add (slippage protection).
573
+ * @returns Pending transaction.
574
+ * @example
575
+ * ```typescript
576
+ * const result = await gSwap.positions.addLiquidityByPrice({
577
+ * walletAddress: 'eth|123...abc',
578
+ * positionId: '',
579
+ * token0: 'GALA|Unit|none|none',
580
+ * token1: 'GUSDC|Unit|none|none',
581
+ * fee: 500,
582
+ * tickSpacing: 10,
583
+ * minPrice: '0.45',
584
+ * maxPrice: '0.55',
585
+ * amount0Desired: '100',
586
+ * amount1Desired: '50',
587
+ * amount0Min: '95',
588
+ * amount1Min: '47.5'
589
+ * });
590
+ * console.log('Liquidity added with price range:', result);
591
+ * ```
592
+ */
593
+ addLiquidityByPrice(args: {
594
+ walletAddress?: string;
595
+ positionId: string;
596
+ token0: GalaChainTokenClassKey | string;
597
+ token1: GalaChainTokenClassKey | string;
598
+ fee: number;
599
+ tickSpacing: number;
600
+ minPrice: PriceIn;
601
+ maxPrice: PriceIn;
602
+ amount0Desired: NumericAmount;
603
+ amount1Desired: NumericAmount;
604
+ amount0Min: NumericAmount;
605
+ amount1Min: NumericAmount;
606
+ }): Promise<PendingTransaction>;
607
+ /**
608
+ * Removes liquidity from a position.
609
+ * @param args - Parameters for removing liquidity.
610
+ * @param args.walletAddress - The wallet address removing liquidity.
611
+ * @param args.positionId - The position identifier.
612
+ * @param args.token0 - The first token in the pair.
613
+ * @param args.token1 - The second token in the pair.
614
+ * @param args.fee - The pool fee tier.
615
+ * @param args.tickLower - The lower tick of the position range.
616
+ * @param args.tickUpper - The upper tick of the position range.
617
+ * @param args.amount - The amount of liquidity to remove.
618
+ * @param args.amount0Min - Minimum amount of token0 to receive (slippage protection, optional).
619
+ * @param args.amount1Min - Minimum amount of token1 to receive (slippage protection, optional).
620
+ * @returns Pending transaction.
621
+ * @example
622
+ * ```typescript
623
+ * // Remove 50% of liquidity from a position
624
+ * const result = await gSwap.positions.removeLiquidity({
625
+ * walletAddress: 'eth|123...abc',
626
+ * positionId: 'position-123',
627
+ * token0: 'GALA|Unit|none|none',
628
+ * token1: 'GUSDC|Unit|none|none',
629
+ * fee: 500,
630
+ * tickLower: -6000,
631
+ * tickUpper: 6000,
632
+ * amount: '50000000000000000000', // 50% of position liquidity
633
+ * amount0Min: '45',
634
+ * amount1Min: '22'
635
+ * });
636
+ * console.log('Liquidity removed:', result);
637
+ * ```
638
+ */
639
+ removeLiquidity(args: {
640
+ walletAddress?: string;
641
+ positionId: string;
642
+ token0: GalaChainTokenClassKey | string;
643
+ token1: GalaChainTokenClassKey | string;
644
+ fee: number;
645
+ tickLower: number;
646
+ tickUpper: number;
647
+ amount: NumericAmount;
648
+ amount0Min?: NumericAmount;
649
+ amount1Min?: NumericAmount;
650
+ }): Promise<PendingTransaction>;
651
+ /**
652
+ * Collects accumulated fees from a liquidity position.
653
+ * @param args - Parameters for collecting fees.
654
+ * @param args.walletAddress - The wallet address collecting fees.
655
+ * @param args.positionId - The position identifier.
656
+ * @param args.token0 - The first token in the pair.
657
+ * @param args.token1 - The second token in the pair.
658
+ * @param args.fee - The pool fee tier.
659
+ * @param args.tickLower - The lower tick of the position range.
660
+ * @param args.tickUpper - The upper tick of the position range.
661
+ * @param args.amount0Requested - Desired amount of token0 fees to collect.
662
+ * @param args.amount1Requested - Desired amount of token1 fees to collect.
663
+ * @returns Pending transaction.
664
+ * @example
665
+ * ```typescript
666
+ * // Collect all accumulated fees from a position
667
+ * const result = await gSwap.positions.collectPositionFees({
668
+ * walletAddress: 'eth|123...abc',
669
+ * positionId: 'position-123',
670
+ * token0: 'GALA|Unit|none|none',
671
+ * token1: 'GUSDC|Unit|none|none',
672
+ * fee: 500,
673
+ * tickLower: -6000,
674
+ * tickUpper: 6000,
675
+ * amount0Requested: '1000000000000000000', // Max fees available
676
+ * amount1Requested: '500000000' // Max fees available
677
+ * });
678
+ * console.log('Fees collected:', result);
679
+ * ```
680
+ */
681
+ collectPositionFees(args: {
682
+ walletAddress?: string;
683
+ positionId: string;
684
+ token0: GalaChainTokenClassKey | string;
685
+ token1: GalaChainTokenClassKey | string;
686
+ fee: number;
687
+ tickLower: number;
688
+ tickUpper: number;
689
+ amount0Requested: NumericAmount;
690
+ amount1Requested: NumericAmount;
691
+ }): Promise<PendingTransaction>;
692
+ calculateOptimalPositionSize(tokenAmount: NumericAmount, spotPrice: NumericAmount, lowerPrice: NumericAmount, upperPrice: NumericAmount, tokenDecimals: number, otherTokenDecimals: number): BigNumber;
693
+ private sendUserPositionsRequest;
694
+ private sendPositionRequest;
695
+ }
696
+
697
+ /**
698
+ * Handles quote operations for token swaps.
699
+ */
700
+ declare class Quoting {
701
+ private readonly gatewayBaseUrl;
702
+ private readonly dexContractBasePath;
703
+ private readonly httpClient;
704
+ constructor(gatewayBaseUrl: string, dexContractBasePath: string, httpClient?: HttpClient);
705
+ /**
706
+ * Gets a quote for an exact amount of token being sold.
707
+ * @param tokenIn - The input token to sell.
708
+ * @param tokenOut - The output token to buy.
709
+ * @param amountIn - The exact amount of input tokens you want to sell.
710
+ * @param fee - The pool fee tier. If not specified, will check all available fee tiers and return the best quote.
711
+ * @returns The expected number of tokens you will receive (buy) when/if you execute the swap.
712
+ */
713
+ quoteExactInput(tokenIn: GalaChainTokenClassKey | string, tokenOut: GalaChainTokenClassKey | string, amountIn: NumericAmount, fee?: FEE_TIER): Promise<GetQuoteResult>;
714
+ /**
715
+ * Gets a quote for an exact amount of tokens being bought.
716
+ * @param tokenIn - The input token sell.
717
+ * @param tokenOut - The output token to buy.
718
+ * @param amountOut - The exact amount of output tokens you want to buy.
719
+ * @param fee - The pool fee tier. If not specified, will check all available fee tiers and return the best quote.
720
+ * @returns The expected number of tokens you will need to sell (input) to receive the specified amount of output tokens.
721
+ */
722
+ quoteExactOutput(tokenIn: GalaChainTokenClassKey | string, tokenOut: GalaChainTokenClassKey | string, amountOut: string | number | BigNumber, fee?: FEE_TIER): Promise<GetQuoteResult>;
723
+ private getSingleQuote;
724
+ private getSingleQuoteExactInput;
725
+ private getSingleQuoteExactOutput;
726
+ private sendQuoteRequest;
727
+ }
728
+
729
+ /**
730
+ * Service for handling token swap operations.
731
+ */
732
+ declare class Swaps {
733
+ private readonly bundlerService;
734
+ private readonly options?;
735
+ constructor(bundlerService: Bundler, options?: {
736
+ walletAddress?: string | undefined;
737
+ } | undefined);
738
+ /**
739
+ * Executes a token swap transaction.
740
+ * @param walletAddress - The wallet address executing the swap.
741
+ * @param tokenIn - The input token to sell.
742
+ * @param tokenOut - The output token to buy.
743
+ * @param fee - The pool fee tier.
744
+ * @param amount - Swap parameters specifying either exact input or exact output.
745
+ * @param amount.exactIn - For exact input swaps, the exact amount of input tokens to sell.
746
+ * @param amount.amountOutMinimum - For exact input swaps, the minimum amount of output tokens to buy (slippage protection).
747
+ * @param amount.exactOut - For exact output swaps, the exact amount of output tokens to buy.
748
+ * @param amount.amountInMaximum - For exact output swaps, the maximum amount of input tokens to sell (slippage protection).
749
+ * @returns Pending transaction.
750
+ * @example
751
+ * ```typescript
752
+ * // Exact input swap: sell 100 GALA for USDC
753
+ * const result = await swapsService.swap(
754
+ * 'GALA|Unit|none|none',
755
+ * 'GUSDC|Unit|none|none',
756
+ * 500,
757
+ * { exactIn: '100', amountOutMinimum: '45' },
758
+ * 'eth|123...abc', // your wallet address
759
+ * );
760
+ * console.log('Swap successful:', result);
761
+ * ```
762
+ */
763
+ swap(tokenIn: GalaChainTokenClassKey | string, tokenOut: GalaChainTokenClassKey | string, fee: number, amount: {
764
+ exactIn: NumericAmount;
765
+ amountOutMinimum?: NumericAmount;
766
+ } | {
767
+ exactOut: NumericAmount;
768
+ amountInMaximum?: NumericAmount;
769
+ }, walletAddress?: string): Promise<PendingTransaction>;
770
+ }
771
+
772
+ /**
773
+ * Main class for interacting with the gSwap decentralized exchange.
774
+ * Provides methods for trading, liquidity management, and position handling.
775
+ */
776
+ declare class GSwap {
777
+ readonly gatewayBaseUrl: string;
778
+ readonly dexContractBasePath: string;
779
+ readonly tokenContractBasePath: string;
780
+ readonly bundlerBaseUrl: string;
781
+ readonly bundlingAPIBasePath: string;
782
+ readonly dexBackendBaseUrl: string;
783
+ readonly transactionWaitTimeoutMs: number;
784
+ readonly signer?: GalaChainSigner | undefined;
785
+ /**
786
+ * Quoting functionality for price discovery and trade estimation.
787
+ * Use this to get quotes for token swaps without executing transactions.
788
+ *
789
+ * @example
790
+ * ```typescript
791
+ * // Get the best quote across all fee tiers
792
+ * const quote = await gSwap.quoting.quoteExactInput(tokenA, tokenB, amount);
793
+ * ```
794
+ */
795
+ readonly quoting: Quoting;
796
+ /**
797
+ * Position management operations for liquidity positions.
798
+ * Use this to manage liquidity positions including creation, modification, and fee collection.
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * // Get all user positions
803
+ * const positions = await gSwap.positions.getUserPositions('eth|123...abc');
804
+ *
805
+ * // Add liquidity to a position using price range
806
+ * const result = await gSwap.positions.addLiquidityByPrice({
807
+ * walletAddress: 'eth|123...abc',
808
+ * positionId: '',
809
+ * token0: 'GALA|Unit|none|none',
810
+ * token1: 'GUSDC|Unit|none|none',
811
+ * fee: 500,
812
+ * tickSpacing: 10,
813
+ * minPrice: '0.45',
814
+ * maxPrice: '0.55',
815
+ * amount0Desired: '100',
816
+ * amount1Desired: '50',
817
+ * amount0Min: '95',
818
+ * amount1Min: '47.5'
819
+ * });
820
+ * ```
821
+ */
822
+ readonly positions: Positions;
823
+ /**
824
+ * Token swap operations for trading tokens.
825
+ * Use this to execute token swaps on the DEX.
826
+ *
827
+ * @example
828
+ * ```typescript
829
+ * // Execute an exact input swap: sell 100 GALA for USDC
830
+ * const result = await gSwap.swaps.swap(
831
+ * 'GALA|Unit|none|none',
832
+ * 'GUSDC|Unit|none|none',
833
+ * 500,
834
+ * { exactIn: '100', amountOutMinimum: '45' },
835
+ * 'eth|123...abc', // your wallet address
836
+ * );
837
+ * ```
838
+ */
839
+ readonly swaps: Swaps;
840
+ /**
841
+ * User asset management operations.
842
+ * Use this to retrieve user token balances and asset information.
843
+ *
844
+ * @example
845
+ * ```typescript
846
+ * // Get user assets with pagination
847
+ * const assets = await gSwap.assets.getUserAssets('eth|123...abc', 1, 20);
848
+ * console.log(`User has ${assets.count} different tokens`);
849
+ * ```
850
+ */
851
+ readonly assets: Assets;
852
+ /**
853
+ * Event management operations for real-time socket connections.
854
+ * Use this to manage event streaming and transaction status updates.
855
+ *
856
+ * @example
857
+ * ```typescript
858
+ * // Connect to event socket for transaction updates
859
+ * await GSwap.events.connectEventSocket();
860
+ *
861
+ * // Check if socket is connected
862
+ * const isConnected = GSwap.events.eventSocketConnected();
863
+ * ```
864
+ */
865
+ static readonly events: Events;
866
+ private readonly httpClient;
867
+ private readonly httpRequestor;
868
+ private readonly bundler;
869
+ readonly pools: Pools;
870
+ /**
871
+ * Creates a new SDK instance.
872
+ * @param options - Customization options.
873
+ * @param options.signer - The signer to use for authenticated operations. Required if you use any functionality that creates transactions (such as swapping). Not required for readonly operations.
874
+ * @param options.gatewayBaseUrl - Base URL for the GalaChain Gateway API.
875
+ * @param options.dexContractBasePath - Base path for DEX contract API endpoints, within the GalaChain Gateway API.
876
+ * @param options.tokenContractBasePath - Base path for token contract API endpoints, within the GalaChain Gateway API.
877
+ * @param options.bundlerBaseUrl - Base URL for the DEX transaction bundling API.
878
+ * @param options.bundlingAPIBasePath - Base path for transaction bundling API endpoints.
879
+ * @param options.dexBackendBaseUrl - Base URL for the DEX backend API (for user assets and other data).
880
+ * @param options.httpRequestor - Custom HTTP requestor to use for API calls. Defaults to the global `fetch` function.
881
+ * @param options.transactionWaitTimeoutMs - Timeout in milliseconds for waiting for transactions to complete. Defaults to 300,000 milliseconds (five minutes).
882
+ * @param options.walletAddress - Optional default wallet address for operations that require a wallet address (e.x. swapping). If not provided, you must specify the wallet address in each method call.
883
+ */
884
+ constructor(options?: {
885
+ signer?: GalaChainSigner | undefined;
886
+ gatewayBaseUrl?: string | undefined;
887
+ dexContractBasePath?: string | undefined;
888
+ tokenContractBasePath?: string | undefined;
889
+ bundlerBaseUrl?: string | undefined;
890
+ bundlingAPIBasePath?: string | undefined;
891
+ dexBackendBaseUrl?: string | undefined;
892
+ transactionWaitTimeoutMs?: number | undefined;
893
+ walletAddress?: string | undefined;
894
+ httpRequestor?: HttpRequestor | undefined;
895
+ });
896
+ }
897
+
898
+ declare class GSwapSDKError extends Error {
899
+ readonly code: string;
900
+ readonly details?: Record<string, unknown> | undefined;
901
+ constructor(message: string, code: string, details?: Record<string, unknown> | undefined);
902
+ static noSignerError(): GSwapSDKError;
903
+ static fromErrorResponse(url: string, response: HTTPResponse): Promise<GSwapSDKError>;
904
+ static incorrectTokenOrderingError(specifiedToken0: GalaChainTokenClassKey | string, specifiedToken1: GalaChainTokenClassKey | string): GSwapSDKError;
905
+ static transactionWaitTimeoutError(txId: string): GSwapSDKError;
906
+ static transactionWaitFailedError(txId: string, detail: Record<string, unknown>): GSwapSDKError;
907
+ static socketConnectionRequiredError(): GSwapSDKError;
908
+ static noPoolAvailableError(tokenIn: GalaChainTokenClassKey | string, tokenOut: GalaChainTokenClassKey | string, fee?: number): GSwapSDKError;
909
+ }
910
+
911
+ declare function compareTokens(first: GalaChainTokenClassKey | string, second: GalaChainTokenClassKey | string): number;
912
+
913
+ declare function validateNumericAmount(amount: NumericAmount, parameterName: string, allowZero?: boolean): void;
914
+ declare function validatePriceValues(spotPrice: NumericAmount, lowerPrice: NumericAmount, upperPrice: NumericAmount): void;
915
+ declare function validateTokenDecimals(decimals: number, parameterName: string): void;
916
+ declare function validateTickRange(tickLower: number, tickUpper: number): void;
917
+ declare function validateFee(fee: number): void;
918
+ declare function validateTickSpacing(tickSpacing: number): void;
919
+ declare function validateWalletAddress(address?: string): asserts address is string;
920
+
921
+ export { Assets, Bundler, type BundlerRequest, type BundlerResponse, EventSocketClient, Events, FEE_TIER, GSwap, GSwapSDKError, type GalaChainSigner, type GalaChainTokenClassKey, GalaWalletSigner, type GetPoolDataRawResponse, type GetPoolDataResponse, type GetPositionResult, type GetQuoteResult, type GetUserAssetsResult, type GetUserPositionsResult, type NumericAmount, PendingTransaction, Pools, Positions, type Price, type PriceIn, PrivateKeySigner, type QuoteExactAmountRawResponse, type QuoteExactAmountResponse, Quoting, type SqrtPrice, type SqrtPriceIn, Swaps, TradeEventEmitter, type TransactionPendingResponse, type UserAsset, compareTokens, validateFee, validateNumericAmount, validatePriceValues, validateTickRange, validateTickSpacing, validateTokenDecimals, validateWalletAddress };