@gearbox-protocol/sdk 1.4.0 → 1.5.0

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.
@@ -1,5 +1,6 @@
1
1
  import { LPTokens, SupportedToken } from "../tokens/token";
2
2
  export declare type TokensWithAPY = LPTokens | Extract<SupportedToken, "LDO">;
3
+ export declare type LpTokensAPY = Record<TokensWithAPY, number>;
3
4
  export * from "./convexAPY";
4
5
  export * from "./curveAPY";
5
6
  export * from "./lidoAPY";
@@ -0,0 +1,34 @@
1
+ import { Signer } from "ethers";
2
+ import { AdapterInterface } from "../contracts/adapters";
3
+ import { SupportedContract } from "../contracts/contracts";
4
+ import { PathFinderResultStructOutput } from "../types/contracts/pathfinder/interfaces/IPathFinder";
5
+ import { EVMTx } from "./eventOrTx";
6
+ export declare enum AdapterType {
7
+ Swap = 1,
8
+ LP = 2
9
+ }
10
+ interface BaseAdapterProps {
11
+ name: string;
12
+ type: AdapterType;
13
+ adapterInterface: AdapterInterface;
14
+ contractAddress: string;
15
+ adapterAddress: string;
16
+ contractSymbol: SupportedContract;
17
+ }
18
+ interface ExecuteProps {
19
+ tradePath: PathFinderResultStructOutput;
20
+ slippage: number;
21
+ signer: Signer;
22
+ }
23
+ export declare class BaseAdapter {
24
+ readonly name: string;
25
+ readonly type: AdapterType;
26
+ readonly adapterInterface: AdapterInterface;
27
+ readonly contractAddress: string;
28
+ readonly adapterAddress: string;
29
+ readonly contractSymbol: SupportedContract;
30
+ constructor(props: BaseAdapterProps);
31
+ execute(props: ExecuteProps): Promise<EVMTx>;
32
+ static connect(tradePath: PathFinderResultStructOutput): BaseAdapter;
33
+ }
34
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.BaseAdapter = exports.AdapterType = void 0;
40
+ var adapters_1 = require("../contracts/adapters");
41
+ var AdapterType;
42
+ (function (AdapterType) {
43
+ AdapterType[AdapterType["Swap"] = 1] = "Swap";
44
+ AdapterType[AdapterType["LP"] = 2] = "LP";
45
+ })(AdapterType = exports.AdapterType || (exports.AdapterType = {}));
46
+ var BaseAdapter = /** @class */ (function () {
47
+ function BaseAdapter(props) {
48
+ this.name = props.name;
49
+ this.type = props.type;
50
+ this.adapterInterface = props.adapterInterface;
51
+ this.adapterAddress = props.adapterAddress;
52
+ this.contractAddress = props.contractAddress;
53
+ this.contractSymbol = props.contractSymbol;
54
+ }
55
+ BaseAdapter.prototype.execute = function (props) {
56
+ return __awaiter(this, void 0, void 0, function () {
57
+ return __generator(this, function (_a) {
58
+ console.debug(props);
59
+ return [2 /*return*/, {}];
60
+ });
61
+ });
62
+ };
63
+ BaseAdapter.connect = function (tradePath) {
64
+ console.debug(tradePath);
65
+ return new BaseAdapter({
66
+ name: "",
67
+ type: AdapterType.Swap,
68
+ adapterInterface: adapters_1.AdapterInterface.NO_SWAP,
69
+ adapterAddress: "",
70
+ contractAddress: "",
71
+ contractSymbol: "CONVEX_3CRV_POOL",
72
+ });
73
+ };
74
+ return BaseAdapter;
75
+ }());
76
+ exports.BaseAdapter = BaseAdapter;
@@ -0,0 +1,34 @@
1
+ import { BigNumber } from "ethers";
2
+ import { LPTokens } from "../tokens/token";
3
+ import { TokenData } from "../tokens/tokenData";
4
+ export interface Asset {
5
+ token: string;
6
+ balance: BigNumber;
7
+ }
8
+ export interface LpAsset extends Asset {
9
+ symbol: LPTokens;
10
+ name: string;
11
+ }
12
+ interface NextAssetProps<T extends Asset> {
13
+ allowedTokens: Array<string>;
14
+ selectedAssets: Array<T>;
15
+ balances: Record<string, BigNumber>;
16
+ tokensList: Record<string, TokenData>;
17
+ prices?: Record<string, BigNumber>;
18
+ }
19
+ export declare function nextAsset<T extends Asset>({ allowedTokens, selectedAssets, balances, tokensList, prices, }: NextAssetProps<T>): string | undefined;
20
+ export declare function getBalances(allowedTokens: Array<string>, externalBalances: Record<string, BigNumber>): Record<string, BigNumber>;
21
+ export declare function constructAssetRecord<A extends Asset>(a: Array<A>): Record<string, A>;
22
+ export declare type WrapResult<T> = [Array<T>, BigNumber, BigNumber];
23
+ export declare const memoWrapETH: (ethAddress: string, wethAddress: string) => <T extends Asset>(assets: T[]) => WrapResult<T>;
24
+ /**
25
+ * Sums the the second assets list into the first assets list
26
+ * Creates new assets.
27
+ */
28
+ export declare function sumAssets<A extends Asset, B extends Asset>(a: Array<A>, b: Array<B>): Array<A | B>;
29
+ /**
30
+ * Subtracts the the second assets list from the first assets list
31
+ * Balance cant be negative; doesn't create new assets.
32
+ */
33
+ export declare function subAssets<A extends Asset, B extends Asset>(a: Array<A>, b: Array<B>): Array<A>;
34
+ export {};
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.subAssets = exports.sumAssets = exports.memoWrapETH = exports.constructAssetRecord = exports.getBalances = exports.nextAsset = void 0;
15
+ var ethers_1 = require("ethers");
16
+ var math_1 = require("../utils/math");
17
+ var creditAccount_1 = require("./creditAccount");
18
+ function nextAsset(_a) {
19
+ var allowedTokens = _a.allowedTokens, selectedAssets = _a.selectedAssets, balances = _a.balances, tokensList = _a.tokensList, _b = _a.prices, prices = _b === void 0 ? {} : _b;
20
+ var selectedRecord = selectedAssets.reduce(function (acc, _a) {
21
+ var token = _a.token;
22
+ acc[token.toLowerCase()] = true;
23
+ return acc;
24
+ }, {});
25
+ var notSelected = allowedTokens.filter(function (allowedToken) {
26
+ var alreadySelected = selectedRecord[allowedToken.toLowerCase()];
27
+ return !alreadySelected;
28
+ });
29
+ var sorted = (0, creditAccount_1.sortBalances)(getBalances(notSelected, balances), prices, tokensList);
30
+ var address = (sorted[0] || [])[0];
31
+ return address;
32
+ }
33
+ exports.nextAsset = nextAsset;
34
+ function getBalances(allowedTokens, externalBalances) {
35
+ return allowedTokens.reduce(function (acc, address) {
36
+ var _a;
37
+ var addressLc = address.toLowerCase();
38
+ return __assign(__assign({}, acc), (_a = {}, _a[addressLc] = externalBalances[addressLc] || ethers_1.BigNumber.from(0), _a));
39
+ }, {});
40
+ }
41
+ exports.getBalances = getBalances;
42
+ function constructAssetRecord(a) {
43
+ var record = a.reduce(function (acc, asset) {
44
+ acc[asset.token] = asset;
45
+ return acc;
46
+ }, {});
47
+ return record;
48
+ }
49
+ exports.constructAssetRecord = constructAssetRecord;
50
+ var memoWrapETH = function (ethAddress, wethAddress) {
51
+ return function wrapETH(assets) {
52
+ var assetsRecord = constructAssetRecord(assets);
53
+ var weth = assetsRecord[wethAddress];
54
+ var _a = (weth || {}).balance, wethAmount = _a === void 0 ? ethers_1.BigNumber.from(0) : _a;
55
+ var eth = assetsRecord[ethAddress];
56
+ var _b = (eth || {}).balance, ethAmount = _b === void 0 ? ethers_1.BigNumber.from(0) : _b;
57
+ var wethOrETH = weth || eth;
58
+ if (wethOrETH) {
59
+ assetsRecord[wethAddress] = __assign(__assign({}, wethOrETH), { token: wethAddress, balance: (0, math_1.nonNegativeBn)(ethAmount).add((0, math_1.nonNegativeBn)(wethAmount)) });
60
+ }
61
+ if (eth) {
62
+ delete assetsRecord[ethAddress];
63
+ }
64
+ return [Object.values(assetsRecord), ethAmount, wethAmount];
65
+ };
66
+ };
67
+ exports.memoWrapETH = memoWrapETH;
68
+ /**
69
+ * Sums the the second assets list into the first assets list
70
+ * Creates new assets.
71
+ */
72
+ function sumAssets(a, b) {
73
+ var aRecord = constructAssetRecord(a);
74
+ var resRecord = b.reduce(function (acc, bAsset) {
75
+ var aAsset = acc[bAsset.token];
76
+ var _a = (aAsset || {}).balance, amount = _a === void 0 ? ethers_1.BigNumber.from(0) : _a;
77
+ var amountSum = (0, math_1.nonNegativeBn)(bAsset.balance).add((0, math_1.nonNegativeBn)(amount));
78
+ var aOrB = aAsset || bAsset;
79
+ acc[bAsset.token] = __assign(__assign({}, aOrB), { balance: amountSum });
80
+ return acc;
81
+ }, aRecord);
82
+ return Object.values(resRecord);
83
+ }
84
+ exports.sumAssets = sumAssets;
85
+ /**
86
+ * Subtracts the the second assets list from the first assets list
87
+ * Balance cant be negative; doesn't create new assets.
88
+ */
89
+ function subAssets(a, b) {
90
+ var bRecord = constructAssetRecord(b);
91
+ return a.map(function (asset) {
92
+ var bAsset = bRecord[asset.token];
93
+ var _a = (bAsset || {}).balance, bAmount = _a === void 0 ? ethers_1.BigNumber.from(0) : _a;
94
+ var amountSub = (0, math_1.nonNegativeBn)(asset.balance).sub((0, math_1.nonNegativeBn)(bAmount));
95
+ return __assign(__assign({}, asset), { balance: (0, math_1.nonNegativeBn)(amountSub) });
96
+ });
97
+ }
98
+ exports.subAssets = subAssets;
@@ -1,10 +1,8 @@
1
1
  import { BigNumber } from "ethers";
