@gearbox-protocol/sdk 0.0.100 → 0.0.103

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 (163) hide show
  1. package/.eslintignore +4 -0
  2. package/.eslintrc.js +52 -0
  3. package/.husky/pre-push +4 -0
  4. package/lib/apy/convexAPY.d.ts +8 -0
  5. package/lib/apy/convexAPY.js +200 -0
  6. package/lib/apy/lidoAPY.d.ts +4 -0
  7. package/lib/apy/lidoAPY.js +103 -0
  8. package/lib/config.d.ts +1 -0
  9. package/lib/config.js +2 -1
  10. package/lib/contracts/contracts.d.ts +9 -4
  11. package/lib/contracts/contracts.js +52 -14
  12. package/lib/contracts/contractsRegister.js +16 -4
  13. package/lib/core/constants.d.ts +7 -1
  14. package/lib/core/constants.js +11 -5
  15. package/lib/core/creditAccount.d.ts +3 -1
  16. package/lib/core/creditAccount.js +33 -31
  17. package/lib/core/creditManager.d.ts +13 -2
  18. package/lib/core/creditManager.js +77 -33
  19. package/lib/core/creditSession.js +14 -3
  20. package/lib/core/errors.d.ts +10 -0
  21. package/lib/core/errors.js +16 -1
  22. package/lib/core/eventOrTx.d.ts +1 -1
  23. package/lib/core/events.d.ts +19 -19
  24. package/lib/core/events.js +32 -30
  25. package/lib/core/multicall.d.ts +1 -1
  26. package/lib/core/pool.d.ts +2 -2
  27. package/lib/core/pool.js +8 -12
  28. package/lib/core/price.d.ts +2 -0
  29. package/lib/core/price.js +14 -0
  30. package/lib/core/strategy.d.ts +36 -0
  31. package/lib/core/strategy.js +57 -0
  32. package/lib/core/tokenDistributor.js +1 -1
  33. package/lib/core/transactions.d.ts +18 -3
  34. package/lib/core/transactions.js +39 -3
  35. package/lib/index.d.ts +8 -3
  36. package/lib/index.js +9 -4
  37. package/lib/oracles/priceFeeds.js +1 -1
  38. package/lib/pathfinder/convexLP.d.ts +1 -1
  39. package/lib/pathfinder/convexLP.js +26 -29
  40. package/lib/pathfinder/curveLP.d.ts +1 -1
  41. package/lib/pathfinder/curveLP.js +5 -7
  42. package/lib/pathfinder/path.d.ts +1 -1
  43. package/lib/pathfinder/path.js +38 -42
  44. package/lib/pathfinder/trade.d.ts +1 -2
  45. package/lib/pathfinder/tradeTypes.d.ts +5 -5
  46. package/lib/pathfinder/yVault.d.ts +2 -2
  47. package/lib/pathfinder/yVault.js +22 -19
  48. package/lib/payload/creditAccount.d.ts +4 -26
  49. package/lib/payload/creditManager.d.ts +3 -25
  50. package/lib/payload/pool.d.ts +2 -17
  51. package/lib/payload/pool.js +0 -1
  52. package/lib/strategies/curve.d.ts +6 -60
  53. package/lib/strategies/curve.js +6 -0
  54. package/lib/strategies/uniswapV2.js +3 -19
  55. package/lib/strategies/uniswapV3.js +1 -1
  56. package/lib/strategies/yearn.js +15 -11
  57. package/lib/tokens/convex.d.ts +3 -3
  58. package/lib/tokens/curveLP.d.ts +2 -2
  59. package/lib/tokens/curveLP.js +1 -1
  60. package/lib/tokens/gear.d.ts +2 -2
  61. package/lib/tokens/gear.js +1 -1
  62. package/lib/tokens/normal.d.ts +1 -1
  63. package/lib/tokens/token.js +9 -9
  64. package/lib/tokens/tokenData.d.ts +3 -1
  65. package/lib/tokens/tokenData.js +10 -8
  66. package/lib/tokens/yearn.d.ts +3 -3
  67. package/lib/utils/errors.d.ts +6 -0
  68. package/lib/utils/errors.js +13 -0
  69. package/lib/utils/formatter.d.ts +2 -1
  70. package/lib/utils/formatter.js +23 -15
  71. package/lib/utils/loading.d.ts +2 -1
  72. package/lib/utils/loading.js +9 -13
  73. package/lib/utils/mappers.d.ts +2 -1
  74. package/lib/utils/mappers.js +13 -5
  75. package/lib/utils/multicall.js +4 -3
  76. package/lib/utils/network.js +2 -2
  77. package/lib/utils/repeater.js +12 -24
  78. package/lib/utils/types.d.ts +1 -0
  79. package/lib/utils/validate.js +1 -1
  80. package/package.json +26 -8
  81. package/src/apy/convexAPY.ts +250 -0
  82. package/src/apy/lidoAPY.ts +89 -0
  83. package/src/config.ts +2 -1
  84. package/src/contracts/contracts.ts +73 -19
  85. package/src/contracts/contractsRegister.ts +19 -4
  86. package/src/core/constants.ts +11 -4
  87. package/src/core/creditAccount.ts +69 -37
  88. package/src/core/creditManager.ts +256 -148
  89. package/src/core/creditOperation.ts +7 -7
  90. package/src/core/creditSession.ts +25 -5
  91. package/src/core/errors.ts +25 -0
  92. package/src/core/eventOrTx.ts +8 -5
  93. package/src/core/events.ts +978 -911
  94. package/src/core/history.ts +46 -46
  95. package/src/core/multicall.ts +1 -1
  96. package/src/core/operations.ts +6 -0
  97. package/src/core/pool.ts +75 -58
  98. package/src/core/price.ts +13 -0
  99. package/src/core/strategy.ts +134 -0
  100. package/src/core/tokenDistributor.ts +2 -2
  101. package/src/core/transactions.ts +427 -350
  102. package/src/index.ts +9 -4
  103. package/src/oracles/priceFeeds.ts +523 -523
  104. package/src/pathfinder/contracts.ts +15 -13
  105. package/src/pathfinder/convexLP.ts +29 -25
  106. package/src/pathfinder/curveLP.ts +57 -53
  107. package/src/pathfinder/path.ts +158 -150
  108. package/src/pathfinder/priority.ts +11 -11
  109. package/src/pathfinder/trade.ts +84 -77
  110. package/src/pathfinder/tradeTypes.ts +98 -94
  111. package/src/pathfinder/yVault.ts +79 -63
  112. package/src/payload/creditAccount.ts +4 -26
  113. package/src/payload/creditManager.ts +4 -26
  114. package/src/payload/pool.ts +2 -19
  115. package/src/payload/token.ts +3 -3
  116. package/src/strategies/convex.ts +217 -210
  117. package/src/strategies/creditFacade.ts +70 -53
  118. package/src/strategies/curve.ts +263 -194
  119. package/src/strategies/lido.ts +33 -37
  120. package/src/strategies/uniswapV2.ts +90 -112
  121. package/src/strategies/uniswapV3.ts +114 -91
  122. package/src/strategies/yearn.ts +58 -62
  123. package/src/tokens/connectors.ts +6 -6
  124. package/src/tokens/convex.ts +297 -296
  125. package/src/tokens/curveLP.ts +170 -165
  126. package/src/tokens/gear.ts +47 -45
  127. package/src/tokens/normal.ts +801 -802
  128. package/src/tokens/token.ts +19 -10
  129. package/src/tokens/tokenData.ts +19 -9
  130. package/src/tokens/tokenType.ts +11 -11
  131. package/src/tokens/yearn.ts +126 -124
  132. package/src/utils/errors.ts +11 -0
  133. package/src/utils/formatter.ts +26 -18
  134. package/src/utils/loading.ts +14 -6
  135. package/src/utils/mappers.ts +15 -6
  136. package/src/utils/multicall.ts +6 -9
  137. package/src/utils/network.ts +21 -21
  138. package/src/utils/repeater.ts +2 -2
  139. package/src/utils/types.ts +6 -2
  140. package/src/utils/validate.ts +1 -1
  141. package/lib/core/adapters.d.ts +0 -15
  142. package/lib/core/adapters.js +0 -19
  143. package/lib/core/contracts.d.ts +0 -67
  144. package/lib/core/contracts.js +0 -254
  145. package/lib/core/contractsRegister.d.ts +0 -2
  146. package/lib/core/contractsRegister.js +0 -58
  147. package/lib/core/creditCard.d.ts +0 -13
  148. package/lib/core/creditCard.js +0 -2
  149. package/lib/core/oracles.d.ts +0 -38
  150. package/lib/core/oracles.js +0 -12
  151. package/lib/core/priceFeeds.d.ts +0 -3
  152. package/lib/core/priceFeeds.js +0 -492
  153. package/lib/core/protocols.d.ts +0 -13
  154. package/lib/core/protocols.js +0 -39
  155. package/lib/core/swap.d.ts +0 -4
  156. package/lib/core/swap.js +0 -8
  157. package/lib/core/trade.d.ts +0 -35
  158. package/lib/core/trade.js +0 -62
  159. package/lib/core/tradeTypes.d.ts +0 -79
  160. package/lib/core/tradeTypes.js +0 -21
  161. package/lib/utils/events.d.ts +0 -2
  162. package/lib/utils/events.js +0 -13
  163. package/src/utils/events.ts +0 -10
