@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
@@ -3,8 +3,14 @@ import {
3
3
  CreditAccountDataExtendedPayload,
4
4
  CreditAccountDataPayload
5
5
  } from "../payload/creditAccount";
6
- import { PERCENTAGE_FACTOR, RAY } from "./constants";
6
+ import {
7
+ PERCENTAGE_FACTOR,
8
+ RAY,
9
+ PERCENTAGE_DECIMALS,
10
+ PRICE_DECIMALS
11
+ } from "./constants";
7
12
  import { TokenData } from "../tokens/tokenData";
13
+ import { calcTotalPrice } from "./price";
8
14
 
9
15
  export type Balance = { address: string; balance: BigNumber };
10
16
 
@@ -12,19 +18,33 @@ export class CreditAccountData {
12
18
  public readonly id: string;
13
19
 
14
20
  public readonly addr: string;
21
+
15
22
  public readonly borrower: string;
23
+
16
24
  public readonly inUse: boolean;
25
+
17
26
  public readonly creditManager: string;
27
+
18
28
  public readonly underlyingToken: string;
29
+
19
30
  public borrowedAmountPlusInterest: BigNumber;
31
+
20
32
  public totalValue: BigNumber;
33
+
21
34
  public healthFactor: number;
35
+
22
36
  public borrowRate: number;
37
+
23
38
  public readonly allowedTokens: Array<string> = [];
39
+
24
40
  public readonly allTokens: Array<string> = [];
41
+
25
42
  public balances: Record<string, BigNumber> = {};
43
+
26
44
  public allBalances: Record<string, BigNumber> = {};
45
+
27
46
  public isDeleting: boolean;
47
+
28
48
  public readonly version: number = 1;
29
49
 
30
50
  constructor(payload: CreditAccountDataPayload) {
@@ -33,7 +53,7 @@ export class CreditAccountData {
33
53
  this.borrower = payload.borrower;
34
54
  this.inUse = payload.inUse;
35
55
  this.creditManager = payload.creditManager;
36
- this.underlyingToken = payload.underlyingToken;
56
+ this.underlyingToken = payload.underlying;
37
57
  this.borrowedAmountPlusInterest = BigNumber.from(
38
58
  payload.borrowedAmountPlusInterest
39
59
  );
@@ -43,7 +63,7 @@ export class CreditAccountData {
43
63
  this.borrowRate =
44
64
  BigNumber.from(payload.borrowRate)
45
65
  .mul(PERCENTAGE_FACTOR)
46
- .mul(100)
66
+ .mul(PERCENTAGE_DECIMALS)
47
67
  .div(RAY)
48
68
  .toNumber() / PERCENTAGE_FACTOR;
49
69
 
@@ -61,51 +81,63 @@ export class CreditAccountData {
61
81
  }
62
82
 
63
83
  balancesSorted(
64
- prices: Record<string, number>,
84
+ prices: Record<string, BigNumber>,
65
85
  tokens: Record<string, TokenData>
66
86
  ): Array<Balance> {
67
- const priceCalc = (addr: string, amount: BigNumber) => {
68
- const price = prices[addr] || 0;
69
- const { decimals = 18 } = tokens[addr] || {};
70
-
71
- return amount
72
- .mul(Math.floor(1000 * price))
73
- .div(BigNumber.from(10).pow(decimals));
74
- };
75
-
76
- const tokensAbcComparator = (t1?: TokenData, t2?: TokenData) => {
77
- const { symbol: symbol1 = "" } = t1 || {};
78
- const { symbol: symbol2 = "" } = t2 || {};
79
-
80
- return symbol1 > symbol2 ? 1 : -1;
81
- };
82
-
83
- const safeBalances = this.balances || [];
84
-
85
- return Object.entries(safeBalances)
86
- .sort(([addr1, amount1], [addr2, amount2]) => {
87
- const addr1Lc = addr1.toLowerCase();
88
- const addr2Lc = addr2.toLowerCase();
89
-
90
- const price1 = priceCalc(addr1Lc, amount1);
91
- const price2 = priceCalc(addr2Lc, amount2);
92
-
93
- return price1.eq(price2)
94
- ? tokensAbcComparator(tokens[addr1Lc], tokens[addr2Lc])
95
- : price1.gt(price2)
96
- ? -1
97
- : 1;
98
- })
99
- .map(([address, balance]) => ({ address, balance }));
87
+ return sortBalances(this.balances, prices, tokens).map(
88
+ ([address, balance]) => ({ address, balance })
89
+ );
100
90
  }
101
91
  }
102
92
 
93
+ export function sortBalances(
94
+ balances: Record<string, BigNumber>,
95
+ prices: Record<string, BigNumber>,
96
+ tokens: Record<string, TokenData>
97
+ ) {
98
+ return Object.entries(balances).sort(([addr1, amount1], [addr2, amount2]) => {
99
+ const addr1Lc = addr1.toLowerCase();
100
+ const addr2Lc = addr2.toLowerCase();
101
+
102
+ const token1 = tokens[addr1Lc];
103
+ const token2 = tokens[addr2Lc];
104
+
105
+ const price1 = prices[addr1Lc] || PRICE_DECIMALS;
106
+ const price2 = prices[addr2Lc] || PRICE_DECIMALS;
107
+
108
+ const totalPrice1 = calcTotalPrice(price1, amount1, token1?.decimals);
109
+ const totalPrice2 = calcTotalPrice(price2, amount2, token2?.decimals);
110
+
111
+ if (totalPrice1.eq(totalPrice2)) {
112
+ return tokensAbcComparator(token1, token2);
113
+ }
114
+
115
+ if (totalPrice1.gt(totalPrice2)) {
116
+ return -1;
117
+ }
118
+
119
+ return 1;
120
+ });
121
+ }
122
+
123
+ export function tokensAbcComparator(t1?: TokenData, t2?: TokenData) {
124
+ const { symbol: symbol1 = "" } = t1 || {};
125
+ const { symbol: symbol2 = "" } = t2 || {};
126
+
127
+ return symbol1 > symbol2 ? 1 : -1;
128
+ }
129
+
103
130
  export class CreditAccountDataExtended extends CreditAccountData {
104
131
  public readonly repayAmount: BigNumber;
132
+
105
133
  public readonly liquidationAmount: BigNumber;
134
+
106
135
  public readonly borrowedAmount: BigNumber;
136
+
107
137
  public readonly canBeClosed: boolean;
138
+
108
139
  public readonly cumulativeIndexAtOpen: BigNumber;
140
+
109
141
  public readonly since: number;
110
142
 
111
143
  constructor(payload: CreditAccountDataExtendedPayload) {
@@ -1,174 +1,282 @@
1
- import {BigNumber, ethers, Signer} from "ethers";
2
- import {formatBN} from "../utils/formatter";
1
+ import { BigNumber, ethers, Signer } from "ethers";
3
2
  import {
4
- PERCENTAGE_FACTOR,
5
- RAY,
6
- UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD
7
- } from "./constants";
8
- import {
9
- CreditManagerDataPayload,
10
- CreditManagerStatPayload
3
+ CreditManagerDataPayload,
4
+ CreditManagerStatPayload
11
5
  } from "../payload/creditManager";
12
- import {ICreditManager, ICreditManager__factory} from "../types";
6
+
7
+ import {
8
+ ICreditManager,
9
+ ICreditManager__factory,
10
+ ICreditFacade__factory
11
+ } from "../types";
12
+
13
+ import { MultiCall } from "./multicall";
14
+ import {
15
+ PERCENTAGE_FACTOR,
16
+ RAY,
17
+ UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD,
18
+ LEVERAGE_DECIMALS,
19
+ PERCENTAGE_DECIMALS
20
+ } from "./constants";
21
+ import { OpenAccountError } from "./errors";
13
22
 
14
23
  export class CreditManagerData {
15
- public readonly id: string;
16
- public readonly address: string;
17
- public readonly underlyingToken: string;
18
- public readonly isWETH: boolean;
19
- public readonly canBorrow: boolean;
20
- public readonly borrowRate: number;
21
- public readonly minAmount: BigNumber;
22
- public readonly maxAmount: BigNumber;
23
- public readonly maxLeverageFactor: number;
24
- public readonly availableLiquidity: BigNumber;
25
- public readonly allowedTokens: Array<string>;
26
- public readonly adapters: Record<string, string> = {};
27
- public readonly version: number = 1;
28
-
29
- constructor(payload: CreditManagerDataPayload) {
30
- this.id = payload.addr;
31
- this.address = payload.addr;
32
-
33
- this.underlyingToken = payload.underlyingToken || "";
34
- this.isWETH = payload.isWETH || false;
35
- this.canBorrow = payload.canBorrow || false;
36
- this.borrowRate =
37
- BigNumber.from(payload.borrowRate || 0)
38
- .mul(PERCENTAGE_FACTOR)
39
- .mul(100)
40
- .div(RAY)
41
- .toNumber() / PERCENTAGE_FACTOR;
42
- this.minAmount = BigNumber.from(payload.minAmount || 0);
43
- this.maxAmount = BigNumber.from(payload.maxAmount || 0);
44
- this.maxLeverageFactor = BigNumber.from(
45
- payload.maxLeverageFactor || 0
46
- ).toNumber();
47
- this.availableLiquidity = BigNumber.from(payload.availableLiquidity || 0);
48
- this.allowedTokens = payload.allowedTokens || [];
49
- payload.adapters?.forEach(a => {
50
- this.adapters[a.allowedContract] = a.adapter;
51
- });
52
- }
53
-
54
- validateOpenAccount(
55
- balance: BigNumber,
56
- decimals: number,
57
- amount_BN: BigNumber,
58
- leverage: number
59
- ): string | null {
60
- if (balance.lt(amount_BN)) return "Insufficient funds";
61
-
62
- if (amount_BN.lt(this.minAmount))
63
- return `Amount is less than minimal (${formatBN(
64
- this.minAmount,
65
- decimals
66
- )})`;
67
-
68
- if (amount_BN.gt(this.maxAmount))
69
- return `Amount is greater than maximum (${formatBN(
70
- this.maxAmount,
71
- decimals
72
- )})`;
73
-
74
- if (leverage > this.maxLeverageFactor) return `Leverage is bigger than max`;
75
-
76
- if (amount_BN.mul(leverage).div(100).gt(this.availableLiquidity))
77
- return "Insufficient liquidity in the pool";
78
-
79
- return null;
80
- }
81
-
82
- getContractETH(
83
- signer: Signer | ethers.providers.Provider
84
- ): ICreditManager {
85
- return ICreditManager__factory.connect(this.address, signer);
86
- }
87
-
88
- get isPaused(): boolean {
89
- return false;
90
- }
24
+ public readonly id: string;
25
+
26
+ public readonly address: string;
27
+
28
+ public readonly underlyingToken: string;
29
+
30
+ public readonly isWETH: boolean;
31
+
32
+ public readonly canBorrow: boolean;
33
+
34
+ public readonly borrowRate: number;
35
+
36
+ public readonly minAmount: BigNumber;
37
+
38
+ public readonly maxAmount: BigNumber;
39
+
40
+ public readonly maxLeverageFactor: number; // for V1 only
41
+
42
+ public readonly availableLiquidity: BigNumber;
43
+
44
+ public readonly allowedTokens: Array<string>;
45
+
46
+ public readonly adapters: Record<string, string>;
47
+
48
+ public readonly liquidationThresholds: Record<string, BigNumber>;
49
+
50
+ public readonly version: number;
51
+
52
+ public readonly creditFacade: string; // V2 only: address of creditFacade
53
+
54
+ public readonly isDegenMode: boolean; // V2 only: true if contract is in Degen mode
55
+
56
+ public readonly degenNFT: string; // V2 only: degenNFT, address(0) if not in degen mode
57
+
58
+ public readonly isIncreaseDebtForbidden: boolean; // V2 only: true if increasing debt is forbidden
59
+
60
+ public readonly forbiddenTokenMask: BigNumber; // V2 only: mask which forbids some particular tokens
61
+
62
+ public readonly isPaused: boolean = false;
63
+
64
+ constructor(payload: CreditManagerDataPayload) {
65
+ this.id = payload.addr;
66
+ this.address = payload.addr;
67
+
68
+ this.underlyingToken = payload.underlying || "";
69
+
70
+ this.isWETH = payload.isWETH || false;
71
+ this.canBorrow = payload.canBorrow || false;
72
+
73
+ this.borrowRate =
74
+ BigNumber.from(payload.borrowRate || 0)
75
+ .mul(PERCENTAGE_FACTOR)
76
+ .mul(PERCENTAGE_DECIMALS)
77
+ .div(RAY)
78
+ .toNumber() / PERCENTAGE_FACTOR;
79
+ this.minAmount = BigNumber.from(payload.minAmount || 0);
80
+ this.maxAmount = BigNumber.from(payload.maxAmount || 0);
81
+
82
+ this.maxLeverageFactor = BigNumber.from(
83
+ payload.maxLeverageFactor || 0
84
+ ).toNumber();
85
+ this.availableLiquidity = BigNumber.from(payload.availableLiquidity || 0);
86
+
87
+ this.allowedTokens = payload.collateralTokens || [];
88
+ this.adapters = (payload.adapters || []).reduce<Record<string, string>>(
89
+ (acc, { allowedContract, adapter }) => ({
90
+ ...acc,
91
+ [allowedContract]: adapter
92
+ }),
93
+ {}
94
+ );
95
+
96
+ this.liquidationThresholds = (payload.liquidationThresholds || []).reduce<
97
+ Record<string, BigNumber>
98
+ >((acc, threshold, index) => {
99
+ const address = payload.collateralTokens[index];
100
+
101
+ if (address) acc[address.toLowerCase()] = BigNumber.from(threshold);
102
+
103
+ return acc;
104
+ }, {});
105
+
106
+ this.version = BigNumber.from(payload.version || 1).toNumber();
107
+ this.creditFacade = payload.creditFacade || "";
108
+ this.isDegenMode = payload.isDegenMode || false;
109
+ this.degenNFT = payload.degenNFT || "";
110
+ this.isIncreaseDebtForbidden = payload.isIncreaseDebtForbidden || false;
111
+ this.forbiddenTokenMask = BigNumber.from(payload.forbiddenTokenMask || 0);
112
+ }
113
+
114
+ getContractETH(signer: Signer | ethers.providers.Provider): ICreditManager {
115
+ return ICreditManager__factory.connect(this.address, signer);
116
+ }
117
+
118
+ contractToAdapter(contractAddress: string): string | undefined {
119
+ return this.adapters[contractAddress];
120
+ }
121
+
122
+ encodeAddCollateral(
123
+ accountAddress: string,
124
+ tokenAddress: string,
125
+ amount: BigNumber
126
+ ): MultiCall {
127
+ if (this.version !== 2)
128
+ throw new Error("Multicall is eligible only for version 2");
129
+ return {
130
+ target: this.creditFacade,
131
+ callData: ICreditFacade__factory.createInterface().encodeFunctionData(
132
+ "addCollateral",
133
+ [accountAddress, tokenAddress, amount]
134
+ )
135
+ };
136
+ }
137
+
138
+ encodeIncreaseDebt(amount: BigNumber): MultiCall {
139
+ if (this.version !== 2)
140
+ throw new Error("Multicall is eligible only for version 2");
141
+ return {
142
+ target: this.creditFacade,
143
+ callData: ICreditFacade__factory.createInterface().encodeFunctionData(
144
+ "increaseDebt",
145
+ [amount]
146
+ )
147
+ };
148
+ }
149
+
150
+ encodeDecreaseDebt(amount: BigNumber): MultiCall {
151
+ if (this.version !== 2)
152
+ throw new Error("Multicall is eligible only for version 2");
153
+ return {
154
+ target: this.creditFacade,
155
+ callData: ICreditFacade__factory.createInterface().encodeFunctionData(
156
+ "decreaseDebt",
157
+ [amount]
158
+ )
159
+ };
160
+ }
161
+
162
+ validateOpenAccount(totalAmount: BigNumber, leverage: number): true {
163
+ if (totalAmount.lt(this.minAmount))
164
+ throw new OpenAccountError("amountLessMin", this.minAmount);
165
+
166
+ if (totalAmount.gt(this.maxAmount))
167
+ throw new OpenAccountError("amountGreaterMax", this.maxAmount);
168
+
169
+ if (leverage > this.maxLeverageFactor)
170
+ throw new OpenAccountError(
171
+ "leverageGreaterMax",
172
+ BigNumber.from(this.maxLeverageFactor)
173
+ );
174
+
175
+ if (
176
+ totalAmount
177
+ .mul(leverage)
178
+ .div(LEVERAGE_DECIMALS)
179
+ .gt(this.availableLiquidity)
180
+ )
181
+ throw new OpenAccountError(
182
+ "insufficientPoolLiquidity",
183
+ BigNumber.from(this.availableLiquidity)
184
+ );
185
+
186
+ return true;
187
+ }
91
188
  }
92
189
 
93
190
  export function calcMaxIncreaseBorrow(
94
- healthFactor: number,
95
- borrowAmountPlusInterest: BigNumber,
96
- maxLeverageFactor: number
191
+ healthFactor: number,
192
+ borrowAmountPlusInterest: BigNumber,
193
+ maxLeverageFactor: number
97
194
  ): BigNumber {
98
- const healthFactorPercentage = Math.floor(healthFactor * PERCENTAGE_FACTOR);
195
+ const healthFactorPercentage = Math.floor(healthFactor * PERCENTAGE_FACTOR);
99
196
 
100
- const minHealthFactor = Math.floor(
101
- (UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD * (maxLeverageFactor + 100)) /
102
- maxLeverageFactor
103
- );
197
+ const minHealthFactor = Math.floor(
198
+ (UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD *
199
+ (maxLeverageFactor + LEVERAGE_DECIMALS)) /
200
+ maxLeverageFactor
201
+ );
104
202
 
105
- const result = borrowAmountPlusInterest
106
- .mul(healthFactorPercentage - minHealthFactor)
107
- .div(minHealthFactor - UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD);
108
- return result.isNegative() ? BigNumber.from(0) : result;
203
+ const result = borrowAmountPlusInterest
204
+ .mul(healthFactorPercentage - minHealthFactor)
205
+ .div(minHealthFactor - UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD);
206
+ return result.isNegative() ? BigNumber.from(0) : result;
109
207
  }
110
208
 
111
209
  export function calcHealthFactorAfterIncreasingBorrow(
112
- healthFactor: number | undefined,
113
- borrowAmountPlusInterest: BigNumber | undefined,
114
- additional: BigNumber
210
+ healthFactor: number | undefined,
211
+ borrowAmountPlusInterest: BigNumber | undefined,
212
+ additional: BigNumber
115
213
  ): number {
116
- if (!healthFactor || !borrowAmountPlusInterest) return 0;
214
+ if (!healthFactor || !borrowAmountPlusInterest) return 0;
117
215
 
118
- const healthFactorPercentage = Math.floor(healthFactor * PERCENTAGE_FACTOR);
216
+ const healthFactorPercentage = Math.floor(healthFactor * PERCENTAGE_FACTOR);
119
217
 
120
- return (
121
- borrowAmountPlusInterest
122
- .mul(healthFactorPercentage)
123
- .add(additional.mul(UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD))
124
- .div(borrowAmountPlusInterest.add(additional))
125
- .toNumber() / PERCENTAGE_FACTOR
126
- );
218
+ return (
219
+ borrowAmountPlusInterest
220
+ .mul(healthFactorPercentage)
221
+ .add(additional.mul(UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD))
222
+ .div(borrowAmountPlusInterest.add(additional))
223
+ .toNumber() / PERCENTAGE_FACTOR
224
+ );
127
225
  }
128
226
 
129
227
  export function calcHealthFactorAfterAddingCollateral(
130
- healthFactor: number | undefined,
131
- borrowAmountPlusInterest: BigNumber | undefined,
132
- additionalCollateral: BigNumber
228
+ healthFactor: number | undefined,
229
+ borrowAmountPlusInterest: BigNumber | undefined,
230
+ additionalCollateral: BigNumber
133
231
  ): number {
134
- if (!healthFactor || !borrowAmountPlusInterest) return 0;
232
+ if (!healthFactor || !borrowAmountPlusInterest) return 0;
135
233
 
136
- const healthFactorPercentage = Math.floor(healthFactor * PERCENTAGE_FACTOR);
234
+ const healthFactorPercentage = Math.floor(healthFactor * PERCENTAGE_FACTOR);
137
235
 
138
- return (
139
- borrowAmountPlusInterest
140
- .mul(healthFactorPercentage)
141
- .add(additionalCollateral.mul(UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD))
142
- .div(borrowAmountPlusInterest)
143
- .toNumber() / PERCENTAGE_FACTOR
144
- );
236
+ return (
237
+ borrowAmountPlusInterest
238
+ .mul(healthFactorPercentage)
239
+ .add(additionalCollateral.mul(UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD))
240
+ .div(borrowAmountPlusInterest)
241
+ .toNumber() / PERCENTAGE_FACTOR
242
+ );
145
243
  }
146
244
 
147
245
  export class CreditManagerStat extends CreditManagerData {
148
- public readonly uniqueUsers: number;
149
- public readonly openedAccountsCount: number;
150
- public readonly totalOpenedAccounts: number;
151
- public readonly totalClosedAccounts: number;
152
- public readonly totalRepaidAccounts: number;
153
- public readonly totalLiquidatedAccounts: number;
154
- public readonly totalBorrowed: BigNumber;
155
- public readonly cumulativeBorrowed: BigNumber;
156
- public readonly totalRepaid: BigNumber;
157
- public readonly totalProfit: BigNumber;
158
- public readonly totalLosses: BigNumber;
159
-
160
- constructor(payload: CreditManagerStatPayload) {
161
- super(payload);
162
- this.uniqueUsers = payload.uniqueUsers;
163
- this.openedAccountsCount = payload.openedAccountsCount || 0;
164
- this.totalOpenedAccounts = payload.totalOpenedAccounts || 0;
165
- this.totalClosedAccounts = payload.totalClosedAccounts || 0;
166
- this.totalRepaidAccounts = payload.totalRepaidAccounts || 0;
167
- this.totalLiquidatedAccounts = payload.totalLiquidatedAccounts || 0;
168
- this.totalBorrowed = BigNumber.from(payload.totalBorrowed || 0);
169
- this.cumulativeBorrowed = BigNumber.from(payload.cumulativeBorrowed || 0);
170
- this.totalRepaid = BigNumber.from(payload.totalRepaid || 0);
171
- this.totalProfit = BigNumber.from(payload.totalProfit || 0);
172
- this.totalLosses = BigNumber.from(payload.totalLosses || 0);
173
- }
246
+ public readonly uniqueUsers: number;
247
+
248
+ public readonly openedAccountsCount: number;
249
+
250
+ public readonly totalOpenedAccounts: number;
251
+
252
+ public readonly totalClosedAccounts: number;
253
+
254
+ public readonly totalRepaidAccounts: number;
255
+
256
+ public readonly totalLiquidatedAccounts: number;
257
+
258
+ public readonly totalBorrowed: BigNumber;
259
+
260
+ public readonly cumulativeBorrowed: BigNumber;
261
+
262
+ public readonly totalRepaid: BigNumber;
263
+
264
+ public readonly totalProfit: BigNumber;
265
+
266
+ public readonly totalLosses: BigNumber;
267
+
268
+ constructor(payload: CreditManagerStatPayload) {
269
+ super(payload);
270
+ this.uniqueUsers = payload.uniqueUsers;
271
+ this.openedAccountsCount = payload.openedAccountsCount || 0;
272
+ this.totalOpenedAccounts = payload.totalOpenedAccounts || 0;
273
+ this.totalClosedAccounts = payload.totalClosedAccounts || 0;
274
+ this.totalRepaidAccounts = payload.totalRepaidAccounts || 0;
275
+ this.totalLiquidatedAccounts = payload.totalLiquidatedAccounts || 0;
276
+ this.totalBorrowed = BigNumber.from(payload.totalBorrowed || 0);
277
+ this.cumulativeBorrowed = BigNumber.from(payload.cumulativeBorrowed || 0);
278
+ this.totalRepaid = BigNumber.from(payload.totalRepaid || 0);
279
+ this.totalProfit = BigNumber.from(payload.totalProfit || 0);
280
+ this.totalLosses = BigNumber.from(payload.totalLosses || 0);
281
+ }
174
282
  }
@@ -1,9 +1,9 @@
1
1
  export interface CreditOperation {
2
- id: number,
3
- txHash: string,
4
- blockNum: number,
5
- protocol: string,
6
- operation: string,
7
- timestamp: number,
8
- date: string
2
+ id: number;
3
+ txHash: string;
4
+ blockNum: number;
5
+ protocol: string;
6
+ operation: string;
7
+ timestamp: number;
8
+ date: string;
9
9
  }