@gearbox-protocol/sdk 0.0.98 → 0.0.101

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 (86) hide show
  1. package/lib/apy/convexAPY.d.ts +8 -0
  2. package/lib/apy/convexAPY.js +202 -0
  3. package/lib/apy/lidoAPY.d.ts +4 -0
  4. package/lib/apy/lidoAPY.js +97 -0
  5. package/lib/config.d.ts +1 -0
  6. package/lib/config.js +2 -1
  7. package/lib/contracts/contracts.d.ts +6 -1
  8. package/lib/contracts/contracts.js +52 -14
  9. package/lib/contracts/contractsRegister.js +3 -3
  10. package/lib/core/constants.d.ts +4 -0
  11. package/lib/core/constants.js +8 -4
  12. package/lib/core/creditAccount.d.ts +2 -0
  13. package/lib/core/creditAccount.js +31 -30
  14. package/lib/core/creditManager.d.ts +13 -2
  15. package/lib/core/creditManager.js +79 -29
  16. package/lib/core/errors.d.ts +10 -0
  17. package/lib/core/errors.js +16 -1
  18. package/lib/core/events.js +9 -9
  19. package/lib/core/multicall.d.ts +1 -1
  20. package/lib/core/pool.d.ts +1 -1
  21. package/lib/core/pool.js +7 -5
  22. package/lib/core/price.d.ts +4 -0
  23. package/lib/core/price.js +12 -0
  24. package/lib/core/strategy.d.ts +34 -0
  25. package/lib/core/strategy.js +57 -0
  26. package/lib/index.d.ts +7 -1
  27. package/lib/index.js +8 -3
  28. package/lib/pathfinder/path.js +1 -1
  29. package/lib/pathfinder/yVault.js +7 -4
  30. package/lib/payload/creditAccount.d.ts +4 -26
  31. package/lib/payload/creditManager.d.ts +12 -24
  32. package/lib/payload/pool.d.ts +2 -17
  33. package/lib/payload/pool.js +0 -1
  34. package/lib/tokens/token.js +4 -4
  35. package/lib/utils/formatter.d.ts +1 -0
  36. package/lib/utils/formatter.js +6 -1
  37. package/lib/utils/mappers.d.ts +2 -1
  38. package/lib/utils/mappers.js +13 -5
  39. package/lib/utils/multicall.js +4 -3
  40. package/lib/utils/types.d.ts +1 -0
  41. package/package.json +1 -1
  42. package/src/apy/convexAPY.ts +249 -0
  43. package/src/apy/lidoAPY.ts +81 -0
  44. package/src/config.ts +2 -1
  45. package/src/contracts/contracts.ts +69 -16
  46. package/src/contracts/contractsRegister.ts +3 -3
  47. package/src/core/constants.ts +7 -3
  48. package/src/core/creditAccount.ts +39 -33
  49. package/src/core/creditManager.ts +230 -148
  50. package/src/core/errors.ts +24 -0
  51. package/src/core/events.ts +921 -915
  52. package/src/core/multicall.ts +1 -1
  53. package/src/core/pool.ts +56 -51
  54. package/src/core/price.ts +16 -0
  55. package/src/core/strategy.ts +123 -0
  56. package/src/index.ts +8 -1
  57. package/src/pathfinder/path.ts +154 -154
  58. package/src/pathfinder/yVault.ts +57 -56
  59. package/src/payload/creditAccount.ts +4 -26
  60. package/src/payload/creditManager.ts +13 -25
  61. package/src/payload/pool.ts +2 -19
  62. package/src/tokens/token.ts +10 -5
  63. package/src/utils/formatter.ts +5 -1
  64. package/src/utils/mappers.ts +12 -5
  65. package/src/utils/multicall.ts +4 -9
  66. package/src/utils/types.ts +6 -2
  67. package/lib/core/adapters.d.ts +0 -15
  68. package/lib/core/adapters.js +0 -19
  69. package/lib/core/contracts.d.ts +0 -67
  70. package/lib/core/contracts.js +0 -254
  71. package/lib/core/contractsRegister.d.ts +0 -2
  72. package/lib/core/contractsRegister.js +0 -58
  73. package/lib/core/creditCard.d.ts +0 -13
  74. package/lib/core/creditCard.js +0 -2
  75. package/lib/core/oracles.d.ts +0 -38
  76. package/lib/core/oracles.js +0 -12
  77. package/lib/core/priceFeeds.d.ts +0 -3
  78. package/lib/core/priceFeeds.js +0 -492
  79. package/lib/core/protocols.d.ts +0 -13
  80. package/lib/core/protocols.js +0 -39
  81. package/lib/core/swap.d.ts +0 -4
  82. package/lib/core/swap.js +0 -8
  83. package/lib/core/trade.d.ts +0 -35
  84. package/lib/core/trade.js +0 -62
  85. package/lib/core/tradeTypes.d.ts +0 -79
  86. package/lib/core/tradeTypes.js +0 -21
