forked from polkadot-js/extension
-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathindex.ts
428 lines (349 loc) · 16 KB
/
index.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Copyright 2019-2022 @subwallet/extension-base
// SPDX-License-Identifier: Apache-2.0
import { SwapError } from '@subwallet/extension-base/background/errors/SwapError';
import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
import KoniState from '@subwallet/extension-base/koni/background/handlers/State';
import { ServiceStatus, ServiceWithProcessInterface, StoppableServiceInterface } from '@subwallet/extension-base/services/base/types';
import { ChainService } from '@subwallet/extension-base/services/chain-service';
import { EventService } from '@subwallet/extension-base/services/event-service';
import { AssetHubSwapHandler } from '@subwallet/extension-base/services/swap-service/handler/asset-hub';
import { SwapBaseInterface } from '@subwallet/extension-base/services/swap-service/handler/base-handler';
import { ChainflipSwapHandler } from '@subwallet/extension-base/services/swap-service/handler/chainflip-handler';
import { HydradxHandler } from '@subwallet/extension-base/services/swap-service/handler/hydradx-handler';
import { _PROVIDER_TO_SUPPORTED_PAIR_MAP, DynamicSwapAction, findSwapDestinations, findXcmDestinations, getInitStep, getSwapAltToken, getSwapStep, getXcmStep, isEquiValentAsset, SWAP_QUOTE_TIMEOUT_MAP } from '@subwallet/extension-base/services/swap-service/utils';
import { BasicTxErrorType, SwapRequestV2 } from '@subwallet/extension-base/types';
import { CommonOptimalPath, DEFAULT_FIRST_STEP, MOCK_STEP_FEE } from '@subwallet/extension-base/types/service-base';
import { _SUPPORTED_SWAP_PROVIDERS, OptimalSwapPathParams, QuoteAskResponse, SwapErrorType, SwapPair, SwapProviderId, SwapQuote, SwapQuoteResponse, SwapRequest, SwapRequestResult, SwapStepType, SwapSubmitParams, SwapSubmitStepData, ValidateSwapProcessParams } from '@subwallet/extension-base/types/swap';
import { createPromiseHandler, PromiseHandler } from '@subwallet/extension-base/utils';
import subwalletApiSdk from '@subwallet/subwallet-api-sdk';
import { BehaviorSubject } from 'rxjs';
import { SimpleSwapHandler } from './handler/simpleswap-handler';
import { UniswapHandler } from './handler/uniswap-handler';
export const _isChainSupportedByProvider = (providerSlug: SwapProviderId, chain: string) => {
const supportedChains = _PROVIDER_TO_SUPPORTED_PAIR_MAP[providerSlug];
return supportedChains ? supportedChains.includes(chain) : false;
};
export class SwapService implements ServiceWithProcessInterface, StoppableServiceInterface {
protected readonly state: KoniState;
private eventService: EventService;
private readonly chainService: ChainService;
private swapPairSubject: BehaviorSubject<SwapPair[]> = new BehaviorSubject<SwapPair[]>([]);
private handlers: Record<string, SwapBaseInterface> = {};
startPromiseHandler: PromiseHandler<void> = createPromiseHandler();
stopPromiseHandler: PromiseHandler<void> = createPromiseHandler();
status: ServiceStatus = ServiceStatus.NOT_INITIALIZED;
constructor (state: KoniState) {
this.state = state;
this.eventService = state.eventService;
this.chainService = state.chainService;
}
private async askProvidersForQuote (request: SwapRequest) {
const availableQuotes: QuoteAskResponse[] = [];
await Promise.all(Object.values(this.handlers).map(async (handler) => {
// temporary solution to reduce number of requests to providers, will work as long as there's only 1 provider for 1 chain
if (handler.init && handler.isReady === false) {
await handler.init();
}
}));
const quotes = await subwalletApiSdk.swapApi?.fetchSwapQuoteData(request);
if (Array.isArray(quotes)) {
quotes.forEach((quoteData) => {
if (!quoteData.quote || Object.keys(quoteData.quote).length === 0) {
return;
}
if (!('errorClass' in quoteData.quote)) {
availableQuotes.push({ quote: quoteData.quote as SwapQuote | undefined });
} else {
availableQuotes.push({
error: new SwapError(quoteData.quote.errorType as SwapErrorType, quoteData.quote.message)
});
}
});
}
return availableQuotes;
}
private getDefaultProcess (params: OptimalSwapPathParams): CommonOptimalPath {
const result: CommonOptimalPath = {
totalFee: [MOCK_STEP_FEE],
steps: [DEFAULT_FIRST_STEP]
};
result.totalFee.push({
feeComponent: [],
feeOptions: [params.request.pair.from],
defaultFeeToken: params.request.pair.from
});
result.steps.push({
id: result.steps.length,
name: 'Swap',
type: SwapStepType.SWAP
});
return result;
}
public async generateOptimalProcess (params: OptimalSwapPathParams): Promise<CommonOptimalPath> {
if (!params.selectedQuote) {
return this.getDefaultProcess(params);
} else {
const providerId = params.request.currentQuote?.id || params.selectedQuote.provider.id;
const handler = this.handlers[providerId];
if (handler) {
return handler.generateOptimalProcess(params);
} else {
return this.getDefaultProcess(params);
}
}
}
public async handleSwapRequest (request: SwapRequest): Promise<SwapRequestResult> {
/*
* 1. Ask swap quotes from providers
* 2. Select the best quote
* 3. Generate optimal process for that quote
* */
const swapQuoteResponse = await this.getLatestQuotes(request);
const optimalProcess = await this.generateOptimalProcess({
request,
selectedQuote: swapQuoteResponse.optimalQuote
});
return {
process: optimalProcess,
quote: swapQuoteResponse
} as SwapRequestResult;
}
public handleSwapRequestV2 (request: SwapRequestV2): DynamicSwapAction[][] {
const { fromToken, toToken } = request;
const fromTokenInfo = this.chainService.getAssetBySlug(fromToken);
const toTokenInfo = this.chainService.getAssetBySlug(toToken);
const fromChain = fromTokenInfo.originChain;
const toChain = toTokenInfo.originChain;
const firstSwapDes = findSwapDestinations(this.chainService, fromTokenInfo);
const firstXcmDes = findXcmDestinations(this.chainService, fromTokenInfo);
if (!firstSwapDes.length && !firstXcmDes.length) {
return [];
}
const routes: DynamicSwapAction[][] = [];
let steps: DynamicSwapAction[] = [];
// try find swap
if (fromChain === toChain) {
if (firstSwapDes.includes(toTokenInfo)) {
steps.push(getInitStep(fromToken));
steps.push(getSwapStep(toToken));
routes.push(steps);
return routes;
}
}
// try find xcm
if (isEquiValentAsset(fromTokenInfo, toTokenInfo)) {
if (firstXcmDes.includes(toTokenInfo)) {
steps.push(getInitStep(fromToken));
steps.push(getXcmStep(toToken));
routes.push(steps);
return routes;
}
}
// brute force to find nested routes
for (const xcmAsset of firstXcmDes) {
const swapDesChild = findSwapDestinations(this.chainService, xcmAsset);
if (!swapDesChild.length) {
/* empty */
} else if (swapDesChild.includes(toTokenInfo)) {
steps = [];
steps.push(getInitStep(fromToken));
steps.push(getXcmStep(xcmAsset.slug));
steps.push(getSwapStep(toToken));
routes.push(steps);
} else {
for (const swapAsset of swapDesChild) {
const xcmDesChild = findXcmDestinations(this.chainService, swapAsset);
if (xcmDesChild.includes(toTokenInfo)) {
steps = [];
steps.push(getInitStep(fromToken));
steps.push(getXcmStep(xcmAsset.slug));
steps.push(getSwapStep(swapAsset.slug));
steps.push(getXcmStep(toToken));
routes.push(steps);
}
}
}
}
for (const swapAsset of firstSwapDes) {
const xcmDesChild = findXcmDestinations(this.chainService, swapAsset);
if (!xcmDesChild.length) {
/* empty */
} else if (xcmDesChild.includes(toTokenInfo)) {
steps = [];
steps.push(getInitStep(fromToken));
steps.push(getSwapStep(swapAsset.slug));
steps.push(getXcmStep(toToken));
routes.push(steps);
} else {
for (const xcmAsset of xcmDesChild) {
const swapDesChild = findSwapDestinations(this.chainService, xcmAsset);
if (swapDesChild.includes(toTokenInfo)) {
steps = [];
steps.push(getInitStep(fromToken));
steps.push(getSwapStep(swapAsset.slug));
steps.push(getXcmStep(xcmAsset.slug));
steps.push(getSwapStep(toToken));
routes.push(steps);
}
}
}
}
return routes;
}
public async getLatestQuotes (request: SwapRequest): Promise<SwapQuoteResponse> {
request.pair.metadata = this.getSwapPairMetadata(request.pair.slug); // todo: improve this
const quoteAskResponses = await this.askProvidersForQuote(request);
// todo: handle error to return back to UI
// todo: more logic to select the best quote
const availableQuotes = quoteAskResponses.filter((quote) => !quote.error).map((quote) => quote.quote as SwapQuote);
let quoteError: SwapError | undefined;
let selectedQuote: SwapQuote | undefined;
let aliveUntil = (+Date.now() + SWAP_QUOTE_TIMEOUT_MAP.default);
if (availableQuotes.length === 0) {
const preferredErrorResp = quoteAskResponses.find((quote) => {
return !!quote.error && ![SwapErrorType.UNKNOWN, SwapErrorType.ASSET_NOT_SUPPORTED].includes(quote.error.errorType);
});
const defaultErrorResp = quoteAskResponses.find((quote) => !!quote.error);
quoteError = preferredErrorResp?.error || defaultErrorResp?.error;
} else {
selectedQuote = availableQuotes.find((quote) => quote.provider.id === request.currentQuote?.id) || availableQuotes[0];
aliveUntil = selectedQuote?.aliveUntil || (+Date.now() + SWAP_QUOTE_TIMEOUT_MAP.default);
}
return {
optimalQuote: selectedQuote,
quotes: availableQuotes,
error: quoteError,
aliveUntil
} as SwapQuoteResponse;
}
private initHandlers () {
_SUPPORTED_SWAP_PROVIDERS.forEach((providerId) => {
switch (providerId) {
case SwapProviderId.CHAIN_FLIP_TESTNET:
this.handlers[providerId] = new ChainflipSwapHandler(this.chainService, this.state.balanceService, this.state.feeService);
break;
case SwapProviderId.CHAIN_FLIP_MAINNET:
this.handlers[providerId] = new ChainflipSwapHandler(this.chainService, this.state.balanceService, this.state.feeService, false);
break;
case SwapProviderId.HYDRADX_TESTNET:
this.handlers[providerId] = new HydradxHandler(this.chainService, this.state.balanceService, this.state.feeService);
break;
case SwapProviderId.HYDRADX_MAINNET:
this.handlers[providerId] = new HydradxHandler(this.chainService, this.state.balanceService, this.state.feeService, false);
break;
case SwapProviderId.POLKADOT_ASSET_HUB:
this.handlers[providerId] = new AssetHubSwapHandler(this.chainService, this.state.balanceService, this.state.feeService, 'statemint');
break;
case SwapProviderId.KUSAMA_ASSET_HUB:
this.handlers[providerId] = new AssetHubSwapHandler(this.chainService, this.state.balanceService, this.state.feeService, 'statemine');
break;
// case SwapProviderId.ROCOCO_ASSET_HUB:
// this.handlers[providerId] = new AssetHubSwapHandler(this.chainService, this.state.balanceService, this.state.feeService, 'rococo_assethub');
// break;
case SwapProviderId.WESTEND_ASSET_HUB:
this.handlers[providerId] = new AssetHubSwapHandler(this.chainService, this.state.balanceService, this.state.feeService, 'westend_assethub');
break;
case SwapProviderId.SIMPLE_SWAP:
this.handlers[providerId] = new SimpleSwapHandler(this.chainService, this.state.balanceService, this.state.feeService);
break;
case SwapProviderId.UNISWAP:
this.handlers[providerId] = new UniswapHandler(this.chainService, this.state.balanceService, this.state.transactionService, this.state.feeService);
break;
default:
throw new Error('Unsupported provider');
}
});
}
async init (): Promise<void> {
this.status = ServiceStatus.INITIALIZING;
this.eventService.emit('swap.ready', true);
this.status = ServiceStatus.INITIALIZED;
this.initHandlers();
await this.start();
}
async start (): Promise<void> {
if (this.status === ServiceStatus.STOPPING) {
await this.waitForStopped();
}
if (this.status === ServiceStatus.STARTED || this.status === ServiceStatus.STARTING) {
return this.waitForStarted();
}
this.status = ServiceStatus.STARTING;
// todo: start the service jobs, subscribe data,...
this.swapPairSubject.next(this.getSwapPairs()); // todo: might need to change it online
// Update promise handler
this.startPromiseHandler.resolve();
this.stopPromiseHandler = createPromiseHandler();
this.status = ServiceStatus.STARTED;
}
async stop (): Promise<void> {
if (this.status === ServiceStatus.STARTING) {
await this.waitForStarted();
}
if (this.status === ServiceStatus.STOPPED || this.status === ServiceStatus.STOPPING) {
return this.waitForStopped();
}
// todo: unsub, persist data,...
this.stopPromiseHandler.resolve();
this.startPromiseHandler = createPromiseHandler();
this.status = ServiceStatus.STOPPED;
}
waitForStarted (): Promise<void> {
return this.startPromiseHandler.promise;
}
waitForStopped (): Promise<void> {
return this.stopPromiseHandler.promise;
}
public getSwapPairs (): SwapPair[] {
return Object.entries(this.chainService.swapRefMap).map(([slug, assetRef]) => {
const fromAsset = this.chainService.getAssetBySlug(assetRef.srcAsset);
return {
slug,
from: assetRef.srcAsset,
to: assetRef.destAsset,
metadata: {
alternativeAsset: getSwapAltToken(fromAsset)
}
} as SwapPair;
});
}
private getSwapPairMetadata (slug: string): Record<string, any> | undefined {
return this.getSwapPairs().find((pair) => pair.slug === slug)?.metadata;
}
public async validateSwapProcess (params: ValidateSwapProcessParams): Promise<TransactionError[]> {
const providerId = params.selectedQuote.provider.id;
const handler = this.handlers[providerId];
if (handler) {
return handler.validateSwapProcess(params);
} else {
return [new TransactionError(BasicTxErrorType.INTERNAL_ERROR)];
}
}
public async handleSwapProcess (params: SwapSubmitParams): Promise<SwapSubmitStepData> {
const handler = this.handlers[params.quote.provider.id];
if (params.process.steps.length === 1) { // todo: do better to handle error generating steps
return Promise.reject(new TransactionError(BasicTxErrorType.INTERNAL_ERROR, 'Please check your network and try again'));
}
if (handler) {
return handler.handleSwapProcess(params);
} else {
return Promise.reject(new TransactionError(BasicTxErrorType.INTERNAL_ERROR));
}
}
public subscribeSwapPairs (callback: (pairs: SwapPair[]) => void) {
return this.chainService.subscribeSwapRefMap().subscribe((refMap) => {
const latestData = Object.entries(refMap).map(([slug, assetRef]) => {
const fromAsset = this.chainService.getAssetBySlug(assetRef.srcAsset);
return {
slug,
from: assetRef.srcAsset,
to: assetRef.destAsset,
metadata: {
alternativeAsset: getSwapAltToken(fromAsset)
}
} as SwapPair;
});
callback(latestData);
});
}
}