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

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 (80) hide show
  1. package/dist/cli.js +190 -36
  2. package/dist/cli.mjs +188 -34
  3. package/dist/index.browser.global.js +118889 -92229
  4. package/dist/index.browser.mjs +13381 -11153
  5. package/dist/index.d.ts +2284 -1938
  6. package/dist/index.js +13794 -11360
  7. package/dist/index.mjs +14253 -11843
  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 +280 -233
  19. package/src/index.browser.ts +2 -1
  20. package/src/interfaces/common.tsx +229 -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 +99 -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 +159 -15
  31. package/src/modules/pricer-lst.ts +1 -1
  32. package/src/modules/pricer-quote-utils.ts +54 -0
  33. package/src/modules/pricer.ts +157 -54
  34. package/src/modules/pricerBase.ts +2 -1
  35. package/src/modules/zkLend.ts +3 -2
  36. package/src/node/deployer.ts +36 -1
  37. package/src/node/pricer-redis.ts +3 -1
  38. package/src/strategies/base-strategy.ts +168 -16
  39. package/src/strategies/constants.ts +8 -3
  40. package/src/strategies/ekubo-cl-vault.tsx +1048 -355
  41. package/src/strategies/factory.ts +199 -0
  42. package/src/strategies/index.ts +5 -3
  43. package/src/strategies/registry.ts +262 -0
  44. package/src/strategies/sensei.ts +354 -10
  45. package/src/strategies/svk-strategy.ts +292 -31
  46. package/src/strategies/token-boosted-xstrk-carry-strategy.tsx +1261 -0
  47. package/src/strategies/types.ts +4 -0
  48. package/src/strategies/universal-adapters/adapter-utils.ts +4 -1
  49. package/src/strategies/universal-adapters/avnu-adapter.ts +196 -272
  50. package/src/strategies/universal-adapters/baseAdapter.ts +263 -251
  51. package/src/strategies/universal-adapters/common-adapter.ts +206 -203
  52. package/src/strategies/universal-adapters/index.ts +10 -8
  53. package/src/strategies/universal-adapters/svk-troves-adapter.ts +511 -0
  54. package/src/strategies/universal-adapters/token-transfer-adapter.ts +200 -0
  55. package/src/strategies/universal-adapters/vesu-adapter.ts +120 -82
  56. package/src/strategies/universal-adapters/vesu-modify-position-adapter.ts +525 -0
  57. package/src/strategies/universal-adapters/vesu-multiply-adapter.ts +866 -860
  58. package/src/strategies/universal-adapters/vesu-position-common.ts +258 -0
  59. package/src/strategies/universal-adapters/vesu-supply-only-adapter.ts +18 -3
  60. package/src/strategies/universal-lst-muliplier-strategy.tsx +895 -416
  61. package/src/strategies/universal-strategy.tsx +1332 -1173
  62. package/src/strategies/vesu-rebalance.tsx +254 -153
  63. package/src/strategies/yoloVault.ts +1096 -0
  64. package/src/utils/cacheClass.ts +11 -2
  65. package/src/utils/health-factor-math.ts +33 -1
  66. package/src/utils/index.ts +3 -1
  67. package/src/utils/logger.browser.ts +22 -4
  68. package/src/utils/logger.node.ts +259 -24
  69. package/src/utils/starknet-call-parser.ts +1036 -0
  70. package/src/utils/strategy-utils.ts +61 -0
  71. package/src/modules/ExtendedWrapperSDk/index.ts +0 -62
  72. package/src/modules/ExtendedWrapperSDk/types.ts +0 -311
  73. package/src/modules/ExtendedWrapperSDk/wrapper.ts +0 -395
  74. package/src/strategies/universal-adapters/extended-adapter.ts +0 -662
  75. package/src/strategies/universal-adapters/unused-balance-adapter.ts +0 -109
  76. package/src/strategies/vesu-extended-strategy/services/operationService.ts +0 -34
  77. package/src/strategies/vesu-extended-strategy/utils/config.runtime.ts +0 -77
  78. package/src/strategies/vesu-extended-strategy/utils/constants.ts +0 -49
  79. package/src/strategies/vesu-extended-strategy/utils/helper.ts +0 -372
  80. package/src/strategies/vesu-extended-strategy/vesu-extended-strategy.tsx +0 -1140