@@ -1,6 +1,6 @@
1
1
  import { BytesLike } from "ethers";
2
2
 
3
3
  export interface MultiCall {
4
- targetContract: string;
4
+ target: string;
5
5
  callData: BytesLike;
6
6
  }
package/src/core/pool.ts CHANGED
@@ -1,64 +1,69 @@
1
- import {BigNumber, Signer} from "ethers";
2
- import {IPoolService, IPoolService__factory} from "../types";
3
- import {PoolDataPayload} from "../payload/pool";
4
- import {rayToNumber} from "../utils/formatter";
1
+ import { BigNumber, Signer } from "ethers";
2
+
3
+ import { PoolDataPayload } from "../payload/pool";
4
+ import { rayToNumber } from "../utils/formatter";
5
+
6
+ import { IPoolService, IPoolService__factory } from "../types";
7
+
8
+ import { PERCENTAGE_DECIMALS } from "./constants";
5
9
 
6
10
  export class PoolData {
7
- public readonly id: string;
8
- public readonly address: string;
11
+ public readonly id: string;
12
+ public readonly address: string;
9
13
 
10
- public readonly underlyingToken: string;
11
- public readonly dieselToken: string;
12
- public readonly isWETH: boolean;
14
+ public readonly underlyingToken: string;
15
+ public readonly dieselToken: string;
16
+ public readonly isWETH: boolean;
13
17
 
14
- // Information
15
- public readonly expectedLiquidity: BigNumber;
16
- public readonly expectedLiquidityLimit: BigNumber;
17
- public readonly availableLiquidity: BigNumber;
18
- public readonly totalBorrowed: BigNumber;
19
- public readonly depositAPY: number;
20
- public readonly borrowAPY: number;
21
- public readonly borrowAPYRay: BigNumber;
22
- public readonly dieselRate: number;
23
- public readonly dieselRateRay: BigNumber;
24
- public readonly withdrawFee: number;
25
- public readonly timestampLU: BigNumber;
26
- public readonly cumulativeIndex_RAY: BigNumber;
18
+ // Information
19
+ public readonly expectedLiquidity: BigNumber;
20
+ public readonly expectedLiquidityLimit: BigNumber;
21
+ public readonly availableLiquidity: BigNumber;
22
+ public readonly totalBorrowed: BigNumber;
23
+ public readonly depositAPY: number;
24
+ public readonly borrowAPY: number;
25
+ public readonly borrowAPYRay: BigNumber;
26
+ public readonly dieselRate: number;
27
+ public readonly dieselRateRay: BigNumber;
28
+ public readonly withdrawFee: number;
29
+ public readonly timestampLU: BigNumber;
30
+ public readonly cumulativeIndex_RAY: BigNumber;
27
31
 
28
- constructor(payload: PoolDataPayload) {
29
- this.id = payload.addr;
30
- this.address = payload.addr;
31
- this.underlyingToken = payload.underlyingToken || "";
32
- this.dieselToken = payload.dieselToken || "";
32
+ constructor(payload: PoolDataPayload) {
33
+ this.id = payload.addr;
34
+ this.address = payload.addr;
35
+ this.underlyingToken = payload.underlying || "";
36
+ this.dieselToken = payload.dieselToken || "";
33
37
 
34
- this.isWETH = payload.isWETH || false;
38
+ this.isWETH = payload.isWETH || false;
35
39
 
36
- this.expectedLiquidity = BigNumber.from(payload.expectedLiquidity);
37
- this.expectedLiquidityLimit = BigNumber.from(
38
- payload.expectedLiquidityLimit || 0
39
- );
40
- this.availableLiquidity = BigNumber.from(payload.availableLiquidity);
41
- this.totalBorrowed = BigNumber.from(payload.totalBorrowed);
42
- this.depositAPY = rayToNumber(payload.depositAPY_RAY) * 100;
43
- this.borrowAPY = rayToNumber(payload.borrowAPY_RAY) * 100;
44
- this.borrowAPYRay = BigNumber.from(payload.borrowAPY_RAY);
45
- this.dieselRate = rayToNumber(payload.dieselRate_RAY);
46
- this.dieselRateRay = BigNumber.from(payload.dieselRate_RAY);
47
- this.withdrawFee = BigNumber.from(payload.withdrawFee).toNumber() / 100;
48
- this.timestampLU = BigNumber.from(payload.timestampLU || 0);
49
- this.cumulativeIndex_RAY = BigNumber.from(payload.cumulativeIndex_RAY || 0);
50
- }
40
+ this.expectedLiquidity = BigNumber.from(payload.expectedLiquidity);
41
+ this.expectedLiquidityLimit = BigNumber.from(
42
+ payload.expectedLiquidityLimit || 0
43
+ );
44
+ this.availableLiquidity = BigNumber.from(payload.availableLiquidity);
45
+ this.totalBorrowed = BigNumber.from(payload.totalBorrowed);
46
+ this.depositAPY = rayToNumber(payload.depositAPY_RAY) * PERCENTAGE_DECIMALS;
47
+ this.borrowAPY = rayToNumber(payload.borrowAPY_RAY) * PERCENTAGE_DECIMALS;
48
+ this.borrowAPYRay = BigNumber.from(payload.borrowAPY_RAY);
49
+ this.dieselRate = rayToNumber(payload.dieselRate_RAY);
50
+ this.dieselRateRay = BigNumber.from(payload.dieselRate_RAY);
51
+ this.withdrawFee =
52
+ BigNumber.from(payload.withdrawFee).toNumber() / PERCENTAGE_DECIMALS;
53
+ this.timestampLU = BigNumber.from(payload.timestampLU || 0);
54
+ this.cumulativeIndex_RAY = BigNumber.from(payload.cumulativeIndex_RAY || 0);
55
+ }
51
56
 
52
- getContractETH(signer: Signer): IPoolService {
53
- return IPoolService__factory.connect(this.address, signer);
54
- }
57
+ getContractETH(signer: Signer): IPoolService {
58
+ return IPoolService__factory.connect(this.address, signer);
59
+ }
55
60
 
56
- get isPaused(): boolean {
57
- return false;
58
- }
61
+ get isPaused(): boolean {
62
+ return false;
63
+ }
59
64
  }