2
+ import { LpTokensAPY } from "../apy";
2
3
  import { CreditAccountDataExtendedPayload, CreditAccountDataPayload } from "../payload/creditAccount";
3
4
  import { TokenData } from "../tokens/tokenData";
4
- export interface Balance {
5
- address: string;
6
- balance: BigNumber;
7
- }
5
+ import { Asset, LpAsset } from "./assets";
8
6
  export declare class CreditAccountData {
9
7
  readonly id: string;
10
8
  readonly addr: string;
@@ -23,7 +21,7 @@ export declare class CreditAccountData {
23
21
  isDeleting: boolean;
24
22
  readonly version: number;
25
23
  constructor(payload: CreditAccountDataPayload);
26
- balancesSorted(prices: Record<string, BigNumber>, tokens: Record<string, TokenData>): Array<Balance>;
24
+ balancesSorted(prices: Record<string, BigNumber>, tokens: Record<string, TokenData>): Array<Asset>;
27
25
  }
28
26
  export declare function sortBalances(balances: Record<string, BigNumber>, prices: Record<string, BigNumber>, tokens: Record<string, TokenData>): Array<[string, BigNumber]>;
29
27
  export declare function tokensAbcComparator(t1?: TokenData, t2?: TokenData): 1 | -1;
@@ -37,3 +35,14 @@ export declare class CreditAccountDataExtended extends CreditAccountData {
37
35
  readonly since: number;
38
36
  constructor(payload: CreditAccountDataExtendedPayload);
39
37
  }
38
+ export interface CalcOverallAPYProps {
39
+ lpAssets: Array<LpAsset>;
40
+ lpAPY: LpTokensAPY | undefined;
41
+ prices: Record<string, BigNumber>;
42
+ tokensList: Record<string, TokenData>;
43
+ totalValue: BigNumber | undefined;
44
+ debt: BigNumber | undefined;
45
+ borrowRate: number;
46
+ underlyingToken: string;
47
+ }
48
+ export declare function calcOverallAPY({ lpAssets, lpAPY, prices, tokensList, totalValue, debt, borrowRate, underlyingToken, }: CalcOverallAPYProps): number | undefined;
@@ -15,8 +15,9 @@ var __extends = (this && this.__extends) || (function () {
15
15
  };
16
16
  })();
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.CreditAccountDataExtended = exports.amountAbcComparator = exports.tokensAbcComparator = exports.sortBalances = exports.CreditAccountData = void 0;
18
+ exports.calcOverallAPY = exports.CreditAccountDataExtended = exports.amountAbcComparator = exports.tokensAbcComparator = exports.sortBalances = exports.CreditAccountData = void 0;
19
19
  var ethers_1 = require("ethers");
