Skip to content

Commit

Permalink
feat: add thorswap quotor
Browse files Browse the repository at this point in the history
  • Loading branch information
kwoktung committed Oct 17, 2023
1 parent 13da8b5 commit f54fb85
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 4 deletions.
67 changes: 64 additions & 3 deletions packages/kit/src/views/Swap/quoter/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import axios from 'axios';
import BigNumber from 'bignumber.js';
import { th } from 'date-fns/locale';
import * as ethers from 'ethers';

import { getNetworkImpl } from '@onekeyhq/engine/src/managers/network';
import type { Token } from '@onekeyhq/engine/src/types/token';
Expand Down Expand Up @@ -31,6 +33,7 @@ import { DeezyQuoter } from './deezy';
import { JupiterQuoter } from './jupiter';
import { SocketQuoter } from './socket';
import { SwftcQuoter } from './swftc';
import { ThorSwapQuoter } from './thorswap';

import type {
BuildTransactionParams,
Expand Down Expand Up @@ -62,6 +65,16 @@ type TransactionOrder = {
orderId: string;
};

type ThorSwapOrder = {
to: string;
memo: string;
amountIn: string;
};

type ThorSwapData = {
quoteId: string;
};

type EVMTransaction = {
to: string;
value: string;
Expand All @@ -84,6 +97,8 @@ type BuildTransactionHttpResponse = {
order?: TransactionOrder;
errMsg?: string;
result?: FetchQuoteHttpResult;
thor?: ThorSwapData;
thorOrder?: ThorSwapOrder;
};

type FetchQuoteHttpParams = {
Expand Down Expand Up @@ -147,6 +162,8 @@ export class SwapQuoter {

private socket = new SocketQuoter();

private thor = new ThorSwapQuoter();

private deezy = new DeezyQuoter();

private quoters: Quoter[] = [
Expand All @@ -155,6 +172,7 @@ export class SwapQuoter {
this.jupiter,
this.swftc,
this.deezy,
this.thor,
];

transactionReceipts: Record<
Expand Down Expand Up @@ -209,6 +227,44 @@ export class SwapQuoter {
return result;
}

async convertThorSwapOrderToTransaction(
params: BuildTransactionParams,
order: ThorSwapOrder,
) {
const { tokenIn, networkIn, activeAccount, sellAmount } = params;
if (!sellAmount || !tokenIn) {
return;
}
if (!order.to || !order.memo || order.amountIn !== params.sellAmount) {
throw new Error(
'failed to build transaction due to invalid thor swap order params',
);
}
const depositCoinAmt = new BigNumber(order.amountIn)
.shiftedBy(-tokenIn.decimals)
.toFixed();
let result: TransactionData | undefined;
if (!tokenIn.tokenIdOnNetwork && networkIn.impl === IMPL_EVM) {
result = await backgroundApiProxy.engine.buildEncodedTxFromTransfer({
networkId: networkIn.id,
accountId: activeAccount.id,
transferInfo: {
from: activeAccount.address,
to: order.to,
amount: depositCoinAmt,
},
});
const transaction = result as IEncodedTxEvm;
if (transaction.data) {
throw new Error('failed to build transaction due to invalid data');
} else {
transaction.data = ethers.utils.hexlify(order.memo);
}
return result;
}
throw new Error('failed to build transaction due to unsupported network');
}

async fetchLimitOrderQuote(params: ILimitOrderQuoteParams) {
const urlParams = convertLimitOrderParams(params) as
| FetchQuoteHttpParams
Expand Down Expand Up @@ -416,7 +472,6 @@ export class SwapQuoter {
const requestId = this.parseRequestId(res);

const data = res.data as BuildTransactionHttpResponse;

if (data.errMsg) {
throw new Error(data.errMsg);
}
Expand All @@ -433,14 +488,20 @@ export class SwapQuoter {
requestId,
};
}
return {
const result = {
data: {
...data.transaction,
from: params.activeAccount.address,
} as IEncodedTxEvm,
result: data.result,
requestId,
};
} as BuildTransactionResponse;
if (data.thor) {
result.attachment = {
thorswapQuoteId: data.thor.quoteId,
};
}
return result;
}
return { data: data.transaction, result: data.result, requestId };
}
Expand Down
69 changes: 69 additions & 0 deletions packages/kit/src/views/Swap/quoter/thorswap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import axios from 'axios';

import backgroundApiProxy from '../../../background/instance/backgroundApiProxy';
import { QuoterType } from '../typings';

import type {
Quoter,
TransactionDetails,
TransactionProgress,
} from '../typings';

export class ThorSwapQuoter implements Quoter {
type: QuoterType = QuoterType.thorswap;

async getBaseUrl() {
const baseUrl = await backgroundApiProxy.serviceSwap.getServerEndPoint();
return `${baseUrl}/thorswap`;
}

async queryTransactionProgress(
tx: TransactionDetails,
): Promise<TransactionProgress> {
const { networkId, accountId, nonce, hash, attachment } = tx;
if (nonce !== undefined) {
const status =
await backgroundApiProxy.serviceHistory.queryTransactionNonceStatus({
networkId,
accountId,
nonce,
});
if (status === 'failed' || status === 'canceled') {
return { status };
}
}
if (hash && attachment?.thorswapQuoteId) {
const baseUrl = await this.getBaseUrl();
const url = `${baseUrl}/transaction_status`;
const res = await axios.get(url, {
params: {
hash,
quoteId: attachment?.thorswapQuoteId,
},
});
const data = res.data as {
status: string;
done: boolean;
result: {
quoteId: string;
firstTransactionHash: string;
status: string;
isLending: boolean;
isStreamingSwap: false;
legs: {
chain: string;
hash: string;
}[];
};
};
if (data.status === 'success') {
return { status: 'sucesss' };
}
return { status: 'pending' };
}
if (Date.now() - tx.addedTime > 60 * 60 * 1000 * 24) {
return { status: 'failed' };
}
return undefined;
}
}
7 changes: 7 additions & 0 deletions packages/kit/src/views/Swap/typings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export enum QuoterType {
jupiter = 'jupiter',
onekey = 'onekey',
deezy = 'Deezy',
thorswap = 'Thorswap',
}

export type FieldType = 'INPUT' | 'OUTPUT';
Expand Down Expand Up @@ -237,6 +238,12 @@ export interface TransactionAttachment {
swftcReceiveCoinAmt?: string;
swftcReceiveCoinCode?: string;
socketUsedBridgeNames?: string[];

thorswapQuoteId?: string;
}

export interface ThorswapOrderReceipt {
quoteId: string;
}

export type BuildTransactionParams = FetchQuoteParams & {
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/src/views/Swap/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,8 @@ export function convertParams(params: FetchQuoteParams) {
if (params.onChainSatsPerVbyte) {
urlParams.onChainSatsPerVbyte = params.onChainSatsPerVbyte;
}
urlParams.includes = '0x,1inch,jupiter,openocean,swftc,socket,mdex,Deezy';
urlParams.includes =
'0x,1inch,jupiter,openocean,swftc,socket,mdex,Deezy,Thorswap';
urlParams.noFilter = true;
return urlParams;
}
Expand Down

0 comments on commit f54fb85

Please sign in to comment.