@strkfarm/sdk 2.0.0-dev.35 → 2.0.0-dev.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/cli.js +2 -2
  2. package/dist/cli.mjs +2 -2
  3. package/dist/index.browser.global.js +19596 -28786
  4. package/dist/index.browser.mjs +8559 -17931
  5. package/dist/index.d.ts +578 -2746
  6. package/dist/index.js +8649 -18059
  7. package/dist/index.mjs +8577 -17949
  8. package/package.json +3 -3
  9. package/src/data/universal-vault.abi.json +8 -7
  10. package/src/dataTypes/bignumber.browser.ts +5 -1
  11. package/src/dataTypes/bignumber.node.ts +5 -0
  12. package/src/global.ts +21 -1
  13. package/src/interfaces/common.tsx +39 -4
  14. package/src/modules/avnu.ts +19 -10
  15. package/src/modules/index.ts +1 -1
  16. package/src/strategies/base-strategy.ts +92 -8
  17. package/src/strategies/constants.ts +8 -3
  18. package/src/strategies/ekubo-cl-vault.tsx +150 -16
  19. package/src/strategies/factory.ts +21 -1
  20. package/src/strategies/index.ts +2 -7
  21. package/src/strategies/registry.ts +28 -5
  22. package/src/strategies/sensei.ts +29 -13
  23. package/src/strategies/svk-strategy.ts +26 -2
  24. package/src/strategies/token-boosted-xstrk-carry-strategy.tsx +1223 -0
  25. package/src/strategies/universal-adapters/avnu-adapter.ts +16 -8
  26. package/src/strategies/universal-adapters/index.ts +1 -2
  27. package/src/strategies/universal-adapters/svk-troves-adapter.ts +19 -6
  28. package/src/strategies/universal-adapters/vesu-modify-position-adapter.ts +22 -3
  29. package/src/strategies/universal-adapters/vesu-multiply-adapter.ts +75 -52
  30. package/src/strategies/universal-adapters/vesu-position-common.ts +38 -31
  31. package/src/strategies/universal-lst-muliplier-strategy.tsx +222 -269
  32. package/src/strategies/universal-strategy.tsx +166 -105
  33. package/src/strategies/vesu-rebalance.tsx +3 -6
  34. package/src/strategies/yoloVault.ts +1084 -0
  35. package/src/utils/health-factor-math.ts +29 -0
  36. package/src/modules/ExtendedWrapperSDk/index.ts +0 -62
  37. package/src/modules/ExtendedWrapperSDk/types.ts +0 -334
  38. package/src/modules/ExtendedWrapperSDk/wrapper.ts +0 -611
  39. package/src/strategies/universal-adapters/extended-adapter.ts +0 -860
  40. package/src/strategies/universal-adapters/usdc<>usdce-adapter.ts +0 -200
  41. package/src/strategies/usdc-boosted-strategy.tsx +0 -693
  42. package/src/strategies/vesu-extended-strategy/services/executionService.ts +0 -2234
  43. package/src/strategies/vesu-extended-strategy/services/extended-vesu-state-manager.ts +0 -4254
  44. package/src/strategies/vesu-extended-strategy/services/ltv-imbalance-rebalance-math.ts +0 -783
  45. package/src/strategies/vesu-extended-strategy/services/operationService.ts +0 -56
  46. package/src/strategies/vesu-extended-strategy/types/transaction-metadata.ts +0 -88
  47. package/src/strategies/vesu-extended-strategy/utils/config.runtime.ts +0 -78
  48. package/src/strategies/vesu-extended-strategy/utils/constants.ts +0 -48
  49. package/src/strategies/vesu-extended-strategy/utils/helper.ts +0 -528
  50. package/src/strategies/vesu-extended-strategy/vesu-extended-strategy.tsx +0 -1014
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as starknet from 'starknet';
2
- import { RpcProvider, BlockIdentifier, Call, Contract, Uint256, Account, CairoCustomEnum, RawArgs } from 'starknet';
2
+ import { Uint256, RpcProvider, BlockIdentifier, Call, Contract, Account, CairoCustomEnum, RawArgs } from 'starknet';
3
3
  import BigNumber from 'bignumber.js';
4
4
  import React, { ReactNode } from 'react';
5
5
  import { Quote, AvnuOptions } from '@avnu/avnu-sdk';
