@gearbox-protocol/sdk 1.5.5 → 1.5.8

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 (47) hide show
  1. package/lib/contracts/contracts.d.ts +1 -0
  2. package/lib/contracts/contracts.js +3 -0
  3. package/lib/core/creditManager.d.ts +1 -1
  4. package/lib/core/creditManager.js +1 -1
  5. package/lib/index.d.ts +0 -1
  6. package/lib/index.js +0 -1
  7. package/lib/parsers/curveAdapterParser.d.ts +1 -0
  8. package/lib/parsers/curveAdapterParser.js +17 -3
  9. package/lib/parsers/curveAdapterParser.spec.js +1 -1
  10. package/lib/pathfinder/core.d.ts +22 -0
  11. package/lib/pathfinder/core.js +9 -0
  12. package/lib/pathfinder/pathOptions.d.ts +11 -0
  13. package/lib/pathfinder/pathOptions.js +74 -0
  14. package/lib/pathfinder/pathOptions.spec.d.ts +1 -0
  15. package/lib/pathfinder/pathOptions.spec.js +90 -0
  16. package/lib/pathfinder/pathfinder.d.ts +24 -0
  17. package/lib/pathfinder/pathfinder.js +177 -0
  18. package/lib/pathfinder/pathfinder.spec.d.ts +1 -0
  19. package/lib/pathfinder/pathfinder.spec.js +21 -0
  20. package/lib/types/contracts/interfaces/IAddressProvider.sol/IAddressProvider.d.ts +9 -1
  21. package/lib/types/contracts/interfaces/adapters/lido/ILidoV1Adapter.sol/ILidoV1Adapter.d.ts +17 -1
  22. package/lib/types/contracts/pathfinder/interfaces/IClosePathResolver.d.ts +4 -1
  23. package/lib/types/contracts/pathfinder/interfaces/IDepositor.sol/IDepositor.d.ts +6 -3
  24. package/lib/types/contracts/pathfinder/interfaces/IDepositor.sol/IDepositorOptions.d.ts +7 -4
  25. package/lib/types/contracts/pathfinder/interfaces/ILPWorker.sol/ILPWorker.d.ts +4 -1
  26. package/lib/types/contracts/pathfinder/interfaces/ILPWorker.sol/ILPWorkerOptions.d.ts +4 -1
  27. package/lib/types/contracts/pathfinder/interfaces/IPathFinder.d.ts +20 -7
  28. package/lib/types/contracts/pathfinder/interfaces/IPathResolver.d.ts +5 -2
  29. package/lib/types/contracts/pathfinder/interfaces/ISwapAggregator.d.ts +8 -5
  30. package/lib/types/contracts/pathfinder/interfaces/IWithdrawer.sol/IWithdrawer.d.ts +7 -4
  31. package/lib/types/contracts/pathfinder/interfaces/IWithdrawer.sol/IWithdrawerOptions.d.ts +7 -4
  32. package/lib/types/factories/contracts/interfaces/IAddressProvider.sol/IAddressProvider__factory.js +13 -0
  33. package/lib/types/factories/contracts/interfaces/adapters/lido/ILidoV1Adapter.sol/ILidoV1Adapter__factory.js +26 -0
  34. package/lib/types/factories/contracts/pathfinder/interfaces/IClosePathResolver__factory.js +10 -0
  35. package/lib/types/factories/contracts/pathfinder/interfaces/IDepositor.sol/IDepositorOptions__factory.js +40 -0
  36. package/lib/types/factories/contracts/pathfinder/interfaces/IDepositor.sol/IDepositor__factory.js +30 -0
  37. package/lib/types/factories/contracts/pathfinder/interfaces/ILPWorker.sol/ILPWorkerOptions__factory.js +10 -0
  38. package/lib/types/factories/contracts/pathfinder/interfaces/ILPWorker.sol/ILPWorker__factory.js +10 -0
  39. package/lib/types/factories/contracts/pathfinder/interfaces/IPathFinder__factory.d.ts +7 -17
  40. package/lib/types/factories/contracts/pathfinder/interfaces/IPathFinder__factory.js +10 -0
  41. package/lib/types/factories/contracts/pathfinder/interfaces/IPathResolver__factory.js +20 -0
  42. package/lib/types/factories/contracts/pathfinder/interfaces/ISwapAggregator__factory.js +50 -0
  43. package/lib/types/factories/contracts/pathfinder/interfaces/IWithdrawer.sol/IWithdrawerOptions__factory.js +40 -0
  44. package/lib/types/factories/contracts/pathfinder/interfaces/IWithdrawer.sol/IWithdrawer__factory.js +40 -0
  45. package/package.json +3 -1
  46. package/lib/tokens/connectors.d.ts +0 -2
  47. package/lib/tokens/connectors.js +0 -9
