@strkfarm/sdk 2.0.0-dev.4 → 2.0.0-dev.40

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