60
65
 
61
66
  export interface PoolsStat {
62
- tvl: number;
63
- totalBorrowed: number;
67
+ tvl: number;
68
+ totalBorrowed: number;
64
69
  }
@@ -0,0 +1,16 @@
1
+ import { BigNumber } from "ethers";
2
+ import { TokenData } from "../tokens/tokenData";
3
+
4
+ export const PRICE_DECIMALS = 1000;
5
+
6
+ export const priceCalc = (
7
+ price: number,
8
+ amount: BigNumber,
9
+ token: TokenData | undefined
10
+ ) => {
11
+ const { decimals = 18 } = token || {};
12
+
13
+ return amount
14
+ .mul(Math.floor(PRICE_DECIMALS * price))
15
+ .div(BigNumber.from(10).pow(decimals));
16
+ };
@@ -0,0 +1,123 @@
1
+ import { LEVERAGE_DECIMALS } from "../core/constants";
2
+
3
+ export interface StrategyPayload {
4
+ apy?: number;
5
+
6
+ name: string;
7
+ lpToken: string;
8
+ pools: Array<string>;
9
+
10
+ unleveragableCollateral: Array<string>;
11
+ leveragableCollateral: Array<string>;
12
+
13
+ baseAssets: Array<string>;
14
+ }
15
+
16
+ interface PoolStats {
17
+ borrowRate: number;
18
+ }
19
+
20
+ type PoolList = Record<string, PoolStats>;
21
+
22
+ export class Strategy {
23
+ apy: number | undefined;
24
+
25
+ name: string;
26
+ lpToken: string;
27
+ pools: Array<string>;
28
+
29
+ unleveragableCollateral: Array<string>;
30
+ leveragableCollateral: Array<string>;
31
+
32
+ baseAssets: Array<string>;
33
+
34
+ constructor(payload: StrategyPayload) {
35
+ this.apy = payload.apy;
36
+
37
+ this.name = payload.name;
38
+ this.lpToken = payload.lpToken;
39
+ this.pools = payload.pools;
40
+ this.unleveragableCollateral = payload.unleveragableCollateral;
41
+ this.leveragableCollateral = payload.leveragableCollateral;
42
+ this.baseAssets = payload.baseAssets;
43
+ }
44
+
45
+ public roiMax(apy: number, maxLeverage: number, poolApy: PoolList) {
46
+ const minApy = this.minBorrowApy(poolApy);
47
+
48
+ return this.roi(apy, maxLeverage, maxLeverage - LEVERAGE_DECIMALS, minApy);
49
+ }
50
+
51
+ public overallAPY(
52
+ apy: number,
53
+ leverage: number,
54
+ depositCollateral: string,
55
+ borrowAPY: number
56
+ ) {
57
+ const farmLev = this.farmLev(leverage, depositCollateral);
58
+
59
+ return this.roi(apy, farmLev, leverage - LEVERAGE_DECIMALS, borrowAPY);
60
+ }
61
+
62
+ public liquidationPrice(
63
+ leverage: number,
64
+
65
+ ltStrategy: number,
66
+ ltCollateral: number,
67
+
68
+ depositCollateral: string
69
+ ) {
70
+ const farmLev = this.farmLev(leverage, depositCollateral);
71
+
72
+ return (
73
+ 1 -
74
+ (leverage - LEVERAGE_DECIMALS - ltCollateral * (leverage - farmLev)) /
75
+ (ltStrategy * farmLev)
76
+ );
77
+ }
78
+
79
+ public ltStrategyLP(maxLeverage: number) {
80
+ return 1 - LEVERAGE_DECIMALS / maxLeverage;
81
+ }
82
+
83
+ public maxLeverage(ltStrategyLP: number) {
84
+ const leverage = Math.floor(1 / (1 - ltStrategyLP));
85
+ return Math.floor(leverage * LEVERAGE_DECIMALS);
86
+ }
87
+
88
+ private roi(
89
+ apy: number,
90
+ farmLev: number,
91
+ debtLev: number,
92
+ borrowAPY: number
93
+ ) {
94
+ return (apy * farmLev - borrowAPY * debtLev) / LEVERAGE_DECIMALS;
95
+ }
96
+
97
+ private minBorrowApy(poolApy: PoolList) {
98
+ const apys = Object.values(poolApy).sort(
99
+ (a, b) => a.borrowRate - b.borrowRate
100
+ );
101
+
102
+ return apys.length > 0 ? apys[0].borrowRate : 0;
103
+ }
104
+
105
+ private farmLev(leverage: number, depositCollateral: string) {
106
+ return this.inBaseAssets(depositCollateral) ||
107
+ this.inLeveragableAssets(depositCollateral)
108
+ ? leverage
109
+ : leverage - LEVERAGE_DECIMALS;
110
+ }
111
+
112
+ private inBaseAssets(depositCollateral: string) {
113
+ return this.baseAssets.some(
114
+ c => c.toLowerCase() === depositCollateral.toLowerCase()
115
+ );
116
+ }
117
+
118
+ private inLeveragableAssets(depositCollateral: string) {
119
+ return this.leveragableCollateral.some(
120
+ c => c.toLowerCase() === depositCollateral.toLowerCase()
121
+ );
122
+ }
123
+ }
package/src/index.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export * from "./core/constants";
2
+ export * from "./core/price";
2
3
  export * from "./core/creditAccount";