20
+ var formatter_1 = require("../utils/formatter");
20
21
  var price_1 = require("../utils/price");
21
22
  var constants_1 = require("./constants");
22
23
  var CreditAccountData = /** @class */ (function () {
@@ -57,8 +58,8 @@ var CreditAccountData = /** @class */ (function () {
57
58
  }
58
59
  CreditAccountData.prototype.balancesSorted = function (prices, tokens) {
59
60
  return sortBalances(this.balances, prices, tokens).map(function (_a) {
60
- var address = _a[0], balance = _a[1];
61
- return ({ address: address, balance: balance });
61
+ var token = _a[0], balance = _a[1];
62
+ return ({ token: token, balance: balance });
62
63
  });
63
64
  };
64
65
  return CreditAccountData;
@@ -113,3 +114,34 @@ var CreditAccountDataExtended = /** @class */ (function (_super) {
113
114
  return CreditAccountDataExtended;
114
115
  }(CreditAccountData));
115
116
  exports.CreditAccountDataExtended = CreditAccountDataExtended;
117
+ function calcOverallAPY(_a) {
118
+ var lpAssets = _a.lpAssets, lpAPY = _a.lpAPY, prices = _a.prices, tokensList = _a.tokensList, totalValue = _a.totalValue, debt = _a.debt, borrowRate = _a.borrowRate, underlyingToken = _a.underlyingToken;
119
+ if (!lpAPY || !totalValue || !debt)
120
+ return undefined;
121
+ var assetAPYMoney = lpAssets.reduce(function (acc, _a) {
122
+ var symbol = _a.symbol, tokenAddress = _a.token, amount = _a.balance;
123
+ var apy = lpAPY[symbol] || 0;
124
+ var price = prices[tokenAddress] || ethers_1.BigNumber.from(0);
125
+ var token = tokensList[tokenAddress];
126
+ var apyBN = (0, formatter_1.toBN)((apy / constants_1.PERCENTAGE_DECIMALS).toString(), constants_1.WAD_DECIMALS_POW);
127
+ var money = (0, price_1.calcTotalPrice)(price, amount, token === null || token === void 0 ? void 0 : token.decimals);
128
+ var apyMoney = money.mul(apyBN).div(constants_1.WAD);
129
+ return acc.add(apyMoney);
130
+ }, ethers_1.BigNumber.from(0));
131
+ var _b = tokensList[underlyingToken] || {}, _c = _b.decimals, underlyingDecimals = _c === void 0 ? 18 : _c, _d = _b.address, underlyingAddress = _d === void 0 ? "" : _d;
132
+ var underlyingPrice = prices[underlyingAddress] || constants_1.PRICE_DECIMALS;
133
+ var assetAPYAmountInUnderlying = (0, price_1.convertByPrice)(assetAPYMoney, {
134
+ price: underlyingPrice,
135
+ decimals: underlyingDecimals,
136
+ });
137
+ var borrowAPY = (0, formatter_1.toBN)((borrowRate / constants_1.PERCENTAGE_DECIMALS).toString(), constants_1.WAD_DECIMALS_POW);
138
+ var debtAPY = debt.mul(borrowAPY).div(constants_1.WAD);
139
+ var yourAssets = totalValue.sub(debt);
140
+ var apyInPercent = assetAPYAmountInUnderlying
141
+ .sub(debtAPY)
142
+ .mul(constants_1.PERCENTAGE_DECIMALS)
143
+ .mul(constants_1.WAD)
144
+ .div(yourAssets);
145
+ return Number((0, formatter_1.toSignificant)(apyInPercent, constants_1.WAD_DECIMALS_POW));
146
+ }
147
+ exports.calcOverallAPY = calcOverallAPY;
@@ -1,6 +1,8 @@
1
1
  import { BigNumber, ethers, Signer } from "ethers";
2
2
  import { CreditManagerDataPayload, CreditManagerStatPayload } from "../payload/creditManager";
3
+ import { TokenData } from "../tokens/tokenData";
3
4
  import { ICreditManager } from "../types";
5
+ import { Asset } from "./assets";
4
6
  import { MultiCall } from "./multicall";
5
7
  export declare class CreditManagerData {
6
8
  readonly id: string;
@@ -38,9 +40,6 @@ export declare class CreditManagerData {
38
40
  protected validateOpenAccountV1(collateral: BigNumber, debt: BigNumber): true;
39
41
  protected validateOpenAccountV2(debt: BigNumber): true;
40
42
  }
41
- export declare function calcMaxIncreaseBorrow(healthFactor: number, borrowAmountPlusInterest: BigNumber, maxLeverageFactor: number): BigNumber;
42
- export declare function calcHealthFactorAfterIncreasingBorrow(healthFactor: number | undefined, borrowAmountPlusInterest: BigNumber | undefined, additional: BigNumber): number;
43
- export declare function calcHealthFactorAfterAddingCollateral(healthFactor: number | undefined, borrowAmountPlusInterest: BigNumber | undefined, additionalCollateral: BigNumber): number;
44
43
  export declare class CreditManagerStat extends CreditManagerData {
45
44
  readonly uniqueUsers: number;
46
45
  readonly openedAccountsCount: number;
@@ -55,3 +54,13 @@ export declare class CreditManagerStat extends CreditManagerData {
55
54
  readonly totalLosses: BigNumber;
56
55
  constructor(payload: CreditManagerStatPayload);
57
56
  }
57
+ export declare function calcMaxIncreaseBorrow(healthFactor: number, borrowAmountPlusInterest: BigNumber, maxLeverageFactor: number): BigNumber;
58
+ export interface CalcHealthFactorProps {
59
+ assets: Array<Asset>;
60
+ prices: Record<string, BigNumber>;
61
+ tokensList: Record<string, TokenData>;
62
+ liquidationThresholds: Record<string, BigNumber>;
63
+ underlyingToken: TokenData | undefined;
64
+ borrowed: BigNumber;
65
+ }
66
+ export declare function calcHealthFactor({ assets, prices, tokensList, liquidationThresholds, underlyingToken, borrowed, }: CalcHealthFactorProps): number;
@@ -26,9 +26,10 @@ var __assign = (this && this.__assign) || function () {
26
26
  return __assign.apply(this, arguments);
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.CreditManagerStat = exports.calcHealthFactorAfterAddingCollateral = exports.calcHealthFactorAfterIncreasingBorrow = exports.calcMaxIncreaseBorrow = exports.CreditManagerData = void 0;
29
+ exports.calcHealthFactor = exports.calcMaxIncreaseBorrow = exports.CreditManagerStat = exports.CreditManagerData = void 0;
30
30
  var ethers_1 = require("ethers");
31
31
  var types_1 = require("../types");
32
+ var price_1 = require("../utils/price");
32
33
  var constants_1 = require("./constants");
33
34
  var errors_1 = require("./errors");
34
35
  var CreditManagerData = /** @class */ (function () {
@@ -136,41 +137,6 @@ var CreditManagerData = /** @class */ (function () {
136
137
  return CreditManagerData;
137
138
  }());
138
139
  exports.CreditManagerData = CreditManagerData;
139
- function calcMaxIncreaseBorrow(healthFactor, borrowAmountPlusInterest, maxLeverageFactor) {
140
- var healthFactorPercentage = Math.floor(healthFactor * constants_1.PERCENTAGE_FACTOR);
141
- var minHealthFactor = maxLeverageFactor > 0
142
- ? Math.floor((constants_1.UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD *
143
- (maxLeverageFactor + constants_1.LEVERAGE_DECIMALS)) /
144
- maxLeverageFactor)
145
- : 10000;
146
- var result = borrowAmountPlusInterest
147
- .mul(healthFactorPercentage - minHealthFactor)
148
- .div(minHealthFactor - constants_1.UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD);
149
- return result.isNegative() ? ethers_1.BigNumber.from(0) : result;
150
- }
151
- exports.calcMaxIncreaseBorrow = calcMaxIncreaseBorrow;
152
- function calcHealthFactorAfterIncreasingBorrow(healthFactor, borrowAmountPlusInterest, additional) {
153
- if (!healthFactor || !borrowAmountPlusInterest)
154
- return 0;
155
- var healthFactorPercentage = Math.floor(healthFactor * constants_1.PERCENTAGE_FACTOR);
156
- return (borrowAmountPlusInterest
157
- .mul(healthFactorPercentage)
158
- .add(additional.mul(constants_1.UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD))
159
- .div(borrowAmountPlusInterest.add(additional))
160
- .toNumber() / constants_1.PERCENTAGE_FACTOR);
161
- }
162
- exports.calcHealthFactorAfterIncreasingBorrow = calcHealthFactorAfterIncreasingBorrow;
163
- function calcHealthFactorAfterAddingCollateral(healthFactor, borrowAmountPlusInterest, additionalCollateral) {
164
- if (!healthFactor || !borrowAmountPlusInterest)
165
- return 0;
166
- var healthFactorPercentage = Math.floor(healthFactor * constants_1.PERCENTAGE_FACTOR);
167
- return (borrowAmountPlusInterest
168
- .mul(healthFactorPercentage)
169
- .add(additionalCollateral.mul(constants_1.UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD))
170
- .div(borrowAmountPlusInterest)
171
- .toNumber() / constants_1.PERCENTAGE_FACTOR);
172
- }
173
- exports.calcHealthFactorAfterAddingCollateral = calcHealthFactorAfterAddingCollateral;
174
140
  var CreditManagerStat = /** @class */ (function (_super) {
175
141
  __extends(CreditManagerStat, _super);
176
142
  function CreditManagerStat(payload) {
@@ -191,3 +157,35 @@ var CreditManagerStat = /** @class */ (function (_super) {
191
157
  return CreditManagerStat;
192
158
  }(CreditManagerData));
193
159
  exports.CreditManagerStat = CreditManagerStat;
160
+ function calcMaxIncreaseBorrow(healthFactor, borrowAmountPlusInterest, maxLeverageFactor) {
161
+ var healthFactorPercentage = Math.floor(healthFactor * constants_1.PERCENTAGE_FACTOR);
162
+ var minHealthFactor = maxLeverageFactor > 0
163
+ ? Math.floor((constants_1.UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD *
164
+ (maxLeverageFactor + constants_1.LEVERAGE_DECIMALS)) /
165
+ maxLeverageFactor)
166
+ : 10000;
167
+ var result = borrowAmountPlusInterest
168
+ .mul(healthFactorPercentage - minHealthFactor)
169
+ .div(minHealthFactor - constants_1.UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD);
170
+ return result.isNegative() ? ethers_1.BigNumber.from(0) : result;
171
+ }
172
+ exports.calcMaxIncreaseBorrow = calcMaxIncreaseBorrow;
173
+ function calcHealthFactor(_a) {
174
+ var assets = _a.assets, prices = _a.prices, tokensList = _a.tokensList, liquidationThresholds = _a.liquidationThresholds, underlyingToken = _a.underlyingToken, borrowed = _a.borrowed;
175
+ var assetLTMoney = assets.reduce(function (acc, _a) {
176
+ var tokenAddress = _a.token, amount = _a.balance;
177
+ var lt = liquidationThresholds[tokenAddress] || ethers_1.BigNumber.from(0);
178
+ var price = prices[tokenAddress] || ethers_1.BigNumber.from(0);
179
+ var token = tokensList[tokenAddress];
180
+ var money = (0, price_1.calcTotalPrice)(price, amount, token === null || token === void 0 ? void 0 : token.decimals);
181
+ var ltMoney = money.mul(lt).div(constants_1.PERCENTAGE_FACTOR);
182
+ return acc.add(ltMoney);
183
+ }, ethers_1.BigNumber.from(0));
184
+ var underlyingPrice = prices[(underlyingToken === null || underlyingToken === void 0 ? void 0 : underlyingToken.address) || ""] || constants_1.PRICE_DECIMALS;
185
+ var borrowedMoney = (0, price_1.calcTotalPrice)(underlyingPrice, borrowed, underlyingToken === null || underlyingToken === void 0 ? void 0 : underlyingToken.decimals);
186
+ var hfInPercent = borrowedMoney.gt(0)
187
+ ? assetLTMoney.mul(constants_1.PERCENTAGE_FACTOR).div(borrowedMoney)
188
+ : ethers_1.BigNumber.from(0);
189
+ return hfInPercent.toNumber() / constants_1.PERCENTAGE_FACTOR;
190
+ }
191
+ exports.calcHealthFactor = calcHealthFactor;
@@ -1,5 +1,8 @@
1
1
  import { BigNumber } from "ethers";
2
2
  import { TokensWithAPY } from "../apy";
3
+ import { TokenData } from "../tokens/tokenData";
4
+ import { Asset } from "./assets";
5
+ import { CreditManagerData } from "./creditManager";
3
6
  export interface StrategyPayload {
4
7
  apy?: number;
5
8
  apyTokenSymbol: TokensWithAPY;
@@ -14,10 +17,15 @@ interface PoolStats {
14
17
  borrowRate: number;
15
18
  }
16
19
  declare type PoolList = Record<string, PoolStats>;
17
- interface TokenDescription {
18
- price: BigNumber;
19
- amount: BigNumber;
20
- decimals: number | undefined;
20
+ interface LiquidationPriceProps {
21
+ assets: Array<Asset>;
22
+ prices: Record<string, BigNumber>;
23
+ tokensList: Record<string, TokenData>;
24
+ liquidationThresholds: Record<string, BigNumber>;
25
+ borrowed: BigNumber;
26
+ underlyingToken: TokenData;
27
+ lpAmount: BigNumber;
28
+ lpToken: TokenData;
21
29
  }
22
30
  export declare class Strategy {
23
31
  apy: number | undefined;
@@ -28,11 +36,13 @@ export declare class Strategy {
28
36
  leveragableCollateral: Array<string>;
29
37
  baseAssets: Array<string>;
30
38
  constructor(payload: StrategyPayload);
39
+ static maxLeverage(lpToken: string, cms: Array<PartialCM>): number;
31
40
  maxAPY(maxLeverage: number, poolApy: PoolList): number;
32
41
  overallAPY(apy: number, leverage: number, depositCollateral: string, borrowAPY: number): number;
33
- liquidationPrice(borrowed: TokenDescription, collateral: TokenDescription, lp: TokenDescription, ltCollateral: BigNumber): BigNumber;
42
+ liquidationPrice({ assets, prices, tokensList, liquidationThresholds, borrowed, underlyingToken, lpAmount, lpToken, }: LiquidationPriceProps): BigNumber;
34
43
  protected farmLev(leverage: number, depositCollateral: string): number;
35
44
  protected inBaseAssets(depositCollateral: string): boolean;
36
45
  protected inLeveragableAssets(depositCollateral: string): boolean;
37
46
  }
47
+ declare type PartialCM = Pick<CreditManagerData, "liquidationThresholds" | "address">;
38
48
  export {};
@@ -14,6 +14,12 @@ var Strategy = /** @class */ (function () {
14
14
  this.leveragableCollateral = payload.leveragableCollateral;
15
15
  this.baseAssets = payload.baseAssets;
16
16
  }
17
+ Strategy.maxLeverage = function (lpToken, cms) {
18
+ var maxThreshold = maxLeverageThreshold(lpToken, cms)[0];
19
+ var ONE = ethers_1.BigNumber.from(constants_1.PERCENTAGE_FACTOR);
20
+ var maxLeverage = ONE.mul(constants_1.LEVERAGE_DECIMALS).div(ONE.sub(maxThreshold));
21
+ return maxLeverage.sub(constants_1.LEVERAGE_DECIMALS).toNumber();
22
+ };
17
23
  Strategy.prototype.maxAPY = function (maxLeverage, poolApy) {
18
24
  var minApy = minBorrowApy(poolApy);
19
25
  return roi(this.apy || 0, maxLeverage, maxLeverage - constants_1.LEVERAGE_DECIMALS, minApy);
@@ -23,14 +29,26 @@ var Strategy = /** @class */ (function () {
23
29
  return roi(apy, farmLev, leverage - constants_1.LEVERAGE_DECIMALS, borrowAPY);
24
30
  };
25
31
  // eslint-disable-next-line class-methods-use-this
26
- Strategy.prototype.liquidationPrice = function (borrowed, collateral, lp, ltCollateral) {
27
- var borrowedMoney = (0, price_1.calcTotalPrice)(borrowed.price, borrowed.amount, borrowed.decimals);
28
- var collateralMoney = (0, price_1.calcTotalPrice)(collateral.price, collateral.amount, collateral.decimals)
29
- .mul(ltCollateral)
30
- .div(constants_1.PERCENTAGE_FACTOR);
31
- var lpMoney = (0, price_1.calcTotalPrice)(lp.price, lp.amount, lp.decimals);
32
+ Strategy.prototype.liquidationPrice = function (_a) {
33
+ var assets = _a.assets, prices = _a.prices, tokensList = _a.tokensList, liquidationThresholds = _a.liquidationThresholds, borrowed = _a.borrowed, underlyingToken = _a.underlyingToken, lpAmount = _a.lpAmount, lpToken = _a.lpToken;
34
+ var collateralLTMoney = assets.reduce(function (acc, _a) {
35
+ var tokenAddress = _a.token, amount = _a.balance;
36
+ var lt = liquidationThresholds[tokenAddress] || ethers_1.BigNumber.from(0);
37
+ var price = prices[tokenAddress] || ethers_1.BigNumber.from(0);
38
+ var token = tokensList[tokenAddress];
39
+ var money = (0, price_1.calcTotalPrice)(price, amount, token === null || token === void 0 ? void 0 : token.decimals);
40
+ var ltMoney = money.mul(lt).div(constants_1.PERCENTAGE_FACTOR);
41
+ return acc.add(ltMoney);
42
+ }, ethers_1.BigNumber.from(0));
43
+ var underlyingPrice = prices[(underlyingToken === null || underlyingToken === void 0 ? void 0 : underlyingToken.address) || ""] || constants_1.PRICE_DECIMALS;
44
+ var borrowedMoney = (0, price_1.calcTotalPrice)(underlyingPrice, borrowed, underlyingToken === null || underlyingToken === void 0 ? void 0 : underlyingToken.decimals);
45
+ var lpPrice = prices[(lpToken === null || lpToken === void 0 ? void 0 : lpToken.address) || ""] || constants_1.PRICE_DECIMALS;
46
+ var lpMoney = (0, price_1.calcTotalPrice)(lpPrice, lpAmount, lpToken === null || lpToken === void 0 ? void 0 : lpToken.decimals);
32
47
  if (lpMoney.gt(0)) {
33
- var lqPrice = borrowedMoney.sub(collateralMoney).mul(constants_1.WAD).div(lpMoney);
48
+ var lqPrice = borrowedMoney
49
+ .sub(collateralLTMoney)
50
+ .mul(constants_1.WAD)
51
+ .div(lpMoney);
34
52
  return lqPrice.gte(0) ? lqPrice : ethers_1.BigNumber.from(0);
35
53
  }
36
54
  return ethers_1.BigNumber.from(0);
@@ -57,3 +75,20 @@ function minBorrowApy(poolApy) {
57
75
  var apys = Object.values(poolApy).sort(function (a, b) { return a.borrowRate - b.borrowRate; });
58
76
  return apys.length > 0 ? apys[0].borrowRate : 0;
59
77
  }
78
+ function maxLeverageThreshold(lpToken, cms) {
79
+ var ltByCM = cms.map(function (cm) {
80
+ var lt = cm.liquidationThresholds[lpToken] || ethers_1.BigNumber.from(0);
81
+ return [cm.address, lt];
82
+ });
83
+ var sorted = ltByCM.sort(function (_a, _b) {
84
+ var ltA = _a[1];
85
+ var ltB = _b[1];
86
+ if (ltA.gt(ltB))
87
+ return 1;
88
+ if (ltB.gt(ltA))
89
+ return -1;
90
+ return 0;
91
+ });
92
+ var _a = sorted[0] || [], _b = _a[0], cm = _b === void 0 ? "" : _b, _c = _a[1], lt = _c === void 0 ? ethers_1.BigNumber.from(0) : _c;
93
+ return [lt, cm];
94
+ }
@@ -0,0 +1,49 @@
1
+ import { BigNumber, Signer } from "ethers";
2
+ import { AdapterInterface } from "../contracts/adapters";
3
+ import { SwapType } from "../pathfinder/tradeTypes";
4
+ import { TokenData } from "../tokens/tokenData";
5
+ import { PathFinderResultStructOutput } from "../types/contracts/pathfinder/interfaces/IPathFinder";
6
+ import { BaseAdapter } from "./adapter";
7
+ import { EVMTx } from "./eventOrTx";
8
+ export interface BaseTradeInterface {
9
+ swapType: SwapType;
10
+ expectedAmount: BigNumber;
11
+ rate: BigNumber;
12
+ tokenFrom: string;
13
+ tokenTo: string;
14
+ operationName: string;
15
+ }
16
+ export interface TradeProps {
17
+ adapter: BaseAdapter;
18
+ tradePath: PathFinderResultStructOutput;
19
+ swapType: SwapType;
20
+ expectedAmount: BigNumber;
21
+ rate: BigNumber;
22
+ tokenFrom: string;
23
+ tokenTo: string;
24
+ operationName: string;
25
+ }
26
+ export interface ConnectTradeProps {
27
+ adapter: BaseAdapter;
28
+ tradePath: PathFinderResultStructOutput;
29
+ }
30
+ export declare class Trade implements BaseTradeInterface {
31
+ protected helper: BaseAdapter;
32
+ protected tradePath: PathFinderResultStructOutput;
33
+ readonly swapType: SwapType;
34
+ readonly expectedAmount: BigNumber;
35
+ readonly rate: BigNumber;
36
+ readonly tokenFrom: string;
37
+ readonly tokenTo: string;
38
+ readonly operationName: string;
39
+ constructor({ tradePath, adapter }: TradeProps);
40
+ static connect({ tradePath, adapter }: ConnectTradeProps): Trade;
41
+ getName(): string;
42
+ getAdapterInterface(): AdapterInterface;
43
+ getContractAddress(): string;
44
+ getAdapterAddress(): string;
45
+ execute(slippage: number, signer: Signer): Promise<EVMTx>;
46
+ toString(tokenData: Record<string, TokenData>): string;
47
+ getFromAmount(slippage: number): BigNumber;
48
+ getToAmount(slippage: number): BigNumber;
49
+ }
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Trade = void 0;
4
+ var ethers_1 = require("ethers");
5
+ var tradeTypes_1 = require("../pathfinder/tradeTypes");
6
+ var formatter_1 = require("../utils/formatter");
7
+ var adapter_1 = require("./adapter");
8
+ var constants_1 = require("./constants");
9
+ var Trade = /** @class */ (function () {
10
+ function Trade(_a) {
11
+ var tradePath = _a.tradePath, adapter = _a.adapter;
12
+ this.helper = adapter;
13
+ this.tradePath = tradePath;
14
+ this.swapType = tradeTypes_1.SwapType.ExactInput;
15
+ this.expectedAmount = ethers_1.BigNumber.from(0);
16
+ this.rate = ethers_1.BigNumber.from(0);
17
+ this.tokenFrom = "";
18
+ this.tokenTo = "";
19
+ this.operationName = "";
20
+ }
21
+ Trade.connect = function (_a) {
22
+ var tradePath = _a.tradePath, adapter = _a.adapter;
23
+ return new Trade({
24
+ tradePath: tradePath,
25
+ adapter: adapter,
26
+ swapType: tradeTypes_1.SwapType.ExactInput,
27
+ expectedAmount: ethers_1.BigNumber.from(0),
28
+ rate: ethers_1.BigNumber.from(0),
29
+ tokenFrom: "",
30
+ tokenTo: "",
31
+ operationName: "",
32
+ });
33
+ };
34
+ Trade.prototype.getName = function () {
35
+ return this.helper.name;
36
+ };
37
+ Trade.prototype.getAdapterInterface = function () {
38
+ return this.helper.adapterInterface;
39
+ };
40
+ Trade.prototype.getContractAddress = function () {
41
+ return this.helper.contractAddress;
42
+ };
43
+ Trade.prototype.getAdapterAddress = function () {
44
+ return this.helper.adapterAddress;
45
+ };
46
+ Trade.prototype.execute = function (slippage, signer) {
47
+ return this.helper.execute({ tradePath: this.tradePath, slippage: slippage, signer: signer });
48
+ };
49
+ Trade.prototype.toString = function (tokenData) {
50
+ var result = this.helper.type === adapter_1.AdapterType.Swap
51
+ ? "Swap "
52
+ : "".concat(this.operationName || "Farm", " ");
53
+ var fromToken = tokenData[this.tokenFrom];
54
+ var toToken = tokenData[this.tokenTo];
55
+ result += "".concat((0, formatter_1.formatBN)(this.tradePath.amount, fromToken.decimals), " ").concat(fromToken.symbol, " \u21D2 ").concat((0, formatter_1.formatBN)(this.expectedAmount, toToken.decimals), " ").concat(toToken.symbol, " on ").concat(this.helper.name);
56
+ return result;
57
+ };
58
+ Trade.prototype.getFromAmount = function (slippage) {
59
+ return this.expectedAmount
60
+ .mul(constants_1.PERCENTAGE_FACTOR)
61
+ .div(constants_1.PERCENTAGE_FACTOR + slippage);
62
+ };
63
+ Trade.prototype.getToAmount = function (slippage) {
64
+ return this.expectedAmount
65
+ .mul(constants_1.PERCENTAGE_FACTOR + slippage)
66
+ .div(constants_1.PERCENTAGE_FACTOR);
67
+ };
68
+ return Trade;
69
+ }());
70
+ exports.Trade = Trade;
@@ -0,0 +1,54 @@
1
+ import type { TransactionRequest } from "@ethersproject/abstract-provider";
2
+ import { BigNumber, BytesLike } from "ethers";
3
+ import { FunctionFragment } from "ethers/lib/utils";
4
+ export declare type TxType = "unsupported" | "swap" | "approve" | "lp";
5
+ export declare type LpOperationType = "withdraw" | "deposit";
6
+ export interface RawTransaction {
7
+ id: number;
8
+ method: "eth_sendTransaction";
9
+ params: [TransactionRequest];
10
+ }
11
+ export interface TxInfo {
12
+ from?: string;
13
+ to?: string;
14
+ amountFrom?: BigNumber;
15
+ amountTo?: BigNumber;
16
+ functionFragment: FunctionFragment;
17
+ }
18
+ export declare class SwapOperation {
19
+ readonly id: number;
20
+ operation?: string;
21
+ from?: string;
22
+ to?: string;
23
+ amountFrom?: BigNumber;
24
+ amountTo?: BigNumber;
25
+ tx?: TransactionRequest;
26
+ raw: RawTransaction;
27
+ kind: TxType;
28
+ protected calldata?: BytesLike;
29
+ isPending: boolean;
30
+ farm?: string;
31
+ lpOperationType?: LpOperationType;
32
+ static tokens: Record<string, boolean>;
33
+ constructor(raw: RawTransaction, kind: TxType);
34
+ static NewSwapOperation(params: {
35
+ adapter: string;
36
+ operation: string;
37
+ from: string;
38
+ to: string;
39
+ amountFrom: BigNumber;
40
+ amountTo: BigNumber;
41
+ raw: RawTransaction;
42
+ }): SwapOperation;
43
+ static NewLPOperation(params: {
44
+ adapter: string;
45
+ operation: string;
46
+ from: string;
47
+ amountFrom: BigNumber;
48
+ farm: string;
49
+ type: LpOperationType;
50
+ raw: RawTransaction;
51
+ }): SwapOperation;
52
+ static NewUnsupportedOperation(raw: RawTransaction): SwapOperation;
53
+ static NewApproveOperation(creditManager: string, raw: RawTransaction, token: string): SwapOperation;
54
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SwapOperation = void 0;
4
+ var types_1 = require("../types");
5
+ var SwapOperation = /** @class */ (function () {
6
+ function SwapOperation(raw, kind) {
7
+ this.id = raw.id;
8
+ this.raw = raw;
9
+ this.kind = kind;
10
+ this.isPending = false;
11
+ }
12
+ SwapOperation.NewSwapOperation = function (params) {
13
+ var _a, _b;
14
+ var newOperation = new SwapOperation(params.raw, "swap");
15
+ newOperation.operation = params.operation;
16
+ newOperation.from = params.from;
17
+ newOperation.to = params.to;
18
+ newOperation.amountFrom = params.amountFrom;
19
+ newOperation.amountTo = params.amountTo;
20
+ newOperation.raw = params.raw;
21
+ newOperation.calldata = (_b = (_a = params.raw) === null || _a === void 0 ? void 0 : _a.params[0]) === null || _b === void 0 ? void 0 : _b.data;
22
+ newOperation.tx = {
23
+ to: params.adapter,
24
+ data: newOperation.calldata,
25
+ };
26
+ return newOperation;
27
+ };
28
+ SwapOperation.NewLPOperation = function (params) {
29
+ var _a, _b;
30
+ var newOperation = new SwapOperation(params.raw, "lp");
31
+ newOperation.operation = params.operation;
32
+ newOperation.from = params.from;
33
+ newOperation.amountFrom = params.amountFrom;
34
+ newOperation.raw = params.raw;
35
+ newOperation.calldata = (_b = (_a = params.raw) === null || _a === void 0 ? void 0 : _a.params[0]) === null || _b === void 0 ? void 0 : _b.data;
36
+ newOperation.farm = params.farm;
37
+ newOperation.tx = {
38
+ to: params.adapter,
39
+ data: newOperation.calldata,
40
+ };
41
+ newOperation.lpOperationType = params.type;
42
+ return newOperation;
43
+ };
44
+ SwapOperation.NewUnsupportedOperation = function (raw) {
45
+ return new SwapOperation(raw, "unsupported");
46
+ };
47
+ SwapOperation.NewApproveOperation = function (creditManager, raw, token) {
48
+ var _a, _b;
49
+ var operation = new SwapOperation(raw, "approve");
50
+ operation.to = token;
51
+ operation.calldata = (_a = raw === null || raw === void 0 ? void 0 : raw.params[0]) === null || _a === void 0 ? void 0 : _a.data;
52
+ var tokenI = types_1.IERC20__factory.createInterface();
53
+ try {
54
+ var spender = tokenI.decodeFunctionData("approve", ((_b = raw === null || raw === void 0 ? void 0 : raw.params[0]) === null || _b === void 0 ? void 0 : _b.data) || "")[0];
55
+ var cmi = types_1.ICreditManager__factory.createInterface();
56
+ operation.from = spender;
57
+ // @ts-ignore
58
+ operation.calldata = cmi.encodeFunctionData("approve", [
59
+ spender,
60
+ operation.to,
61
+ ]);
62
+ operation.tx = {
63
+ to: creditManager,
64
+ data: operation.calldata,
65
+ };
66
+ return operation;
67
+ }
68
+ catch (e) {
69
+ console.error(e);
70
+ return SwapOperation.NewUnsupportedOperation(raw);
71
+ }
72
+ };
73
+ SwapOperation.tokens = {};
74
+ return SwapOperation;
75
+ }());
76
+ exports.SwapOperation = SwapOperation;
package/lib/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export * from "./contracts/contracts";
2
2
  export * from "./contracts/protocols";
3
+ export * from "./core/adapter";
4
+ export * from "./core/assets";
3
5
  export * from "./core/constants";
4
6
  export * from "./core/creditAccount";
5
7
  export * from "./core/creditManager";
@@ -11,7 +13,9 @@ export * from "./core/operations";
11
13
  export * from "./core/pool";
12
14
  export * from "./core/strategy";
13
15
  export * from "./core/tokenDistributor";
16
+ export * from "./core/trade";
14
17
  export * from "./core/transactions";
18
+ export * from "./core/wcOperation";
15
19
  export * from "./oracles/oracles";
16
20
  export * from "./oracles/priceFeeds";
17
21
  export * from "./payload/creditAccount";
package/lib/index.js CHANGED
@@ -17,6 +17,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.callRepeater = exports.swapKeyValue = exports.objectEntries = exports.keyToLowercase = exports.getUnderlyingToken = exports.getPoolTokens = exports.TokenType = exports.getContractName = exports.AdapterInterface = void 0;
18
18
  __exportStar(require("./contracts/contracts"), exports);
19
19
  __exportStar(require("./contracts/protocols"), exports);
20
+ __exportStar(require("./core/adapter"), exports);
21
+ __exportStar(require("./core/assets"), exports);
20
22
  __exportStar(require("./core/constants"), exports);
21
23
  __exportStar(require("./core/creditAccount"), exports);
22
24
  __exportStar(require("./core/creditManager"), exports);
@@ -28,7 +30,9 @@ __exportStar(require("./core/operations"), exports);
28
30
  __exportStar(require("./core/pool"), exports);
29
31
  __exportStar(require("./core/strategy"), exports);
30
32
  __exportStar(require("./core/tokenDistributor"), exports);
33
+ __exportStar(require("./core/trade"), exports);
31
34
  __exportStar(require("./core/transactions"), exports);
35
+ __exportStar(require("./core/wcOperation"), exports);
32
36
  __exportStar(require("./oracles/oracles"), exports);
33
37
  __exportStar(require("./oracles/priceFeeds"), exports);
34
38
  __exportStar(require("./payload/creditAccount"), exports);
@@ -4,3 +4,4 @@ export declare function rayMul(a: BigNumber, b: BigNumber): BigNumber;
4
4
  export declare function rayDiv(a: BigNumber, b: BigNumber): BigNumber;
5
5
  export declare function percentMul(a: BigNumber, b: number): BigNumber;
6
6
  export declare function sqrt(x: BigNumber): BigNumber;
7
+ export declare const nonNegativeBn: (v: BigNumber) => BigNumber;
package/lib/utils/math.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sqrt = exports.percentMul = exports.rayDiv = exports.rayMul = exports.revertRay = void 0;
3
+ exports.nonNegativeBn = exports.sqrt = exports.percentMul = exports.rayDiv = exports.rayMul = exports.revertRay = void 0;
4
4
  var ethers_1 = require("ethers");
5
5
  var constants_1 = require("../core/constants");
6
6
  var ONE = ethers_1.BigNumber.from(1);
@@ -42,3 +42,7 @@ function sqrt(x) {
42
42
  return y;
43
43
  }
44
44
  exports.sqrt = sqrt;
45
+ var nonNegativeBn = function (v) {
46
+ return v.isNegative() ? ethers_1.BigNumber.from(0) : v;
47
+ };
48
+ exports.nonNegativeBn = nonNegativeBn;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gearbox-protocol/sdk",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Gearbox SDK",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",