@@ -1,16 +1,32 @@
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";
11
+ import {
12
+ convertQuoteAmountToUsd,
13
+ PRICER_USDC_ADDRESS,
14
+ resolveQuoteTokenConfig,
15
+ } from "./pricer-quote-utils";
8
16
 
9
17
  export interface PriceInfo {
10
18
  price: number,
11
19
  timestamp: Date
12
20
  }
13
21
 
22
+ const PRICE_METHOD_PRIORITY: PriceMethod[] = [
23
+ 'AvnuApi',
24
+ 'Coinbase',
25
+ 'Coinmarketcap',
26
+ 'Ekubo',
27
+ 'Avnu',
28
+ ];
29
+
14
30
  export class Pricer extends PricerBase {
15
31
  protected prices: {
16
32
  [key: string]: PriceInfo
@@ -19,20 +35,24 @@ export class Pricer extends PricerBase {
19
35
  refreshInterval = 30000;
20
36
  staleTime = 60000;
21
37
 
38
+ protected readonly avnuApiPricer: PricerAvnuApi;
39
+
22
40
  // code populates this map during runtime to determine which method to use for a given token
23
41
  // The method set will be the first one to try after first attempt
24
- protected methodToUse: {[tokenSymbol: string]: 'Ekubo' | 'Coinbase' | 'Coinmarketcap'} = {};
42
+ protected methodToUse: {[tokenSymbol: string]: PriceMethod} = {};
25
43
 
26
44
  /**
27
45
  * TOKENA and TOKENB are the two token names to get price of TokenA in terms of TokenB
28
46
  */
47
+ // ! switch to USDC (new) later
29
48
  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
49
+ protected EKUBO_API = `https://prod-api-quoter.ekubo.org/23448594291968334/{{AMOUNT}}/{{TOKEN_ADDRESS}}/${PRICER_USDC_ADDRESS}`; // e.g. ETH/USDC
31
50
 
32
51
  constructor(config: IConfig, tokens: TokenInfo[], refreshInterval = 30000, staleTime = 60000) {
33
52
  super(config, tokens);
34
53
  this.refreshInterval = refreshInterval;
35
54
  this.staleTime = staleTime;
55
+ this.avnuApiPricer = new PricerAvnuApi(config, tokens);
36
56
  }
37
57
 
38
58
  isReady() {
@@ -66,6 +86,7 @@ export class Pricer extends PricerBase {
66
86
  }
67
87
 
68
88
  start() {
89
+ this.avnuApiPricer.start();
69
90
  this._loadPrices();
70
91
  setInterval(() => {
71
92
  this._loadPrices();
@@ -81,7 +102,7 @@ export class Pricer extends PricerBase {
81
102
  Global.assert(!this.isStale(timestamp, tokenName), `Price of ${tokenName} is stale`);
82
103
 
83
104
  }
84
- async getPrice(tokenSymbol: string) {
105
+ async getPrice(tokenSymbol: string, blockNumber?: BlockIdentifier) {
85
106
  Global.assert(this.prices[tokenSymbol], `Price of ${tokenSymbol} not found`);
86
107
  this.assertNotStale(this.prices[tokenSymbol].timestamp, tokenSymbol);
87
108
  return this.prices[tokenSymbol];
@@ -93,7 +114,10 @@ export class Pricer extends PricerBase {
93
114
  let retry = 0;
94
115
  while (retry < MAX_RETRIES) {
95
116
  try {
96
- if (token.symbol === 'USDT') {
117
+ if (token.dontPrice) {
118
+ return;
119
+ }
120
+ if (token.symbol === 'USDT' || token.symbol === 'USDC') {
97
121
  this.prices[token.symbol] = {
98
122
  price: 1,
99
123
  timestamp: new Date()
@@ -142,47 +166,70 @@ export class Pricer extends PricerBase {
142
166
  }
143
167
  }
144
168
 
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
169
+ async _getPrice(token: TokenInfo): Promise<number> {
170
+ const methodsToTry = this._getMethodsToTry(token);
171
+
172
+ for (const method of methodsToTry) {
173
+ logger.verbose(`Fetching price of ${token.symbol} using ${method}`);
174
+ try {
175
+ const result = await this._tryPriceMethod(token, method);
176
+ if (!token.priceMethod) {
177
+ this.methodToUse[token.symbol] = method;
176
178
  }
179
+ return result;
180
+ } catch (error: any) {
181
+ console.warn(`${method}: price err [${token.symbol}]: `, error.message);
182
+ }
177
183
  }
178
184
 
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');
185
+ throw new FatalError(`Price not found for ${token.symbol}`);
186
+ }
187
+
188
+ protected _getMethodsToTry(token: TokenInfo): PriceMethod[] {
189
+ const methods: PriceMethod[] = [];
190
+
191
+ if (token.priceMethod) {
192
+ methods.push(token.priceMethod);
183
193
  }
184
194
 
185
- throw new FatalError(`Price not found for ${token.symbol}`);
195
+ const pinned = this.methodToUse[token.symbol];
196
+ if (pinned && pinned !== token.priceMethod) {
197
+ methods.push(pinned);
198
+ }
199
+
200
+ for (const method of PRICE_METHOD_PRIORITY) {
201
+ if (!methods.includes(method)) {
202
+ methods.push(method);
203
+ }
204
+ }
205
+
206
+ return methods;
207
+ }
208
+
209
+ protected async _tryPriceMethod(token: TokenInfo, method: PriceMethod): Promise<number> {
210
+ switch (method) {
211
+ case 'AvnuApi':
212
+ return await this._getPriceAvnuApi(token);
213
+ case 'Coinbase':
214
+ return await this._getPriceCoinbase(token);
215
+ case 'Coinmarketcap':
216
+ return await this._getPriceCoinMarketCap(token);
217
+ case 'Ekubo':
218
+ return await this._getPriceEkubo(
219
+ token,
220
+ new Web3Number(token.priceCheckAmount ? token.priceCheckAmount : 1, token.decimals),
221
+ );
222
+ case 'Avnu':
223
+ return await this._getAvnuPrice(
224
+ token,
225
+ new Web3Number(token.priceCheckAmount ? token.priceCheckAmount : 1, token.decimals),
226
+ );
227
+ }
228
+ }
229
+
230
+ async _getPriceAvnuApi(token: TokenInfo): Promise<number> {
231
+ const priceInfo = await this.avnuApiPricer.getPrice(token.symbol);
232
+ return priceInfo.price;
186
233
  }
187
234
 
188
235
  async _getPriceCoinbase(token: TokenInfo) {
@@ -200,24 +247,80 @@ export class Pricer extends PricerBase {
200
247
  throw new Error("Not implemented");
201
248
  }
202
249
 
250
+ protected async _resolveQuoteTokenUsdPrice(symbol: string): Promise<number> {
251
+ const cached = this.prices[symbol];
252
+ if (cached && !this.isStale(cached.timestamp, symbol)) {
253
+ return cached.price;
254
+ }
255
+
256
+ const quoteToken = this.tokens.find((t) => t.symbol === symbol);
257
+ if (!quoteToken) {
258
+ throw new FatalError(`Quote token ${symbol} not found in pricer tokens`);
259
+ }
260
+
261
+ return await this._getPrice(quoteToken);
262
+ }
263
+
264
+ protected async _convertDexQuoteToUsd(
265
+ token: TokenInfo,
266
+ quoteAmount: number,
267
+ ): Promise<number> {
268
+ const quoteConfig = resolveQuoteTokenConfig(token, this.tokens);
269
+ const usdPrice = await convertQuoteAmountToUsd(
270
+ token.symbol,
271
+ quoteAmount,
272
+ quoteConfig,
273
+ this._resolveQuoteTokenUsdPrice.bind(this),
274
+ );
275
+ logger.verbose(
276
+ `${token.symbol}: ${quoteAmount} ${quoteConfig.symbol} -> $${usdPrice}`,
277
+ );
278
+ return usdPrice;
279
+ }
280
+
281
+ async _getAvnuPrice(token: TokenInfo, amountIn = new Web3Number(1, token.decimals), retry = 0): Promise<number> {
282
+ const quoteConfig = resolveQuoteTokenConfig(token, this.tokens);
283
+ logger.verbose(`Getting price of ${token.symbol} using Avnu, amountIn: ${amountIn.toWei()}`);
284
+
285
+ const avnuWrapper = new AvnuWrapper();
286
+ const quote = await avnuWrapper.getQuotes(
287
+ token.address.toString(),
288
+ quoteConfig.address,
289
+ amountIn.toWei(),
290
+ "0x1",
291
+ );
292
+ const multiplier = 1 / amountIn.toNumber();
293
+ const outputQuote = Number(
294
+ Web3Number.fromWei(quote.buyAmount.toString(), quoteConfig.decimals).toFixed(6),
295
+ ) * multiplier;
296
+ logger.verbose(`Avnu: ${token.symbol} -> ${quoteConfig.symbol}: ${outputQuote}, retry: ${retry}`);
297
+ if (outputQuote === 0 && retry < 3) {
298
+ const retryAmountIn = new Web3Number(100, token.decimals);
299
+ return await this._getAvnuPrice(token, retryAmountIn, retry + 1);
300
+ }
301
+
302
+ return await this._convertDexQuoteToUsd(token, outputQuote);
303
+ }
304
+
203
305
  async _getPriceEkubo(token: TokenInfo, amountIn = new Web3Number(1, token.decimals), retry = 0): Promise<number> {
204
- const url = this.EKUBO_API.replace("{{TOKEN_ADDRESS}}", token.address.toString()).replace("{{AMOUNT}}", amountIn.toWei());
306
+ const quoteConfig = resolveQuoteTokenConfig(token, this.tokens);
307
+ logger.verbose(`Getting price of ${token.symbol} using Ekubo, amountIn: ${amountIn.toWei()}`);
308
+ const url = this.EKUBO_API
309
+ .replace("{{TOKEN_ADDRESS}}", token.address.toString())
310
+ .replace("{{AMOUNT}}", amountIn.toWei())
311
+ .replace(PRICER_USDC_ADDRESS, quoteConfig.address);
205
312
  const result = await axios.get(url);
206
313
  const data: any = result.data;
207
314
  const multiplier = 1 / amountIn.toNumber();
208
- const outputUSDC = Number(Web3Number.fromWei(data.total_calculated, 6).toFixed(6)) * multiplier;
209
- logger.verbose(`Ekubo: ${token.symbol} -> USDC: ${outputUSDC}, retry: ${retry}`);
210
- if (outputUSDC === 0 && retry < 3) {
211
- // try again with a higher amount
212
- const amountIn = new Web3Number(100, token.decimals); // 100 unit of token
213
- return await this._getPriceEkubo(token, amountIn, retry + 1);
315
+ const outputQuote = Number(
316
+ Web3Number.fromWei(data.total_calculated, quoteConfig.decimals).toFixed(6),
317
+ ) * multiplier;
318
+ logger.verbose(`Ekubo: ${token.symbol} -> ${quoteConfig.symbol}: ${outputQuote}, retry: ${retry}`);
319
+ if (outputQuote === 0 && retry < 3) {
320
+ const retryAmountIn = new Web3Number(100, token.decimals);
321
+ return await this._getPriceEkubo(token, retryAmountIn, retry + 1);
214
322
  }
215
323
 
216
- // if usdc depegs, it will not longer be 1 USD
217
- // so we need to get the price of USDC in USD
218
- // and then convert the outputUSDC to USD
219
- const usdcPrice = 1; // (await this.getPrice('USDC')).price;
220
- logger.verbose(`USDC Price: ${usdcPrice}`);
221
- return outputUSDC * usdcPrice;
324
+ return await this._convertDexQuoteToUsd(token, outputQuote);
222
325
  }
223
326
  }
@@ -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);