3
4
  export * from "./core/creditManager";
4
5
  export * from "./core/creditSession";
5
6
  export * from "./contracts/contracts";
7
+ export * from "./core/eventOrTx";
6
8
  export * from "./core/events";
7
9
  export * from "./core/errors";
8
10
  export * from "./core/pool";
@@ -26,6 +28,7 @@ export * from "./utils/events";
26
28
  export * from "./utils/math";
27
29
  export * from "./payload/graphPayload";
28
30
  export * from "./types/index";
31
+ export * from "./core/strategy";
29
32
 
30
33
  export type { IDataCompressor, IWETHGateway } from "./types";
31
34
 
@@ -40,8 +43,12 @@ export * from "./tokens/gear";
40
43
  export * from "./tokens/normal";
41
44
  export * from "./tokens/yearn";
42
45
 
46
+ export * from "./apy/lidoAPY";
47
+ export * from "./apy/convexAPY";
48
+
43
49
  export * from "./core/history";
44
- export { MultiCallContract } from "./utils/multicall";
50
+ export * from "./utils/multicall";
51
+ export * from "./utils/types";
45
52
  export { callRepeater } from "./utils/repeater";
46
53
  export { getContractName } from "./contracts/contractsRegister";
47
54
  export { AdapterInterface } from "./contracts/adapters";
