@strkfarm/sdk 2.0.0-dev.5 → 2.0.0-dev.50

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 (79) hide show
  1. package/dist/cli.js +190 -36
  2. package/dist/cli.mjs +188 -34
  3. package/dist/index.browser.global.js +119400 -92821
  4. package/dist/index.browser.mjs +13293 -11146
  5. package/dist/index.d.ts +2281 -1938
  6. package/dist/index.js +13532 -11179
  7. package/dist/index.mjs +14165 -11836
  8. package/package.json +59 -60
  9. package/src/data/avnu.abi.json +840 -0
  10. package/src/data/ekubo-price-fethcer.abi.json +265 -0
  11. package/src/data/redeem-request-nft.abi.json +752 -0
  12. package/src/data/universal-vault.abi.json +8 -7
  13. package/src/dataTypes/_bignumber.ts +13 -4
  14. package/src/dataTypes/bignumber.browser.ts +10 -1
  15. package/src/dataTypes/bignumber.node.ts +10 -1
  16. package/src/dataTypes/index.ts +3 -2
  17. package/src/dataTypes/mynumber.ts +141 -0
  18. package/src/global.ts +279 -233
  19. package/src/index.browser.ts +2 -1
  20. package/src/interfaces/common.tsx +228 -6
  21. package/src/modules/apollo-client-config.ts +28 -0
  22. package/src/modules/avnu.ts +21 -12
  23. package/src/modules/ekubo-pricer.ts +80 -0
  24. package/src/modules/ekubo-quoter.ts +48 -30
  25. package/src/modules/erc20.ts +17 -0
  26. package/src/modules/harvests.ts +43 -29
  27. package/src/modules/index.ts +2 -1
  28. package/src/modules/pragma.ts +23 -8
  29. package/src/modules/pricer-avnu-api.ts +114 -0
  30. package/src/modules/pricer-from-api.ts +156 -15
  31. package/src/modules/pricer-lst.ts +1 -1
  32. package/src/modules/pricer.ts +107 -41
  33. package/src/modules/pricerBase.ts +2 -1
  34. package/src/modules/zkLend.ts +3 -2
  35. package/src/node/deployer.ts +36 -1
  36. package/src/node/pricer-redis.ts +3 -1
  37. package/src/strategies/base-strategy.ts +168 -16
  38. package/src/strategies/constants.ts +8 -3
  39. package/src/strategies/ekubo-cl-vault.tsx +1048 -355
  40. package/src/strategies/factory.ts +199 -0
  41. package/src/strategies/index.ts +5 -3
  42. package/src/strategies/registry.ts +262 -0
  43. package/src/strategies/sensei.ts +354 -10
  44. package/src/strategies/svk-strategy.ts +292 -31
  45. package/src/strategies/token-boosted-xstrk-carry-strategy.tsx +1261 -0
  46. package/src/strategies/types.ts +4 -0
  47. package/src/strategies/universal-adapters/adapter-utils.ts +4 -1
  48. package/src/strategies/universal-adapters/avnu-adapter.ts +196 -272
  49. package/src/strategies/universal-adapters/baseAdapter.ts +263 -251
  50. package/src/strategies/universal-adapters/common-adapter.ts +206 -203
  51. package/src/strategies/universal-adapters/index.ts +10 -8
  52. package/src/strategies/universal-adapters/svk-troves-adapter.ts +511 -0
  53. package/src/strategies/universal-adapters/token-transfer-adapter.ts +200 -0
  54. package/src/strategies/universal-adapters/vesu-adapter.ts +120 -82
  55. package/src/strategies/universal-adapters/vesu-modify-position-adapter.ts +525 -0
  56. package/src/strategies/universal-adapters/vesu-multiply-adapter.ts +866 -860
  57. package/src/strategies/universal-adapters/vesu-position-common.ts +258 -0
  58. package/src/strategies/universal-adapters/vesu-supply-only-adapter.ts +18 -3
  59. package/src/strategies/universal-lst-muliplier-strategy.tsx +895 -416
  60. package/src/strategies/universal-strategy.tsx +1332 -1173
  61. package/src/strategies/vesu-rebalance.tsx +254 -153
  62. package/src/strategies/yoloVault.ts +1096 -0
  63. package/src/utils/cacheClass.ts +11 -2
  64. package/src/utils/health-factor-math.ts +33 -1
  65. package/src/utils/index.ts +3 -1
  66. package/src/utils/logger.browser.ts +22 -4
  67. package/src/utils/logger.node.ts +259 -24
  68. package/src/utils/starknet-call-parser.ts +1036 -0
  69. package/src/utils/strategy-utils.ts +61 -0
  70. package/src/modules/ExtendedWrapperSDk/index.ts +0 -62
  71. package/src/modules/ExtendedWrapperSDk/types.ts +0 -311
  72. package/src/modules/ExtendedWrapperSDk/wrapper.ts +0 -395
  73. package/src/strategies/universal-adapters/extended-adapter.ts +0 -662
  74. package/src/strategies/universal-adapters/unused-balance-adapter.ts +0 -109
  75. package/src/strategies/vesu-extended-strategy/services/operationService.ts +0 -34
  76. package/src/strategies/vesu-extended-strategy/utils/config.runtime.ts +0 -77
  77. package/src/strategies/vesu-extended-strategy/utils/constants.ts +0 -49
  78. package/src/strategies/vesu-extended-strategy/utils/helper.ts +0 -372
  79. package/src/strategies/vesu-extended-strategy/vesu-extended-strategy.tsx +0 -1140