@@ -1,17 +1,19 @@
1
- import {NetworkType} from "../core/constants";
1
+ import { NetworkType } from "../core/constants";
2
2
 
3
3
  export type PathFinderContracts = "PATH_FINDER" | "CONVEX_PATH_FINDER";
4
4
 
5
- export const pathFindersByNetwork: Record<NetworkType,
6
- Record<PathFinderContracts, string>> = {
7
- Mainnet: {
8
- // PATH_FINDER
9
- PATH_FINDER: "",
10
- CONVEX_PATH_FINDER: ""
11
- },
12
- Kovan: {
13
- // PATH_FINDER
14
- PATH_FINDER: "",
15
- CONVEX_PATH_FINDER: ""
16
- }
5
+ export const pathFindersByNetwork: Record<
6
+ NetworkType,
7
+ Record<PathFinderContracts, string>
8
+ > = {
9
+ Mainnet: {
10
+ // PATH_FINDER
11
+ PATH_FINDER: "",
12
+ CONVEX_PATH_FINDER: ""
13
+ },
14
+ Kovan: {
15
+ // PATH_FINDER
16
+ PATH_FINDER: "",
17
+ CONVEX_PATH_FINDER: ""
18
+ }
17
19
  };
@@ -1,33 +1,37 @@
1
- import {LPWithdrawPathFinder, Path} from "./path";
2
- import {ConvexLPToken, convexTokens} from "../tokens/convex";
1
+ import { convexTokens } from "../tokens/convex";
2
+ import { objectEntries } from "../utils/mappers";
3
+ import type { LPWithdrawPathFinder, Path } from "./path";
3
4
 
4
5
  export class ConvexLPPathFinder implements LPWithdrawPathFinder {
5
- async findWithdrawPaths(p: Path): Promise<Array<Path>> {
6
- const pids = new Set<number>();
7
-
8
- for (let [cvxToken, tokenData] of Object.entries(convexTokens)) {
9
- const currentBalance = p.popBalance(cvxToken as ConvexLPToken);
10
- if (currentBalance.gt(1)) {
11
- pids.add(tokenData.pid);
12
- }
6
+ // eslint-disable-next-line class-methods-use-this
7
+ async findWithdrawPaths(p: Path): Promise<Array<Path>> {
8
+ const pids = objectEntries(convexTokens).reduce(
9
+ (acc, [cvxToken, tokenData]) => {
10
+ const currentBalance = p.popBalance(cvxToken);
11
+ if (currentBalance.gt(1)) {
12
+ pids.add(tokenData.pid);
13
13
  }
14
+ return acc;
15
+ },
16
+ new Set<number>()
17
+ );
14
18
 
15
- // const convexPathFinder = ConvexPathFinder__factory.connect(
16
- // pathFindersByNetwork[p.networkType].CONVEX_PATH_FINDER,
17
- // p.provider
18
- // );
19
+ // const convexPathFinder = ConvexPathFinder__factory.connect(
20
+ // pathFindersByNetwork[p.networkType].CONVEX_PATH_FINDER,
21
+ // p.provider
22
+ // );
19
23
 
20
- // const tokenBalances = await convexPathFinder.calcRewards(
21
- // p.creditAccount.addr,
22
- // Array.from(pids)
23
- // );
24
+ // const tokenBalances = await convexPathFinder.calcRewards(
25
+ // p.creditAccount.addr,
26
+ // Array.from(pids)
27
+ // );
24
28
 
25
- // for (let balance of tokenBalances) {
26
- // p.balances[balance.token] = p.balances[balance.token].add(
27
- // balance.balance
28
- // );
29
- // }
29
+ // for (let balance of tokenBalances) {
30
+ // p.balances[balance.token] = p.balances[balance.token].add(
31
+ // balance.balance
32
+ // );
33
+ // }
30
34
 
31
- return await p.withdrawTokens();
32
- }
35
+ return p.withdrawTokens();
36
+ }
33
37
  }
@@ -1,71 +1,75 @@
1
- import {LPWithdrawPathFinder, Path} from "./path";
2
- import {CurveLPToken, curveTokens} from "../tokens/curveLP";
3
- import {contractParams, contractsByAddress, CurveParams, CurvePoolContract} from "../contracts/contracts";
4
- import {TradeType} from "./tradeTypes";
5
- import {CallData, MultiCallContract} from "../utils/multicall";
6
- import {ICurvePool__factory} from "../types";
7
- import {ICurvePoolInterface} from "../types/contracts/integrations/curve/ICurvePool";
8
- import {BigNumber} from "ethers";
1
+ import { BigNumber } from "ethers";
2
+ import type { LPWithdrawPathFinder, Path } from "./path";
3
+ import { CurveLPToken, curveTokens } from "../tokens/curveLP";
4
+ import {
5
+ contractParams,
6
+ contractsByAddress,
7
+ CurveParams,
8
+ CurvePoolContract
9
+ } from "../contracts/contracts";
10
+ import { TradeType } from "./tradeTypes";
11
+ import { CallData, MultiCallContract } from "../utils/multicall";
12
+ import { ICurvePool__factory } from "../types";
13
+ import { ICurvePoolInterface } from "../types/contracts/integrations/curve/ICurvePool";
9
14
 
10
15
  export class CurvePathFinder implements LPWithdrawPathFinder {
11
- lpToken: CurveLPToken;
12
- contract: CurvePoolContract;
16
+ lpToken: CurveLPToken;
13
17
 
14
- constructor(token: CurveLPToken) {
15
- this.lpToken = token;
16
- const curvePools = curveTokens[this.lpToken].lpActions.filter(
17
- a => a.type == TradeType.CurveWithdrawLP
18
- );
18
+ contract: CurvePoolContract;
19
19
 
20
- if (curvePools.length !== 1) throw new Error("Cant find Withdrawer");
20
+ constructor(token: CurveLPToken) {
21
+ this.lpToken = token;
22
+ const curvePools = curveTokens[this.lpToken].lpActions.filter(
23
+ a => a.type === TradeType.CurveWithdrawLP
24
+ );
21
25
 
22
- this.contract = curvePools[0].contract as CurvePoolContract;
26
+ if (curvePools.length !== 1) throw new Error("Cant find Withdrawer");
23
27
 
24
- const wrapper = (contractParams[curvePools[0].contract] as CurveParams)
25
- .wrapper;
28
+ this.contract = curvePools[0].contract as CurvePoolContract;
26
29
 
27
- if (wrapper) {
28
- this.contract = wrapper;
29
- }
30
- }
30
+ const { wrapper } = contractParams[curvePools[0].contract] as CurveParams;
31
31
 
32
- async findWithdrawPaths(p: Path): Promise<Array<Path>> {
33
- const coins = (contractParams[this.contract] as CurveParams).tokens;
34
- const nCoins = coins.length;
32
+ if (wrapper) {
33
+ this.contract = wrapper;
34
+ }
35
+ }
35
36
 
36
- const lpBalance = p.popBalance(this.lpToken);
37
+ async findWithdrawPaths(p: Path): Promise<Array<Path>> {
38
+ const coins = (contractParams[this.contract] as CurveParams).tokens;
39
+ const nCoins = coins.length;
37
40
 
38
- const multiCallContract = new MultiCallContract(
39
- contractsByAddress[this.contract],
40
- ICurvePool__factory.createInterface(),
41
- p.provider
42
- );
41
+ const lpBalance = p.popBalance(this.lpToken);
43
42
 
44
- const data: Array<CallData<ICurvePoolInterface>> = [];
43
+ const multiCallContract = new MultiCallContract(
44
+ contractsByAddress[this.contract],
45
+ ICurvePool__factory.createInterface(),
46
+ p.provider
47
+ );
45
48
 
46
- for (let i = 0; i < nCoins; i++) {
47
- data.push({
48
- // @ts-ignore
49
- method: "calc_withdraw_one_coin(uint256,int128)",
50
- params: [lpBalance, i]
51
- });
52
- }
49
+ const data: Array<CallData<ICurvePoolInterface>> = [];
53
50
 
54
- const balances = await multiCallContract.call<Array<BigNumber>>(data);
51
+ for (let i = 0; i < nCoins; i += 1) {
52
+ data.push({
53
+ method: "calc_withdraw_one_coin(uint256,int128)",
54
+ params: [lpBalance, i]
55
+ });
56
+ }
55
57
 
56
- console.log(balances)
58
+ const balances = await multiCallContract.call<Array<BigNumber>>(data);
57
59
 
58
- const paths: Array<Path> = [];
59
- for (let i = 0; i < nCoins; i++) {
60
- const newPath = p.clone();
61
- // newPath.balances[coins[i]] = newPath.balances[coins[i]].add(balances[i]);
62
- // newPath.calls.push({
63
- // targetContract: contractsByNetwork[p.networkType][this.contract],
64
- // callData: ICurveV1Adapter__factory.createInterface().encodeFunctionData("remove_all_liquidity_one_coin", [i])
65
- // })
66
- paths.push(newPath);
67
- }
60
+ console.debug(balances);
68
61
 
69
- return paths;
62
+ const paths: Array<Path> = [];
63
+ for (let i = 0; i < nCoins; i += 1) {
64
+ const newPath = p.clone();
65
+ // newPath.balances[coins[i]] = newPath.balances[coins[i]].add(balances[i]);
66
+ // newPath.calls.push({
67
+ // targetContract: contractsByNetwork[p.networkType][this.contract],
68
+ // callData: ICurveV1Adapter__factory.createInterface().encodeFunctionData("remove_all_liquidity_one_coin", [i])
69
+ // })
70
+ paths.push(newPath);
70
71
  }
72
+
73
+ return paths;
74
+ }
71
75
  }
@@ -1,166 +1,174 @@
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;
50
- }
25
+ public readonly calls: Array<MultiCall> = [];
51
26
 
52
- public popBalance(token: SupportedToken): BigNumber {
53
- const currentBalance = this.balances[token];
27
+ public readonly balances: PartialRecord<SupportedToken, BigNumber>;
54
28
 
55
- if (currentBalance === undefined || currentBalance.gt(1))
56
- return BigNumber.from(0);
29
+ public readonly underlying: SupportedToken;
57
30
 
58
- this.balances[token] = BigNumber.from(1);
59
- return currentBalance.sub(1);
60
- }
31
+ public readonly creditManager: CreditManagerData;
61
32
 
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
- }
33
+ public readonly creditAccount: CreditAccountData;
78
34
 
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
- }
35
+ public readonly networkType: NetworkType;
117
36
 
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
- }
37
+ public readonly provider: ethers.providers.Provider;
38
+
39
+ public totalGasLimit: number;
40
+
41
+ constructor(opts: {
42
+ balances: PartialRecord<SupportedToken, BigNumber>;
43
+ underlying: SupportedToken;
44
+ creditManager: CreditManagerData;
45
+ creditAccount: CreditAccountData;
46
+ networkType: NetworkType;
47
+ provider: ethers.providers.Provider;
48
+ totalGasLimit: number;
49
+ }) {
50
+ this.balances = opts.balances;
51
+ this.underlying = opts.underlying;
52
+ this.creditManager = opts.creditManager;
53
+ this.creditAccount = opts.creditAccount;
54
+ this.networkType = opts.networkType;
55
+ this.provider = opts.provider;
56
+ this.totalGasLimit = opts.totalGasLimit;
57
+ }
58
+
59
+ public popBalance(token: SupportedToken): BigNumber {
60
+ const currentBalance = this.balances[token];
158
61
 
159
- clone(): Path {
160
- return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
62
+ if (currentBalance === undefined || currentBalance.gt(1))
63
+ return BigNumber.from(0);
64
+
65
+ this.balances[token] = BigNumber.from(1);
66
+ return currentBalance.sub(1);
67
+ }
68
+
69
+ private static comparedByPriority(
70
+ [tokenA]: [string, BigNumber],
71
+ [tokenB]: [string, BigNumber]
72
+ ): number {
73
+ const priorityTokenA =
74
+ priority[supportedTokens[tokenA as SupportedToken].type];
75
+ const priorityTokenB =
76
+ priority[supportedTokens[tokenB as SupportedToken].type];
77
+
78
+ if (priorityTokenA > priorityTokenB) {
79
+ return -1;
80
+ }
81
+ if (priorityTokenA < priorityTokenB) {
82
+ return 1;
161
83
  }
84
+ return 0;
85
+ }
86
+
87
+ static async findBestPath(
88
+ creditAccount: CreditAccountData,
89
+ creditManager: CreditManagerData,
90
+ provider: ethers.providers.Provider
91
+ ) {
92
+ const networkType = await detectNetwork(provider);
93
+
94
+ const balances = Object.entries(creditAccount.balances)
95
+ .map(([address, balance]) => ({
96
+ token: tokenSymbolByAddress[address.toLowerCase()],
97
+ balance
98
+ }))
99
+ .filter(t => t.balance.gt(1))
100
+ .reduce(
101
+ (obj, curValue) => ({ ...obj, [curValue.token]: curValue.balance }),
102
+ {}
103
+ );
104
+
105
+ const initialPath = new Path({
106
+ balances,
107
+ creditAccount,
108
+ creditManager,
109
+ networkType,
110
+ provider,
111
+ underlying: "DAI", // creditManager.underlyingToken
112
+ totalGasLimit: 0
113
+ });
114
+
115
+ const lpPaths = await initialPath.withdrawTokens();
116
+ const pathFinder = PathFinder__factory.connect(
117
+ pathFindersByNetwork[networkType].PATH_FINDER,
118
+ provider
119
+ );
120
+
121
+ console.debug(lpPaths);
122
+ console.debug(pathFinder);
123
+ // const bestPath = await pathFinder.bestPath();
124
+ }
125
+
126
+ async withdrawTokens(): Promise<Array<Path>> {
127
+ const existingTokens = Object.entries(this.balances)
128
+ .filter(([, balance]) => balance.gt(1))
129
+ .sort(Path.comparedByPriority);
130
+
131
+ // TODO: Add checks for lenght
132
+ if (existingTokens.length === 0)
133
+ throw new Error("No tokens with balance >1");
134
+
135
+ const nextToken = existingTokens[0][0] as SupportedToken;
136
+ let lpPathFinder: LPWithdrawPathFinder;
137
+ // Get balances and keep non-zero only
138
+ // Find token with highest priority
139
+ // Get token type of this token
140
+ switch (supportedTokens[nextToken].type) {
141
+ case TokenType.NORMAL_TOKEN:
142
+ case TokenType.CONNECTOR:
143
+ return [this];
144
+
145
+ case TokenType.YEARN_VAULT_OF_CURVE_LP:
146
+ case TokenType.YEARN_VAULT_OF_META_CURVE_LP:
147
+ case TokenType.YEARN_VAULT:
148
+ lpPathFinder = new YearnVaultPathFinder(nextToken as YearnLPToken);
149
+ break;
150
+
151
+ case TokenType.CONVEX_LP_TOKEN:
152
+ lpPathFinder = new ConvexLPPathFinder();
153
+ break;
154
+
155
+ case TokenType.META_CURVE_LP:
156
+ case TokenType.CURVE_LP:
157
+ lpPathFinder = new CurvePathFinder(nextToken as CurveLPToken);
158
+ break;
159
+
160
+ default:
161
+ throw new Error("Token type not supported yet");
162
+ }
163
+
164
+ return lpPathFinder.findWithdrawPaths(this);
165
+ }
166
+
167
+ clone(): Path {
168
+ return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
169
+ }
162
170
  }