@@ -29,6 +29,7 @@ export declare type CurveParams = {
29
29
  type: AdapterInterface.CURVE_V1_2ASSETS | AdapterInterface.CURVE_V1_3ASSETS | AdapterInterface.CURVE_V1_4ASSETS | AdapterInterface.CURVE_V1_WRAPPER;
30
30
  lpToken: CurveLPToken;
31
31
  tokens: Array<NormalToken | CurveLPToken>;
32
+ underlyings?: Array<NormalToken>;
32
33
  wrapper?: CurvePoolContract;
33
34
  } & BaseContractParams;
34
35
  export declare type CurveSteCRVPoolParams = {
@@ -126,6 +126,7 @@ exports.contractParams = {
126
126
  type: adapters_1.AdapterInterface.CURVE_V1_2ASSETS,
127
127
  lpToken: "FRAX3CRV",
128
128
  tokens: ["FRAX", "3Crv"],
129
+ underlyings: ["FRAX", "DAI", "USDC", "USDT"],
129
130
  },
130
131
  CURVE_LUSD_POOL: {
131
132
  name: "Curve LUSD",
@@ -133,6 +134,7 @@ exports.contractParams = {
133
134
  type: adapters_1.AdapterInterface.CURVE_V1_2ASSETS,
134
135
  lpToken: "LUSD3CRV",
135
136
  tokens: ["LUSD", "3Crv"],
137
+ underlyings: ["LUSD", "DAI", "USDC", "USDT"],
136
138
  },
137
139
  CURVE_SUSD_POOL: {
138
140
  name: "Curve SUSD",
@@ -155,6 +157,7 @@ exports.contractParams = {
155
157
  type: adapters_1.AdapterInterface.CURVE_V1_2ASSETS,
156
158
  lpToken: "gusd3CRV",
157
159
  tokens: ["GUSD", "3Crv"],
160
+ underlyings: ["GUSD", "DAI", "USDC", "USDT"],
158
161
  },
159
162
  YEARN_DAI_VAULT: {
160
163
  name: "Yearn DAI",
@@ -15,7 +15,7 @@ export declare class CreditManagerData {
15
15
  readonly maxAmount: BigNumber;
16
16
  readonly maxLeverageFactor: number;
17
17
  readonly availableLiquidity: BigNumber;
18
- readonly allowedTokens: Array<string>;
18
+ readonly collateralTokens: Array<string>;
19
19
  readonly adapters: Record<string, string>;
20
20
  readonly liquidationThresholds: Record<string, BigNumber>;
21
21
  readonly version: number;
@@ -52,7 +52,7 @@ var CreditManagerData = /** @class */ (function () {
52
52
  this.maxAmount = ethers_1.BigNumber.from(payload.maxAmount || 0);
53
53
  this.maxLeverageFactor = ethers_1.BigNumber.from(payload.maxLeverageFactor || 0).toNumber();
54
54
  this.availableLiquidity = ethers_1.BigNumber.from(payload.availableLiquidity || 0);
55
- this.allowedTokens = (payload.collateralTokens || []).map(function (t) {
55
+ this.collateralTokens = (payload.collateralTokens || []).map(function (t) {
56
56
  return t.toLowerCase();
57
57
  });
58
58
  this.adapters = (payload.adapters || []).reduce(function (acc, _a) {
package/lib/index.d.ts CHANGED
@@ -42,7 +42,6 @@ export * from "./strategies/lido";
42
42
  export * from "./strategies/uniswapV2";
43
43
  export * from "./strategies/uniswapV3";
44
44
  export * from "./strategies/yearn";
45
- export * from "./tokens/connectors";
46
45
  export * from "./tokens/convex";
47
46
  export * from "./tokens/curveLP";
48
47
  export * from "./tokens/decimals";
package/lib/index.js CHANGED
@@ -62,7 +62,6 @@ __exportStar(require("./strategies/lido"), exports);
62
62
  __exportStar(require("./strategies/uniswapV2"), exports);
63
63
  __exportStar(require("./strategies/uniswapV3"), exports);
64
64
  __exportStar(require("./strategies/yearn"), exports);
65
- __exportStar(require("./tokens/connectors"), exports);
66
65
  __exportStar(require("./tokens/convex"), exports);
67
66
  __exportStar(require("./tokens/curveLP"), exports);
68
67
  __exportStar(require("./tokens/decimals"), exports);
@@ -8,5 +8,6 @@ export declare class CurveAdapterParser extends AbstractParser implements IParse
8
8
  constructor(contract: SupportedContract, isContract: boolean);
9
9
  parse(calldata: string): string;
10
10
  getTokenByIndex(index: number): SupportedToken;
11
+ getUnderlyingTokenByIndex(index: number): SupportedToken;
11
12
  convertAmounts(amounts: Array<BigNumberish>): string;
12
13
  }
@@ -53,14 +53,24 @@ var CurveAdapterParser = /** @class */ (function (_super) {
53
53
  case "exchange":
54
54
  case "exchange_underlying": {
55
55
  var _b = this.decodeFunctionData(functionFragment, calldata), i = _b[0], j = _b[1], dx = _b[2], min_dy = _b[3];
56
- var iSym = this.getTokenByIndex(i);
57
- var jSym = this.getTokenByIndex(j);
56
+ var iSym = functionFragment.name === "exchange_underlying"
57
+ ? this.getUnderlyingTokenByIndex(i)
58
+ : this.getTokenByIndex(i);
59
+ var jSym = functionFragment.name === "exchange_underlying"
60
+ ? this.getUnderlyingTokenByIndex(j)
61
+ : this.getTokenByIndex(j);
58
62
  return "".concat(functionName, "(i ,j: ").concat(iSym, " => ").concat(jSym, ", dx: ").concat(this.formatBN(dx, iSym), ", min_dy: ").concat(this.formatBN(min_dy, jSym), ")");
59
63
  }
60
64
  case "exchange_all":
61
65
  case "exchange_all_underlying": {
62
66
  var _c = this.decodeFunctionData(functionFragment, calldata), i = _c[0], j = _c[1], rateMinRAY = _c[2];
63
- return "".concat(functionName, "(i: ").concat(this.getTokenByIndex(i), ", j: ").concat(this.getTokenByIndex(j), ", rateMinRAY: ").concat((0, formatter_1.formatBN)(rateMinRAY, 27));
67
+ var iSym = functionFragment.name === "exchange_all_underlying"
68
+ ? this.getUnderlyingTokenByIndex(i)
69
+ : this.getTokenByIndex(i);
70
+ var jSym = functionFragment.name === "exchange_all_underlying"
71
+ ? this.getUnderlyingTokenByIndex(j)
72
+ : this.getTokenByIndex(j);
73
+ return "".concat(functionName, "(i: ").concat(iSym, ", j: ").concat(jSym, ", rateMinRAY: ").concat((0, formatter_1.formatBN)(rateMinRAY, 27));
64
74
  }
65
75
  case "add_liquidity_one_coin": {
66
76
  var _d = this.decodeFunctionData(functionFragment, calldata), amount = _d[0], i = _d[1], minAmount = _d[2];
@@ -92,6 +102,10 @@ var CurveAdapterParser = /** @class */ (function (_super) {
92
102
  return contracts_1.contractParams[this.contract]
93
103
  .tokens[index];
94
104
  };
105
+ CurveAdapterParser.prototype.getUnderlyingTokenByIndex = function (index) {
106
+ return contracts_1.contractParams[this.contract]
107
+ .underlyings[index];
108
+ };
95
109
  CurveAdapterParser.prototype.convertAmounts = function (amounts) {
96
110
  var _this = this;
97
111
  return amounts
@@ -16,7 +16,7 @@ describe("CurveAdapterParser test", function () {
16
16
  constants_1.WAD.mul(3),
17
17
  constants_1.WAD.mul(32),
18
18
  ]));
19
- (0, chai_1.expect)(parsed).to.be.eq("Curve2AssetsAdapter[CURVE_FRAX_POOL].exchange_underlying(i ,j: FRAX => 3Crv, dx: 3.00 [3000000000000000000], min_dy: 32.00 [32000000000000000000])", "Curve2AssetsAdapter: Incorrect parse exchange_underlying");
19
+ (0, chai_1.expect)(parsed).to.be.eq("Curve2AssetsAdapter[CURVE_FRAX_POOL].exchange_underlying(i ,j: FRAX => DAI, dx: 3.00 [3000000000000000000], min_dy: 32.00 [32000000000000000000])", "Curve2AssetsAdapter: Incorrect parse exchange_underlying");
20
20
  parsed = parser.parse(ifc.encodeFunctionData("add_liquidity_one_coin", [
21
21
  constants_1.WAD.mul(3),
22
22
  0,
@@ -0,0 +1,22 @@
1
+ import { BigNumber } from "ethers";
2
+ export declare enum SwapOperation {
3
+ EXACT_INPUT = 0,
4
+ EXACT_INPUT_ALL = 1,
5
+ EXACT_OUTPUT = 2
6
+ }
7
+ export interface MultiCall {
8
+ target: string;
9
+ callData: string;
10
+ }
11
+ export interface PathFinderResult {
12
+ amount: BigNumber;
13
+ calls: Array<MultiCall>;
14
+ }
15
+ export interface PathFinderOpenStrategyResult {
16
+ balances: Record<string, BigNumber>;
17
+ calls: Array<MultiCall>;
18
+ }
19
+ export interface PathFinderCloseResult {
20
+ underlyingBalance: BigNumber;
21
+ calls: Array<MultiCall>;
22
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SwapOperation = void 0;
4
+ var SwapOperation;
5
+ (function (SwapOperation) {
6
+ SwapOperation[SwapOperation["EXACT_INPUT"] = 0] = "EXACT_INPUT";
7
+ SwapOperation[SwapOperation["EXACT_INPUT_ALL"] = 1] = "EXACT_INPUT_ALL";
8
+ SwapOperation[SwapOperation["EXACT_OUTPUT"] = 2] = "EXACT_OUTPUT";
9
+ })(SwapOperation = exports.SwapOperation || (exports.SwapOperation = {}));
@@ -0,0 +1,11 @@
1
+ import { BigNumberish } from "ethers";
2
+ export interface PathOption {
3
+ target: string;
4
+ option: number;
5
+ totalOptions: number;
6
+ }
7
+ export declare type PathOptionSerie = Array<PathOption>;
8
+ export declare class PathOptionFactory {
9
+ static generatePathOptions(balances: Record<string, BigNumberish>, loopsInTx: number): Array<PathOptionSerie>;
10
+ static next(path: PathOptionSerie): PathOptionSerie;
11
+ }
@@ -0,0 +1,74 @@
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
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
14
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
15
+ if (ar || !(i in from)) {
16
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
17
+ ar[i] = from[i];
18
+ }
19
+ }
20
+ return to.concat(ar || Array.prototype.slice.call(from));
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.PathOptionFactory = void 0;
24
+ var ethers_1 = require("ethers");
25
+ var contracts_1 = require("../contracts/contracts");
26
+ var curveLP_1 = require("../tokens/curveLP");
27
+ var token_1 = require("../tokens/token");
28
+ var PathOptionFactory = /** @class */ (function () {
29
+ function PathOptionFactory() {
30
+ }
31
+ PathOptionFactory.generatePathOptions = function (balances, loopsInTx) {
32
+ var curveSymbols = Object.keys(curveLP_1.curveTokens);
33
+ var initPO = Object.entries(balances)
34
+ .filter(function (_a) {
35
+ var token = _a[0], balance = _a[1];
36
+ return ethers_1.BigNumber.from(balance).gt(1) &&
37
+ curveSymbols.includes(token_1.tokenSymbolByAddress[token.toLowerCase()]);
38
+ })
39
+ .map(function (_a) {
40
+ var target = _a[0];
41
+ return {
42
+ target: target,
43
+ option: 0,
44
+ totalOptions: contracts_1.contractParams[curveLP_1.curveTokens[token_1.tokenSymbolByAddress[target.toLowerCase()]].pool].tokens.length,
45
+ };
46
+ });
47
+ var totalLoops = initPO.reduce(function (acc, item) { return acc * item.totalOptions; }, 1);
48
+ var result = [];
49
+ var currentPo = __spreadArray([], initPO, true);
50
+ for (var i = 0; i < totalLoops; i++) {
51
+ if (i % loopsInTx === 0) {
52
+ result.push(currentPo);
53
+ }
54
+ if (i < totalLoops - 1) {
55
+ currentPo = PathOptionFactory.next(currentPo);
56
+ }
57
+ }
58
+ return result;
59
+ };
60
+ PathOptionFactory.next = function (path) {
61
+ var newPath = __spreadArray([], path, true);
62
+ for (var i = path.length - 1; i >= 0; i--) {
63
+ var po = __assign({}, newPath[i]);
64
+ po.option++;
65
+ newPath[i] = po;
66
+ if (po.option < po.totalOptions)
67
+ return newPath;
68
+ po.option = 0;
69
+ }
70
+ throw new Error("Path options overflow");
71
+ };
72
+ return PathOptionFactory;
73
+ }());
74
+ exports.PathOptionFactory = PathOptionFactory;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var chai_1 = require("chai");
4
+ var token_1 = require("../tokens/token");
5
+ var pathOptions_1 = require("./pathOptions");
6
+ describe("PathOptionFactory test", function () {
7
+ it("next works correctly", function () {
8
+ var serie = [
9
+ {
10
+ target: token_1.tokenDataByNetwork.Mainnet["3Crv"],
11
+ option: 0,
12
+ totalOptions: 3,
13
+ },
14
+ {
15
+ target: token_1.tokenDataByNetwork.Mainnet.FRAX3CRV,
16
+ option: 0,
17
+ totalOptions: 2,
18
+ },
19
+ {
20
+ target: token_1.tokenDataByNetwork.Mainnet.LUSD3CRV,
21
+ option: 0,
22
+ totalOptions: 2,
23
+ },
24
+ ];
25
+ var expectedNext = JSON.parse(JSON.stringify(serie));
26
+ expectedNext[2].option = 1;
27
+ var next = pathOptions_1.PathOptionFactory.next(serie);
28
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
29
+ expectedNext[1].option = 1;
30
+ expectedNext[2].option = 0;
31
+ next = pathOptions_1.PathOptionFactory.next(next);
32
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
33
+ expectedNext[1].option = 1;
34
+ expectedNext[2].option = 1;
35
+ next = pathOptions_1.PathOptionFactory.next(next);
36
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
37
+ expectedNext[0].option = 1;
38
+ expectedNext[1].option = 0;
39
+ expectedNext[2].option = 0;
40
+ next = pathOptions_1.PathOptionFactory.next(next);
41
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
42
+ expectedNext[0].option = 1;
43
+ expectedNext[1].option = 0;
44
+ expectedNext[2].option = 1;
45
+ next = pathOptions_1.PathOptionFactory.next(next);
46
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
47
+ expectedNext[0].option = 1;
48
+ expectedNext[1].option = 1;
49
+ expectedNext[2].option = 0;
50
+ next = pathOptions_1.PathOptionFactory.next(next);
51
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
52
+ expectedNext[0].option = 1;
53
+ expectedNext[1].option = 1;
54
+ expectedNext[2].option = 1;
55
+ next = pathOptions_1.PathOptionFactory.next(next);
56
+ (0, chai_1.expect)(next).to.be.eql(expectedNext);
57
+ });
58
+ it("generatePathOptions works correctly", function () {
59
+ var _a;
60
+ var balances = (_a = {},
61
+ _a[token_1.tokenDataByNetwork.Mainnet["1INCH"]] = 100,
62
+ _a[token_1.tokenDataByNetwork.Mainnet["3Crv"]] = 200,
63
+ _a[token_1.tokenDataByNetwork.Mainnet.USDC] = 200,
64
+ _a[token_1.tokenDataByNetwork.Mainnet.FRAX3CRV] = 200,
65
+ _a[token_1.tokenDataByNetwork.Mainnet.LUSD3CRV] = 200,
66
+ _a);
67
+ var result = pathOptions_1.PathOptionFactory.generatePathOptions(balances, 4);
68
+ var expected = [
69
+ {
70
+ target: token_1.tokenDataByNetwork.Mainnet["3Crv"],
71
+ option: 0,
72
+ totalOptions: 3,
73
+ },
74
+ {
75
+ target: token_1.tokenDataByNetwork.Mainnet.FRAX3CRV,
76
+ option: 0,
77
+ totalOptions: 2,
78
+ },
79
+ {
80
+ target: token_1.tokenDataByNetwork.Mainnet.LUSD3CRV,
81
+ option: 0,
82
+ totalOptions: 2,
83
+ },
84
+ ];
85
+ for (var i = 0; i < 3; i++) {
86
+ expected[0].option = i;
87
+ (0, chai_1.expect)(expected).to.be.eql(result[i]);
88
+ }
89
+ });
90
+ });
@@ -0,0 +1,24 @@
1
+ import { Provider } from "@ethersproject/abstract-provider";
2
+ import { BigNumber, BigNumberish, Signer } from "ethers";
3
+ import { NetworkType } from "../core/constants";
4
+ import { CreditAccountData } from "../core/creditAccount";
5
+ import { CreditManagerData } from "../core/creditManager";
6
+ import { SupportedToken } from "../tokens/token";
7
+ import { IPathFinder } from "../types";
8
+ import { PathFinderOpenStrategyResult, PathFinderResult, SwapOperation } from "./core";
9
+ export interface CloseResult {
10
+ amount: BigNumberish;
11
+ gasUsage: BigNumberish;
12
+ }
13
+ export declare class PathFinder {
14
+ pathFinder: IPathFinder;
15
+ network: NetworkType;
16
+ static connectors: Array<SupportedToken>;
17
+ protected readonly _connectors: Array<string>;
18
+ constructor(address: string, provider: Signer | Provider, network?: NetworkType, connectors?: Array<SupportedToken>);
19
+ findAllSwaps(creditAccount: CreditAccountData, swapOperation: SwapOperation, tokenIn: SupportedToken | string, tokenOut: SupportedToken | string, amount: BigNumberish, slippage: number): Promise<Array<PathFinderResult>>;
20
+ findOneTokenPath(creditAccount: CreditAccountData, tokenIn: SupportedToken | string, tokenOut: SupportedToken | string, amount: BigNumberish, slippage: number): Promise<PathFinderResult>;
21
+ findOpenStrategyPath(cm: CreditManagerData, expectedBalances: Record<SupportedToken | string, BigNumberish>, target: SupportedToken | string, slippage: number): Promise<PathFinderOpenStrategyResult>;
22
+ findBestClosePath(creditAccount: CreditAccountData, slippage: number): Promise<BigNumber>;
23
+ static compare(r1: CloseResult, r2: CloseResult, gasPriceRAY: BigNumberish): CloseResult;
24
+ }
@@ -0,0 +1,177 @@
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.PathFinder = void 0;
40
+ var ethers_1 = require("ethers");
41
+ var constants_1 = require("../core/constants");
42
+ var token_1 = require("../tokens/token");
43
+ var types_1 = require("../types");
44
+ var pathOptions_1 = require("./pathOptions");
45
+ var MAX_GAS_PER_ROUTE = 14e6;
46
+ var GAS_PER_BLOCK = 30e6;
47
+ var PathFinder = /** @class */ (function () {
48
+ function PathFinder(address, provider, network, connectors) {
49
+ if (network === void 0) { network = "Mainnet"; }
50
+ var _this = this;
51
+ this.pathFinder = types_1.IPathFinder__factory.connect(address, provider);
52
+ this.network = network;
53
+ this._connectors = (connectors || PathFinder.connectors).map(function (c) { return token_1.tokenDataByNetwork[_this.network][c]; });
54
+ }
55
+ PathFinder.prototype.findAllSwaps = function (creditAccount, swapOperation, tokenIn, tokenOut, amount, slippage) {
56
+ return __awaiter(this, void 0, void 0, function () {
57
+ var swapTask, results;
58
+ return __generator(this, function (_a) {
59
+ switch (_a.label) {
60
+ case 0:
61
+ swapTask = {
62
+ swapOperation: swapOperation,
63
+ creditAccount: creditAccount.addr,
64
+ tokenIn: token_1.tokenDataByNetwork[this.network][tokenIn] || tokenIn,
65
+ tokenOut: token_1.tokenDataByNetwork[this.network][tokenOut] ||
66
+ tokenOut,
67
+ connectors: this._connectors,
68
+ amount: amount,
69
+ slippage: slippage,
70
+ externalSlippage: false,
71
+ };
72
+ return [4 /*yield*/, this.pathFinder.callStatic.findAllSwaps(swapTask)];
73
+ case 1:
74
+ results = _a.sent();
75
+ return [2 /*return*/, results.map(function (r) { return ({
76
+ amount: ethers_1.BigNumber.from(r.amount),
77
+ gasUsage: r.gasUsage.toNumber(),
78
+ calls: r.calls,
79
+ }); })];
80
+ }
81
+ });
82
+ });
83
+ };
84
+ PathFinder.prototype.findOneTokenPath = function (creditAccount, tokenIn, tokenOut, amount, slippage) {
85
+ return __awaiter(this, void 0, void 0, function () {
86
+ var tokenInAddr, result;
87
+ return __generator(this, function (_a) {
88
+ switch (_a.label) {
89
+ case 0:
90
+ tokenInAddr = token_1.tokenDataByNetwork[this.network][tokenIn] || tokenIn;
91
+ if (creditAccount.balances[tokenInAddr.toLowerCase()].lt(amount)) {
92
+ throw new Error("Not enough balance for token ".concat(tokenIn));
93
+ }
94
+ return [4 /*yield*/, this.pathFinder.callStatic.findOneTokenPath(tokenInAddr, amount, token_1.tokenDataByNetwork[this.network][tokenOut] || tokenOut, creditAccount.addr, this._connectors, slippage)];
95
+ case 1:
96
+ result = _a.sent();
97
+ return [2 /*return*/, {
98
+ amount: ethers_1.BigNumber.from(result.amount),
99
+ calls: result.calls,
100
+ }];
101
+ }
102
+ });
103
+ });
104
+ };
105
+ PathFinder.prototype.findOpenStrategyPath = function (cm, expectedBalances, target, slippage) {
106
+ return __awaiter(this, void 0, void 0, function () {
107
+ var targetAddr, expectedBalancesAddr, balances, result, balancesAfter;
108
+ var _this = this;
109
+ return __generator(this, function (_a) {
110
+ switch (_a.label) {
111
+ case 0:
112
+ targetAddr = token_1.tokenDataByNetwork[this.network][target] || target;
113
+ expectedBalancesAddr = Object.entries(expectedBalances).reduce(function (acc, _a) {
114
+ var token = _a[0], balance = _a[1];
115
+ var tokenAddr = token_1.tokenDataByNetwork[_this.network][token] || token;
116
+ acc[tokenAddr.toLowerCase()] = balance;
117
+ return acc;
118
+ }, {});
119
+ balances = cm.collateralTokens.map(function (token) { return ({
120
+ token: token,
121
+ balance: expectedBalancesAddr[token] || 0,
122
+ }); });
123
+ return [4 /*yield*/, this.pathFinder.callStatic.findOpenStrategyPath(cm.address, balances, targetAddr, this._connectors, slippage)];
124
+ case 1:
125
+ result = _a.sent();
126
+ balancesAfter = result[0].reduce(function (acc, b) {
127
+ acc[b.token.toLowerCase()] = ethers_1.BigNumber.from(b.balance);
128
+ return acc;
129
+ }, {});
130
+ return [2 /*return*/, {
131
+ balances: balancesAfter,
132
+ calls: result[1].calls,
133
+ }];
134
+ }
135
+ });
136
+ });
137
+ };
138
+ PathFinder.prototype.findBestClosePath = function (creditAccount, slippage) {
139
+ return __awaiter(this, void 0, void 0, function () {
140
+ var loopsPerTx, pathOptions, requests, results, bestResult;
141
+ var _this = this;
142
+ return __generator(this, function (_a) {
143
+ switch (_a.label) {
144
+ case 0:
145
+ loopsPerTx = GAS_PER_BLOCK / MAX_GAS_PER_ROUTE;
146
+ pathOptions = pathOptions_1.PathOptionFactory.generatePathOptions(creditAccount.allBalances, loopsPerTx);
147
+ requests = pathOptions.map(function (po) {
148
+ return _this.pathFinder.callStatic.findBestClosePath(creditAccount.addr, _this._connectors, slippage, po, loopsPerTx, false);
149
+ });
150
+ return [4 /*yield*/, Promise.all(requests)];
151
+ case 1:
152
+ results = _a.sent();
153
+ bestResult = results.reduce(function (best, _a) {
154
+ var pathFinderResult = _a[0], gasPriceRAY = _a[1];
155
+ return PathFinder.compare(best, pathFinderResult, gasPriceRAY);
156
+ }, {
157
+ amount: ethers_1.BigNumber.from(0),
158
+ gasUsage: 0,
159
+ });
160
+ return [2 /*return*/, ethers_1.BigNumber.from(bestResult.amount)];
161
+ }
162
+ });
163
+ });
164
+ };
165
+ PathFinder.compare = function (r1, r2, gasPriceRAY) {
166
+ var comparator = function (_a, gasPrice) {
167
+ var amount = _a.amount, gasUsage = _a.gasUsage;
168
+ return ethers_1.BigNumber.from(amount).sub(ethers_1.BigNumber.from(gasUsage).mul(gasPrice).div(constants_1.RAY));
169
+ };
170
+ return comparator(r1, gasPriceRAY).gt(comparator(r2, gasPriceRAY))
171
+ ? r1
172
+ : r2;
173
+ };
174
+ PathFinder.connectors = ["USDC", "WETH", "DAI"];
175
+ return PathFinder;
176
+ }());
177
+ exports.PathFinder = PathFinder;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var chai_1 = require("chai");
4
+ var constants_1 = require("../core/constants");
5
+ var pathfinder_1 = require("./pathfinder");
6
+ describe("PathFinder test", function () {
7
+ it("compare works correctly", function () {
8
+ var r1 = {
9
+ amount: 2000,
10
+ gasUsage: 1000,
11
+ };
12
+ var r2 = {
13
+ amount: 3000,
14
+ gasUsage: 2000,
15
+ };
16
+ var result = pathfinder_1.PathFinder.compare(r1, r2, constants_1.RAY);
17
+ (0, chai_1.expect)(result).to.be.eql(r2);
18
+ result = pathfinder_1.PathFinder.compare(r1, r2, constants_1.RAY.mul(2));
19
+ (0, chai_1.expect)(result).to.be.eql(r1);
20
+ });
21
+ });
@@ -9,18 +9,20 @@ export interface IAddressProviderInterface extends utils.Interface {
9
9
  "getContractsRegister()": FunctionFragment;
10
10
  "getDataCompressor()": FunctionFragment;
11
11
  "getGearToken()": FunctionFragment;
12
+ "getLeveragedActions()": FunctionFragment;
12
13
  "getPriceOracle()": FunctionFragment;
13
14
  "getTreasuryContract()": FunctionFragment;
14
15
  "getWETHGateway()": FunctionFragment;
15
16
  "getWethToken()": FunctionFragment;
16
17
  "version()": FunctionFragment;
17
18
  };
18
- getFunction(nameOrSignatureOrTopic: "getACL" | "getAccountFactory" | "getContractsRegister" | "getDataCompressor" | "getGearToken" | "getPriceOracle" | "getTreasuryContract" | "getWETHGateway" | "getWethToken" | "version"): FunctionFragment;
19
+ getFunction(nameOrSignatureOrTopic: "getACL" | "getAccountFactory" | "getContractsRegister" | "getDataCompressor" | "getGearToken" | "getLeveragedActions" | "getPriceOracle" | "getTreasuryContract" | "getWETHGateway" | "getWethToken" | "version"): FunctionFragment;
19
20
  encodeFunctionData(functionFragment: "getACL", values?: undefined): string;
20
21
  encodeFunctionData(functionFragment: "getAccountFactory", values?: undefined): string;
21
22
  encodeFunctionData(functionFragment: "getContractsRegister", values?: undefined): string;
22
23
  encodeFunctionData(functionFragment: "getDataCompressor", values?: undefined): string;
23
24
  encodeFunctionData(functionFragment: "getGearToken", values?: undefined): string;
25
+ encodeFunctionData(functionFragment: "getLeveragedActions", values?: undefined): string;
24
26
  encodeFunctionData(functionFragment: "getPriceOracle", values?: undefined): string;
25
27
  encodeFunctionData(functionFragment: "getTreasuryContract", values?: undefined): string;
26
28
  encodeFunctionData(functionFragment: "getWETHGateway", values?: undefined): string;
@@ -31,6 +33,7 @@ export interface IAddressProviderInterface extends utils.Interface {
31
33
  decodeFunctionResult(functionFragment: "getContractsRegister", data: BytesLike): Result;
32
34
  decodeFunctionResult(functionFragment: "getDataCompressor", data: BytesLike): Result;
33
35
  decodeFunctionResult(functionFragment: "getGearToken", data: BytesLike): Result;
36
+ decodeFunctionResult(functionFragment: "getLeveragedActions", data: BytesLike): Result;
34
37
  decodeFunctionResult(functionFragment: "getPriceOracle", data: BytesLike): Result;
35
38
  decodeFunctionResult(functionFragment: "getTreasuryContract", data: BytesLike): Result;
36
39
  decodeFunctionResult(functionFragment: "getWETHGateway", data: BytesLike): Result;
@@ -70,6 +73,7 @@ export interface IAddressProvider extends BaseContract {
70
73
  getContractsRegister(overrides?: CallOverrides): Promise<[string]>;
71
74
  getDataCompressor(overrides?: CallOverrides): Promise<[string]>;
72
75
  getGearToken(overrides?: CallOverrides): Promise<[string]>;
76
+ getLeveragedActions(overrides?: CallOverrides): Promise<[string]>;
73
77
  getPriceOracle(overrides?: CallOverrides): Promise<[string]>;
74
78
  getTreasuryContract(overrides?: CallOverrides): Promise<[string]>;
75
79
  getWETHGateway(overrides?: CallOverrides): Promise<[string]>;
@@ -81,6 +85,7 @@ export interface IAddressProvider extends BaseContract {
81
85
  getContractsRegister(overrides?: CallOverrides): Promise<string>;
82
86
  getDataCompressor(overrides?: CallOverrides): Promise<string>;
83
87
  getGearToken(overrides?: CallOverrides): Promise<string>;
88
+ getLeveragedActions(overrides?: CallOverrides): Promise<string>;
84
89
  getPriceOracle(overrides?: CallOverrides): Promise<string>;
85
90
  getTreasuryContract(overrides?: CallOverrides): Promise<string>;
86
91
  getWETHGateway(overrides?: CallOverrides): Promise<string>;
@@ -92,6 +97,7 @@ export interface IAddressProvider extends BaseContract {
92
97
  getContractsRegister(overrides?: CallOverrides): Promise<string>;
93
98
  getDataCompressor(overrides?: CallOverrides): Promise<string>;
94
99
  getGearToken(overrides?: CallOverrides): Promise<string>;
100
+ getLeveragedActions(overrides?: CallOverrides): Promise<string>;
95
101
  getPriceOracle(overrides?: CallOverrides): Promise<string>;
96
102
  getTreasuryContract(overrides?: CallOverrides): Promise<string>;
97
103
  getWETHGateway(overrides?: CallOverrides): Promise<string>;
@@ -108,6 +114,7 @@ export interface IAddressProvider extends BaseContract {
108
114
  getContractsRegister(overrides?: CallOverrides): Promise<BigNumber>;
109
115
  getDataCompressor(overrides?: CallOverrides): Promise<BigNumber>;
110
116
  getGearToken(overrides?: CallOverrides): Promise<BigNumber>;
117
+ getLeveragedActions(overrides?: CallOverrides): Promise<BigNumber>;
111
118
  getPriceOracle(overrides?: CallOverrides): Promise<BigNumber>;
112
119
  getTreasuryContract(overrides?: CallOverrides): Promise<BigNumber>;
113
120
  getWETHGateway(overrides?: CallOverrides): Promise<BigNumber>;
@@ -120,6 +127,7 @@ export interface IAddressProvider extends BaseContract {
120
127
  getContractsRegister(overrides?: CallOverrides): Promise<PopulatedTransaction>;
121
128
  getDataCompressor(overrides?: CallOverrides): Promise<PopulatedTransaction>;
122
129
  getGearToken(overrides?: CallOverrides): Promise<PopulatedTransaction>;
130
+ getLeveragedActions(overrides?: CallOverrides): Promise<PopulatedTransaction>;
123
131
  getPriceOracle(overrides?: CallOverrides): Promise<PopulatedTransaction>;
124
132
  getTreasuryContract(overrides?: CallOverrides): Promise<PopulatedTransaction>;
125
133
  getWETHGateway(overrides?: CallOverrides): Promise<PopulatedTransaction>;