@@ -1,16 +1,27 @@
1
1
  import axios from "axios";
2
2
  import { FatalError, Global } from "@/global";
3
- import { TokenInfo } from "@/interfaces/common";
3
+ import { PriceMethod, TokenInfo } from "@/interfaces/common";
4
4
  import { IConfig } from "@/interfaces/common";
5
5
  import { Web3Number } from "@/dataTypes";
6
6
  import { PricerBase } from "./pricerBase";
7
7
  import { logger } from "@/utils/logger";
8
+ import { AvnuWrapper } from "./avnu";
9
+ import { BlockIdentifier } from "starknet";
10
+ import { PricerAvnuApi } from "./pricer-avnu-api";
8
11
 
9
12
  export interface PriceInfo {
10
13
  price: number,
11
14
  timestamp: Date
12
15
  }
13
16
 
17
+ const PRICE_METHOD_PRIORITY: PriceMethod[] = [
18
+ 'AvnuApi',
19
+ 'Coinbase',
20
+ 'Coinmarketcap',
21
+ 'Ekubo',
22
+ 'Avnu',
23
+ ];
24
+
14
25
  export class Pricer extends PricerBase {
15
26
  protected prices: {
16
27
  [key: string]: PriceInfo
@@ -19,20 +30,24 @@ export class Pricer extends PricerBase {
19
30
  refreshInterval = 30000;
20
31
  staleTime = 60000;
21
32
 
33
+ protected readonly avnuApiPricer: PricerAvnuApi;
34
+
22
35
  // code populates this map during runtime to determine which method to use for a given token
23
36
  // The method set will be the first one to try after first attempt
24
- protected methodToUse: {[tokenSymbol: string]: 'Ekubo' | 'Coinbase' | 'Coinmarketcap'} = {};
37
+ protected methodToUse: {[tokenSymbol: string]: PriceMethod} = {};
25
38
 
26
39
  /**
27
40
  * TOKENA and TOKENB are the two token names to get price of TokenA in terms of TokenB
28
41
  */
42
+ // ! switch to USDC (new) later
29
43
  protected PRICE_API = `https://api.coinbase.com/v2/prices/{{PRICER_KEY}}/buy`;
30
- protected EKUBO_API = 'https://quoter-mainnet-api.ekubo.org/{{AMOUNT}}/{{TOKEN_ADDRESS}}/0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8'; // e.g. ETH/USDC
44
+ protected EKUBO_API = 'https://prod-api-quoter.ekubo.org/23448594291968334/{{AMOUNT}}/{{TOKEN_ADDRESS}}/0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb'; // e.g. ETH/USDC
31
45
 
32
46
  constructor(config: IConfig, tokens: TokenInfo[], refreshInterval = 30000, staleTime = 60000) {
33
47
  super(config, tokens);
34
48
  this.refreshInterval = refreshInterval;
35
49
  this.staleTime = staleTime;
50
+ this.avnuApiPricer = new PricerAvnuApi(config, tokens);
36
51
  }
37
52
 
38
53
  isReady() {
@@ -66,6 +81,7 @@ export class Pricer extends PricerBase {
66
81
  }
67
82
 
68
83
  start() {
84
+ this.avnuApiPricer.start();
69
85
  this._loadPrices();
70
86
  setInterval(() => {
71
87
  this._loadPrices();
@@ -81,7 +97,7 @@ export class Pricer extends PricerBase {
81
97
  Global.assert(!this.isStale(timestamp, tokenName), `Price of ${tokenName} is stale`);
82
98
 
83
99
  }
84
- async getPrice(tokenSymbol: string) {
100
+ async getPrice(tokenSymbol: string, blockNumber?: BlockIdentifier) {
85
101
  Global.assert(this.prices[tokenSymbol], `Price of ${tokenSymbol} not found`);
86
102
  this.assertNotStale(this.prices[tokenSymbol].timestamp, tokenSymbol);
87
103
  return this.prices[tokenSymbol];
@@ -93,7 +109,10 @@ export class Pricer extends PricerBase {
93
109
  let retry = 0;
94
110
  while (retry < MAX_RETRIES) {
95
111
  try {
96
- if (token.symbol === 'USDT') {
112
+ if (token.dontPrice) {
113
+ return;
114
+ }
115
+ if (token.symbol === 'USDT' || token.symbol === 'USDC') {
97
116
  this.prices[token.symbol] = {
98
117
  price: 1,
99
118
  timestamp: new Date()
@@ -142,47 +161,70 @@ export class Pricer extends PricerBase {
142
161
  }
143
162
  }
144
163
 
145
- async _getPrice(token: TokenInfo, defaultMethod = 'all'): Promise<number> {
146
- const methodToUse: string = this.methodToUse[token.symbol] || defaultMethod; // default start with coinbase
147
- logger.verbose(`Fetching price of ${token.symbol} using ${methodToUse}`);
148
- switch (methodToUse) {
149
- case 'Coinbase':
150
- // try {
151
- // const result = await this._getPriceCoinbase(token);
152
- // this.methodToUse[token.symbol] = 'Coinbase';
153
- // return result;
154
- // } catch (error: any) {
155
- // console.warn(`Coinbase: price err: message [${token.symbol}]: `, error.message);
156
- // // do nothing, try next
157
- // }
158
- case 'Coinmarketcap':
159
- try {
160
- const result = await this._getPriceCoinMarketCap(token);
161
- this.methodToUse[token.symbol] = 'Coinmarketcap';
162
- return result;
163
- } catch (error: any) {
164
- console.warn(`CoinMarketCap: price err [${token.symbol}]: `, Object.keys(error));
165
- console.warn(`CoinMarketCap: price err [${token.symbol}]: `, error.message);
166
- }
167
- case 'Ekubo':
168
- try {
169
- const result = await this._getPriceEkubo(token, new Web3Number(token.priceCheckAmount ? token.priceCheckAmount : 1, token.decimals));
170
- this.methodToUse[token.symbol] = 'Ekubo';
171
- return result;
172
- } catch (error: any) {
173
- console.warn(`Ekubo: price err [${token.symbol}]: `, error.message);
174
- console.warn(`Ekubo: price err [${token.symbol}]: `, Object.keys(error));
175
- // do nothing, try next
164
+ async _getPrice(token: TokenInfo): Promise<number> {
165
+ const methodsToTry = this._getMethodsToTry(token);
166
+
167
+ for (const method of methodsToTry) {
168
+ logger.verbose(`Fetching price of ${token.symbol} using ${method}`);
169
+ try {
170
+ const result = await this._tryPriceMethod(token, method);
171
+ if (!token.priceMethod) {
172
+ this.methodToUse[token.symbol] = method;
176
173
  }
174
+ return result;
175
+ } catch (error: any) {
176
+ console.warn(`${method}: price err [${token.symbol}]: `, error.message);
177
+ }
177
178
  }
178
179
 
179
- // if methodToUse is the default one, pass Coinbase to try all from start
180
- if (defaultMethod == 'all') {
181
- // try again with coinbase
182
- return await this._getPrice(token, 'Coinbase');
180
+ throw new FatalError(`Price not found for ${token.symbol}`);
181
+ }
182
+
183
+ protected _getMethodsToTry(token: TokenInfo): PriceMethod[] {
184
+ const methods: PriceMethod[] = [];
185
+
186
+ if (token.priceMethod) {
187
+ methods.push(token.priceMethod);
183
188
  }
184
189
 
185
- throw new FatalError(`Price not found for ${token.symbol}`);
190
+ const pinned = this.methodToUse[token.symbol];
191
+ if (pinned && pinned !== token.priceMethod) {
192
+ methods.push(pinned);
193
+ }
194
+
195
+ for (const method of PRICE_METHOD_PRIORITY) {
196
+ if (!methods.includes(method)) {
197
+ methods.push(method);
198
+ }
199
+ }
200
+
201
+ return methods;
202
+ }
203
+
204
+ protected async _tryPriceMethod(token: TokenInfo, method: PriceMethod): Promise<number> {
205
+ switch (method) {
206
+ case 'AvnuApi':
207
+ return await this._getPriceAvnuApi(token);
208
+ case 'Coinbase':
209
+ return await this._getPriceCoinbase(token);
210
+ case 'Coinmarketcap':
211
+ return await this._getPriceCoinMarketCap(token);
212
+ case 'Ekubo':
213
+ return await this._getPriceEkubo(
214
+ token,
215
+ new Web3Number(token.priceCheckAmount ? token.priceCheckAmount : 1, token.decimals),
216
+ );
217
+ case 'Avnu':
218
+ return await this._getAvnuPrice(
219
+ token,
220
+ new Web3Number(token.priceCheckAmount ? token.priceCheckAmount : 1, token.decimals),
221
+ );
222
+ }
223
+ }
224
+
225
+ async _getPriceAvnuApi(token: TokenInfo): Promise<number> {
226
+ const priceInfo = await this.avnuApiPricer.getPrice(token.symbol);
227
+ return priceInfo.price;
186
228
  }
187
229
 
188
230
  async _getPriceCoinbase(token: TokenInfo) {
@@ -200,7 +242,31 @@ export class Pricer extends PricerBase {
200
242
  throw new Error("Not implemented");
201
243
  }
202
244
 
245
+ async _getAvnuPrice(token: TokenInfo, amountIn = new Web3Number(1, token.decimals), retry = 0): Promise<number> {
246
+ logger.verbose(`Getting price of ${token.symbol} using Ekubo, amountIn: ${amountIn.toWei()}`);
247
+
248
+ const avnuWrapper = new AvnuWrapper();
249
+ const usdcAddress = '0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb';
250
+ const quote = await avnuWrapper.getQuotes(token.address.toString(), usdcAddress, amountIn.toWei(), '0x1');
251
+ const multiplier = 1 / amountIn.toNumber();
252
+ const outputUSDC = Number(Web3Number.fromWei(quote.buyAmount.toString(), 6).toFixed(6)) * multiplier;
253
+ logger.verbose(`Avnu: ${token.symbol} -> USDC: ${outputUSDC}, retry: ${retry}`);
254
+ if (outputUSDC === 0 && retry < 3) {
255
+ // try again with a higher amount
256
+ const amountIn = new Web3Number(100, token.decimals); // 100 unit of token
257
+ return await this._getAvnuPrice(token, amountIn, retry + 1);
258
+ }
259
+
260
+ // if usdc depegs, it will not longer be 1 USD
261
+ // so we need to get the price of USDC in USD
262
+ // and then convert the outputUSDC to USD
263
+ const usdcPrice = 1; // (await this.getPrice('USDC')).price;
264
+ logger.verbose(`USDC Price: ${usdcPrice}`);
265
+ return outputUSDC * usdcPrice;
266
+ }
267
+
203
268
  async _getPriceEkubo(token: TokenInfo, amountIn = new Web3Number(1, token.decimals), retry = 0): Promise<number> {
269
+ logger.verbose(`Getting price of ${token.symbol} using Ekubo, amountIn: ${amountIn.toWei()}`);
204
270
  const url = this.EKUBO_API.replace("{{TOKEN_ADDRESS}}", token.address.toString()).replace("{{AMOUNT}}", amountIn.toWei());
205
271
  const result = await axios.get(url);
206
272
  const data: any = result.data;
@@ -1,5 +1,6 @@
1
1
  import { IConfig, TokenInfo } from "@/interfaces";
2
2
  import { PriceInfo } from "./pricer";
3
+ import { BlockIdentifier } from "starknet";
3
4
 
4
5
  export abstract class PricerBase {
5
6
  readonly config: IConfig;
@@ -9,7 +10,7 @@ export abstract class PricerBase {
9
10
  this.tokens = tokens;
10
11
  }
11
12
 
12
- async getPrice(tokenSymbol: string): Promise<PriceInfo> {
13
+ async getPrice(tokenSymbol: string, blockNumber?: BlockIdentifier): Promise<PriceInfo> {
13
14
  throw new Error('Method not implemented');
14
15
  }
15
16
  }
@@ -2,7 +2,7 @@ import axios from "axios";
2
2
  import BigNumber from "bignumber.js";
3
3
  import { Web3Number } from "@/dataTypes/bignumber.browser";
4
4
  import { FatalError, Global } from "@/global";
5
- import { TokenInfo } from "@/interfaces";
5
+ import { TokenIndexingType, TokenInfo } from "@/interfaces";
6
6
  import { ILending, ILendingPosition, LendingToken, MarginType } from "@/interfaces/lending";
7
7
  import { ContractAddr } from "@/dataTypes/address";
8
8
  import { IConfig } from "@/interfaces";
@@ -42,7 +42,8 @@ export class ZkLend extends ILending implements ILending {
42
42
  decimals: pool.token.decimals,
43
43
  borrowFactor: Web3Number.fromWei(pool.borrow_factor.value, pool.borrow_factor.decimals),
44
44
  collareralFactor,
45
- displayDecimals: 2
45
+ displayDecimals: 2,
46
+ indexingType: TokenIndexingType.IGNORE,
46
47
  }
47
48
  this.tokens.push(token);
48
49
  });
@@ -4,6 +4,7 @@ import { readFileSync, existsSync, writeFileSync } from 'fs'
4
4
  import { IConfig } from '../interfaces';
5
5
  import { Store, getDefaultStoreConfig } from '../utils/store';
6
6
  import { add } from 'winston';
7
+ import { logger } from '@/utils';
7
8
 
8
9
  function getContracts() {
9
10
  const PATH = './contracts.json'
@@ -207,13 +208,47 @@ async function executeTransactions(
207
208
  return tx;
208
209
  }
209
210
 
211
+ async function myWaitForTransaction(
212
+ transaction_hash: string,
213
+ provider: RpcProvider,
214
+ retry = 0
215
+ ) {
216
+ const MAX_RETRIES = 60;
217
+ logger.verbose(`Waiting for transaction: ${transaction_hash}, retry: ${retry}`);
218
+ try {
219
+ const status = await provider.getTransactionStatus(transaction_hash);
220
+ logger.verbose(`Transaction status: ${JSON.stringify(status.execution_status)}`);
221
+ if (status.execution_status == TransactionExecutionStatus.SUCCEEDED) {
222
+ return true;
223
+ }
224
+ if (status.execution_status == TransactionExecutionStatus.REVERTED) {
225
+ throw new Error(`Transaction reverted: ${transaction_hash}`);
226
+ }
227
+ if (retry > MAX_RETRIES) {
228
+ throw new Error(`Transaction not found: ${transaction_hash}`);
229
+ }
230
+ await new Promise(resolve => setTimeout(resolve, 1000));
231
+ return myWaitForTransaction(transaction_hash, provider, retry + 1);
232
+ } catch (error) {
233
+ if (error instanceof Error && error.message.includes('Transaction reverted')) {
234
+ throw new Error(`Transaction reverted: ${transaction_hash}`);
235
+ }
236
+ if (retry > MAX_RETRIES) {
237
+ throw error;
238
+ }
239
+ await new Promise(resolve => setTimeout(resolve, 1000));
240
+ return myWaitForTransaction(transaction_hash, provider, retry + 1);
241
+ }
242
+ }
243
+
210
244
  const Deployer = {
211
245
  getAccount,
212
246
  myDeclare,
213
247
  deployContract,
214
248
  prepareMultiDeployContracts,
215
249
  executeDeployCalls,
216
- executeTransactions
250
+ executeTransactions,
251
+ myWaitForTransaction
217
252
  }
218
253
 
219
254
  export default Deployer;
@@ -4,6 +4,7 @@ import { PriceInfo, Pricer } from '@/modules/pricer';
4
4
  import { createClient } from 'redis';
5
5
  import type { RedisClientType } from 'redis'
6
6
  import { logger } from "@/utils/logger";
7
+ import { BlockIdentifier } from "starknet";
7
8
 
8
9
  export class PricerRedis extends Pricer {
9
10
  private redisClient: RedisClientType | null = null;
@@ -17,6 +18,7 @@ export class PricerRedis extends Pricer {
17
18
  await this.initRedis(redisUrl);
18
19
 
19
20
  logger.info(`Starting Pricer with Redis`);
21
+ this.avnuApiPricer.start();
20
22
  this._loadPrices(this._setRedisPrices.bind(this));
21
23
  setInterval(() => {
22
24
  this._loadPrices(this._setRedisPrices.bind(this));
@@ -51,7 +53,7 @@ export class PricerRedis extends Pricer {
51
53
  }
52
54
 
53
55
  /** Returns price from redis */
54
- async getPrice(tokenSymbol: string) {
56
+ async getPrice(tokenSymbol: string, blockNumber?: BlockIdentifier) {
55
57
  const STALE_TIME = 60000;
56
58
  if (!this.redisClient) {
57
59
  throw new FatalError(`Redis client not initialised`);
@@ -1,8 +1,9 @@
1
1
  import { ContractAddr, Web3Number } from "@/dataTypes";
2
2
  import { IConfig, TokenInfo, VaultPosition } from "@/interfaces";
3
3
  import { CacheClass } from "@/utils/cacheClass";
4
- import { Call } from "starknet";
5
4
  import { PositionInfo } from "./universal-adapters";
5
+ import { Call, BlockIdentifier } from "starknet";
6
+ import { HarvestInfo } from "@/modules/harvests";
6
7
 
7
8
  export interface SingleActionAmount {
8
9
  tokenInfo: TokenInfo,
@@ -28,33 +29,87 @@ export interface DualTokenInfo {
28
29
  token1: SingleTokenInfo
29
30
  }
30
31
 
32
+ export type StrategyInputMode = "single" | "dual";
33
+ export type InputModeFromAction<T> = T extends DualActionAmount ? "dual" : "single";
34
+
35
+ export interface NetAPYSplit {
36
+ apy: number;
37
+ id: string;
38
+ }
39
+
40
+ export interface NetAPYDetails {
41
+ net: number;
42
+ splits: NetAPYSplit[];
43
+ }
44
+
45
+ export type UserPositionCardSubValueColor = "default" | "positive" | "negative" | "info";
46
+
47
+ export interface UserPositionCard {
48
+ title: string;
49
+ value: string;
50
+ tooltip?: string;
51
+ subValue?: string;
52
+ subValueColor?: UserPositionCardSubValueColor;
53
+ }
54
+
55
+ export interface UserPositionCardsInput {
56
+ user: ContractAddr;
57
+ investmentFlows?: Array<{ amount: string; type: string; timestamp: number; tx_hash: string }>;
58
+ usualTimeToEarnings?: string | null;
59
+ usualTimeToEarningsDescription?: string | null;
60
+ }
61
+
31
62
  interface CacheData {
32
63
  timestamp: number;
33
64
  ttl: number;
34
65
  data: any;
35
66
  }
36
- export class BaseStrategy<TVLInfo, ActionInfo> extends CacheClass {
37
- readonly config: IConfig;
38
- readonly cache: Map<string, CacheData> = new Map();
67
+ export class BaseStrategy<
68
+ TVLInfo,
69
+ DepositActionInfo,
70
+ WithdrawActionInfo = DepositActionInfo,
71
+ > extends CacheClass {
72
+ readonly config: IConfig;
73
+ readonly cache: Map<string, CacheData> = new Map();
74
+ private readonly _depositInputMode: InputModeFromAction<DepositActionInfo>;
75
+ private readonly _withdrawInputMode: InputModeFromAction<WithdrawActionInfo>;
39
76
 
40
- constructor(config: IConfig) {
77
+ constructor(
78
+ config: IConfig,
79
+ inputModes?: {
80
+ depositInputMode?: InputModeFromAction<DepositActionInfo>;
81
+ withdrawInputMode?: InputModeFromAction<WithdrawActionInfo>;
82
+ }
83
+ ) {
41
84
  super();
42
85
  this.config = config;
86
+ this._depositInputMode = (inputModes?.depositInputMode ??
87
+ ("single" as InputModeFromAction<DepositActionInfo>));
88
+ this._withdrawInputMode = (inputModes?.withdrawInputMode ??
89
+ ("single" as InputModeFromAction<WithdrawActionInfo>));
90
+ }
91
+
92
+ depositInputMode(): InputModeFromAction<DepositActionInfo> {
93
+ return this._depositInputMode;
94
+ }
95
+
96
+ withdrawInputMode(): InputModeFromAction<WithdrawActionInfo> {
97
+ return this._withdrawInputMode;
43
98
  }
44
99
 
45
- async getUserTVL(user: ContractAddr): Promise<TVLInfo> {
100
+ async getUserTVL(user: ContractAddr, blockIdentifier?: BlockIdentifier): Promise<TVLInfo> {
46
101
  throw new Error("Not implemented");
47
102
  }
48
103
 
49
104
  async getTVL(): Promise<TVLInfo> {
50
105
  throw new Error("Not implemented");
51
- }
106
+ }
52
107
 
53
- async depositCall(amountInfo: ActionInfo, receiver: ContractAddr): Promise<Call[]> {
108
+ async depositCall(amountInfo: DepositActionInfo, receiver: ContractAddr): Promise<Call[]> {
54
109
  throw new Error("Not implemented");
55
110
  }
56
111
 
57
- async withdrawCall(amountInfo: ActionInfo, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]> {
112
+ async withdrawCall(amountInfo: WithdrawActionInfo, receiver: ContractAddr, owner: ContractAddr, isMaxWithdraw: boolean = false): Promise<Call[]> {
58
113
  throw new Error("Not implemented");
59
114
  }
60
115
 
@@ -62,19 +117,116 @@ export class BaseStrategy<TVLInfo, ActionInfo> extends CacheClass {
62
117
  throw new Error("Not implemented");
63
118
  }
64
119
 
65
- async getUnusedBalance(): Promise<SingleTokenInfo> {
120
+ async netAPY(
121
+ blockIdentifier?: BlockIdentifier,
122
+ sinceBlocks?: number,
123
+ timeperiod?: "24h" | "7d" | "30d" | "3m"
124
+ ): Promise<number | string | NetAPYDetails> {
66
125
  throw new Error("Not implemented");
67
126
  }
68
127
 
69
- async netAPY(): Promise<APYInfo> {
70
- throw new Error("Not implemented");
128
+ async getPendingRewards(): Promise<HarvestInfo[]> {
129
+ return [];
71
130
  }
72
131
 
73
- async getAUM(): Promise<{net: SingleTokenInfo, prevAum: Web3Number, splits: PositionInfo[]}> {
132
+ async getUserRealizedAPY(
133
+ blockIdentifier?: BlockIdentifier,
134
+ sinceBlocks?: number
135
+ ): Promise<number> {
74
136
  throw new Error("Not implemented");
75
137
  }
76
138
 
77
- async getHealthFactors(): Promise<number[]> {
78
- throw new Error("Not implemented");
139
+ async getUserPositionCards(_input: UserPositionCardsInput): Promise<UserPositionCard[]> {
140
+ throw new Error("Not implemented");
79
141
  }
80
- }
142
+
143
+ async getMaxTVL() : Promise<Web3Number> {
144
+ // Can throw an error as well if needed, RN returning 0
145
+ return new Web3Number('0', 18)
146
+ }
147
+
148
+ protected formatTokenAmountForCard(amount: Web3Number, tokenInfo: TokenInfo): string {
149
+ const displayDecimals = tokenInfo.displayDecimals ?? 2;
150
+ const fixed = Number(amount.toFixed(displayDecimals));
151
+ const normalized = Number.isFinite(fixed) ? fixed : 0;
152
+ return `${normalized.toLocaleString("en-US", {
153
+ maximumFractionDigits: displayDecimals,
154
+ minimumFractionDigits: 0,
155
+ })} ${tokenInfo.symbol}`;
156
+ }
157
+
158
+ protected formatPercentForCard(value: number): string {
159
+ if (!Number.isFinite(value)) return "N/A";
160
+ return `${(value * 100).toFixed(2)}%`;
161
+ }
162
+
163
+ protected formatUSDForCard(value: number): string {
164
+ if (!Number.isFinite(value)) return "$0.00";
165
+ return new Intl.NumberFormat("en-US", {
166
+ style: "currency",
167
+ currency: "USD",
168
+ maximumFractionDigits: 2,
169
+ }).format(value);
170
+ }
171
+
172
+ protected getSubValueColorFromSignedNumber(value: number): UserPositionCardSubValueColor {
173
+ if (!Number.isFinite(value)) return "default";
174
+ if (value > 0) return "positive";
175
+ if (value < 0) return "negative";
176
+ return "default";
177
+ }
178
+
179
+ /**
180
+ * Calculate lifetime earnings for a user based on provided data from client
181
+ * Formula: lifetimeEarnings = currentValue + totalWithdrawals - totalDeposits
182
+ *
183
+ * @param userTVL - The user's current TVL (SingleTokenInfo with amount, usdValue, tokenInfo)
184
+ * @param investmentFlows - Array of investment flow transactions from client
185
+ * @returns Object containing lifetime earnings, current value, and total deposits/withdrawals
186
+ */
187
+ getLifetimeEarnings(
188
+ userTVL: SingleTokenInfo,
189
+ investmentFlows: Array<{ amount: string; type: string; timestamp: number; tx_hash: string }>
190
+ ): {
191
+ tokenInfo: SingleTokenInfo;
192
+ lifetimeEarnings: Web3Number;
193
+ currentValue: Web3Number;
194
+ totalDeposits: Web3Number;
195
+ totalWithdrawals: Web3Number;
196
+ } {
197
+ // Get token decimals from userTVL
198
+ const tokenDecimals = userTVL.tokenInfo.decimals;
199
+
200
+ // Initialize totals
201
+ let totalDeposits = Web3Number.fromWei("0", tokenDecimals);
202
+ let totalWithdrawals = Web3Number.fromWei("0", tokenDecimals);
203
+
204
+ // Process investment flows
205
+ for (const flow of investmentFlows) {
206
+ const amount = Web3Number.fromWei(flow.amount, tokenDecimals);
207
+
208
+ if (flow.type === 'deposit') {
209
+ totalDeposits = totalDeposits.plus(amount);
210
+ } else if (flow.type === 'withdraw' || flow.type === 'redeem') {
211
+ totalWithdrawals = totalWithdrawals.plus(amount);
212
+ }
213
+ }
214
+
215
+ // Calculate lifetime earnings: current value + withdrawals - deposits
216
+ const lifetimeEarnings = userTVL.amount
217
+ .plus(totalWithdrawals)
218
+ .minus(totalDeposits);
219
+
220
+ return {
221
+ tokenInfo: {
222
+ tokenInfo: userTVL.tokenInfo,
223
+ amount: lifetimeEarnings,
224
+ usdValue: 0, // Lifetime earnings are not converted to USD
225
+ },
226
+ lifetimeEarnings,
227
+ currentValue: userTVL.amount,
228
+ totalDeposits,
229
+ totalWithdrawals,
230
+ };
231
+ }
232
+ }
@@ -1,12 +1,17 @@
1
1
  import { ContractAddr } from "@/dataTypes";
2
2
 
3
- export const COMMON_CONTRACTS = [{
3
+ export const MY_ACCESS_CONTROL = {
4
4
  address: ContractAddr.from("0x0636a3f51cc37f5729e4da4b1de6a8549a28f3c0d5bf3b17f150971e451ff9c2"),
5
5
  name: "Access Controller",
6
6
  sourceCodeUrl: "https://github.com/strkfarm/strkfarm-contracts/blob/main/src/components/accessControl.cairo",
7
- }];
7
+ };
8
+
9
+ export const COMMON_CONTRACTS = [MY_ACCESS_CONTROL];
8
10
 
9
11
  export const ENDPOINTS = {
10
12
  VESU_BASE: "https://proxy.api.troves.fi/vesu",
11
13
  VESU_BASE_STAGING: "https://proxy.api.troves.fi/vesu-staging"
12
- }
14
+ }
15
+
16
+
17
+ export const MAX_AVNU_RETRY_DELAY = Number(process.env.MAX_AVNU_RETRY_DELAY ?? 100);