From baac7128e26cf4e683591431a13fd733577e74e9 Mon Sep 17 00:00:00 2001 From: JayJay1024 Date: Fri, 29 Mar 2024 15:23:41 +0800 Subject: [PATCH] perf: code cleanup --- src/bridges/base.ts | 8 --- src/components/address-input.tsx | 34 --------- src/components/bridge-select.tsx | 2 +- src/components/transfer-action.tsx | 2 +- src/config/constant.ts | 8 --- src/config/gql.ts | 89 ----------------------- src/config/index.ts | 1 - src/types/bridge.ts | 27 +------ src/types/cross-chain.ts | 6 +- src/types/graphql.ts | 112 +---------------------------- src/ui/segmented-tabs.tsx | 73 ------------------- src/ui/step-title.tsx | 15 ---- src/ui/tabs.tsx | 93 ------------------------ src/ui/version-switch.tsx | 36 ---------- src/utils/cross-chain.ts | 39 ---------- src/utils/misc.ts | 32 +-------- 16 files changed, 10 insertions(+), 567 deletions(-) delete mode 100644 src/components/address-input.tsx delete mode 100644 src/config/constant.ts delete mode 100644 src/ui/segmented-tabs.tsx delete mode 100644 src/ui/step-title.tsx delete mode 100644 src/ui/tabs.tsx delete mode 100644 src/ui/version-switch.tsx diff --git a/src/bridges/base.ts b/src/bridges/base.ts index 0f25e0fcd..32101d884 100644 --- a/src/bridges/base.ts +++ b/src/bridges/base.ts @@ -91,10 +91,6 @@ export abstract class BaseBridge { options?: TransferOptions & { askEstimateGas?: boolean }, ): Promise; - isLnBridge() { - return false; - } - getLogo() { return this.logo; } @@ -103,10 +99,6 @@ export abstract class BaseBridge { return this.name; } - getCategory() { - return this.category; - } - getContract() { return this.contract; } diff --git a/src/components/address-input.tsx b/src/components/address-input.tsx deleted file mode 100644 index 9ecacd813..000000000 --- a/src/components/address-input.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { InputValue } from "@/types"; -import Input from "@/ui/input"; -import InputAlert from "@/ui/input-alert"; -import { ChangeEventHandler, useCallback } from "react"; -import { isAddress } from "viem"; - -interface Props { - value: InputValue; - placeholder?: string; - className?: string; - onChange?: (value: InputValue) => void; -} - -export default function AddressInput({ value, placeholder, className, onChange = () => undefined }: Props) { - const handleChange = useCallback>( - (e) => { - const input = e.target.value; - const valid = input ? isAddress(input) : true; - onChange({ input, value: input, valid }); - }, - [onChange], - ); - - return ( -
- - {value.valid ? null : } -
- ); -} diff --git a/src/components/bridge-select.tsx b/src/components/bridge-select.tsx index 7dd0cd211..bdcce1154 100644 --- a/src/components/bridge-select.tsx +++ b/src/components/bridge-select.tsx @@ -45,7 +45,7 @@ export default function BridgeSelect({ value, options = [], onChange = () => und function bridgeName(category: BridgeCategory | null | undefined) { if (category) { const bridge = bridgeFactory({ category }); - return bridge ? bridge.getName() : category === "lnbridge" ? "Helix LnBridge" : undefined; + return bridge?.getName(); } return undefined; } diff --git a/src/components/transfer-action.tsx b/src/components/transfer-action.tsx index c54b49fd7..e92f8ee06 100644 --- a/src/components/transfer-action.tsx +++ b/src/components/transfer-action.tsx @@ -52,7 +52,7 @@ export default function TransferAction({ recipient, transferable, transferAmount sourceToken && targetToken && bridgeInstance && - (bridgeInstance.getCategory().startsWith("xtoken") || bridgeFee) && + bridgeFee && transferable && transferAmount.input && transferAmount.valid && diff --git a/src/config/constant.ts b/src/config/constant.ts deleted file mode 100644 index 169342b6a..000000000 --- a/src/config/constant.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * If the fee rate is 10.123%, its value in the contract is 10123 (10.123 * FEE_RATE_BASE) - */ -export const FEE_RATE_BASE = 1000; - -export const FEE_RATE_MIN = 0; -export const FEE_RATE_MAX = 0.25 * FEE_RATE_BASE; // 0.25% -export const FEE_RATE_MAX_V3 = 100 * FEE_RATE_BASE; // 100% diff --git a/src/config/gql.ts b/src/config/gql.ts index a52755dbd..9d89a0026 100644 --- a/src/config/gql.ts +++ b/src/config/gql.ts @@ -83,46 +83,6 @@ export const GQL_HISTORY_RECORD_BY_ID = gql` } `; -export const GQL_QUERY_LNBRIDGE_RELAY_INFOS = gql` - query queryLnBridgeRelayInfos( - $fromChain: String - $toChain: String - $relayer: String - $row: Int - $page: Int - $version: String - ) { - queryLnBridgeRelayInfos( - fromChain: $fromChain - toChain: $toChain - relayer: $relayer - row: $row - page: $page - version: $version - ) { - total - records { - id - fromChain - toChain - bridge - relayer - sendToken - margin - baseFee - liquidityFeeRate - cost - profit - heartbeatTimestamp - messageChannel - lastTransferId - withdrawNonce - transferLimit - } - } - } -`; - export const GQL_HISTORY_RECORD_BY_TX_HASH = gql` query historyRecordByTxHash($txHash: String) { historyRecordByTxHash(txHash: $txHash) { @@ -132,52 +92,3 @@ export const GQL_HISTORY_RECORD_BY_TX_HASH = gql` } } `; - -export const GQL_CHECK_LNBRIDGE_EXIST = gql` - query checkLnBridgeExist($fromChainId: Int, $toChainId: Int, $fromToken: String, $toToken: String, $version: String) { - checkLnBridgeExist( - fromChainId: $fromChainId - toChainId: $toChainId - fromToken: $fromToken - toToken: $toToken - version: $version - ) - } -`; - -export const GQL_GET_LN_BRIDGE_MESSAGE_CHANNEL = gql` - query GetLnBridgeMessageChannel($bridge: String = "", $fromChain: String = "", $toChain: String = "") { - queryLnBridgeRelayInfos(row: 1, page: 0, bridge: $bridge, fromChain: $fromChain, toChain: $toChain) { - records { - messageChannel - } - } - } -`; - -export const GQL_GET_WITHDRAWABLE_LIQUIDITIES = gql` - query GetWithdrawableLiquidities( - $page: Int! - $relayer: String = "" - $recvTokenAddress: String = "" - $fromChain: String = "" - $toChain: String = "" - ) { - historyRecords( - row: 10 - page: $page - relayer: $relayer - recvTokenAddress: $recvTokenAddress - fromChains: [$fromChain] - toChains: [$toChain] - needWithdrawLiquidity: true - ) { - total - records { - id - sendAmount - lastRequestWithdraw - } - } - } -`; diff --git a/src/config/index.ts b/src/config/index.ts index ec26668bd..8c65c5891 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -1,2 +1 @@ -export * from "./constant"; export * from "./gql"; diff --git a/src/types/bridge.ts b/src/types/bridge.ts index 0abc09296..88f49f1dd 100644 --- a/src/types/bridge.ts +++ b/src/types/bridge.ts @@ -2,15 +2,10 @@ import { Address, Hex } from "viem"; import { PublicClient, WalletClient } from "wagmi"; import { ChainConfig } from "./chain"; import { Token } from "./token"; -import { MessageChannel } from "./graphql"; - -export type LnBridgeVersion = "lnv2" | "lnv3"; -export type LnBridgeV2Type = "default" | "opposite"; /** - * `lpbridge-darwinia-dvm` etc. are named from graphql indexer, except `lnbridge`. + * `lpbridge-darwinia-dvm` etc. are named from graphql indexer. */ -export type LnBridgeCategory = "lnbridge" | "lnv2-default" | "lnv2-opposite" | "lnv3"; export type L2BridgeCategory = "l2arbitrumbridge-ethereum"; export type HelixLpBridgeCategory = "lpbridge-darwinia-dvm" | "lpbridge-ethereum"; export type HelixBridgeCategory = @@ -24,12 +19,7 @@ export type XTokenBridgeCategory = | "xtoken-darwinia-dvm" | "xtoken-crab-dvm" | "xtoken-pangolin-dvm"; -export type BridgeCategory = - | LnBridgeCategory - | L2BridgeCategory - | HelixLpBridgeCategory - | HelixBridgeCategory - | XTokenBridgeCategory; +export type BridgeCategory = L2BridgeCategory | HelixLpBridgeCategory | HelixBridgeCategory | XTokenBridgeCategory; export interface BridgeContract { sourceAddress: Address; @@ -55,8 +45,6 @@ export interface BridgeConstructorArgs { export interface GetFeeArgs { baseFee?: bigint; - protocolFee?: bigint; - liquidityFeeRate?: bigint; transferAmount?: bigint; sender?: Address; recipient?: Address; @@ -67,15 +55,4 @@ export interface TransferOptions { relayer?: Address; transferId?: Hex | null; totalFee?: bigint; - withdrawNonce?: bigint; - depositedMargin?: bigint; -} - -export interface GetWithdrawFeeArgs { - amount: bigint; - sender?: Address; - relayer?: Address; - transferId?: Hex | null; - withdrawNonce?: string | null; - messageChannel?: MessageChannel | null; } diff --git a/src/types/cross-chain.ts b/src/types/cross-chain.ts index 69dc03660..1ffa320da 100644 --- a/src/types/cross-chain.ts +++ b/src/types/cross-chain.ts @@ -18,7 +18,7 @@ type Action = "issue" | "redeem"; export type CrossChain = | { target: Target; - bridge: { category: L2BridgeCategory; lnv2Type?: never }; + bridge: { category: L2BridgeCategory }; index?: never; price?: never; baseFee?: never; @@ -28,7 +28,7 @@ export type CrossChain = } | { target: Target; - bridge: { category: HelixBridgeCategory | XTokenBridgeCategory; lnv2Type?: never }; + bridge: { category: HelixBridgeCategory | XTokenBridgeCategory }; index?: never; price?: never; baseFee?: never; @@ -38,7 +38,7 @@ export type CrossChain = } | { target: Target; - bridge: { category: HelixLpBridgeCategory; lnv2Type?: never }; + bridge: { category: HelixLpBridgeCategory }; index: number; // One of the bridge contract transfer parameters price?: bigint; // When transferring native token, we need to set the price baseFee: bigint; diff --git a/src/types/graphql.ts b/src/types/graphql.ts index 6b9c2eef0..0f548361d 100644 --- a/src/types/graphql.ts +++ b/src/types/graphql.ts @@ -1,6 +1,6 @@ import { TokenSymbol } from "./token"; -import { BridgeCategory, LnBridgeCategory, LnBridgeVersion } from "./bridge"; -import { Network, ChainID } from "./chain"; +import { BridgeCategory } from "./bridge"; +import { Network } from "./chain"; import { Address, Hex } from "viem"; /** @@ -17,8 +17,6 @@ export enum RecordResult { FAILED, } -export type MessageChannel = "layerzero" | "msgline" | "sub2sub" | "arbitrum-l2"; - export interface HistoryRecord { id: string; fromChain: Network; @@ -49,32 +47,6 @@ export interface HistoryRecord { extData: Hex; } -export interface LnBridgeRelayInfo { - id: string; - version: LnBridgeVersion; - nonce: string; - targetNonce: string | null; - fromChain: Network; - toChain: Network; - bridge: BridgeCategory; - relayer: Address; - sendToken: Address | null; - transaction_hash: Hex; - timestamp: number; - margin: string | null; - protocolFee: string | null; - baseFee: string | null; - liquidityFeeRate: number | null; - slashCount: number | null; - withdrawNonce: string | null; - lastTransferId: Hex | null; - cost: string | null; - profit: string | null; - heartbeatTimestamp: number | null; - messageChannel: MessageChannel | null; - transferLimit: string | null; -} - /** * Custom */ @@ -102,43 +74,6 @@ export interface HistoryRecordResData { historyRecordById: HistoryRecord | null; } -export type LnBridgeRelayerOverview = Pick< - LnBridgeRelayInfo, - | "id" - | "relayer" - | "bridge" - | "fromChain" - | "toChain" - | "sendToken" - | "baseFee" - | "liquidityFeeRate" - | "margin" - | "cost" - | "profit" - | "heartbeatTimestamp" - | "messageChannel" - | "lastTransferId" - | "withdrawNonce" - | "transferLimit" ->; - -export interface QueryLnBridgeRelayInfosReqParams { - fromChain?: Network; - toChain?: Network; - relayer?: string; - bridge?: BridgeCategory; - version?: LnBridgeVersion; - row: number; - page: number; -} - -export interface QueryLnBridgeRelayInfosResData { - queryLnBridgeRelayInfos: { - total: number; - records: LnBridgeRelayerOverview[]; - } | null; -} - export interface HistoryRecordByTxHashReqParams { txHash: Hex; } @@ -146,46 +81,3 @@ export interface HistoryRecordByTxHashReqParams { export interface HistoryRecordByTxHashResData { historyRecordByTxHash: Pick | null; } - -export interface CheckLnBridgeExistReqParams { - fromChainId: ChainID | undefined; - toChainId: ChainID | undefined; - fromToken: Address | undefined; - toToken: Address | undefined; - version: string | undefined; -} - -export interface CheckLnBridgeExistResData { - checkLnBridgeExist: boolean | null; -} - -export interface LnV3MessageChannelReqParams { - bridge: LnBridgeCategory | null | undefined; - fromChain: Network | null | undefined; - toChain: Network | null | undefined; -} - -export interface LnV3MessageChannelResData { - queryLnBridgeRelayInfos: { - records: { messageChannel: MessageChannel }[]; - }; -} - -export interface WithdrawableLiquiditiesReqParams { - page: number; - relayer: Address | null | undefined; - recvTokenAddress: Address | null | undefined; - fromChain: Network | null | undefined; - toChain: Network | null | undefined; -} - -export interface WithdrawableLiquiditiesResData { - historyRecords: { - total: number; - records: { - id: string; - sendAmount: string; - lastRequestWithdraw: string; // Timestamp in Seconds - }[]; - }; -} diff --git a/src/ui/segmented-tabs.tsx b/src/ui/segmented-tabs.tsx deleted file mode 100644 index bd022163f..000000000 --- a/src/ui/segmented-tabs.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import { Key, ReactElement, useRef } from "react"; -import { CSSTransition, SwitchTransition } from "react-transition-group"; -import Tooltip from "./tooltip"; - -export interface SegmentedTabsProps { - activeKey: K; - options: { - key: K; - label: ReactElement | string; - children: ReactElement; - disabled?: boolean; - hidden?: boolean; - }[]; - className?: string; - wrapClassName?: string; - onChange?: (key: K) => void; -} - -export default function SegmentedTabs({ - options, - activeKey, - className, - wrapClassName, - onChange = () => undefined, -}: SegmentedTabsProps) { - const previousRef = useRef(null); - const currentRef = useRef(null); - const stateRef = useRef(activeKey); - - const nodeRef = stateRef.current === activeKey ? currentRef : previousRef; - stateRef.current = activeKey; - - return ( -
- {/* labels */} -
- {options - .filter(({ hidden }) => !hidden) - .map(({ key, label, disabled }) => ( -
- - - -
- ))} -
- - {/* content */} - - -
- {options.find(({ key }) => key === activeKey)?.children} -
-
-
-
- ); -} diff --git a/src/ui/step-title.tsx b/src/ui/step-title.tsx deleted file mode 100644 index 990735539..000000000 --- a/src/ui/step-title.tsx +++ /dev/null @@ -1,15 +0,0 @@ -interface Props { - step: number; - title: string; -} - -export default function StepTitle({ step, title }: Props) { - return ( -
-
- {step} -
-
{title}
-
- ); -} diff --git a/src/ui/tabs.tsx b/src/ui/tabs.tsx deleted file mode 100644 index 44284e022..000000000 --- a/src/ui/tabs.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import Image from "next/image"; -import { Key, ReactElement, useEffect, useRef, useState } from "react"; -import { CSSTransition, SwitchTransition } from "react-transition-group"; - -export interface TabsProps { - activeKey: K; - options: { - key: K; - label: ReactElement | string; - children: ReactElement; - }[]; - className?: string; - onChange?: (key: K) => void; -} - -export default function Tabs({ - options, - activeKey, - className, - onChange = () => undefined, -}: TabsProps) { - const [dividerWidth, setDividerWidth] = useState(); - - const labelRefs = useRef<(HTMLButtonElement | null)[]>([]); - const railRef = useRef(null); - - const previousRef = useRef(null); - const currentRef = useRef(null); - const stateRef = useRef(activeKey); - - const nodeRef = stateRef.current === activeKey ? currentRef : previousRef; - stateRef.current = activeKey; - const activeItem = options.find(({ key }) => key === activeKey) || options.at(0); - - useEffect(() => { - const labelElement = labelRefs.current[options.findIndex(({ key }) => key === activeKey)]; - const railElement = railRef.current; - - if (labelElement && railElement) { - railElement.style.transform = `translateX(${labelElement.offsetLeft}px)`; - railElement.style.width = `${labelElement.clientWidth}px`; - } - }, [options, activeKey]); - - return ( -
- {/* labels */} -
-
setDividerWidth(node?.scrollWidth)}> - {options.map(({ key, label }, index) => ( - - ))} -
- - {/* divider & rail */} -
-
-
-
-
-
- - {/* content */} - - -
- {activeItem ? ( - activeItem.children - ) : ( -
- No data - No data -
- )} -
-
-
-
- ); -} diff --git a/src/ui/version-switch.tsx b/src/ui/version-switch.tsx deleted file mode 100644 index 336262d8f..000000000 --- a/src/ui/version-switch.tsx +++ /dev/null @@ -1,36 +0,0 @@ -"use client"; - -import { useRef } from "react"; - -type Version = "v2" | "v3"; - -interface Props { - value: Version; - onChange: (value: Version) => void; -} - -export default function VersionSwitch({ value, onChange }: Props) { - const targetRef = useRef(null); - const thumbRef = useRef(null); - - return ( -
onChange(value === "v2" ? "v3" : "v2")} - > -
- {value} -
-
- ); -} diff --git a/src/utils/cross-chain.ts b/src/utils/cross-chain.ts index 94c0daa9d..b486dc021 100644 --- a/src/utils/cross-chain.ts +++ b/src/utils/cross-chain.ts @@ -28,14 +28,6 @@ let availableTargetChains: AvailableTargetChains = {}; let availableTargetTokens: AvailableTargetTokens = {}; let availableBridges: AvailableBridges = {}; -/** - * For LnBridge relayer - */ -let lnbridgeDefaultSourceChains: ChainConfig[] = []; -let lnbridgeDefaultTargetChains: ChainConfig[] = []; -let lnbridgeAvailableSourceTokens: AvailableSourceTokens = {}; -let lnbridgeAvailableTargetChains: AvailableTargetChains = {}; - getChainConfigs().forEach((sourceChain) => { let sourceTokens: Token[] = []; @@ -131,8 +123,6 @@ defaultSourceChains.sort(chainCompareFn); defaultTargetChains.sort(chainCompareFn); defaultSourceTokens.sort(tokenCompareFn); defaultTargetTokens.sort(tokenCompareFn); -lnbridgeDefaultSourceChains.sort(chainCompareFn); -lnbridgeDefaultTargetChains.sort(chainCompareFn); export function getCrossDefaultValue() { return { @@ -195,32 +185,3 @@ export function getAvailableTargetTokens( } return defaultTokens; } - -export function getLnBridgeCrossDefaultValue() { - return { defaultSourceChains: lnbridgeDefaultSourceChains, defaultTargetChains: lnbridgeDefaultTargetChains }; -} - -export function getLnBridgeAvailableSourceTokens( - sourceChain: ChainConfig | undefined, - targetChain: ChainConfig | undefined, - defaultTokens: Token[] = [], -) { - if (sourceChain && targetChain) { - const result = (lnbridgeAvailableSourceTokens[sourceChain.network]?.[targetChain.network] || []).sort( - tokenCompareFn, - ); - return result.length ? result : defaultTokens; - } - return defaultTokens; -} - -export function getLnBridgeAvailableTargetChains( - sourceChain: ChainConfig | undefined, - defaultChains: ChainConfig[] = [], -) { - if (sourceChain) { - const result = (lnbridgeAvailableTargetChains[sourceChain.network] || []).sort(chainCompareFn); - return result.length ? result : defaultChains; - } - return defaultChains; -} diff --git a/src/utils/misc.ts b/src/utils/misc.ts index 33a82a96f..8cf69a87c 100644 --- a/src/utils/misc.ts +++ b/src/utils/misc.ts @@ -1,6 +1,5 @@ -import { FEE_RATE_BASE, FEE_RATE_MAX, FEE_RATE_MAX_V3, FEE_RATE_MIN } from "@/config/constant"; import { RecordResult } from "@/types/graphql"; -import { Address, Hex, isHex } from "viem"; +import { Address, Hex } from "viem"; export function parseRecordResult(result: RecordResult) { switch (result) { @@ -33,20 +32,6 @@ export function getBridgeLogoSrc(fileName: string) { return `/images/bridge/${fileName}`; } -export function parseFeeRate(rate: string) { - return Math.round(Number(rate) * FEE_RATE_BASE); -} - -export function formatFeeRate(rate: number) { - return Number((rate / FEE_RATE_BASE).toFixed(3)); -} - -export function isValidFeeRate(rate: number, isV3?: boolean) { - const min = FEE_RATE_MIN; - const max = isV3 ? FEE_RATE_MAX_V3 : FEE_RATE_MAX; - return min <= rate && rate <= max; -} - export async function fetchMsglineFeeAndParams( fromChainId: number, toChainId: number, @@ -65,18 +50,3 @@ export async function fetchMsglineFeeAndParams( return { fee, extParams }; } } - -/** - * Extract transfer IDs - * @param ids IDs from history records - * @returns Hex[] - */ -export function extractTransferIds(ids: string[]): Hex[] { - return ids.map((id) => { - const transferId = id.split("-").slice(-1).at(0); - if (!transferId || !isHex(transferId)) { - throw new Error(`Failed to extract transfer id, id: ${id}`); - } - return transferId; - }); -}