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

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