/
path-factory.ts
305 lines (260 loc) · 12.3 KB
/
path-factory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import BigNumber from 'bignumber.js';
import { InsufficientLiquidityError, RubicSdkError } from 'src/common/errors';
import { PriceToken, Token } from 'src/common/tokens';
import { Cache } from 'src/common/utils/decorators';
import { notNull } from 'src/common/utils/object';
import { EvmBlockchainName } from 'src/core/blockchain/models/blockchain-name';
import { EvmWeb3Public } from 'src/core/blockchain/web3-public-service/web3-public/evm-web3-public/evm-web3-public';
import { BatchCall } from 'src/core/blockchain/web3-public-service/web3-public/evm-web3-public/models/batch-call';
import { EvmWeb3Pure } from 'src/core/blockchain/web3-pure/typed-web3-pure/evm-web3-pure/evm-web3-pure';
import { Web3Pure } from 'src/core/blockchain/web3-pure/web3-pure';
import { Injector } from 'src/core/injector/injector';
import { OnChainProxyFeeInfo } from 'src/features/on-chain/calculation-manager/providers/common/models/on-chain-proxy-fee-info';
import { Exact } from 'src/features/on-chain/calculation-manager/providers/common/on-chain-trade/evm-on-chain-trade/models/exact';
import { DefaultRoutesMethodArgument } from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/models/route-method-arguments';
import {
UniswapCalculatedInfo,
UniswapCalculatedInfoWithProfit
} from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/models/uniswap-calculated-info';
import { UniswapRoute } from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/models/uniswap-route';
import { UniswapV2CalculationOptions } from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/models/uniswap-v2-calculation-options';
import { UniswapV2ProviderConfiguration } from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/models/uniswap-v2-provider-configuration';
import { UniswapV2TradeClass } from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/models/uniswap-v2-trade-class';
import { UniswapV2AbstractTrade } from 'src/features/on-chain/calculation-manager/providers/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-trade';
import { getFromToTokensAmountsByExact } from 'src/features/on-chain/calculation-manager/providers/dexes/common/utils/get-from-to-tokens-amounts-by-exact';
import { hasLengthAtLeast } from 'src/features/on-chain/calculation-manager/utils/type-guards';
export interface PathFactoryStruct {
readonly from: PriceToken<EvmBlockchainName>;
readonly to: PriceToken<EvmBlockchainName>;
readonly weiAmount: BigNumber;
readonly exact: Exact;
readonly options: UniswapV2CalculationOptions;
readonly proxyFeeInfo: OnChainProxyFeeInfo | undefined;
}
export interface UniswapV2AbstractProviderStruct<T extends UniswapV2AbstractTrade> {
readonly UniswapV2TradeClass: UniswapV2TradeClass<T>;
readonly providerSettings: UniswapV2ProviderConfiguration;
}
export class PathFactory<T extends UniswapV2AbstractTrade> {
private readonly web3Public: EvmWeb3Public;
protected readonly from: PriceToken<EvmBlockchainName>;
protected readonly to: PriceToken<EvmBlockchainName>;
private readonly weiAmount: BigNumber;
protected readonly exact: Exact;
private readonly options: UniswapV2CalculationOptions;
private readonly proxyFeeInfo: OnChainProxyFeeInfo | undefined;
protected readonly UniswapV2TradeClass: UniswapV2TradeClass<T>;
protected readonly routingProvidersAddresses: ReadonlyArray<string>;
protected readonly maxTransitTokens: number;
private get walletAddress(): string | undefined {
return Injector.web3PrivateService.getWeb3PrivateByBlockchain(this.from.blockchain).address;
}
@Cache
protected get stringWeiAmount(): string {
return this.weiAmount.toFixed(0);
}
constructor(
uniswapProviderStruct: UniswapV2AbstractProviderStruct<T>,
pathFactoryStruct: PathFactoryStruct
) {
this.web3Public = Injector.web3PublicService.getWeb3Public(
pathFactoryStruct.from.blockchain
);
this.from = pathFactoryStruct.from;
this.to = pathFactoryStruct.to;
this.weiAmount = pathFactoryStruct.weiAmount;
this.exact = pathFactoryStruct.exact;
this.options = pathFactoryStruct.options;
this.UniswapV2TradeClass = uniswapProviderStruct.UniswapV2TradeClass;
this.routingProvidersAddresses =
uniswapProviderStruct.providerSettings.routingProvidersAddresses;
this.maxTransitTokens = pathFactoryStruct.options.disableMultihops
? 0
: uniswapProviderStruct.providerSettings.maxTransitTokens;
this.proxyFeeInfo = pathFactoryStruct.proxyFeeInfo;
}
public async getAmountAndPath(
gasPriceInUsd: BigNumber | undefined
): Promise<UniswapCalculatedInfo> {
const allRoutes = await this.getAllRoutes();
const sortedRoutes = allRoutes
.filter(route => route.outputAbsoluteAmount.gt(0))
.sort(
(a, b) =>
b.outputAbsoluteAmount.comparedTo(a.outputAbsoluteAmount) *
(this.exact === 'input' ? 1 : -1)
);
if (sortedRoutes.length === 0) {
throw new InsufficientLiquidityError();
}
if (this.options.gasCalculation === 'disabled') {
if (!hasLengthAtLeast(sortedRoutes, 1)) {
throw new RubicSdkError('Routes array length has to be bigger than 0');
}
return {
route: sortedRoutes[0]
};
}
if (
this.options.gasCalculation === 'rubicOptimisation' &&
this.to.price?.isFinite() &&
gasPriceInUsd
) {
const gasLimits = this.getDefaultGases(sortedRoutes);
if (this.walletAddress) {
const gasRequests = await Promise.all(this.getGasRequests(sortedRoutes));
const estimatedGasLimits = await this.web3Public.batchEstimatedGas(
this.walletAddress,
gasRequests
);
estimatedGasLimits.forEach((elem, index) => {
if (elem?.isFinite()) {
gasLimits[index] = elem;
}
});
}
const routesWithProfit: UniswapCalculatedInfoWithProfit[] = sortedRoutes.map(
(route, index) => {
const estimatedGas = gasLimits[index];
if (!estimatedGas) {
throw new RubicSdkError('Estimated gas has to be defined');
}
const gasFeeInUsd = estimatedGas.multipliedBy(gasPriceInUsd);
let profit: BigNumber;
if (this.exact === 'input') {
profit = Web3Pure.fromWei(route.outputAbsoluteAmount, this.to.decimals)
.multipliedBy(this.to.price)
.minus(gasFeeInUsd);
} else {
profit = Web3Pure.fromWei(route.outputAbsoluteAmount, this.from.decimals)
.multipliedBy(this.from.price)
.multipliedBy(-1)
.minus(gasFeeInUsd);
}
return {
route,
estimatedGas,
profit
};
}
);
const sortedByProfitRoutes = routesWithProfit.sort((a, b) =>
b.profit.comparedTo(a.profit)
);
if (!sortedByProfitRoutes?.[0]) {
throw new RubicSdkError('Profit routes array length has to be bigger than 0');
}
return sortedByProfitRoutes[0];
}
let gasLimit = this.getDefaultGases(sortedRoutes.slice(0, 1))[0];
if (this.walletAddress) {
const callData = await this.getGasRequests(sortedRoutes.slice(0, 1))[0];
if (!callData) {
throw new RubicSdkError('Call data has to be defined');
}
const estimatedGas = (
await this.web3Public.batchEstimatedGas(this.walletAddress, [callData])
)[0];
if (estimatedGas?.isFinite()) {
gasLimit = estimatedGas;
}
}
if (!sortedRoutes?.[0]) {
throw new RubicSdkError('Routes length has to be bigger than 0');
}
return {
route: sortedRoutes[0],
estimatedGas: gasLimit
};
}
private getGasRequests(routes: UniswapRoute[]): Promise<BatchCall>[] {
return this.getTradesByRoutes(routes).map(trade => trade.getEstimatedGasCallData());
}
private getDefaultGases(routes: UniswapRoute[]): BigNumber[] {
return this.getTradesByRoutes(routes).map(trade => trade.getDefaultEstimatedGas());
}
private getTradesByRoutes(routes: UniswapRoute[]): UniswapV2AbstractTrade[] {
return routes.map(route => {
const { from, to, fromWithoutFee } = getFromToTokensAmountsByExact(
this.from,
this.to,
this.exact,
this.weiAmount,
this.weiAmount,
route.outputAbsoluteAmount
);
return new this.UniswapV2TradeClass(
{
from,
to,
path: route.path,
routPoolInfo: route?.routPoolInfo,
wrappedPath: route.path,
exact: this.exact,
deadlineMinutes: this.options.deadlineMinutes,
slippageTolerance: this.options.slippageTolerance,
gasFeeInfo: null,
useProxy: this.options.useProxy,
proxyFeeInfo: this.proxyFeeInfo,
fromWithoutFee,
withDeflation: { from: { isDeflation: false }, to: { isDeflation: false } }
},
EvmWeb3Pure.EMPTY_ADDRESS
);
});
}
protected async getAllRoutes(): Promise<UniswapRoute[]> {
const transitTokens = await Token.createTokens(
this.routingProvidersAddresses,
this.from.blockchain
);
const vertexes: Token[] = transitTokens.filter(
elem => !elem.isEqualTo(this.from) && !elem.isEqualTo(this.to)
);
const initialPath = [this.from];
const routesPaths: Token[][] = [];
const routesMethodArguments: DefaultRoutesMethodArgument[] = [];
const recGraphVisitor = (path: Token[], transitTokensLimit: number): void => {
if (path.length === transitTokensLimit + 1) {
const finalPath = path.concat(this.to);
routesPaths.push(finalPath);
routesMethodArguments.push([
this.stringWeiAmount,
Token.tokensToAddresses(finalPath)
]);
return;
}
vertexes
.filter(vertex => path.every(token => !token.isEqualTo(vertex)))
.forEach(vertex => {
const extendedPath = path.concat(vertex);
recGraphVisitor(extendedPath, transitTokensLimit);
});
};
for (let i = 0; i <= this.maxTransitTokens; i++) {
recGraphVisitor(initialPath, i);
}
const responses = await this.UniswapV2TradeClass.callForRoutes(
this.from.blockchain,
this.exact,
routesMethodArguments
);
const tokens = responses.map((response, index) => {
if (!response.success || !response.output) {
return null;
}
const amounts = response.output;
const numberAmount = this.exact === 'input' ? amounts[amounts.length - 1] : amounts[0];
if (!numberAmount) {
throw new RubicSdkError('Amount has to be defined');
}
const outputAbsoluteAmount = new BigNumber(numberAmount);
const path = routesPaths?.[index];
if (!path) {
throw new RubicSdkError('Path has to be defined');
}
return { outputAbsoluteAmount, path };
});
return tokens.filter(notNull);
}
}