/
one-inch-trade.ts
196 lines (173 loc) · 7.62 KB
/
one-inch-trade.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
import BigNumber from 'bignumber.js';
import { InsufficientFundsOneinchError, LowSlippageError, RubicSdkError } from 'src/common/errors';
import { PriceTokenAmount, Token } from 'src/common/tokens';
import { nativeTokensList } from 'src/common/tokens/constants/native-tokens';
import { Cache } from 'src/common/utils/decorators';
import { EvmWeb3Pure } from 'src/core/blockchain/web3-pure/typed-web3-pure/evm-web3-pure/evm-web3-pure';
import { Injector } from 'src/core/injector/injector';
import { EncodeTransactionOptions } from 'src/features/common/models/encode-transaction-options';
import {
createTokenNativeAddressProxy,
createTokenNativeAddressProxyInPathStartAndEnd
} from 'src/features/common/utils/token-native-address-proxy';
import { oneinchApiParams } from 'src/features/on-chain/calculation-manager/providers/aggregators/1inch/constants/constants';
import { OneinchSwapRequest } from 'src/features/on-chain/calculation-manager/providers/aggregators/1inch/models/oneinch-swap-request';
import { OneinchSwapResponse } from 'src/features/on-chain/calculation-manager/providers/aggregators/1inch/models/oneinch-swap-response';
import { OneinchTradeStruct } from 'src/features/on-chain/calculation-manager/providers/aggregators/1inch/models/oneinch-trade-struct';
import { OneInchApiService } from 'src/features/on-chain/calculation-manager/providers/aggregators/1inch/one-inch-api-service';
import {
ON_CHAIN_TRADE_TYPE,
OnChainTradeType
} from 'src/features/on-chain/calculation-manager/providers/common/models/on-chain-trade-type';
import { AggregatorEvmOnChainTrade } from 'src/features/on-chain/calculation-manager/providers/common/on-chain-aggregator/aggregator-evm-on-chain-trade-abstract';
import { GetToAmountAndTxDataResponse } from 'src/features/on-chain/calculation-manager/providers/common/on-chain-aggregator/models/aggregator-on-chain-types';
export class OneInchTrade extends AggregatorEvmOnChainTrade {
/** @internal */
public static async getGasLimit(tradeStruct: OneinchTradeStruct): Promise<BigNumber | null> {
const fromBlockchain = tradeStruct.from.blockchain;
const walletAddress =
Injector.web3PrivateService.getWeb3PrivateByBlockchain(fromBlockchain).address;
if (!walletAddress) {
return null;
}
try {
const transactionConfig = await new OneInchTrade(
tradeStruct,
EvmWeb3Pure.EMPTY_ADDRESS
).encode({ fromAddress: walletAddress });
const web3Public = Injector.web3PublicService.getWeb3Public(fromBlockchain);
const gasLimit = (
await web3Public.batchEstimatedGas(walletAddress, [transactionConfig])
)[0];
if (!gasLimit?.isFinite()) {
return null;
}
return gasLimit;
} catch (_err) {
return null;
}
}
/** @internal */
public static async checkIfNeedApproveAndThrowError(
from: PriceTokenAmount,
toToken: Token,
fromWithoutFee: PriceTokenAmount,
fromAddress: string,
useProxy: boolean
): Promise<void | never> {
const needApprove = await new OneInchTrade(
{
from,
to: toToken,
fromWithoutFee,
useProxy,
path: [from, toToken] as ReadonlyArray<Token>
} as OneinchTradeStruct,
EvmWeb3Pure.EMPTY_ADDRESS
).needApprove(fromAddress);
if (needApprove) {
throw new RubicSdkError('Approve is needed');
}
}
public readonly dexContractAddress: string;
private readonly nativeSupportedFromWithoutFee: PriceTokenAmount;
private readonly nativeSupportedTo: PriceTokenAmount;
private readonly disableMultihops: boolean;
private readonly availableProtocols: string | undefined;
/**
* @internal
* Path with wrapped native address.
*/
public readonly wrappedPath: ReadonlyArray<Token>;
/** @internal */
public readonly transactionData: string | null;
public get type(): OnChainTradeType {
return ON_CHAIN_TRADE_TYPE.ONE_INCH;
}
constructor(tradeStruct: OneinchTradeStruct, providerAddress: string) {
super(tradeStruct, providerAddress);
this.dexContractAddress = tradeStruct.dexContractAddress;
this.disableMultihops = tradeStruct.disableMultihops;
this.transactionData = tradeStruct.data;
this.availableProtocols = tradeStruct.availableProtocols;
this.wrappedPath = createTokenNativeAddressProxyInPathStartAndEnd(
this.path,
oneinchApiParams.nativeAddress
);
this.nativeSupportedFromWithoutFee = createTokenNativeAddressProxy(
tradeStruct.fromWithoutFee,
oneinchApiParams.nativeAddress
);
this.nativeSupportedTo = createTokenNativeAddressProxy(
tradeStruct.to,
oneinchApiParams.nativeAddress
);
}
protected async getTransactionConfigAndAmount(
options: EncodeTransactionOptions
): Promise<GetToAmountAndTxDataResponse> {
const fromTokenAddress = this.nativeSupportedFromWithoutFee.address;
const toTokenAddress = this.nativeSupportedTo.address;
const swapRequest: OneinchSwapRequest = {
params: {
src: fromTokenAddress,
dst: toTokenAddress,
amount: this.nativeSupportedFromWithoutFee.stringWeiAmount,
slippage: (this.slippageTolerance * 100).toString(),
from: options.fromAddress || this.walletAddress,
disableEstimate: true,
...(this.disableMultihops && {
connectorTokens: `${fromTokenAddress},${toTokenAddress}`
}),
...(options.receiverAddress && { receiver: options.receiverAddress }),
...(this.availableProtocols && { protocols: this.availableProtocols })
}
};
const { tx, dstAmount } = await this.getResponseFromApiToTransactionRequest(swapRequest);
return {
tx: {
...tx,
gas: String(tx.gas)
},
toAmount: dstAmount
};
}
@Cache({
maxAge: 15_000
})
private async getResponseFromApiToTransactionRequest(
params: OneinchSwapRequest
): Promise<OneinchSwapResponse> {
return OneInchApiService.oneInchHttpGetRequest<OneinchSwapResponse>(
'swap',
this.from.blockchain,
params
);
}
private specifyError(err: {
error?:
| {
message?: string;
description?: string;
}
| Error;
}): RubicSdkError | null {
const inchError = err?.error || err;
if (inchError) {
if ('message' in inchError) {
if (inchError.message?.includes('cannot estimate')) {
const nativeToken = nativeTokensList[this.from.blockchain]?.symbol;
const message = `1inch sets increased costs on gas fee. For transaction enter less ${nativeToken} amount or top up your ${nativeToken} balance.`;
return new RubicSdkError(message);
}
if (inchError.message?.includes('insufficient funds for transfer')) {
return new InsufficientFundsOneinchError(this.from.blockchain);
}
}
if ('description' in inchError && inchError.description?.includes('cannot estimate')) {
return new LowSlippageError();
}
}
return null;
}
}