163
171
 
164
172
  export interface LPWithdrawPathFinder {
165
- findWithdrawPaths(p: Path): Promise<Array<Path>>;
173
+ findWithdrawPaths(p: Path): Promise<Array<Path>>;
166
174
  }
@@ -1,14 +1,14 @@
1
- import {TokenType} from "../tokens/tokenType";
1
+ import { TokenType } from "../tokens/tokenType";
2
2
 
3
3
  export const priority: Record<TokenType, number> = {
4
- [TokenType.CONNECTOR]: 1,
5
- [TokenType.NORMAL_TOKEN]: 2,
6
- [TokenType.CURVE_LP]: 3,
7
- [TokenType.YEARN_VAULT]: 3,
8
- [TokenType.META_CURVE_LP]: 4,
9
- [TokenType.YEARN_VAULT_OF_CURVE_LP]: 4,
10
- [TokenType.CONVEX_LP_TOKEN]: 5,
11
- [TokenType.YEARN_VAULT_OF_META_CURVE_LP]: 5,
12
- [TokenType.CONVEX_STAKED_PHANTOM_TOKEN]: 5,
13
- [TokenType.DIESEL_LP_TOKEN]: 6
4
+ [TokenType.CONNECTOR]: 1,
5
+ [TokenType.NORMAL_TOKEN]: 2,
6
+ [TokenType.CURVE_LP]: 3,
7
+ [TokenType.YEARN_VAULT]: 3,
8
+ [TokenType.META_CURVE_LP]: 4,
9
+ [TokenType.YEARN_VAULT_OF_CURVE_LP]: 4,
10
+ [TokenType.CONVEX_LP_TOKEN]: 5,
11
+ [TokenType.YEARN_VAULT_OF_META_CURVE_LP]: 5,
12
+ [TokenType.CONVEX_STAKED_PHANTOM_TOKEN]: 5,
13
+ [TokenType.DIESEL_LP_TOKEN]: 6
14
14
  };