@@ -38,6 +38,7 @@ declare class _Web3Number<T extends _Web3Number<T>> extends BigNumber {
38
38
  declare class Web3Number extends _Web3Number<Web3Number> {
39
39
  static fromWei(weiNumber: string | number, decimals: number): Web3Number;
40
40
  static fromNumber(number: number, decimals: number): Web3Number;
41
+ static fromUint256(uint256Value: Uint256): Web3Number;
41
42
  }
42
43
 
43
44
  /**
@@ -127,6 +128,10 @@ interface IProtocol {
127
128
  name: string;
128
129
  logo: string;
129
130
  }
131
+ interface ICurator {
132
+ name: string;
133
+ logo: string;
134
+ }
130
135
  declare enum StrategyTag {
131
136
  META_VAULT = "Meta Vaults",
132
137
  LEVERED = "Maxx",
@@ -137,7 +142,8 @@ declare enum VaultType {
137
142
  LOOPING = "Looping",
138
143
  META_VAULT = "Meta Vault",
139
144
  DELTA_NEUTRAL = "Delta Neutral",
140
- AUTOMATED_LP = "Automated LP"
145
+ AUTOMATED_LP = "Automated LP",
146
+ TVA = "Troves Value Averaging"
141
147
  }
142
148
  declare enum AuditStatus {
143
149
  AUDITED = "Audited",
@@ -149,7 +155,8 @@ declare enum SourceCodeType {
149
155
  }
150
156
  declare enum AccessControlType {
151
157
  MULTISIG_ACCOUNT = "Multisig Account",
152
- STANDARD_ACCOUNT = "Standard Account"
158
+ STANDARD_ACCOUNT = "Standard Account",
159
+ ROLE_BASED_ACCESS = "Role Based Access"
153
160
  }
154
161
  declare enum InstantWithdrawalVault {
155
162
  YES = "Yes",
@@ -162,7 +169,7 @@ interface SourceCodeInfo {
162
169
  interface AccessControlInfo {
163
170
  type: AccessControlType;
164
171
  addresses: ContractAddr[];
165
- timeLock: string;
172
+ timeLock?: string;
166
173
  }
167
174
  interface SecurityMetadata {
168
175
  auditStatus: AuditStatus;
@@ -215,6 +222,10 @@ interface StrategySettings {
215
222
  alerts?: StrategyAlert[];
216
223
  tags?: StrategyTag[];
217
224
  }
225
+ interface StrategyApyHistoryUIConfig {
226
+ showApyHistory?: boolean;
227
+ noApyHistoryMessage?: string;
228
+ }
218
229
  /**
219
230
  * @property risk.riskFactor.factor - The risk factors that are considered for the strategy.
220
231
  * @property risk.riskFactor.factor - The value of the risk factor from 0 to 10, 0 being the lowest and 10 being the highest.
@@ -225,6 +236,19 @@ interface IStrategyMetadata<T> {
225
236
  id: string;
226
237
  name: string;
227
238
  description: string | React.ReactNode;
239
+ /**
240
+ * Optional UI sort priority. Higher shows earlier.
241
+ * Intended for pinning flagship parent vaults (e.g. BTC above STRK).
242
+ */
243
+ priority?: number;
244
+ /**
245
+ * Optional UI config for the variant intro popup (strategy page).
246
+ * Should be identical across strategies that share the same `parentId`.
247
+ */
248
+ variantIntro?: {
249
+ title: string;
250
+ description: string;
251
+ };
228
252
  address: ContractAddr;
229
253
  launchBlock: number;
230
254
  type: "ERC4626" | "ERC721" | "Other";
@@ -241,7 +265,7 @@ interface IStrategyMetadata<T> {
241
265
  notARisks: RiskType[];
242
266
  };
243
267
  apyMethodology?: string;
244
- realizedAPYMethodology?: string;
268
+ realizedApyMethodology?: string;
245
269
  additionalInfo: T;
246
270
  contractDetails: {
247
271
  address: ContractAddr;
@@ -256,10 +280,7 @@ interface IStrategyMetadata<T> {
256
280
  }[];
257
281
  docs?: string;
258
282
  investmentSteps: string[];
259
- curator?: {
260
- name: string;
261
- logo: string;
262
- };
283
+ curator?: ICurator;
263
284
  isPreview?: boolean;
264
285
  tags?: StrategyTag[];
265
286
  security: SecurityMetadata;
@@ -272,6 +293,7 @@ interface IStrategyMetadata<T> {
272
293
  info?: React.ReactNode | string;
273
294
  };
274
295
  settings?: StrategySettings;
296
+ apyHistoryUIConfig?: StrategyApyHistoryUIConfig;
275
297
  actions?: Array<{
276
298
  name?: string;
277
299
  pool?: {
@@ -291,6 +313,8 @@ interface IStrategyMetadata<T> {
291
313
  amount?: string | number;
292
314
  isDeposit?: boolean;
293
315
  }>;
316
+ parentId?: string;
317
+ parentName?: string;
294
318
  }
295
319
  interface IInvestmentFlow {
296
320
  id?: string;
@@ -351,6 +375,7 @@ declare const Protocols: {
351
375
  VAULT: IProtocol;
352
376
  TROVES: IProtocol;
353
377
  };
378
+ declare const UnwrapLabsCurator: ICurator;
354
379
 
355
380
  interface ILendingMetadata {
356
381
  name: string;
@@ -496,6 +521,8 @@ interface DualTokenInfo {
496
521
  token0: SingleTokenInfo;
497
522
  token1: SingleTokenInfo;
498
523
  }
524
+ type StrategyInputMode = "single" | "dual";
525
+ type InputModeFromAction<T> = T extends DualActionAmount ? "dual" : "single";
499
526
  interface NetAPYSplit {
500
527
  apy: number;
501
528
  id: string;
@@ -504,23 +531,55 @@ interface NetAPYDetails {
504
531
  net: number;
505
532
  splits: NetAPYSplit[];
506
533
  }
534
+ type UserPositionCardSubValueColor = "default" | "positive" | "negative" | "info";
535
+ interface UserPositionCard {
536
+ title: string;
537
+ value: string;
538
+ tooltip?: string;
539
+ subValue?: string;
540
+ subValueColor?: UserPositionCardSubValueColor;
541
+ }
542
+ interface UserPositionCardsInput {
543
+ user: ContractAddr;
544
+ investmentFlows?: Array<{
545
+ amount: string;
546
+ type: string;
547
+ timestamp: number;
548
+ tx_hash: string;
549
+ }>;
550
+ usualTimeToEarnings?: string | null;
551
+ usualTimeToEarningsDescription?: string | null;
552
+ }
507
553
  interface CacheData {
508
554
  timestamp: number;
509
555
  ttl: number;
510
556
  data: any;
511
557
  }
512
- declare class BaseStrategy<TVLInfo, ActionInfo> extends CacheClass {
558
+ declare class BaseStrategy<TVLInfo, DepositActionInfo, WithdrawActionInfo = DepositActionInfo> extends CacheClass {
513
559
  readonly config: IConfig;
514
560
  readonly cache: Map<string, CacheData>;
515
- constructor(config: IConfig);
561
+ private readonly _depositInputMode;
562
+ private readonly _withdrawInputMode;
563
+ constructor(config: IConfig, inputModes?: {
564
+ depositInputMode?: InputModeFromAction<DepositActionInfo>;
565
+ withdrawInputMode?: InputModeFromAction<WithdrawActionInfo>;
566
+ });
567
+ depositInputMode(): InputModeFromAction<DepositActionInfo>;
568
+ withdrawInputMode(): InputModeFromAction<WithdrawActionInfo>;
516
569
  getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<TVLInfo>;
517
570
  getTVL(): Promise<TVLInfo>;
518
- depositCall(amountInfo: ActionInfo, receiver: ContractAddr): Promise<Call[]>;
519
- withdrawCall(amountInfo: ActionInfo, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]>;
571
+ depositCall(amountInfo: DepositActionInfo, receiver: ContractAddr): Promise<Call[]>;
572
+ withdrawCall(amountInfo: WithdrawActionInfo, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]>;
520
573
  getVaultPositions(): Promise<VaultPosition[]>;
521
- netAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number, timeperiod?: "24h" | "7d" | "30d" | "3m"): Promise<number | NetAPYDetails>;
574
+ netAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number, timeperiod?: "24h" | "7d" | "30d" | "3m"): Promise<number | string | NetAPYDetails>;
522
575
  getPendingRewards(): Promise<HarvestInfo[]>;
523
576
  getUserRealizedAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number): Promise<number>;
577
+ getUserPositionCards(_input: UserPositionCardsInput): Promise<UserPositionCard[]>;
578
+ getMaxTVL(): Promise<Web3Number>;
579
+ protected formatTokenAmountForCard(amount: Web3Number, tokenInfo: TokenInfo): string;
580
+ protected formatPercentForCard(value: number): string;
581
+ protected formatUSDForCard(value: number): string;
582
+ protected getSubValueColorFromSignedNumber(value: number): UserPositionCardSubValueColor;
524
583
  /**
525
584
  * Calculate lifetime earnings for a user based on provided data from client
526
585
  * Formula: lifetimeEarnings = currentValue + totalWithdrawals - totalDeposits
@@ -690,7 +749,7 @@ declare class AvnuWrapper {
690
749
  getQuotes(fromToken: string, toToken: string, amountWei: string, taker: string, retry?: number, excludeSources?: string[]): Promise<Quote>;
691
750
  getSwapInfo(quote: Pick<Quote, 'quoteId' | 'buyTokenAddress' | 'buyAmount' | 'sellTokenAddress' | 'sellAmount'>, taker: string, integratorFeeBps: number, integratorFeeRecipient: string, minAmount?: string, options?: AvnuOptions): Promise<SwapInfo>;
692
751
  static buildZeroSwap(tokenToSell: ContractAddr, beneficiary: string, tokenToBuy?: ContractAddr): SwapInfo;
693
- getSwapCallData(quote: Pick<Quote, 'quoteId' | 'buyTokenAddress' | 'buyAmount' | 'sellTokenAddress' | 'sellAmount'>, taker: string): Promise<bigint[][]>;
752
+ getSwapCallData(quote: Pick<Quote, 'quoteId' | 'buyTokenAddress' | 'buyAmount' | 'sellTokenAddress' | 'sellAmount'>, taker: string, minAmount?: Web3Number): Promise<bigint[][]>;
694
753
  }
695
754
 
696
755
  declare class AutoCompounderSTRK {
@@ -1029,6 +1088,8 @@ declare class EkuboCLVault extends BaseStrategy<DualTokenInfo, DualActionAmount>
1029
1088
  * regardless of quote asset configuration.
1030
1089
  */
1031
1090
  getUserRealizedAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number): Promise<number>;
1091
+ getMaxTVL(): Promise<Web3Number>;
1092
+ getUserPositionCards(input: UserPositionCardsInput): Promise<UserPositionCard[]>;
1032
1093
  feeBasedAPY(timeperiod?: '24h' | '7d' | '30d' | '3m'): Promise<number>;
1033
1094
  /**
1034
1095
  * Calculates assets before and now in a given token of TVL per share to observe growth
@@ -1241,9 +1302,105 @@ declare class SenseiVault extends BaseStrategy<SingleTokenInfo, SingleActionAmou
1241
1302
  * Not implemented for Sensei Strategy yet.
1242
1303
  */
1243
1304
  getUserRealizedAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number): Promise<number>;
1305
+ getUserPositionCards(_input: UserPositionCardsInput): Promise<UserPositionCard[]>;
1244
1306
  }
1245
1307
  declare const SenseiStrategies: IStrategyMetadata<SenseiVaultSettings>[];
1246
1308
 
1309
+ interface YoloVaultSettings {
1310
+ startDate: string;
1311
+ expiryDate: string;
1312
+ mainToken: TokenInfo;
1313
+ secondaryToken: TokenInfo;
1314
+ totalEpochs: number;
1315
+ minEpochDurationSeconds: number;
1316
+ spendingLevels: YoloSpendingLevel[];
1317
+ feeBps: number;
1318
+ /** When true, base token is ERC-4626 (e.g. vUSDC); amounts for TVL / user info use `convert_to_assets` into `baseUnderlying`. */
1319
+ isBaseERC4626?: boolean;
1320
+ /** When true, second token is ERC-4626 (e.g. xSTRK); amounts use `convert_to_assets` into `secondUnderlying`. */
1321
+ isSecondERC4626?: boolean;
1322
+ /** Required when `isBaseERC4626` is true (e.g. USDC). */
1323
+ baseUnderlying?: TokenInfo;
1324
+ /** Required when `isSecondERC4626` is true (e.g. STRK / WBTC for xSTRK / xWBTC). */
1325
+ secondUnderlying?: TokenInfo;
1326
+ }
1327
+ interface YoloSpendingLevel {
1328
+ minPrice?: number;
1329
+ maxPrice?: number;
1330
+ spendPercent: number;
1331
+ }
1332
+ interface UserYoloInfo {
1333
+ shares: bigint;
1334
+ claimable_second_tokens: bigint;
1335
+ base_token_balance: bigint;
1336
+ base_token_consumed: bigint;
1337
+ base_consumed_last_index: bigint;
1338
+ second_token_last_index: bigint;
1339
+ second_token_balance: bigint;
1340
+ }
1341
+ interface YoloVaultStatus {
1342
+ current_epoch: bigint;
1343
+ total_epochs: bigint;
1344
+ remaining_base: bigint;
1345
+ total_second_tokens: bigint;
1346
+ global_second_token_index: bigint;
1347
+ cumulative_spend_index: bigint;
1348
+ total_shares: bigint;
1349
+ base_token_assets_per_share: bigint;
1350
+ }
1351
+ interface YoloSettings {
1352
+ base_token: bigint;
1353
+ second_token: bigint;
1354
+ total_epochs: bigint;
1355
+ min_time_per_epoch: bigint;
1356
+ max_spend_units_per_epoch: bigint;
1357
+ base_token_assets_per_share: bigint;
1358
+ oracle: bigint;
1359
+ }
1360
+ type YoloErc4626RuntimeConfig = {
1361
+ isBaseERC4626: boolean;
1362
+ isSecondERC4626: boolean;
1363
+ baseUnderlying?: TokenInfo;
1364
+ secondUnderlying?: TokenInfo;
1365
+ };
1366
+ declare class YoLoVault extends BaseStrategy<DualTokenInfo, SingleActionAmount, DualActionAmount> {
1367
+ readonly address: ContractAddr;
1368
+ readonly metadata: IStrategyMetadata<YoloVaultSettings>;
1369
+ readonly pricer: PricerBase;
1370
+ /** Resolves to a `Contract` built from `provider.getClassAt` at the vault address (no checked-in vault ABI). */
1371
+ readonly contract: Promise<Contract>;
1372
+ readonly primaryToken: TokenInfo;
1373
+ readonly secondaryToken: TokenInfo;
1374
+ readonly erc4626: YoloErc4626RuntimeConfig;
1375
+ constructor(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<YoloVaultSettings>);
1376
+ /** Underlying (or base token) used for pricing / swap sell leg when base is ERC-4626. */
1377
+ tokenForPrimaryPricing(): TokenInfo;
1378
+ /** Underlying (or second token) for price ratios when second leg is ERC-4626 (e.g. STRK for xSTRK). */
1379
+ tokenForSecondaryPricing(): TokenInfo;
1380
+ private primaryAmountDecimals;
1381
+ private secondaryAmountDecimals;
1382
+ private convertWrapperSharesToUnderlying;
1383
+ private getNormalizedUserInfo;
1384
+ private resolveWithdrawRequest;
1385
+ getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<DualTokenInfo>;
1386
+ getVaultPositions(): Promise<VaultPosition[]>;
1387
+ getTVL(): Promise<DualTokenInfo>;
1388
+ depositCall(amountInfo: SingleActionAmount, receiver: ContractAddr): Promise<Call[]>;
1389
+ getVaultStatus(): Promise<YoloVaultStatus>;
1390
+ matchInputAmounts(amountInfo: DualActionAmount, user: ContractAddr): Promise<DualActionAmount>;
1391
+ withdrawCall(amountInfo: DualActionAmount, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]>;
1392
+ netAPY(): Promise<number | string | NetAPYDetails>;
1393
+ getSwapAmounts(spendUnits: Web3Number): Promise<{
1394
+ grossSpend: Web3Number;
1395
+ netSpend: Web3Number;
1396
+ isReadyForNextSwap: boolean;
1397
+ }>;
1398
+ getSettings: () => Promise<YoloSettings>;
1399
+ getMaxTVL(): Promise<Web3Number>;
1400
+ getUserPositionCards(input: UserPositionCardsInput): Promise<UserPositionCard[]>;
1401
+ }
1402
+ declare const YoloVaultStrategies: IStrategyMetadata<YoloVaultSettings>[];
1403
+
1247
1404
  interface LeveledLogMethod {
1248
1405
  (message: string, ...meta: any[]): void;
1249
1406
  (message: any): void;
@@ -1383,6 +1540,11 @@ declare class HealthFactorMath {
1383
1540
  static getHealthFactor(collateralAmount: Web3Number, collateralPrice: number, maxLTV: number, debtAmount: Web3Number, debtPrice: number): number;
1384
1541
  static getMaxDebtAmountOnLooping(collateralAmount: Web3Number, collateralPrice: number, maxLTV: number, targetHF: number, debtPrice: number, debtTokenInfo: TokenInfo): Web3Number;
1385
1542
  static getMaxDebtAmount(collateralAmount: Web3Number, collateralPrice: number, maxLTV: number, targetHF: number, debtPrice: number, debtTokenInfo: TokenInfo): Web3Number;
1543
+ static calculateDebtReductionAmountForWithdrawal: (debtAmount: Web3Number, collateralAmount: Web3Number, maxLtv: number, targetHF: number, withdrawalAmount: Web3Number, collateralPrice: number, debtPrice: number, collateralTokenInfo: TokenInfo, debtTokenInfo: TokenInfo) => {
1544
+ deltadebtAmountUnits: null;
1545
+ } | {
1546
+ deltadebtAmountUnits: Web3Number;
1547
+ };
1386
1548
  }
1387
1549
 
1388
1550
  type RequiredFields<T> = {
@@ -1869,6 +2031,7 @@ declare class VesuMultiplyAdapter extends BaseAdapter<VesuDepositParams, VesuWit
1869
2031
  protected getAPY(supportedPosition: SupportedPosition): Promise<PositionAPY>;
1870
2032
  protected getPosition(supportedPosition: SupportedPosition): Promise<PositionAmount | null>;
1871
2033
  maxBorrowableAPY(): Promise<number>;
2034
+ private _computeMax;
1872
2035
  maxDeposit(amount?: Web3Number): Promise<PositionInfo>;
1873
2036
  maxWithdraw(): Promise<PositionInfo>;
1874
2037
  protected _getDepositLeaf(): {
@@ -1972,576 +2135,6 @@ declare class VesuModifyPositionAdapter extends BaseAdapter<VesuModifyPositionDe
1972
2135
  getExpectedWithdrawDebtDelta(withdrawAmount: Web3Number): Promise<Web3Number>;
1973
2136
  }
1974
2137
 
1975
- /**
1976
- * TypeScript type definitions for Extended Exchange API
1977
- * Based on Python SDK models from x10.perpetual
1978
- */
1979
- declare enum OrderSide {
1980
- BUY = "BUY",
1981
- SELL = "SELL"
1982
- }
1983
- declare enum TimeInForce {
1984
- GTT = "GTT",
1985
- IOC = "IOC",
1986
- FOK = "FOK"
1987
- }
1988
- declare enum OrderType {
1989
- LIMIT = "LIMIT",
1990
- CONDITIONAL = "CONDITIONAL",
1991
- MARKET = "MARKET",
1992
- TPSL = "TPSL"
1993
- }
1994
- declare enum OrderStatus {
1995
- UNKNOWN = "UNKNOWN",
1996
- NEW = "NEW",
1997
- UNTRIGGERED = "UNTRIGGERED",
1998
- PARTIALLY_FILLED = "PARTIALLY_FILLED",
1999
- FILLED = "FILLED",
2000
- CANCELLED = "CANCELLED",
2001
- EXPIRED = "EXPIRED",
2002
- REJECTED = "REJECTED"
2003
- }
2004
- declare enum OrderStatusReason {
2005
- UNKNOWN = "UNKNOWN",
2006
- NONE = "NONE",
2007
- UNKNOWN_MARKET = "UNKNOWN_MARKET",
2008
- DISABLED_MARKET = "DISABLED_MARKET",
2009
- NOT_ENOUGH_FUNDS = "NOT_ENOUGH_FUNDS",
2010
- NO_LIQUIDITY = "NO_LIQUIDITY",
2011
- INVALID_FEE = "INVALID_FEE",
2012
- INVALID_QTY = "INVALID_QTY",
2013
- INVALID_PRICE = "INVALID_PRICE",
2014
- INVALID_VALUE = "INVALID_VALUE",
2015
- UNKNOWN_ACCOUNT = "UNKNOWN_ACCOUNT",
2016
- SELF_TRADE_PROTECTION = "SELF_TRADE_PROTECTION",
2017
- POST_ONLY_FAILED = "POST_ONLY_FAILED",
2018
- REDUCE_ONLY_FAILED = "REDUCE_ONLY_FAILED",
2019
- INVALID_EXPIRE_TIME = "INVALID_EXPIRE_TIME",
2020
- POSITION_TPSL_CONFLICT = "POSITION_TPSL_CONFLICT",
2021
- INVALID_LEVERAGE = "INVALID_LEVERAGE",
2022
- PREV_ORDER_NOT_FOUND = "PREV_ORDER_NOT_FOUND",
2023
- PREV_ORDER_TRIGGERED = "PREV_ORDER_TRIGGERED",
2024
- TPSL_OTHER_SIDE_FILLED = "TPSL_OTHER_SIDE_FILLED",
2025
- PREV_ORDER_CONFLICT = "PREV_ORDER_CONFLICT",
2026
- ORDER_REPLACED = "ORDER_REPLACED",
2027
- POST_ONLY_MODE = "POST_ONLY_MODE",
2028
- REDUCE_ONLY_MODE = "REDUCE_ONLY_MODE",
2029
- TRADING_OFF_MODE = "TRADING_OFF_MODE"
2030
- }
2031
- declare enum PositionSide {
2032
- LONG = "LONG",
2033
- SHORT = "SHORT"
2034
- }
2035
- declare enum ExitType {
2036
- TRADE = "TRADE",
2037
- LIQUIDATION = "LIQUIDATION",
2038
- ADL = "ADL"
2039
- }
2040
- declare enum AssetOperationType {
2041
- DEPOSIT = "DEPOSIT",
2042
- WITHDRAWAL = "WITHDRAWAL",
2043
- TRANSFER = "TRANSFER"
2044
- }
2045
- declare enum AssetOperationStatus {
2046
- CREATED = "CREATED",
2047
- IN_PROGRESS = "IN_PROGRESS",
2048
- COMPLETED = "COMPLETED",
2049
- REJECTED = "REJECTED"
2050
- }
2051
- interface SettlementSignature {
2052
- r: string;
2053
- s: string;
2054
- }
2055
- interface StarkSettlement {
2056
- signature: SettlementSignature;
2057
- stark_key: string;
2058
- collateral_position: string;
2059
- }
2060
- interface StarkDebuggingOrderAmounts {
2061
- collateral_amount: string;
2062
- fee_amount: string;
2063
- synthetic_amount: string;
2064
- }
2065
- interface PlacedOrder {
2066
- id: number;
2067
- external_id: string;
2068
- }
2069
- interface OpenOrder {
2070
- id: number;
2071
- account_id: number;
2072
- external_id: string;
2073
- market: string;
2074
- type: OrderType;
2075
- side: OrderSide;
2076
- status: OrderStatus;
2077
- status_reason?: OrderStatusReason;
2078
- price: string;
2079
- average_price?: string;
2080
- qty: string;
2081
- filled_qty?: string;
2082
- reduce_only: boolean;
2083
- post_only: boolean;
2084
- payed_fee?: string;
2085
- created_time: number;
2086
- updated_time: number;
2087
- expiry_time?: number;
2088
- }
2089
- interface Position {
2090
- id: number;
2091
- accountId: number;
2092
- market: string;
2093
- side: PositionSide;
2094
- leverage: string;
2095
- size: string;
2096
- value: string;
2097
- openPrice: string;
2098
- markPrice: string;
2099
- liquidationPrice?: string;
2100
- unrealisedPnl: string;
2101
- realisedPnl: string;
2102
- tpPrice?: string;
2103
- slPrice?: string;
2104
- adl?: number;
2105
- createdAt: number;
2106
- updatedAt: number;
2107
- }
2108
- interface PositionHistory {
2109
- id: number;
2110
- account_id: number;
2111
- market: string;
2112
- side: PositionSide;
2113
- leverage: string;
2114
- size: string;
2115
- open_price: string;
2116
- exit_type?: ExitType;
2117
- exit_price?: string;
2118
- realised_pnl: string;
2119
- created_time: number;
2120
- closed_time?: number;
2121
- }
2122
- interface Balance {
2123
- collateral_name: string;
2124
- balance: string;
2125
- equity: string;
2126
- availableForTrade: string;
2127
- availableForWithdrawal: string;
2128
- unrealisedPnl: string;
2129
- initialMargin: string;
2130
- marginRatio: string;
2131
- updatedTime: number;
2132
- }
2133
- interface RiskFactorConfig {
2134
- upper_bound: string;
2135
- risk_factor: string;
2136
- }
2137
- interface MarketStats {
2138
- daily_volume: string;
2139
- daily_volume_base: string;
2140
- daily_price_change: string;
2141
- daily_low: string;
2142
- daily_high: string;
2143
- last_price: string;
2144
- ask_price: string;
2145
- bid_price: string;
2146
- mark_price: string;
2147
- index_price: string;
2148
- funding_rate: string;
2149
- next_funding_rate: number;
2150
- open_interest: string;
2151
- open_interest_base: string;
2152
- }
2153
- interface TradingConfig {
2154
- min_order_size: string;
2155
- min_order_size_change: string;
2156
- min_price_change: string;
2157
- max_market_order_value: string;
2158
- max_limit_order_value: string;
2159
- max_position_value: string;
2160
- max_leverage: string;
2161
- max_num_orders: number;
2162
- limit_price_cap: string;
2163
- limit_price_floor: string;
2164
- risk_factor_config: RiskFactorConfig[];
2165
- }
2166
- interface L2Config {
2167
- type: string;
2168
- collateral_id: string;
2169
- collateral_resolution: number;
2170
- synthetic_id: string;
2171
- synthetic_resolution: number;
2172
- }
2173
- interface Market {
2174
- name: string;
2175
- asset_name: string;
2176
- asset_precision: number;
2177
- collateral_asset_name: string;
2178
- collateral_asset_precision: number;
2179
- active: boolean;
2180
- market_stats: MarketStats;
2181
- trading_config: TradingConfig;
2182
- l2_config: L2Config;
2183
- }
2184
- interface AssetOperation {
2185
- id: string;
2186
- type: AssetOperationType;
2187
- status: AssetOperationStatus;
2188
- amount: string;
2189
- asset: string;
2190
- created_time: number;
2191
- updated_time: number;
2192
- description?: string;
2193
- transactionHash?: string;
2194
- }
2195
- interface CreateOrderRequest {
2196
- market_name: string;
2197
- amount: string;
2198
- price: string;
2199
- side: OrderSide;
2200
- post_only?: boolean;
2201
- reduce_only?: boolean;
2202
- previous_order_id?: number;
2203
- external_id?: string;
2204
- time_in_force?: TimeInForce;
2205
- }
2206
- interface WithdrawRequest {
2207
- amount: string;
2208
- asset?: string;
2209
- }
2210
- interface SignedWithdrawRequest {
2211
- recipient: string;
2212
- position_id: number;
2213
- amount: number;
2214
- expiration: number;
2215
- salt: number;
2216
- }
2217
- interface CancelOrderRequest {
2218
- order_id: number;
2219
- }
2220
- interface ApiResponse<T> {
2221
- success: boolean;
2222
- message: string;
2223
- data: T;
2224
- }
2225
- interface ExtendedApiResponse<T> {
2226
- status: 'OK' | 'ERROR';
2227
- message: string;
2228
- data: T;
2229
- }
2230
- interface ExtendedWrapperConfig {
2231
- readUrl: string;
2232
- writeUrl: string;
2233
- apiKey?: string;
2234
- timeout?: number;
2235
- retries?: number;
2236
- }
2237
- interface UpdateLeverageRequest {
2238
- leverage: string;
2239
- market: string;
2240
- }
2241
- interface FundingRate {
2242
- m: string;
2243
- f: string;
2244
- t: number;
2245
- }
2246
- interface FundingPayment {
2247
- id: number;
2248
- accountId?: number;
2249
- account_id?: number;
2250
- market: string;
2251
- positionId?: number;
2252
- position_id?: number;
2253
- side: PositionSide;
2254
- size: string;
2255
- value: string;
2256
- markPrice?: string;
2257
- mark_price?: string;
2258
- fundingFee?: string;
2259
- funding_fee?: string;
2260
- fundingRate?: string;
2261
- funding_rate?: string;
2262
- paidTime?: number;
2263
- paid_time?: number;
2264
- }
2265
-
2266
- /**
2267
- * ExtendedWrapper - TypeScript wrapper for Extended Exchange API
2268
- * Provides a clean interface to interact with the Extended Exchange trading API
2269
- */
2270
-
2271
- declare class ExtendedWrapper {
2272
- private readUrl;
2273
- private writeUrl;
2274
- private apiKey?;
2275
- private timeout;
2276
- private retries;
2277
- /** Per-market rules from GET /markets (tradingConfig); retained for process lifetime (no TTL). */
2278
- private marketTradingRulesCache;
2279
- private marketTradingRulesInflight;
2280
- constructor(config: ExtendedWrapperConfig);
2281
- /**
2282
- * Make HTTP request with retry logic and error handling
2283
- */
2284
- private makeRequest;
2285
- private resolveTradingRules;
2286
- /**
2287
- * Create a new order on Extended Exchange
2288
- */
2289
- createOrder(request: CreateOrderRequest): Promise<ExtendedApiResponse<PlacedOrder>>;
2290
- /**
2291
- * Get all markets
2292
- */
2293
- getMarkets(marketNames?: string): Promise<ExtendedApiResponse<Market[]>>;
2294
- /**
2295
- *
2296
- * @param orderId - The ID of the order to get
2297
- * @returns The order
2298
- */
2299
- getOrderByOrderId(orderId: string): Promise<ExtendedApiResponse<OpenOrder>>;
2300
- /**
2301
- * Get market statistics for a specific market
2302
- */
2303
- getMarketStatistics(marketName: string): Promise<ExtendedApiResponse<MarketStats>>;
2304
- /**
2305
- * Get current trading positions
2306
- */
2307
- getPositions(marketNames?: string): Promise<ExtendedApiResponse<Position[]>>;
2308
- /**
2309
- * Get account balance and holdings
2310
- */
2311
- getHoldings(): Promise<ExtendedApiResponse<Balance>>;
2312
- /**
2313
- * Initiate a withdrawal from Extended Exchange
2314
- * Returns data as number | string to preserve precision for large integers
2315
- */
2316
- withdraw(request: WithdrawRequest): Promise<ExtendedApiResponse<number | string>>;
2317
- /**
2318
- * Create and sign a withdrawal request hash
2319
- */
2320
- signWithdrawalRequest(request: SignedWithdrawRequest): Promise<ExtendedApiResponse<{
2321
- withdraw_request_hash: string;
2322
- signature: {
2323
- r: string;
2324
- s: string;
2325
- };
2326
- }>>;
2327
- /**
2328
- * Cancel an existing order
2329
- */
2330
- cancelOrder(request: CancelOrderRequest): Promise<ExtendedApiResponse<{}>>;
2331
- /**
2332
- * Get all open orders
2333
- */
2334
- getOpenOrders(marketName?: string): Promise<ExtendedApiResponse<OpenOrder[]>>;
2335
- /**
2336
- * Update leverage on the market
2337
- * @param request
2338
- * @returns
2339
- */
2340
- updateLeverage(request: UpdateLeverageRequest): Promise<ExtendedApiResponse<{}>>;
2341
- /**
2342
- * Get asset operations with optional filtering
2343
- */
2344
- getAssetOperations(options?: {
2345
- id?: number;
2346
- operationsType?: AssetOperationType[];
2347
- operationsStatus?: AssetOperationStatus[];
2348
- startTime?: number;
2349
- endTime?: number;
2350
- cursor?: number;
2351
- limit?: number;
2352
- }): Promise<ExtendedApiResponse<AssetOperation[]>>;
2353
- /**
2354
- * Health check endpoint
2355
- */
2356
- healthCheck(): Promise<ExtendedApiResponse<MarketStats>>;
2357
- /**
2358
- * Convenience method to create a buy order
2359
- */
2360
- createBuyOrder(marketName: string, amount: string, price: string, options?: {
2361
- post_only?: boolean;
2362
- reduce_only?: boolean;
2363
- previous_order_id?: number;
2364
- external_id?: string;
2365
- time_in_force?: TimeInForce;
2366
- }): Promise<ExtendedApiResponse<PlacedOrder>>;
2367
- /**
2368
- * Get order by ID
2369
- * @param orderId - The ID of the order to get
2370
- * @returns The order
2371
- */
2372
- getOrderById(orderId: number): Promise<ExtendedApiResponse<OpenOrder>>;
2373
- /**
2374
- * Convenience method to create a sell order
2375
- */
2376
- createSellOrder(marketName: string, amount: string, price: string, options?: {
2377
- post_only?: boolean;
2378
- reduce_only?: boolean;
2379
- previous_order_id?: number;
2380
- external_id?: string;
2381
- time_in_force?: TimeInForce;
2382
- }): Promise<ExtendedApiResponse<PlacedOrder>>;
2383
- /**
2384
- * Get positions for a specific market
2385
- */
2386
- getPositionsForMarket(marketName: string): Promise<ExtendedApiResponse<Position[]>>;
2387
- /**
2388
- * Get open orders for a specific market
2389
- */
2390
- getOpenOrdersForMarket(marketName: string): Promise<ExtendedApiResponse<OpenOrder[]>>;
2391
- /**
2392
- * Cancel order by ID (convenience method)
2393
- */
2394
- cancelOrderById(orderId: number): Promise<ExtendedApiResponse<{}>>;
2395
- /**
2396
- * Get order history for a specific market
2397
- * @param marketName - The name of the market to get order history for
2398
- * @returns The order history for the specified market
2399
- */
2400
- getOrderHistory(marketName: string): Promise<ExtendedApiResponse<OpenOrder[]>>;
2401
- /**
2402
- * Withdraw USDC (convenience method)
2403
- * Returns data as number | string to preserve precision for large integers
2404
- */
2405
- withdrawUSDC(amount: string): Promise<ExtendedApiResponse<number | string>>;
2406
- /**
2407
- * Get funding rates for a specific market
2408
- * @param marketName - The name of the market to get funding rates for
2409
- * @returns The funding rates for the specified market
2410
- */
2411
- getFundingRates(marketName: string, side: string, startTime?: number, endTime?: number): Promise<ExtendedApiResponse<FundingRate[]>>;
2412
- /**
2413
- * Get funding payments for a specific market.
2414
- */
2415
- getUserFundingPayments(marketName: string, side: string, startTime: number, limit?: number, cursor?: number): Promise<ExtendedApiResponse<FundingPayment[]>>;
2416
- }
2417
-
2418
- interface AvnuAdapterConfig extends BaseAdapterConfig {
2419
- baseUrl: string;
2420
- avnuContract: ContractAddr;
2421
- slippage: number;
2422
- minimumExtendedPriceDifferenceForSwapOpen: number;
2423
- maximumExtendedPriceDifferenceForSwapClosing: number;
2424
- }
2425
- declare class AvnuAdapter extends BaseAdapter<DepositParams, WithdrawParams> {
2426
- readonly config: AvnuAdapterConfig;
2427
- protected avnuWrapper: AvnuWrapper;
2428
- lastSwapPriceInfo: SwapPriceInfo | null;
2429
- private _depositApproveProofReadableId;
2430
- private _depositSwapProofReadableId;
2431
- private _withdrawApproveProofReadableId;
2432
- private _withdrawSwapProofReadableId;
2433
- private buildSwapLeafConfigs;
2434
- private buildSwapCalls;
2435
- constructor(config: AvnuAdapterConfig);
2436
- protected getAPY(supportedPosition: SupportedPosition): Promise<PositionAPY>;
2437
- protected getPosition(supportedPosition: SupportedPosition): Promise<PositionAmount | null>;
2438
- maxDeposit(amount?: Web3Number): Promise<PositionInfo>;
2439
- maxWithdraw(): Promise<PositionInfo>;
2440
- protected _getDepositLeaf(): {
2441
- target: ContractAddr;
2442
- method: string;
2443
- packedArguments: bigint[];
2444
- sanitizer: ContractAddr;
2445
- id: string;
2446
- }[];
2447
- protected _getWithdrawLeaf(): {
2448
- target: ContractAddr;
2449
- method: string;
2450
- packedArguments: bigint[];
2451
- sanitizer: ContractAddr;
2452
- id: string;
2453
- }[];
2454
- protected _getLegacySwapLeaf(): {
2455
- target: ContractAddr;
2456
- method: string;
2457
- packedArguments: bigint[];
2458
- sanitizer: ContractAddr;
2459
- id: string;
2460
- }[];
2461
- getDepositCall(params: DepositParams): Promise<ManageCall[]>;
2462
- getWithdrawCall(params: WithdrawParams): Promise<ManageCall[]>;
2463
- getSwapCallData(quote: Quote): Promise<bigint[][]>;
2464
- getHealthFactor(): Promise<number>;
2465
- fetchQuoteWithRetry(params: Record<string, any>, retries?: number): Promise<any>;
2466
- }
2467
-
2468
- interface ExtendedAdapterConfig extends BaseAdapterConfig {
2469
- vaultIdExtended: number;
2470
- extendedContract: ContractAddr;
2471
- extendedBackendReadUrl: string;
2472
- extendedBackendWriteUrl: string;
2473
- extendedTimeout: number;
2474
- extendedRetries: number;
2475
- extendedBaseUrl: string;
2476
- extendedMarketName: string;
2477
- extendedPrecision: number;
2478
- avnuAdapter: AvnuAdapter;
2479
- retryDelayForOrderStatus: number;
2480
- minimumExtendedMovementAmount: number;
2481
- }
2482
- declare class ExtendedAdapter extends BaseAdapter<DepositParams, WithdrawParams> {
2483
- readonly config: ExtendedAdapterConfig;
2484
- readonly client: ExtendedWrapper;
2485
- readonly usdcToken: TokenInfo;
2486
- readonly retryDelayForOrderStatus: number;
2487
- readonly minimumExtendedMovementAmount: number;
2488
- constructor(config: ExtendedAdapterConfig);
2489
- private _depositApproveProofReadableId;
2490
- private _depositCallProofReadableId;
2491
- protected getAPY(supportedPosition: SupportedPosition): Promise<PositionAPY>;
2492
- getFundingRates(side: string, startTime?: number, endTime?: number): Promise<{
2493
- success: boolean;
2494
- data: FundingRate[];
2495
- }>;
2496
- /** Account funding payment history via `GET /api/v1/account/funding-payments` (USDC amounts). */
2497
- getFundingPayments(side: string, startTime?: number, limit?: number): Promise<{
2498
- success: boolean;
2499
- data: FundingPayment[];
2500
- }>;
2501
- protected getPosition(supportedPosition: SupportedPosition): Promise<PositionAmount>;
2502
- maxDeposit(amount?: Web3Number): Promise<PositionInfo>;
2503
- maxWithdraw(): Promise<PositionInfo>;
2504
- protected _getDepositLeaf(): {
2505
- target: ContractAddr;
2506
- method: string;
2507
- packedArguments: bigint[];
2508
- sanitizer: ContractAddr;
2509
- id: string;
2510
- }[];
2511
- protected _getWithdrawLeaf(): {
2512
- target: ContractAddr;
2513
- method: string;
2514
- packedArguments: bigint[];
2515
- sanitizer: ContractAddr;
2516
- id: string;
2517
- }[];
2518
- getDepositCall(params: DepositParams): Promise<ManageCall[]>;
2519
- getWithdrawCall(params: WithdrawParams): Promise<ManageCall[]>;
2520
- withdrawFromExtended(amount: Web3Number): Promise<{
2521
- status: boolean;
2522
- receivedTxnHash: boolean;
2523
- }>;
2524
- getHealthFactor(): Promise<number>;
2525
- getExtendedDepositAmount(): Promise<Balance | undefined>;
2526
- setLeverage(leverage: string, marketName: string): Promise<boolean>;
2527
- getAllOpenPositions(): Promise<Position[] | null>;
2528
- getOrderStatus(orderId: string, marketName: string): Promise<OpenOrder | null>;
2529
- fetchOrderBookFromExtended(): Promise<{
2530
- status: boolean;
2531
- bid: Web3Number;
2532
- ask: Web3Number;
2533
- }>;
2534
- createOrder(leverage: string, btcAmount: number, side: OrderSide, attempt?: number, maxAttempts?: number): Promise<{
2535
- position_id: string;
2536
- btc_exposure: string;
2537
- } | null>;
2538
- createExtendedPositon(client: ExtendedWrapper, marketName: string, amount: string, price: string, side: OrderSide): Promise<{
2539
- position_id: string;
2540
- } | null>;
2541
- getDepositOrWithdrawalStatus(orderId: number | string, // for deposits, send txn hash as string
2542
- operationsType: AssetOperationType): Promise<boolean>;
2543
- }
2544
-
2545
2138
  declare const SIMPLE_SANITIZER: ContractAddr;
2546
2139
  declare const SVK_SIMPLE_SANITIZER: ContractAddr;
2547
2140
  declare const EXTENDED_SANITIZER: ContractAddr;
@@ -2603,6 +2196,62 @@ declare class TokenTransferAdapter extends BaseAdapter<DepositParams, WithdrawPa
2603
2196
  getHealthFactor(): Promise<number>;
2604
2197
  }
2605
2198
 
2199
+ interface AvnuDepositParams extends DepositParams {
2200
+ minAmount?: Web3Number;
2201
+ }
2202
+ interface AvnuWithdrawParams extends WithdrawParams {
2203
+ minAmount?: Web3Number;
2204
+ }
2205
+ interface AvnuAdapterConfig extends BaseAdapterConfig {
2206
+ baseUrl: string;
2207
+ avnuContract: ContractAddr;
2208
+ slippage: number;
2209
+ minimumExtendedPriceDifferenceForSwapOpen: number;
2210
+ maximumExtendedPriceDifferenceForSwapClosing: number;
2211
+ }
2212
+ declare class AvnuAdapter extends BaseAdapter<AvnuDepositParams, AvnuWithdrawParams> {
2213
+ readonly config: AvnuAdapterConfig;
2214
+ protected avnuWrapper: AvnuWrapper;
2215
+ lastSwapPriceInfo: SwapPriceInfo | null;
2216
+ private _depositApproveProofReadableId;
2217
+ private _depositSwapProofReadableId;
2218
+ private _withdrawApproveProofReadableId;
2219
+ private _withdrawSwapProofReadableId;
2220
+ private buildSwapLeafConfigs;
2221
+ private buildSwapCalls;
2222
+ constructor(config: AvnuAdapterConfig);
2223
+ protected getAPY(supportedPosition: SupportedPosition): Promise<PositionAPY>;
2224
+ protected getPosition(supportedPosition: SupportedPosition): Promise<PositionAmount | null>;
2225
+ maxDeposit(amount?: Web3Number): Promise<PositionInfo>;
2226
+ maxWithdraw(): Promise<PositionInfo>;
2227
+ protected _getDepositLeaf(): {
2228
+ target: ContractAddr;
2229
+ method: string;
2230
+ packedArguments: bigint[];
2231
+ sanitizer: ContractAddr;
2232
+ id: string;
2233
+ }[];
2234
+ protected _getWithdrawLeaf(): {
2235
+ target: ContractAddr;
2236
+ method: string;
2237
+ packedArguments: bigint[];
2238
+ sanitizer: ContractAddr;
2239
+ id: string;
2240
+ }[];
2241
+ protected _getLegacySwapLeaf(): {
2242
+ target: ContractAddr;
2243
+ method: string;
2244
+ packedArguments: bigint[];
2245
+ sanitizer: ContractAddr;
2246
+ id: string;
2247
+ }[];
2248
+ getDepositCall(params: AvnuDepositParams): Promise<ManageCall[]>;
2249
+ getWithdrawCall(params: AvnuWithdrawParams): Promise<ManageCall[]>;
2250
+ getSwapCallData(quote: Quote): Promise<bigint[][]>;
2251
+ getHealthFactor(): Promise<number>;
2252
+ fetchQuoteWithRetry(params: Record<string, any>, retries?: number): Promise<any>;
2253
+ }
2254
+
2606
2255
  /** Public Troves strategies feed (APY + metadata). Override in config for tests. */
2607
2256
  declare const DEFAULT_TROVES_STRATEGIES_API = "https://app.troves.fi/api/strategies";
2608
2257
  interface SvkTrovesAdapterConfig extends BaseAdapterConfig {
@@ -2622,6 +2271,11 @@ interface SvkTrovesAdapterConfig extends BaseAdapterConfig {
2622
2271
  positionOwner?: ContractAddr;
2623
2272
  /** Optional APY endpoint (defaults to {@link DEFAULT_TROVES_STRATEGIES_API}). */
2624
2273
  trovesStrategiesApiUrl?: string;
2274
+ /**
2275
+ * Optional redeem request NFT contract address. When provided, pending assets are calculated
2276
+ * using `getPendingAssetsFromOwnerNFTMethod` instead of `due_assets_from_owner`.
2277
+ */
2278
+ redeemRequestNFT?: ContractAddr;
2625
2279
  }
2626
2280
  /**
2627
2281
  * Universal adapter for **Starknet Vault Kit (SVK)** style Troves strategies:
@@ -2687,186 +2341,6 @@ declare enum LSTPriceType {
2687
2341
  AVNU_PRICE = "AVNU_PRICE"
2688
2342
  }
2689
2343
 
2690
- interface UniversalManageCall {
2691
- proofs: string[];
2692
- manageCall: ManageCall;
2693
- step: UNIVERSAL_MANAGE_IDS;
2694
- }
2695
- interface UniversalStrategySettings {
2696
- vaultAddress: ContractAddr;
2697
- manager: ContractAddr;
2698
- vaultAllocator: ContractAddr;
2699
- redeemRequestNFT: ContractAddr;
2700
- aumOracle: ContractAddr;
2701
- redemptionRouter?: ContractAddr;
2702
- leafAdapters: LeafAdapterFn<any>[];
2703
- adapters: {
2704
- id: string;
2705
- adapter: BaseAdapter<DepositParams, WithdrawParams>;
2706
- }[];
2707
- targetHealthFactor: number;
2708
- minHealthFactor: number;
2709
- }
2710
- declare enum AUMTypes {
2711
- FINALISED = "finalised",
2712
- DEFISPRING = "defispring"
2713
- }
2714
- declare enum PositionTypeAvnuExtended {
2715
- OPEN = "open",
2716
- CLOSE = "close"
2717
- }
2718
- declare class UniversalStrategy<S extends UniversalStrategySettings> extends BaseStrategy<SingleTokenInfo, SingleActionAmount> {
2719
- /** Contract address of the strategy */
2720
- readonly address: ContractAddr;
2721
- /** Pricer instance for token price calculations */
2722
- readonly pricer: PricerBase;
2723
- /** Metadata containing strategy information */
2724
- readonly metadata: IStrategyMetadata<S>;
2725
- /** Contract instance for interacting with the strategy */
2726
- readonly contract: Contract;
2727
- readonly managerContract: Contract;
2728
- merkleTree: StandardMerkleTree | undefined;
2729
- constructor(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<S>);
2730
- getMerkleTree(): StandardMerkleTree;
2731
- getMerkleRoot(): string;
2732
- getProofs<T>(id: string): {
2733
- proofs: string[];
2734
- callConstructor: GenerateCallFn<T>;
2735
- };
2736
- getAdapter(id: string): BaseAdapter<any, any>;
2737
- asset(): TokenInfo;
2738
- depositCall(amountInfo: SingleActionAmount, receiver: ContractAddr): Promise<Call[]>;
2739
- withdrawCall(amountInfo: SingleActionAmount, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]>;
2740
- getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<{
2741
- tokenInfo: TokenInfo;
2742
- amount: Web3Number;
2743
- usdValue: number;
2744
- }>;
2745
- getVesuAPYs(): Promise<{
2746
- baseAPYs: number[];
2747
- rewardAPYs: number[];
2748
- positions: VaultPosition[];
2749
- }>;
2750
- /**
2751
- * Calculates the weighted average APY across all pools based on USD value.
2752
- * @returns {Promise<number>} The weighted average APY across all pools
2753
- */
2754
- netAPY(): Promise<{
2755
- net: number;
2756
- splits: {
2757
- apy: number;
2758
- id: string;
2759
- }[];
2760
- }>;
2761
- protected returnNetAPY(baseAPYs: number[], rewardAPYs: number[], weights: number[], prevAUMUSD: Web3Number): Promise<{
2762
- net: number;
2763
- splits: {
2764
- apy: number;
2765
- id: string;
2766
- }[];
2767
- }>;
2768
- protected getUnusedBalanceAPY(): Promise<{
2769
- apy: number;
2770
- weight: number;
2771
- }>;
2772
- private computeAPY;
2773
- /**
2774
- * Calculates user realized APY based on trueSharesBasedAPY method.
2775
- * Returns the APY as a number.
2776
- */
2777
- getUserRealizedAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number): Promise<number>;
2778
- /**
2779
- * Calculates the total TVL of the strategy.
2780
- * @returns Object containing the total amount in token units and USD value
2781
- */
2782
- getTVL(): Promise<{
2783
- tokenInfo: TokenInfo;
2784
- amount: Web3Number;
2785
- usdValue: number;
2786
- }>;
2787
- getUnusedBalance(): Promise<SingleTokenInfo>;
2788
- protected getVesuAUM(adapter: VesuAdapter, _priceType?: LSTPriceType): Promise<Web3Number>;
2789
- getPrevAUM(): Promise<Web3Number>;
2790
- getAUM(unrealizedAUM?: boolean): Promise<{
2791
- net: SingleTokenInfo;
2792
- prevAum: Web3Number;
2793
- splits: {
2794
- id: string;
2795
- aum: Web3Number;
2796
- }[];
2797
- }>;
2798
- protected getRewardsAUM(prevAum: Web3Number): Promise<Web3Number>;
2799
- getVesuAdapters(): VesuAdapter[];
2800
- getVesuPositions(blockNumber?: BlockIdentifier): Promise<VaultPosition[]>;
2801
- getVaultPositions(): Promise<VaultPosition[]>;
2802
- getSetManagerCall(strategist: ContractAddr, root?: string): Call;
2803
- getManageCall(proofIds: string[], manageCalls: ManageCall[]): Call;
2804
- getVesuModifyPositionCalls(params: {
2805
- isLeg1: boolean;
2806
- isDeposit: boolean;
2807
- depositAmount: Web3Number;
2808
- debtAmount: Web3Number;
2809
- }): UniversalManageCall[];
2810
- getTag(): string;
2811
- /**
2812
- * Gets LST APR for the strategy's underlying asset from Endur API
2813
- * @returns Promise<number> The LST APR (not divided by 1e18)
2814
- */
2815
- getLSTAPR(address: ContractAddr): Promise<number>;
2816
- getVesuHealthFactors(blockNumber?: BlockIdentifier): Promise<number[]>;
2817
- computeRebalanceConditionAndReturnCalls(): Promise<Call[]>;
2818
- private getNewHealthFactor;
2819
- /**
2820
- *
2821
- * @param vesuAdapter
2822
- * @param currentHf
2823
- * @param isDeposit if true, attempt by adding collateral, else by repaying
2824
- * @returns
2825
- */
2826
- private getLegRebalanceAmount;
2827
- getVesuModifyPositionCall(params: {
2828
- isDeposit: boolean;
2829
- leg1DepositAmount: Web3Number;
2830
- }): Promise<Call>;
2831
- getBringLiquidityCall(params: {
2832
- amount: Web3Number;
2833
- }): Promise<Call>;
2834
- getPendingRewards(): Promise<HarvestInfo[]>;
2835
- getHarvestCall(): Promise<{
2836
- call: Call;
2837
- reward: Web3Number;
2838
- tokenInfo: TokenInfo;
2839
- }>;
2840
- getRebalanceCall(params: {
2841
- isLeg1toLeg2: boolean;
2842
- amount: Web3Number;
2843
- }): Promise<Call>;
2844
- }
2845
- declare enum UNIVERSAL_MANAGE_IDS {
2846
- FLASH_LOAN = "flash_loan_init",
2847
- VESU_LEG1 = "vesu_leg1",
2848
- VESU_LEG2 = "vesu_leg2",
2849
- APPROVE_TOKEN1 = "approve_token1",
2850
- APPROVE_TOKEN2 = "approve_token2",
2851
- APPROVE_BRING_LIQUIDITY = "approve_bring_liquidity",
2852
- BRING_LIQUIDITY = "bring_liquidity",
2853
- DEFISPRING_REWARDS = "defispring_rewards",
2854
- APPROVE_SWAP_TOKEN1 = "approve_swap_token1",
2855
- AVNU_SWAP_REWARDS = "avnu_swap_rewards"
2856
- }
2857
- declare enum UNIVERSAL_ADAPTERS {
2858
- COMMON = "common_adapter",
2859
- VESU_LEG1 = "vesu_leg1_adapter",
2860
- VESU_LEG2 = "vesu_leg2_adapter"
2861
- }
2862
- declare function getContractDetails(settings: UniversalStrategySettings & {
2863
- aumOracle?: ContractAddr;
2864
- }): {
2865
- address: ContractAddr;
2866
- name: string;
2867
- }[];
2868
- declare const UniversalStrategies: IStrategyMetadata<UniversalStrategySettings>[];
2869
-
2870
2344
  /**
2871
2345
  * Base class for all SVK (Starknet Vault Kit) strategies.
2872
2346
  * Contains common functions that are shared across all SVK strategies.
@@ -2958,42 +2432,67 @@ declare abstract class SVKStrategy<S extends UniversalStrategySettings> extends
2958
2432
  id: string;
2959
2433
  }[];
2960
2434
  }>;
2435
+ getTVL(): Promise<SingleTokenInfo>;
2961
2436
  getPrevAUM(): Promise<Web3Number>;
2962
2437
  maxDepositables(): Promise<PositionInfo[]>;
2963
2438
  maxWithdrawables(): Promise<PositionInfo[]>;
2964
2439
  }
2965
2440
 
2966
- interface HyperLSTStrategySettings extends UniversalStrategySettings {
2967
- borrowable_assets: TokenInfo[];
2968
- underlyingToken: TokenInfo;
2969
- quoteAmountToFetchPrice: Web3Number;
2441
+ interface UniversalManageCall {
2442
+ proofs: string[];
2443
+ manageCall: ManageCall;
2444
+ step: UNIVERSAL_MANAGE_IDS;
2445
+ }
2446
+ interface UniversalStrategySettings {
2447
+ vaultAddress: ContractAddr;
2448
+ manager: ContractAddr;
2449
+ vaultAllocator: ContractAddr;
2450
+ redeemRequestNFT: ContractAddr;
2451
+ aumOracle: ContractAddr;
2452
+ redemptionRouter?: ContractAddr;
2453
+ leafAdapters: LeafAdapterFn<any>[];
2454
+ adapters: {
2455
+ id: string;
2456
+ adapter: BaseAdapter<DepositParams, WithdrawParams>;
2457
+ }[];
2970
2458
  targetHealthFactor: number;
2971
2459
  minHealthFactor: number;
2972
- aumOracle: ContractAddr;
2973
2460
  }
2974
- declare class UniversalLstMultiplierStrategy<S extends HyperLSTStrategySettings> extends SVKStrategy<S> {
2975
- private quoteAmountToFetchPrice;
2461
+ declare enum AUMTypes {
2462
+ FINALISED = "finalised",
2463
+ DEFISPRING = "defispring",
2464
+ BTCFI = "btcfi"
2465
+ }
2466
+ declare enum PositionTypeAvnuExtended {
2467
+ OPEN = "open",
2468
+ CLOSE = "close"
2469
+ }
2470
+ declare class UniversalStrategy<S extends UniversalStrategySettings> extends SVKStrategy<S> {
2976
2471
  constructor(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<S>);
2977
- getTag(): string;
2978
- getVesuSameTokenAdapter(): VesuMultiplyAdapter;
2979
- getVesuAdapters(): VesuMultiplyAdapter[];
2980
- getRewardsAUM(_prevAum: Web3Number): Promise<Web3Number>;
2981
- getLSTDexPrice(): Promise<number>;
2982
- getLSTAvnuRate(): Promise<number>;
2983
- getLSTExchangeRate(): Promise<number>;
2984
- private _getMinOutputAmountLSTBuy;
2985
- private _getMinOutputAmountLSTSell;
2472
+ getMerkleTree(): StandardMerkleTree;
2473
+ getMerkleRoot(): string;
2474
+ getProofs<T>(id: string): {
2475
+ proofs: string[];
2476
+ callConstructor: GenerateCallFn<T>;
2477
+ };
2478
+ getAdapter(id: string): BaseAdapter<any, any>;
2479
+ asset(): TokenInfo;
2480
+ depositCall(amountInfo: SingleActionAmount, receiver: ContractAddr): Promise<Call[]>;
2481
+ withdrawCall(amountInfo: SingleActionAmount, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]>;
2482
+ getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<{
2483
+ tokenInfo: TokenInfo;
2484
+ amount: Web3Number;
2485
+ usdValue: number;
2486
+ }>;
2487
+ getVesuAPYs(): Promise<{
2488
+ baseAPYs: number[];
2489
+ rewardAPYs: number[];
2490
+ positions: VaultPosition[];
2491
+ }>;
2986
2492
  /**
2987
- * Uses vesu's multiple call to create leverage on LST
2988
- * Deposit amount is in LST
2989
- * @param params
2493
+ * Calculates the weighted average APY across all pools based on USD value.
2494
+ * @returns {Promise<number>} The weighted average APY across all pools
2990
2495
  */
2991
- getFundManagementCall(params: {
2992
- isDeposit: boolean;
2993
- leg1DepositAmount: Web3Number;
2994
- }): Promise<Call[] | null>;
2995
- getLSTUnderlyingTokenInfo(): TokenInfo;
2996
- getLSTAPR(_address: ContractAddr): Promise<number>;
2997
2496
  netAPY(): Promise<{
2998
2497
  net: number;
2999
2498
  splits: {
@@ -3001,1534 +2500,314 @@ declare class UniversalLstMultiplierStrategy<S extends HyperLSTStrategySettings>
3001
2500
  id: string;
3002
2501
  }[];
3003
2502
  }>;
3004
- maxNewDeposits(params?: {
3005
- isAPYComputation: boolean;
3006
- }): Promise<number>;
2503
+ protected returnNetAPY(baseAPYs: number[], rewardAPYs: number[], weights: number[], prevAUMUSD: Web3Number): Promise<{
2504
+ net: number;
2505
+ splits: {
2506
+ apy: number;
2507
+ id: string;
2508
+ }[];
2509
+ }>;
3007
2510
  protected getUnusedBalanceAPY(): Promise<{
3008
2511
  apy: number;
3009
2512
  weight: number;
3010
2513
  }>;
2514
+ private computeAPY;
2515
+ /**
2516
+ * Calculates user realized APY based on trueSharesBasedAPY method.
2517
+ * Returns the APY as a number.
2518
+ */
2519
+ getUserRealizedAPY(blockIdentifier?: BlockIdentifier, sinceBlocks?: number): Promise<number>;
2520
+ getUserPositionCards(input: UserPositionCardsInput): Promise<UserPositionCard[]>;
2521
+ /**
2522
+ * Calculates the total TVL of the strategy.
2523
+ * @returns Object containing the total amount in token units and USD value
2524
+ */
2525
+ getTVL(): Promise<{
2526
+ tokenInfo: TokenInfo;
2527
+ amount: Web3Number;
2528
+ usdValue: number;
2529
+ }>;
2530
+ getUnusedBalance(): Promise<SingleTokenInfo>;
2531
+ protected getVesuAUM(adapter: VesuAdapter, _priceType?: LSTPriceType): Promise<Web3Number>;
2532
+ getPrevAUM(): Promise<Web3Number>;
3011
2533
  getAUM(unrealizedAUM?: boolean): Promise<{
3012
2534
  net: SingleTokenInfo;
3013
2535
  prevAum: Web3Number;
3014
- splits: PositionInfo[];
2536
+ splits: {
2537
+ id: string;
2538
+ aum: Web3Number;
2539
+ }[];
3015
2540
  }>;
3016
- getTVLUnrealized(): Promise<{
3017
- net: SingleTokenInfo;
3018
- prevAum: Web3Number;
3019
- splits: PositionInfo[];
3020
- }>;
3021
- getUserUnrealizedGains(user: ContractAddr): Promise<{
3022
- unrealizedGains: Web3Number;
3023
- userShare: number;
3024
- tokenInfo: TokenInfo;
3025
- }>;
3026
- }
3027
- declare const AUDIT_URL = "https://docs.troves.fi/p/security#starknet-vault-kit";
3028
- declare function getFAQs(lstSymbol: string, underlyingSymbol: string, isLST: boolean): FAQ[];
3029
- declare const _riskFactor: RiskFactor[];
3030
- declare function getInvestmentSteps(lstSymbol: string, underlyingSymbol: string): string[];
3031
- declare const HyperLSTStrategies: IStrategyMetadata<HyperLSTStrategySettings>[];
3032
-
3033
- interface USDCBoostedStrategySettings extends UniversalStrategySettings {
3034
- vesuPoolId: ContractAddr;
3035
- collateralToken: TokenInfo;
3036
- debtToken: TokenInfo;
3037
- maxLTV: number;
3038
- targetLTV: number;
3039
- hyperxSTRKVaultAddress: ContractAddr;
3040
- }
3041
- declare class USDCBoostedStrategy<S extends USDCBoostedStrategySettings> extends SVKStrategy<S> {
3042
- constructor(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<S>);
3043
- getTag(): string;
3044
- private getAdapterById;
3045
- getVesuModifyPositionCall(params: {
3046
- isDeposit: boolean;
3047
- leg1DepositAmount: Web3Number;
3048
- debtAmount?: Web3Number;
3049
- }): Promise<Call>;
3050
- getVesuPositions(): Promise<VaultPosition[]>;
3051
- getVesuHealthFactor(blockNumber?: BlockIdentifier): Promise<number>;
3052
- getModifyHyperPositionCall(params: {
3053
- isDeposit: boolean;
3054
- amount: Web3Number;
3055
- }): Promise<Call>;
3056
- getAvnuSwapCall(params: {
3057
- isDeposit: boolean;
3058
- amount: Web3Number;
3059
- }): Promise<Call>;
3060
- /**
3061
- * Returns the USDC balance sitting idle inside the vault contract itself.
3062
- * This balance can offset the required liquidity during withdrawal processing.
3063
- */
3064
- getUnusedBalanceVault(): Promise<Web3Number>;
2541
+ protected getRewardsAUM(prevAum: Web3Number): Promise<Web3Number>;
2542
+ getVesuMultiplyAdapter(): VesuMultiplyAdapter;
2543
+ getVesuModifyPositionAdapter(): VesuModifyPositionAdapter;
3065
2544
  /**
3066
- * Returns the current STRK balance sitting unused in the vault allocator.
3067
- * This covers STRK from prior borrow cycles that hasn't been swapped yet.
2545
+ * Legacy helper for retired Evergreen flows. New integrations should use
2546
+ * getVesuMultiplyAdapter / getVesuModifyPositionAdapter and BaseAdapter deposit/withdraw leaves.
3068
2547
  */
3069
- getUnusedDebt(): Promise<Web3Number>;
3070
- /**
3071
- * Returns the xSTRK balance sitting in the vault allocator.
3072
- * This is non-zero when the previous cycle's request_redeem on the HyperPosition
3073
- * has been settled — the redeemed xSTRK lands here and is ready to be swapped.
3074
- */
3075
- getxSTRKInVault(): Promise<Web3Number>;
2548
+ getVesuAdapters(): VesuAdapter[];
2549
+ getVesuPositions(blockNumber?: BlockIdentifier): Promise<VaultPosition[]>;
2550
+ getVaultPositions(): Promise<VaultPosition[]>;
2551
+ getSetManagerCall(strategist: ContractAddr, root?: string): Call;
3076
2552
  /**
3077
- * Simulates depositing `depositAmount` USDC on Vesu and returns the
3078
- * incremental STRK that would be borrowed. Needed to size the AVNU swap
3079
- * call that is batched together with the Vesu call in the same transaction.
2553
+ * Compatibility helper: SVKStrategy's `getManageCall` expects proof-groups.
2554
+ * We derive proof-groups from each manageCall's `proofReadableId`.
3080
2555
  */
3081
- computeVesuDepositBorrowAmount(depositAmount: Web3Number): Promise<Web3Number>;
3082
- computeVesuWithdrawDebtDelta(withdrawAmount: Web3Number): Promise<Web3Number>;
3083
- getPendingHyperAssets(): Promise<Web3Number>;
3084
- getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<{
3085
- tokenInfo: TokenInfo;
3086
- amount: Web3Number;
3087
- usdValue: number;
3088
- }>;
3089
- getTVL(): Promise<{
3090
- tokenInfo: TokenInfo;
3091
- amount: Web3Number;
3092
- usdValue: number;
3093
- }>;
3094
- getAUM(): Promise<{
3095
- net: SingleTokenInfo;
3096
- prevAum: Web3Number;
3097
- splits: PositionInfo[];
3098
- }>;
3099
- getFundManagementCall(params: {
2556
+ protected getManageCallFromManageCalls(manageCalls: ManageCall[]): Call;
2557
+ getVesuModifyPositionCalls(params: {
2558
+ isLeg1: boolean;
3100
2559
  isDeposit: boolean;
3101
- leg1DepositAmount: Web3Number;
3102
- }): Promise<Call[] | null>;
3103
- }
3104
- declare const USDCBoostedStrategies: IStrategyMetadata<USDCBoostedStrategySettings>[];
3105
-
3106
- /**
3107
- * Snapshot of a single Vesu pool's position: collateral, debt, and their prices.
3108
- */
3109
- interface VesuPoolState {
3110
- poolId: ContractAddr;
3111
- collateralToken: TokenInfo;
3112
- debtToken: TokenInfo;
3113
- collateralAmount: Web3Number;
3114
- collateralUsdValue: number;
3115
- debtAmount: Web3Number;
3116
- debtUsdValue: number;
3117
- collateralPrice: number;
3118
- debtPrice: number;
3119
- }
3120
- /**
3121
- * Snapshot of a single Extended exchange open position.
3122
- */
3123
- interface ExtendedPositionState {
3124
- instrument: string;
3125
- side: string;
3126
- size: Web3Number;
3127
- valueUsd: Web3Number;
3128
- leverage: string;
3129
- }
3130
- /**
3131
- * Snapshot of the Extended exchange account-level balance.
3132
- */
3133
- interface ExtendedBalanceState {
3134
- equity: Web3Number;
3135
- availableForTrade: Web3Number;
3136
- availableForWithdrawal: Web3Number;
3137
- unrealisedPnl: Web3Number;
3138
- balance: Web3Number;
3139
- /**
3140
- * Funds in transit to/from Extended.
3141
- * Positive = deposit in transit (funds left wallet, not yet credited on Extended).
3142
- * Negative = withdrawal in transit (funds left Extended, not yet received in wallet).
3143
- */
3144
- pendingDeposit: Web3Number;
3145
- }
3146
- /**
3147
- * Generic token balance with USD valuation.
3148
- */
3149
- interface TokenBalance {
3150
- token: TokenInfo;
3151
- amount: Web3Number;
3152
- usdValue: number;
3153
- }
3154
- /**
3155
- * Per-position exposure change on the Extended exchange.
3156
- * Positive delta = increase position size, negative = reduce.
3157
- */
3158
- interface ExtendedPositionDelta {
3159
- instrument: string;
3160
- delta: Web3Number;
3161
- }
3162
- /**
3163
- * Per-pool position change on Vesu.
3164
- * debtDelta: positive = borrow more, negative = repay.
3165
- * collateralDelta: positive = add collateral, negative = remove.
3166
- */
3167
- interface VesuPoolDelta {
3168
- poolId: ContractAddr;
3169
- collateralToken: TokenInfo;
3170
- debtToken: TokenInfo;
3171
- debtDelta: Web3Number;
3172
- collateralDelta: Web3Number;
3173
- collateralPrice: number;
3174
- debtPrice: number;
3175
- }
3176
- /**
3177
- * Enumerates all possible fund-routing paths used during execution.
3178
- */
3179
- declare enum RouteType {
3180
- /** Deposit USDC from operator wallet directly to Extended exchange */
3181
- WALLET_TO_EXTENDED = "WALLET_TO_EXTENDED",
3182
- /** USDC from vault allocator → deposit to Extended (via manager) */
3183
- VA_TO_EXTENDED = "VA_TO_EXTENDED",
3184
- /** Withdraw from Extended exchange → operator wallet */
3185
- EXTENDED_TO_WALLET = "EXTENDED_TO_WALLET",
3186
- /** Swap USDC → BTC to deposit to Vesu */
3187
- AVNU_DEPOSIT_SWAP = "AVNU_DEPOSIT_SWAP",
3188
- /** Increase leverage on Vesu i.e. deposit on vesu, borrow, in one go to create lever */
3189
- VESU_MULTIPLY_INCREASE_LEVER = "VESU_MULTIPLY_INCREASE_LEVER",
3190
- /** Decrease leverage on Vesu i.e. withdraw from vesu, repay, in one go to reduce leverage */
3191
- VESU_MULTIPLY_DECREASE_LEVER = "VESU_MULTIPLY_DECREASE_LEVER",
3192
- /** Swap BTC → USDC to withdraw from Vesu */
3193
- AVNU_WITHDRAW_SWAP = "AVNU_WITHDRAW_SWAP",
3194
- /** Borrow additional USDC from Vesu (when wallet + VA insufficient for Extended) */
3195
- VESU_BORROW = "VESU_BORROW",
3196
- /** Repay USDC debt to Vesu (debtDelta < 0) */
3197
- VESU_REPAY = "VESU_REPAY",
3198
- /** Transfer USDC from operator wallet to vault allocator */
3199
- WALLET_TO_VA = "WALLET_TO_VA",
3200
- /** Realize PnL on Extended exchange */
3201
- REALISE_PNL = "REALISE_PNL",
3202
- /** Increase leverage on Extended exchange i.e. deposit on extended, in one go to create lever */
3203
- EXTENDED_INCREASE_LEVER = "EXTENDED_INCREASE_LEVER",
3204
- /** Decrease leverage on Extended exchange i.e. withdraw from extended, in one go to reduce leverage */
3205
- EXTENDED_DECREASE_LEVER = "EXTENDED_DECREASE_LEVER",
3206
- /** Increase leverage on Extended exchange to max leverage (e.g. 4x from 3x) */
3207
- CRISIS_INCREASE_EXTENDED_MAX_LEVERAGE = "CRISIS_INCREASE_EXTENDER_MAX_LEVERAGE",
3208
- /** Undo max leverage on Extended exchange to reduce leverage (e.g. 4x to 3x) */
3209
- CRISIS_UNDO_EXTENDED_MAX_LEVERAGE = "CRISIS_UNDO_EXTENDED_MAX_LEVERAGE",
3210
- /** Borrow beyyond target HF (e.g. 1.2 from 1.4) */
3211
- CRISIS_BORROW_BEYOND_TARGET_HF = "CRISIS_BORROW_BEYOND_TARGET_HF",
3212
- /** Bring liquidity from vault allocator to vault contract (for user withdrawals) */
3213
- BRING_LIQUIDITY = "BRING_LIQUIDITY",
3214
- RETURN_TO_WAIT = "RETURN_TO_WAIT"
3215
- }
3216
- /** Common fields shared by every route variant */
3217
- interface RouteBase {
3218
- /** Execution order — lower values execute first */
3219
- priority: number;
3220
- }
3221
- /** Simple fund-transfer routes: WALLET_TO_EXTENDED, VA_TO_EXTENDED, EXTENDED_TO_WALLET, WALLET_TO_VA */
3222
- interface TransferRoute extends RouteBase {
3223
- type: RouteType.WALLET_TO_EXTENDED | RouteType.VA_TO_EXTENDED | RouteType.EXTENDED_TO_WALLET | RouteType.WALLET_TO_VA;
3224
- /** Amount to transfer */
3225
- amount: Web3Number;
3226
- }
3227
- /** AVNU swap routes: AVNU_DEPOSIT_SWAP (USDC→BTC), AVNU_WITHDRAW_SWAP (BTC→USDC) */
3228
- interface SwapRoute extends RouteBase {
3229
- type: RouteType.AVNU_DEPOSIT_SWAP | RouteType.AVNU_WITHDRAW_SWAP;
3230
- /** Source token symbol */
3231
- fromToken: string;
3232
- /** Source amount */
3233
- fromAmount: Web3Number;
3234
- /** Destination token symbol */
3235
- toToken: string;
3236
- /** Exact output amount (if known; otherwise undefined means best-effort) */
3237
- toAmount?: Web3Number;
3238
- }
3239
- /** Vesu multiply lever routes: deposit+borrow or withdraw+repay in one go */
3240
- interface VesuMultiplyRoute extends RouteBase {
3241
- type: RouteType.VESU_MULTIPLY_INCREASE_LEVER | RouteType.VESU_MULTIPLY_DECREASE_LEVER;
3242
- /** Pool to interact with */
3243
- poolId: ContractAddr;
3244
- /** Collateral token info */
3245
- collateralToken: TokenInfo;
3246
- /** Collateral amount delta (positive = deposit, negative = withdraw) */
3247
- marginAmount: Web3Number;
3248
- swappedCollateralAmount: Web3Number;
3249
- /** Debt token info */
3250
- debtToken: TokenInfo;
3251
- /** Debt amount delta (positive = borrow, negative = repay) */
3252
- debtAmount: Web3Number;
3253
- }
3254
- /** Vesu single-side borrow / repay routes */
3255
- interface VesuDebtRoute extends RouteBase {
3256
- type: RouteType.VESU_BORROW | RouteType.VESU_REPAY;
3257
- /** Pool to interact with */
3258
- poolId: ContractAddr;
3259
- /** Amount to borrow (positive) or repay (negative) */
3260
- amount: Web3Number;
3261
- /** Collateral token info */
3262
- collateralToken: TokenInfo;
3263
- /** Debt token info */
3264
- debtToken: TokenInfo;
3265
- }
3266
- /** Realise PnL on Extended exchange */
3267
- interface RealisePnlRoute extends RouteBase {
3268
- type: RouteType.REALISE_PNL;
3269
- /** Amount of PnL to realise (the shortfall beyond available-to-withdraw) */
3270
- amount: Web3Number;
3271
- /** Extended instrument name (e.g. "BTC-USD") */
3272
- instrument: string;
3273
- }
3274
- /** Increase / decrease leverage on Extended exchange */
3275
- interface ExtendedLeverRoute extends RouteBase {
3276
- type: RouteType.EXTENDED_INCREASE_LEVER | RouteType.EXTENDED_DECREASE_LEVER;
3277
- /** Change in exposure denominated in the exposure token */
3278
- amount: Web3Number;
3279
- /** Extended instrument name (e.g. "BTC-USD") */
3280
- instrument: string;
3281
- }
3282
- /** Crisis: temporarily increase / undo max leverage on Extended — no args for now */
3283
- interface CrisisExtendedLeverRoute extends RouteBase {
3284
- type: RouteType.CRISIS_INCREASE_EXTENDED_MAX_LEVERAGE | RouteType.CRISIS_UNDO_EXTENDED_MAX_LEVERAGE;
3285
- }
3286
- /** Crisis: borrow beyond the normal target HF */
3287
- interface CrisisBorrowRoute extends RouteBase {
3288
- type: RouteType.CRISIS_BORROW_BEYOND_TARGET_HF;
3289
- /** Pool to borrow from */
3290
- poolId: ContractAddr;
3291
- /** Token being borrowed */
3292
- token: string;
3293
- /** Amount to borrow */
3294
- amount: Web3Number;
3295
- }
3296
- /** Bring liquidity from vault allocator to vault contract for user withdrawals */
3297
- interface BringLiquidityRoute extends RouteBase {
3298
- type: RouteType.BRING_LIQUIDITY;
3299
- /** Amount to bring */
3300
- amount: Web3Number;
3301
- }
3302
- /** Control routes: RETURN_TO_WAIT (stop execution, resume in next cycle) */
3303
- interface WaitRoute extends RouteBase {
3304
- type: RouteType.RETURN_TO_WAIT;
3305
- }
3306
- /**
3307
- * A single step in the execution plan produced by the solver.
3308
- * Discriminated union keyed on `type` — each variant carries only
3309
- * the metadata that specific route needs.
3310
- */
3311
- type ExecutionRoute = TransferRoute | SwapRoute | VesuMultiplyRoute | VesuDebtRoute | RealisePnlRoute | ExtendedLeverRoute | CrisisExtendedLeverRoute | CrisisBorrowRoute | BringLiquidityRoute | WaitRoute;
3312
- /**
3313
- * Broad category of a detected case. Multiple categories may apply simultaneously.
3314
- */
3315
- declare enum CaseCategory {
3316
- LTV_REBALANCE = "LTV_REBALANCE",
3317
- NEW_DEPOSITS = "NEW_DEPOSITS",
3318
- WITHDRAWAL = "WITHDRAWAL",
3319
- EXPOSURE_IMBALANCE = "EXPOSURE_IMBALANCE",
3320
- MARGIN_CRISIS = "MARGIN_CRISIS"
3321
- }
3322
- /**
3323
- * Specific case IDs corresponding to the situations defined in cases.json.
3324
- */
3325
- declare enum CaseId {
3326
- MANAGE_LTV = "MANAGE_LTV",
3327
- /** @deprecated use MANAGE_LTV */ LTV_VESU_LOW_TO_EXTENDED = "LTV_VESU_LOW_TO_EXTENDED",
3328
- /** @deprecated use MANAGE_LTV */ LTV_EXTENDED_PROFITABLE_AVAILABLE = "LTV_EXTENDED_PROFITABLE_AVAILABLE",
3329
- /** @deprecated use MANAGE_LTV */ LTV_EXTENDED_PROFITABLE_REALIZE = "LTV_EXTENDED_PROFITABLE_REALIZE",
3330
- /** @deprecated use MANAGE_LTV */ LTV_VESU_HIGH_USE_VA_OR_WALLET = "LTV_VESU_HIGH_USE_VA_OR_WALLET",
3331
- /** @deprecated use MANAGE_LTV */ LTV_EXTENDED_HIGH_USE_VA_OR_WALLET = "LTV_EXTENDED_HIGH_USE_VA_OR_WALLET",
3332
- DEPOSIT_FRESH_VAULT = "DEPOSIT_FRESH_VAULT",
3333
- DEPOSIT_EXTENDED_AVAILABLE = "DEPOSIT_EXTENDED_AVAILABLE",
3334
- DEPOSIT_VESU_BORROW_CAPACITY = "DEPOSIT_VESU_BORROW_CAPACITY",
3335
- DEPOSIT_COMBINATION = "DEPOSIT_COMBINATION",
3336
- WITHDRAWAL_SIMPLE = "WITHDRAWAL_SIMPLE",
3337
- MARGIN_CRISIS_EXTENDED = "MARGIN_CRISIS_EXTENDED",
3338
- MARGIN_CRISIS_VESU = "MARGIN_CRISIS_VESU",
3339
- IMBALANCE_EXTENDED_EXCESS_SHORT_NO_FUNDS = "IMBALANCE_EXTENDED_EXCESS_SHORT_NO_FUNDS",
3340
- IMBALANCE_EXTENDED_EXCESS_SHORT_HAS_FUNDS = "IMBALANCE_EXTENDED_EXCESS_SHORT_HAS_FUNDS",
3341
- IMBALANCE_VESU_EXCESS_LONG_NO_FUNDS = "IMBALANCE_VESU_EXCESS_LONG_NO_FUNDS",
3342
- IMBALANCE_VESU_EXCESS_LONG_HAS_FUNDS = "IMBALANCE_VESU_EXCESS_LONG_HAS_FUNDS"
3343
- }
3344
- /**
3345
- * A detected case describing the current system state and the
3346
- * high-level steps required to resolve it.
3347
- */
3348
- interface SolveCase {
3349
- id: CaseId;
3350
- category: CaseCategory;
3351
- title: string;
3352
- description: string;
3353
- /** High-level steps describing what needs to happen for this case */
3354
- steps: string[];
3355
- }
3356
- /** Decimal places for rounding collateral / exposure deltas in token terms (e.g. BTC) */
3357
- declare const COLLATERAL_PRECISION = 4;
3358
- /**
3359
- * A single detected case with its metadata, amounts, and the execution
3360
- * routes that belong to this case.
3361
- */
3362
- interface SolveCaseEntry {
3363
- case: SolveCase;
3364
- additionalArgs: {
3365
- amount?: Web3Number;
3366
- };
3367
- routes: ExecutionRoute[];
3368
- }
3369
- /**
3370
- * Maps each CaseId to the RouteTypes that are relevant for resolving it.
3371
- * Used to filter the global route list into per-case route subsets.
3372
- */
3373
- declare const CASE_ROUTE_TYPES: Record<CaseId, RouteType[]>;
3374
- /**
3375
- * Complete output from the solver describing all needed state changes.
3376
- *
3377
- * - cases: detected cases describing the system state and needed actions.
3378
- * - extendedDeposit: positive = deposit USDC into Extended, negative = withdraw.
3379
- * - extendedPositionDeltas: per-instrument exposure changes (with instrument id).
3380
- * - vesuDeltas: per-pool debt & collateral changes (with pool id and token pair).
3381
- * - vesuAllocationUsd: USDC directed to Vesu side (negative = unwind from Vesu).
3382
- * - extendedAllocationUsd: USDC directed to Extended side (negative = withdraw from Extended).
3383
- * - bringLiquidityAmount: amount VA should send via bringLiquidity to the vault
3384
- * (= withdrawAmount input; 0 during investment cycles).
3385
- */
3386
- interface SolveResult {
3387
- /** Detected cases describing the current situation, amounts, and per-case routes */
3388
- cases: SolveCaseEntry[];
3389
- extendedDeposit: Web3Number;
3390
- extendedPositionDeltas: ExtendedPositionDelta[];
3391
- vesuDepositAmount: Web3Number;
3392
- vesuDeltas: VesuPoolDelta[];
3393
- vesuAllocationUsd: Web3Number;
3394
- extendedAllocationUsd: Web3Number;
3395
- bringLiquidityAmount: Web3Number;
3396
- /**
3397
- * Net pending deposit for Extended.
3398
- * Positive = deposit in transit (wallet → Extended), negative = withdrawal in transit.
3399
- * Used by ExecutionService to avoid double-sending transfers.
3400
- */
3401
- pendingDeposit: Web3Number;
3402
- }
3403
- interface StateManagerConfig {
3404
- pricer: PricerBase;
3405
- networkConfig: IConfig;
3406
- vesuAdapters: VesuMultiplyAdapter[];
3407
- extendedAdapter: ExtendedAdapter;
3408
- vaultAllocator: ContractAddr;
3409
- walletAddress: string;
3410
- /** Strategy / vault token — idle balance in the vault allocator is denominated in this asset */
3411
- assetToken: TokenInfo;
3412
- /**
3413
- * Native USDC (Starknet) — operator wallet stablecoin balance is always read for this token,
3414
- * independent of {@link assetToken} (e.g. when the strategy vault uses another asset).
3415
- */
3416
- usdcToken: TokenInfo;
3417
- /** Collateral token (e.g. WBTC) for wallet balance checks */
3418
- collateralToken: TokenInfo;
3419
- limitBalanceBufferFactor: number;
3420
- }
3421
- /**
3422
- * Returns a short human-readable summary of a route's key fields for logging.
3423
- */
3424
- declare function routeSummary(r: ExecutionRoute): string;
3425
- /**
3426
- * Single source of truth for all mutable state during a solve() call.
3427
- *
3428
- * Stores **raw** snapshots from refresh (no safety buffer applied in fields).
3429
- * Buffer {@link limitBalanceBufferFactor} is applied only in **getters** used
3430
- * during solve (caps, diagnostics). **Spend / add** methods mutate balances
3431
- * in **raw** USD only (no buffer on debits or credits).
3432
- *
3433
- * **Extended deposits** ({@link SolveBudget.addToExtAvailTrade}): while account equity is
3434
- * below required margin (Σ position value ÷ Extended leverage), incoming USDC is credited
3435
- * only to **balance** and **equity**. Only the excess is credited to **availableForWithdrawal**
3436
- * and **availableForTrade**, matching “margin first, then free collateral”.
3437
- */
3438
- declare class SolveBudget {
3439
- private unusedBalance;
3440
- private walletBalance;
3441
- /**
3442
- * Idle non-stable {@link StateManagerConfig.assetToken} in the vault allocator.
3443
- * Null when asset and USDC are the same token (VA idle stablecoin is only in {@link vaultUsdcBalance}).
3444
- */
3445
- private vaultAssetBalance;
3446
- /** Idle {@link StateManagerConfig.usdcToken} in the vault allocator (including when it is also the strategy asset). */
3447
- private vaultUsdcBalance;
3448
- private extendedPositions;
3449
- private extendedBalance;
3450
- private vesuPoolStates;
3451
- private vesuPerPoolDebtDeltasToBorrow;
3452
- private shouldVesuRebalance;
3453
- readonly assetToken: TokenInfo;
3454
- readonly usdcToken: TokenInfo;
3455
- constructor(state: {
3456
- assetToken: TokenInfo;
3457
- usdcToken: TokenInfo;
3458
- unusedBalance: TokenBalance[];
3459
- walletBalance: TokenBalance | null;
3460
- vaultAssetBalance: TokenBalance | null;
3461
- vaultUsdcBalance: TokenBalance | null;
3462
- extendedPositions: ExtendedPositionState[];
3463
- extendedBalance: ExtendedBalanceState | null;
3464
- vesuPoolStates: VesuPoolState[];
3465
- });
3466
- /** `1 - limitBalanceBufferFactor` — multiplier applied to raw notionals for “usable” USD. */
3467
- private _usableFraction;
3468
- /**
3469
- * Raw USD notional for a token row. USDC (and configured {@link usdcToken}) uses 1:1 from amount;
3470
- * non-stable assets (e.g. WBTC in VA) use {@link TokenBalance.usdValue} from the pricer at refresh.
3471
- */
3472
- private _rawTokenUsd;
3473
- /** Apply safety buffer to a raw USD scalar. */
3474
- bufferedUsd(rawUsd: number): number;
3475
- /** Convert a buffered “usable” USD amount to raw nominal USD (inverse of {@link bufferedUsd}). */
3476
- rawUsdFromBuffered(bufferedUsd: number): number;
3477
- /** Buffered USD notional for one token balance row. */
3478
- bufferedTokenUsd(tb: TokenBalance | null | undefined): number;
3479
- logStateSummary(): {
3480
- unusedBalances: {
3481
- token: string;
3482
- amount: number;
3483
- }[];
3484
- walletBalance: {
3485
- token: string;
3486
- amount: number;
3487
- } | undefined;
3488
- vaultAssetBalance: {
3489
- token: string;
3490
- amount: number;
3491
- } | undefined;
3492
- vaultUsdcBalance: {
3493
- token: string;
3494
- amount: number;
3495
- } | undefined;
3496
- vesuPoolStates: {
3497
- poolId: ContractAddr;
3498
- collateralAmount: number;
3499
- debtAmount: number;
3500
- }[];
3501
- vesuBorrowCapacity: number;
3502
- vesuRebalance: boolean[];
3503
- vesuPerPoolDebtDeltasToBorrow: number[];
3504
- extendedBalance: number | undefined;
3505
- extendedEquity: number | undefined;
3506
- extendedAvailableForTrade: number | undefined;
3507
- extendedAvailableForWithdrawal: number | undefined;
3508
- extendedUnrealisedPnl: number | undefined;
3509
- extendedPendingDeposit: number | undefined;
3510
- extendedPositions: {
3511
- instrument: string;
3512
- size: number;
3513
- valueUsd: number;
3514
- }[];
3515
- };
3516
- /**
3517
- * Initialise derived views for a solve cycle. Mutates only when pending
3518
- * withdrawal from Extended is in transit (credits wallet raw balance).
3519
- */
3520
- initBudget(): void;
3521
- /**
3522
- * Apply a safety buffer to all liquid balances (VA, wallet, extended trade/withdraw/upnl,
3523
- * unused balances). Call after withdrawal classification but before LTV/deposit classifiers
3524
- * so that withdrawal uses full raw amounts while subsequent classifiers see buffered values.
3525
- */
3526
- applyBuffer(factor: number): void;
3527
- get vesuPoolState(): VesuPoolState;
3528
- /** Buffered VA USD: non-stable asset slot (if any) + USDC slot. */
3529
- get vaUsd(): number;
3530
- /** Buffered USD in VA strategy-asset bucket only. */
3531
- get vaAssetUsd(): number;
3532
- /** Buffered USD in VA USDC bucket (includes full VA idle when asset === USDC). */
3533
- get vaUsdcUsd(): number;
3534
- get walletUsd(): number;
3535
- get vaWalletUsd(): number;
3536
- get extAvailWithdraw(): number;
3537
- get extAvailUpnl(): number;
3538
- /**
3539
- * Buffered Extended available-for-trade plus positive {@link ExtendedBalanceState.pendingDeposit}
3540
- * (deposit in transit is usable the same way as the pre-buffer implementation).
3541
- */
3542
- get extAvailTrade(): number;
3543
- get extPendingDeposit(): number;
3544
- /**
3545
- * Aggregate positive per-pool borrow headroom (USD). Repay/borrow routes update
3546
- * {@link vesuPerPoolDebtDeltasToBorrow}; no separate counter.
3547
- */
3548
- get vesuBorrowCapacity(): number;
3549
- /** Diagnostic: buffered idle + positive debt delta + buffered Extended afT + in-flight deposit. */
3550
- get totalUnused(): number;
3551
- /** Sum of buffered USD across merged unused-balance rows (VA + wallet). */
3552
- get unusedBalancesBufferedUsdSum(): number;
3553
- /** Read-only snapshot view for validation / logging. */
3554
- get unusedBalanceRows(): readonly TokenBalance[];
3555
- /** Read-only Vesu pool view for solve computations. */
3556
- get vesuPools(): readonly VesuPoolState[];
3557
- /** Read-only Extended positions view for solve computations. */
3558
- get extendedPositionsView(): readonly ExtendedPositionState[];
3559
- /** Read-only Extended balance view for diagnostics / margin checks. */
3560
- get extendedBalanceView(): ExtendedBalanceState | null;
3561
- /** Current debt deltas per pool (positive=borrow, negative=repay). */
3562
- get vesuDebtDeltas(): readonly Web3Number[];
3563
- /** Per-pool rebalance flags derived from target HF checks. */
3564
- get vesuRebalanceFlags(): readonly boolean[];
3565
- /** Raw USD in VA (USDC slot + non-stable asset slot when distinct); spend caps when executing transfers. */
3566
- private _vaRawUsd;
3567
- /** VA liquidity usable for repay / {@link spendVaRawUsd} (matches nominal balances after any {@link applyBuffer} scaling). */
3568
- get vaRawUsd(): number;
3569
- private _walletRawUsd;
3570
- /** Remove up to `usd` notional from a token balance, scaling token amount proportionally. */
3571
- private _deductUsdFromTokenBalance;
3572
- /** Add USD notional; infers price from current amount/usd when possible, else 1:1. */
3573
- private _addUsdToTokenBalance;
3574
- /**
3575
- * Rebuilds {@link unusedBalance} from vault + wallet snapshots (same merge as refresh).
3576
- */
3577
- private _recomputeUnusedBalance;
3578
- /**
3579
- * Spend VA **raw** USD (up to {@link vaRawUsd}). Prefer {@link vaultUsdcBalance} when present, then {@link vaultAssetBalance}.
3580
- */
3581
- spendVA(rawDesired: number): number;
3582
- /**
3583
- * Spend nominal/raw USD from VA (e.g. Vesu repay, on-chain USDC). Does not apply the safety buffer to the cap.
3584
- */
3585
- spendVaRawUsd(rawUsdDesired: number): number;
3586
- /**
3587
- * Add **raw nominal USD** to VA (borrow proceeds, wallet→VA in raw USDC, etc.).
3588
- */
3589
- addToVA(rawUsd: number): void;
3590
- spendWallet(rawDesired: number): number;
3591
- /** Add **raw nominal USD** to the operator wallet balance (e.g. Extended→wallet withdrawal). */
3592
- addToWallet(rawUsd: number): void;
3593
- spendVAWallet(rawDesired: number): number;
3594
- private _updateExtAvailWithdraw;
3595
- private _updateExtAvailUpnl;
3596
- spendExtAvailTrade(rawDesired: number): number;
3597
- spendExtAvailTradeToEquityOnly(rawDesired: number): number;
3598
- spendExtAvailWithdraw(rawDesired: number): number;
3599
- spendExtAvailUpnl(rawDesired: number): number;
3600
- /**
3601
- * Withdraw from Extended **withdrawal bucket only** to operator wallet (planning).
3602
- * Used when VA must be funded from Extended and withdraw should be exhausted before unrealised PnL.
3603
- */
3604
- spendAvailWithdrawToWallet(rawDesired: number): number;
3605
- /**
3606
- * Required Extended equity (USD) for current open positions: total notional ÷ strategy leverage.
3607
- * Same basis as {@link ExtendedSVKVesuStateManager._classifyLtvExtended} margin check.
3608
- */
3609
- private _extendedMarginRequirementUsd;
3610
- /** How much more equity is needed before deposits should increase withdraw / trade availability. */
3611
- private _extendedEquityShortfallUsd;
3612
- /**
3613
- * Credits a USDC inflow on Extended. Fills margin shortfall (balance+equity only) first;
3614
- * any remainder is credited across balance, equity, availableForWithdrawal, and availableForTrade.
3615
- */
3616
- addToExtAvailTrade(rawUsd: number): void;
3617
- spendVesuBorrowCapacity(desired: number): {
3618
- used: number;
3619
- spendsByPool: Omit<VesuDebtRoute, 'priority' | 'type'>[];
3620
- };
3621
- repayVesuBorrowCapacity(desired: number): {
3622
- used: number;
3623
- spendsByPool: Omit<VesuDebtRoute, 'priority' | 'type'>[];
3624
- };
3625
- /** Update a Vesu pool's collateral and debt after a lever / borrow / repay route. */
3626
- applyVesuDelta(poolId: ContractAddr, collToken: TokenInfo, debtToken: TokenInfo, collDelta: Web3Number, debtDelta: Web3Number): void;
3627
- /**
3628
- * Update Extended position size after a lever route; sync {@link ExtendedPositionState.valueUsd}
3629
- * and margin buckets (released USD on decrease, locked USD on increase).
3630
- *
3631
- * @param collateralPriceUsd BTC collateral price for notional / margin math; if omitted, uses
3632
- * existing valueUsd / |size| or the first Vesu pool collateral price.
3633
- */
3634
- applyExtendedExposureDelta(instrument: string, sizeDelta: Web3Number, collateralPriceUsd?: number): void;
3635
- /** Pull margin for larger Extended exposure from liquid buckets, then balance/equity. */
3636
- private _lockExtendedMarginUsd;
3637
- /**
3638
- * For each Vesu pool, computes the debt delta needed to bring the position
3639
- * back to the target health factor.
3640
- *
3641
- * Positive = can borrow more, negative = need to repay.
3642
- */
3643
- private _computeperPoolDebtDeltasToBorrow;
3644
- }
3645
- declare function createSolveBudgetFromRawState(params: {
3646
- assetToken: TokenInfo;
3647
- usdcToken: TokenInfo;
3648
- unusedBalance: TokenBalance[];
3649
- walletBalance: TokenBalance | null;
3650
- vaultAssetBalance: TokenBalance | null;
3651
- vaultUsdcBalance: TokenBalance | null;
3652
- extendedPositions: ExtendedPositionState[];
3653
- extendedBalance: ExtendedBalanceState | null;
3654
- vesuPoolStates: VesuPoolState[];
3655
- limitBalanceBufferFactor?: number;
3656
- }): SolveBudget;
3657
- /**
3658
- * Reads all on-chain / off-chain state for the Extended + SVK + Vesu strategy,
3659
- * then solves for the optimal rebalancing deltas.
3660
- *
3661
- * Usage:
3662
- * const manager = new ExtendedSVKVesuStateManager(config);
3663
- * const result = await manager.solve();
3664
- */
3665
- declare class ExtendedSVKVesuStateManager {
3666
- private readonly _config;
3667
- private readonly _tag;
3668
- /** Single mutable state holder — initialised by _refresh(), budget by initBudget(). */
3669
- private _budget;
3670
- constructor(config: StateManagerConfig);
3671
- /**
3672
- * Main entry point. Refreshes all state, then computes and returns
3673
- * the optimal deltas for rebalancing the strategy.
3674
- *
3675
- * @param withdrawAmount — amount (in vault asset, e.g. USDC) the user wants
3676
- * to withdraw. When > 0 the solver shrinks protocol allocations so that the
3677
- * vault allocator ends up with enough balance to execute bringLiquidity.
3678
- * Pass 0 (default) for normal investment / rebalancing cycles.
3679
- */
3680
- solve(withdrawAmount?: Web3Number): Promise<SolveResult | null>;
3681
- /**
3682
- * Reads all on-chain and off-chain state in parallel and stores
3683
- * results in private instance variables.
3684
- */
3685
- private _refresh;
3686
- /** True when strategy asset and USDC share one token — VA idle balance is tracked as USDC, not as asset. */
3687
- private _vaultAssetAndUsdcAreSameToken;
3688
- /**
3689
- * Reads idle {@link StateManagerConfig.assetToken} in the vault allocator when it differs from USDC.
3690
- * When asset and USDC are the same token, returns null (that balance is reported via {@link _fetchVaultAllocatorUsdcBalanceIfDistinct} only).
3691
- */
3692
- private _fetchVaultAllocatorAssetBalance;
3693
- /**
3694
- * Reads {@link StateManagerConfig.usdcToken} idle in the vault allocator (always — distinct asset or USDC-as-asset).
3695
- */
3696
- private _fetchVaultAllocatorUsdcBalanceIfDistinct;
3697
- /**
3698
- * Merges vault-allocator asset (if any), vault-allocator USDC, and operator wallet
3699
- * balances into entries keyed by token address.
3700
- */
3701
- private _computeUnusedBalances;
3702
- /**
3703
- * Reads the operator wallet balance for {@link StateManagerConfig.usdcToken} only
3704
- * (wallet stablecoin is always USDC, regardless of strategy {@link StateManagerConfig.assetToken}).
3705
- */
3706
- private _fetchWalletBalances;
3707
- /**
3708
- * Reads the Extended exchange account-level balance (equity, available for
3709
- * trade/withdrawal, etc.). Returns null if the API call fails.
3710
- */
3711
- private _fetchExtendedBalance;
3712
- /**
3713
- * Computes the net pending deposit by subtracting pending withdrawals from
3714
- * pending deposits. Uses the Extended exchange asset operations API.
3715
- *
3716
- * Positive = deposit in transit (wallet → Extended).
3717
- * Negative = withdrawal in transit (Extended → wallet).
3718
- */
3719
- private _fetchPendingDeposit;
3720
- /**
3721
- * Reads all open positions on the Extended exchange. Each position
3722
- * includes instrument, side, size, USD value, and leverage.
3723
- */
3724
- private _fetchExtendedPositions;
3725
- /**
3726
- * Reads a single Vesu pool's position data: collateral amount/price,
3727
- * debt amount/price.
3728
- */
3729
- private _fetchSingleVesuPoolState;
3730
- /**
3731
- * Reads all Vesu pool states in parallel (one per configured adapter).
3732
- */
3733
- private _fetchAllVesuPoolStates;
3734
- /**
3735
- * Validates that all critical refreshed state is present and contains
3736
- * finite, sensible values. Throws on invalid state.
3737
- */
3738
- private _validateRefreshedState;
3739
- private _validateTokenBalanceOrThrow;
3740
- private _validateVesuPoolPricesOrThrow;
3741
- private _validateExtendedBalanceOrThrow;
3742
- private _assertPositiveFinite;
3743
- /**
3744
- * Computes total distributable capital by combining idle vault balance
3745
- * and Extended available balance, then adjusting for aggregate debt
3746
- * delta and any pending withdrawal.
3747
- *
3748
- * When withdrawAmount > 0 the distributable pool shrinks, forcing the
3749
- * allocation split to produce smaller (or negative) allocations — which
3750
- * in turn causes protocol positions to unwind and free capital for the
3751
- * vault allocator to execute bringLiquidity.
3752
- */
3753
- private _computeDistributableAmount;
3754
- /**
3755
- * Total investable = vault allocator balance + Extended available-for-trade +
3756
- * buffered unrealised PnL, matching `deposit_cases_extended_vesu.xlsx`:
3757
- * `(VA + wallet + EXT_WITH_AVL + EXT_UPNL) * (1 − buffer)`.
3758
- * Positive {@link ExtendedBalanceState.pendingDeposit} stays on the afT leg only (see {@link SolveBudget.extAvailTrade}).
3759
- */
3760
- private _computeTotalInvestableAmount;
3761
- private _sumDebtDeltas;
3762
- /**
3763
- * Splits distributable capital between Vesu and Extended using leverage
3764
- * ratios and existing exposure to match delta-neutral targets.
3765
- *
3766
- * Formula (from existing strategy):
3767
- * ExtendedAlloc = (vL * distributable + vesuExposure - extendedExposure) / (vL + eL)
3768
- * VesuAlloc = distributable - ExtendedAlloc
3769
- */
3770
- private _computeAllocationSplit;
3771
- private _hasNoVesuAdapters;
3772
- /**
3773
- * Distributes the total Vesu USD allocation across pools proportionally
3774
- * by existing collateral value, then converts each share to collateral
3775
- * token units.
3776
- */
3777
- private _computePerPoolCollateralDeltas;
3778
- /**
3779
- * Determines how much of the total Vesu allocation goes to a single pool.
3780
- * Single-pool or zero-total cases get the entire allocation.
3781
- * Multi-pool cases split proportionally by current collateral USD value.
3782
- */
3783
- private _computePoolCollateralShare;
3784
- /**
3785
- * Computes per-position exposure deltas for delta neutrality.
3786
- * Target: total Extended short exposure = total projected Vesu collateral
3787
- * exposure (current + collateral deltas).
3788
- */
3789
- private _computeExtendedPositionDeltas;
3790
- /**
3791
- * Target Extended exposure = sum of (current collateral + collateralDelta)
3792
- * * price, across all Vesu pools.
3793
- */
3794
- private _computeTargetExtendedExposure;
3795
- private _hasNoExtendedPositions;
3796
- /**
3797
- * Creates a single-element delta array for the default instrument
3798
- * when no Extended positions currently exist.
3799
- */
3800
- private _singleInstrumentDelta;
3801
- /**
3802
- * Distributes a total exposure delta proportionally across existing
3803
- * positions by their current USD value share.
3804
- */
3805
- private _distributeExposureDeltaAcrossPositions;
3806
- /**
3807
- * Returns the fraction (0–1) of total Extended exposure held by
3808
- * a single position. Returns 1 when there is only one position
3809
- * or when total exposure is zero.
3810
- */
3811
- private _positionExposureShareFraction;
3812
- /**
3813
- * Net deposit change = allocation target − currently available for trade.
3814
- * Positive = need to deposit more, negative = can withdraw excess.
3815
- */
3816
- private _computeExtendedDepositDelta;
3817
- private _computeVesuDepositAmount;
3818
- /**
3819
- * The wallet is a pass-through for USDC flows between the vault allocator
3820
- * and the Extended exchange.
3821
- *
3822
- * Positive = vault allocator → wallet → Extended (deposit)
3823
- * Negative = Extended → wallet → vault allocator (withdrawal)
3824
- */
3825
- private _deriveWalletDelta;
3826
- /**
3827
- * The bringLiquidity amount is the USDC that the vault allocator must
3828
- * transfer back to the vault contract for the user's withdrawal.
3829
- * Equals the withdrawAmount passed into solve(); 0 during investment cycles.
3830
- */
3831
- private _computeBringLiquidityAmount;
3832
- private _buildVesuRepayRoutes;
3833
- private _buildVesuBorrowRoutes;
3834
- private _getWalletToVARoute;
3835
- private _getWalletToEXTENDEDRoute;
3836
- private _getVAToEXTENDEDRoute;
3837
- private _getExtendedToWalletRoute;
3838
- private _getWALLETToVARoute;
3839
- private _getUpnlRoute;
3840
- /**
3841
- * 1. Withdrawal — source funds in priority order:
3842
- * 1) VA balance 2) Wallet 3) Vesu borrow capacity
3843
- * 4) Extended available-for-withdrawal + unrealised PnL
3844
- * 5) Unwind positions on both sides (freed funds handled next cycle)
3845
- */
3846
- private _classifyWithdrawal;
3847
- /**
3848
- * 2a. LTV Rebalance — Vesu side
3849
- *
3850
- * Triggered when vesuPerPoolDebtDeltasToBorrow sum is negative (high LTV, needs repayment).
3851
- * Sources funds to VA so the subsequent deposit classifier can build the correct lever routes.
3852
- *
3853
- * Priority: 1) VA + Wallet (no routes) 2) Extended available-for-withdrawal
3854
- * 3) Extended uPnL 4) Margin crisis (future)
3855
- *
3856
- * Design: accumulate all ext-to-wallet moves, add transfer routes at the end (principle #3).
3857
- */
3858
- /**
3859
- * Unified LTV / exposure classifier: `rebalance()` drives both LTV (debt, margin,
3860
- * funding) and Vesu↔Extended position alignment. There is no separate imbalance pass.
3861
- * Computes both Vesu repay and Extended margin needs,
3862
- * then builds all routes in a single pass with no duplicate transfers.
3863
- *
3864
- * Vesu repay priority: VA > Wallet > ExtAvl > ExtUpnl
3865
- * Extended margin priority: Wallet > VA > VesuBorrow
3866
- * Shared sources consumed by Vesu first (higher priority).
3867
- */
3868
- private _classifyLTV;
3869
- private _ltvRebalanceInputsFromBudget;
3870
- private _isLtvRebalanceNoop;
3871
- /**
3872
- * Turn pure rebalance() deltas into execution routes.
3873
- * Order: Vesu multiply decrease → Extended decrease → aggregated transfers
3874
- * (REALISE_PNL, EXTENDED_TO_WALLET + WAIT, WALLET_TO_VA, VESU_BORROW, VESU_REPAY, VA_TO_EXTENDED),
3875
- * then Vesu multiply increase and Extended increase (need VA / Extended funded first).
3876
- */
3877
- private _buildLtvRoutesFromRebalanceDeltas;
3878
- /**
3879
- * LTV_EXTENDED_PROFITABLE_AVAILABLE:
3880
- * Extended has enough available-to-withdraw → withdraw, move to VA, repay Vesu.
3881
- * Routes: [EXTENDED_TO_WALLET, WALLET_TO_VA, VESU_REPAY]
3882
- */
3883
- /**
3884
- * LTV_EXTENDED_PROFITABLE_REALIZE:
3885
- * Extended has unrealised PnL → realise it first, then withdraw + repay.
3886
- * Routes: [REALISE_PNL, EXTENDED_TO_WALLET, WALLET_TO_VA, VESU_REPAY]
3887
- */
3888
- /**
3889
- * MARGIN_CRISIS_VESU:
3890
- * Neither VA/Wallet nor Extended withdrawal covers the shortfall.
3891
- * Temporarily increase Extended leverage to free margin, withdraw to VA, then
3892
- * decrease Vesu lever to bring LTV back in range.
3893
- * Routes: [CRISIS_INCREASE_EXTENDED_MAX_LEVERAGE, EXTENDED_TO_WALLET, WALLET_TO_VA,
3894
- * VESU_MULTIPLY_DECREASE_LEVER, EXTENDED_DECREASE_LEVER, CRISIS_UNDO_EXTENDED_MAX_LEVERAGE]
3895
- */
3896
- /**
3897
- * LTV_EXTENDED_HIGH_USE_VA_OR_WALLET:
3898
- * VA/Wallet has funds → route them to Extended.
3899
- * Routes: [VA_TO_EXTENDED, WALLET_TO_EXTENDED] (wallet-first, then VA for remainder)
3900
- */
3901
- /**
3902
- * LTV_VESU_LOW_TO_EXTENDED:
3903
- * Borrow USDC from Vesu, route through VA to Extended.
3904
- * Routes: [VESU_BORROW, VA_TO_EXTENDED]
3905
- */
3906
- /**
3907
- * MARGIN_CRISIS_EXTENDED:
3908
- * Borrow beyond target HF on Vesu to free USDC, deposit to Extended,
3909
- * then decrease Vesu/Extended lever, undo crisis leverage.
3910
- * Routes: [CRISIS_BORROW_BEYOND_TARGET_HF, VA_TO_EXTENDED,
3911
- * VESU_MULTIPLY_DECREASE_LEVER, EXTENDED_DECREASE_LEVER,
3912
- * CRISIS_UNDO_EXTENDED_MAX_LEVERAGE]
3913
- */
3914
- private _rebalanceFunds;
3915
- private _scaleVesuPoolDeltasByFactor;
3916
- /**
3917
- * 3. New Deposits / Excess Funds
3918
- *
3919
- * Computes how much exposure to create on Vesu and Extended, then
3920
- * distributes available funds using shortest-path priority chains:
3921
- * Extended margin: Wallet → VA → Vesu borrow
3922
- * Vesu margin: VA → Wallet → Extended
3923
- */
3924
- /**
3925
- * 3. New Deposits / Excess Funds
3926
- *
3927
- * Computes allocation split between Vesu and Extended, then sources
3928
- * funds and creates lever-increase routes.
3929
- *
3930
- * Order: {@link _rebalanceFunds} first → project VA / Extended liquid after the same funding
3931
- * routes (wallet→VA, borrow→VA, VA→Extended, Extended→wallet→VA) → ideal Vesu/Extended deltas
3932
- * from distributable split → cap common BTC by min(Vesu fundable, Extended fundable) → scale
3933
- * Vesu deltas and recompute Extended deltas so both sides stay matched.
3934
- *
3935
- * Fund flow (single pass — avoid VA→Extended then Extended→wallet round-trips):
3936
- * 1) Treat Vesu borrow headroom that the multiply route will consume as covering
3937
- * part of the Vesu USDC need (no standalone VESU_BORROW for that slice). Cap
3938
- * standalone VESU_BORROW→VA→Extended by remaining headroom.
3939
- * 2) Cover Extended deposit delta: REALISE_PNL first, then withdrawal→avail-trade,
3940
- * then wallet→Extended, then VA→Extended only up to VA surplus above the USDC
3941
- * that must remain for Vesu (after step 1), then borrow→VA→Extended.
3942
- * 3) Cover Vesu VA shortfall: wallet→VA, Extended withdrawal→wallet→VA, REALISE_PNL,
3943
- * then combined Extended→wallet→VA for the remainder.
3944
- * 4) RETURN_TO_WAIT when needed; then AVNU + VESU_MULTIPLY + EXTENDED_INCREASE.
3945
- */
3946
- /**
3947
- * @param skipAvnuDepositSwap Omit AVNU before Vesu multiply when LTV cases already ran this cycle
3948
- * (matrix tests expect deposit routes without that step).
3949
- */
3950
- private _classifyDeposits;
3951
- /** 4. Exposure Imbalance */
3952
- /**
3953
- * IMBALANCE_EXTENDED_EXCESS_SHORT_HAS_FUNDS:
3954
- * Extended has too much short exposure vs Vesu. Use VA/Wallet funds to
3955
- * add Vesu collateral and reduce Extended exposure.
3956
- *
3957
- * The new Vesu collateral covers part of the imbalance; the remaining
3958
- * gap is closed by reducing Extended short exposure.
3959
- *
3960
- * Routes: [AVNU_DEPOSIT_SWAP, VESU_MULTIPLY_INCREASE_LEVER, EXTENDED_DECREASE_LEVER]
3961
- */
3962
- /**
3963
- * IMBALANCE_EXTENDED_EXCESS_SHORT_NO_FUNDS:
3964
- * No available funds to add Vesu collateral → reduce Extended exposure
3965
- * by the full imbalance amount.
3966
- * Routes: [EXTENDED_DECREASE_LEVER]
3967
- */
3968
- private _buildImbalanceExtExcessShortNoFundsRoutes;
3969
- /**
3970
- * IMBALANCE_VESU_EXCESS_LONG_HAS_FUNDS:
3971
- * Vesu has too much long exposure vs Extended. Deposit funds on Extended
3972
- * to increase short exposure, and decrease Vesu lever for the remainder.
3973
- *
3974
- * Routes: [WALLET_TO_EXTENDED / VA_TO_EXTENDED, EXTENDED_INCREASE_LEVER,
3975
- * VESU_MULTIPLY_DECREASE_LEVER]
3976
- */
3977
- /**
3978
- * IMBALANCE_VESU_EXCESS_LONG_NO_FUNDS:
3979
- * No funds to increase Extended → decrease Vesu lever by the full imbalance.
3980
- * Routes: [VESU_MULTIPLY_DECREASE_LEVER]
3981
- */
3982
- /**
3983
- * Classifies the current state into actionable cases. Each case carries
3984
- * its own execution routes with amounts and state info.
3985
- */
3986
- private _classifyCases;
3987
- private _totalVesuCollateral;
3988
- private _totalVesuCollateralUsd;
3989
- private _totalExtendedExposure;
3990
- private _totalExtendedExposureUsd;
3991
- private _logSolveResult;
3992
- }
3993
-
3994
- /**
3995
- * Transaction metadata that SDK generates and risk engine stores in DB.
3996
- * This metadata is used to track transaction lifecycle without coupling SDK to DB.
3997
- */
3998
- interface TransactionMetadata {
3999
- protocolFrom: string;
4000
- protocolTo: string;
4001
- transactionType: 'DEPOSIT' | 'WITHDRAWAL' | 'NONE';
4002
- usdAmount: string;
4003
- status: 'COMPLETED' | 'FAILED' | 'PENDING';
4004
- cycleType: CycleType;
4005
- }
4006
- declare enum CycleType {
4007
- INVESTMENT = "INVESTMENT",
4008
- REBALANCE_PRICE_DROP = "REBALANCE_PRICE_DROP",
4009
- REBALANCE_PRICE_RISE = "REBALANCE_PRICE_RISE",
4010
- WITHDRAWAL = "WITHDRAWAL",
4011
- DELTA_NEUTRAL_ADJUSTMENT = "DELTA_NEUTRAL_ADJUSTMENT"
4012
- }
4013
- /**
4014
- * Enhanced return type for operations that generate transactions.
4015
- * Includes both the calls (for execution) and metadata (for DB storage).
4016
- */
4017
- interface TransactionResult<T = any> {
4018
- calls: Call[];
4019
- status: boolean;
4020
- transactionMetadata: TransactionMetadata;
4021
- }
4022
- /**
4023
- * Key lifecycle event types emitted during execution.
4024
- * Used by callers (e.g. risk engine) to hook into the execution pipeline
4025
- * and persist state to DB, send alerts, etc.
4026
- */
4027
- declare enum ExecutionEventType {
4028
- /** Execution started — tx sent on-chain or order placed on exchange */
4029
- INITIATED = "INITIATED",
4030
- /** Execution completed successfully — tx confirmed / order filled */
4031
- SUCCESS = "SUCCESS",
4032
- /** Execution failed — tx reverted / order rejected / timeout */
4033
- FAILURE = "FAILURE"
4034
- }
4035
- /**
4036
- * Metadata payload accompanying each execution lifecycle event.
4037
- * Contains relevant identifiers, prices, and contextual information.
4038
- */
4039
- interface ExecutionEventMetadata {
4040
- /** Route type string (e.g. RouteType value) */
4041
- routeType?: string;
4042
- /** Human-readable route summary */
4043
- routeSummary?: string;
4044
- /** On-chain transaction hash (when available) */
4045
- txHash?: string;
4046
- /** Exchange order ID (for off-chain orders) */
4047
- orderId?: string;
4048
- /** Amount involved in the operation */
4049
- amount?: string;
4050
- /** Protocol name */
4051
- protocol?: string;
4052
- /** Actual execution price (for exchange orders) */
4053
- executionPrice?: number;
4054
- /** Limit price that was set */
4055
- limitPrice?: number;
4056
- /** Error message on failure */
4057
- error?: string;
4058
- /** On-chain calls that were built */
4059
- calls?: Call[];
4060
- /** Extensible: any extra metadata */
4061
- [key: string]: any;
4062
- }
4063
- /**
4064
- * Callback invoked on key execution lifecycle events.
4065
- * Callers can use this to save to DB, send notifications, log, etc.
4066
- */
4067
- type ExecutionCallback = (eventType: ExecutionEventType, metadata: ExecutionEventMetadata) => void | Promise<void>;
4068
-
4069
- interface ExecutionConfig {
4070
- networkConfig: IConfig;
4071
- pricer: PricerBase;
4072
- vesuMultiplyAdapter: VesuMultiplyAdapter;
4073
- vesuModifyPositionAdapter: VesuModifyPositionAdapter;
4074
- extendedAdapter: ExtendedAdapter;
4075
- avnuAdapter: AvnuAdapter;
4076
- usdcTransferAdapter: TokenTransferAdapter;
4077
- vaultAllocator: ContractAddr;
4078
- walletAddress: string;
4079
- wbtcToken: TokenInfo;
4080
- usdcToken: TokenInfo;
4081
- /**
4082
- * Returns the strategy's merkle tree (built from all leaf adapters).
4083
- * Used to generate proofs for adapter manage calls.
4084
- */
4085
- getMerkleTree: () => StandardMerkleTree;
4086
- /**
4087
- * Combines merkle proofs and ManageCall[] into a single on-chain Call
4088
- * that invokes `manage_vault_with_merkle_verification` on the manager contract.
4089
- */
4090
- getManageCall: (proofs: string[][], manageCalls: ManageCall[]) => Call;
4091
- /**
4092
- * Callback to get the bring-liquidity call from the strategy.
4093
- */
4094
- getBringLiquidityCall: (params: {
4095
- amount: Web3Number;
4096
- }) => Promise<Call>;
4097
- /**
4098
- * Optional callback invoked on key execution lifecycle events.
4099
- * Use to persist state to DB, send alerts, etc.
4100
- */
4101
- onExecutionEvent?: ExecutionCallback;
4102
- /**
4103
- * Acceptable slippage for Extended limit orders in basis points.
4104
- * E.g. 10 = 0.1%. Default: 10 (0.1%).
4105
- * For BUY orders: limitPrice = midPrice * (1 + slippage)
4106
- * For SELL orders: limitPrice = midPrice * (1 - slippage)
4107
- */
4108
- extendedAcceptableSlippageBps?: number;
4109
- /**
4110
- * Maximum acceptable price divergence between Extended and Vesu
4111
- * execution prices in basis points. Default: 50 (0.5%).
4112
- *
4113
- * During increase exposure (extended SHORT + vesu LONG):
4114
- * (extendedPrice - vesuPrice) / vesuPrice must be > -maxDivergence
4115
- * During decrease exposure (extended BUY + vesu decrease):
4116
- * (extendedPrice - vesuPrice) / vesuPrice must be < +maxDivergence
4117
- */
4118
- maxPriceDivergenceBps?: number;
4119
- /**
4120
- * Max time (ms) to wait for Extended limit order fill in coordinated
4121
- * dual-exchange mode. Default: 3000 (3 seconds).
4122
- */
4123
- extendedFillTimeoutMs?: number;
4124
- }
4125
- /**
4126
- * Processes a {@link SolveResult} and translates each case's {@link ExecutionRoute}s into
4127
- * concrete on-chain transaction calls (batched) or off-chain API operations.
4128
- *
4129
- * Key design principles:
4130
- *
4131
- * 1. **Case-based execution**: Cases are processed sequentially. Within each
4132
- * case, routes execute in priority order.
4133
- *
4134
- * 2. **RETURN_TO_WAIT**: When encountered, all pending on-chain calls are
4135
- * flushed and execution halts. The remaining routes will be re-computed
4136
- * in the next solve cycle once async operations (bridge, deposit credit) settle.
4137
- *
4138
- * 3. **On-chain batching**: Consecutive on-chain routes (Starknet calls) are
4139
- * accumulated into a single multicall batch. Off-chain routes (Extended API)
4140
- * flush the batch, execute independently, then resume accumulation.
4141
- *
4142
- * 4. **pendingDeposit awareness**: Transfers to Extended are reduced by any
4143
- * amount already in transit, avoiding double-sends.
4144
- *
4145
- * 5. **AVNU buffer**: Swap amounts use a 0.1% buffer to account for slippage.
4146
- *
4147
- * Usage:
4148
- * const executor = new ExecutionService(config);
4149
- * const results = await executor.execute(solveResult);
4150
- */
4151
- declare class ExecutionService {
4152
- private readonly _config;
4153
- private readonly _tag;
4154
- private readonly _tokenSymbols;
4155
- private readonly _tokenDecimals;
4156
- private readonly _poolNames;
4157
- /**
4158
- * Remaining pending deposit budget (consumed during execution to avoid double-sends).
4159
- * Initialised from SolveResult.pendingDeposit at the start of execute().
4160
- */
4161
- private _pendingDepositRemaining;
4162
- /**
4163
- * Starknet account used for on-chain estimation in coordinated mode.
4164
- * Set at the start of execute() and valid for the duration of the call.
4165
- */
4166
- private _account;
4167
- constructor(config: ExecutionConfig);
4168
- /**
4169
- * Emits a lifecycle event via the configured callback (if present).
4170
- * Safe to call even when no callback is configured.
4171
- */
4172
- private _emitEvent;
4173
- private _getProofGroupsForManageCalls;
4174
- /**
4175
- * Builds a single manage call (manage_vault_with_merkle_verification) for an adapter.
4176
- *
4177
- * Pattern:
4178
- * 1. Calls adapter.getDepositCall / getWithdrawCall to get ManageCall[]
4179
- * 2. Gets merkle proofs for the adapter's leaves
4180
- * 3. Combines via getManageCall into a single on-chain Call
4181
- *
4182
- * Use this for any VA-routed operation that needs merkle proof verification.
4183
- */
4184
- private _buildAdapterManageCall;
4185
- private _getExtendedMidPrice;
4186
- /**
4187
- * Executes a limit order on Extended with acceptable slippage from mid spot price.
4188
- *
4189
- * Flow:
4190
- * 1. Set leverage on the market
4191
- * 2. Fetch orderbook → compute mid price
4192
- * 3. Apply configured slippage to derive limit price
4193
- * 4. Place IOC limit order at that price
4194
- * 5. Poll for fill status with retries
4195
- *
4196
- * Returns execution details including the fill price, or null on failure.
4197
- */
4198
- private _executeExtendedLimitOrder;
4199
- private _fetchExtendedOrderStatusWithRetries;
4200
- private _cancelExtendedOrderIfOpen;
4201
- private _executeExtendedLimitOrderWithRecovery;
4202
- /** ExecutionRoute types that change BTC exposure (on-chain or off-chain). */
4203
- private static readonly EXPOSURE_CHANGING_ROUTES;
4204
- /** ExecutionRoute types that correspond to increasing delta-neutral exposure. */
4205
- private static readonly INCREASE_EXPOSURE_ROUTES;
4206
- /** On-chain route types that change BTC exposure (Vesu side). */
4207
- private static readonly ON_CHAIN_EXPOSURE_ROUTES;
4208
- /** Off-chain Extended route types that change BTC exposure. */
4209
- private static readonly EXTENDED_EXPOSURE_ROUTES;
4210
- /**
4211
- * Validates that the price divergence between Extended (orderbook mid) and
4212
- * AVNU (actual on-chain swap price) is within acceptable limits.
4213
- *
4214
- * Mirrors the check from `checkPriceDifferenceBetweenAvnuAndExtended` in the
4215
- * strategy — see investmentOrchestrator.ts for the call-site pattern.
4216
- *
4217
- * For OPEN (increasing exposure): we SELL on Extended (short) and BUY on AVNU (long).
4218
- * → Extended price should not be too far below AVNU price.
4219
- * → (extendedMid − avnuPrice) / avnuPrice must be > −maxDivergence
4220
- *
4221
- * For CLOSE (decreasing exposure): we BUY on Extended (close short) and SELL on AVNU.
4222
- * → Extended price should not be too far above AVNU price.
4223
- * → (extendedMid − avnuPrice) / avnuPrice must be < +maxDivergence
4224
- *
4225
- * @param isIncreasingExposure true when opening/increasing delta-neutral position
4226
- * @throws if divergence exceeds configured maxPriceDivergenceBps
4227
- */
4228
- private _validatePriceDivergence;
4229
- /**
4230
- * Computes the net weighted execution price (USDC per BTC) across all adapters
4231
- * that have a stored SwapPriceInfo from the most recent call build.
4232
- *
4233
- * For deposit (USDC→BTC): price = sum(USDC sold) / sum(BTC bought)
4234
- * For withdraw (BTC→USDC): price = sum(USDC bought) / sum(BTC sold)
4235
- * @returns no-swap means, logic is fine and explicit no swap is needed
4236
- */
4237
- private _getNetExecutionPrice;
4238
- /** Clears cached swap price info on all adapters to prevent stale data across cycles. */
4239
- private _clearAdapterPriceInfo;
4240
- /**
4241
- * Main entry point: takes a SolveResult and executes all cases in order,
4242
- * building the necessary transaction calls.
4243
- *
4244
- * - Cases are processed sequentially.
4245
- * - Within a case, on-chain calls are batched; off-chain calls flush the batch.
4246
- * - Dual-exchange exposure cases use the coordinated path (construct → estimate → fill Extended → send on-chain).
4247
- * - RETURN_TO_WAIT halts execution for the current case and all subsequent cases.
4248
- * - Execution stops on the first route failure.
4249
- *
4250
- * @param account Starknet account used for on-chain fee estimation in coordinated mode.
4251
- * @returns Ordered list of TransactionResults (one per batch/off-chain op).
4252
- */
4253
- execute(solveResult: SolveResult, account: Account): Promise<TransactionResult[]>;
4254
- /**
4255
- * Executes a single case's routes.
4256
- *
4257
- * First splits routes at the first RETURN_TO_WAIT into an "active window"
4258
- * (routes that will execute this cycle). If the active window contains both
4259
- * on-chain and off-chain exposure routes, delegates to the coordinated
4260
- * dual-exchange path. Otherwise, uses the standard route-by-route flow.
4261
- */
4262
- private _executeCase;
4263
- /**
4264
- * Standard route-by-route execution for non-coordinated cases.
4265
- *
4266
- * On-chain routes are accumulated into a Call[] batch. When an off-chain
4267
- * route or RETURN_TO_WAIT is encountered, the batch is flushed first.
4268
- */
4269
- private _executeStandardCase;
4270
- /**
4271
- * Coordinated execution for cases that touch both Vesu (on-chain) and
4272
- * Extended (off-chain) exposure in the same case.
4273
- *
4274
- * Flow:
4275
- * 1. Partition active routes into on-chain vs Extended
4276
- * 2. Construct all on-chain calls in parallel
4277
- * 3. Estimate on-chain batch (dry-run via account.estimateInvokeFee)
4278
- * 4. Validate price divergence between Extended and AVNU
4279
- * 5. Race Extended limit order fill against timeout
4280
- * 6. If filled → return Extended result + on-chain batch
4281
- * If timeout/failure → drop everything
4282
- *
4283
- * // TODO: If Extended fills but the orchestrator's on-chain multicall later
4284
- * // reverts, we have an unhedged Extended position. The orchestrator should
4285
- * // catch the on-chain failure, re-solve with updated state to recompute
4286
- * // necessary on-chain calls, and retry. This recovery is non-trivial and
4287
- * // should be implemented as a follow-up.
4288
- */
4289
- private _executeCoordinatedCase;
4290
- /** Returns true if the route produces Starknet Call objects (on-chain tx). */
4291
- private _isOnChainRoute;
4292
- /** Checks whether any route in the list is a RETURN_TO_WAIT sentinel. */
4293
- private _caseHitReturnToWait;
4294
- /**
4295
- * Returns true when the active window contains both on-chain exposure
4296
- * routes (Vesu/AVNU) and off-chain Extended exposure routes — meaning
4297
- * both exchanges participate in the same exposure change and should be
4298
- * executed via the coordinated (fill-or-abort) path.
4299
- */
4300
- private _isDualExchangeCase;
4301
- /** Dispatches an on-chain route to the appropriate call builder. */
4302
- private _buildOnChainCalls;
4303
- /**
4304
- * WALLET_TO_EXTENDED: Deposit USDC from operator wallet directly to Extended.
4305
- *
4306
- * Builds raw approve + deposit calls (NOT through the manager/merkle system)
4307
- * because the wallet interacts with Extended directly, not via vault allocator.
4308
- *
4309
- * Adjusts amount by pending deposit to avoid double-sending.
4310
- */
4311
- private _buildWalletToExtendedCalls;
4312
- /**
4313
- * VA_TO_EXTENDED: Deposit USDC from vault allocator to Extended.
4314
- *
4315
- * Uses the extended adapter's getDepositCall to build ManageCalls,
4316
- * then wraps them in a merkle-verified manage call through the manager contract.
4317
- *
4318
- * Adjusts amount by pending deposit to avoid double-sending.
4319
- */
4320
- private _buildVAToExtendedCalls;
4321
- /**
4322
- * WALLET_TO_VA: Transfer USDC from operator wallet to vault allocator.
4323
- * Caps amount by actual wallet balance.
4324
- */
4325
- private _buildWalletToVACalls;
4326
- /**
4327
- * AVNU_DEPOSIT_SWAP: Standalone USDC → BTC swap via AVNU.
4328
- *
4329
- * Uses avnu adapter's getDepositCall to build swap ManageCalls,
4330
- * then wraps in a merkle-verified manage call.
4331
- * Applies 0.1% buffer so downstream Vesu deposit has sufficient BTC.
4332
- */
4333
- private _buildAvnuDepositSwapCalls;
4334
- /**
4335
- * AVNU_WITHDRAW_SWAP: Standalone BTC → USDC swap via AVNU.
4336
- *
4337
- * Uses avnu adapter's getWithdrawCall to build swap ManageCalls,
4338
- * then wraps in a merkle-verified manage call.
4339
- * Applies 0.1% buffer so Vesu-returned BTC is sufficient for the swap.
4340
- */
4341
- private _buildAvnuWithdrawSwapCalls;
4342
- /**
4343
- * VESU_MULTIPLY_INCREASE_LEVER: Compound operation.
4344
- * 1. AVNU swap USDC → BTC (with 0.1% buffer on collateral amount)
4345
- * 2. Vesu multiply deposit — add BTC as collateral (triggers flash-loan leverage)
4346
- *
4347
- * Both steps go through the merkle-verified manager contract via their respective adapters.
4348
- */
4349
- private _buildVesuIncreaseLeverCalls;
4350
- /**
4351
- * VESU_MULTIPLY_DECREASE_LEVER: Compound operation.
4352
- * 1. Vesu multiply withdraw — reduce BTC collateral (repays proportional debt via flash-loan)
4353
- * 2. AVNU swap BTC → USDC (with 0.1% buffer to account for slippage)
4354
- *
4355
- * Both steps go through the merkle-verified manager contract via their respective adapters.
4356
- */
4357
- private _buildVesuDecreaseLeverCalls;
4358
- private _validateVesuDebtRoute;
4359
- /**
4360
- * VESU_BORROW: Borrow additional USDC from Vesu.
4361
- */
4362
- private _buildVesuBorrowCalls;
4363
- /**
4364
- * VESU_REPAY: Repay USDC debt to Vesu.
4365
- */
4366
- private _buildVesuRepayCalls;
4367
- /** BRING_LIQUIDITY: Transfer from VA to vault contract for user withdrawals. */
4368
- private _buildBringLiquidityCalls;
4369
- /**
4370
- * CRISIS_BORROW_BEYOND_TARGET_HF: Borrow beyond normal target HF.
4371
- * TODO: Implement crisis borrow flow when needed.
4372
- */
4373
- private _buildCrisisBorrowCalls;
4374
- /** Dispatches an off-chain route to the appropriate executor. */
4375
- private _executeOffChainRoute;
4376
- /**
4377
- * EXTENDED_TO_WALLET: Withdraw from Extended exchange to operator wallet.
4378
- *
4379
- * This initiates the off-chain withdrawal API call. When followed by
4380
- * RETURN_TO_WAIT, the executor will halt and the next solve cycle picks up
4381
- * once the withdrawal settles and wallet balance is updated.
4382
- *
4383
- * If a pending withdrawal is already in transit (pendingDeposit < 0),
4384
- * the amount is reduced accordingly.
4385
- */
4386
- private _executeExtendedToWallet;
4387
- /**
4388
- * REALISE_PNL: Converts unrealised PnL to realised by closing a portion
4389
- * of the short position and immediately reopening it.
4390
- *
4391
- * Uses {@link calculatePositionToCloseToWithdrawAmount} to determine the
4392
- * minimal position size to close so that the required amount becomes
4393
- * available for withdrawal.
4394
- *
4395
- * Both close and reopen orders use limit pricing via _executeExtendedLimitOrder.
4396
- *
4397
- * Steps:
4398
- * 1. Close portion of short position (BUY limit order) → realises PnL
4399
- * 2. Immediately reopen same size (SELL limit order) → maintains exposure
4400
- */
4401
- private _executeRealisePnl;
4402
- /**
4403
- * EXTENDED_INCREASE_LEVER: Create a SHORT sell limit order on Extended to
4404
- * increase delta-neutral exposure.
4405
- *
4406
- * Uses limit pricing: limitPrice = midPrice * (1 - slippage) to prevent
4407
- * selling at unfavourable rates.
4408
- *
4409
- * Validates price divergence between Extended and Vesu before execution.
4410
- */
4411
- private _executeExtendedIncreaseLever;
4412
- /**
4413
- * EXTENDED_DECREASE_LEVER: Close portion of SHORT position on Extended
4414
- * by placing a BUY limit order.
4415
- *
4416
- * Uses limit pricing: limitPrice = midPrice * (1 + slippage) to prevent
4417
- * buying at unfavourable rates.
4418
- *
4419
- * Validates price divergence between Extended and Vesu before execution.
4420
- */
4421
- private _executeExtendedDecreaseLever;
4422
- /**
4423
- * CRISIS_INCREASE_EXTENDED_MAX_LEVERAGE: Temporarily increase Extended
4424
- * leverage to the crisis maximum (e.g. 4x) to free margin.
4425
- */
4426
- private _executeCrisisIncreaseLeverage;
2560
+ depositAmount: Web3Number;
2561
+ debtAmount: Web3Number;
2562
+ }): UniversalManageCall[];
2563
+ getTag(): string;
4427
2564
  /**
4428
- * CRISIS_UNDO_EXTENDED_MAX_LEVERAGE: Revert Extended leverage back to
4429
- * the normal calculated level.
2565
+ * Gets LST APR for the strategy's underlying asset from Endur API
2566
+ * @returns Promise<number> The LST APR (not divided by 1e18)
4430
2567
  */
4431
- private _executeCrisisUndoLeverage;
2568
+ getLSTAPR(address: ContractAddr): Promise<number>;
2569
+ getVesuHealthFactors(blockNumber?: BlockIdentifier): Promise<number[]>;
2570
+ computeRebalanceConditionAndReturnCalls(): Promise<Call[]>;
2571
+ private getNewHealthFactor;
4432
2572
  /**
4433
- * Adjusts a deposit-to-Extended amount by the remaining pending deposit
4434
- * budget. If pending deposit > 0, those funds are already in transit and
4435
- * shouldn't be re-sent.
4436
2573
  *
4437
- * Mutates `_pendingDepositRemaining` as the budget is consumed.
4438
- */
4439
- private _consumePendingDeposit;
4440
- /**
4441
- * Applies a 0.1% buffer (AVNU_BUFFER_FACTOR) to an amount.
4442
- * This ensures the downstream consumer (Vesu deposit or AVNU swap)
4443
- * always has sufficient tokens despite minor slippage.
4444
- */
4445
- private _applyAvnuBuffer;
4446
- /**
4447
- * Creates a TransactionResult for a batch of on-chain calls.
4448
- * The caller is expected to send all calls in a single multicall transaction.
2574
+ * @param vesuAdapter
2575
+ * @param currentHf
2576
+ * @param isDeposit if true, attempt by adding collateral, else by repaying
2577
+ * @returns
4449
2578
  */
4450
- private _onChainBatchResult;
4451
- private _successResult;
4452
- private _failureResult;
2579
+ private getLegRebalanceAmount;
2580
+ getVesuModifyPositionCall(params: {
2581
+ isDeposit: boolean;
2582
+ leg1DepositAmount: Web3Number;
2583
+ }): Promise<Call>;
2584
+ getPendingRewards(): Promise<HarvestInfo[]>;
2585
+ getHarvestCall(): Promise<{
2586
+ call: Call;
2587
+ reward: Web3Number;
2588
+ tokenInfo: TokenInfo;
2589
+ }>;
2590
+ getRebalanceCall(params: {
2591
+ isLeg1toLeg2: boolean;
2592
+ amount: Web3Number;
2593
+ }): Promise<Call>;
2594
+ }
2595
+ declare enum UNIVERSAL_MANAGE_IDS {
2596
+ FLASH_LOAN = "flash_loan_init",
2597
+ VESU_LEG1 = "vesu_leg1",
2598
+ VESU_LEG2 = "vesu_leg2",
2599
+ APPROVE_TOKEN1 = "approve_token1",
2600
+ APPROVE_TOKEN2 = "approve_token2",
2601
+ APPROVE_BRING_LIQUIDITY = "approve_bring_liquidity",
2602
+ BRING_LIQUIDITY = "bring_liquidity",
2603
+ DEFISPRING_REWARDS = "defispring_rewards",
2604
+ APPROVE_SWAP_TOKEN1 = "approve_swap_token1",
2605
+ AVNU_SWAP_REWARDS = "avnu_swap_rewards"
2606
+ }
2607
+ declare enum UNIVERSAL_ADAPTER_IDS {
2608
+ VESU_MULTIPLY = "vesu_multiply",
2609
+ VESU_MODIFY = "vesu_modify",
2610
+ AVNU = "avnu"
4453
2611
  }
2612
+ declare function getContractDetails(settings: UniversalStrategySettings & {
2613
+ aumOracle?: ContractAddr;
2614
+ }): {
2615
+ address: ContractAddr;
2616
+ name: string;
2617
+ }[];
2618
+ declare const UniversalStrategies: IStrategyMetadata<UniversalStrategySettings>[];
4454
2619
 
4455
- interface VesuExtendedStrategySettings extends UniversalStrategySettings {
2620
+ interface HyperLSTStrategySettings extends UniversalStrategySettings {
2621
+ borrowable_assets: {
2622
+ tokenInfo: TokenInfo;
2623
+ poolId: ContractAddr;
2624
+ }[];
4456
2625
  underlyingToken: TokenInfo;
4457
- borrowable_assets: TokenInfo[];
4458
- targetHealthFactor: number;
4459
2626
  quoteAmountToFetchPrice: Web3Number;
2627
+ targetHealthFactor: number;
4460
2628
  minHealthFactor: number;
4461
2629
  aumOracle: ContractAddr;
4462
- minimumWBTCDifferenceForAvnuSwap: number;
4463
- walletAddress: string;
2630
+ adapterIds?: {
2631
+ /** VesuMultiplyAdapter for underlying-matched debt (first matching borrowable pool) */
2632
+ primaryMultiply: string;
2633
+ multiply: Record<string, string>;
2634
+ modify: Record<string, string>;
2635
+ };
4464
2636
  }
4465
- declare class VesuExtendedMultiplierStrategy<S extends VesuExtendedStrategySettings> extends SVKStrategy<S> {
4466
- wbtcToken: TokenInfo;
4467
- usdcToken: TokenInfo;
4468
- readonly stateManager: ExtendedSVKVesuStateManager;
2637
+ declare class UniversalLstMultiplierStrategy<S extends HyperLSTStrategySettings> extends SVKStrategy<S> {
2638
+ private quoteAmountToFetchPrice;
4469
2639
  constructor(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<S>);
2640
+ getTag(): string;
2641
+ private getAdapterById;
2642
+ getVesuMultiplyAdapterByKey(key: string): VesuMultiplyAdapter;
2643
+ getVesuSameTokenAdapter(): VesuMultiplyAdapter;
2644
+ getVesuMultiplyAdapters(): VesuMultiplyAdapter[];
2645
+ getRewardsAUM(_prevAum: Web3Number): Promise<Web3Number>;
2646
+ getLSTAvnuRate(): Promise<number>;
2647
+ getLSTExchangeRate(): Promise<number>;
2648
+ private _getMinOutputAmountLSTBuy;
2649
+ private _getMinOutputAmountLSTSell;
4470
2650
  /**
4471
- * Extracts the required adapters from metadata and constructs the
4472
- * state manager used by shouldInvest / handleWithdraw.
2651
+ * Uses vesu's multiple call to create leverage on LST
2652
+ * Deposit amount is in LST
2653
+ * @param params
4473
2654
  */
4474
- private _initializeStateManager;
2655
+ getFundManagementCall(params: {
2656
+ isDeposit: boolean;
2657
+ leg1DepositAmount: Web3Number;
2658
+ }): Promise<Call[] | null>;
2659
+ getLSTUnderlyingTokenInfo(): TokenInfo;
2660
+ getLSTAPR(_address: ContractAddr): Promise<number>;
2661
+ netAPY(): Promise<{
2662
+ net: number;
2663
+ splits: {
2664
+ apy: number;
2665
+ id: string;
2666
+ }[];
2667
+ }>;
2668
+ maxNewDeposits(params?: {
2669
+ isAPYComputation: boolean;
2670
+ }): Promise<number>;
2671
+ protected getUnusedBalanceAPY(): Promise<{
2672
+ apy: number;
2673
+ weight: number;
2674
+ }>;
2675
+ getAUM(unrealizedAUM?: boolean): Promise<{
2676
+ net: SingleTokenInfo;
2677
+ prevAum: Web3Number;
2678
+ splits: PositionInfo[];
2679
+ }>;
2680
+ getTVLUnrealized(): Promise<{
2681
+ net: SingleTokenInfo;
2682
+ prevAum: Web3Number;
2683
+ splits: PositionInfo[];
2684
+ }>;
2685
+ getUserUnrealizedGains(user: ContractAddr): Promise<{
2686
+ unrealizedGains: Web3Number;
2687
+ userShare: number;
2688
+ tokenInfo: TokenInfo;
2689
+ }>;
2690
+ }
2691
+ declare const AUDIT_URL = "https://docs.troves.fi/p/security#starknet-vault-kit";
2692
+ declare function getFAQs(lstSymbol: string, underlyingSymbol: string, isLST: boolean): FAQ[];
2693
+ declare const _riskFactor: RiskFactor[];
2694
+ declare function getInvestmentSteps(lstSymbol: string, underlyingSymbol: string): string[];
2695
+ declare const HyperLSTStrategies: IStrategyMetadata<HyperLSTStrategySettings>[];
2696
+
2697
+ interface BoostedxSTRKCarryStrategySettings extends UniversalStrategySettings {
2698
+ depositToken: TokenInfo;
2699
+ debtToken: TokenInfo;
2700
+ lstHyperToken: TokenInfo;
2701
+ vesuPoolId: ContractAddr;
2702
+ maxLTV: number;
2703
+ targetLTV: number;
2704
+ hyperLstVaultAddress: ContractAddr;
2705
+ hyperLstRedeemNFT: ContractAddr;
2706
+ trovesStrategyId: string;
2707
+ hasBtcFiRewards: boolean;
2708
+ adapterIds?: {
2709
+ vesu: string;
2710
+ avnu: string;
2711
+ hyper: string;
2712
+ transfer: string;
2713
+ };
2714
+ }
2715
+ declare class BoostedxSTRKCarryStrategy<S extends BoostedxSTRKCarryStrategySettings> extends SVKStrategy<S> {
2716
+ constructor(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<S>);
4475
2717
  getTag(): string;
2718
+ private getAdapterById;
2719
+ private getTruePriceForToken;
2720
+ getMinOutputAmountLSTBuy(amountInUnderlying: Web3Number): Promise<Web3Number>;
2721
+ getMinOutputAmountLSTSell(amountInLST: Web3Number): Promise<Web3Number>;
2722
+ getVesuModifyPositionCall(params: {
2723
+ isDeposit: boolean;
2724
+ leg1DepositAmount: Web3Number;
2725
+ debtAmount?: Web3Number;
2726
+ }): Promise<Call>;
2727
+ getVesuPositions(): Promise<VaultPosition[]>;
2728
+ getVesuHealthFactor(blockNumber?: BlockIdentifier): Promise<number>;
2729
+ getModifyHyperPositionCall(params: {
2730
+ isDeposit: boolean;
2731
+ amount: Web3Number;
2732
+ }): Promise<Call>;
2733
+ getAvnuSwapCall(params: {
2734
+ isDeposit: boolean;
2735
+ amount: Web3Number;
2736
+ minAmount?: Web3Number;
2737
+ }): Promise<Call>;
4476
2738
  /**
4477
- * Fetches current WBTC (collateral) and USDC (debt) prices from the pricer.
4478
- * Validates that both prices are finite and positive, throwing if not.
2739
+ * Returns the deposit token balance sitting idle inside the vault contract itself.
2740
+ * This balance can offset the required liquidity during withdrawal processing.
4479
2741
  */
4480
- getAssetPrices(): Promise<{
4481
- collateralPrice: PriceInfo;
4482
- debtPrice: PriceInfo;
4483
- }>;
4484
- getVesuMultiplyAdapter(): Promise<VesuMultiplyAdapter>;
4485
- getVesuModifyPositionAdapter(): Promise<VesuModifyPositionAdapter>;
4486
- getUsdcTransferAdapter(): Promise<TokenTransferAdapter>;
4487
- getAvnuAdapter(): Promise<AvnuAdapter>;
4488
- getExtendedAdapter(): Promise<ExtendedAdapter>;
2742
+ getUnusedBalanceVault(): Promise<Web3Number>;
4489
2743
  /**
4490
- * Creates an ExecutionService wired to this strategy's adapters and config.
4491
- * Use with `stateManager.solve()` to get a SolveResult, then pass it to
4492
- * `executionService.execute(solveResult)` for execution.
4493
- *
4494
- * @param onExecutionEvent - Optional callback for execution lifecycle events (DB persistence, alerts, etc.)
4495
- * @param extendedAcceptableSlippageBps - Slippage for Extended limit orders (default: 10 = 0.1%)
4496
- * @param maxPriceDivergenceBps - Max price divergence between Extended and AVNU (default: 50 = 0.5%)
2744
+ * Returns the current borrow token balance sitting unused in the vault allocator.
2745
+ * This covers borrow token from prior borrow cycles that hasn't been swapped yet.
2746
+ */
2747
+ getUnusedDebt(): Promise<Web3Number>;
2748
+ /**
2749
+ * Returns the LST balance sitting in the vault allocator.
2750
+ * This is non-zero when the previous cycle's request_redeem on the HyperPosition
2751
+ * has been settled — the redeemed LST lands here and is ready to be swapped.
4497
2752
  */
4498
- createExecutionService(opts?: {
4499
- onExecutionEvent?: ExecutionCallback;
4500
- extendedAcceptableSlippageBps?: number;
4501
- maxPriceDivergenceBps?: number;
4502
- }): Promise<ExecutionService>;
2753
+ getLstInVaultAllocator(): Promise<Web3Number>;
4503
2754
  /**
4504
- * Calculates the total Assets Under Management across all adapters.
4505
- * Aggregates position values from every adapter, converts to the vault's
4506
- * base asset, and returns the net AUM along with the previous AUM snapshot
4507
- * and per-position breakdowns.
2755
+ * Simulates depositing `depositAmount` on Vesu and returns the
2756
+ * incremental borrow token that would be borrowed. Needed to size the AVNU swap
2757
+ * call that is batched together with the Vesu call in the same transaction.
4508
2758
  */
2759
+ computeVesuDepositBorrowAmount(depositAmount: Web3Number): Promise<Web3Number>;
2760
+ computeVesuWithdrawDebtDelta(withdrawAmount: Web3Number): Promise<Web3Number>;
2761
+ getPendingHyperAssets(): Promise<Web3Number>;
2762
+ getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<{
2763
+ tokenInfo: TokenInfo;
2764
+ amount: Web3Number;
2765
+ usdValue: number;
2766
+ }>;
4509
2767
  getAUM(): Promise<{
4510
2768
  net: SingleTokenInfo;
4511
2769
  prevAum: Web3Number;
4512
2770
  splits: PositionInfo[];
4513
2771
  }>;
4514
2772
  /**
4515
- * Computes the maximum additional USDC that can be borrowed from Vesu
4516
- * while keeping the strategy profitable. Uses the Extended funding rate
4517
- * and Vesu supply APY to derive a break-even borrow APY, then queries
4518
- * Vesu for the max borrowable amount at that rate.
2773
+ * Get Vesu APYs for collateral and debt positions
2774
+ */
2775
+ getVesuAPYs(): Promise<{
2776
+ baseAPYs: number[];
2777
+ rewardAPYs: number[];
2778
+ positions: VaultPosition[];
2779
+ }>;
2780
+ /**
2781
+ * Get APY from the Hyper LST vault position
2782
+ */
2783
+ getHyperVaultAPY(): Promise<{
2784
+ apy: number;
2785
+ weight: number;
2786
+ }>;
2787
+ /**
2788
+ * Get APY for unused balance (idle funds in vault allocator)
2789
+ */
2790
+ protected getUnusedBalanceAPY(): Promise<{
2791
+ apy: number;
2792
+ weight: number;
2793
+ }>;
2794
+ /**
2795
+ * Compute weighted APY from individual APYs, weights, and total AUM
4519
2796
  */
4520
- getMaxBorrowableAmount(): Promise<Web3Number>;
2797
+ private computeAPY;
4521
2798
  /**
4522
- * Returns the current health metrics for the strategy:
4523
- * [0] Vesu health factor (maxLTV / actualLTV) — higher is safer.
4524
- * [1] Extended margin ratio (as percentage) — higher means more margin available.
2799
+ * Calculate net APY from base and reward APYs
4525
2800
  */
4526
- getVesuHealthFactors(): Promise<number[]>;
2801
+ protected returnNetAPY(baseAPYs: number[], rewardAPYs: number[], weights: number[], totalWeightUSD: number): Promise<{
2802
+ net: number;
2803
+ splits: {
2804
+ apy: number;
2805
+ id: string;
2806
+ }[];
2807
+ }>;
4527
2808
  /**
4528
- * Calculates the weighted net APY of the strategy across all positions.
4529
- * Combines Vesu supply APY (scaled by 0.1 performance fee) and Extended
4530
- * position APY, weighted by their respective USD values.
4531
- * Also returns per-position APY splits.
2809
+ * Calculate net APY across all positions (Vesu, Hyper vault, unused balance)
2810
+ * weighted by USD value
4532
2811
  */
4533
2812
  netAPY(): Promise<{
4534
2813
  net: number;
@@ -4538,477 +2817,16 @@ declare class VesuExtendedMultiplierStrategy<S extends VesuExtendedStrategySetti
4538
2817
  }[];
4539
2818
  }>;
4540
2819
  /**
4541
- * Fetches the operator wallet's current holdings for USDC and WBTC,
4542
- * returning each token's balance and USD value.
2820
+ * Calculate future rewards (e.g. BTCFI rewards) contribution to AUM
2821
+ * Similar to universal-strategy.tsx approach
4543
2822
  */
4544
- getWalletHoldings(): Promise<{
4545
- tokenInfo: TokenInfo;
4546
- amount: Web3Number;
4547
- usdValue: number;
4548
- }[]>;
2823
+ protected getRewardsAUM(prevAum: Web3Number): Promise<Web3Number>;
2824
+ getFundManagementCall(params: {
2825
+ isDeposit: boolean;
2826
+ leg1DepositAmount: Web3Number;
2827
+ }): Promise<Call[] | null>;
4549
2828
  }
4550
- declare const VesuExtendedTestStrategies: (extendedBackendReadUrl: string, extendedBackendWriteUrl: string, vaultIdExtended: number, minimumExtendedMovementAmount: number, minimumVesuMovementAmount: number, minimumExtendedRetriesDelayForOrderStatus: number, minimumExtendedPriceDifferenceForSwapOpen: number, maximumExtendedPriceDifferenceForSwapClosing: number) => IStrategyMetadata<VesuExtendedStrategySettings>[];
4551
-
4552
- declare const AddressesConfig: {
4553
- readonly tokens: {
4554
- readonly USDC: {
4555
- readonly address: "0x053C91253BC9682c04929cA02ED00b3E423f6710D2ee7e0D5EBB06F3eCF368A8";
4556
- readonly decimals: 6;
4557
- };
4558
- readonly WBTC: {
4559
- readonly address: "0x3fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac";
4560
- readonly decimals: 8;
4561
- };
4562
- };
4563
- readonly contracts: {
4564
- readonly EXTENDED: "0x062da0780fae50d68cecaa5a051606dc21217ba290969b302db4dd99d2e9b470";
4565
- readonly MULTIPLY: "0x07964760e90baa28841ec94714151e03fbc13321797e68a874e88f27c9d58513";
4566
- };
4567
- readonly wallet: {
4568
- readonly address: string;
4569
- };
4570
- };
4571
- declare const ExtendedConfig: {
4572
- readonly baseUrl: string;
4573
- readonly marketName: "BTC-USD";
4574
- readonly maintenanceMargin: 0.01;
4575
- readonly precision: 5;
4576
- readonly fees: number;
4577
- readonly minPositionSize: 0.0001;
4578
- };
4579
- declare const VesuConfig: {
4580
- readonly poolId: "0x02eef0c13b10b487ea5916b54c0a7f98ec43fb3048f60fdeedaf5b08f6f88aaf";
4581
- readonly maxLtv: 0.8428;
4582
- readonly maxLiquidationRatio: 0.86;
4583
- readonly targetHealthFactor: number;
4584
- readonly ekubo: {
4585
- readonly endpoint: "https://quoter-mainnet-api.ekubo.org/{{AMOUNT}}/{{TOKEN_FROM_ADDRESS}}/{{TOKEN_TO_ADDRESS}}";
4586
- readonly priceMaxSlippage: number;
4587
- };
4588
- readonly avnu: {
4589
- readonly api: "https://starknet.api.avnu.fi/swap/v2/quotes";
4590
- };
4591
- readonly targetLtv: 0.61;
4592
- readonly minDebtForVesuRebalacing: number;
4593
- };
4594
- declare const AbisConfig: {
4595
- readonly vesu: {
4596
- readonly multiply: ({
4597
- type: string;
4598
- name: string;
4599
- interface_name: string;
4600
- members?: undefined;
4601
- items?: undefined;
4602
- variants?: undefined;
4603
- inputs?: undefined;
4604
- kind?: undefined;
4605
- } | {
4606
- type: string;
4607
- name: string;
4608
- members: {
4609
- name: string;
4610
- type: string;
4611
- }[];
4612
- interface_name?: undefined;
4613
- items?: undefined;
4614
- variants?: undefined;
4615
- inputs?: undefined;
4616
- kind?: undefined;
4617
- } | {
4618
- type: string;
4619
- name: string;
4620
- items: {
4621
- type: string;
4622
- name: string;
4623
- inputs: {
4624
- name: string;
4625
- type: string;
4626
- }[];
4627
- outputs: {
4628
- type: string;
4629
- }[];
4630
- state_mutability: string;
4631
- }[];
4632
- interface_name?: undefined;
4633
- members?: undefined;
4634
- variants?: undefined;
4635
- inputs?: undefined;
4636
- kind?: undefined;
4637
- } | {
4638
- type: string;
4639
- name: string;
4640
- variants: {
4641
- name: string;
4642
- type: string;
4643
- }[];
4644
- interface_name?: undefined;
4645
- members?: undefined;
4646
- items?: undefined;
4647
- inputs?: undefined;
4648
- kind?: undefined;
4649
- } | {
4650
- type: string;
4651
- name: string;
4652
- inputs: {
4653
- name: string;
4654
- type: string;
4655
- }[];
4656
- interface_name?: undefined;
4657
- members?: undefined;
4658
- items?: undefined;
4659
- variants?: undefined;
4660
- kind?: undefined;
4661
- } | {
4662
- type: string;
4663
- name: string;
4664
- kind: string;
4665
- members: {
4666
- name: string;
4667
- type: string;
4668
- kind: string;
4669
- }[];
4670
- interface_name?: undefined;
4671
- items?: undefined;
4672
- variants?: undefined;
4673
- inputs?: undefined;
4674
- } | {
4675
- type: string;
4676
- name: string;
4677
- kind: string;
4678
- variants: {
4679
- name: string;
4680
- type: string;
4681
- kind: string;
4682
- }[];
4683
- interface_name?: undefined;
4684
- members?: undefined;
4685
- items?: undefined;
4686
- inputs?: undefined;
4687
- })[];
4688
- readonly pool: ({
4689
- type: string;
4690
- name: string;
4691
- interface_name: string;
4692
- members?: undefined;
4693
- variants?: undefined;
4694
- items?: undefined;
4695
- inputs?: undefined;
4696
- kind?: undefined;
4697
- } | {
4698
- type: string;
4699
- name: string;
4700
- members: {
4701
- name: string;
4702
- type: string;
4703
- }[];
4704
- interface_name?: undefined;
4705
- variants?: undefined;
4706
- items?: undefined;
4707
- inputs?: undefined;
4708
- kind?: undefined;
4709
- } | {
4710
- type: string;
4711
- name: string;
4712
- variants: {
4713
- name: string;
4714
- type: string;
4715
- }[];
4716
- interface_name?: undefined;
4717
- members?: undefined;
4718
- items?: undefined;
4719
- inputs?: undefined;
4720
- kind?: undefined;
4721
- } | {
4722
- type: string;
4723
- name: string;
4724
- items: {
4725
- type: string;
4726
- name: string;
4727
- inputs: {
4728
- name: string;
4729
- type: string;
4730
- }[];
4731
- outputs: {
4732
- type: string;
4733
- }[];
4734
- state_mutability: string;
4735
- }[];
4736
- interface_name?: undefined;
4737
- members?: undefined;
4738
- variants?: undefined;
4739
- inputs?: undefined;
4740
- kind?: undefined;
4741
- } | {
4742
- type: string;
4743
- name: string;
4744
- inputs: {
4745
- name: string;
4746
- type: string;
4747
- }[];
4748
- interface_name?: undefined;
4749
- members?: undefined;
4750
- variants?: undefined;
4751
- items?: undefined;
4752
- kind?: undefined;
4753
- } | {
4754
- type: string;
4755
- name: string;
4756
- kind: string;
4757
- members: {
4758
- name: string;
4759
- type: string;
4760
- kind: string;
4761
- }[];
4762
- interface_name?: undefined;
4763
- variants?: undefined;
4764
- items?: undefined;
4765
- inputs?: undefined;
4766
- } | {
4767
- type: string;
4768
- name: string;
4769
- kind: string;
4770
- variants: {
4771
- name: string;
4772
- type: string;
4773
- kind: string;
4774
- }[];
4775
- interface_name?: undefined;
4776
- members?: undefined;
4777
- items?: undefined;
4778
- inputs?: undefined;
4779
- })[];
4780
- };
4781
- readonly extended: {
4782
- readonly contract: ({
4783
- type: string;
4784
- name: string;
4785
- interface_name: string;
4786
- members?: undefined;
4787
- variants?: undefined;
4788
- items?: undefined;
4789
- inputs?: undefined;
4790
- kind?: undefined;
4791
- } | {
4792
- type: string;
4793
- name: string;
4794
- members: {
4795
- name: string;
4796
- type: string;
4797
- }[];
4798
- interface_name?: undefined;
4799
- variants?: undefined;
4800
- items?: undefined;
4801
- inputs?: undefined;
4802
- kind?: undefined;
4803
- } | {
4804
- type: string;
4805
- name: string;
4806
- variants: {
4807
- name: string;
4808
- type: string;
4809
- }[];
4810
- interface_name?: undefined;
4811
- members?: undefined;
4812
- items?: undefined;
4813
- inputs?: undefined;
4814
- kind?: undefined;
4815
- } | {
4816
- type: string;
4817
- name: string;
4818
- items: {
4819
- type: string;
4820
- name: string;
4821
- inputs: {
4822
- name: string;
4823
- type: string;
4824
- }[];
4825
- outputs: {
4826
- type: string;
4827
- }[];
4828
- state_mutability: string;
4829
- }[];
4830
- interface_name?: undefined;
4831
- members?: undefined;
4832
- variants?: undefined;
4833
- inputs?: undefined;
4834
- kind?: undefined;
4835
- } | {
4836
- type: string;
4837
- name: string;
4838
- inputs: {
4839
- name: string;
4840
- type: string;
4841
- }[];
4842
- interface_name?: undefined;
4843
- members?: undefined;
4844
- variants?: undefined;
4845
- items?: undefined;
4846
- kind?: undefined;
4847
- } | {
4848
- type: string;
4849
- name: string;
4850
- kind: string;
4851
- members: {
4852
- name: string;
4853
- type: string;
4854
- kind: string;
4855
- }[];
4856
- interface_name?: undefined;
4857
- variants?: undefined;
4858
- items?: undefined;
4859
- inputs?: undefined;
4860
- } | {
4861
- type: string;
4862
- name: string;
4863
- kind: string;
4864
- variants: {
4865
- name: string;
4866
- type: string;
4867
- kind: string;
4868
- }[];
4869
- interface_name?: undefined;
4870
- members?: undefined;
4871
- items?: undefined;
4872
- inputs?: undefined;
4873
- })[];
4874
- };
4875
- };
4876
-
4877
- /**
4878
- * Function to return formatted amount to BigInt
4879
- * Converts a decimal amount to the proper format for blockchain transactions
4880
- * @param {number} amount - The decimal amount to convert
4881
- * @param {number} fromTokenDecimals - The decimal precision of the token
4882
- * @returns {string} The formatted amount as a hexadecimal string
4883
- */
4884
- declare const returnFormattedAmount: (amount: number, toTokenDecimals: number) => string;
4885
- /**
4886
- * calculates the amount to distribute to Extended and Vesu
4887
- * Determines how much to allocate to each platform based on leverage calculations
4888
- * @param {number} amount - The total amount to distribute
4889
- * @returns {object} Object containing avnu_amount, extended_amount, and extended_leverage
4890
- */
4891
- declare const calculateAmountDistribution: (amountToInvest: number, collateralPrice: number, // in usd
4892
- collateralUnits: Web3Number, // existing collateral in vesu (e.g. BTC)
4893
- extendedExposureUsd: Web3Number) => {
4894
- vesuAmount: Web3Number;
4895
- extendedAmount: Web3Number;
4896
- extendedLeverage: number;
4897
- vesuLeverage: number;
4898
- };
4899
- /**
4900
- * calculate the amount distribution for withdrawal
4901
- * @param amount - The amount to withdraw
4902
- * @param client - The client
4903
- * @param marketName - The market name
4904
- * @returns {object} Object containing avnu_amount and extended_amount
4905
- */
4906
- declare const calculateAmountDistributionForWithdrawal: (amountInUsdc: Web3Number, collateralPrice: number, collateralUnits: Web3Number, extendedPosition: Position[] | null) => Promise<{
4907
- vesu_amount: Web3Number;
4908
- extended_amount: Web3Number;
4909
- extended_leverage: number;
4910
- vesu_leverage: number;
4911
- } | null>;
4912
- /**
4913
- * calculate the leverage required for Avnu
4914
- * calculates the optimal leverage for Avnu based on LTV ratios and price drop protection
4915
- * @returns {number} The calculated leverage value
4916
- */
4917
- declare const calculateVesuLeverage: () => number;
4918
- /**
4919
- * calculate leverage for extended
4920
- * calculates the maximum safe leverage for Extended based on maintenance margin and price drop protection
4921
- * @returns {number} The calculated leverage value
4922
- */
4923
- declare const calculateExtendedLevergae: () => number;
4924
- /**
4925
- * calculates the debt amount for leverage operations
4926
- * Determines how much debt to add or remove based on collateral changes and target health factor
4927
- * @param {Web3Number} collateralAmount - Current collateral amount
4928
- * @param {Web3Number} debtAmount - Current debt amount
4929
- * @param {number} debtPrice - Current price of the debt token
4930
- * @param {number} maxLtv - Maximum loan-to-value ratio (default: MAX_LTV_BTC_USDC)
4931
- * @param {number} addedAmount - Amount being added to collateral
4932
- * @param {number} collateralPrice - Current price of the collateral token
4933
- * @param {boolean} isDeposit - Whether this is a deposit (true) or withdrawal (false)
4934
- * @returns {object} Object containing deltadebtAmountUnits and isIncrease flag
4935
- */
4936
- declare const calculateDebtAmount: (collateralAmount: Web3Number, debtAmount: Web3Number, debtPrice: number, maxLtv: number | undefined, addedAmount: Web3Number, // this is in btc
4937
- collateralPrice: number, isDeposit: boolean, targetLtv?: number) => {
4938
- deltadebtAmountUnits: Web3Number;
4939
- isIncrease: boolean;
4940
- } | {
4941
- deltadebtAmountUnits: null;
4942
- isIncrease: null;
4943
- };
4944
- /**
4945
- * calculate the debt amount to be repaid for withdrawal
4946
- * @param debtAmount in debt units
4947
- * @param collateralAmount in collateral units
4948
- * @param maxLtv in percentage
4949
- * @param withdrawalAmount in collateral units
4950
- * @param collateralPrice in usd
4951
- * @param debtPrice in usd
4952
- * @returns deltadebtAmountUnits in debt units
4953
- * isIncrease: true if the debt amount is increasing, false if it is decreasing
4954
- */
4955
- declare const calculateDebtReductionAmountForWithdrawal: (debtAmount: Web3Number, collateralAmount: Web3Number, maxLtv: number | undefined, withdrawalAmount: Web3Number, collateralPrice: number, debtPrice: number, usdcDecimals: number) => {
4956
- deltadebtAmountUnits: string;
4957
- } | {
4958
- deltadebtAmountUnits: null;
4959
- };
4960
- /**
4961
- * calculate the amount to deposit on extended when incurring losses
4962
- * @param client - The client
4963
- * @returns The amount to deposit on extended when incurring losses
4964
- */
4965
- declare const calculateAmountDepositOnExtendedWhenIncurringLosses: (client: ExtendedWrapper) => Promise<Web3Number | null>;
4966
- /**
4967
- * calculate the amount of collateral to deposit to maintain the ltv
4968
- * The formula is:
4969
- * ((debt * debtPrice * targetHF) - (collateral * collateralPrice * ltv)) / ltv
4970
- * @param collateralAmount in collateral units
4971
- * @param debtAmount in debt units
4972
- * @param debtPrice in usd
4973
- * @param maxLtv
4974
- * @param collateralPrice in usd
4975
- * @param targetHF
4976
- * @returns deltaCollateralAmountUnits in collateral units
4977
- * null if there is an error
4978
- */
4979
- declare const calculateWBTCAmountToMaintainLTV: (collateralAmount: Web3Number, debtAmount: Web3Number, debtPrice: number, maxLtv: number | undefined, collateralPrice: number) => {
4980
- deltaCollateralAmountUnits: Web3Number;
4981
- } | {
4982
- deltaCollateralAmountUnits: null;
4983
- };
4984
- declare const calculateExposureDelta: (exposure_extended: number, exposure_vesu: number) => number;
4985
- /**
4986
- * calculate the delta percentage between the current btc price and the last btc price
4987
- * @param {number} btcPrice - The current btc price
4988
- * @param {number} lastBtcPrice - The last btc price
4989
- * @returns {number} The delta percentage
4990
- */
4991
- declare const calculateBTCPriceDelta: (btcPrice: number, lastBtcPrice: number) => number;
4992
- declare const calculateVesUPositionSizeGivenExtended: (extendedPositonSize: number, extendedHoldingAmount: Web3Number, collateralAmount: Web3Number, extendedBtcPrice: number) => {
4993
- vesuAmountInBTC: Web3Number;
4994
- extendedAmountInBTC: Web3Number;
4995
- };
4996
- /**
4997
- * calculate the debt amount to be repaid to maintain the ltv
4998
- * @param maxLtv - The maximum ltv
4999
- * @param existingVesuCollateral - The existing vesu collateral
5000
- * @param existingVesuDebt - The existing vesu debt
5001
- * @param collateralPrice - The collateral price
5002
- * @param debtPrice - The debt price
5003
- * @param targetHf - The target hf
5004
- * @@dev returns negative to represent debt to be repaid
5005
- * @returns The debt amount to be repaid
5006
- */
5007
- declare const calculateDeltaDebtAmount: (existingVesuCollateral: Web3Number, existingVesuDebt: Web3Number, debtPrice: number, collateralPrice: number) => {
5008
- deltaDebt: Web3Number;
5009
- shouldRebalance: boolean;
5010
- };
5011
- declare const calculatePositionToCloseToWithdrawAmount: (extendedBalance: Balance, extendedPositions: Position, amountToWithdraw: Web3Number) => Promise<Web3Number>;
2829
+ declare const BoostedxSTRKCarryStrategies: IStrategyMetadata<BoostedxSTRKCarryStrategySettings>[];
5012
2830
 
5013
2831
  /**
5014
2832
  * Filter option definition
@@ -5034,7 +2852,9 @@ declare enum StrategyType {
5034
2852
  UNIVERSAL = "universal",
5035
2853
  HYPER_LST = "hyper-lst",
5036
2854
  VESU_REBALANCE = "vesu-rebalance",
5037
- SENSEI = "sensei"
2855
+ SENSEI = "sensei",
2856
+ YOLO_VAULT = "yolo-vault",
2857
+ BOOSTEDXSTRKCARRY = "boostedxstrkcarry"
5038
2858
  }
5039
2859
  /**
5040
2860
  * Strategy metadata extracted from IStrategyMetadata
@@ -5085,10 +2905,12 @@ declare enum FactoryStrategyType {
5085
2905
  EKUBO_CL = "EKUBO_CL",
5086
2906
  HYPER_LST = "HYPER_LST",
5087
2907
  VESU_REBALANCE = "VESU_REBALANCE",
5088
- SENSEI = "SENSEI"
2908
+ SENSEI = "SENSEI",
2909
+ YOLO_VAULT = "YOLO_VAULT"
5089
2910
  }
5090
2911
  declare function createUniversalStrategy(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<UniversalStrategySettings>): UniversalStrategy<UniversalStrategySettings>;
5091
2912
  declare function createEkuboCLStrategy(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<CLVaultStrategySettings>): EkuboCLVault;
2913
+ declare function createYoloVaultStrategy(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<YoloVaultSettings>): YoLoVault;
5092
2914
  declare function createHyperLSTStrategy(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<HyperLSTStrategySettings>): UniversalLstMultiplierStrategy<HyperLSTStrategySettings>;
5093
2915
  declare function createVesuRebalanceStrategy(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<VesuRebalanceSettings>): VesuRebalance;
5094
2916
  declare function createSenseiStrategy(config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<SenseiVaultSettings>): SenseiVault;
@@ -5099,7 +2921,7 @@ declare function getStrategyTypeFromMetadata(metadata: IStrategyMetadata<any>):
5099
2921
  /**
5100
2922
  * Generic factory function that creates SDK strategy instances based on type
5101
2923
  */
5102
- declare function createStrategy(type: FactoryStrategyType, config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<any>): EkuboCLVault | VesuRebalance | SenseiVault | UniversalStrategy<UniversalStrategySettings> | UniversalLstMultiplierStrategy<HyperLSTStrategySettings>;
2924
+ declare function createStrategy(type: FactoryStrategyType, config: IConfig, pricer: PricerBase, metadata: IStrategyMetadata<any>): EkuboCLVault | VesuRebalance | SenseiVault | YoLoVault | UniversalStrategy<UniversalStrategySettings> | UniversalLstMultiplierStrategy<HyperLSTStrategySettings>;
5103
2925
 
5104
2926
  interface EkuboRouteNode {
5105
2927
  pool_key: {
@@ -5306,6 +3128,16 @@ declare class Midas {
5306
3128
  } | number>;
5307
3129
  }
5308
3130
 
3131
+ declare class EkuboPricer extends PricerBase {
3132
+ EKUBO_PRICE_FETCHER_ADDRESS: string;
3133
+ readonly contract: Contract;
3134
+ private readonly USDC_ADDRESS;
3135
+ private readonly USDC_DECIMALS;
3136
+ constructor(config: IConfig, tokens: TokenInfo[]);
3137
+ private div2Power128;
3138
+ getPrice(tokenAddr: string, blockIdentifier?: BlockIdentifier): Promise<PriceInfo>;
3139
+ }
3140
+
5309
3141
  declare class TelegramNotif {
5310
3142
  private subscribers;
5311
3143
  readonly bot: TelegramBot;
@@ -5458,4 +3290,4 @@ declare class PasswordJsonCryptoUtil {
5458
3290
  decrypt(encryptedData: string, password: string): any;
5459
3291
  }
5460
3292
 
5461
- export { type APYInfo, APYType, AUDIT_URL, AUMTypes, AVNU_EXCHANGE, AVNU_EXCHANGE_FOR_LEGACY_USDC, AVNU_LEGACY_SANITIZER, AVNU_MIDDLEWARE, AVNU_QUOTE_URL, AbisConfig, type AccessControlInfo, AccessControlType, type AccountInfo, type AdapterLeafType, AddressesConfig, type AllAccountsStore, type AmountInfo, type AmountsInfo, type ApiResponse, type ApproveCallParams, type AssetOperation, AssetOperationStatus, AssetOperationType, AuditStatus, AutoCompounderSTRK, AvnuAdapter, type AvnuAdapterConfig, type AvnuSwapCallParams, AvnuWrapper, type Balance, BaseAdapter, type BaseAdapterConfig, BaseStrategy, type BringLiquidityRoute, CASE_ROUTE_TYPES, type CLVaultStrategySettings, COLLATERAL_PRECISION, type CancelOrderRequest, CaseCategory, CaseId, CommonAdapter, type CommonAdapterConfig, ContractAddr, type CreateOrderRequest, type CrisisBorrowRoute, type CrisisExtendedLeverRoute, CycleType, DEFAULT_TROVES_STRATEGIES_API, type DecreaseLeverParams, Deployer, type DepositParams, type DualActionAmount, type DualTokenInfo, ERC20, EXTENDED_CONTRACT, EXTENDED_SANITIZER, type EkuboBounds, EkuboCLVault, EkuboCLVaultStrategies, type EkuboPoolKey, type EkuboQuote, EkuboQuoter, type EkuboRouteNode, type EkuboSplit, type ExecutionCallback, type ExecutionConfig, type ExecutionEventMetadata, ExecutionEventType, type ExecutionRoute, ExecutionService, ExitType, ExtendedAdapter, type ExtendedAdapterConfig, type ExtendedApiResponse, type ExtendedBalanceState, ExtendedConfig, type ExtendedLeverRoute, type ExtendedPositionDelta, type ExtendedPositionState, ExtendedSVKVesuStateManager, ExtendedWrapper, type ExtendedWrapperConfig, type FAQ, FactoryStrategyType, FatalError, type FilterOption, type FlashloanCallParams, FlowChartColors, type FundingPayment, type FundingRate, type GenerateCallFn, Global, HealthFactorMath, HyperLSTStrategies, type HyperLSTStrategySettings, type IConfig, type IInvestmentFlow, ILending, type ILendingMetadata, type ILendingPosition, type IProtocol, type IStrategyMetadata, type IncreaseLeverParams, Initializable, InstantWithdrawalVault, type L2Config, LSTAPRService, LSTPriceType, type LSTStats, type LeafAdapterFn, type LeafData, type LendingToken, type LoggerConfig, type LoggerLevel, type ManageCall, MarginType, type Market, type MarketStats, Midas, MyNumber, type NetAPYDetails, type NetAPYSplit, Network, type OpenOrder, OrderSide, OrderStatus, OrderStatusReason, OrderType, PRICE_ROUTER, type ParsedStarknetCall, PasswordJsonCryptoUtil, type PlacedOrder, type Position, type PositionAPY, type PositionAmount, type PositionHistory, type PositionInfo, PositionSide, PositionTypeAvnuExtended, Pragma, type PriceInfo, Pricer, PricerBase, PricerFromApi, PricerLST, PricerRedis, Protocols, type RealisePnlRoute, type RedemptionInfo, type RequiredFields, type RequiredKeys, type RequiredStoreConfig, type RiskFactor, type RiskFactorConfig, RiskType, type Route, type RouteNode, RouteType, SIMPLE_SANITIZER, SIMPLE_SANITIZER_V2, SIMPLE_SANITIZER_VESU_V1_DELEGATIONS, SVK_SIMPLE_SANITIZER, type SecurityMetadata, SenseiStrategies, SenseiVault, type SenseiVaultSettings, type SettlementSignature, type SignedWithdrawRequest, type SingleActionAmount, type SingleTokenInfo, SolveBudget, type SolveCase, type SolveCaseEntry, type SolveResult, type SourceCodeInfo, SourceCodeType, StandardMerkleTree, type StandardMerkleTreeData, type StarkDebuggingOrderAmounts, type StarkSettlement, StarknetCallParser, type StarknetCallParserOptions, type StateManagerConfig, Store, type StoreConfig, type StrategyAlert, type StrategyCapabilities, type StrategyFilterMetadata, StrategyLiveStatus, type StrategyMetadata, type StrategyRegistryEntry, type StrategySettings, StrategyTag, StrategyType, type SupportedPosition, SvkTrovesAdapter, type SvkTrovesAdapterConfig, type Swap, type SwapInfo, type SwapPriceInfo, type SwapRoute, TRANSFER_SANITIZER, TelegramGroupNotif, TelegramNotif, TimeInForce, type TokenAmount, type TokenBalance, type TokenInfo, TokenMarketData, TokenTransferAdapter, type TokenTransferAdapterConfig, type TradingConfig, type TransactionMetadata, type TransactionResult, type TransferRoute, UNIVERSAL_ADAPTERS, UNIVERSAL_MANAGE_IDS, USDCBoostedStrategies, USDCBoostedStrategy, type USDCBoostedStrategySettings, UniversalLstMultiplierStrategy, type UniversalManageCall, UniversalStrategies, UniversalStrategy, type UniversalStrategySettings, type UpdateLeverageRequest, VESU_SINGLETON, VESU_V2_MODIFY_POSITION_SANITIZER, type VaultPosition, VaultType, VesuAdapter, type VesuAdapterConfig, type VesuAmount, VesuAmountDenomination, VesuAmountType, VesuConfig, type VesuDebtRoute, type VesuDefiSpringRewardsCallParams, type VesuDepositParams, VesuExtendedMultiplierStrategy, type VesuExtendedStrategySettings, VesuExtendedTestStrategies, type VesuModifyDelegationCallParams, VesuModifyPositionAdapter, type VesuModifyPositionAdapterConfig, type VesuModifyPositionCallParams, type VesuModifyPositionDepositParams, type VesuModifyPositionWithdrawParams, VesuMultiplyAdapter, type VesuMultiplyAdapterConfig, type VesuMultiplyCallParams, type VesuMultiplyRoute, type VesuPoolDelta, VesuPoolMetadata, type VesuPoolState, VesuPools, VesuRebalance, type VesuRebalanceSettings, VesuRebalanceStrategies, VesuSupplyOnlyAdapter, type VesuSupplyOnlyAdapterConfig, type VesuWithdrawParams, type WaitRoute, Web3Number, type WithdrawParams, type WithdrawRequest, ZkLend, _riskFactor, assert, buildStrategyRegistry, calculateAmountDepositOnExtendedWhenIncurringLosses, calculateAmountDistribution, calculateAmountDistributionForWithdrawal, calculateBTCPriceDelta, calculateDebtAmount, calculateDebtReductionAmountForWithdrawal, calculateDeltaDebtAmount, calculateExposureDelta, calculateExtendedLevergae, calculatePositionToCloseToWithdrawAmount, calculateVesUPositionSizeGivenExtended, calculateVesuLeverage, calculateWBTCAmountToMaintainLTV, configureLogger, createEkuboCLStrategy, createHyperLSTStrategy, createSenseiStrategy, createSolveBudgetFromRawState, createStrategy, createUniversalStrategy, createVesuRebalanceStrategy, detectCapabilities, extensionMap, getAPIUsingHeadlessBrowser, getAllStrategyMetadata, getAllStrategyTags, getContractDetails, getDefaultStoreConfig, getFAQs, getFilterMetadata, getInvestmentSteps, getLiveStrategies, getMainnetConfig, getNoRiskTags, getRiskColor, getRiskExplaination, getStrategiesByType, getStrategyTagDesciption, getStrategyTypeFromMetadata, getTrovesEndpoint, getVesuSingletonAddress, highlightTextWithLinks, type i257, isDualTokenStrategy, logger, returnFormattedAmount, routeSummary, toAmountsInfo, toBigInt };
3293
+ export { type APYInfo, APYType, AUDIT_URL, AUMTypes, AVNU_EXCHANGE, AVNU_EXCHANGE_FOR_LEGACY_USDC, AVNU_LEGACY_SANITIZER, AVNU_MIDDLEWARE, AVNU_QUOTE_URL, type AccessControlInfo, AccessControlType, type AccountInfo, type AdapterLeafType, type AllAccountsStore, type AmountInfo, type AmountsInfo, type ApproveCallParams, AuditStatus, AutoCompounderSTRK, AvnuAdapter, type AvnuAdapterConfig, type AvnuDepositParams, type AvnuSwapCallParams, type AvnuWithdrawParams, AvnuWrapper, BaseAdapter, type BaseAdapterConfig, BaseStrategy, BoostedxSTRKCarryStrategies, BoostedxSTRKCarryStrategy, type BoostedxSTRKCarryStrategySettings, type CLVaultStrategySettings, CommonAdapter, type CommonAdapterConfig, ContractAddr, DEFAULT_TROVES_STRATEGIES_API, type DecreaseLeverParams, Deployer, type DepositParams, type DualActionAmount, type DualTokenInfo, ERC20, EXTENDED_CONTRACT, EXTENDED_SANITIZER, type EkuboBounds, EkuboCLVault, EkuboCLVaultStrategies, type EkuboPoolKey, EkuboPricer, type EkuboQuote, EkuboQuoter, type EkuboRouteNode, type EkuboSplit, type FAQ, FactoryStrategyType, FatalError, type FilterOption, type FlashloanCallParams, FlowChartColors, type GenerateCallFn, Global, HealthFactorMath, HyperLSTStrategies, type HyperLSTStrategySettings, type IConfig, type ICurator, type IInvestmentFlow, ILending, type ILendingMetadata, type ILendingPosition, type IProtocol, type IStrategyMetadata, type IncreaseLeverParams, Initializable, type InputModeFromAction, InstantWithdrawalVault, LSTAPRService, LSTPriceType, type LSTStats, type LeafAdapterFn, type LeafData, type LendingToken, type LoggerConfig, type LoggerLevel, type ManageCall, MarginType, Midas, MyNumber, type NetAPYDetails, type NetAPYSplit, Network, PRICE_ROUTER, type ParsedStarknetCall, PasswordJsonCryptoUtil, type PositionAPY, type PositionAmount, type PositionInfo, PositionTypeAvnuExtended, Pragma, type PriceInfo, Pricer, PricerBase, PricerFromApi, PricerLST, PricerRedis, Protocols, type RedemptionInfo, type RequiredFields, type RequiredKeys, type RequiredStoreConfig, type RiskFactor, RiskType, type Route, type RouteNode, SIMPLE_SANITIZER, SIMPLE_SANITIZER_V2, SIMPLE_SANITIZER_VESU_V1_DELEGATIONS, SVK_SIMPLE_SANITIZER, type SecurityMetadata, SenseiStrategies, SenseiVault, type SenseiVaultSettings, type SingleActionAmount, type SingleTokenInfo, type SourceCodeInfo, SourceCodeType, StandardMerkleTree, type StandardMerkleTreeData, StarknetCallParser, type StarknetCallParserOptions, Store, type StoreConfig, type StrategyAlert, type StrategyApyHistoryUIConfig, type StrategyCapabilities, type StrategyFilterMetadata, type StrategyInputMode, StrategyLiveStatus, type StrategyMetadata, type StrategyRegistryEntry, type StrategySettings, StrategyTag, StrategyType, type SupportedPosition, SvkTrovesAdapter, type SvkTrovesAdapterConfig, type Swap, type SwapInfo, type SwapPriceInfo, TRANSFER_SANITIZER, TelegramGroupNotif, TelegramNotif, type TokenAmount, type TokenInfo, TokenMarketData, TokenTransferAdapter, type TokenTransferAdapterConfig, UNIVERSAL_ADAPTER_IDS, UNIVERSAL_MANAGE_IDS, UniversalLstMultiplierStrategy, type UniversalManageCall, UniversalStrategies, UniversalStrategy, type UniversalStrategySettings, UnwrapLabsCurator, type UserPositionCard, type UserPositionCardSubValueColor, type UserPositionCardsInput, type UserYoloInfo, VESU_SINGLETON, VESU_V2_MODIFY_POSITION_SANITIZER, type VaultPosition, VaultType, VesuAdapter, type VesuAdapterConfig, type VesuAmount, VesuAmountDenomination, VesuAmountType, type VesuDefiSpringRewardsCallParams, type VesuDepositParams, type VesuModifyDelegationCallParams, VesuModifyPositionAdapter, type VesuModifyPositionAdapterConfig, type VesuModifyPositionCallParams, type VesuModifyPositionDepositParams, type VesuModifyPositionWithdrawParams, VesuMultiplyAdapter, type VesuMultiplyAdapterConfig, type VesuMultiplyCallParams, VesuPoolMetadata, VesuPools, VesuRebalance, type VesuRebalanceSettings, VesuRebalanceStrategies, VesuSupplyOnlyAdapter, type VesuSupplyOnlyAdapterConfig, type VesuWithdrawParams, Web3Number, type WithdrawParams, YoLoVault, type YoloSettings, type YoloSpendingLevel, type YoloVaultSettings, type YoloVaultStatus, YoloVaultStrategies, ZkLend, _riskFactor, assert, buildStrategyRegistry, configureLogger, createEkuboCLStrategy, createHyperLSTStrategy, createSenseiStrategy, createStrategy, createUniversalStrategy, createVesuRebalanceStrategy, createYoloVaultStrategy, detectCapabilities, extensionMap, getAPIUsingHeadlessBrowser, getAllStrategyMetadata, getAllStrategyTags, getContractDetails, getDefaultStoreConfig, getFAQs, getFilterMetadata, getInvestmentSteps, getLiveStrategies, getMainnetConfig, getNoRiskTags, getRiskColor, getRiskExplaination, getStrategiesByType, getStrategyTagDesciption, getStrategyTypeFromMetadata, getTrovesEndpoint, getVesuSingletonAddress, highlightTextWithLinks, type i257, isDualTokenStrategy, logger, toAmountsInfo, toBigInt };