Skip to content

Commit

Permalink
Fix/swap add okx (#6173)
Browse files Browse the repository at this point in the history
  • Loading branch information
ezailWang authored Nov 12, 2024
1 parent 2c752d3 commit 6989a20
Show file tree
Hide file tree
Showing 12 changed files with 198 additions and 18 deletions.
3 changes: 3 additions & 0 deletions development/spellCheckerSkipWords.js
Original file line number Diff line number Diff line change
Expand Up @@ -769,4 +769,7 @@ module.exports = [
'everstake',
'unbonding',
'algodv2',
'okx',
'OKX',
'Okx',
];
28 changes: 15 additions & 13 deletions packages/kit-bg/src/services/ServicePassword/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ import type { IPasswordRes } from './types';
export default class ServicePassword extends ServiceBase {
private cachedPassword?: string;

private cachedPasswordActivityTimeStep = 0;

private cachedPasswordTTL: number = timerUtils.getTimeDurationMs({
hour: 2,
});

private cachedPasswordTimeOutObject: NodeJS.Timeout | null = null;

private passwordPromptTTL: number = timerUtils.getTimeDurationMs({
minute: 5,
});
Expand Down Expand Up @@ -166,22 +166,23 @@ export default class ServicePassword extends ServiceBase {
async setCachedPassword(password: string): Promise<string> {
ensureSensitiveTextEncoded(password);
this.cachedPassword = password;
this.cachedPasswordActivityTimeStep = Date.now();
if (this.cachedPasswordTimeOutObject) {
clearTimeout(this.cachedPasswordTimeOutObject);
}
this.cachedPasswordTimeOutObject = setTimeout(() => {
void this.clearCachedPassword();
}, this.cachedPasswordTTL);
return password;
}

@backgroundMethod()
async getCachedPassword(): Promise<string | undefined> {
const now = Date.now();
if (
!this.cachedPassword ||
now - this.cachedPasswordActivityTimeStep > this.cachedPasswordTTL ||
now < this.cachedPasswordActivityTimeStep
) {
await this.clearCachedPassword();
return undefined;
if (this.cachedPasswordTimeOutObject) {
clearTimeout(this.cachedPasswordTimeOutObject);
}
this.cachedPasswordActivityTimeStep = now;
this.cachedPasswordTimeOutObject = setTimeout(() => {
void this.clearCachedPassword();
}, this.cachedPasswordTTL);
return this.cachedPassword;
}

Expand Down Expand Up @@ -645,7 +646,8 @@ export default class ServicePassword extends ServiceBase {
}
const { time: lastActivity } = await settingsLastActivityAtom.get();
const idleDuration = Math.floor((Date.now() - lastActivity) / (1000 * 60));
if (idleDuration >= appLockDuration) {
const unavailableTime = Date.now() < lastActivity;
if (idleDuration >= appLockDuration || unavailableTime) {
await this.lockApp({ manual: false });
}
}
Expand Down
20 changes: 20 additions & 0 deletions packages/kit-bg/src/services/ServiceSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ import type {
IFetchTokenDetailParams,
IFetchTokenListParams,
IFetchTokensParams,
IOKXTransactionObject,
ISwapApproveTransaction,
ISwapNetwork,
ISwapNetworkBase,
ISwapToken,
ISwapTokenBase,
ISwapTxHistory,
} from '@onekeyhq/shared/types/swap/types';
import {
Expand All @@ -56,6 +58,7 @@ import {
} from '@onekeyhq/shared/types/swap/types';

import { inAppNotificationAtom } from '../states/jotai/atoms';
import { vaultFactory } from '../vaults/factory';

import ServiceBase from './ServiceBase';

Expand Down Expand Up @@ -1225,4 +1228,21 @@ export default class ServiceSwap extends ServiceBase {
isExit,
);
}

@backgroundMethod()
async buildOkxSwapEncodedTx(params: {
accountId: string;
networkId: string;
okxTx: IOKXTransactionObject;
fromTokenInfo: ISwapTokenBase;
}) {
const vault = await vaultFactory.getVault({
accountId: params.accountId,
networkId: params.networkId,
});
return vault.buildOkxSwapEncodedTx({
okxTx: params.okxTx,
fromTokenInfo: params.fromTokenInfo,
});
}
}
2 changes: 1 addition & 1 deletion packages/kit-bg/src/states/jotai/atoms/password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const passwordAtomInitialValue: IPasswordPersistAtom = {
isPasswordSet: false,
webAuthCredentialId: '',
appLockDuration: 240,
enableSystemIdleLock: false,
enableSystemIdleLock: true,
};
export const { target: passwordPersistAtom, use: usePasswordPersistAtom } =
globalAtom<IPasswordPersistAtom>({
Expand Down
7 changes: 7 additions & 0 deletions packages/kit-bg/src/vaults/base/VaultBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ import type {
IBuildDecodedTxParams,
IBuildEncodedTxParams,
IBuildHistoryTxParams,
IBuildOkxSwapEncodedTxParams,
IBuildUnsignedTxParams,
IGetPrivateKeyFromImportedParams,
IGetPrivateKeyFromImportedResult,
Expand Down Expand Up @@ -1300,4 +1301,10 @@ export abstract class VaultBase extends VaultBaseChainOnly {
): Promise<IServerFetchAccountHistoryDetailResp> {
throw new NotImplemented();
}

async buildOkxSwapEncodedTx(
params: IBuildOkxSwapEncodedTxParams,
): Promise<IEncodedTx> {
throw new NotImplemented();
}
}
7 changes: 6 additions & 1 deletion packages/kit-bg/src/vaults/impls/sol/Vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {
} from '@solana/web3.js';
import BigNumber from 'bignumber.js';
import bs58 from 'bs58';
import { isEmpty, isNative, isNil } from 'lodash';
import { isEmpty, isNil } from 'lodash';

import type {
IEncodedTxSol,
Expand Down Expand Up @@ -115,6 +115,7 @@ import type {
IBuildAccountAddressDetailParams,
IBuildDecodedTxParams,
IBuildEncodedTxParams,
IBuildOkxSwapEncodedTxParams,
IBuildUnsignedTxParams,
IGetPrivateKeyFromImportedParams,
IGetPrivateKeyFromImportedResult,
Expand Down Expand Up @@ -1395,4 +1396,8 @@ export default class Vault extends VaultBase {

return true;
}

override async buildOkxSwapEncodedTx(params: IBuildOkxSwapEncodedTxParams) {
return Promise.resolve(params.okxTx.data);
}
}
21 changes: 20 additions & 1 deletion packages/kit-bg/src/vaults/impls/sui/Vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import { isEmpty } from 'lodash';

import type { IEncodedTxSui } from '@onekeyhq/core/src/chains/sui/types';
import coreChainApi from '@onekeyhq/core/src/instance/coreChainApi';
import type { ISignedTxPro, IUnsignedTxPro } from '@onekeyhq/core/src/types';
import type {
IEncodedTx,
ISignedTxPro,
IUnsignedTxPro,
} from '@onekeyhq/core/src/types';
import { OneKeyInternalError } from '@onekeyhq/shared/src/errors';
import { memoizee } from '@onekeyhq/shared/src/utils/cacheUtils';
import hexUtils from '@onekeyhq/shared/src/utils/hexUtils';
Expand Down Expand Up @@ -50,6 +54,7 @@ import type {
IBuildAccountAddressDetailParams,
IBuildDecodedTxParams,
IBuildEncodedTxParams,
IBuildOkxSwapEncodedTxParams,
IBuildUnsignedTxParams,
IGetPrivateKeyFromImportedParams,
IGetPrivateKeyFromImportedResult,
Expand Down Expand Up @@ -534,4 +539,18 @@ export default class Vault extends VaultBase {
}
}
}

override async buildOkxSwapEncodedTx(
params: IBuildOkxSwapEncodedTxParams,
): Promise<IEncodedTxSui> {
const accountAddress = await this.getAccountAddress();
if (params.okxTx.from !== accountAddress) {
throw new OneKeyInternalError('Invalid from address');
}
const encodedTx = {
rawTx: Transaction.from(params.okxTx.data).serialize(),
sender: params.okxTx.from,
};
return Promise.resolve(encodedTx);
}
}
25 changes: 25 additions & 0 deletions packages/kit-bg/src/vaults/impls/ton/Vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import type {
IBuildAccountAddressDetailParams,
IBuildDecodedTxParams,
IBuildEncodedTxParams,
IBuildOkxSwapEncodedTxParams,
IBuildUnsignedTxParams,
IGetPrivateKeyFromImportedParams,
IGetPrivateKeyFromImportedResult,
Expand Down Expand Up @@ -456,4 +457,28 @@ export default class Vault extends VaultBase {
txid: txId,
};
}

override async buildOkxSwapEncodedTx(
params: IBuildOkxSwapEncodedTxParams,
): Promise<IEncodedTx> {
const { okxTx, fromTokenInfo } = params;
const { from, to, value, data } = okxTx;
const amount = new BigNumber(value)
.shiftedBy(-fromTokenInfo.decimals)
.toString();
const message = {
address: to,
amount: TonWeb.utils.toNano(amount).toString(),
payload: data,
};
const fromAddress = await this.getAccountAddress();
if (from !== fromAddress) {
throw new OneKeyInternalError('Invalid from address');
}
return {
from,
to,
messages: [message],
};
}
}
70 changes: 69 additions & 1 deletion packages/kit-bg/src/vaults/impls/tron/Vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ import type {
IEncodedTxTron,
} from '@onekeyhq/core/src/chains/tron/types';
import coreChainApi from '@onekeyhq/core/src/instance/coreChainApi';
import type { ISignedTxPro, IUnsignedTxPro } from '@onekeyhq/core/src/types';
import type {
IEncodedTx,
ISignedTxPro,
IUnsignedTxPro,
} from '@onekeyhq/core/src/types';
import {
InsufficientBalance,
InvalidAddress,
Expand Down Expand Up @@ -56,6 +60,7 @@ import type {
IBuildAccountAddressDetailParams,
IBuildDecodedTxParams,
IBuildEncodedTxParams,
IBuildOkxSwapEncodedTxParams,
IBuildUnsignedTxParams,
IGetPrivateKeyFromImportedParams,
IGetPrivateKeyFromImportedResult,
Expand Down Expand Up @@ -683,4 +688,67 @@ export default class Vault extends VaultBase {
txid: signedTx.txid,
};
}

override async buildOkxSwapEncodedTx(
params: IBuildOkxSwapEncodedTxParams,
): Promise<IEncodedTxTron> {
const { okxTx, fromTokenInfo } = params;
const { from, to, value, data, signatureData: _signatureData } = okxTx;
const signatureData: { functionSelector: string } = JSON.parse(
(_signatureData as string[])[0] ?? '{}',
);

let signatureDataHex = '';
if (signatureData) {
signatureDataHex = signatureData.functionSelector ?? '';
}

const functionParams = defaultAbiCoder.decode(
['uint256', 'uint256', 'uint256', 'bytes32[]'],
`0x${(data as string).slice(10)}`,
) as [{ _hex: string }, { _hex: string }, { _hex: string }, string[]];

const [{ result, transaction }] =
await this.backgroundApi.serviceAccountProfile.sendProxyRequest<{
result: { result: boolean };
transaction: IUnsignedTransaction;
}>({
networkId: this.networkId,
body: [
{
route: 'tronweb',
params: {
method: 'transactionBuilder.triggerSmartContract',
params: [
to,
signatureDataHex,
{
feeLimit: 300_000_000,
callValue: parseInt(value, 10),
},
[
{ type: 'uint256', value: functionParams[0]._hex },
{
type: 'uint256',
value: functionParams[1]._hex,
},
{ type: 'uint256', value: functionParams[2]._hex },
{
type: 'bytes32[]',
value: functionParams[3],
},
],
from,
],
},
},
],
});
if (!result) {
throw new OneKeyInternalError(
'Unable to build token transfer transaction',
);
}
return transaction;
}
}
11 changes: 10 additions & 1 deletion packages/kit-bg/src/vaults/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ import type {
import type { ILNURLPaymentInfo } from '@onekeyhq/shared/types/lightning';
import type { ENFTType } from '@onekeyhq/shared/types/nft';
import type { IStakingInfo } from '@onekeyhq/shared/types/staking';
import type { ISwapTxInfo } from '@onekeyhq/shared/types/swap/types';
import type {
IOKXTransactionObject,
ISwapTokenBase,
ISwapTxInfo,
} from '@onekeyhq/shared/types/swap/types';
import type { IToken } from '@onekeyhq/shared/types/token';
import type { IReplaceTxInfo } from '@onekeyhq/shared/types/tx';

Expand Down Expand Up @@ -620,3 +624,8 @@ export type IQrWalletGetVerifyAddressChainParamsResult = {
scriptType?: string; // BTC only
chainId?: string; // EVM only
};

export type IBuildOkxSwapEncodedTxParams = {
okxTx: IOKXTransactionObject;
fromTokenInfo: ISwapTokenBase;
};
8 changes: 8 additions & 0 deletions packages/kit/src/views/Swap/hooks/useSwapBuiltTx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,14 @@ export function useSwapBuildTx() {
.shiftedBy(-fromToken.decimals)
.toFixed(),
};
} else if (res?.OKXTxObject) {
encodedTx =
await backgroundApiProxy.serviceSwap.buildOkxSwapEncodedTx({
accountId: swapFromAddressInfo?.accountInfo?.account?.id ?? '',
networkId: res.result.fromTokenInfo.networkId,
okxTx: res.OKXTxObject,
fromTokenInfo: res.result.fromTokenInfo,
});
} else if (res?.tx) {
transferInfo = undefined;
if (typeof res.tx !== 'string' && res.tx.data) {
Expand Down
14 changes: 14 additions & 0 deletions packages/shared/types/swap/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,12 +402,26 @@ export interface IThorSwapCallData {
fromAsset: string;
amountIn: string;
}
export interface IOKXTransactionObject {
data: string;
from: string;
gas?: string;
gasLimit?: string;
gasPrice: string;
minReceiveAmount: string;
to: string;
value: string;
maxPriorityFeePerGas: string;
randomKeyAccount?: string[];
signatureData?: string[];
}
export interface IFetchBuildTxResponse {
result: IFetchBuildTxResult;
tx?: ITransaction;
thorSwapCallData?: IThorSwapCallData;
swftOrder?: IFetchBuildTxOrderResponse;
changellyOrder?: IFetchBuildTxChangellyOrderResponse;
OKXTxObject?: IOKXTransactionObject;
ctx?: any;
socketBridgeScanUrl?: string;
orderId?: string;
Expand Down

0 comments on commit 6989a20

Please sign in to comment.