@crypticdot/defituna-api 1.10.15 → 3.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.
package/dist/index.mjs DELETED
@@ -1,1511 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/client/client.ts
8
- import camelcaseKeys from "camelcase-keys";
9
- import snakecaseKeys from "snakecase-keys";
10
-
11
- // src/client/schemas.ts
12
- var schemas_exports = {};
13
- __export(schemas_exports, {
14
- AmountWithUsdSchema: () => AmountWithUsdSchema,
15
- AmountWithoutUsdSchema: () => AmountWithoutUsdSchema,
16
- CloseSpotPositionQuote: () => CloseSpotPositionQuote,
17
- DecreaseSpotPositionQuote: () => DecreaseSpotPositionQuote,
18
- FeesStatsGroup: () => FeesStatsGroup,
19
- IncreaseSpotPositionQuote: () => IncreaseSpotPositionQuote,
20
- LendingPosition: () => LendingPosition,
21
- LendingPositionNotification: () => LendingPositionNotification,
22
- LimitOrder: () => LimitOrder,
23
- LimitOrderQuoteByInput: () => LimitOrderQuoteByInput,
24
- LimitOrderQuoteByOutput: () => LimitOrderQuoteByOutput,
25
- LimitOrderState: () => LimitOrderState,
26
- LimitOrderStateSchema: () => LimitOrderStateSchema,
27
- LpPositionAutoCompound: () => LpPositionAutoCompound,
28
- LpPositionAutoCompoundSchema: () => LpPositionAutoCompoundSchema,
29
- LpPositionLimitOrderSwap: () => LpPositionLimitOrderSwap,
30
- LpPositionLimitOrderSwapSchema: () => LpPositionLimitOrderSwapSchema,
31
- LpPositionRebalance: () => LpPositionRebalance,
32
- LpPositionRebalanceSchema: () => LpPositionRebalanceSchema,
33
- LpPositionsActionType: () => LpPositionsActionType,
34
- LpPositionsActionTypeSchema: () => LpPositionsActionTypeSchema,
35
- Market: () => Market,
36
- Mint: () => Mint,
37
- NotificationAction: () => NotificationAction,
38
- NotificationActionSchema: () => NotificationActionSchema,
39
- NotificationEntity: () => NotificationEntity,
40
- NotificationEntitySchema: () => NotificationEntitySchema,
41
- OrderBook: () => OrderBook,
42
- OrderBookEntry: () => OrderBookEntry,
43
- OrderHistoryEntry: () => OrderHistoryEntry,
44
- OrderHistoryEntryNotification: () => OrderHistoryEntryNotification,
45
- OrderHistoryOrderType: () => OrderHistoryOrderType,
46
- OrderHistoryOrderTypeSchema: () => OrderHistoryOrderTypeSchema,
47
- OrderHistoryStatus: () => OrderHistoryStatus,
48
- OrderHistoryStatusSchema: () => OrderHistoryStatusSchema,
49
- OrderHistoryUIDirection: () => OrderHistoryUIDirection,
50
- OrderHistoryUIDirectionSchema: () => OrderHistoryUIDirectionSchema,
51
- PaginationMeta: () => PaginationMeta,
52
- Pool: () => Pool,
53
- PoolPriceCandle: () => PoolPriceCandle,
54
- PoolProvider: () => PoolProvider,
55
- PoolProviderSchema: () => PoolProviderSchema,
56
- PoolSubscriptionTopic: () => PoolSubscriptionTopic,
57
- PoolSubscriptionTopicSchema: () => PoolSubscriptionTopicSchema,
58
- PoolSwap: () => PoolSwap,
59
- PoolSwapNotification: () => PoolSwapNotification,
60
- PoolTicks: () => PoolTicks,
61
- StakingLeaderboardPage: () => StakingLeaderboardPage,
62
- StakingLeaderboardPosition: () => StakingLeaderboardPosition,
63
- StakingPosition: () => StakingPosition,
64
- StakingPositionHistoryAction: () => StakingPositionHistoryAction,
65
- StakingPositionHistoryActionType: () => StakingPositionHistoryActionType,
66
- StakingPositionHistoryActionTypeSchema: () => StakingPositionHistoryActionTypeSchema,
67
- StakingPositionNotification: () => StakingPositionNotification,
68
- StakingRevenueStatsGroup: () => StakingRevenueStatsGroup,
69
- StakingTreasury: () => StakingTreasury,
70
- StateSnapshot: () => StateSnapshot,
71
- StateSnapshotNotification: () => StateSnapshotNotification,
72
- SwapQuoteByInput: () => SwapQuoteByInput,
73
- SwapQuoteByOutput: () => SwapQuoteByOutput,
74
- Tick: () => Tick,
75
- TokenOraclePrice: () => TokenOraclePrice,
76
- TokensPnlSchema: () => TokensPnlSchema,
77
- TradableAmount: () => TradableAmount,
78
- TradeHistoryAction: () => TradeHistoryAction,
79
- TradeHistoryActionSchema: () => TradeHistoryActionSchema,
80
- TradeHistoryEntry: () => TradeHistoryEntry,
81
- TradeHistoryEntryNotification: () => TradeHistoryEntryNotification,
82
- TradeHistoryUIDirection: () => TradeHistoryUIDirection,
83
- TradeHistoryUIDirectionSchema: () => TradeHistoryUIDirectionSchema,
84
- TunaLpPositionAction: () => TunaLpPositionAction,
85
- TunaLpPositionActionClose: () => TunaLpPositionActionClose,
86
- TunaLpPositionActionCollectAndCompoundFees: () => TunaLpPositionActionCollectAndCompoundFees,
87
- TunaLpPositionActionCollectFees: () => TunaLpPositionActionCollectFees,
88
- TunaLpPositionActionDecreaseLiquidity: () => TunaLpPositionActionDecreaseLiquidity,
89
- TunaLpPositionActionIncreaseLiquidity: () => TunaLpPositionActionIncreaseLiquidity,
90
- TunaLpPositionActionLiquidate: () => TunaLpPositionActionLiquidate,
91
- TunaLpPositionActionOpen: () => TunaLpPositionActionOpen,
92
- TunaLpPositionActionParametersUpdate: () => TunaLpPositionActionParametersUpdate,
93
- TunaLpPositionActionRepayDebt: () => TunaLpPositionActionRepayDebt,
94
- TunaLpPositionAutoCompounding: () => TunaLpPositionAutoCompounding,
95
- TunaLpPositionAutoCompoundingSchema: () => TunaLpPositionAutoCompoundingSchema,
96
- TunaLpPositionDtoSchema: () => TunaLpPositionDtoSchema,
97
- TunaLpPositionFlagsSchema: () => TunaLpPositionFlagsSchema,
98
- TunaLpPositionHistorical: () => TunaLpPositionHistorical,
99
- TunaLpPositionParameters: () => TunaLpPositionParameters,
100
- TunaLpPositionTokenPrices: () => TunaLpPositionTokenPrices,
101
- TunaLpPositionTransfer: () => TunaLpPositionTransfer,
102
- TunaLpPositionValue: () => TunaLpPositionValue,
103
- TunaPositionLegacy: () => TunaPositionLegacy,
104
- TunaPositionPoolToken: () => TunaPositionPoolToken,
105
- TunaPositionPoolTokenSchema: () => TunaPositionPoolTokenSchema,
106
- TunaPositionState: () => TunaPositionState,
107
- TunaPositionStateSchema: () => TunaPositionStateSchema,
108
- TunaPositionTokenPnlSchema: () => TunaPositionTokenPnlSchema,
109
- TunaSpotPosition: () => TunaSpotPosition,
110
- TunaSpotPositionState: () => TunaSpotPositionState,
111
- TunaSpotPositionStateSchema: () => TunaSpotPositionStateSchema,
112
- UpdateStreamSubscriptionResult: () => UpdateStreamSubscriptionResult,
113
- UsdPnlSchema: () => UsdPnlSchema,
114
- Vault: () => Vault,
115
- VaultHistoricalStats: () => VaultHistoricalStats,
116
- WalletSubscriptionTopic: () => WalletSubscriptionTopic,
117
- WalletSubscriptionTopicSchema: () => WalletSubscriptionTopicSchema
118
- });
119
- import { z as z11 } from "zod";
120
-
121
- // src/client/schemas/basic.ts
122
- import { z } from "zod";
123
- var AmountWithUsdSchema = z.object({
124
- amount: z.coerce.bigint(),
125
- usd: z.number()
126
- });
127
- var AmountWithoutUsdSchema = z.object({
128
- amount: z.coerce.bigint()
129
- });
130
- var TokensPnlSchema = z.object({
131
- amount: z.coerce.bigint(),
132
- rate: z.number()
133
- });
134
- var UsdPnlSchema = z.object({
135
- amount: z.number(),
136
- rate: z.number()
137
- });
138
-
139
- // src/client/schemas/pool.ts
140
- import z3 from "zod";
141
-
142
- // src/client/schemas/mint.ts
143
- import { z as z2 } from "zod";
144
- var Mint = z2.object({
145
- address: z2.string(),
146
- symbol: z2.string(),
147
- name: z2.string(),
148
- logo: z2.string(),
149
- decimals: z2.number()
150
- });
151
-
152
- // src/client/schemas/pool.ts
153
- var PoolProvider = {
154
- ORCA: "orca",
155
- FUSION: "fusion"
156
- };
157
- var PoolProviderSchema = z3.enum([PoolProvider.ORCA, ...Object.values(PoolProvider)]);
158
- var Pool = z3.object({
159
- address: z3.string(),
160
- provider: PoolProviderSchema,
161
- mintA: Mint,
162
- mintB: Mint,
163
- tokenAVault: z3.string(),
164
- tokenBVault: z3.string(),
165
- tickSpacing: z3.number(),
166
- feeRate: z3.number(),
167
- protocolFeeRate: z3.number(),
168
- olpFeeRate: z3.nullable(z3.number()),
169
- liquidity: z3.coerce.bigint(),
170
- sqrtPrice: z3.coerce.bigint(),
171
- price: z3.number(),
172
- tickCurrentIndex: z3.number(),
173
- stats: z3.optional(
174
- z3.nullable(
175
- z3.object({
176
- tvlUsd: z3.coerce.number(),
177
- groups: z3.object({
178
- "24h": z3.optional(
179
- z3.nullable(
180
- z3.object({
181
- volumeUsd: z3.number(),
182
- feesUsd: z3.number(),
183
- priceChange: z3.number()
184
- })
185
- )
186
- )
187
- })
188
- })
189
- )
190
- )
191
- });
192
-
193
- // src/client/schemas/state_snapshot.ts
194
- import z10 from "zod";
195
-
196
- // src/client/schemas/limit_orders.ts
197
- import { z as z4 } from "zod";
198
- var LimitOrderState = {
199
- OPEN: "open",
200
- PARTIALLY_FILLED: "partially_filled",
201
- FILLED: "filled",
202
- COMPLETE: "complete",
203
- CANCELLED: "cancelled"
204
- };
205
- var LimitOrderStateSchema = z4.enum([LimitOrderState.OPEN, ...Object.values(LimitOrderState)]);
206
- var LimitOrder = z4.object({
207
- address: z4.string(),
208
- orderMint: z4.string(),
209
- authority: z4.string(),
210
- pool: Pool,
211
- state: LimitOrderStateSchema,
212
- aToB: z4.boolean(),
213
- tickIndex: z4.number(),
214
- fillRatio: z4.number(),
215
- openTxSignature: z4.string(),
216
- closeTxSignature: z4.nullable(z4.string()),
217
- amountIn: AmountWithUsdSchema,
218
- amountOut: AmountWithUsdSchema,
219
- openedAt: z4.coerce.date(),
220
- closedAt: z4.nullable(z4.coerce.date())
221
- });
222
-
223
- // src/client/schemas/lp_positions.ts
224
- import z6 from "zod";
225
-
226
- // src/client/schemas/positions_shared.ts
227
- import z5 from "zod";
228
- var TunaPositionPoolToken = {
229
- A: "a",
230
- B: "b"
231
- };
232
- var TunaPositionPoolTokenSchema = z5.enum(Object.values(TunaPositionPoolToken));
233
-
234
- // src/client/schemas/lp_positions.ts
235
- var LpPositionLimitOrderSwap = {
236
- NO_SWAP: "no_swap",
237
- SWAP_TO_TOKEN_A: "swap_to_token_a",
238
- SWAP_TO_TOKEN_B: "swap_to_token_b"
239
- };
240
- var LpPositionAutoCompound = {
241
- NO_AUTO_COMPOUND: "no_auto_compound",
242
- AUTO_COMPOUND: "auto_compound",
243
- AUTO_COMPOUND_WITH_LEVERAGE: "auto_compound_with_leverage"
244
- };
245
- var LpPositionRebalance = {
246
- NO_REBALANCE: "no_rebalance",
247
- AUTO_REBALANCE: "auto_rebalance"
248
- };
249
- var LpPositionsActionType = {
250
- OPEN_POSITION: "open_position",
251
- CLOSE_POSITION: "close_position",
252
- INCREASE_LIQUIDITY: "increase_liquidity",
253
- DECREASE_LIQUIDITY: "decrease_liquidity",
254
- REPAY_DEBT: "repay_debt",
255
- LIQUIDATE: "liquidate",
256
- EXECUTE_LIMIT_ORDER: "execute_limit_order",
257
- COLLECT_FEES: "collect_fees",
258
- COLLECT_REWARDS: "collect_rewards",
259
- COLLECT_AND_COMPOUND_FEES: "collect_and_compound_fees",
260
- REBALANCE_POSITION: "rebalance_position",
261
- SET_LIMIT_ORDERS: "set_limit_orders",
262
- SET_FLAGS: "set_flags",
263
- SET_REBALANCE_THRESHOLD: "set_rebalance_threshold"
264
- };
265
- var LpPositionLimitOrderSwapSchema = z6.enum(Object.values(LpPositionLimitOrderSwap));
266
- var LpPositionAutoCompoundSchema = z6.enum(Object.values(LpPositionAutoCompound));
267
- var LpPositionRebalanceSchema = z6.enum(Object.values(LpPositionRebalance));
268
- var LpPositionsActionTypeSchema = z6.enum(Object.values(LpPositionsActionType));
269
- var TunaPositionState = {
270
- OPEN: "open",
271
- LIQUIDATED: "liquidated",
272
- CLOSED_BY_LIMIT_ORDER: "closed_by_limit_order",
273
- CLOSED: "closed"
274
- };
275
- var TunaPositionStateSchema = z6.enum([TunaPositionState.OPEN, ...Object.values(TunaPositionState)]);
276
- var TunaLpPositionAutoCompounding = {
277
- WITH_LEVERAGE: "with_leverage",
278
- WITHOUT_LEVERAGE: "without_leverage"
279
- };
280
- var TunaLpPositionAutoCompoundingSchema = z6.enum(
281
- Object.values(TunaLpPositionAutoCompounding)
282
- );
283
- var TunaPositionTokenPnlSchema = z6.object({
284
- amount: z6.coerce.bigint(),
285
- bps: z6.number()
286
- });
287
- var TunaLpPositionFlagsSchema = z6.object({
288
- lowerLimitOrderSwapToToken: z6.nullable(TunaPositionPoolTokenSchema),
289
- upperLimitOrderSwapToToken: z6.nullable(TunaPositionPoolTokenSchema),
290
- autoCompounding: z6.nullable(TunaLpPositionAutoCompoundingSchema),
291
- autoRebalancing: z6.boolean()
292
- });
293
- var TunaLpPositionDtoSchema = z6.object({
294
- address: z6.string(),
295
- authority: z6.string(),
296
- version: z6.number(),
297
- state: TunaPositionStateSchema,
298
- positionMint: z6.string(),
299
- liquidity: z6.coerce.bigint(),
300
- tickLowerIndex: z6.number(),
301
- tickUpperIndex: z6.number(),
302
- lowerLimitOrderPrice: z6.number(),
303
- upperLimitOrderPrice: z6.number(),
304
- entryPrice: z6.number(),
305
- flags: TunaLpPositionFlagsSchema,
306
- pool: Pool,
307
- marketMaker: PoolProviderSchema,
308
- depositedCollateralA: AmountWithUsdSchema,
309
- depositedCollateralB: AmountWithUsdSchema,
310
- leverage: z6.number(),
311
- maxLeverage: z6.number(),
312
- liquidationPriceLower: z6.number(),
313
- liquidationPriceUpper: z6.number(),
314
- initialDebtA: AmountWithUsdSchema,
315
- initialDebtB: AmountWithUsdSchema,
316
- currentDebtA: AmountWithUsdSchema,
317
- currentDebtB: AmountWithUsdSchema,
318
- leftoversA: AmountWithUsdSchema,
319
- leftoversB: AmountWithUsdSchema,
320
- yieldA: AmountWithUsdSchema,
321
- yieldB: AmountWithUsdSchema,
322
- compoundedYieldA: AmountWithUsdSchema,
323
- compoundedYieldB: AmountWithUsdSchema,
324
- totalA: AmountWithUsdSchema,
325
- totalB: AmountWithUsdSchema,
326
- pnlA: TokensPnlSchema,
327
- pnlB: TokensPnlSchema,
328
- pnlUsd: UsdPnlSchema,
329
- openedAt: z6.coerce.date(),
330
- closedAt: z6.nullable(z6.coerce.date())
331
- });
332
- var TunaLpPositionHistorical = z6.object({
333
- positionAddress: z6.string(),
334
- authority: z6.string(),
335
- pool: z6.string(),
336
- state: TunaPositionStateSchema,
337
- lowerPrice: z6.number(),
338
- upperPrice: z6.number(),
339
- lowerLimitOrder: z6.number().nullable(),
340
- upperLimitOrder: z6.number().nullable(),
341
- marketMaker: PoolProviderSchema,
342
- openedAt: z6.coerce.date(),
343
- closedAt: z6.coerce.date().nullable(),
344
- totalValueUsd: z6.number(),
345
- leverage: z6.number(),
346
- initialLeverage: z6.number(),
347
- totalDepositUsd: z6.number(),
348
- totalWithdrawnUsd: z6.number(),
349
- feesSumUsd: z6.number(),
350
- closedPnlSumUsd: z6.number(),
351
- entryPrice: z6.number(),
352
- exitPrice: z6.number().nullable()
353
- });
354
- var TunaPositionLegacy = z6.object({
355
- address: z6.string(),
356
- authority: z6.string(),
357
- version: z6.number(),
358
- state: TunaPositionStateSchema,
359
- positionMint: z6.string(),
360
- liquidity: z6.coerce.bigint(),
361
- tickLowerIndex: z6.number(),
362
- tickUpperIndex: z6.number(),
363
- entrySqrtPrice: z6.coerce.bigint(),
364
- lowerLimitOrderSqrtPrice: z6.coerce.bigint(),
365
- upperLimitOrderSqrtPrice: z6.coerce.bigint(),
366
- flags: z6.number(),
367
- pool: z6.string(),
368
- poolSqrtPrice: z6.coerce.bigint(),
369
- depositedCollateralA: AmountWithoutUsdSchema,
370
- depositedCollateralB: AmountWithoutUsdSchema,
371
- depositedCollateralUsd: z6.object({
372
- amount: z6.number()
373
- }),
374
- loanFundsA: AmountWithUsdSchema,
375
- loanFundsB: AmountWithUsdSchema,
376
- currentLoanA: AmountWithUsdSchema,
377
- currentLoanB: AmountWithUsdSchema,
378
- leftoversA: AmountWithUsdSchema,
379
- leftoversB: AmountWithUsdSchema,
380
- yieldA: AmountWithUsdSchema,
381
- yieldB: AmountWithUsdSchema,
382
- compoundedYieldA: AmountWithUsdSchema,
383
- compoundedYieldB: AmountWithUsdSchema,
384
- totalA: AmountWithUsdSchema,
385
- totalB: AmountWithUsdSchema,
386
- pnlA: TokensPnlSchema,
387
- pnlB: TokensPnlSchema,
388
- pnlUsd: UsdPnlSchema,
389
- openedAt: z6.coerce.date(),
390
- updatedAtSlot: z6.coerce.bigint(),
391
- closedAt: z6.nullable(z6.coerce.date())
392
- });
393
- var TunaLpPositionParameters = z6.object({
394
- lowerPrice: z6.number(),
395
- upperPrice: z6.number(),
396
- lowerLimitOrder: z6.number().nullable(),
397
- upperLimitOrder: z6.number().nullable(),
398
- lowerLimitOrderSwap: LpPositionLimitOrderSwapSchema,
399
- upperLimitOrderSwap: LpPositionLimitOrderSwapSchema,
400
- autoCompound: LpPositionAutoCompoundSchema,
401
- rebalance: LpPositionRebalanceSchema,
402
- rebalanceThresholdTicks: z6.number()
403
- });
404
- var TunaLpPositionValue = z6.object({
405
- totalValueA: z6.number(),
406
- totalValueB: z6.number(),
407
- totalValueUsd: z6.number(),
408
- loanFundsA: z6.number(),
409
- loanFundsB: z6.number(),
410
- loanFundsUsd: z6.number(),
411
- leverage: z6.number()
412
- });
413
- var TunaLpPositionTransfer = z6.object({
414
- amountA: z6.number(),
415
- amountB: z6.number(),
416
- amountUsd: z6.number()
417
- });
418
- var TunaLpPositionTokenPrices = z6.object({
419
- tokenPriceA: z6.number(),
420
- tokenPriceB: z6.number()
421
- });
422
- var TunaLpPositionActionOpen = z6.object({
423
- parameters: TunaLpPositionParameters
424
- });
425
- var TunaLpPositionActionClose = z6.object({
426
- toOwner: TunaLpPositionTransfer.nullable(),
427
- prices: TunaLpPositionTokenPrices.nullable()
428
- });
429
- var TunaLpPositionActionIncreaseLiquidity = z6.object({
430
- fromPosition: TunaLpPositionValue.nullable(),
431
- toPosition: TunaLpPositionValue,
432
- fromOwner: TunaLpPositionTransfer,
433
- fromLending: TunaLpPositionTransfer,
434
- protocolFees: TunaLpPositionTransfer,
435
- prices: TunaLpPositionTokenPrices
436
- });
437
- var TunaLpPositionActionDecreaseLiquidity = z6.object({
438
- withdrawPercent: z6.number(),
439
- closedPnlUsd: z6.number(),
440
- fromPosition: TunaLpPositionValue,
441
- toPosition: TunaLpPositionValue.nullable(),
442
- toOwner: TunaLpPositionTransfer,
443
- toLending: TunaLpPositionTransfer,
444
- collectedFees: TunaLpPositionTransfer,
445
- prices: TunaLpPositionTokenPrices
446
- });
447
- var TunaLpPositionActionLiquidate = z6.object({
448
- withdrawPercent: z6.number(),
449
- fromPosition: TunaLpPositionValue,
450
- toLending: TunaLpPositionTransfer,
451
- protocolFees: TunaLpPositionTransfer,
452
- prices: TunaLpPositionTokenPrices
453
- });
454
- var TunaLpPositionActionRepayDebt = z6.object({
455
- fromPosition: TunaLpPositionValue,
456
- toPosition: TunaLpPositionValue,
457
- fromOwner: TunaLpPositionTransfer,
458
- toLending: TunaLpPositionTransfer,
459
- prices: TunaLpPositionTokenPrices
460
- });
461
- var TunaLpPositionActionCollectFees = z6.object({
462
- closedPnlUsd: z6.number(),
463
- position: TunaLpPositionValue,
464
- collectedFees: TunaLpPositionTransfer,
465
- toOwner: TunaLpPositionTransfer,
466
- prices: TunaLpPositionTokenPrices
467
- });
468
- var TunaLpPositionActionCollectAndCompoundFees = z6.object({
469
- fromPosition: TunaLpPositionValue,
470
- toPosition: TunaLpPositionValue,
471
- collectedFees: TunaLpPositionTransfer,
472
- fromLending: TunaLpPositionTransfer,
473
- protocolFees: TunaLpPositionTransfer,
474
- prices: TunaLpPositionTokenPrices
475
- });
476
- var TunaLpPositionActionParametersUpdate = z6.object({
477
- fromParameters: TunaLpPositionParameters,
478
- toParameters: TunaLpPositionParameters
479
- });
480
- var TunaLpPositionAction = z6.object({
481
- action: LpPositionsActionTypeSchema,
482
- txSignature: z6.string(),
483
- txTimestamp: z6.coerce.date(),
484
- data: z6.object({
485
- /** defined for: IncreaseLiquidity, DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt, CollectAndCompoundFees */
486
- fromPosition: TunaLpPositionValue.optional().nullable(),
487
- /** defined for: IncreaseLiquidity, DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt, CollectAndCompoundFees */
488
- toPosition: TunaLpPositionValue.optional().nullable(),
489
- /** defined for: CollectFees */
490
- position: TunaLpPositionValue.optional().nullable(),
491
- /** defined for: IncreaseLiquidity, RepayDebt */
492
- fromOwner: TunaLpPositionTransfer.optional(),
493
- /** defined for: DecreaseLiquidity, CollectFees, ClosePosition; nullable for: ClosePosition */
494
- toOwner: TunaLpPositionTransfer.optional().nullable(),
495
- /** defined for: IncreaseLiquidity, CollectAndCompoundFees */
496
- fromLending: TunaLpPositionTransfer.optional(),
497
- /** defined for: DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt */
498
- toLending: TunaLpPositionTransfer.optional(),
499
- /** defined for: CollectFees, CollectAndCompoundFees */
500
- collectedFees: TunaLpPositionTransfer.optional(),
501
- /** defined for: IncreaseLiquidity, Liquidate, ExecuteLimitOrder, CollectAndCompoundFees */
502
- protocolFees: TunaLpPositionTransfer.optional(),
503
- /** defined for: IncreaseLiquidity, DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt, CollectFees, CollectAndCompoundFees, ClosePosition; nullable for: ClosePosition */
504
- prices: TunaLpPositionTokenPrices.optional().nullable(),
505
- /** defined for: OpenPosition */
506
- parameters: TunaLpPositionParameters.optional(),
507
- /** defined for: ParametersUpdate */
508
- fromParameters: TunaLpPositionParameters.optional(),
509
- /** defined for: ParametersUpdate */
510
- toParameters: TunaLpPositionParameters.optional(),
511
- /** defined for: DecreaseLiquidity */
512
- withdrawPercent: z6.number().optional(),
513
- /** defined for: DecreaseLiquidity, CollectFees */
514
- closedPnlUsd: z6.number().optional()
515
- })
516
- });
517
-
518
- // src/client/schemas/market.ts
519
- import { z as z7 } from "zod";
520
- var Market = z7.object({
521
- address: z7.string(),
522
- addressLookupTable: z7.string(),
523
- maxLeverage: z7.number(),
524
- maxSwapSlippage: z7.number(),
525
- protocolFee: z7.number(),
526
- protocolFeeOnCollateral: z7.number(),
527
- liquidationFee: z7.number(),
528
- liquidationThreshold: z7.number(),
529
- oraclePriceDeviationThreshold: z7.number(),
530
- rebalanceProtocolFee: z7.number(),
531
- borrowedFundsA: AmountWithUsdSchema,
532
- borrowedFundsB: AmountWithUsdSchema,
533
- borrowLimitA: AmountWithUsdSchema,
534
- borrowLimitB: AmountWithUsdSchema,
535
- maxSpotPositionSizeA: AmountWithUsdSchema,
536
- maxSpotPositionSizeB: AmountWithUsdSchema,
537
- pool: Pool,
538
- disabled: z7.boolean(),
539
- createdAt: z7.coerce.date()
540
- });
541
-
542
- // src/client/schemas/order_book.ts
543
- import z8 from "zod";
544
- var OrderBookEntry = z8.object({
545
- concentratedAmount: z8.coerce.bigint(),
546
- concentratedAmountQuote: z8.coerce.bigint(),
547
- concentratedTotal: z8.coerce.bigint(),
548
- concentratedTotalQuote: z8.coerce.bigint(),
549
- limitAmount: z8.coerce.bigint(),
550
- limitAmountQuote: z8.coerce.bigint(),
551
- limitTotal: z8.coerce.bigint(),
552
- limitTotalQuote: z8.coerce.bigint(),
553
- price: z8.number(),
554
- askSide: z8.boolean()
555
- });
556
- var OrderBook = z8.object({
557
- entries: OrderBookEntry.array(),
558
- poolPrice: z8.number(),
559
- poolAddress: z8.string()
560
- });
561
-
562
- // src/client/schemas/spot_positions.ts
563
- import { z as z9 } from "zod";
564
- var TunaSpotPositionState = {
565
- OPEN: "open",
566
- CLOSED: "closed"
567
- };
568
- var TunaSpotPositionStateSchema = z9.enum([
569
- TunaSpotPositionState.OPEN,
570
- ...Object.values(TunaSpotPositionState)
571
- ]);
572
- var TunaSpotPosition = z9.object({
573
- address: z9.string(),
574
- authority: z9.string(),
575
- version: z9.number(),
576
- state: TunaSpotPositionStateSchema,
577
- lowerLimitOrderPrice: z9.number(),
578
- upperLimitOrderPrice: z9.number(),
579
- entryPrice: z9.number(),
580
- pool: Pool,
581
- positionToken: TunaPositionPoolTokenSchema,
582
- collateralToken: TunaPositionPoolTokenSchema,
583
- marketMaker: PoolProviderSchema,
584
- depositedCollateral: AmountWithUsdSchema,
585
- initialDebt: AmountWithUsdSchema,
586
- currentDebt: AmountWithUsdSchema,
587
- total: AmountWithUsdSchema,
588
- leverage: z9.number(),
589
- maxLeverage: z9.number(),
590
- liquidationPrice: z9.number(),
591
- pnlUsd: UsdPnlSchema,
592
- openedAt: z9.coerce.date(),
593
- closedAt: z9.nullable(z9.coerce.date())
594
- });
595
- var IncreaseSpotPositionQuote = z9.object({
596
- /** Required collateral amount */
597
- collateralAmount: z9.coerce.bigint(),
598
- /** Required amount to borrow */
599
- borrowAmount: z9.coerce.bigint(),
600
- /** Estimated position size in the position token. */
601
- estimatedAmount: z9.coerce.bigint(),
602
- /** Swap input amount. */
603
- swapInputAmount: z9.coerce.bigint(),
604
- /** Minimum swap output amount according to the provided slippage. */
605
- minSwapOutputAmount: z9.coerce.bigint(),
606
- /** Protocol fee in token A */
607
- protocolFeeA: z9.coerce.bigint(),
608
- /** Protocol fee in token B */
609
- protocolFeeB: z9.coerce.bigint(),
610
- /** Price impact in percents */
611
- priceImpact: z9.number(),
612
- /** Liquidation price */
613
- liquidationPrice: z9.number()
614
- });
615
- var DecreaseSpotPositionQuote = z9.object({
616
- /** Confirmed position decrease percentage (100% = 1.0) */
617
- decreasePercent: z9.number(),
618
- /** The maximum acceptable swap input amount for position decrease according to the provided slippage
619
- * (if collateral_token == position_token) OR the minimum swap output amount (if collateral_token != position_token).
620
- */
621
- requiredSwapAmount: z9.coerce.bigint(),
622
- /** Estimated total amount of the adjusted position */
623
- estimatedAmount: z9.coerce.bigint(),
624
- /** Estimated amount of the withdrawn collateral */
625
- estimatedWithdrawnCollateral: z9.coerce.bigint(),
626
- /** Price impact in percents */
627
- priceImpact: z9.number(),
628
- /** Liquidation price */
629
- liquidationPrice: z9.number()
630
- });
631
- var CloseSpotPositionQuote = z9.object({
632
- /** Position decrease percentage */
633
- decreasePercent: z9.number(),
634
- /** The maximum acceptable swap input amount for position decrease according to the provided slippage
635
- * (if collateral_token == position_token) OR the minimum swap output amount (if collateral_token != position_token).
636
- */
637
- requiredSwapAmount: z9.coerce.bigint(),
638
- /** Estimated amount of the withdrawn collateral */
639
- estimatedWithdrawnCollateral: z9.coerce.bigint(),
640
- /** Price impact in percents */
641
- priceImpact: z9.number()
642
- });
643
-
644
- // src/client/schemas/state_snapshot.ts
645
- var StateSnapshot = z10.object({
646
- slot: z10.coerce.bigint(),
647
- blockTime: z10.coerce.date(),
648
- markets: z10.optional(z10.array(Market)),
649
- tunaSpotPositions: z10.optional(z10.array(TunaSpotPosition)),
650
- tunaLpPositions: z10.optional(z10.array(TunaLpPositionDtoSchema)),
651
- fusionLimitOrders: z10.optional(z10.array(LimitOrder)),
652
- orderBooks: z10.optional(z10.array(OrderBook))
653
- });
654
-
655
- // src/client/schemas.ts
656
- var NotificationEntity = {
657
- POOL_SWAP: "pool_swap",
658
- LENDING_POSITION: "lending_position",
659
- STAKING_POSITION: "staking_position",
660
- MARKET: "market",
661
- TRADE_HISTORY_ENTRY: "trade_history_entry",
662
- ORDER_HISTORY_ENTRY: "order_history_entry",
663
- STATE_SNAPSHOT: "state_snapshot"
664
- };
665
- var NotificationAction = {
666
- CREATE: "create",
667
- UPDATE: "update"
668
- };
669
- var TradeHistoryAction = {
670
- SWAP: "swap",
671
- LIMIT_ORDER_FILL: "limit_order_fill",
672
- POSITION_INCREASE: "position_increase",
673
- POSITION_DECREASE: "position_decrease",
674
- TAKE_PROFIT: "take_profit",
675
- STOP_LOSS: "stop_loss",
676
- LIQUIDATION: "liquidation"
677
- };
678
- var TradeHistoryUIDirection = {
679
- BUY: "buy",
680
- SELL: "sell",
681
- OPEN_LONG: "open_long",
682
- CLOSE_LONG: "close_long",
683
- OPEN_SHORT: "open_short",
684
- CLOSE_SHORT: "close_short"
685
- };
686
- var OrderHistoryOrderType = {
687
- MARKET: "market",
688
- LIMIT: "limit",
689
- TAKE_PROFIT_MARKET: "take_profit_market",
690
- STOP_LOSS_MARKET: "stop_loss_market",
691
- LIQUIDATION_MARKET: "liquidation_market"
692
- };
693
- var OrderHistoryStatus = {
694
- OPEN: "open",
695
- PARTIALLY_FILLED: "partially_filled",
696
- FILLED: "filled",
697
- CANCELLED: "cancelled",
698
- CLAIMED: "claimed",
699
- REJECTED: "rejected"
700
- };
701
- var OrderHistoryUIDirection = {
702
- BUY: "buy",
703
- SELL: "sell",
704
- LONG: "long",
705
- SHORT: "short"
706
- };
707
- var StakingPositionHistoryActionType = {
708
- STAKE: "stake",
709
- UNSTAKE: "unstake",
710
- WITHDRAW: "withdraw",
711
- CLAIM_REWARDS: "claim_rewards",
712
- COMPOUND_REWARDS: "compound_rewards"
713
- };
714
- var PoolSubscriptionTopic = {
715
- ORDER_BOOK: "order_book",
716
- POOL_SWAPS: "pool_swaps"
717
- };
718
- var WalletSubscriptionTopic = {
719
- TUNA_POSITIONS: "tuna_positions",
720
- TUNA_SPOT_POSITIONS: "tuna_spot_positions",
721
- LENDING_POSITIONS: "lending_positions",
722
- FUSION_LIMIT_ORDERS: "fusion_limit_orders",
723
- STAKING_POSITION: "staking_position",
724
- TRADE_HISTORY: "trade_history",
725
- ORDER_HISTORY: "order_history"
726
- };
727
- var NotificationEntitySchema = z11.enum([NotificationEntity.POOL_SWAP, ...Object.values(NotificationEntity)]);
728
- var NotificationActionSchema = z11.enum([NotificationAction.CREATE, ...Object.values(NotificationAction)]);
729
- var TradeHistoryActionSchema = z11.enum([TradeHistoryAction.SWAP, ...Object.values(TradeHistoryAction)]);
730
- var TradeHistoryUIDirectionSchema = z11.enum([
731
- TradeHistoryUIDirection.BUY,
732
- ...Object.values(TradeHistoryUIDirection)
733
- ]);
734
- var OrderHistoryOrderTypeSchema = z11.enum([
735
- OrderHistoryOrderType.MARKET,
736
- ...Object.values(OrderHistoryOrderType)
737
- ]);
738
- var OrderHistoryStatusSchema = z11.enum([OrderHistoryStatus.OPEN, ...Object.values(OrderHistoryStatus)]);
739
- var OrderHistoryUIDirectionSchema = z11.enum([
740
- OrderHistoryUIDirection.BUY,
741
- ...Object.values(OrderHistoryUIDirection)
742
- ]);
743
- var StakingPositionHistoryActionTypeSchema = z11.enum([
744
- StakingPositionHistoryActionType.STAKE,
745
- ...Object.values(StakingPositionHistoryActionType)
746
- ]);
747
- var PoolSubscriptionTopicSchema = z11.enum([
748
- PoolSubscriptionTopic.ORDER_BOOK,
749
- ...Object.values(PoolSubscriptionTopic)
750
- ]);
751
- var WalletSubscriptionTopicSchema = z11.enum([
752
- WalletSubscriptionTopic.TUNA_POSITIONS,
753
- ...Object.values(WalletSubscriptionTopic)
754
- ]);
755
- var PaginationMeta = z11.object({
756
- total: z11.number()
757
- });
758
- var TokenOraclePrice = z11.object({
759
- mint: z11.string(),
760
- price: z11.coerce.bigint(),
761
- decimals: z11.number(),
762
- time: z11.coerce.date()
763
- });
764
- var Vault = z11.object({
765
- address: z11.string(),
766
- mint: z11.string(),
767
- depositedFunds: AmountWithUsdSchema,
768
- borrowedFunds: AmountWithUsdSchema,
769
- supplyLimit: AmountWithUsdSchema,
770
- borrowedShares: z11.coerce.bigint(),
771
- depositedShares: z11.coerce.bigint(),
772
- supplyApy: z11.number(),
773
- borrowApy: z11.number(),
774
- interestRate: z11.coerce.bigint(),
775
- utilization: z11.number(),
776
- pythOracleFeedId: z11.string(),
777
- pythOraclePriceUpdate: z11.string()
778
- });
779
- var VaultHistoricalStats = z11.object({
780
- date: z11.preprocess((val, ctx) => {
781
- if (typeof val === "string") {
782
- const [year, month, day] = val.split("-").map(Number);
783
- return new Date(year, month - 1, day);
784
- }
785
- ctx.addIssue({
786
- code: "custom",
787
- message: "Not a valid date string"
788
- });
789
- return z11.NEVER;
790
- }, z11.date()),
791
- supply: AmountWithUsdSchema,
792
- borrow: AmountWithUsdSchema,
793
- supplyApy: z11.number(),
794
- borrowApr: z11.number()
795
- });
796
- var Tick = z11.object({
797
- index: z11.number(),
798
- liquidity: z11.coerce.bigint()
799
- });
800
- var PoolTicks = z11.object({
801
- tickSpacing: z11.number(),
802
- ticks: Tick.array()
803
- });
804
- var LendingPosition = z11.object({
805
- address: z11.string(),
806
- authority: z11.string(),
807
- mint: z11.string(),
808
- vault: z11.string(),
809
- shares: z11.coerce.bigint(),
810
- funds: AmountWithUsdSchema,
811
- earned: AmountWithUsdSchema
812
- });
813
- var PoolSwap = z11.object({
814
- id: z11.string(),
815
- amountIn: z11.coerce.bigint(),
816
- amountOut: z11.coerce.bigint(),
817
- amountUsd: z11.number(),
818
- aToB: z11.boolean(),
819
- pool: z11.string(),
820
- time: z11.coerce.date()
821
- });
822
- var TradeHistoryEntry = z11.object({
823
- // Internal entry ID
824
- id: z11.string(),
825
- pool: Pool,
826
- authority: z11.string(),
827
- aToB: z11.boolean(),
828
- // Trade action which created entry
829
- action: TradeHistoryActionSchema,
830
- // Trade direction formatted for ui display
831
- uiDirection: TradeHistoryUIDirectionSchema,
832
- // Trade price formatted for ui display
833
- uiPrice: z11.number(),
834
- baseToken: AmountWithUsdSchema,
835
- quoteToken: AmountWithUsdSchema,
836
- fee: AmountWithUsdSchema,
837
- pnl: z11.nullable(
838
- z11.object({
839
- usd: z11.number(),
840
- bps: z11.number()
841
- })
842
- ),
843
- txSignature: z11.nullable(z11.string()),
844
- positionAddress: z11.nullable(z11.string()),
845
- slot: z11.coerce.bigint(),
846
- ts: z11.coerce.date()
847
- });
848
- var OrderHistoryEntry = z11.object({
849
- // Internal entry ID
850
- id: z11.string(),
851
- pool: Pool,
852
- authority: z11.string(),
853
- orderType: OrderHistoryOrderTypeSchema,
854
- isReduceOnly: z11.nullable(z11.boolean()),
855
- aToB: z11.boolean(),
856
- uiDirection: OrderHistoryUIDirectionSchema,
857
- uiPrice: z11.nullable(z11.number()),
858
- uiExecutionPrice: z11.nullable(z11.number()),
859
- status: OrderHistoryStatusSchema,
860
- baseToken: AmountWithUsdSchema,
861
- quoteToken: AmountWithUsdSchema,
862
- baseTokenConsumedAmount: z11.nullable(AmountWithUsdSchema),
863
- quoteTokenFilledAmount: z11.nullable(AmountWithUsdSchema),
864
- txSignature: z11.nullable(z11.string()),
865
- positionAddress: z11.nullable(z11.string()),
866
- slot: z11.coerce.bigint(),
867
- ts: z11.coerce.date()
868
- });
869
- var StakingTreasury = z11.object({
870
- address: z11.string(),
871
- stakedTokenMint: z11.string(),
872
- rewardTokenMint: z11.string(),
873
- apy: z11.number(),
874
- uniqueStakers: z11.number(),
875
- totalStaked: AmountWithUsdSchema,
876
- totalReward: AmountWithUsdSchema,
877
- unstakeCooldownSeconds: z11.number(),
878
- isStakingEnabled: z11.boolean(),
879
- isUnstakingEnabled: z11.boolean(),
880
- isWithdrawEnabled: z11.boolean()
881
- });
882
- var StakingPosition = z11.object({
883
- address: z11.string(),
884
- owner: z11.string(),
885
- staked: AmountWithUsdSchema,
886
- unstaked: AmountWithUsdSchema,
887
- claimedReward: AmountWithUsdSchema,
888
- unclaimedReward: AmountWithUsdSchema,
889
- rank: z11.nullable(z11.number()),
890
- vesting: z11.object({
891
- locked: AmountWithUsdSchema,
892
- unlocked: AmountWithUsdSchema,
893
- unlockRate: z11.coerce.bigint(),
894
- unlockEverySeconds: z11.number(),
895
- unlockCliffSeconds: z11.number(),
896
- lockedAt: z11.nullable(z11.coerce.date())
897
- }),
898
- lastUnstakedAt: z11.nullable(z11.coerce.date()),
899
- withdrawAvailableAt: z11.nullable(z11.coerce.date())
900
- });
901
- var StakingLeaderboardPosition = z11.object({
902
- rank: z11.number(),
903
- address: z11.string(),
904
- owner: z11.string(),
905
- staked: AmountWithUsdSchema
906
- });
907
- var StakingLeaderboardPage = z11.object({
908
- data: StakingLeaderboardPosition.array(),
909
- meta: PaginationMeta
910
- });
911
- var StakingPositionHistoryAction = z11.object({
912
- position: z11.string(),
913
- action: StakingPositionHistoryActionTypeSchema,
914
- txSignature: z11.string(),
915
- amount: z11.coerce.bigint(),
916
- time: z11.coerce.date()
917
- });
918
- var PoolPriceCandle = z11.object({
919
- time: z11.number(),
920
- open: z11.number(),
921
- close: z11.number(),
922
- high: z11.number(),
923
- low: z11.number(),
924
- volume: z11.number()
925
- });
926
- var FeesStatsGroup = z11.object({
927
- time: z11.coerce.date(),
928
- addLiquidityFees: z11.number(),
929
- limitOrderFees: z11.number(),
930
- yieldCompoundingFees: z11.number(),
931
- liquidationFees: z11.number(),
932
- totalLiquidationsNetworkFees: z11.number(),
933
- totalLimitOrdersNetworkFees: z11.number(),
934
- totalYieldCompoundingNetworkFees: z11.number(),
935
- failedNetworkFees: z11.number(),
936
- processedNetworkFees: z11.number(),
937
- totalCollectedFees: z11.number(),
938
- totalNetworkFees: z11.number(),
939
- jitoLiquidationFees: z11.number(),
940
- jitoLimitOrderFees: z11.number(),
941
- jitoYieldCompoundingFees: z11.number(),
942
- runningAddLiquidityFees: z11.number(),
943
- runningLimitOrderFees: z11.number(),
944
- runningYieldCompoundingFees: z11.number(),
945
- runningLiquidationFees: z11.number(),
946
- runningTotalLiquidationsNetworkFees: z11.number(),
947
- runningTotalLimitOrdersNetworkFees: z11.number(),
948
- runningTotalYieldCompoundingNetworkFees: z11.number(),
949
- runningFailedNetworkFees: z11.number(),
950
- runningProcessedNetworkFees: z11.number(),
951
- runningJitoLiquidationFees: z11.number(),
952
- runningJitoLimitOrderFees: z11.number(),
953
- runningJitoYieldCompoundingFees: z11.number(),
954
- runningTotalCollectedFees: z11.number(),
955
- runningTotalNetworkFees: z11.number()
956
- });
957
- var StakingRevenueStatsGroup = z11.object({
958
- time: z11.coerce.date(),
959
- totalDepositsUsd: z11.number(),
960
- totalDepositsSol: z11.coerce.bigint(),
961
- runningTotalDepositsUsd: z11.number(),
962
- runningTotalDepositsSol: z11.coerce.bigint()
963
- });
964
- var SwapQuoteByInput = z11.object({
965
- estimatedAmountOut: z11.coerce.bigint(),
966
- minAmountOut: z11.coerce.bigint(),
967
- feeAmount: z11.coerce.bigint(),
968
- feeUsd: z11.number(),
969
- /** Price impact in percents */
970
- priceImpact: z11.number()
971
- });
972
- var SwapQuoteByOutput = z11.object({
973
- estimatedAmountIn: z11.coerce.bigint(),
974
- maxAmountIn: z11.coerce.bigint(),
975
- feeAmount: z11.coerce.bigint(),
976
- feeUsd: z11.number(),
977
- /** Price impact in percents */
978
- priceImpact: z11.number()
979
- });
980
- var LimitOrderQuoteByInput = z11.object({
981
- amountOut: z11.coerce.bigint()
982
- });
983
- var LimitOrderQuoteByOutput = z11.object({
984
- amountIn: z11.coerce.bigint()
985
- });
986
- var TradableAmount = AmountWithUsdSchema;
987
- var UpdateStreamSubscriptionResult = z11.object({
988
- status: z11.string()
989
- });
990
- var createNotificationSchema = (dataSchema, metaSchema) => z11.object({
991
- entity: NotificationEntitySchema,
992
- action: NotificationActionSchema,
993
- data: dataSchema,
994
- id: z11.string(),
995
- authority: z11.nullish(z11.string()),
996
- ...metaSchema ? { meta: metaSchema } : { meta: z11.undefined().nullable() }
997
- });
998
- var PoolSwapNotification = createNotificationSchema(PoolSwap);
999
- var LendingPositionNotification = createNotificationSchema(LendingPosition);
1000
- var TradeHistoryEntryNotification = createNotificationSchema(TradeHistoryEntry);
1001
- var OrderHistoryEntryNotification = createNotificationSchema(OrderHistoryEntry);
1002
- var StakingPositionNotification = createNotificationSchema(StakingPosition);
1003
- var StateSnapshotNotification = createNotificationSchema(StateSnapshot);
1004
-
1005
- // src/client/client.ts
1006
- var DEFAULT_TIMEOUT = 5e3;
1007
- var DEFAULT_HTTP_RETRIES = 3;
1008
- var ProviderFilter = /* @__PURE__ */ ((ProviderFilter2) => {
1009
- ProviderFilter2["ORCA"] = "orca";
1010
- ProviderFilter2["FUSION"] = "fusion";
1011
- ProviderFilter2["ALL"] = "all";
1012
- return ProviderFilter2;
1013
- })(ProviderFilter || {});
1014
- var TunaApiClient = class {
1015
- get baseURL() {
1016
- return this._baseURL;
1017
- }
1018
- get timeout() {
1019
- return this._timeout;
1020
- }
1021
- get httpRetries() {
1022
- return this._httpRetries;
1023
- }
1024
- get headers() {
1025
- return this._headers;
1026
- }
1027
- constructor(baseURL, config) {
1028
- this._baseURL = baseURL;
1029
- this._timeout = config?.timeout ?? DEFAULT_TIMEOUT;
1030
- this._httpRetries = config?.httpRetries ?? DEFAULT_HTTP_RETRIES;
1031
- this._headers = config?.headers ?? {};
1032
- }
1033
- setConfig(config) {
1034
- if (config.baseURL) {
1035
- this._baseURL = config.baseURL;
1036
- }
1037
- this._timeout = config?.timeout ?? DEFAULT_TIMEOUT;
1038
- this._httpRetries = config?.httpRetries ?? DEFAULT_HTTP_RETRIES;
1039
- this._headers = config?.headers ?? {};
1040
- }
1041
- async httpRequest(url, schema, options, retries = this.httpRetries, backoff = 100 + Math.floor(Math.random() * 100)) {
1042
- try {
1043
- const controller = new AbortController();
1044
- const abort = setTimeout(() => {
1045
- controller.abort();
1046
- }, this.timeout);
1047
- const signal = options?.signal || controller.signal;
1048
- const response = await fetch(url, {
1049
- ...options,
1050
- signal,
1051
- headers: { "Content-Type": "application/json", ...this.headers, ...options?.headers }
1052
- });
1053
- clearTimeout(abort);
1054
- if (!response.ok) {
1055
- const errorBody = await response.json();
1056
- throw errorBody;
1057
- }
1058
- const data = await response.json();
1059
- const transformed = camelcaseKeys(data, { deep: true, exclude: ["24h", "7d", "30d"] });
1060
- if (options?.parseRoot) {
1061
- return schema.parse(transformed);
1062
- }
1063
- return schema.parse(transformed.data);
1064
- } catch (error) {
1065
- if (retries > 0 && !(error instanceof Error && error.name === "AbortError")) {
1066
- await new Promise((resolve) => setTimeout(resolve, backoff));
1067
- return this.httpRequest(url, schema, options, retries - 1, backoff * 2);
1068
- }
1069
- throw error;
1070
- }
1071
- }
1072
- /* Endpoints */
1073
- async getMints() {
1074
- const url = this.buildURL("mints");
1075
- return await this.httpRequest(url, Mint.array());
1076
- }
1077
- async getMint(mintAddress) {
1078
- const url = this.buildURL(`mints/${mintAddress}`);
1079
- return await this.httpRequest(url, Mint);
1080
- }
1081
- async getMarkets() {
1082
- const url = this.buildURL("markets");
1083
- return await this.httpRequest(url, Market.array());
1084
- }
1085
- async getMarket(marketAddress) {
1086
- const url = this.buildURL(`markets/${marketAddress}`);
1087
- return await this.httpRequest(url, Market);
1088
- }
1089
- async getOraclePrices() {
1090
- const url = this.buildURL("oracle-prices");
1091
- return await this.httpRequest(url, TokenOraclePrice.array());
1092
- }
1093
- async getOraclePrice(mintAddress) {
1094
- const url = this.buildURL(`oracle-prices/${mintAddress}`);
1095
- return await this.httpRequest(url, TokenOraclePrice);
1096
- }
1097
- async getVaults() {
1098
- const url = this.buildURL("vaults");
1099
- return await this.httpRequest(url, Vault.array());
1100
- }
1101
- async getVault(vaultAddress) {
1102
- const url = this.buildURL(`vaults/${vaultAddress}`);
1103
- return await this.httpRequest(url, Vault);
1104
- }
1105
- /**
1106
- * Returns vault historical data for selected time interval.
1107
- *
1108
- * Example usage: getVaultHistory('H3ifgix98vzi3yCPbmZDLTheeTRf2jykXx8FpY5L7Sfd', '2025-03-10', '2025-04-10')
1109
- */
1110
- async getVaultHistory(vaultAddress, from, to) {
1111
- const url = this.appendUrlSearchParams(this.buildURL(`vaults/${vaultAddress}/history`), {
1112
- from: from.toISOString().slice(0, 10),
1113
- to: to.toISOString().slice(0, 10)
1114
- });
1115
- return await this.httpRequest(url, VaultHistoricalStats.array());
1116
- }
1117
- async getPools(providerFilter) {
1118
- const url = this.appendUrlSearchParams(this.buildURL("pools"), {
1119
- provider: providerFilter && providerFilter !== "all" /* ALL */ ? providerFilter : void 0
1120
- });
1121
- return await this.httpRequest(url, Pool.array());
1122
- }
1123
- async getPool(address) {
1124
- const url = this.buildURL(`pools/${address}`);
1125
- return await this.httpRequest(url, Pool);
1126
- }
1127
- async getPoolTicks(poolAddress) {
1128
- const url = this.buildURL(`pools/${poolAddress}/ticks`);
1129
- return await this.httpRequest(url, PoolTicks);
1130
- }
1131
- async getPoolSwaps(poolAddress) {
1132
- const url = this.buildURL(`pools/${poolAddress}/swaps`);
1133
- return await this.httpRequest(url, PoolSwap.array());
1134
- }
1135
- async getPoolOrderBook(poolAddress, priceStep, inverted) {
1136
- const url = this.appendUrlSearchParams(this.buildURL(`pools/${poolAddress}/order-book`), {
1137
- price_step: priceStep,
1138
- inverted: inverted || void 0
1139
- });
1140
- return await this.httpRequest(url, OrderBook);
1141
- }
1142
- async getPoolPriceCandles(poolAddress, options) {
1143
- const { from, to, interval, candles } = options;
1144
- const url = this.appendUrlSearchParams(this.buildURL(`pools/${poolAddress}/candles`), {
1145
- from: from.toISOString(),
1146
- to: to.toISOString(),
1147
- candles,
1148
- interval
1149
- });
1150
- return await this.httpRequest(url, PoolPriceCandle.array());
1151
- }
1152
- async getStakingTreasury() {
1153
- const url = this.buildURL(`staking/treasury`);
1154
- return await this.httpRequest(url, StakingTreasury);
1155
- }
1156
- async getStakingLeaderboard(page, pageSize, search) {
1157
- const url = this.appendUrlSearchParams(this.buildURL(`staking/leaderboard`), {
1158
- page,
1159
- page_size: pageSize,
1160
- search: search || void 0
1161
- });
1162
- return await this.httpRequest(url, StakingLeaderboardPage, { parseRoot: true });
1163
- }
1164
- async getUserLendingPositions(userAddress) {
1165
- const url = this.buildURL(`users/${userAddress}/lending-positions`);
1166
- return await this.httpRequest(url, LendingPosition.array());
1167
- }
1168
- async getUserLendingPositionByAddress(userAddress, lendingPositionAddress) {
1169
- const url = this.buildURL(`users/${userAddress}/lending-positions/${lendingPositionAddress}`);
1170
- return await this.httpRequest(url, LendingPosition);
1171
- }
1172
- async getUserTunaPositions(userAddress) {
1173
- const url = this.buildURL(`users/${userAddress}/tuna-positions`);
1174
- return await this.httpRequest(url, TunaLpPositionDtoSchema.array());
1175
- }
1176
- async getUserTunaPositionByAddress(userAddress, tunaPositionAddress) {
1177
- const url = this.buildURL(`users/${userAddress}/tuna-positions/${tunaPositionAddress}`);
1178
- return await this.httpRequest(url, TunaLpPositionDtoSchema);
1179
- }
1180
- async getUserLpPositions(userAddress, options) {
1181
- const query = {};
1182
- if (options) {
1183
- if (options.filter) {
1184
- query.filter = options.filter;
1185
- }
1186
- if (options.afterPosition) {
1187
- query.after_position = options.afterPosition;
1188
- }
1189
- if (options.openedAt) {
1190
- if (options.openedAt.from) {
1191
- query.opened_at_min = options.openedAt.from.toISOString();
1192
- }
1193
- if (options.openedAt.to) {
1194
- query.opened_at_max = options.openedAt.to.toISOString();
1195
- }
1196
- }
1197
- if (options.closedAt) {
1198
- if (options.closedAt.from) {
1199
- query.closed_at_min = options.closedAt.from.toISOString();
1200
- }
1201
- if (options.closedAt.to) {
1202
- query.closed_at_max = options.closedAt.to.toISOString();
1203
- }
1204
- }
1205
- }
1206
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/lp-positions`), query);
1207
- return await this.httpRequest(url, TunaLpPositionHistorical.array());
1208
- }
1209
- async getUserLpPositionActions(userAddress, positionAddress) {
1210
- const url = this.buildURL(`users/${userAddress}/lp-positions/${positionAddress}/actions`);
1211
- return await this.httpRequest(url, TunaLpPositionAction.array());
1212
- }
1213
- async getUserTunaSpotPositions(userAddress) {
1214
- const url = this.buildURL(`users/${userAddress}/spot-positions`);
1215
- return await this.httpRequest(url, TunaSpotPosition.array());
1216
- }
1217
- async getUserTunaSpotPositionByAddress(userAddress, tunaSpotPositionAddress) {
1218
- const url = this.buildURL(`users/${userAddress}/spot-positions/${tunaSpotPositionAddress}`);
1219
- return await this.httpRequest(url, TunaSpotPosition);
1220
- }
1221
- async getUserLimitOrders(userAddress, options) {
1222
- const query = {};
1223
- if (options) {
1224
- if (options.pool?.length) {
1225
- query.pool = options.pool.join(",");
1226
- }
1227
- if (options.status?.length) {
1228
- query.status = options.status.join(",");
1229
- }
1230
- if (options.openedAt?.from) {
1231
- query.opened_at_from = options.openedAt.from.toISOString();
1232
- }
1233
- if (options.openedAt?.to) {
1234
- query.opened_at_from = options.openedAt.to.toISOString();
1235
- }
1236
- if (options.limit) {
1237
- query.limit = options.limit;
1238
- }
1239
- if (options.cursor) {
1240
- query.cursor = options.cursor;
1241
- }
1242
- if (options.desc !== void 0) {
1243
- query.desc = options.desc;
1244
- }
1245
- }
1246
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/limit-orders`), query);
1247
- return await this.httpRequest(url, LimitOrder.array());
1248
- }
1249
- async getUserLimitOrderByAddress(userAddress, limitOrderAddress) {
1250
- const url = this.buildURL(`users/${userAddress}/limit-orders/${limitOrderAddress}`);
1251
- return await this.httpRequest(url, LimitOrder);
1252
- }
1253
- async getUserTradeHistory(userAddress, options) {
1254
- const query = {};
1255
- if (options) {
1256
- if (options.pool?.length) {
1257
- query.pool = options.pool.join(",");
1258
- }
1259
- if (options.action?.length) {
1260
- query.action = options.action.join(",");
1261
- }
1262
- if (options.uiDirection?.length) {
1263
- query.ui_direction = options.uiDirection.join(",");
1264
- }
1265
- if (options.limit) {
1266
- query.limit = options.limit;
1267
- }
1268
- if (options.cursor) {
1269
- query.cursor = options.cursor;
1270
- }
1271
- if (options.desc !== void 0) {
1272
- query.desc = options.desc;
1273
- }
1274
- }
1275
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/trade-history`), query);
1276
- return await this.httpRequest(url, TradeHistoryEntry.array());
1277
- }
1278
- async getUserOrderHistory(userAddress, options) {
1279
- const query = {};
1280
- if (options) {
1281
- if (options.pool?.length) {
1282
- query.pool = options.pool.join(",");
1283
- }
1284
- if (options.orderType?.length) {
1285
- query.order_type = options.orderType.join(",");
1286
- }
1287
- if (options.uiDiretion?.length) {
1288
- query.ui_direction = options.uiDiretion.join(",");
1289
- }
1290
- if (options.limit) {
1291
- query.limit = options.limit;
1292
- }
1293
- if (options.cursor) {
1294
- query.cursor = options.cursor;
1295
- }
1296
- if (options.desc !== void 0) {
1297
- query.desc = options.desc;
1298
- }
1299
- }
1300
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/order-history`), query);
1301
- return await this.httpRequest(url, OrderHistoryEntry.array());
1302
- }
1303
- async getUserStakingPosition(userAddress) {
1304
- const url = this.buildURL(`users/${userAddress}/staking-position`);
1305
- return await this.httpRequest(url, StakingPosition);
1306
- }
1307
- async getUserStakingPositionHistory(userAddress) {
1308
- const url = this.buildURL(`users/${userAddress}/staking-position/history`);
1309
- return await this.httpRequest(url, StakingPositionHistoryAction.array());
1310
- }
1311
- async getFeesStats(from, to, interval) {
1312
- const url = this.appendUrlSearchParams(this.buildURL(`stats/fees`), {
1313
- from: from.toISOString(),
1314
- to: to.toISOString(),
1315
- interval
1316
- });
1317
- return await this.httpRequest(url, FeesStatsGroup.array());
1318
- }
1319
- async getStakingRevenueStats(from, to) {
1320
- const url = this.appendUrlSearchParams(this.buildURL(`stats/staking/revenue`), {
1321
- from: from.toISOString().split("T")[0],
1322
- to: to.toISOString().split("T")[0]
1323
- });
1324
- return await this.httpRequest(url, StakingRevenueStatsGroup.array());
1325
- }
1326
- async getLimitOrderQuoteByInput(args, config) {
1327
- const { pool, amountIn, aToB, tickIndex } = args;
1328
- const query = {
1329
- pool,
1330
- amount_in: amountIn.toString(),
1331
- a_to_b: aToB,
1332
- tick_index: tickIndex
1333
- };
1334
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/limit-order-by-input`), query);
1335
- return await this.httpRequest(url, LimitOrderQuoteByInput, {
1336
- signal: config?.abortSignal
1337
- });
1338
- }
1339
- async getLimitOrderQuoteByOutput(args, config) {
1340
- const { pool, amountOut, aToB, tickIndex } = args;
1341
- const query = {
1342
- pool,
1343
- amount_out: amountOut.toString(),
1344
- a_to_b: aToB,
1345
- tick_index: tickIndex
1346
- };
1347
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/limit-order-by-output`), query);
1348
- return await this.httpRequest(url, LimitOrderQuoteByOutput, {
1349
- signal: config?.abortSignal
1350
- });
1351
- }
1352
- async getSwapQuoteByInput(args, config) {
1353
- const { pool, amountIn, aToB, slippageToleranceBps } = args;
1354
- const query = {
1355
- pool,
1356
- amount_in: amountIn.toString(),
1357
- a_to_b: aToB
1358
- };
1359
- if (slippageToleranceBps) {
1360
- query.slippage_tolerance = slippageToleranceBps;
1361
- }
1362
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/swap-by-input`), query);
1363
- return await this.httpRequest(url, SwapQuoteByInput, {
1364
- signal: config?.abortSignal
1365
- });
1366
- }
1367
- async getSwapQuoteByOutput(args, config) {
1368
- const { pool, amountOut, aToB, slippageToleranceBps } = args;
1369
- const query = {
1370
- pool,
1371
- amount_out: amountOut.toString(),
1372
- a_to_b: aToB
1373
- };
1374
- if (slippageToleranceBps) {
1375
- query.slippage_tolerance = slippageToleranceBps;
1376
- }
1377
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/swap-by-output`), query);
1378
- return await this.httpRequest(url, SwapQuoteByOutput, {
1379
- signal: config?.abortSignal
1380
- });
1381
- }
1382
- async getIncreaseSpotPositionQuote(args, config) {
1383
- const {
1384
- market,
1385
- increaseAmount,
1386
- collateralToken,
1387
- positionToken,
1388
- leverage,
1389
- positionAmount,
1390
- positionDebt,
1391
- slippageTolerance
1392
- } = args;
1393
- const query = {
1394
- market,
1395
- increase_amount: increaseAmount.toString(),
1396
- collateral_token: collateralToken,
1397
- position_token: positionToken,
1398
- leverage
1399
- };
1400
- if (slippageTolerance) {
1401
- query.slippage_tolerance = slippageTolerance;
1402
- }
1403
- if (positionAmount) {
1404
- query.position_amount = positionAmount.toString();
1405
- }
1406
- if (positionDebt) {
1407
- query.position_debt = positionDebt.toString();
1408
- }
1409
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/increase-spot-position`), query);
1410
- return await this.httpRequest(url, IncreaseSpotPositionQuote, {
1411
- signal: config?.abortSignal
1412
- });
1413
- }
1414
- async getDecreaseSpotPositionQuote(args, config) {
1415
- const {
1416
- market,
1417
- decreaseAmount,
1418
- collateralToken,
1419
- positionToken,
1420
- leverage,
1421
- positionAmount,
1422
- positionDebt,
1423
- slippageTolerance
1424
- } = args;
1425
- const query = {
1426
- market,
1427
- decrease_amount: decreaseAmount.toString(),
1428
- collateral_token: collateralToken,
1429
- position_token: positionToken,
1430
- leverage,
1431
- position_amount: positionAmount.toString(),
1432
- position_debt: positionDebt.toString()
1433
- };
1434
- if (slippageTolerance) {
1435
- query.slippage_tolerance = slippageTolerance;
1436
- }
1437
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/decrease-spot-position`), query);
1438
- return await this.httpRequest(url, DecreaseSpotPositionQuote, {
1439
- signal: config?.abortSignal
1440
- });
1441
- }
1442
- async getCloseSpotPositionQuote(args, config) {
1443
- const { market, decreasePercent, collateralToken, positionToken, positionAmount, positionDebt, slippageTolerance } = args;
1444
- const query = {
1445
- market,
1446
- decrease_percent: decreasePercent,
1447
- collateral_token: collateralToken,
1448
- position_token: positionToken,
1449
- position_amount: positionAmount.toString(),
1450
- position_debt: positionDebt.toString()
1451
- };
1452
- if (slippageTolerance) {
1453
- query.slippage_tolerance = slippageTolerance;
1454
- }
1455
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/close-spot-position`), query);
1456
- return await this.httpRequest(url, CloseSpotPositionQuote, {
1457
- signal: config?.abortSignal
1458
- });
1459
- }
1460
- async getTradableAmount(args, config) {
1461
- const { market, collateralToken, positionToken, availableBalance, leverage, positionAmount, increase } = args;
1462
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/tradable-amount`), {
1463
- market,
1464
- collateral_token: collateralToken,
1465
- position_token: positionToken,
1466
- available_balance: availableBalance.toString(),
1467
- leverage,
1468
- position_amount: positionAmount.toString(),
1469
- increase
1470
- });
1471
- return await this.httpRequest(url, TradableAmount, {
1472
- signal: config?.abortSignal
1473
- });
1474
- }
1475
- async getUpdatesStream() {
1476
- const url = this.buildURL(`streams/sse`);
1477
- return new EventSource(url);
1478
- }
1479
- async updateStreamSubscription(streamId, subscription) {
1480
- const url = this.buildURL(`streams/${streamId}/subscription`);
1481
- const body = JSON.stringify(snakecaseKeys(subscription, { deep: true }));
1482
- return await this.httpRequest(url, UpdateStreamSubscriptionResult, { method: "PUT", body });
1483
- }
1484
- /* Utility functions */
1485
- buildURL(endpoint) {
1486
- return `${this.baseURL}${this.baseURL.endsWith("/") ? "" : "/"}v1/${endpoint}`;
1487
- }
1488
- appendUrlSearchParams(url, params) {
1489
- const urlSearchParams = new URLSearchParams();
1490
- Object.entries(params).forEach(([key, value]) => {
1491
- if (value !== void 0) {
1492
- urlSearchParams.append(key, String(value));
1493
- }
1494
- });
1495
- if (urlSearchParams.size > 0) {
1496
- return `${url}?${urlSearchParams.toString()}`;
1497
- }
1498
- return url;
1499
- }
1500
- };
1501
- export {
1502
- NotificationAction,
1503
- NotificationEntity,
1504
- PoolProvider,
1505
- PoolSubscriptionTopic,
1506
- ProviderFilter,
1507
- TunaApiClient,
1508
- TunaPositionState,
1509
- WalletSubscriptionTopic,
1510
- schemas_exports as schemas
1511
- };