@@ -1,166 +1,166 @@
1
- import {BigNumber, ethers} from "ethers";
2
- import {CreditManagerData} from "../core/creditManager";
3
- import {MultiCall} from "../core/multicall";
1
+ import { BigNumber, ethers } from "ethers";
2
+ import { CreditManagerData } from "../core/creditManager";
3
+ import { MultiCall } from "../core/multicall";
4
4
  import {
5
- SupportedToken,
6
- supportedTokens,
7
- tokenSymbolByAddress
5
+ SupportedToken,
6
+ supportedTokens,
7
+ tokenSymbolByAddress
8
8
  } from "../tokens/token";
9
- import {NetworkType} from "../core/constants";
10
- import {CreditAccountData} from "../core/creditAccount";
11
-
12
- import {PathFinder__factory} from "../types";
13
- import {priority} from "./priority";
14
- import {YearnLPToken} from "../tokens/yearn";
15
- import {YearnVaultPathFinder} from "./yVault";
16
- import {ConvexLPPathFinder} from "./convexLP";
17
- import {CurvePathFinder} from "./curveLP";
18
- import {CurveLPToken} from "../tokens/curveLP";
19
- import {PartialRecord} from "../utils/types";
20
- import {detectNetwork} from "../utils/network";
21
- import {pathFindersByNetwork} from "./contracts";
22
- import {TokenType} from "../tokens/tokenType";
9
+ import { NetworkType } from "../core/constants";
10
+ import { CreditAccountData } from "../core/creditAccount";
11
+
12
+ import { PathFinder__factory } from "../types";
13
+ import { priority } from "./priority";
14
+ import { YearnLPToken } from "../tokens/yearn";
15
+ import { YearnVaultPathFinder } from "./yVault";
16
+ import { ConvexLPPathFinder } from "./convexLP";
17
+ import { CurvePathFinder } from "./curveLP";
18
+ import { CurveLPToken } from "../tokens/curveLP";
19
+ import { PartialRecord } from "../utils/types";
20
+ import { detectNetwork } from "../utils/network";
21
+ import { pathFindersByNetwork } from "./contracts";
22
+ import { TokenType } from "../tokens/tokenType";
23
23
 
