@strkfarm/sdk 2.0.0-dev.26 → 2.0.0-dev.28

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 (70) hide show
  1. package/dist/cli.js +190 -36
  2. package/dist/cli.mjs +188 -34
  3. package/dist/index.browser.global.js +79130 -49354
  4. package/dist/index.browser.mjs +18039 -11431
  5. package/dist/index.d.ts +2869 -898
  6. package/dist/index.js +19036 -12207
  7. package/dist/index.mjs +18942 -12158
  8. package/package.json +1 -1
  9. package/src/data/avnu.abi.json +840 -0
  10. package/src/data/ekubo-price-fethcer.abi.json +265 -0
  11. package/src/dataTypes/_bignumber.ts +13 -4
  12. package/src/dataTypes/index.ts +3 -2
  13. package/src/dataTypes/mynumber.ts +141 -0
  14. package/src/global.ts +76 -41
  15. package/src/index.browser.ts +2 -1
  16. package/src/interfaces/common.tsx +167 -2
  17. package/src/modules/ExtendedWrapperSDk/types.ts +26 -4
  18. package/src/modules/ExtendedWrapperSDk/wrapper.ts +110 -67
  19. package/src/modules/apollo-client-config.ts +28 -0
  20. package/src/modules/avnu.ts +4 -4
  21. package/src/modules/ekubo-pricer.ts +79 -0
  22. package/src/modules/ekubo-quoter.ts +46 -30
  23. package/src/modules/erc20.ts +17 -0
  24. package/src/modules/harvests.ts +43 -29
  25. package/src/modules/pragma.ts +23 -8
  26. package/src/modules/pricer-from-api.ts +156 -15
  27. package/src/modules/pricer-lst.ts +1 -1
  28. package/src/modules/pricer.ts +40 -4
  29. package/src/modules/pricerBase.ts +2 -1
  30. package/src/node/deployer.ts +36 -1
  31. package/src/node/pricer-redis.ts +2 -1
  32. package/src/strategies/base-strategy.ts +78 -10
  33. package/src/strategies/ekubo-cl-vault.tsx +906 -347
  34. package/src/strategies/factory.ts +159 -0
  35. package/src/strategies/index.ts +6 -1
  36. package/src/strategies/registry.ts +239 -0
  37. package/src/strategies/sensei.ts +335 -7
  38. package/src/strategies/svk-strategy.ts +97 -27
  39. package/src/strategies/types.ts +4 -0
  40. package/src/strategies/universal-adapters/adapter-utils.ts +2 -1
  41. package/src/strategies/universal-adapters/avnu-adapter.ts +177 -268
  42. package/src/strategies/universal-adapters/baseAdapter.ts +263 -251
  43. package/src/strategies/universal-adapters/common-adapter.ts +206 -203
  44. package/src/strategies/universal-adapters/extended-adapter.ts +155 -336
  45. package/src/strategies/universal-adapters/index.ts +9 -8
  46. package/src/strategies/universal-adapters/token-transfer-adapter.ts +200 -0
  47. package/src/strategies/universal-adapters/usdc<>usdce-adapter.ts +200 -0
  48. package/src/strategies/universal-adapters/vesu-adapter.ts +110 -75
  49. package/src/strategies/universal-adapters/vesu-modify-position-adapter.ts +476 -0
  50. package/src/strategies/universal-adapters/vesu-multiply-adapter.ts +762 -844
  51. package/src/strategies/universal-adapters/vesu-position-common.ts +251 -0
  52. package/src/strategies/universal-adapters/vesu-supply-only-adapter.ts +18 -3
  53. package/src/strategies/universal-lst-muliplier-strategy.tsx +396 -204
  54. package/src/strategies/universal-strategy.tsx +1426 -1178
  55. package/src/strategies/vesu-extended-strategy/services/executionService.ts +2251 -0
  56. package/src/strategies/vesu-extended-strategy/services/extended-vesu-state-manager.ts +2941 -0
  57. package/src/strategies/vesu-extended-strategy/services/operationService.ts +12 -1
  58. package/src/strategies/vesu-extended-strategy/types/transaction-metadata.ts +52 -0
  59. package/src/strategies/vesu-extended-strategy/utils/config.runtime.ts +1 -0
  60. package/src/strategies/vesu-extended-strategy/utils/constants.ts +3 -1
  61. package/src/strategies/vesu-extended-strategy/utils/helper.ts +158 -124
  62. package/src/strategies/vesu-extended-strategy/vesu-extended-strategy.tsx +377 -1781
  63. package/src/strategies/vesu-rebalance.tsx +255 -152
  64. package/src/utils/health-factor-math.ts +4 -1
  65. package/src/utils/index.ts +2 -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/strategies/universal-adapters/unused-balance-adapter.ts +0 -109