24
24
  export class Path {
25
- public readonly calls: Array<MultiCall> = [];
26
- public readonly balances: PartialRecord<SupportedToken, BigNumber>;
27
- public readonly underlying: SupportedToken;
28
- public readonly creditManager: CreditManagerData;
29
- public readonly creditAccount: CreditAccountData;
30
- public readonly networkType: NetworkType;
31
- public readonly provider: ethers.providers.Provider;
32
- public totalGasLimit: number;
33
-
34
- constructor(opts: {
35
- balances: PartialRecord<SupportedToken, BigNumber>;
36
- underlying: SupportedToken;
37
- creditManager: CreditManagerData;
38
- creditAccount: CreditAccountData;
39
- networkType: NetworkType;
40
- provider: ethers.providers.Provider;
41
- totalGasLimit: number;
42
- }) {
43
- this.balances = opts.balances;
44
- this.underlying = opts.underlying;
45
- this.creditManager = opts.creditManager;
46
- this.creditAccount = opts.creditAccount;
47
- this.networkType = opts.networkType;
48
- this.provider = opts.provider;
49
- this.totalGasLimit = opts.totalGasLimit;
25
+ public readonly calls: Array<MultiCall> = [];
26
+ public readonly balances: PartialRecord<SupportedToken, BigNumber>;
27
+ public readonly underlying: SupportedToken;
28
+ public readonly creditManager: CreditManagerData;
29
+ public readonly creditAccount: CreditAccountData;
30
+ public readonly networkType: NetworkType;
31
+ public readonly provider: ethers.providers.Provider;
32
+ public totalGasLimit: number;
33
+
34
+ constructor(opts: {
35
+ balances: PartialRecord<SupportedToken, BigNumber>;
36
+ underlying: SupportedToken;
37
+ creditManager: CreditManagerData;
38
+ creditAccount: CreditAccountData;
39
+ networkType: NetworkType;
40
+ provider: ethers.providers.Provider;
41
+ totalGasLimit: number;
42
+ }) {
43
+ this.balances = opts.balances;
44
+ this.underlying = opts.underlying;
45
+ this.creditManager = opts.creditManager;
46
+ this.creditAccount = opts.creditAccount;
47
+ this.networkType = opts.networkType;
48
+ this.provider = opts.provider;
49
+ this.totalGasLimit = opts.totalGasLimit;
50
+ }
51
+
52
+ public popBalance(token: SupportedToken): BigNumber {
53
+ const currentBalance = this.balances[token];
54
+
55
+ if (currentBalance === undefined || currentBalance.gt(1))
56
+ return BigNumber.from(0);
57
+
58
+ this.balances[token] = BigNumber.from(1);
59
+ return currentBalance.sub(1);
60
+ }
61
+
62
+ private comparedByPriority(
63
+ [tokenA, _balanceA]: [string, BigNumber],
64
+ [tokenB, _balanceB]: [string, BigNumber]
65
+ ): number {
66
+ const priorityTokenA =
67
+ priority[supportedTokens[tokenA as SupportedToken].type];
68
+ const priorityTokenB =
69
+ priority[supportedTokens[tokenB as SupportedToken].type];
70
+
71
+ if (priorityTokenA > priorityTokenB) {
72
+ return -1;
73
+ } else if (priorityTokenA < priorityTokenB) {
74
+ return 1;
50
75
  }
51
-
52
- public popBalance(token: SupportedToken): BigNumber {
53
- const currentBalance = this.balances[token];
54
-
55
- if (currentBalance === undefined || currentBalance.gt(1))
56
- return BigNumber.from(0);
57
-
58
- this.balances[token] = BigNumber.from(1);
59
- return currentBalance.sub(1);
76
+ return 0;
77
+ }
78
+
79
+ static async findBestPath(
80
+ creditAccount: CreditAccountData,
81
+ creditManager: CreditManagerData,
82
+ provider: ethers.providers.Provider
83
+ ) {
84
+ const networkType = await detectNetwork(provider);
85
+
86
+ const balances = Object.entries(creditAccount.balances)
87
+ .map(([address, balance]) => ({
88
+ token: tokenSymbolByAddress[address.toLowerCase()],
89
+ balance
90
+ }))
91
+ .filter(t => t.balance.gt(1))
92
+ .reduce(
93
+ (obj, curValue) => ({ ...obj, [curValue.token]: curValue.balance }),
94
+ {}
95
+ );
96
+
97
+ const initialPath = new Path({
98
+ balances,
99
+ creditAccount,
100
+ creditManager,
101
+ networkType,
102
+ provider,
103
+ underlying: "DAI", // creditManager.underlyingToken
104
+ totalGasLimit: 0
105
+ });
106
+
107
+ const lpPaths = await initialPath.withdrawTokens();
108
+ const pathFinder = PathFinder__factory.connect(
109
+ pathFindersByNetwork[networkType].PATH_FINDER,
110
+ provider
111
+ );
112
+
113
+ console.log(lpPaths);
114
+ console.log(pathFinder);
115
+ // const bestPath = await pathFinder.bestPath();
116
+ }
117
+
118
+ async withdrawTokens(): Promise<Array<Path>> {
119
+ const existingTokens = Object.entries(this.balances)
120
+ .filter(([_token, balance]) => balance.gt(1))
121
+ .sort(this.comparedByPriority);
122
+
123
+ // TODO: Add checks for lenght
124
+ if (existingTokens.length === 0)
125
+ throw new Error("No tokens with balance >1");
126
+
127
+ const nextToken = existingTokens[0][0] as SupportedToken;
128
+ let lpPathFinder: LPWithdrawPathFinder;
129
+ // Get balances and keep non-zero only
130
+ // Find token with highest priority
131
+ // Get token type of this token
132
+ switch (supportedTokens[nextToken].type) {
133
+ case TokenType.NORMAL_TOKEN:
134
+ case TokenType.CONNECTOR:
135
+ return [this];
136
+
137
+ case TokenType.YEARN_VAULT_OF_CURVE_LP:
138
+ case TokenType.YEARN_VAULT_OF_META_CURVE_LP:
139
+ case TokenType.YEARN_VAULT:
140
+ lpPathFinder = new YearnVaultPathFinder(nextToken as YearnLPToken);
141
+ break;
142
+
143
+ case TokenType.CONVEX_LP_TOKEN:
144
+ lpPathFinder = new ConvexLPPathFinder();
145
+ break;
146
+
147
+ case TokenType.META_CURVE_LP:
148
+ case TokenType.CURVE_LP:
149
+ lpPathFinder = new CurvePathFinder(nextToken as CurveLPToken);
150
+ break;
151
+
152
+ default:
153
+ throw new Error("Token type not supported yet");
60
154
  }
61
155
 
62
- private comparedByPriority(
63
- [tokenA, _balanceA]: [string, BigNumber],
64
- [tokenB, _balanceB]: [string, BigNumber]
65
- ): number {
66
- const priorityTokenA =
67
- priority[supportedTokens[tokenA as SupportedToken].type];
68
- const priorityTokenB =
69
- priority[supportedTokens[tokenB as SupportedToken].type];
70
-
71
- if (priorityTokenA > priorityTokenB) {
72
- return -1;
73
- } else if (priorityTokenA < priorityTokenB) {
74
- return 1;
75
- }
76
- return 0;
77
- }
156
+ return await lpPathFinder.findWithdrawPaths(this);
157
+ }
78
158
 
79
- static async findBestPath(
80
- creditAccount: CreditAccountData,
81
- creditManager: CreditManagerData,
82
- provider: ethers.providers.Provider
83
- ) {
84
- const networkType = await detectNetwork(provider);
85
-
86
- const balances = Object.entries(creditAccount.balances)
87
- .map(([address, balance]) => ({
88
- token: tokenSymbolByAddress[address.toLowerCase()],
89
- balance
90
- }))
91
- .filter(t => t.balance.gt(1))
92
- .reduce(
93
- (obj, curValue) => ({...obj, [curValue.token]: curValue.balance}),
94
- {}
95
- );
96
-
97
- const initialPath = new Path({
98
- balances,
99
- creditAccount,
100
- creditManager,
101
- networkType,
102
- provider,
103
- underlying: "DAI", // creditManager.underlyingToken
104
- totalGasLimit: 0
105
- });
106
-
107
- const lpPaths = await initialPath.withdrawTokens();
108
- const pathFinder = PathFinder__factory.connect(
109
- pathFindersByNetwork[networkType].PATH_FINDER,
110
- provider
111
- );
112
-
113
- console.log(lpPaths);
114
- console.log(pathFinder);
115
- // const bestPath = await pathFinder.bestPath();
116
- }
117
-
118
- async withdrawTokens(): Promise<Array<Path>> {
119
- const existingTokens = Object.entries(this.balances)
120
- .filter(([_token, balance]) => balance.gt(1))
121
- .sort(this.comparedByPriority);
122
-
123
- // TODO: Add checks for lenght
124
- if (existingTokens.length === 0)
125
- throw new Error("No tokens with balance >1");
126
-
127
- const nextToken = existingTokens.at(0)![0] as SupportedToken;
128
- let lpPathFinder: LPWithdrawPathFinder;
129
- // Get balances and keep non-zero only
130
- // Find token with highest priority
131
- // Get token type of this token
132
- switch (supportedTokens[nextToken].type) {
133
- case TokenType.NORMAL_TOKEN:
134
- case TokenType.CONNECTOR:
135
- return [this];
136
-
137
- case TokenType.YEARN_VAULT_OF_CURVE_LP:
138
- case TokenType.YEARN_VAULT_OF_META_CURVE_LP:
139
- case TokenType.YEARN_VAULT:
140
- lpPathFinder = new YearnVaultPathFinder(nextToken as YearnLPToken);
141
- break;
142
-
143
- case TokenType.CONVEX_LP_TOKEN:
144
- lpPathFinder = new ConvexLPPathFinder();
145
- break;
146
-
147
- case TokenType.META_CURVE_LP:
148
- case TokenType.CURVE_LP:
149
- lpPathFinder = new CurvePathFinder(nextToken as CurveLPToken);
150
- break;
151
-
152
- default:
153
- throw new Error("Token type not supported yet");
154
- }
155
-
156
- return await lpPathFinder.findWithdrawPaths(this);
157
- }
158
-
159
- clone(): Path {
160
- return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
161
- }
159
+ clone(): Path {
160
+ return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
161
+ }
162
162
  }
163
163
 
164
164
  export interface LPWithdrawPathFinder {
165
- findWithdrawPaths(p: Path): Promise<Array<Path>>;
165
+ findWithdrawPaths(p: Path): Promise<Array<Path>>;
166
166
  }