@@ -1,1178 +1,1426 @@
1
- import { ContractAddr, Web3Number } from "@/dataTypes";
2
- import { BaseStrategy, SingleActionAmount, SingleTokenInfo } from "./base-strategy";
3
- import { PricerBase } from "@/modules/pricerBase";
4
- import { FAQ, getNoRiskTags, IConfig, IStrategyMetadata, Protocols, RiskFactor, RiskType, VaultPosition } from "@/interfaces";
5
- import { BlockIdentifier, Call, CallData, Contract, num, uint256 } from "starknet";
6
- import { VesuRebalanceSettings } from "./vesu-rebalance";
7
- import { assert, LeafData, logger, StandardMerkleTree } from "@/utils";
8
- import UniversalVaultAbi from '../data/universal-vault.abi.json';
9
- import ManagerAbi from '../data/vault-manager.abi.json';
10
- import { ApproveCallParams, AvnuSwapCallParams, BaseAdapter, CommonAdapter, DepositParams, FlashloanCallParams, GenerateCallFn, LeafAdapterFn, ManageCall, WithdrawParams } from "./universal-adapters";
11
- import { Global } from "@/global";
12
- import { AvnuWrapper, ERC20 } from "@/modules";
13
- import { AVNU_MIDDLEWARE, VESU_SINGLETON } from "./universal-adapters/adapter-utils";
14
- import { VesuHarvests } from "@/modules/harvests";
15
-
16
- export interface UniversalManageCall {
17
- proofs: string[];
18
- manageCall: ManageCall;
19
- step: UNIVERSAL_MANAGE_IDS;
20
- }
21
-
22
- export interface UniversalStrategySettings {
23
- vaultAddress: ContractAddr,
24
- manager: ContractAddr,
25
- vaultAllocator: ContractAddr,
26
- redeemRequestNFT: ContractAddr,
27
-
28
- // Individual merkle tree leaves
29
- leafAdapters: LeafAdapterFn<any>[],
30
-
31
- // Useful for returning adapter class objects that can compute
32
- // certain things for us (e.g. positions, hfs)
33
- adapters: {id: string, adapter: BaseAdapter<DepositParams, WithdrawParams>}[]
34
- }
35
-
36
- export enum AUMTypes {
37
- FINALISED = 'finalised',
38
- DEFISPRING = 'defispring'
39
- }
40
-
41
- export enum PositionTypeAvnuExtended {
42
- OPEN = 'open',
43
- CLOSE = 'close'
44
- }
45
-
46
- // export class UniversalStrategy<
47
- // S extends UniversalStrategySettings
48
- // > extends BaseStrategy<
49
- // SingleTokenInfo,
50
- // SingleActionAmount
51
- // > {
52
-
53
- // /** Contract address of the strategy */
54
- // readonly address: ContractAddr;
55
- // /** Pricer instance for token price calculations */
56
- // readonly pricer: PricerBase;
57
- // /** Metadata containing strategy information */
58
- // readonly metadata: IStrategyMetadata<S>;
59
- // /** Contract instance for interacting with the strategy */
60
- // readonly contract: Contract;
61
- // readonly managerContract: Contract;
62
- // merkleTree: StandardMerkleTree | undefined;
63
-
64
- // constructor(
65
- // config: IConfig,
66
- // pricer: PricerBase,
67
- // metadata: IStrategyMetadata<S>
68
- // ) {
69
- // super(config);
70
- // this.pricer = pricer;
71
-
72
- // assert(
73
- // metadata.depositTokens.length === 1,
74
- // "VesuRebalance only supports 1 deposit token"
75
- // );
76
- // this.metadata = metadata;
77
- // this.address = metadata.address;
78
-
79
- // this.contract = new Contract({
80
- // abi: UniversalVaultAbi,
81
- // address: this.address.address,
82
- // providerOrAccount: this.config.provider
83
- // });
84
- // this.managerContract = new Contract({
85
- // abi: ManagerAbi,
86
- // address: this.metadata.additionalInfo.manager.address,
87
- // providerOrAccount: this.config.provider
88
- // });
89
- // }
90
-
91
- // getAllLeaves() {
92
- // const leaves = this.metadata.additionalInfo.leafAdapters.map((adapter, index) => {
93
- // return adapter()
94
- // });
95
- // const _leaves: LeafData[] = [];
96
- // leaves.forEach((_l) => {
97
- // _leaves.push(..._l.leaves);
98
- // })
99
- // return _leaves;
100
-
101
- // }
102
- // getMerkleTree() {
103
- // if (this.merkleTree) return this.merkleTree;
104
- // const _leaves = this.getAllLeaves();
105
-
106
- // const standardTree = StandardMerkleTree.of(_leaves);
107
- // this.merkleTree = standardTree;
108
- // return standardTree;
109
- // }
110
-
111
- // getMerkleRoot() {
112
- // return this.getMerkleTree().root;
113
- // }
114
-
115
- // getAdapter(id: string): BaseAdapter<DepositParams, WithdrawParams> {
116
- // const adapter = this.metadata.additionalInfo.adapters.find(adapter => adapter.id === id);
117
- // if (!adapter) {
118
- // throw new Error(`Adapter not found for ID: ${id}`);
119
- // }
120
- // return adapter.adapter;
121
- // }
122
-
123
- // asset() {
124
- // return this.metadata.depositTokens[0];
125
- // }
126
-
127
- // async depositCall(amountInfo: SingleActionAmount, receiver: ContractAddr): Promise<Call[]> {
128
- // // Technically its not erc4626 abi, but we just need approve call
129
- // // so, its ok to use it
130
- // assert(
131
- // amountInfo.tokenInfo.address.eq(this.asset().address),
132
- // "Deposit token mismatch"
133
- // );
134
- // const assetContract = new Contract({
135
- // abi: UniversalVaultAbi,
136
- // address: this.asset().address.address,
137
- // providerOrAccount: this.config.provider
138
- // });
139
- // const call1 = assetContract.populate("approve", [
140
- // this.address.address,
141
- // uint256.bnToUint256(amountInfo.amount.toWei())
142
- // ]);
143
- // const call2 = this.contract.populate("deposit", [
144
- // uint256.bnToUint256(amountInfo.amount.toWei()),
145
- // receiver.address
146
- // ]);
147
- // return [call1, call2];
148
- // }
149
-
150
- // async withdrawCall(amountInfo: SingleActionAmount, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]> {
151
- // assert(
152
- // amountInfo.tokenInfo.address.eq(this.asset().address),
153
- // "Withdraw token mismatch"
154
- // );
155
- // const shares = await this.contract.call('convert_to_shares', [uint256.bnToUint256(amountInfo.amount.toWei())]);
156
- // const call = this.contract.populate("request_redeem", [
157
- // uint256.bnToUint256(shares.toString()),
158
- // receiver.address,
159
- // owner.address
160
- // ]);
161
- // return [call];
162
- // }
163
-
164
- // /**
165
- // * Calculates the Total Value Locked (TVL) for a specific user.
166
- // * @param user - Address of the user
167
- // * @returns Object containing the amount in token units and USD value
168
- // */
169
- // async getUserTVL(user: ContractAddr) {
170
- // const shares = await this.contract.balance_of(user.address);
171
- // const assets = await this.contract.convert_to_assets(
172
- // uint256.bnToUint256(shares)
173
- // );
174
- // const amount = Web3Number.fromWei(
175
- // assets.toString(),
176
- // this.metadata.depositTokens[0].decimals
177
- // );
178
- // let price = await this.pricer.getPrice(
179
- // this.metadata.depositTokens[0].symbol
180
- // );
181
- // const usdValue = Number(amount.toFixed(6)) * price.price;
182
- // return {
183
- // tokenInfo: this.asset(),
184
- // amount,
185
- // usdValue
186
- // };
187
- // }
188
-
189
- // /**
190
- // * Calculates the weighted average APY across all pools based on USD value.
191
- // * @returns {Promise<number>} The weighted average APY across all pools
192
- // */
193
- // async netAPY(): Promise<{ net: number, splits: { apy: number, id: string }[] }> {
194
- // if (this.metadata.isPreview) {
195
- // return { net: 0, splits: [{
196
- // apy: 0, id: 'base'
197
- // }, {
198
- // apy: 0, id: 'defispring'
199
- // }] };
200
- // }
201
-
202
- // const { positions, baseAPYs, rewardAPYs } = await this.getVesuAPYs();
203
-
204
- // const unusedBalanceAPY = await this.getUnusedBalanceAPY();
205
- // baseAPYs.push(...[unusedBalanceAPY.apy]);
206
- // rewardAPYs.push(0);
207
-
208
- // // Compute APy using weights
209
- // const weights = positions.map((p, index) => p.usdValue * (index % 2 == 0 ? 1 : -1));
210
- // weights.push(unusedBalanceAPY.weight);
211
-
212
- // const prevAUM = await this.getPrevAUM();
213
- // const price = await this.pricer.getPrice(this.metadata.depositTokens[0].symbol);
214
- // const prevAUMUSD = prevAUM.multipliedBy(price.price);
215
- // return this.returnNetAPY(baseAPYs, rewardAPYs, weights, prevAUMUSD);
216
- // }
217
-
218
- // protected async returnNetAPY(baseAPYs: number[], rewardAPYs: number[], weights: number[], prevAUMUSD: Web3Number) {
219
- // // If no positions, return 0
220
- // if (weights.every(p => p == 0)) {
221
- // return { net: 0, splits: [{
222
- // apy: 0, id: 'base'
223
- // }, {
224
- // apy: 0, id: 'defispring'
225
- // }]};
226
- // }
227
-
228
- // const baseAPY = this.computeAPY(baseAPYs, weights, prevAUMUSD);
229
- // const rewardAPY = this.computeAPY(rewardAPYs, weights, prevAUMUSD);
230
- // const netAPY = baseAPY + rewardAPY;
231
- // logger.verbose(`${this.metadata.name}::netAPY: net: ${netAPY}, baseAPY: ${baseAPY}, rewardAPY: ${rewardAPY}`);
232
- // return { net: netAPY, splits: [{
233
- // apy: baseAPY, id: 'base'
234
- // }, {
235
- // apy: rewardAPY, id: 'defispring'
236
- // }] };
237
- // }
238
-
239
- // protected async getUnusedBalanceAPY() {
240
- // return {
241
- // apy: 0, weight: 0
242
- // }
243
- // }
244
-
245
- // private computeAPY(apys: number[], weights: number[], currentAUM: Web3Number) {
246
- // assert(apys.length === weights.length, "APYs and weights length mismatch");
247
- // const weightedSum = apys.reduce((acc, apy, i) => acc + apy * weights[i], 0);
248
- // logger.verbose(`${this.getTag()} computeAPY: apys: ${JSON.stringify(apys)}, weights: ${JSON.stringify(weights)}, weightedSum: ${weightedSum}, currentAUM: ${currentAUM}`);
249
- // return weightedSum / currentAUM.toNumber();
250
- // }
251
-
252
- // /**
253
- // * Calculates the total TVL of the strategy.
254
- // * @returns Object containing the total amount in token units and USD value
255
- // */
256
- // async getTVL() {
257
- // const assets = await this.contract.total_assets();
258
- // const amount = Web3Number.fromWei(
259
- // assets.toString(),
260
- // this.metadata.depositTokens[0].decimals
261
- // );
262
- // let price = await this.pricer.getPrice(
263
- // this.metadata.depositTokens[0].symbol
264
- // );
265
- // const usdValue = Number(amount.toFixed(6)) * price.price;
266
- // return {
267
- // tokenInfo: this.asset(),
268
- // amount,
269
- // usdValue
270
- // };
271
- // }
272
-
273
- // async getUnusedBalance(): Promise<SingleTokenInfo> {
274
- // const balance = await (new ERC20(this.config)).balanceOf(this.asset().address, this.metadata.additionalInfo.vaultAllocator, this.asset().decimals);
275
- // const price = await this.pricer.getPrice(this.metadata.depositTokens[0].symbol);
276
- // const usdValue = Number(balance.toFixed(6)) * price.price;
277
- // return {
278
- // tokenInfo: this.asset(),
279
- // amount: balance,
280
- // usdValue
281
- // };
282
- // }
283
-
284
- // protected async getVesuAUM(adapter: VesuAdapter) {
285
- // const legAUM = await adapter.getPositions(this.config);
286
- // const underlying = this.asset();
287
- // let vesuAum = Web3Number.fromWei("0", underlying.decimals);
288
-
289
- // let tokenUnderlyingPrice = await this.pricer.getPrice(this.asset().symbol);
290
- // logger.verbose(`${this.getTag()} tokenUnderlyingPrice: ${tokenUnderlyingPrice.price}`);
291
-
292
- // // handle collateral
293
- // if (legAUM[0].token.address.eq(underlying.address)) {
294
- // vesuAum = vesuAum.plus(legAUM[0].amount);
295
- // } else {
296
- // vesuAum = vesuAum.plus(legAUM[0].usdValue / tokenUnderlyingPrice.price);
297
- // }
298
-
299
- // // handle debt
300
- // if (legAUM[1].token.address.eq(underlying.address)) {
301
- // vesuAum = vesuAum.minus(legAUM[1].amount);
302
- // } else {
303
- // vesuAum = vesuAum.minus(legAUM[1].usdValue / tokenUnderlyingPrice.price);
304
- // };
305
-
306
- // logger.verbose(`${this.getTag()} Vesu AUM: ${vesuAum}, legCollateral: ${legAUM[0].amount.toNumber()}, legDebt: ${legAUM[1].amount.toNumber()}`);
307
- // return vesuAum;
308
- // }
309
-
310
- // async getPrevAUM() {
311
- // const currentAUM: bigint = await this.contract.call('aum', []) as bigint;
312
- // const prevAum = Web3Number.fromWei(currentAUM.toString(), this.asset().decimals);
313
- // logger.verbose(`${this.getTag()} Prev AUM: ${prevAum}`);
314
- // return prevAum;
315
- // }
316
-
317
- // async getAUM(): Promise<{net: SingleTokenInfo, prevAum: Web3Number, splits: {id: string, aum: Web3Number}[]}> {
318
- // const prevAum = await this.getPrevAUM();
319
- // const token1Price = await this.pricer.getPrice(this.metadata.depositTokens[0].symbol);
320
-
321
- // // calculate vesu aum
322
- // const vesuAdapters = this.getVesuAdapters();
323
- // let vesuAum = Web3Number.fromWei("0", this.asset().decimals);
324
- // for (const adapter of vesuAdapters) {
325
- // vesuAum = vesuAum.plus(await this.getVesuAUM(adapter));
326
- // }
327
-
328
- // // account unused balance as aum as well (from vault allocator)
329
- // const balance = await this.getUnusedBalance();
330
- // logger.verbose(`${this.getTag()} unused balance: ${balance.amount.toNumber()}`);
331
-
332
- // // Initiate return values
333
- // const zeroAmt = Web3Number.fromWei('0', this.asset().decimals);
334
- // const net = {
335
- // tokenInfo: this.asset(),
336
- // amount: zeroAmt,
337
- // usdValue: 0
338
- // };
339
- // const aumToken = vesuAum.plus(balance.amount);
340
- // if (aumToken.isZero()) {
341
- // return { net, splits: [{
342
- // aum: zeroAmt, id: AUMTypes.FINALISED
343
- // }, {
344
- // aum: zeroAmt, id: AUMTypes.DEFISPRING
345
- // }], prevAum};
346
- // }
347
- // logger.verbose(`${this.getTag()} Actual AUM: ${aumToken}`);
348
-
349
- // // compute rewards contribution to AUM
350
- // const rewardAssets = await this.getRewardsAUM(prevAum);
351
-
352
- // // Sum up and return
353
- // const newAUM = aumToken.plus(rewardAssets);
354
- // logger.verbose(`${this.getTag()} New AUM: ${newAUM}`);
355
-
356
- // net.amount = newAUM;
357
- // net.usdValue = newAUM.multipliedBy(token1Price.price).toNumber();
358
- // const splits = [{
359
- // id: AUMTypes.FINALISED,
360
- // aum: aumToken
361
- // }, {
362
- // id: AUMTypes.DEFISPRING,
363
- // aum: rewardAssets
364
- // }];
365
- // return { net, splits, prevAum };
366
- // }
367
-
368
- // // account for future rewards (e.g. defispring rewards)
369
- // protected async getRewardsAUM(prevAum: Web3Number) {
370
- // const lastReportTime = await this.contract.call('last_report_timestamp', []);
371
- // // - calculate estimated growth from strk rewards
372
- // const netAPY = await this.netAPY();
373
- // // account only 80% of value
374
- // const defispringAPY = (netAPY.splits.find(s => s.id === 'defispring')?.apy || 0) * 0.8;
375
- // if (!defispringAPY) throw new Error('DefiSpring APY not found');
376
-
377
- // // compute rewards contribution to AUM
378
- // const timeDiff = (Math.round(Date.now() / 1000) - Number(lastReportTime));
379
- // const growthRate = timeDiff * defispringAPY / (365 * 24 * 60 * 60);
380
- // const rewardAssets = prevAum.multipliedBy(growthRate);
381
- // logger.verbose(`${this.getTag()} DefiSpring AUM time difference: ${timeDiff}`);
382
- // logger.verbose(`${this.getTag()} Current AUM: ${prevAum.toString()}`);
383
- // logger.verbose(`${this.getTag()} Net APY: ${JSON.stringify(netAPY)}`);
384
- // logger.verbose(`${this.getTag()} rewards AUM: ${rewardAssets}`);
385
-
386
- // return rewardAssets;
387
- // }
388
-
389
-
390
-
391
- // async getVaultPositions(): Promise<VaultPosition[]> {
392
- // const vesuPositions = await this.getVesuPositions();
393
- // const unusedBalance = await this.getUnusedBalance();
394
- // return [...vesuPositions, {
395
- // amount: unusedBalance.amount,
396
- // usdValue: unusedBalance.usdValue,
397
- // token: this.asset(),
398
- // remarks: "Unused Balance (may not include recent deposits)"
399
- // }];
400
- // }
401
-
402
- // getSetManagerCall(strategist: ContractAddr, root = this.getMerkleRoot()) {
403
- // return this.managerContract.populate('set_manage_root', [strategist.address, num.getHexString(root)]);
404
- // }
405
-
406
- // getManageCall(proofIds: string[], manageCalls: ManageCall[]) {
407
- // assert(proofIds.length == manageCalls.length, 'Proof IDs and Manage Calls length mismatch');
408
- // return this.managerContract.populate('manage_vault_with_merkle_verification', {
409
- // proofs: proofIds.map(id => this.getProofs(id).proofs),
410
- // decoder_and_sanitizers: manageCalls.map(call => call.sanitizer.address),
411
- // targets: manageCalls.map(call => call.call.contractAddress.address),
412
- // selectors: manageCalls.map(call => call.call.selector),
413
- // calldatas: manageCalls.map(call => call.call.calldata), // Calldata[]
414
- // });
415
- // }
416
-
417
- // getVesuModifyPositionCalls(params: {
418
- // isLeg1: boolean,
419
- // isDeposit: boolean,
420
- // depositAmount: Web3Number,
421
- // debtAmount: Web3Number
422
- // }): UniversalManageCall[] {
423
- // assert(params.depositAmount.gt(0) || params.debtAmount.gt(0), 'Either deposit or debt amount must be greater than 0');
424
- // // approve token
425
- // const isToken1 = params.isLeg1 == params.isDeposit; // XOR
426
- // const STEP1_ID = isToken1 ? UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN1 :UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN2;
427
- // const manage4Info = this.getProofs<ApproveCallParams>(STEP1_ID);
428
- // const approveAmount = params.isDeposit ? params.depositAmount : params.debtAmount;
429
- // const manageCall4 = manage4Info.callConstructor({
430
- // amount: approveAmount
431
- // })
432
-
433
- // // deposit and borrow or repay and withdraw
434
- // const STEP2_ID = params.isLeg1 ? UNIVERSAL_MANAGE_IDS.VESU_LEG1 : UNIVERSAL_MANAGE_IDS.VESU_LEG2;
435
- // const manage5Info = this.getProofs<VesuModifyPositionCallParams>(STEP2_ID);
436
- // const manageCall5 = manage5Info.callConstructor(VesuAdapter.getDefaultModifyPositionCallParams({
437
- // collateralAmount: params.depositAmount,
438
- // isAddCollateral: params.isDeposit,
439
- // debtAmount: params.debtAmount,
440
- // isBorrow: params.isDeposit
441
- // }))
442
-
443
- // const output = [{
444
- // proofs: manage5Info.proofs,
445
- // manageCall: manageCall5,
446
- // step: STEP2_ID
447
- // }];
448
- // if (approveAmount.gt(0)) {
449
- // output.unshift({
450
- // proofs: manage4Info.proofs,
451
- // manageCall: manageCall4,
452
- // step: STEP1_ID
453
- // })
454
- // }
455
- // return output;
456
- // }
457
-
458
- // getTag() {
459
- // return `${UniversalStrategy.name}:${this.metadata.name}`;
460
- // }
461
-
462
- // /**
463
- // * Gets LST APR for the strategy's underlying asset from Endur API
464
- // * @returns Promise<number> The LST APR (not divided by 1e18)
465
- // */
466
- // async getLSTAPR(address: ContractAddr): Promise<number> {
467
- // return 0;
468
- // }
469
-
470
- // async getVesuHealthFactors(blockNumber: BlockIdentifier = 'latest') {
471
- // return await Promise.all(this.getVesuAdapters().map(v => v.getHealthFactor(blockNumber)));
472
- // }
473
-
474
- // async computeRebalanceConditionAndReturnCalls(): Promise<Call[]> {
475
- // const vesuAdapters = this.getVesuAdapters();
476
- // const healthFactors = await this.getVesuHealthFactors();
477
- // const leg1HealthFactor = healthFactors[0];
478
- // const leg2HealthFactor = healthFactors[1];
479
- // logger.verbose(`${this.getTag()}: HealthFactorLeg1: ${leg1HealthFactor}`);
480
- // logger.verbose(`${this.getTag()}: HealthFactorLeg2: ${leg2HealthFactor}`);
481
-
482
- // const minHf = this.metadata.additionalInfo.minHealthFactor;
483
- // const isRebalanceNeeded1 = leg1HealthFactor < minHf;
484
- // const isRebalanceNeeded2 = leg2HealthFactor < minHf;
485
- // if (!isRebalanceNeeded1 && !isRebalanceNeeded2) {
486
- // return [];
487
- // }
488
-
489
- // if (isRebalanceNeeded1) {
490
- // const amount = await this.getLegRebalanceAmount(vesuAdapters[0], leg1HealthFactor, false);
491
- // const leg2HF = await this.getNewHealthFactor(vesuAdapters[1], amount, true);
492
- // assert(leg2HF > minHf, `Rebalance Leg1 failed: Leg2 HF after rebalance would be too low: ${leg2HF}`);
493
- // return [await this.getRebalanceCall({
494
- // isLeg1toLeg2: false,
495
- // amount: amount
496
- // })];
497
- // } else {
498
- // const amount = await this.getLegRebalanceAmount(vesuAdapters[1], leg2HealthFactor, true);
499
- // const leg1HF = await this.getNewHealthFactor(vesuAdapters[0], amount, false);
500
- // assert(leg1HF > minHf, `Rebalance Leg2 failed: Leg1 HF after rebalance would be too low: ${leg1HF}`);
501
- // return [await this.getRebalanceCall({
502
- // isLeg1toLeg2: true,
503
- // amount: amount
504
- // })];
505
- // }
506
- // }
507
-
508
- // private async getNewHealthFactor(vesuAdapter: VesuAdapter, newAmount: Web3Number, isWithdraw: boolean) {
509
- // const {
510
- // collateralTokenAmount,
511
- // collateralUSDAmount,
512
- // collateralPrice,
513
- // debtTokenAmount,
514
- // debtUSDAmount,
515
- // debtPrice,
516
- // ltv
517
- // } = await vesuAdapter.getAssetPrices();
518
-
519
- // if (isWithdraw) {
520
- // const newHF = ((collateralTokenAmount.toNumber() - newAmount.toNumber()) * collateralPrice * ltv) / debtUSDAmount;
521
- // logger.verbose(`getNewHealthFactor:: HF: ${newHF}, amoutn: ${newAmount.toNumber()}, isDeposit`);
522
- // return newHF;
523
- // } else { // is borrow
524
- // const newHF = (collateralUSDAmount * ltv) / ((debtTokenAmount.toNumber() + newAmount.toNumber()) * debtPrice);
525
- // logger.verbose(`getNewHealthFactor:: HF: ${newHF}, amoutn: ${newAmount.toNumber()}, isRepay`);
526
- // return newHF;
527
- // }
528
- // }
529
-
530
- // /**
531
- // *
532
- // * @param vesuAdapter
533
- // * @param currentHf
534
- // * @param isDeposit if true, attempt by adding collateral, else by repaying
535
- // * @returns
536
- // */
537
- // private async getLegRebalanceAmount(vesuAdapter: VesuAdapter, currentHf: number, isDeposit: boolean) {
538
- // const {
539
- // collateralTokenAmount,
540
- // collateralUSDAmount,
541
- // collateralPrice,
542
- // debtTokenAmount,
543
- // debtUSDAmount,
544
- // debtPrice,
545
- // ltv
546
- // } = await vesuAdapter.getAssetPrices();
547
-
548
- // // debt is zero, nothing to rebalance
549
- // if(debtTokenAmount.isZero()) {
550
- // return Web3Number.fromWei(0, 0);
551
- // }
552
-
553
- // assert(collateralPrice > 0 && debtPrice > 0, "getRebalanceAmount: Invalid price");
554
-
555
- // // avoid calculating for too close
556
- // const targetHF = this.metadata.additionalInfo.targetHealthFactor;
557
- // if (currentHf > targetHF - 0.01)
558
- // throw new Error("getLegRebalanceAmount: Current health factor is healthy");
559
-
560
- // if (isDeposit) {
561
- // // TargetHF = (collAmount + newAmount) * price * ltv / debtUSD
562
- // const newAmount = targetHF * debtUSDAmount / (collateralPrice * ltv) - collateralTokenAmount.toNumber();
563
- // logger.verbose(`${this.getTag()}:: getLegRebalanceAmount: addCollateral, currentHf: ${currentHf}, targetHF: ${targetHF}, collAmount: ${collateralTokenAmount.toString()}, collUSD: ${collateralUSDAmount}, collPrice: ${collateralPrice}, debtAmount: ${debtTokenAmount.toString()}, debtUSD: ${debtUSDAmount}, debtPrice: ${debtPrice}, ltv: ${ltv}, newAmount: ${newAmount}`);
564
- // return new Web3Number(newAmount.toFixed(8), collateralTokenAmount.decimals);
565
- // } else {
566
- // // TargetHF = collUSD * ltv / (debtAmount - newAmount) * debtPrice
567
- // const newAmount = debtTokenAmount.toNumber() - collateralUSDAmount * ltv / (targetHF * debtPrice);
568
- // logger.verbose(`${this.getTag()}:: getLegRebalanceAmount: repayDebt, currentHf: ${currentHf}, targetHF: ${targetHF}, collAmount: ${collateralTokenAmount.toString()}, collUSD: ${collateralUSDAmount}, collPrice: ${collateralPrice}, debtAmount: ${debtTokenAmount.toString()}, debtUSD: ${debtUSDAmount}, debtPrice: ${debtPrice}, ltv: ${ltv}, newAmount: ${newAmount}`);
569
- // return new Web3Number(newAmount.toFixed(8), debtTokenAmount.decimals);
570
- // }
571
- // }
572
-
573
- // async getVesuModifyPositionCall(params: {
574
- // isDeposit: boolean,
575
- // leg1DepositAmount: Web3Number
576
- // }) {
577
- // const [vesuAdapter1, vesuAdapter2] = this.getVesuAdapters();
578
- // const leg1LTV = await vesuAdapter1.getLTVConfig(this.config);
579
- // const leg2LTV = await vesuAdapter2.getLTVConfig(this.config);
580
- // logger.verbose(`${this.getTag()}: LTVLeg1: ${leg1LTV}`);
581
- // logger.verbose(`${this.getTag()}: LTVLeg2: ${leg2LTV}`);
582
-
583
- // const token1Price = await this.pricer.getPrice(vesuAdapter1.config.collateral.symbol);
584
- // const token2Price = await this.pricer.getPrice(vesuAdapter2.config.collateral.symbol);
585
- // logger.verbose(`${this.getTag()}: Price${vesuAdapter1.config.collateral.symbol}: ${token1Price.price}`);
586
- // logger.verbose(`${this.getTag()}: Price${vesuAdapter2.config.collateral.symbol}: ${token2Price.price}`);
587
-
588
- // const TARGET_HF = this.metadata.additionalInfo.targetHealthFactor;
589
-
590
- // const k1 = token1Price.price * leg1LTV / token2Price.price / TARGET_HF;
591
- // const k2 = token1Price.price * TARGET_HF / token2Price.price / leg2LTV;
592
-
593
- // const borrow2Amount = new Web3Number(
594
- // params.leg1DepositAmount.multipliedBy(k1.toFixed(6)).dividedBy(k2 - k1).toFixed(6),
595
- // vesuAdapter2.config.debt.decimals
596
- // );
597
- // const borrow1Amount = new Web3Number(
598
- // borrow2Amount.multipliedBy(k2).toFixed(6),
599
- // vesuAdapter1.config.debt.decimals
600
- // );
601
- // logger.verbose(`${this.getTag()}:: leg1DepositAmount: ${params.leg1DepositAmount.toString()} ${vesuAdapter1.config.collateral.symbol}`);
602
- // logger.verbose(`${this.getTag()}:: borrow1Amount: ${borrow1Amount.toString()} ${vesuAdapter1.config.debt.symbol}`);
603
- // logger.verbose(`${this.getTag()}:: borrow2Amount: ${borrow2Amount.toString()} ${vesuAdapter2.config.debt.symbol}`);
604
-
605
- // let callSet1 = this.getVesuModifyPositionCalls({
606
- // isLeg1: true,
607
- // isDeposit: params.isDeposit,
608
- // depositAmount: params.leg1DepositAmount.plus(borrow2Amount),
609
- // debtAmount: borrow1Amount
610
- // });
611
-
612
- // let callSet2 = this.getVesuModifyPositionCalls({
613
- // isLeg1: false,
614
- // isDeposit: params.isDeposit,
615
- // depositAmount: borrow1Amount,
616
- // debtAmount: borrow2Amount
617
- // });
618
-
619
- // if (!params.isDeposit) {
620
- // let temp = callSet2;
621
- // callSet2 = [...callSet1];
622
- // callSet1 = [...temp];
623
- // }
624
- // const allActions = [...callSet1.map(i => i.manageCall), ...callSet2.map(i => i.manageCall)];
625
- // const flashloanCalldata = CallData.compile([
626
- // [...callSet1.map(i => i.proofs), ...callSet2.map(i => i.proofs)],
627
- // allActions.map(i => i.sanitizer.address),
628
- // allActions.map(i => i.call.contractAddress.address),
629
- // allActions.map(i => i.call.selector),
630
- // allActions.map(i => i.call.calldata)
631
- // ])
632
-
633
- // // flash loan
634
- // const STEP1_ID = UNIVERSAL_MANAGE_IDS.FLASH_LOAN;
635
- // const manage1Info = this.getProofs<FlashloanCallParams>(STEP1_ID);
636
- // const manageCall1 = manage1Info.callConstructor({
637
- // amount: borrow2Amount,
638
- // data: flashloanCalldata.map(i => BigInt(i))
639
- // })
640
- // const manageCall = this.getManageCall([UNIVERSAL_MANAGE_IDS.FLASH_LOAN], [manageCall1]);
641
- // return manageCall;
642
- // }
643
-
644
- // async getBringLiquidityCall(params: {
645
- // amount: Web3Number
646
- // }) {
647
- // const manage1Info = this.getProofs<ApproveCallParams>(UNIVERSAL_MANAGE_IDS.APPROVE_BRING_LIQUIDITY);
648
- // const manageCall1 = manage1Info.callConstructor({
649
- // amount: params.amount
650
- // });
651
- // const manage2Info = this.getProofs<ApproveCallParams>(UNIVERSAL_MANAGE_IDS.BRING_LIQUIDITY);
652
- // const manageCall2 = manage2Info.callConstructor({
653
- // amount: params.amount
654
- // });
655
- // const manageCall = this.getManageCall([UNIVERSAL_MANAGE_IDS.APPROVE_BRING_LIQUIDITY, UNIVERSAL_MANAGE_IDS.BRING_LIQUIDITY], [manageCall1, manageCall2]);
656
- // return manageCall;
657
- // }
658
-
659
- // async getHarvestCall() {
660
- // const vesuHarvest = new VesuHarvests(this.config);
661
- // const harvestInfo = await vesuHarvest.getUnHarvestedRewards(this.metadata.additionalInfo.vaultAllocator);
662
- // if (harvestInfo.length != 1) {
663
- // throw new Error(`Expected 1 harvest info, got ${harvestInfo.length}`);
664
- // }
665
-
666
- // const amount = harvestInfo[0].claim.amount;
667
- // const actualReward = harvestInfo[0].actualReward;
668
- // const proofs = harvestInfo[0].proof;
669
- // if (actualReward.isZero()) {
670
- // throw new Error(`Expected non-zero actual reward, got ${harvestInfo[0].actualReward}`);
671
- // }
672
-
673
- // const manage1Info = this.getProofs<VesuDefiSpringRewardsCallParams>(UNIVERSAL_MANAGE_IDS.DEFISPRING_REWARDS);
674
- // const manageCall1 = manage1Info.callConstructor({
675
- // amount,
676
- // proofs
677
- // });
678
- // const proofIds: string[] = [UNIVERSAL_MANAGE_IDS.DEFISPRING_REWARDS];
679
- // const manageCalls: ManageCall[] = [manageCall1];
680
-
681
- // // swap rewards for underlying
682
- // const STRK = Global.getDefaultTokens().find(t => t.symbol === 'STRK')!;
683
- // if (this.asset().symbol != 'STRK') {
684
- // // approve
685
- // const manage2Info = this.getProofs<ApproveCallParams>(UNIVERSAL_MANAGE_IDS.APPROVE_SWAP_TOKEN1);
686
- // const manageCall2 = manage2Info.callConstructor({
687
- // amount: actualReward
688
- // });
689
-
690
- // // swap
691
- // const avnuModule = new AvnuWrapper();
692
- // const quote = await avnuModule.getQuotes(
693
- // STRK.address.address,
694
- // this.asset().address.address,
695
- // actualReward.toWei(),
696
- // this.address.address
697
- // );
698
- // const swapInfo = await avnuModule.getSwapInfo(quote, this.address.address, 0, this.address.address);
699
- // const manage3Info = this.getProofs<AvnuSwapCallParams>(UNIVERSAL_MANAGE_IDS.AVNU_SWAP_REWARDS);
700
- // const manageCall3 = manage3Info.callConstructor({
701
- // props: swapInfo
702
- // });
703
- // proofIds.push(UNIVERSAL_MANAGE_IDS.APPROVE_SWAP_TOKEN1);
704
- // proofIds.push(UNIVERSAL_MANAGE_IDS.AVNU_SWAP_REWARDS);
705
-
706
- // manageCalls.push(manageCall2);
707
- // manageCalls.push(manageCall3);
708
- // }
709
-
710
- // const manageCall = this.getManageCall(proofIds, manageCalls);
711
- // return { call: manageCall, reward: actualReward, tokenInfo: STRK };
712
- // }
713
-
714
- // async getRebalanceCall(params: {
715
- // isLeg1toLeg2: boolean,
716
- // amount: Web3Number
717
- // }) {
718
- // let callSet1 = this.getVesuModifyPositionCalls({
719
- // isLeg1: true,
720
- // isDeposit: params.isLeg1toLeg2,
721
- // depositAmount: Web3Number.fromWei(0, 0),
722
- // debtAmount: params.amount
723
- // });
724
-
725
- // let callSet2 = this.getVesuModifyPositionCalls({
726
- // isLeg1: false,
727
- // isDeposit: params.isLeg1toLeg2,
728
- // depositAmount: params.amount,
729
- // debtAmount: Web3Number.fromWei(0, 0)
730
- // });
731
-
732
- // if (params.isLeg1toLeg2) {
733
- // const manageCall = this.getManageCall([
734
- // ...callSet1.map(i => i.step), ...callSet2.map(i => i.step)
735
- // ], [...callSet1.map(i => i.manageCall), ...callSet2.map(i => i.manageCall)]);
736
- // return manageCall;
737
- // } else {
738
- // const manageCall = this.getManageCall([
739
- // ...callSet2.map(i => i.step), ...callSet1.map(i => i.step)
740
- // ], [...callSet2.map(i => i.manageCall), ...callSet1.map(i => i.manageCall)]);
741
- // return manageCall;
742
- // }
743
- // }
744
- // }
745
-
746
-
747
- // useful to map readble names to proofs and calls
748
- export enum UNIVERSAL_MANAGE_IDS {
749
- FLASH_LOAN = 'flash_loan_init',
750
- VESU_LEG1 = 'vesu_leg1',
751
- VESU_LEG2 = 'vesu_leg2',
752
- APPROVE_TOKEN1 = 'approve_token1',
753
- APPROVE_TOKEN2 = 'approve_token2',
754
- APPROVE_BRING_LIQUIDITY = 'approve_bring_liquidity',
755
- BRING_LIQUIDITY = 'bring_liquidity',
756
-
757
- // defi spring claim
758
- DEFISPRING_REWARDS = 'defispring_rewards',
759
-
760
- // avnu swaps
761
- APPROVE_SWAP_TOKEN1 = 'approve_swap_token1',
762
- AVNU_SWAP_REWARDS = 'avnu_swap_rewards'
763
- }
764
-
765
- // export enum UNIVERSAL_ADAPTERS {
766
- // COMMON = 'common_adapter',
767
- // VESU_LEG1 = 'vesu_leg1_adapter',
768
- // VESU_LEG2 = 'vesu_leg2_adapter'
769
- // }
770
-
771
- // function getLooperSettings(
772
- // token1Symbol: string,
773
- // token2Symbol: string,
774
- // vaultSettings: UniversalStrategySettings,
775
- // pool1: ContractAddr,
776
- // pool2: ContractAddr,
777
- // ) {
778
- // const USDCToken = Global.getDefaultTokens().find(token => token.symbol === token1Symbol)!;
779
- // const ETHToken = Global.getDefaultTokens().find(token => token.symbol === token2Symbol)!;
780
-
781
- // const commonAdapter = new CommonAdapter({
782
- // manager: vaultSettings.manager,
783
- // asset: USDCToken.address,
784
- // id: UNIVERSAL_MANAGE_IDS.FLASH_LOAN,
785
- // vaultAddress: vaultSettings.vaultAddress,
786
- // vaultAllocator: vaultSettings.vaultAllocator,
787
- // })
788
- // const vesuAdapterUSDCETH = new VesuAdapter({
789
- // poolId: pool1,
790
- // collateral: USDCToken,
791
- // debt: ETHToken,
792
- // vaultAllocator: vaultSettings.vaultAllocator,
793
- // id: UNIVERSAL_MANAGE_IDS.VESU_LEG1
794
- // })
795
- // const vesuAdapterETHUSDC = new VesuAdapter({
796
- // poolId: pool2,
797
- // collateral: ETHToken,
798
- // debt: USDCToken,
799
- // vaultAllocator: vaultSettings.vaultAllocator,
800
- // id: UNIVERSAL_MANAGE_IDS.VESU_LEG2
801
- // })
802
- // vaultSettings.adapters.push(...[{
803
- // id: UNIVERSAL_ADAPTERS.COMMON,
804
- // adapter: commonAdapter
805
- // }, {
806
- // id: UNIVERSAL_ADAPTERS.VESU_LEG1,
807
- // adapter: vesuAdapterUSDCETH
808
- // }, {
809
- // id: UNIVERSAL_ADAPTERS.VESU_LEG2,
810
- // adapter: vesuAdapterETHUSDC
811
- // }])
812
-
813
- // // vesu looping
814
- // vaultSettings.leafAdapters.push(commonAdapter.getFlashloanAdapter.bind(commonAdapter));
815
- // vaultSettings.leafAdapters.push(vesuAdapterUSDCETH.getModifyPosition.bind(vesuAdapterUSDCETH));
816
- // vaultSettings.leafAdapters.push(vesuAdapterETHUSDC.getModifyPosition.bind(vesuAdapterETHUSDC));
817
- // vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(USDCToken.address, VESU_SINGLETON, UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN1).bind(commonAdapter));
818
- // vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(ETHToken.address, VESU_SINGLETON, UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN2).bind(commonAdapter));
819
-
820
- // // to bridge liquidity back to vault (used by bring_liquidity)
821
- // vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(USDCToken.address, vaultSettings.vaultAddress, UNIVERSAL_MANAGE_IDS.APPROVE_BRING_LIQUIDITY).bind(commonAdapter));
822
- // vaultSettings.leafAdapters.push(commonAdapter.getBringLiquidityAdapter(UNIVERSAL_MANAGE_IDS.BRING_LIQUIDITY).bind(commonAdapter));
823
-
824
- // // claim rewards
825
- // vaultSettings.leafAdapters.push(vesuAdapterUSDCETH.getDefispringRewardsAdapter(UNIVERSAL_MANAGE_IDS.DEFISPRING_REWARDS).bind(vesuAdapterUSDCETH));
826
-
827
- // // avnu swap
828
- // const STRKToken = Global.getDefaultTokens().find(token => token.symbol === 'STRK')!;
829
- // vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(STRKToken.address, AVNU_MIDDLEWARE, UNIVERSAL_MANAGE_IDS.APPROVE_SWAP_TOKEN1).bind(commonAdapter));
830
- // vaultSettings.leafAdapters.push(commonAdapter.getAvnuAdapter(STRKToken.address, USDCToken.address, UNIVERSAL_MANAGE_IDS.AVNU_SWAP_REWARDS, true).bind(commonAdapter));
831
- // return vaultSettings;
832
- // }
833
-
834
- // const _riskFactor: RiskFactor[] = [
835
- // { type: RiskType.SMART_CONTRACT_RISK, value: 0.5, weight: 25, reason: "Audited by Zellic" },
836
- // { type: RiskType.LIQUIDATION_RISK, value: 1.5, weight: 50, reason: "Liquidation risk is mitigated by stable price feed on Starknet" },
837
- // { type: RiskType.TECHNICAL_RISK, value: 1, weight: 50, reason: "Technical failures like risk monitoring failures" }
838
- // ];
839
-
840
- // const usdcVaultSettings: UniversalStrategySettings = {
841
- // vaultAddress: ContractAddr.from('0x7e6498cf6a1bfc7e6fc89f1831865e2dacb9756def4ec4b031a9138788a3b5e'),
842
- // manager: ContractAddr.from('0xf41a2b1f498a7f9629db0b8519259e66e964260a23d20003f3e42bb1997a07'),
843
- // vaultAllocator: ContractAddr.from('0x228cca1005d3f2b55cbaba27cb291dacf1b9a92d1d6b1638195fbd3d0c1e3ba'),
844
- // redeemRequestNFT: ContractAddr.from('0x906d03590010868cbf7590ad47043959d7af8e782089a605d9b22567b64fda'),
845
- // aumOracle: ContractAddr.from("0x6faf45ed185dec13ef723c9ead4266cab98d06f2cb237e331b1fa5c2aa79afe"),
846
- // leafAdapters: [],
847
- // adapters: [],
848
- // targetHealthFactor: 1.3,
849
- // minHealthFactor: 1.25
850
- // }
851
-
852
- // const wbtcVaultSettings: UniversalStrategySettings = {
853
- // vaultAddress: ContractAddr.from('0x5a4c1651b913aa2ea7afd9024911603152a19058624c3e425405370d62bf80c'),
854
- // manager: ContractAddr.from('0xef8a664ffcfe46a6af550766d27c28937bf1b77fb4ab54d8553e92bca5ba34'),
855
- // vaultAllocator: ContractAddr.from('0x1e01c25f0d9494570226ad28a7fa856c0640505e809c366a9fab4903320e735'),
856
- // redeemRequestNFT: ContractAddr.from('0x4fec59a12f8424281c1e65a80b5de51b4e754625c60cddfcd00d46941ec37b2'),
857
- // aumOracle: ContractAddr.from("0x2edf4edbed3f839e7f07dcd913e92299898ff4cf0ba532f8c572c66c5b331b2"),
858
- // leafAdapters: [],
859
- // adapters: [],
860
- // targetHealthFactor: 1.3,
861
- // minHealthFactor: 1.25
862
- // }
863
-
864
- // const ethVaultSettings: UniversalStrategySettings = {
865
- // vaultAddress: ContractAddr.from('0x446c22d4d3f5cb52b4950ba832ba1df99464c6673a37c092b1d9622650dbd8'),
866
- // manager: ContractAddr.from('0x494888b37206616bd09d759dcda61e5118470b9aa7f58fb84f21c778a7b8f97'),
867
- // vaultAllocator: ContractAddr.from('0x4acc0ad6bea58cb578d60ff7c31f06f44369a7a9a7bbfffe4701f143e427bd'),
868
- // redeemRequestNFT: ContractAddr.from('0x2e6cd71e5060a254d4db00655e420db7bf89da7755bb0d5f922e2f00c76ac49'),
869
- // aumOracle: ContractAddr.from("0x4b747f2e75c057bed9aa2ce46fbdc2159dc684c15bd32d4f95983a6ecf39a05"),
870
- // leafAdapters: [],
871
- // adapters: [],
872
- // targetHealthFactor: 1.3,
873
- // minHealthFactor: 1.25
874
- // }
875
-
876
- // const strkVaultSettings: UniversalStrategySettings = {
877
- // vaultAddress: ContractAddr.from('0x55d012f57e58c96e0a5c7ebbe55853989d01e6538b15a95e7178aca4af05c21'),
878
- // manager: ContractAddr.from('0xcc6a5153ca56293405506eb20826a379d982cd738008ef7e808454d318fb81'),
879
- // vaultAllocator: ContractAddr.from('0xf29d2f82e896c0ed74c9eff220af34ac148e8b99846d1ace9fbb02c9191d01'),
880
- // redeemRequestNFT: ContractAddr.from('0x46902423bd632c428376b84fcee9cac5dbe016214e93a8103bcbde6e1de656b'),
881
- // aumOracle: ContractAddr.from("0x6d7dbfad4bb51715da211468389a623da00c0625f8f6efbea822ee5ac5231f4"),
882
- // leafAdapters: [],
883
- // adapters: [],
884
- // targetHealthFactor: 1.3,
885
- // minHealthFactor: 1.25
886
- // }
887
-
888
- // const usdtVaultSettings: UniversalStrategySettings = {
889
- // vaultAddress: ContractAddr.from('0x1c4933d1880c6778585e597154eaca7b428579d72f3aae425ad2e4d26c6bb3'),
890
- // manager: ContractAddr.from('0x39bb9843503799b552b7ed84b31c06e4ff10c0537edcddfbf01fe944b864029'),
891
- // vaultAllocator: ContractAddr.from('0x56437d18c43727ac971f6c7086031cad7d9d6ccb340f4f3785a74cc791c931a'),
892
- // redeemRequestNFT: ContractAddr.from('0x5af0c2a657eaa8e23ed78e855dac0c51e4f69e2cf91a18c472041a1f75bb41f'),
893
- // aumOracle: ContractAddr.from("0x7018f8040c8066a4ab929e6760ae52dd43b6a3a289172f514750a61fcc565cc"),
894
- // leafAdapters: [],
895
- // adapters: [],
896
- // targetHealthFactor: 1.3,
897
- // minHealthFactor: 1.25
898
- // }
899
-
900
- // type AllowedSources = 'vesu' | 'endur' | 'extended';
901
- // export default function MetaVaultDescription(allowedSources: AllowedSources[]) {
902
- // const logos: any = {
903
- // vesu: Protocols.VESU.logo,
904
- // endur: Protocols.ENDUR.logo,
905
- // extended: Protocols.EXTENDED.logo,
906
- // ekubo: "https://dummyimage.com/64x64/ffffff/000000&text=K",
907
- // };
908
- // const _sources = [
909
- // { key: "vesu", name: "Vesu", status: "Live", description: "Integrated liquidity venue used for automated routing to capture the best available yield." },
910
- // { key: "endur", name: "Endur", status: "Coming soon", description: "Planned integration to tap into STRK staking–backed yields via our LST pipeline." },
911
- // { key: "extended", name: "Extended", status: "Coming soon", description: "Expanding coverage to additional money markets and vaults across the ecosystem." },
912
- // // { key: "ekubo", name: "Ekubo", status: "Coming soon", description: "Concentrated liquidity strategies targeted for optimized fee APR harvesting." },
913
- // ];
914
- // const sources = _sources.filter(s => allowedSources.includes(s.key as any));
915
-
916
- // const containerStyle = {
917
- // maxWidth: "800px",
918
- // margin: "0 auto",
919
- // backgroundColor: "#111",
920
- // color: "#eee",
921
- // fontFamily: "Arial, sans-serif",
922
- // borderRadius: "12px",
923
- // };
924
-
925
- // const cardStyle = {
926
- // border: "1px solid #333",
927
- // borderRadius: "10px",
928
- // padding: "12px",
929
- // marginBottom: "12px",
930
- // backgroundColor: "#1a1a1a",
931
- // };
932
-
933
- // const logoStyle = {
934
- // width: "24px",
935
- // height: "24px",
936
- // borderRadius: "8px",
937
- // border: "1px solid #444",
938
- // backgroundColor: "#222",
939
- // };
940
-
941
- // return (
942
- // <div style={containerStyle}>
943
- // <h1 style={{ fontSize: "18px", marginBottom: "10px" }}>Meta Vault — Automated Yield Router</h1>
944
- // <p style={{ fontSize: "14px", lineHeight: "1.5", marginBottom: "16px" }}>
945
- // This Evergreen vault is a tokenized Meta Vault, auto-compounding strategy that continuously allocates your deposited
946
- // asset to the best available yield source in the ecosystem. Depositors receive vault shares that
947
- // represent a proportional claim on the underlying assets and accrued yield. Allocation shifts are
948
- // handled programmatically based on on-chain signals and risk filters, minimizing idle capital and
949
- // maximizing net APY.
950
- // </p>
951
-
952
- // <div style={{ backgroundColor: "#222", padding: "10px", borderRadius: "8px", marginBottom: "20px", border: "1px solid #444" }}>
953
- // <p style={{ fontSize: "13px", color: "#ccc" }}>
954
- // <strong>Withdrawals:</strong> Requests can take up to <strong>1-2 hours</strong> to process as the vault unwinds and settles routing.
955
- // </p>
956
- // </div>
957
-
958
- // <h2 style={{ fontSize: "18px", marginBottom: "10px" }}>Supported Yield Sources</h2>
959
- // {sources.map((s) => (
960
- // <div key={s.key} style={cardStyle}>
961
- // <div style={{ display: "flex", gap: "10px", alignItems: "flex-start" }}>
962
- // <img src={logos[s.key]} alt={`${s.name} logo`} style={logoStyle} />
963
- // <div style={{ flex: 1 }}>
964
- // <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
965
- // <h3 style={{ fontSize: "15px", margin: 0 }}>{s.name}</h3>
966
- // <StatusBadge status={s.status} />
967
- // </div>
968
- // {/* <p style={{ fontSize: "13px", color: "#ccc", marginTop: "4px" }}>{s.description}</p> */}
969
- // </div>
970
- // </div>
971
- // </div>
972
- // ))}
973
- // </div>
974
- // );
975
- // }
976
-
977
- // function StatusBadge({ status }: { status: string }) {
978
- // const isSoon = String(status).toLowerCase() !== "live";
979
- // const badgeStyle = {
980
- // fontSize: "12px",
981
- // padding: "2px 6px",
982
- // borderRadius: "12px",
983
- // border: "1px solid",
984
- // color: isSoon ? "rgb(196 196 195)" : "#6aff7d",
985
- // borderColor: isSoon ? "#484848" : "#6aff7d",
986
- // backgroundColor: isSoon ? "#424242" : "#002b1a",
987
- // };
988
- // return <span style={badgeStyle}>{status}</span>;
989
- // }
990
-
991
- // function getDescription(tokenSymbol: string, allowedSources: AllowedSources[]) {
992
- // return MetaVaultDescription(allowedSources);
993
- // }
994
-
995
- // function getFAQs(): FAQ[] {
996
- // return [
997
- // {
998
- // question: "What is the Meta Vault?",
999
- // answer:
1000
- // "The Meta Vault is a tokenized strategy that automatically allocates your deposited assets to the best available yield source in the ecosystem. It optimizes returns while minimizing idle capital.",
1001
- // },
1002
- // {
1003
- // question: "How does yield allocation work?",
1004
- // answer:
1005
- // "The vault continuously monitors supported protocols and routes liquidity to the source offering the highest net yield after accounting for fees, slippage, and gas costs. Reallocations are performed automatically.",
1006
- // },
1007
- // {
1008
- // question: "Which yield sources are supported?",
1009
- // answer: (
1010
- // <span>
1011
- // Currently, <strong>Vesu</strong> is live. Future integrations may include{" "}
1012
- // <strong>Endur</strong>, <strong>Extended</strong>, and{" "}
1013
- // <strong>Ekubo</strong> (all coming soon).
1014
- // </span>
1015
- // ),
1016
- // },
1017
- // {
1018
- // question: "What do I receive when I deposit?",
1019
- // answer:
1020
- // "Depositors receive vault tokens representing their proportional share of the vault. These tokens entitle holders to both the principal and accrued yield.",
1021
- // },
1022
- // {
1023
- // question: "How long do withdrawals take?",
1024
- // answer:
1025
- // "Withdrawals may take up to 1-2 hours to process, as the vault unwinds and settles liquidity routing across integrated protocols.",
1026
- // },
1027
- // {
1028
- // question: "Is the Meta Vault non-custodial?",
1029
- // answer:
1030
- // "Yes. The Meta Vault operates entirely on-chain. Users always maintain control of their vault tokens, and the strategy is fully transparent.",
1031
- // },
1032
- // {
1033
- // question: "How is risk managed?",
1034
- // answer:
1035
- // "Integrations are supported with active risk monitoring like liquidation risk. Only vetted protocols are included to balance yield with safety. However, usual Defi risks like smart contract risk, extreme volatile market risk, etc. are still present.",
1036
- // },
1037
- // {
1038
- // question: "Are there any fees?",
1039
- // answer:
1040
- // "Troves charges a performance of 10% on the yield generated. The APY shown is net of this fee. This fee is only applied to the profits earned, ensuring that users retain their initial capital.",
1041
- // },
1042
- // ];
1043
- // }
1044
-
1045
- export function getContractDetails(settings: UniversalStrategySettings & { aumOracle?: ContractAddr }): {address: ContractAddr, name: string}[] {
1046
- const contracts = [
1047
- { address: settings.vaultAddress, name: "Vault" },
1048
- { address: settings.manager, name: "Vault Manager" },
1049
- { address: settings.vaultAllocator, name: "Vault Allocator" },
1050
- { address: settings.redeemRequestNFT, name: "Redeem Request NFT" },
1051
- ];
1052
- if (settings.aumOracle) {
1053
- contracts.push({ address: settings.aumOracle, name: "AUM Oracle" });
1054
- }
1055
- return contracts;
1056
- }
1057
-
1058
- // const investmentSteps: string[] = [
1059
- // "Deposit funds into the vault",
1060
- // "Vault manager allocates funds to optimal yield sources",
1061
- // "Vault manager reports asset under management (AUM) regularly to the vault",
1062
- // "Request withdrawal and vault manager processes it in 1-2 hours"
1063
- // ]
1064
-
1065
- // const AUDIT_URL = 'https://docs.troves.fi/p/security#starknet-vault-kit'
1066
- // export const UniversalStrategies: IStrategyMetadata<UniversalStrategySettings>[] =
1067
- // [
1068
- // {
1069
- // name: "USDC Evergreen",
1070
- // description: getDescription('USDC', ['vesu', 'extended']),
1071
- // address: ContractAddr.from('0x7e6498cf6a1bfc7e6fc89f1831865e2dacb9756def4ec4b031a9138788a3b5e'),
1072
- // launchBlock: 0,
1073
- // type: 'ERC4626',
1074
- // depositTokens: [Global.getDefaultTokens().find(token => token.symbol === 'USDC')!],
1075
- // additionalInfo: getLooperSettings('USDC', 'ETH', usdcVaultSettings, VesuPools.Genesis, VesuPools.Genesis),
1076
- // risk: {
1077
- // riskFactor: _riskFactor,
1078
- // netRisk:
1079
- // _riskFactor.reduce((acc, curr) => acc + curr.value * curr.weight, 0) /
1080
- // _riskFactor.reduce((acc, curr) => acc + curr.weight, 0),
1081
- // notARisks: getNoRiskTags(_riskFactor)
1082
- // },
1083
- // auditUrl: AUDIT_URL,
1084
- // protocols: [Protocols.VESU],
1085
- // maxTVL: Web3Number.fromWei(0, 6),
1086
- // contractDetails: getContractDetails(usdcVaultSettings),
1087
- // faqs: getFAQs(),
1088
- // investmentSteps: investmentSteps,
1089
- // },
1090
- // {
1091
- // name: "WBTC Evergreen",
1092
- // description: getDescription('WBTC', ['vesu', 'endur', 'extended']),
1093
- // address: ContractAddr.from('0x5a4c1651b913aa2ea7afd9024911603152a19058624c3e425405370d62bf80c'),
1094
- // launchBlock: 0,
1095
- // type: 'ERC4626',
1096
- // depositTokens: [Global.getDefaultTokens().find(token => token.symbol === 'WBTC')!],
1097
- // additionalInfo: getLooperSettings('WBTC', 'ETH', wbtcVaultSettings, VesuPools.Genesis, VesuPools.Genesis),
1098
- // risk: {
1099
- // riskFactor: _riskFactor,
1100
- // netRisk:
1101
- // _riskFactor.reduce((acc, curr) => acc + curr.value * curr.weight, 0) /
1102
- // _riskFactor.reduce((acc, curr) => acc + curr.weight, 0),
1103
- // notARisks: getNoRiskTags(_riskFactor)
1104
- // },
1105
- // protocols: [Protocols.VESU],
1106
- // maxTVL: Web3Number.fromWei(0, 8),
1107
- // contractDetails: getContractDetails(wbtcVaultSettings),
1108
- // faqs: getFAQs(),
1109
- // investmentSteps: investmentSteps,
1110
- // auditUrl: AUDIT_URL,
1111
- // },
1112
- // {
1113
- // name: "ETH Evergreen",
1114
- // description: getDescription('ETH', ['vesu', 'extended']),
1115
- // address: ContractAddr.from('0x446c22d4d3f5cb52b4950ba832ba1df99464c6673a37c092b1d9622650dbd8'),
1116
- // launchBlock: 0,
1117
- // type: 'ERC4626',
1118
- // depositTokens: [Global.getDefaultTokens().find(token => token.symbol === 'ETH')!],
1119
- // additionalInfo: getLooperSettings('ETH', 'WBTC', ethVaultSettings, VesuPools.Genesis, VesuPools.Genesis),
1120
- // risk: {
1121
- // riskFactor: _riskFactor,
1122
- // netRisk:
1123
- // _riskFactor.reduce((acc, curr) => acc + curr.value * curr.weight, 0) /
1124
- // _riskFactor.reduce((acc, curr) => acc + curr.weight, 0),
1125
- // notARisks: getNoRiskTags(_riskFactor)
1126
- // },
1127
- // protocols: [Protocols.VESU],
1128
- // maxTVL: Web3Number.fromWei(0, 18),
1129
- // contractDetails: getContractDetails(ethVaultSettings),
1130
- // faqs: getFAQs(),
1131
- // investmentSteps: investmentSteps,
1132
- // auditUrl: AUDIT_URL,
1133
- // },
1134
- // {
1135
- // name: "STRK Evergreen",
1136
- // description: getDescription('STRK', ['vesu', 'endur', 'extended']),
1137
- // address: ContractAddr.from('0x55d012f57e58c96e0a5c7ebbe55853989d01e6538b15a95e7178aca4af05c21'),
1138
- // launchBlock: 0,
1139
- // type: 'ERC4626',
1140
- // depositTokens: [Global.getDefaultTokens().find(token => token.symbol === 'STRK')!],
1141
- // additionalInfo: getLooperSettings('STRK', 'ETH', strkVaultSettings, VesuPools.Genesis, VesuPools.Genesis),
1142
- // risk: {
1143
- // riskFactor: _riskFactor,
1144
- // netRisk:
1145
- // _riskFactor.reduce((acc, curr) => acc + curr.value * curr.weight, 0) /
1146
- // _riskFactor.reduce((acc, curr) => acc + curr.weight, 0),
1147
- // notARisks: getNoRiskTags(_riskFactor)
1148
- // },
1149
- // protocols: [Protocols.VESU],
1150
- // maxTVL: Web3Number.fromWei(0, 18),
1151
- // contractDetails: getContractDetails(strkVaultSettings),
1152
- // faqs: getFAQs(),
1153
- // investmentSteps: investmentSteps,
1154
- // auditUrl: AUDIT_URL,
1155
- // },
1156
- // {
1157
- // name: "USDT Evergreen",
1158
- // description: getDescription('USDT', ['vesu']),
1159
- // address: ContractAddr.from('0x1c4933d1880c6778585e597154eaca7b428579d72f3aae425ad2e4d26c6bb3'),
1160
- // launchBlock: 0,
1161
- // type: 'ERC4626',
1162
- // depositTokens: [Global.getDefaultTokens().find(token => token.symbol === 'USDT')!],
1163
- // additionalInfo: getLooperSettings('USDT', 'ETH', usdtVaultSettings, VesuPools.Genesis, VesuPools.Genesis),
1164
- // risk: {
1165
- // riskFactor: _riskFactor,
1166
- // netRisk:
1167
- // _riskFactor.reduce((acc, curr) => acc + curr.value * curr.weight, 0) /
1168
- // _riskFactor.reduce((acc, curr) => acc + curr.weight, 0),
1169
- // notARisks: getNoRiskTags(_riskFactor)
1170
- // },
1171
- // protocols: [Protocols.VESU],
1172
- // maxTVL: Web3Number.fromWei(0, 6),
1173
- // contractDetails: getContractDetails(usdtVaultSettings),
1174
- // faqs: getFAQs(),
1175
- // investmentSteps: investmentSteps,
1176
- // auditUrl: AUDIT_URL,
1177
- // }
1178
- // ]
1
+ import { ContractAddr, Web3Number } from "@/dataTypes";
2
+ import { BaseStrategy, SingleActionAmount, SingleTokenInfo } from "./base-strategy";
3
+ import { PricerBase } from "@/modules/pricerBase";
4
+ import { FAQ, getNoRiskTags, IConfig, IStrategyMetadata, Protocols, RiskFactor, RiskType, StrategyTag, VaultPosition, AuditStatus, SourceCodeType, AccessControlType, InstantWithdrawalVault, StrategyLiveStatus, StrategySettings, VaultType, RedemptionInfo } from "@/interfaces";
5
+ import { BlockIdentifier, Call, CallData, Contract, num, uint256 } from "starknet";
6
+ import { VesuRebalanceSettings } from "./vesu-rebalance";
7
+ import { assert, LeafData, logger, StandardMerkleTree } from "@/utils";
8
+ import UniversalVaultAbi from '../data/universal-vault.abi.json';
9
+ import ManagerAbi from '../data/vault-manager.abi.json';
10
+ import { ApproveCallParams, AvnuSwapCallParams, BaseAdapter, CommonAdapter, DepositParams, FlashloanCallParams, GenerateCallFn, LeafAdapterFn, ManageCall, WithdrawParams } from "./universal-adapters";
11
+ import { VesuAdapter, VesuModifyPositionCallParams, VesuDefiSpringRewardsCallParams, VesuPools } from "./universal-adapters/vesu-adapter";
12
+ import { Global } from "@/global";
13
+ import { AvnuWrapper, ERC20 } from "@/modules";
14
+ import { AVNU_MIDDLEWARE, VESU_SINGLETON } from "./universal-adapters/adapter-utils";
15
+ import { LSTPriceType } from "./types";
16
+ import { HarvestInfo, VesuHarvests } from "@/modules/harvests";
17
+
18
+ export interface UniversalManageCall {
19
+ proofs: string[];
20
+ manageCall: ManageCall;
21
+ step: UNIVERSAL_MANAGE_IDS;
22
+ }
23
+
24
+ export interface UniversalStrategySettings {
25
+ vaultAddress: ContractAddr,
26
+ manager: ContractAddr,
27
+ vaultAllocator: ContractAddr,
28
+ redeemRequestNFT: ContractAddr,
29
+ aumOracle: ContractAddr,
30
+ redemptionRouter?: ContractAddr,
31
+
32
+ // Individual merkle tree leaves
33
+ leafAdapters: LeafAdapterFn<any>[],
34
+
35
+ // Useful for returning adapter class objects that can compute
36
+ // certain things for us (e.g. positions, hfs)
37
+ adapters: {id: string, adapter: BaseAdapter<DepositParams, WithdrawParams>}[]
38
+
39
+ targetHealthFactor: number,
40
+ minHealthFactor: number
41
+ }
42
+
43
+ export enum AUMTypes {
44
+ FINALISED = 'finalised',
45
+ DEFISPRING = 'defispring'
46
+ }
47
+
48
+ export enum PositionTypeAvnuExtended {
49
+ OPEN = 'open',
50
+ CLOSE = 'close'
51
+ }
52
+
53
+ export class UniversalStrategy<
54
+ S extends UniversalStrategySettings
55
+ > extends BaseStrategy<
56
+ SingleTokenInfo,
57
+ SingleActionAmount
58
+ > {
59
+
60
+ /** Contract address of the strategy */
61
+ readonly address: ContractAddr;
62
+ /** Pricer instance for token price calculations */
63
+ readonly pricer: PricerBase;
64
+ /** Metadata containing strategy information */
65
+ readonly metadata: IStrategyMetadata<S>;
66
+ /** Contract instance for interacting with the strategy */
67
+ readonly contract: Contract;
68
+ readonly managerContract: Contract;
69
+ merkleTree: StandardMerkleTree | undefined;
70
+
71
+ constructor(
72
+ config: IConfig,
73
+ pricer: PricerBase,
74
+ metadata: IStrategyMetadata<S>
75
+ ) {
76
+ super(config);
77
+ this.pricer = pricer;
78
+
79
+ assert(
80
+ metadata.depositTokens.length === 1,
81
+ "VesuRebalance only supports 1 deposit token"
82
+ );
83
+ this.metadata = metadata;
84
+ this.address = metadata.address;
85
+
86
+ this.contract = new Contract({
87
+ abi: UniversalVaultAbi,
88
+ address: this.address.address,
89
+ providerOrAccount: this.config.provider
90
+ });
91
+ this.managerContract = new Contract({
92
+ abi: ManagerAbi,
93
+ address: this.metadata.additionalInfo.manager.address,
94
+ providerOrAccount: this.config.provider
95
+ });
96
+ }
97
+
98
+ getMerkleTree() {
99
+ if (this.merkleTree) return this.merkleTree;
100
+ const leaves = this.metadata.additionalInfo.leafAdapters.map((adapter, index) => {
101
+ return adapter()
102
+ });
103
+ const standardTree = StandardMerkleTree.of(leaves.flatMap(l => l.leaves));
104
+ this.merkleTree = standardTree;
105
+ return standardTree;
106
+ }
107
+
108
+ getMerkleRoot() {
109
+ return this.getMerkleTree().root;
110
+ }
111
+
112
+ getProofs<T>(id: string): { proofs: string[], callConstructor: GenerateCallFn<T> } {
113
+ const tree = this.getMerkleTree();
114
+ let proofs: string[] = [];
115
+ for (const [i, v] of tree.entries()) {
116
+ if (v.readableId == id) {
117
+ proofs = tree.getProof(i);
118
+ }
119
+ }
120
+ if (proofs.length === 0) {
121
+ throw new Error(`Proof not found for ID: ${id}`);
122
+ }
123
+
124
+ // find leaf adapter
125
+ const leafAdapter = this.metadata.additionalInfo.leafAdapters.find(adapter => adapter().leaves[0]?.readableId === id);
126
+ if (!leafAdapter) {
127
+ throw new Error(`Leaf adapter not found for ID: ${id}`);
128
+ }
129
+ const leafInfo = leafAdapter();
130
+ return {
131
+ proofs,
132
+ callConstructor: leafInfo.callConstructor.bind(leafInfo),
133
+ };
134
+ }
135
+
136
+ getAdapter(id: string): BaseAdapter<any, any> {
137
+ const adapter = this.metadata.additionalInfo.adapters.find(adapter => adapter.id === id);
138
+ if (!adapter) {
139
+ throw new Error(`Adapter not found for ID: ${id}`);
140
+ }
141
+ return adapter.adapter;
142
+ }
143
+
144
+ asset() {
145
+ return this.metadata.depositTokens[0];
146
+ }
147
+
148
+ async depositCall(amountInfo: SingleActionAmount, receiver: ContractAddr): Promise<Call[]> {
149
+ // Technically its not erc4626 abi, but we just need approve call
150
+ // so, its ok to use it
151
+ assert(
152
+ amountInfo.tokenInfo.address.eq(this.asset().address),
153
+ "Deposit token mismatch"
154
+ );
155
+ const assetContract = new Contract({
156
+ abi: UniversalVaultAbi,
157
+ address: this.asset().address.address,
158
+ providerOrAccount: this.config.provider
159
+ });
160
+ const call1 = assetContract.populate("approve", [
161
+ this.address.address,
162
+ uint256.bnToUint256(amountInfo.amount.toWei())
163
+ ]);
164
+ const call2 = this.contract.populate("deposit", [
165
+ uint256.bnToUint256(amountInfo.amount.toWei()),
166
+ receiver.address
167
+ ]);
168
+ return [call1, call2];
169
+ }
170
+
171
+ async withdrawCall(amountInfo: SingleActionAmount, receiver: ContractAddr, owner: ContractAddr): Promise<Call[]> {
172
+ assert(
173
+ amountInfo.tokenInfo.address.eq(this.asset().address),
174
+ "Withdraw token mismatch"
175
+ );
176
+ const shares = await this.contract.call('convert_to_shares', [uint256.bnToUint256(amountInfo.amount.toWei())]);
177
+ const call = this.contract.populate("request_redeem", [
178
+ uint256.bnToUint256(shares.toString()),
179
+ receiver.address,
180
+ owner.address
181
+ ]);
182
+ return [call];
183
+ }
184
+
185
+ async getUserTVL(user: ContractAddr, blockIdentifier: BlockIdentifier = "latest") {
186
+ const shares: any = await this.contract.call("balanceOf", [user.address], { blockIdentifier });
187
+ const assets: any = await this.contract.call(
188
+ "convert_to_assets",
189
+ [uint256.bnToUint256(shares)],
190
+ { blockIdentifier }
191
+ );
192
+ const amount = Web3Number.fromWei(
193
+ assets.toString(),
194
+ this.metadata.depositTokens[0].decimals
195
+ );
196
+
197
+ // Convert blockIdentifier to block number for pricer if it's a number
198
+ const blockNumber = typeof blockIdentifier === 'number' || typeof blockIdentifier === 'bigint'
199
+ ? Number(blockIdentifier)
200
+ : undefined;
201
+
202
+ let price = await this.pricer.getPrice(
203
+ this.metadata.depositTokens[0].symbol,
204
+ blockNumber
205
+ );
206
+ const usdValue = Number(amount.toFixed(6)) * price.price;
207
+ return {
208
+ tokenInfo: this.asset(),
209
+ amount,
210
+ usdValue
211
+ };
212
+ }
213
+
214
+ async getVesuAPYs() {
215
+ // get Vesu pools, positions and APYs
216
+ const vesuAdapters = this.getVesuAdapters();
217
+ const allVesuPools = await VesuAdapter.getVesuPools();
218
+ const pools = vesuAdapters.map((vesuAdapter) => {
219
+ return allVesuPools.pools.find(p => vesuAdapter.config.poolId.eqString(num.getHexString(p.id)));
220
+ });
221
+ logger.verbose(`${this.metadata.name}::netAPY: vesu-pools: ${JSON.stringify(pools)}`);
222
+ if (pools.some(p => !p)) {
223
+ throw new Error('Pool not found');
224
+ };
225
+ const positions = await this.getVesuPositions();
226
+ logger.verbose(`${this.metadata.name}::netAPY: positions: ${JSON.stringify(positions)}`);
227
+ const baseAPYs: number[] = [];
228
+ const rewardAPYs: number[] = [];
229
+
230
+
231
+ for (const [index, pool] of pools.entries()) {
232
+ const vesuAdapter = vesuAdapters[index];
233
+ const collateralAsset = pool.assets.find((a: any) => a.symbol.toLowerCase() === vesuAdapter.config.collateral.symbol.toLowerCase())?.stats!;
234
+ const debtAsset = pool.assets.find((a: any) => a.symbol.toLowerCase() === vesuAdapter.config.debt.symbol.toLowerCase())?.stats!;
235
+ const supplyApy = Number(collateralAsset.supplyApy.value || 0) / 1e18;
236
+
237
+ // Use LST APR from Endur API instead of Vesu's lstApr
238
+ const lstAPY = await this.getLSTAPR(vesuAdapter.config.collateral.address);
239
+ logger.verbose(`${this.metadata.name}::netAPY: ${vesuAdapter.config.collateral.symbol} LST APR from Endur: ${lstAPY}`);
240
+
241
+ baseAPYs.push(...[supplyApy + lstAPY, Number(debtAsset.borrowApr.value) / 1e18]);
242
+ rewardAPYs.push(...[Number(collateralAsset.defiSpringSupplyApr?.value || "0") / 1e18, 0]);
243
+ }
244
+ logger.verbose(`${this.metadata.name}::netAPY: baseAPYs: ${JSON.stringify(baseAPYs)}`);
245
+ logger.verbose(`${this.metadata.name}::netAPY: rewardAPYs: ${JSON.stringify(rewardAPYs)}`);
246
+
247
+ // Else further compute will fail
248
+ assert(baseAPYs.length == positions.length, 'APYs and positions length mismatch');
249
+
250
+ return {
251
+ baseAPYs,
252
+ rewardAPYs,
253
+ positions
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Calculates the weighted average APY across all pools based on USD value.
259
+ * @returns {Promise<number>} The weighted average APY across all pools
260
+ */
261
+ async netAPY(): Promise<{ net: number, splits: { apy: number, id: string }[] }> {
262
+ if (this.metadata.isPreview) {
263
+ return { net: 0, splits: [{
264
+ apy: 0, id: 'base'
265
+ }, {
266
+ apy: 0, id: 'defispring'
267
+ }] };
268
+ }
269
+
270
+ const { positions, baseAPYs, rewardAPYs } = await this.getVesuAPYs();
271
+
272
+ const unusedBalanceAPY = await this.getUnusedBalanceAPY();
273
+ baseAPYs.push(...[unusedBalanceAPY.apy]);
274
+ rewardAPYs.push(0);
275
+
276
+ // Compute APy using weights
277
+ const weights = positions.map((p, index) => p.usdValue * (index % 2 == 0 ? 1 : -1));
278
+ weights.push(unusedBalanceAPY.weight);
279
+
280
+ const prevAUM = await this.getPrevAUM();
281
+ const price = await this.pricer.getPrice(this.metadata.depositTokens[0].symbol);
282
+ const prevAUMUSD = prevAUM.multipliedBy(price.price);
283
+ return this.returnNetAPY(baseAPYs, rewardAPYs, weights, prevAUMUSD);
284
+ }
285
+
286
+ protected async returnNetAPY(baseAPYs: number[], rewardAPYs: number[], weights: number[], prevAUMUSD: Web3Number) {
287
+ // If no positions, return 0
288
+ if (weights.every(p => p == 0)) {
289
+ return { net: 0, splits: [{
290
+ apy: 0, id: 'base'
291
+ }, {
292
+ apy: 0, id: 'defispring'
293
+ }]};
294
+ }
295
+
296
+ const baseAPY = this.computeAPY(baseAPYs, weights, prevAUMUSD);
297
+ const rewardAPY = this.computeAPY(rewardAPYs, weights, prevAUMUSD);
298
+ const netAPY = baseAPY + rewardAPY;
299
+ logger.verbose(`${this.metadata.name}::netAPY: net: ${netAPY}, baseAPY: ${baseAPY}, rewardAPY: ${rewardAPY}`);
300
+ return { net: netAPY, splits: [{
301
+ apy: baseAPY, id: 'base'
302
+ }, {
303
+ apy: rewardAPY, id: 'defispring'
304
+ }] };
305
+ }
306
+
307
+ protected async getUnusedBalanceAPY() {
308
+ return {
309
+ apy: 0, weight: 0
310
+ }
311
+ }
312
+
313
+ private computeAPY(apys: number[], weights: number[], currentAUM: Web3Number) {
314
+ assert(apys.length === weights.length, "APYs and weights length mismatch");
315
+ const weightedSum = apys.reduce((acc, apy, i) => acc + apy * weights[i], 0);
316
+ logger.verbose(`${this.getTag()} computeAPY: apys: ${JSON.stringify(apys)}, weights: ${JSON.stringify(weights)}, weightedSum: ${weightedSum}, currentAUM: ${currentAUM}`);
317
+ return weightedSum / currentAUM.toNumber();
318
+ }
319
+
320
+ /**
321
+ * Calculates user realized APY based on trueSharesBasedAPY method.
322
+ * Returns the APY as a number.
323
+ */
324
+ async getUserRealizedAPY(
325
+ blockIdentifier: BlockIdentifier = "latest",
326
+ sinceBlocks = 600000
327
+ ): Promise<number> {
328
+ logger.verbose(
329
+ `${this.getTag()}: getUserRealizedAPY => starting with blockIdentifier=${blockIdentifier}, sinceBlocks=${sinceBlocks}`
330
+ );
331
+
332
+ // Determine current block number and timestamp
333
+ let blockNow =
334
+ typeof blockIdentifier === "number" || typeof blockIdentifier === "bigint"
335
+ ? Number(blockIdentifier)
336
+ : (await this.config.provider.getBlockLatestAccepted()).block_number;
337
+ const blockNowTime =
338
+ typeof blockIdentifier === "number" || typeof blockIdentifier === "bigint"
339
+ ? (await this.config.provider.getBlockWithTxs(blockIdentifier)).timestamp
340
+ : new Date().getTime() / 1000;
341
+
342
+ // Look back window, but never before launch block
343
+ const blockBefore = Math.max(
344
+ blockNow - sinceBlocks,
345
+ this.metadata.launchBlock
346
+ );
347
+
348
+ // TVL amounts (in underlying token units) and supply at current reference block
349
+ const assetsNowRaw: bigint = await this.contract.call("total_assets", [], {
350
+ blockIdentifier,
351
+ }) as bigint;
352
+ const amountNow = Web3Number.fromWei(
353
+ assetsNowRaw.toString(),
354
+ this.metadata.depositTokens[0].decimals
355
+ );
356
+
357
+ const supplyNowRaw: bigint = await this.contract.call("total_supply", [], {
358
+ blockIdentifier,
359
+ }) as bigint;
360
+ const supplyNow = Web3Number.fromWei(supplyNowRaw.toString(), 18);
361
+
362
+ // Historical TVL and supply
363
+ const assetsBeforeRaw: bigint = await this.contract.call(
364
+ "total_assets",
365
+ [],
366
+ { blockIdentifier: blockBefore }
367
+ ) as bigint;
368
+ const amountBefore = Web3Number.fromWei(
369
+ assetsBeforeRaw.toString(),
370
+ this.metadata.depositTokens[0].decimals
371
+ );
372
+
373
+ const supplyBeforeRaw: bigint = await this.contract.call(
374
+ "total_supply",
375
+ [],
376
+ { blockIdentifier: blockBefore }
377
+ ) as bigint;
378
+ const supplyBefore = Web3Number.fromWei(supplyBeforeRaw.toString(), 18);
379
+
380
+ const blockBeforeInfo = await this.config.provider.getBlockWithTxs(
381
+ blockBefore
382
+ );
383
+
384
+ // Calculate assets per share
385
+ const assetsPerShareNow = amountNow
386
+ .multipliedBy(1e18)
387
+ .dividedBy(supplyNow.toString());
388
+
389
+ const assetsPerShareBf = amountBefore
390
+ .multipliedBy(1e18)
391
+ .dividedBy(supplyBefore.toString());
392
+
393
+ const timeDiffSeconds = blockNowTime - blockBeforeInfo.timestamp;
394
+
395
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] assetsNow: ${amountNow.toString()}`);
396
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] assetsBefore: ${amountBefore.toString()}`);
397
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] assetsPerShareNow: ${assetsPerShareNow.toString()}`);
398
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] assetsPerShareBf: ${assetsPerShareBf.toString()}`);
399
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] Supply before: ${supplyBefore.toString()}`);
400
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] Supply now: ${supplyNow.toString()}`);
401
+ logger.verbose(`${this.getTag()} [getUserRealizedAPY] Time diff in seconds: ${timeDiffSeconds}`);
402
+
403
+ const apyForGivenBlocks =
404
+ Number(
405
+ assetsPerShareNow
406
+ .minus(assetsPerShareBf)
407
+ .multipliedBy(10000)
408
+ .dividedBy(assetsPerShareBf)
409
+ ) / 10000;
410
+
411
+ return (apyForGivenBlocks * (365 * 24 * 3600)) / timeDiffSeconds;
412
+ }
413
+
414
+ /**
415
+ * Calculates the total TVL of the strategy.
416
+ * @returns Object containing the total amount in token units and USD value
417
+ */
418
+ async getTVL() {
419
+ const assets = await this.contract.total_assets();
420
+ const amount = Web3Number.fromWei(
421
+ assets.toString(),
422
+ this.metadata.depositTokens[0].decimals
423
+ );
424
+ let price = await this.pricer.getPrice(
425
+ this.metadata.depositTokens[0].symbol
426
+ );
427
+ const usdValue = Number(amount.toFixed(6)) * price.price;
428
+ return {
429
+ tokenInfo: this.asset(),
430
+ amount,
431
+ usdValue
432
+ };
433
+ }
434
+
435
+ async getUnusedBalance(): Promise<SingleTokenInfo> {
436
+ const balance = await (new ERC20(this.config)).balanceOf(this.asset().address, this.metadata.additionalInfo.vaultAllocator, this.asset().decimals);
437
+ const price = await this.pricer.getPrice(this.metadata.depositTokens[0].symbol);
438
+ const usdValue = Number(balance.toFixed(6)) * price.price;
439
+ return {
440
+ tokenInfo: this.asset(),
441
+ amount: balance,
442
+ usdValue
443
+ };
444
+ }
445
+
446
+ protected async getVesuAUM(adapter: VesuAdapter, _priceType?: LSTPriceType) {
447
+ const legAUM = await adapter.getPositions(this.config);
448
+ const underlying = this.asset();
449
+ let vesuAum = Web3Number.fromWei("0", underlying.decimals);
450
+
451
+ let tokenUnderlyingPrice = await this.pricer.getPrice(this.asset().symbol);
452
+ logger.verbose(`${this.getTag()} tokenUnderlyingPrice: ${tokenUnderlyingPrice.price}`);
453
+
454
+ // handle collateral
455
+ if (legAUM[0].token.address.eq(underlying.address)) {
456
+ vesuAum = vesuAum.plus(legAUM[0].amount);
457
+ } else {
458
+ vesuAum = vesuAum.plus(legAUM[0].usdValue / tokenUnderlyingPrice.price);
459
+ }
460
+
461
+ // handle debt
462
+ if (legAUM[1].token.address.eq(underlying.address)) {
463
+ vesuAum = vesuAum.minus(legAUM[1].amount);
464
+ } else {
465
+ vesuAum = vesuAum.minus(legAUM[1].usdValue / tokenUnderlyingPrice.price);
466
+ };
467
+
468
+ logger.verbose(`${this.getTag()} Vesu AUM: ${vesuAum}, legCollateral: ${legAUM[0].amount.toNumber()}, legDebt: ${legAUM[1].amount.toNumber()}`);
469
+ return vesuAum;
470
+ }
471
+
472
+ async getPrevAUM() {
473
+ const currentAUM: bigint = await this.contract.call('aum', []) as bigint;
474
+ const prevAum = Web3Number.fromWei(currentAUM.toString(), this.asset().decimals);
475
+ logger.verbose(`${this.getTag()} Prev AUM: ${prevAum}`);
476
+ return prevAum;
477
+ }
478
+
479
+ async getAUM(unrealizedAUM?: boolean): Promise<{net: SingleTokenInfo, prevAum: Web3Number, splits: {id: string, aum: Web3Number}[]}> {
480
+ const prevAum = await this.getPrevAUM();
481
+ const token1Price = await this.pricer.getPrice(this.metadata.depositTokens[0].symbol);
482
+
483
+ // calculate vesu aum
484
+ const vesuAdapters = this.getVesuAdapters();
485
+ let vesuAum = Web3Number.fromWei("0", this.asset().decimals);
486
+ for (const adapter of vesuAdapters) {
487
+ const priceType = unrealizedAUM ? LSTPriceType.ENDUR_PRICE : LSTPriceType.AVNU_PRICE;
488
+ const aumValue = await this.getVesuAUM(adapter, priceType);
489
+ vesuAum = vesuAum.plus(aumValue);
490
+ }
491
+
492
+ // account unused balance as aum as well (from vault allocator)
493
+ const balance = await this.getUnusedBalance();
494
+ logger.verbose(`${this.getTag()} unused balance: ${balance.amount.toNumber()}`);
495
+
496
+ // Initiate return values
497
+ const zeroAmt = Web3Number.fromWei('0', this.asset().decimals);
498
+ const net = {
499
+ tokenInfo: this.asset(),
500
+ amount: zeroAmt,
501
+ usdValue: 0
502
+ };
503
+ const aumToken = vesuAum.plus(balance.amount);
504
+ if (aumToken.isZero()) {
505
+ return { net, splits: [{
506
+ aum: zeroAmt, id: AUMTypes.FINALISED
507
+ }, {
508
+ aum: zeroAmt, id: AUMTypes.DEFISPRING
509
+ }], prevAum};
510
+ }
511
+ logger.verbose(`${this.getTag()} Actual AUM: ${aumToken}`);
512
+
513
+ // compute rewards contribution to AUM
514
+ const rewardAssets = await this.getRewardsAUM(prevAum);
515
+
516
+ // Sum up and return
517
+ const newAUM = aumToken.plus(rewardAssets);
518
+ logger.verbose(`${this.getTag()} New AUM: ${newAUM}`);
519
+
520
+ net.amount = newAUM;
521
+ net.usdValue = newAUM.multipliedBy(token1Price.price).toNumber();
522
+ const splits = [{
523
+ id: AUMTypes.FINALISED,
524
+ aum: aumToken
525
+ }, {
526
+ id: AUMTypes.DEFISPRING,
527
+ aum: rewardAssets
528
+ }];
529
+ return { net, splits, prevAum };
530
+ }
531
+
532
+ // account for future rewards (e.g. defispring rewards)
533
+ protected async getRewardsAUM(prevAum: Web3Number) {
534
+ const lastReportTime = await this.contract.call('last_report_timestamp', []);
535
+ // - calculate estimated growth from strk rewards
536
+ const netAPY = await this.netAPY();
537
+ // account only 80% of value
538
+ const defispringAPY = (netAPY.splits.find(s => s.id === 'defispring')?.apy || 0) * 0.8;
539
+ // if (!defispringAPY) throw new Error('DefiSpring APY not found');
540
+
541
+ // compute rewards contribution to AUM
542
+ const timeDiff = (Math.round(Date.now() / 1000) - Number(lastReportTime));
543
+ const growthRate = timeDiff * defispringAPY / (365 * 24 * 60 * 60);
544
+ const rewardAssets = prevAum.multipliedBy(growthRate);
545
+ logger.verbose(`${this.getTag()} DefiSpring AUM time difference: ${timeDiff}`);
546
+ logger.verbose(`${this.getTag()} Current AUM: ${prevAum.toString()}`);
547
+ logger.verbose(`${this.getTag()} Net APY: ${JSON.stringify(netAPY)}`);
548
+ logger.verbose(`${this.getTag()} rewards AUM: ${rewardAssets}`);
549
+
550
+ return rewardAssets;
551
+ }
552
+
553
+ getVesuAdapters() {
554
+ const vesuAdapter1 = this.getAdapter(UNIVERSAL_ADAPTERS.VESU_LEG1) as unknown as VesuAdapter;
555
+ const vesuAdapter2 = this.getAdapter(UNIVERSAL_ADAPTERS.VESU_LEG2) as unknown as VesuAdapter;
556
+ vesuAdapter1.pricer = this.pricer;
557
+ vesuAdapter2.pricer = this.pricer;
558
+ vesuAdapter1.networkConfig = this.config;
559
+ vesuAdapter2.networkConfig = this.config;
560
+
561
+ return [vesuAdapter1, vesuAdapter2];
562
+ }
563
+
564
+ async getVesuPositions(blockNumber: BlockIdentifier = 'latest'): Promise<VaultPosition[]> {
565
+ const adapters = this.getVesuAdapters();
566
+ const positions: VaultPosition[] = [];
567
+ for (const adapter of adapters) {
568
+ positions.push(...await adapter.getPositions(this.config, blockNumber));
569
+ }
570
+ return positions;
571
+ }
572
+
573
+ async getVaultPositions(): Promise<VaultPosition[]> {
574
+ const vesuPositions = await this.getVesuPositions();
575
+ const unusedBalance = await this.getUnusedBalance();
576
+ return [...vesuPositions, {
577
+ amount: unusedBalance.amount,
578
+ usdValue: unusedBalance.usdValue,
579
+ token: this.asset(),
580
+ remarks: "Unused Balance (may not include recent deposits)",
581
+ protocol: Protocols.NONE
582
+ }];
583
+ }
584
+
585
+ getSetManagerCall(strategist: ContractAddr, root = this.getMerkleRoot()) {
586
+ return this.managerContract.populate('set_manage_root', [strategist.address, num.getHexString(root)]);
587
+ }
588
+
589
+ // TODO: callConstructor now returns Promise<ManageCall[]>, migrate callers to await and flatten
590
+ getManageCall(proofIds: string[], manageCalls: ManageCall[]) {
591
+ assert(proofIds.length == manageCalls.length, 'Proof IDs and Manage Calls length mismatch');
592
+ return this.managerContract.populate('manage_vault_with_merkle_verification', {
593
+ proofs: proofIds.map(id => this.getProofs(id).proofs),
594
+ decoder_and_sanitizers: manageCalls.map(call => call.sanitizer.address),
595
+ targets: manageCalls.map(call => call.call.contractAddress.address),
596
+ selectors: manageCalls.map(call => call.call.selector),
597
+ calldatas: manageCalls.map(call => call.call.calldata),
598
+ });
599
+ }
600
+
601
+ getVesuModifyPositionCalls(params: {
602
+ isLeg1: boolean,
603
+ isDeposit: boolean,
604
+ depositAmount: Web3Number,
605
+ debtAmount: Web3Number
606
+ }): UniversalManageCall[] {
607
+ assert(params.depositAmount.gt(0) || params.debtAmount.gt(0), 'Either deposit or debt amount must be greater than 0');
608
+ // approve token
609
+ const isToken1 = params.isLeg1 == params.isDeposit; // XOR
610
+ const STEP1_ID = isToken1 ? UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN1 :UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN2;
611
+ const manage4Info = this.getProofs<ApproveCallParams>(STEP1_ID);
612
+ const approveAmount = params.isDeposit ? params.depositAmount : params.debtAmount;
613
+ const manageCall4 = manage4Info.callConstructor({
614
+ amount: approveAmount
615
+ })
616
+
617
+ // deposit and borrow or repay and withdraw
618
+ const STEP2_ID = params.isLeg1 ? UNIVERSAL_MANAGE_IDS.VESU_LEG1 : UNIVERSAL_MANAGE_IDS.VESU_LEG2;
619
+ const manage5Info = this.getProofs<VesuModifyPositionCallParams>(STEP2_ID);
620
+ const manageCall5 = manage5Info.callConstructor(VesuAdapter.getDefaultModifyPositionCallParams({
621
+ collateralAmount: params.depositAmount,
622
+ isAddCollateral: params.isDeposit,
623
+ debtAmount: params.debtAmount,
624
+ isBorrow: params.isDeposit
625
+ }))
626
+
627
+ const output: UniversalManageCall[] = [{
628
+ proofs: manage5Info.proofs,
629
+ manageCall: manageCall5 as unknown as ManageCall,
630
+ step: STEP2_ID
631
+ }];
632
+ if (approveAmount.gt(0)) {
633
+ output.unshift({
634
+ proofs: manage4Info.proofs,
635
+ manageCall: manageCall4 as unknown as ManageCall,
636
+ step: STEP1_ID
637
+ })
638
+ }
639
+ return output;
640
+ }
641
+
642
+ getTag() {
643
+ return `${UniversalStrategy.name}:${this.metadata.name}`;
644
+ }
645
+
646
+ /**
647
+ * Gets LST APR for the strategy's underlying asset from Endur API
648
+ * @returns Promise<number> The LST APR (not divided by 1e18)
649
+ */
650
+ async getLSTAPR(address: ContractAddr): Promise<number> {
651
+ return 0;
652
+ }
653
+
654
+ async getVesuHealthFactors(blockNumber: BlockIdentifier = 'latest') {
655
+ return await Promise.all(this.getVesuAdapters().map(v => v.getHealthFactor(blockNumber)));
656
+ }
657
+
658
+ async computeRebalanceConditionAndReturnCalls(): Promise<Call[]> {
659
+ const vesuAdapters = this.getVesuAdapters();
660
+ const healthFactors = await this.getVesuHealthFactors();
661
+ const leg1HealthFactor = healthFactors[0];
662
+ const leg2HealthFactor = healthFactors[1];
663
+ logger.verbose(`${this.getTag()}: HealthFactorLeg1: ${leg1HealthFactor}`);
664
+ logger.verbose(`${this.getTag()}: HealthFactorLeg2: ${leg2HealthFactor}`);
665
+
666
+ const minHf = this.metadata.additionalInfo.minHealthFactor;
667
+ const isRebalanceNeeded1 = leg1HealthFactor < minHf;
668
+ const isRebalanceNeeded2 = leg2HealthFactor < minHf;
669
+ if (!isRebalanceNeeded1 && !isRebalanceNeeded2) {
670
+ return [];
671
+ }
672
+
673
+ if (isRebalanceNeeded1) {
674
+ const amount = await this.getLegRebalanceAmount(vesuAdapters[0], leg1HealthFactor, false);
675
+ const leg2HF = await this.getNewHealthFactor(vesuAdapters[1], amount, true);
676
+ assert(leg2HF > minHf, `Rebalance Leg1 failed: Leg2 HF after rebalance would be too low: ${leg2HF}`);
677
+ return [await this.getRebalanceCall({
678
+ isLeg1toLeg2: false,
679
+ amount: amount
680
+ })];
681
+ } else {
682
+ const amount = await this.getLegRebalanceAmount(vesuAdapters[1], leg2HealthFactor, true);
683
+ const leg1HF = await this.getNewHealthFactor(vesuAdapters[0], amount, false);
684
+ assert(leg1HF > minHf, `Rebalance Leg2 failed: Leg1 HF after rebalance would be too low: ${leg1HF}`);
685
+ return [await this.getRebalanceCall({
686
+ isLeg1toLeg2: true,
687
+ amount: amount
688
+ })];
689
+ }
690
+ }
691
+
692
+ private async getNewHealthFactor(vesuAdapter: VesuAdapter, newAmount: Web3Number, isWithdraw: boolean) {
693
+ const {
694
+ collateralTokenAmount,
695
+ collateralUSDAmount,
696
+ collateralPrice,
697
+ debtTokenAmount,
698
+ debtUSDAmount,
699
+ debtPrice,
700
+ ltv
701
+ } = await vesuAdapter.getAssetPrices();
702
+
703
+ if (isWithdraw) {
704
+ const newHF = ((collateralTokenAmount.toNumber() - newAmount.toNumber()) * collateralPrice * ltv) / debtUSDAmount;
705
+ logger.verbose(`getNewHealthFactor:: HF: ${newHF}, amoutn: ${newAmount.toNumber()}, isDeposit`);
706
+ return newHF;
707
+ } else { // is borrow
708
+ const newHF = (collateralUSDAmount * ltv) / ((debtTokenAmount.toNumber() + newAmount.toNumber()) * debtPrice);
709
+ logger.verbose(`getNewHealthFactor:: HF: ${newHF}, amoutn: ${newAmount.toNumber()}, isRepay`);
710
+ return newHF;
711
+ }
712
+ }
713
+
714
+ /**
715
+ *
716
+ * @param vesuAdapter
717
+ * @param currentHf
718
+ * @param isDeposit if true, attempt by adding collateral, else by repaying
719
+ * @returns
720
+ */
721
+ private async getLegRebalanceAmount(vesuAdapter: VesuAdapter, currentHf: number, isDeposit: boolean) {
722
+ const {
723
+ collateralTokenAmount,
724
+ collateralUSDAmount,
725
+ collateralPrice,
726
+ debtTokenAmount,
727
+ debtUSDAmount,
728
+ debtPrice,
729
+ ltv
730
+ } = await vesuAdapter.getAssetPrices();
731
+
732
+ // debt is zero, nothing to rebalance
733
+ if(debtTokenAmount.isZero()) {
734
+ return Web3Number.fromWei(0, 0);
735
+ }
736
+
737
+ assert(collateralPrice > 0 && debtPrice > 0, "getRebalanceAmount: Invalid price");
738
+
739
+ // avoid calculating for too close
740
+ const targetHF = this.metadata.additionalInfo.targetHealthFactor;
741
+ if (currentHf > targetHF - 0.01)
742
+ throw new Error("getLegRebalanceAmount: Current health factor is healthy");
743
+
744
+ if (isDeposit) {
745
+ // TargetHF = (collAmount + newAmount) * price * ltv / debtUSD
746
+ const newAmount = targetHF * debtUSDAmount / (collateralPrice * ltv) - collateralTokenAmount.toNumber();
747
+ logger.verbose(`${this.getTag()}:: getLegRebalanceAmount: addCollateral, currentHf: ${currentHf}, targetHF: ${targetHF}, collAmount: ${collateralTokenAmount.toString()}, collUSD: ${collateralUSDAmount}, collPrice: ${collateralPrice}, debtAmount: ${debtTokenAmount.toString()}, debtUSD: ${debtUSDAmount}, debtPrice: ${debtPrice}, ltv: ${ltv}, newAmount: ${newAmount}`);
748
+ return new Web3Number(newAmount.toFixed(8), collateralTokenAmount.decimals);
749
+ } else {
750
+ // TargetHF = collUSD * ltv / (debtAmount - newAmount) * debtPrice
751
+ const newAmount = debtTokenAmount.toNumber() - collateralUSDAmount * ltv / (targetHF * debtPrice);
752
+ logger.verbose(`${this.getTag()}:: getLegRebalanceAmount: repayDebt, currentHf: ${currentHf}, targetHF: ${targetHF}, collAmount: ${collateralTokenAmount.toString()}, collUSD: ${collateralUSDAmount}, collPrice: ${collateralPrice}, debtAmount: ${debtTokenAmount.toString()}, debtUSD: ${debtUSDAmount}, debtPrice: ${debtPrice}, ltv: ${ltv}, newAmount: ${newAmount}`);
753
+ return new Web3Number(newAmount.toFixed(8), debtTokenAmount.decimals);
754
+ }
755
+ }
756
+
757
+ async getVesuModifyPositionCall(params: {
758
+ isDeposit: boolean,
759
+ leg1DepositAmount: Web3Number
760
+ }) {
761
+ const [vesuAdapter1, vesuAdapter2] = this.getVesuAdapters();
762
+ const leg1LTV = await vesuAdapter1.getLTVConfig(this.config);
763
+ const leg2LTV = await vesuAdapter2.getLTVConfig(this.config);
764
+ logger.verbose(`${this.getTag()}: LTVLeg1: ${leg1LTV}`);
765
+ logger.verbose(`${this.getTag()}: LTVLeg2: ${leg2LTV}`);
766
+
767
+ const token1Price = await this.pricer.getPrice(vesuAdapter1.config.collateral.symbol);
768
+ const token2Price = await this.pricer.getPrice(vesuAdapter2.config.collateral.symbol);
769
+ logger.verbose(`${this.getTag()}: Price${vesuAdapter1.config.collateral.symbol}: ${token1Price.price}`);
770
+ logger.verbose(`${this.getTag()}: Price${vesuAdapter2.config.collateral.symbol}: ${token2Price.price}`);
771
+
772
+ const TARGET_HF = this.metadata.additionalInfo.targetHealthFactor;
773
+
774
+ const k1 = token1Price.price * leg1LTV / token2Price.price / TARGET_HF;
775
+ const k2 = token1Price.price * TARGET_HF / token2Price.price / leg2LTV;
776
+
777
+ const borrow2Amount = new Web3Number(
778
+ params.leg1DepositAmount.multipliedBy(k1.toFixed(6)).dividedBy(k2 - k1).toFixed(6),
779
+ vesuAdapter2.config.debt.decimals
780
+ );
781
+ const borrow1Amount = new Web3Number(
782
+ borrow2Amount.multipliedBy(k2).toFixed(6),
783
+ vesuAdapter1.config.debt.decimals
784
+ );
785
+ logger.verbose(`${this.getTag()}:: leg1DepositAmount: ${params.leg1DepositAmount.toString()} ${vesuAdapter1.config.collateral.symbol}`);
786
+ logger.verbose(`${this.getTag()}:: borrow1Amount: ${borrow1Amount.toString()} ${vesuAdapter1.config.debt.symbol}`);
787
+ logger.verbose(`${this.getTag()}:: borrow2Amount: ${borrow2Amount.toString()} ${vesuAdapter2.config.debt.symbol}`);
788
+
789
+ let callSet1 = this.getVesuModifyPositionCalls({
790
+ isLeg1: true,
791
+ isDeposit: params.isDeposit,
792
+ depositAmount: params.leg1DepositAmount.plus(borrow2Amount),
793
+ debtAmount: borrow1Amount
794
+ });
795
+
796
+ let callSet2 = this.getVesuModifyPositionCalls({
797
+ isLeg1: false,
798
+ isDeposit: params.isDeposit,
799
+ depositAmount: borrow1Amount,
800
+ debtAmount: borrow2Amount
801
+ });
802
+
803
+ if (!params.isDeposit) {
804
+ let temp = callSet2;
805
+ callSet2 = [...callSet1];
806
+ callSet1 = [...temp];
807
+ }
808
+ const allActions = [...callSet1.map(i => i.manageCall), ...callSet2.map(i => i.manageCall)];
809
+ const flashloanCalldata = CallData.compile([
810
+ [...callSet1.map(i => i.proofs), ...callSet2.map(i => i.proofs)],
811
+ allActions.map(i => i.sanitizer.address),
812
+ allActions.map(i => i.call.contractAddress.address),
813
+ allActions.map(i => i.call.selector),
814
+ allActions.map(i => i.call.calldata)
815
+ ])
816
+
817
+ // flash loan
818
+ const STEP1_ID = UNIVERSAL_MANAGE_IDS.FLASH_LOAN;
819
+ const manage1Info = this.getProofs<FlashloanCallParams>(STEP1_ID);
820
+ const manageCall1 = manage1Info.callConstructor({
821
+ amount: borrow2Amount,
822
+ data: flashloanCalldata.map(i => BigInt(i))
823
+ })
824
+ const manageCall = this.getManageCall([UNIVERSAL_MANAGE_IDS.FLASH_LOAN], [manageCall1 as unknown as ManageCall]);
825
+ return manageCall;
826
+ }
827
+
828
+ async getBringLiquidityCall(params: {
829
+ amount: Web3Number
830
+ }) {
831
+ const manage1Info = this.getProofs<ApproveCallParams>(UNIVERSAL_MANAGE_IDS.APPROVE_BRING_LIQUIDITY);
832
+ const manageCall1 = manage1Info.callConstructor({
833
+ amount: params.amount
834
+ });
835
+ const manage2Info = this.getProofs<ApproveCallParams>(UNIVERSAL_MANAGE_IDS.BRING_LIQUIDITY);
836
+ const manageCall2 = manage2Info.callConstructor({
837
+ amount: params.amount
838
+ });
839
+ const manageCall = this.getManageCall([UNIVERSAL_MANAGE_IDS.APPROVE_BRING_LIQUIDITY, UNIVERSAL_MANAGE_IDS.BRING_LIQUIDITY], [manageCall1 as unknown as ManageCall, manageCall2 as unknown as ManageCall]);
840
+ return manageCall;
841
+ }
842
+
843
+ async getPendingRewards(): Promise<HarvestInfo[]> {
844
+ const vesuHarvest = new VesuHarvests(this.config);
845
+ return await vesuHarvest.getUnHarvestedRewards(this.metadata.additionalInfo.vaultAllocator);
846
+ }
847
+
848
+ async getHarvestCall() {
849
+ const harvestInfo = await this.getPendingRewards();
850
+ if (harvestInfo.length == 0) {
851
+ throw new Error(`No pending rewards found`);
852
+ }
853
+ if (harvestInfo.length != 1) {
854
+ throw new Error(`Expected 1 harvest info, got ${harvestInfo.length}`);
855
+ }
856
+
857
+ const amount = harvestInfo[0].claim.amount;
858
+ const actualReward = harvestInfo[0].actualReward;
859
+ const proofs = harvestInfo[0].proof;
860
+ if (actualReward.isZero()) {
861
+ throw new Error(`Expected non-zero actual reward, got ${harvestInfo[0].actualReward}`);
862
+ }
863
+
864
+ const manage1Info = this.getProofs<VesuDefiSpringRewardsCallParams>(UNIVERSAL_MANAGE_IDS.DEFISPRING_REWARDS);
865
+ const manageCall1 = manage1Info.callConstructor({
866
+ amount,
867
+ proofs
868
+ });
869
+ const proofIds: string[] = [UNIVERSAL_MANAGE_IDS.DEFISPRING_REWARDS];
870
+ const manageCalls: ManageCall[] = [manageCall1 as unknown as ManageCall];
871
+
872
+ // swap rewards for underlying
873
+ const STRK = Global.getDefaultTokens().find(t => t.symbol === 'STRK')!;
874
+ if (this.asset().symbol != 'STRK') {
875
+ // approve
876
+ const manage2Info = this.getProofs<ApproveCallParams>(UNIVERSAL_MANAGE_IDS.APPROVE_SWAP_TOKEN1);
877
+ const manageCall2 = manage2Info.callConstructor({
878
+ amount: actualReward
879
+ });
880
+
881
+ // swap
882
+ const avnuModule = new AvnuWrapper();
883
+ const quote = await avnuModule.getQuotes(
884
+ STRK.address.address,
885
+ this.asset().address.address,
886
+ actualReward.toWei(),
887
+ this.address.address
888
+ );
889
+ const swapInfo = await avnuModule.getSwapInfo(quote, this.address.address, 0, this.address.address);
890
+ const manage3Info = this.getProofs<AvnuSwapCallParams>(UNIVERSAL_MANAGE_IDS.AVNU_SWAP_REWARDS);
891
+ const manageCall3 = manage3Info.callConstructor({
892
+ props: swapInfo
893
+ });
894
+ proofIds.push(UNIVERSAL_MANAGE_IDS.APPROVE_SWAP_TOKEN1);
895
+ proofIds.push(UNIVERSAL_MANAGE_IDS.AVNU_SWAP_REWARDS);
896
+
897
+ manageCalls.push(manageCall2 as unknown as ManageCall);
898
+ manageCalls.push(manageCall3 as unknown as ManageCall);
899
+ }
900
+
901
+ const manageCall = this.getManageCall(proofIds, manageCalls);
902
+ return { call: manageCall, reward: actualReward, tokenInfo: STRK };
903
+ }
904
+
905
+ async getRebalanceCall(params: {
906
+ isLeg1toLeg2: boolean,
907
+ amount: Web3Number
908
+ }) {
909
+ let callSet1 = this.getVesuModifyPositionCalls({
910
+ isLeg1: true,
911
+ isDeposit: params.isLeg1toLeg2,
912
+ depositAmount: Web3Number.fromWei(0, 0),
913
+ debtAmount: params.amount
914
+ });
915
+
916
+ let callSet2 = this.getVesuModifyPositionCalls({
917
+ isLeg1: false,
918
+ isDeposit: params.isLeg1toLeg2,
919
+ depositAmount: params.amount,
920
+ debtAmount: Web3Number.fromWei(0, 0)
921
+ });
922
+
923
+ if (params.isLeg1toLeg2) {
924
+ const manageCall = this.getManageCall([
925
+ ...callSet1.map(i => i.step), ...callSet2.map(i => i.step)
926
+ ], [...callSet1.map(i => i.manageCall), ...callSet2.map(i => i.manageCall)]);
927
+ return manageCall;
928
+ } else {
929
+ const manageCall = this.getManageCall([
930
+ ...callSet2.map(i => i.step), ...callSet1.map(i => i.step)
931
+ ], [...callSet2.map(i => i.manageCall), ...callSet1.map(i => i.manageCall)]);
932
+ return manageCall;
933
+ }
934
+ }
935
+ }
936
+
937
+ // useful to map readble names to proofs and calls
938
+ export enum UNIVERSAL_MANAGE_IDS {
939
+ FLASH_LOAN = 'flash_loan_init',
940
+ VESU_LEG1 = 'vesu_leg1',
941
+ VESU_LEG2 = 'vesu_leg2',
942
+ APPROVE_TOKEN1 = 'approve_token1',
943
+ APPROVE_TOKEN2 = 'approve_token2',
944
+ APPROVE_BRING_LIQUIDITY = 'approve_bring_liquidity',
945
+ BRING_LIQUIDITY = 'bring_liquidity',
946
+
947
+ // defi spring claim
948
+ DEFISPRING_REWARDS = 'defispring_rewards',
949
+
950
+ // avnu swaps
951
+ APPROVE_SWAP_TOKEN1 = 'approve_swap_token1',
952
+ AVNU_SWAP_REWARDS = 'avnu_swap_rewards'
953
+ }
954
+
955
+ export enum UNIVERSAL_ADAPTERS {
956
+ COMMON = 'common_adapter',
957
+ VESU_LEG1 = 'vesu_leg1_adapter',
958
+ VESU_LEG2 = 'vesu_leg2_adapter'
959
+ }
960
+
961
+ function getLooperSettings(
962
+ token1Symbol: string,
963
+ token2Symbol: string,
964
+ vaultSettings: UniversalStrategySettings,
965
+ pool1: ContractAddr,
966
+ pool2: ContractAddr,
967
+ ) {
968
+ const USDCToken = Global.getDefaultTokens().find(token => token.symbol === token1Symbol)!;
969
+ const ETHToken = Global.getDefaultTokens().find(token => token.symbol === token2Symbol)!;
970
+
971
+ const commonAdapter = new CommonAdapter({
972
+ manager: vaultSettings.manager,
973
+ asset: USDCToken.address,
974
+ id: UNIVERSAL_MANAGE_IDS.FLASH_LOAN,
975
+ vaultAddress: vaultSettings.vaultAddress,
976
+ vaultAllocator: vaultSettings.vaultAllocator,
977
+ })
978
+ const vesuAdapterUSDCETH = new VesuAdapter({
979
+ poolId: pool1,
980
+ collateral: USDCToken,
981
+ debt: ETHToken,
982
+ vaultAllocator: vaultSettings.vaultAllocator,
983
+ id: UNIVERSAL_MANAGE_IDS.VESU_LEG1
984
+ })
985
+ const vesuAdapterETHUSDC = new VesuAdapter({
986
+ poolId: pool2,
987
+ collateral: ETHToken,
988
+ debt: USDCToken,
989
+ vaultAllocator: vaultSettings.vaultAllocator,
990
+ id: UNIVERSAL_MANAGE_IDS.VESU_LEG2
991
+ })
992
+ // vaultSettings.adapters.push(...[{
993
+ // id: UNIVERSAL_ADAPTERS.COMMON,
994
+ // adapter: commonAdapter
995
+ // }, {
996
+ // id: UNIVERSAL_ADAPTERS.VESU_LEG1,
997
+ // adapter: vesuAdapterUSDCETH
998
+ // }, {
999
+ // id: UNIVERSAL_ADAPTERS.VESU_LEG2,
1000
+ // adapter: vesuAdapterETHUSDC
1001
+ // }])
1002
+
1003
+ // vesu looping
1004
+ // vaultSettings.leafAdapters.push(commonAdapter.getFlashloanAdapter.bind(commonAdapter));
1005
+ // vaultSettings.leafAdapters.push(vesuAdapterUSDCETH.getModifyPosition.bind(vesuAdapterUSDCETH));
1006
+ // vaultSettings.leafAdapters.push(vesuAdapterETHUSDC.getModifyPosition.bind(vesuAdapterETHUSDC));
1007
+ vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(USDCToken.address, VESU_SINGLETON, UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN1).bind(commonAdapter));
1008
+ vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(ETHToken.address, VESU_SINGLETON, UNIVERSAL_MANAGE_IDS.APPROVE_TOKEN2).bind(commonAdapter));
1009
+
1010
+ // to bridge liquidity back to vault (used by bring_liquidity)
1011
+ vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(USDCToken.address, vaultSettings.vaultAddress, UNIVERSAL_MANAGE_IDS.APPROVE_BRING_LIQUIDITY).bind(commonAdapter));
1012
+ vaultSettings.leafAdapters.push(commonAdapter.getBringLiquidityAdapter(UNIVERSAL_MANAGE_IDS.BRING_LIQUIDITY).bind(commonAdapter));
1013
+
1014
+ // claim rewards
1015
+ // vaultSettings.leafAdapters.push(vesuAdapterUSDCETH.getDefispringRewardsAdapter(UNIVERSAL_MANAGE_IDS.DEFISPRING_REWARDS).bind(vesuAdapterUSDCETH));
1016
+
1017
+ // avnu swap
1018
+ const STRKToken = Global.getDefaultTokens().find(token => token.symbol === 'STRK')!;
1019
+ vaultSettings.leafAdapters.push(commonAdapter.getApproveAdapter(STRKToken.address, AVNU_MIDDLEWARE, UNIVERSAL_MANAGE_IDS.APPROVE_SWAP_TOKEN1).bind(commonAdapter));
1020
+ // vaultSettings.leafAdapters.push(commonAdapter.getAvnuAdapter(STRKToken.address, USDCToken.address, UNIVERSAL_MANAGE_IDS.AVNU_SWAP_REWARDS, true).bind(commonAdapter));
1021
+ return vaultSettings;
1022
+ }
1023
+
1024
+ const _riskFactor: RiskFactor[] = [
1025
+ { type: RiskType.SMART_CONTRACT_RISK, value: 0.5, weight: 25, reason: "Audited by Zellic" },
1026
+ { type: RiskType.LIQUIDATION_RISK, value: 1.5, weight: 50, reason: "Liquidation risk is mitigated by stable price feed on Starknet" },
1027
+ { type: RiskType.TECHNICAL_RISK, value: 1, weight: 50, reason: "Technical failures like risk monitoring failures" }
1028
+ ];
1029
+
1030
+ const usdcVaultSettings: UniversalStrategySettings = {
1031
+ vaultAddress: ContractAddr.from('0x7e6498cf6a1bfc7e6fc89f1831865e2dacb9756def4ec4b031a9138788a3b5e'),
1032
+ manager: ContractAddr.from('0xf41a2b1f498a7f9629db0b8519259e66e964260a23d20003f3e42bb1997a07'),
1033
+ vaultAllocator: ContractAddr.from('0x228cca1005d3f2b55cbaba27cb291dacf1b9a92d1d6b1638195fbd3d0c1e3ba'),
1034
+ redeemRequestNFT: ContractAddr.from('0x906d03590010868cbf7590ad47043959d7af8e782089a605d9b22567b64fda'),
1035
+ aumOracle: ContractAddr.from("0x6faf45ed185dec13ef723c9ead4266cab98d06f2cb237e331b1fa5c2aa79afe"),
1036
+ leafAdapters: [],
1037
+ adapters: [],
1038
+ targetHealthFactor: 1.25,
1039
+ minHealthFactor: 1.15
1040
+ }
1041
+
1042
+ const wbtcVaultSettings: UniversalStrategySettings = {
1043
+ vaultAddress: ContractAddr.from('0x5a4c1651b913aa2ea7afd9024911603152a19058624c3e425405370d62bf80c'),
1044
+ manager: ContractAddr.from('0xef8a664ffcfe46a6af550766d27c28937bf1b77fb4ab54d8553e92bca5ba34'),
1045
+ vaultAllocator: ContractAddr.from('0x1e01c25f0d9494570226ad28a7fa856c0640505e809c366a9fab4903320e735'),
1046
+ redeemRequestNFT: ContractAddr.from('0x4fec59a12f8424281c1e65a80b5de51b4e754625c60cddfcd00d46941ec37b2'),
1047
+ aumOracle: ContractAddr.from("0x2edf4edbed3f839e7f07dcd913e92299898ff4cf0ba532f8c572c66c5b331b2"),
1048
+ leafAdapters: [],
1049
+ adapters: [],
1050
+ targetHealthFactor: 1.20,
1051
+ minHealthFactor: 1.15
1052
+ }
1053
+
1054
+ const ethVaultSettings: UniversalStrategySettings = {
1055
+ vaultAddress: ContractAddr.from('0x446c22d4d3f5cb52b4950ba832ba1df99464c6673a37c092b1d9622650dbd8'),
1056
+ manager: ContractAddr.from('0x494888b37206616bd09d759dcda61e5118470b9aa7f58fb84f21c778a7b8f97'),
1057
+ vaultAllocator: ContractAddr.from('0x4acc0ad6bea58cb578d60ff7c31f06f44369a7a9a7bbfffe4701f143e427bd'),
1058
+ redeemRequestNFT: ContractAddr.from('0x2e6cd71e5060a254d4db00655e420db7bf89da7755bb0d5f922e2f00c76ac49'),
1059
+ aumOracle: ContractAddr.from("0x4b747f2e75c057bed9aa2ce46fbdc2159dc684c15bd32d4f95983a6ecf39a05"),
1060
+ leafAdapters: [],
1061
+ adapters: [],
1062
+ targetHealthFactor: 1.25,
1063
+ minHealthFactor: 1.21
1064
+ }
1065
+
1066
+ const strkVaultSettings: UniversalStrategySettings = {
1067
+ vaultAddress: ContractAddr.from('0x55d012f57e58c96e0a5c7ebbe55853989d01e6538b15a95e7178aca4af05c21'),
1068
+ manager: ContractAddr.from('0xcc6a5153ca56293405506eb20826a379d982cd738008ef7e808454d318fb81'),
1069
+ vaultAllocator: ContractAddr.from('0xf29d2f82e896c0ed74c9eff220af34ac148e8b99846d1ace9fbb02c9191d01'),
1070
+ redeemRequestNFT: ContractAddr.from('0x46902423bd632c428376b84fcee9cac5dbe016214e93a8103bcbde6e1de656b'),
1071
+ aumOracle: ContractAddr.from("0x6d7dbfad4bb51715da211468389a623da00c0625f8f6efbea822ee5ac5231f4"),
1072
+ leafAdapters: [],
1073
+ adapters: [],
1074
+ targetHealthFactor: 1.20,
1075
+ minHealthFactor: 1.15
1076
+ }
1077
+
1078
+ const usdtVaultSettings: UniversalStrategySettings = {
1079
+ vaultAddress: ContractAddr.from('0x1c4933d1880c6778585e597154eaca7b428579d72f3aae425ad2e4d26c6bb3'),
1080
+ manager: ContractAddr.from('0x39bb9843503799b552b7ed84b31c06e4ff10c0537edcddfbf01fe944b864029'),
1081
+ vaultAllocator: ContractAddr.from('0x56437d18c43727ac971f6c7086031cad7d9d6ccb340f4f3785a74cc791c931a'),
1082
+ redeemRequestNFT: ContractAddr.from('0x5af0c2a657eaa8e23ed78e855dac0c51e4f69e2cf91a18c472041a1f75bb41f'),
1083
+ aumOracle: ContractAddr.from("0x7018f8040c8066a4ab929e6760ae52dd43b6a3a289172f514750a61fcc565cc"),
1084
+ leafAdapters: [],
1085
+ adapters: [],
1086
+ targetHealthFactor: 1.25,
1087
+ minHealthFactor: 1.15
1088
+ }
1089
+
1090
+ type AllowedSources = 'vesu' | 'endur' | 'extended';
1091
+ // export default function MetaVaultDescription(allowedSources: AllowedSources[]) {
1092
+ // const logos: any = {
1093
+ // vesu: Protocols.VESU.logo,
1094
+ // endur: Protocols.ENDUR.logo,
1095
+ // extended: Protocols.EXTENDED.logo,
1096
+ // ekubo: "https://dummyimage.com/64x64/ffffff/000000&text=K",
1097
+ // };
1098
+ // const _sources = [
1099
+ // { key: "vesu", name: "Vesu", status: "Live", description: "Integrated liquidity venue used for automated routing to capture the best available yield." },
1100
+ // { key: "endur", name: "Endur", status: "Coming soon", description: "Planned integration to tap into STRK staking–backed yields via our LST pipeline." },
1101
+ // { key: "extended", name: "Extended", status: "Coming soon", description: "Expanding coverage to additional money markets and vaults across the ecosystem." },
1102
+ // // { key: "ekubo", name: "Ekubo", status: "Coming soon", description: "Concentrated liquidity strategies targeted for optimized fee APR harvesting." },
1103
+ // ];
1104
+ // const sources = _sources.filter(s => allowedSources.includes(s.key as any));
1105
+
1106
+ // const containerStyle = {
1107
+ // maxWidth: "800px",
1108
+ // margin: "0 auto",
1109
+ // color: "#eee",
1110
+ // fontFamily: "Arial, sans-serif",
1111
+ // borderRadius: "12px",
1112
+ // };
1113
+
1114
+ // const cardStyle = {
1115
+ // border: "1px solid #333",
1116
+ // borderRadius: "10px",
1117
+ // padding: "12px",
1118
+ // marginBottom: "12px",
1119
+ // backgroundColor: "#1a1a1a",
1120
+ // };
1121
+
1122
+ // const logoStyle = {
1123
+ // width: "24px",
1124
+ // height: "24px",
1125
+ // borderRadius: "8px",
1126
+ // border: "1px solid #444",
1127
+ // backgroundColor: "#222",
1128
+ // };
1129
+
1130
+ // return (
1131
+ // <div style={containerStyle}>
1132
+ // <h1 style={{ fontSize: "18px", marginBottom: "10px" }}>Meta Vault — Automated Yield Router</h1>
1133
+ // <p style={{ fontSize: "14px", lineHeight: "1.5", marginBottom: "16px" }}>
1134
+ // This Evergreen vault is a tokenized Meta Vault, auto-compounding strategy that continuously allocates your deposited
1135
+ // represent a proportional claim on the underlying assets and accrued yield. Allocation shifts are
1136
+ // handled programmatically based on on-chain signals and risk filters, minimizing idle capital and
1137
+ // maximizing net APY.
1138
+ // </p>
1139
+
1140
+ // <div style={{ backgroundColor: "#222", padding: "10px", borderRadius: "8px", marginBottom: "20px", border: "1px solid #444" }}>
1141
+ // <p style={{ fontSize: "13px", color: "#ccc" }}>
1142
+ // <strong>Withdrawals:</strong> Requests can take up to <strong>1-2 hours</strong> to process as the vault unwinds and settles routing.
1143
+ // </p>
1144
+ // </div>
1145
+
1146
+ // <h2 style={{ fontSize: "18px", marginBottom: "10px" }}>Supported Yield Sources</h2>
1147
+ // {sources.map((s) => (
1148
+ // <div key={s.key} style={cardStyle}>
1149
+ // <div style={{ display: "flex", gap: "10px", alignItems: "flex-start" }}>
1150
+ // <img src={logos[s.key]} alt={`${s.name} logo`} style={logoStyle} />
1151
+ // <div style={{ flex: 1 }}>
1152
+ // <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
1153
+ // <h3 style={{ fontSize: "15px", margin: 0 }}>{s.name}</h3>
1154
+ // <StatusBadge status={s.status} />
1155
+ // </div>
1156
+ // {/* <p style={{ fontSize: "13px", color: "#ccc", marginTop: "4px" }}>{s.description}</p> */}
1157
+ // </div>
1158
+ // </div>
1159
+ // </div>
1160
+ // ))}
1161
+ // </div>
1162
+ // );
1163
+ // }
1164
+
1165
+ // function StatusBadge({ status }: { status: string }) {
1166
+ // const isSoon = String(status).toLowerCase() !== "live";
1167
+ // const badgeStyle = {
1168
+ // fontSize: "12px",
1169
+ // padding: "2px 6px",
1170
+ // borderRadius: "12px",
1171
+ // border: "1px solid",
1172
+ // color: isSoon ? "rgb(196 196 195)" : "#6aff7d",
1173
+ // borderColor: isSoon ? "#484848" : "#6aff7d",
1174
+ // backgroundColor: isSoon ? "#424242" : "#002b1a",
1175
+ // };
1176
+ // return <span style={badgeStyle}>{status}</span>;
1177
+ // }
1178
+
1179
+ function getDescription(_tokenSymbol: string, _allowedSources: AllowedSources[]) {
1180
+ // MetaVaultDescription is currently disabled; return null placeholder
1181
+ return null;
1182
+ }
1183
+
1184
+ function getFAQs(): FAQ[] {
1185
+ return [
1186
+ {
1187
+ question: "What is the Meta Vault?",
1188
+ answer:
1189
+ "The Meta Vault is a tokenized strategy that automatically allocates your deposited assets to the best available yield source in the ecosystem. It optimizes returns while minimizing idle capital.",
1190
+ },
1191
+ {
1192
+ question: "How does yield allocation work?",
1193
+ answer:
1194
+ "The vault continuously monitors supported protocols and routes liquidity to the source offering the highest net yield after accounting for fees, slippage, and gas costs. Reallocations are performed automatically.",
1195
+ },
1196
+ {
1197
+ question: "Which yield sources are supported?",
1198
+ answer: (
1199
+ <span>
1200
+ Currently, <strong>Vesu</strong> is live. Future integrations may include{" "}
1201
+ <strong>Endur</strong>, <strong>Extended</strong>, and{" "}
1202
+ <strong>Ekubo</strong> (all coming soon).
1203
+ </span>
1204
+ ),
1205
+ },
1206
+ {
1207
+ question: "What do I receive when I deposit?",
1208
+ answer:
1209
+ "Depositors receive vault tokens representing their proportional share of the vault. These tokens entitle holders to both the principal and accrued yield.",
1210
+ },
1211
+ {
1212
+ question: "How long do withdrawals take?",
1213
+ answer:
1214
+ "Withdrawals may take up to 1-2 hours to process, as the vault unwinds and settles liquidity routing across integrated protocols.",
1215
+ },
1216
+ {
1217
+ question: "Is the Meta Vault non-custodial?",
1218
+ answer:
1219
+ "Yes. The Meta Vault operates entirely on-chain. Users always maintain control of their vault tokens, and the strategy is fully transparent.",
1220
+ },
1221
+ {
1222
+ question: "How is risk managed?",
1223
+ answer:
1224
+ "Integrations are supported with active risk monitoring like liquidation risk. Only vetted protocols are included to balance yield with safety. However, usual Defi risks like smart contract risk, extreme volatile market risk, etc. are still present.",
1225
+ },
1226
+ {
1227
+ question: "Are there any fees?",
1228
+ answer:
1229
+ "Troves charges a performance of 10% on the yield generated. The APY shown is net of this fee. This fee is only applied to the profits earned, ensuring that users retain their initial capital.",
1230
+ },
1231
+ ];
1232
+ }
1233
+
1234
+ export function getContractDetails(settings: UniversalStrategySettings & { aumOracle?: ContractAddr }): {address: ContractAddr, name: string}[] {
1235
+ const contracts = [
1236
+ { address: settings.vaultAddress, name: "Vault" },
1237
+ { address: settings.manager, name: "Vault Manager" },
1238
+ { address: settings.vaultAllocator, name: "Vault Allocator" },
1239
+ { address: settings.redeemRequestNFT, name: "Redeem Request NFT" },
1240
+ ];
1241
+ if (settings.aumOracle) {
1242
+ contracts.push({ address: settings.aumOracle, name: "AUM Oracle" });
1243
+ }
1244
+ return contracts;
1245
+ }
1246
+
1247
+ const investmentSteps: string[] = [
1248
+ "Deposit funds into the vault",
1249
+ "Vault manager allocates funds to optimal yield sources",
1250
+ "Vault manager reports asset under management (AUM) regularly to the vault",
1251
+ "Request withdrawal and vault manager processes it in 1-2 hours"
1252
+ ]
1253
+
1254
+ const AUDIT_URL = 'https://docs.troves.fi/p/security#starknet-vault-kit'
1255
+
1256
+ // Helper to create common risk object
1257
+ const getUniversalRisk = () => ({
1258
+ riskFactor: _riskFactor,
1259
+ netRisk:
1260
+ _riskFactor.reduce((acc, curr) => acc + curr.value * curr.weight, 0) /
1261
+ _riskFactor.reduce((acc, curr) => acc + curr.weight, 0),
1262
+ notARisks: getNoRiskTags(_riskFactor)
1263
+ });
1264
+
1265
+ // Helper to create Universal strategy settings
1266
+ const createUniversalSettings = (
1267
+ tokenSymbol: string,
1268
+ maxTVLDecimals: number
1269
+ ): StrategySettings => {
1270
+ const isUSDT = tokenSymbol === "USDT";
1271
+ return {
1272
+ maxTVL: Web3Number.fromWei(0, maxTVLDecimals),
1273
+ isAudited: true,
1274
+ liveStatus: isUSDT ? StrategyLiveStatus.RETIRED : StrategyLiveStatus.ACTIVE,
1275
+ isPaused: isUSDT,
1276
+ isInstantWithdrawal: false,
1277
+ hideHarvestInfo: true,
1278
+ quoteToken: Global.getDefaultTokens().find(
1279
+ (token) => token.symbol === tokenSymbol
1280
+ )!,
1281
+ alerts: [
1282
+ {
1283
+ tab: "withdraw" as const,
1284
+ text: "On withdrawal, you will receive an NFT representing your withdrawal request. The funds will be automatically sent to your wallet (NFT owner) in 1-2 hours. You can monitor the status in transactions tab.",
1285
+ type: "info" as const
1286
+ }
1287
+ ],
1288
+ showWithdrawalWarningModal: true
1289
+ };
1290
+ };
1291
+
1292
+ const EVERGREEN_SECURITY = {
1293
+ auditStatus: AuditStatus.AUDITED,
1294
+ sourceCode: {
1295
+ type: SourceCodeType.CLOSED_SOURCE,
1296
+ contractLink: "https://github.com/trovesfi/troves-contracts",
1297
+ },
1298
+ accessControl: {
1299
+ type: AccessControlType.STANDARD_ACCOUNT,
1300
+ addresses: [ContractAddr.from("0x0")],
1301
+ timeLock: "2 Days",
1302
+ },
1303
+ };
1304
+
1305
+ const EVERGREEN_REDEMPTION_INFO: RedemptionInfo = {
1306
+ instantWithdrawalVault: InstantWithdrawalVault.NO,
1307
+ redemptionsInfo: [{
1308
+ title: "Typical Duration",
1309
+ description: "1-2 hours"
1310
+ }],
1311
+ alerts: [{
1312
+ type: 'info',
1313
+ text: 'In cases of low liquidity, high slippages, the redemptions can take longer time. Redemption times are estimates and may vary based on network conditions and liquidity requirements.',
1314
+ tab: 'withdraw'
1315
+ }]
1316
+ };
1317
+
1318
+ // Helper to create a Universal strategy
1319
+ const createUniversalStrategy = (params: {
1320
+ tokenSymbol: string;
1321
+ address: string;
1322
+ vaultSettings: UniversalStrategySettings;
1323
+ token1Symbol: string;
1324
+ token2Symbol: string;
1325
+ maxTVLDecimals: number;
1326
+ allowedSources: AllowedSources[];
1327
+ tags: StrategyTag[];
1328
+ }): IStrategyMetadata<UniversalStrategySettings> => {
1329
+ const isUSDT = params.tokenSymbol === "USDT";
1330
+ return {
1331
+ id: `evergreen_${params.tokenSymbol.toLowerCase()}`,
1332
+ name: `${params.tokenSymbol} Evergreen`,
1333
+ description: getDescription(params.tokenSymbol, params.allowedSources),
1334
+ address: ContractAddr.from(params.address),
1335
+ launchBlock: 0,
1336
+ type: "ERC4626" as const,
1337
+ vaultType: {
1338
+ type: VaultType.META_VAULT,
1339
+ description: "Automatically allocates funds to the best available yield source in the ecosystem"
1340
+ },
1341
+ depositTokens: [
1342
+ Global.getDefaultTokens().find((token) => token.symbol === params.tokenSymbol)!
1343
+ ],
1344
+ additionalInfo: getLooperSettings(
1345
+ params.token1Symbol,
1346
+ params.token2Symbol,
1347
+ params.vaultSettings,
1348
+ VesuPools.Genesis,
1349
+ VesuPools.Genesis
1350
+ ),
1351
+ risk: getUniversalRisk(),
1352
+ auditUrl: AUDIT_URL,
1353
+ protocols: [Protocols.VESU],
1354
+ realizedAPYMethodology: "The realizedAPY is based on past 14 days performance by the vault",
1355
+ curator: {
1356
+ name: "Unwrap Labs",
1357
+ logo: "https://assets.troves.fi/integrations/unwraplabs/white.png"
1358
+ },
1359
+ settings: createUniversalSettings(params.tokenSymbol, params.maxTVLDecimals),
1360
+ contractDetails: getContractDetails(params.vaultSettings),
1361
+ faqs: getFAQs(),
1362
+ investmentSteps: investmentSteps,
1363
+ tags: params.tags,
1364
+ security: EVERGREEN_SECURITY,
1365
+ redemptionInfo: EVERGREEN_REDEMPTION_INFO,
1366
+ discontinuationInfo: isUSDT ? {
1367
+ info: "This strategy has been retired and is no longer accepting new deposits."
1368
+ } : undefined,
1369
+ usualTimeToEarnings: null,
1370
+ usualTimeToEarningsDescription: null,
1371
+ };
1372
+ };
1373
+
1374
+ export const UniversalStrategies: IStrategyMetadata<UniversalStrategySettings>[] =
1375
+ [
1376
+ createUniversalStrategy({
1377
+ tokenSymbol: "USDC.e",
1378
+ address: "0x7e6498cf6a1bfc7e6fc89f1831865e2dacb9756def4ec4b031a9138788a3b5e",
1379
+ vaultSettings: usdcVaultSettings,
1380
+ token1Symbol: "USDC.e",
1381
+ token2Symbol: "ETH",
1382
+ maxTVLDecimals: 6,
1383
+ allowedSources: ["vesu", "extended"],
1384
+ tags: [StrategyTag.META_VAULT]
1385
+ }),
1386
+ createUniversalStrategy({
1387
+ tokenSymbol: "WBTC",
1388
+ address: "0x5a4c1651b913aa2ea7afd9024911603152a19058624c3e425405370d62bf80c",
1389
+ vaultSettings: wbtcVaultSettings,
1390
+ token1Symbol: "WBTC",
1391
+ token2Symbol: "ETH",
1392
+ maxTVLDecimals: 8,
1393
+ allowedSources: ["vesu", "endur", "extended"],
1394
+ tags: [StrategyTag.BTC, StrategyTag.META_VAULT]
1395
+ }),
1396
+ createUniversalStrategy({
1397
+ tokenSymbol: "ETH",
1398
+ address: "0x446c22d4d3f5cb52b4950ba832ba1df99464c6673a37c092b1d9622650dbd8",
1399
+ vaultSettings: ethVaultSettings,
1400
+ token1Symbol: "ETH",
1401
+ token2Symbol: "WBTC",
1402
+ maxTVLDecimals: 18,
1403
+ allowedSources: ["vesu", "extended"],
1404
+ tags: [StrategyTag.META_VAULT]
1405
+ }),
1406
+ createUniversalStrategy({
1407
+ tokenSymbol: "STRK",
1408
+ address: "0x55d012f57e58c96e0a5c7ebbe55853989d01e6538b15a95e7178aca4af05c21",
1409
+ vaultSettings: strkVaultSettings,
1410
+ token1Symbol: "STRK",
1411
+ token2Symbol: "ETH",
1412
+ maxTVLDecimals: 18,
1413
+ allowedSources: ["vesu", "endur", "extended"],
1414
+ tags: [StrategyTag.META_VAULT]
1415
+ }),
1416
+ createUniversalStrategy({
1417
+ tokenSymbol: "USDT",
1418
+ address: "0x1c4933d1880c6778585e597154eaca7b428579d72f3aae425ad2e4d26c6bb3",
1419
+ vaultSettings: usdtVaultSettings,
1420
+ token1Symbol: "USDT",
1421
+ token2Symbol: "ETH",
1422
+ maxTVLDecimals: 6,
1423
+ allowedSources: ["vesu"],
1424
+ tags: [StrategyTag.META_VAULT]
1425
+ })
1426
+ ];