From 5ebb30282a9fd30921306bd294ea099dc5433e5d Mon Sep 17 00:00:00 2001
From: heisenberg <110591045+heisenberg-2077@users.noreply.github.com>
Date: Sat, 7 Dec 2024 21:48:54 +0800
Subject: [PATCH] Revert "feat: udate gasMarket api (#2653)" (#2666)

This reverts commit 1da1db0a73c95d3c7cb2552c32e7d23c37541b22.
---
 package.json                                  |   2 +-
 src/ui/utils/sendTransaction.ts               |   5 +-
 .../Approval/components/MiniSignTx/index.tsx  |  10 +-
 .../components/SignTestnetTx/index.tsx        |   1 -
 src/ui/views/Approval/components/SignTx.tsx   |  10 +-
 .../TxComponents/GasSelectorHeader.tsx        |  13 +-
 .../components/GasPriceBar/index.tsx          |   4 +-
 .../pages/Bridge/hooks/useDbkChainBridge.ts   |   2 +-
 src/ui/views/SendToken/index.tsx              | 177 +++++++-----------
 src/ui/views/Swap/hooks/quote.tsx             |  16 +-
 src/ui/views/Swap/hooks/token.tsx             |   2 +-
 .../components/SkipNonceAlert.tsx             |   5 +-
 .../components/TransactionItem.tsx            |  10 +-
 yarn.lock                                     |   8 +-
 14 files changed, 100 insertions(+), 165 deletions(-)

diff --git a/package.json b/package.json
index 9ffe9442a40..843f8e92d2c 100644
--- a/package.json
+++ b/package.json
@@ -61,7 +61,7 @@
     "@rabby-wallet/gnosis-sdk": "1.3.9",
     "@rabby-wallet/page-provider": "0.4.2",
     "@rabby-wallet/rabby-action": "0.1.8",
-    "@rabby-wallet/rabby-api": "0.8.7",
+    "@rabby-wallet/rabby-api": "0.8.5",
     "@rabby-wallet/rabby-security-engine": "2.0.7",
     "@rabby-wallet/rabby-swap": "0.0.42",
     "@rabby-wallet/widgets": "1.0.9",
diff --git a/src/ui/utils/sendTransaction.ts b/src/ui/utils/sendTransaction.ts
index 969f5fa96b5..11c24cd3884 100644
--- a/src/ui/utils/sendTransaction.ts
+++ b/src/ui/utils/sendTransaction.ts
@@ -143,10 +143,7 @@ export const sendTransaction = async ({
   // get gas
   let normalGas = gasLevel;
   if (!normalGas) {
-    const gasMarket = await wallet.openapi.gasMarket({
-      chainId: chainServerId,
-      tx,
-    });
+    const gasMarket = await wallet.openapi.gasMarket(chainServerId);
     normalGas = gasMarket.find((item) => item.level === 'normal')!;
   }
 
diff --git a/src/ui/views/Approval/components/MiniSignTx/index.tsx b/src/ui/views/Approval/components/MiniSignTx/index.tsx
index 048667578fa..82180835e1e 100644
--- a/src/ui/views/Approval/components/MiniSignTx/index.tsx
+++ b/src/ui/views/Approval/components/MiniSignTx/index.tsx
@@ -462,11 +462,10 @@ export const MiniSignTx = ({
     chain: Chain,
     custom?: number
   ): Promise<GasLevel[]> => {
-    const list = await wallet.openapi.gasMarket({
-      chainId: chain.serverId,
-      customGas: custom && custom > 0 ? custom : undefined,
-      tx: txs[0],
-    });
+    const list = await wallet.openapi.gasMarket(
+      chain.serverId,
+      custom && custom > 0 ? custom : undefined
+    );
     setGasList(list);
     return list;
   };
@@ -851,7 +850,6 @@ export const MiniSignTx = ({
             className={clsx(task.status !== 'idle' && 'pointer-events-none')}
           >
             <GasSelectorHeader
-              tx={txs[0]}
               gasAccountCost={gasAccountCost}
               gasMethod={gasMethod}
               onChangeGasMethod={setGasMethod}
diff --git a/src/ui/views/Approval/components/SignTestnetTx/index.tsx b/src/ui/views/Approval/components/SignTestnetTx/index.tsx
index e0750045517..ccedda3be73 100644
--- a/src/ui/views/Approval/components/SignTestnetTx/index.tsx
+++ b/src/ui/views/Approval/components/SignTestnetTx/index.tsx
@@ -705,7 +705,6 @@ export const SignTestnetTx = ({ params, origin }: SignTxProps) => {
       <FooterBar
         Header={
           <GasSelectorHeader
-            tx={tx}
             disabled={false}
             isReady={isReady}
             gasLimit={gasLimit}
diff --git a/src/ui/views/Approval/components/SignTx.tsx b/src/ui/views/Approval/components/SignTx.tsx
index f892cbdb757..d04cb58f43d 100644
--- a/src/ui/views/Approval/components/SignTx.tsx
+++ b/src/ui/views/Approval/components/SignTx.tsx
@@ -1339,11 +1339,10 @@ const SignTx = ({ params, origin }: SignTxProps) => {
     chain: Chain,
     custom?: number
   ): Promise<GasLevel[]> => {
-    const list = await wallet.openapi.gasMarket({
-      chainId: chain.serverId,
-      customGas: custom && custom > 0 ? custom : undefined,
-      tx,
-    });
+    const list = await wallet.openapi.gasMarket(
+      chain.serverId,
+      custom && custom > 0 ? custom : undefined
+    );
     setGasList(list);
     return list;
   };
@@ -1997,7 +1996,6 @@ const SignTx = ({ params, origin }: SignTxProps) => {
           <FooterBar
             Header={
               <GasSelectorHeader
-                tx={tx}
                 gasAccountCost={gasAccountCost}
                 gasMethod={gasMethod}
                 onChangeGasMethod={setGasMethod}
diff --git a/src/ui/views/Approval/components/TxComponents/GasSelectorHeader.tsx b/src/ui/views/Approval/components/TxComponents/GasSelectorHeader.tsx
index fb1642defea..6c679cd4309 100644
--- a/src/ui/views/Approval/components/TxComponents/GasSelectorHeader.tsx
+++ b/src/ui/views/Approval/components/TxComponents/GasSelectorHeader.tsx
@@ -1,7 +1,7 @@
 import { Button, Input, Skeleton, Tooltip } from 'antd';
 import { matomoRequestEvent } from '@/utils/matomo-request';
 import { ValidateStatus } from 'antd/lib/form/FormItem';
-import { GasLevel, Tx, TxPushType } from 'background/service/openapi';
+import { GasLevel, TxPushType } from 'background/service/openapi';
 import BigNumber from 'bignumber.js';
 import clsx from 'clsx';
 import {
@@ -58,7 +58,6 @@ export interface GasSelectorResponse extends GasLevel {
 }
 
 interface GasSelectorProps {
-  tx: Tx;
   gasLimit: string | undefined;
   gas: {
     gasCostUsd: number | string | BigNumber;
@@ -299,7 +298,6 @@ const GasSelectorHeader = ({
   gasMethod,
   gasAccountCost,
   onChangeGasMethod,
-  tx,
 }: GasSelectorProps) => {
   const wallet = useWallet();
   const dispatch = useRabbyDispatch();
@@ -352,11 +350,10 @@ const GasSelectorHeader = ({
 
   const loadCustomGasData = useCallback(
     async (custom?: number): Promise<GasLevel> => {
-      const list = await wallet.openapi.gasMarket({
-        chainId: chain.serverId,
-        customGas: custom && custom > 0 ? custom : undefined,
-        tx,
-      });
+      const list = await wallet.openapi.gasMarket(
+        chain.serverId,
+        custom && custom > 0 ? custom : undefined
+      );
       return list.find((item) => item.level === 'custom')!;
     },
     []
diff --git a/src/ui/views/Dashboard/components/GasPriceBar/index.tsx b/src/ui/views/Dashboard/components/GasPriceBar/index.tsx
index 4c6b253a3e7..f2cde451f9f 100644
--- a/src/ui/views/Dashboard/components/GasPriceBar/index.tsx
+++ b/src/ui/views/Dashboard/components/GasPriceBar/index.tsx
@@ -40,9 +40,7 @@ export const GasPriceBar: React.FC<Props> = ({ currentConnectedSiteChain }) => {
         ? await wallet.getCustomTestnetGasMarket({
             chainId: chain?.id,
           })
-        : await wallet.openapi.gasMarket({
-            chainId: currentConnectedSiteChainNativeToken,
-          });
+        : await wallet.openapi.gasMarket(currentConnectedSiteChainNativeToken);
       const selectedGasPice = marketGas.find((item) => item.level === 'slow')
         ?.price;
       if (selectedGasPice) {
diff --git a/src/ui/views/Ecology/dbk-chain/pages/Bridge/hooks/useDbkChainBridge.ts b/src/ui/views/Ecology/dbk-chain/pages/Bridge/hooks/useDbkChainBridge.ts
index 1f202c117a7..25fbad13480 100644
--- a/src/ui/views/Ecology/dbk-chain/pages/Bridge/hooks/useDbkChainBridge.ts
+++ b/src/ui/views/Ecology/dbk-chain/pages/Bridge/hooks/useDbkChainBridge.ts
@@ -215,7 +215,7 @@ export const useDbkChainBridge = ({
   );
 
   const fetchGasPrice = useMemoizedFn(async (serverId: string) => {
-    const marketGas = await wallet.openapi.gasMarket({ chainId: serverId });
+    const marketGas = await wallet.openapi.gasMarket(serverId);
     const selectedGasPice = marketGas.find((item) => item.level === 'normal');
     return selectedGasPice;
   });
diff --git a/src/ui/views/SendToken/index.tsx b/src/ui/views/SendToken/index.tsx
index a92fb80ce3e..ad2002b5679 100644
--- a/src/ui/views/SendToken/index.tsx
+++ b/src/ui/views/SendToken/index.tsx
@@ -31,7 +31,7 @@ import { query2obj } from 'ui/utils/url';
 import { formatTokenAmount, splitNumberByStep } from 'ui/utils/number';
 import AccountCard from '../Approval/components/AccountCard';
 import TokenAmountInput from 'ui/component/TokenAmountInput';
-import { GasLevel, TokenItem, Tx } from 'background/service/openapi';
+import { GasLevel, TokenItem } from 'background/service/openapi';
 import { PageHeader, AddressViewer } from 'ui/component';
 import ContactEditModal from 'ui/component/Contact/EditModal';
 import ContactListModal from 'ui/component/Contact/ListModal';
@@ -461,109 +461,21 @@ const SendToken = () => {
   const isNativeToken =
     !!chainItem && currentToken?.id === chainItem.nativeTokenAddress;
 
-  const { addressType } = useCheckAddressType(formSnapshot.to, chainItem);
-
-  const {
-    isShowMessageDataForToken,
-    isShowMessageDataForContract,
-  } = useMemo(() => {
-    return {
-      isShowMessageDataForToken: isNativeToken && addressType === 'EOA',
-      isShowMessageDataForContract: isNativeToken && addressType === 'CONTRACT',
-    };
-  }, [isNativeToken, addressType]);
-
-  const getParams = React.useCallback(
-    ({
-      to,
-      amount,
-      messageDataForSendToEoa,
-      messageDataForContractCall,
-    }: FormSendToken) => {
-      const chain = findChain({
-        serverId: currentToken.chain,
-      })!;
-      const sendValue = new BigNumber(amount || 0)
-        .multipliedBy(10 ** currentToken.decimals)
-        .decimalPlaces(0, BigNumber.ROUND_DOWN);
-      const dataInput = [
-        {
-          name: 'transfer',
-          type: 'function',
-          inputs: [
-            {
-              type: 'address',
-              name: 'to',
-            },
-            {
-              type: 'uint256',
-              name: 'value',
-            },
-          ] as any[],
-        } as const,
-        [
-          to || '0x0000000000000000000000000000000000000000',
-          sendValue.toFixed(0),
-        ] as any[],
-      ] as const;
-      const params: Record<string, any> = {
-        chainId: chain.id,
-        from: currentAccount!.address,
-        to: currentToken.id,
-        value: '0x0',
-        data: abiCoder.encodeFunctionCall(dataInput[0], dataInput[1]),
-        isSend: true,
-      };
-      if (safeInfo?.nonce != null) {
-        params.nonce = safeInfo.nonce;
-      }
-      if (isNativeToken) {
-        params.to = to;
-        delete params.data;
-
-        if (isShowMessageDataForToken && messageDataForSendToEoa) {
-          const encodedValue = formatTxInputDataOnERC20(messageDataForSendToEoa)
-            .hexData;
-
-          params.data = encodedValue;
-        } else if (isShowMessageDataForContract && messageDataForContractCall) {
-          params.data = messageDataForContractCall;
-        }
-
-        params.value = `0x${sendValue.toString(16)}`;
-      }
-
-      return params;
-    },
-    [
-      currentAccount,
-      currentToken.chain,
-      currentToken.decimals,
-      currentToken.id,
-      isNativeToken,
-      isShowMessageDataForContract,
-      isShowMessageDataForToken,
-      safeInfo,
-    ]
-  );
-
   const fetchGasList = useCallback(async () => {
-    const values = form.getFieldsValue();
-    const params = getParams(values) as Tx;
-
     const list: GasLevel[] = chainItem?.isTestnet
       ? await wallet.getCustomTestnetGasMarket({ chainId: chainItem.id })
-      : await wallet.openapi.gasMarket({
-          chainId: chainItem?.serverId || '',
-          tx: params,
-        });
+      : await wallet.openapi.gasMarket(chainItem?.serverId || '');
     return list;
-  }, [chainItem, form, getParams, wallet]);
+  }, [wallet, chainItem]);
 
   const [{ value: gasList }, loadGasList] = useAsyncFn(() => {
     return fetchGasList();
   }, [fetchGasList]);
 
+  useEffect(() => {
+    loadGasList();
+  }, [loadGasList]);
+
   useDebounce(
     async () => {
       const targetChain = findChainByEnum(chain)!;
@@ -573,17 +485,32 @@ const SendToken = () => {
         gasPriceMap[targetChain.enum].expireAt > Date.now()
       ) {
         gasList = gasPriceMap[targetChain.enum].list;
+      } else {
+        gasList = await fetchGasList();
+        setGasPriceMap({
+          ...gasPriceMap,
+          [targetChain.enum]: {
+            list: gasList,
+            expireAt: Date.now() + 300000, // cache gasList for 5 mins
+          },
+        });
       }
     },
     500,
     [chain]
   );
 
-  useEffect(() => {
-    if (clickedMax) {
-      loadGasList();
-    }
-  }, [clickedMax, loadGasList]);
+  const { addressType } = useCheckAddressType(formSnapshot.to, chainItem);
+
+  const {
+    isShowMessageDataForToken,
+    isShowMessageDataForContract,
+  } = useMemo(() => {
+    return {
+      isShowMessageDataForToken: isNativeToken && addressType === 'EOA',
+      isShowMessageDataForContract: isNativeToken && addressType === 'CONTRACT',
+    };
+  }, [isNativeToken, addressType]);
 
   const handleSubmit = async ({
     to,
@@ -595,13 +522,51 @@ const SendToken = () => {
     const chain = findChain({
       serverId: currentToken.chain,
     })!;
-    const params = getParams({
-      to,
-      amount,
-      messageDataForSendToEoa,
-      messageDataForContractCall,
-    });
+    const sendValue = new BigNumber(amount)
+      .multipliedBy(10 ** currentToken.decimals)
+      .decimalPlaces(0, BigNumber.ROUND_DOWN);
+    const dataInput = [
+      {
+        name: 'transfer',
+        type: 'function',
+        inputs: [
+          {
+            type: 'address',
+            name: 'to',
+          },
+          {
+            type: 'uint256',
+            name: 'value',
+          },
+        ] as any[],
+      } as const,
+      [to, sendValue.toFixed(0)] as any[],
+    ] as const;
+    const params: Record<string, any> = {
+      chainId: chain.id,
+      from: currentAccount!.address,
+      to: currentToken.id,
+      value: '0x0',
+      data: abiCoder.encodeFunctionCall(dataInput[0], dataInput[1]),
+      isSend: true,
+    };
+    if (safeInfo?.nonce != null) {
+      params.nonce = safeInfo.nonce;
+    }
     if (isNativeToken) {
+      params.to = to;
+      delete params.data;
+
+      if (isShowMessageDataForToken && messageDataForSendToEoa) {
+        const encodedValue = formatTxInputDataOnERC20(messageDataForSendToEoa)
+          .hexData;
+
+        params.data = encodedValue;
+      } else if (isShowMessageDataForContract && messageDataForContractCall) {
+        params.data = messageDataForContractCall;
+      }
+
+      params.value = `0x${sendValue.toString(16)}`;
       // L2 has extra validation fee so we can not set gasLimit as 21000 when send native token
       const couldSpecifyIntrinsicGas = !CAN_NOT_SPECIFY_INTRINSIC_GAS_CHAINS.includes(
         chain.enum
diff --git a/src/ui/views/Swap/hooks/quote.tsx b/src/ui/views/Swap/hooks/quote.tsx
index e96914a0bfc..8b9bf6de1ae 100644
--- a/src/ui/views/Swap/hooks/quote.tsx
+++ b/src/ui/views/Swap/hooks/quote.tsx
@@ -164,15 +164,7 @@ export const useQuoteMethods = () => {
       const lastTimeGas: ChainGas | null = await walletController.getLastTimeGasSelection(
         CHAINS[chain].id
       );
-      const gasMarket = await walletOpenapi.gasMarket({
-        chainId: CHAINS[chain].serverId,
-        tx: {
-          ...quote.tx,
-          nonce,
-          chainId: CHAINS[chain].id,
-          gas: '0x0',
-        },
-      });
+      const gasMarket = await walletOpenapi.gasMarket(CHAINS[chain].serverId);
 
       let gasPrice = 0;
       if (lastTimeGas?.lastTimeSelect === 'gasPrice' && lastTimeGas.gasPrice) {
@@ -329,9 +321,9 @@ export const useQuoteMethods = () => {
       try {
         let gasPrice: number;
         if (isOpenOcean) {
-          const gasMarket = await walletOpenapi.gasMarket({
-            chainId: CHAINS[chain].serverId,
-          });
+          const gasMarket = await walletOpenapi.gasMarket(
+            CHAINS[chain].serverId
+          );
           gasPrice = gasMarket?.[1]?.price;
         }
         stats.report('swapRequestQuote', {
diff --git a/src/ui/views/Swap/hooks/token.tsx b/src/ui/views/Swap/hooks/token.tsx
index f06fc01156c..fae6b854457 100644
--- a/src/ui/views/Swap/hooks/token.tsx
+++ b/src/ui/views/Swap/hooks/token.tsx
@@ -294,7 +294,7 @@ export const useTokenPair = (userAddress: string) => {
   const { value: gasList } = useAsync(() => {
     gasPriceRef.current = undefined;
     setGasLevel('normal');
-    return wallet.openapi.gasMarket({ chainId: CHAINS[chain].serverId });
+    return wallet.openapi.gasMarket(CHAINS[chain].serverId);
   }, [chain]);
 
   const [reserveGasOpen, setReserveGasOpen] = useState(false);
diff --git a/src/ui/views/TransactionHistory/components/SkipNonceAlert.tsx b/src/ui/views/TransactionHistory/components/SkipNonceAlert.tsx
index 88786982937..7fccf5ad46d 100644
--- a/src/ui/views/TransactionHistory/components/SkipNonceAlert.tsx
+++ b/src/ui/views/TransactionHistory/components/SkipNonceAlert.tsx
@@ -167,10 +167,7 @@ export const SkipNonceAlert = ({
       ? await wallet.getCustomTestnetGasMarket({
           chainId: chain.id,
         })
-      : await wallet.openapi.gasMarket({
-          chainId: chain.serverId,
-          tx: maxGasTx.rawTx,
-        });
+      : await wallet.openapi.gasMarket(chain.serverId);
     const maxGasMarketPrice = maxBy(gasLevels, (level) => level.price)!.price;
     await wallet.sendRequest({
       method: 'eth_sendTransaction',
diff --git a/src/ui/views/TransactionHistory/components/TransactionItem.tsx b/src/ui/views/TransactionHistory/components/TransactionItem.tsx
index c6a1ef53b83..011bc8c05bd 100644
--- a/src/ui/views/TransactionHistory/components/TransactionItem.tsx
+++ b/src/ui/views/TransactionHistory/components/TransactionItem.tsx
@@ -153,10 +153,7 @@ export const TransactionItem = ({
       ? await wallet.getCustomTestnetGasMarket({
           chainId: chain.id,
         })
-      : await wallet.openapi.gasMarket({
-          chainId: chain.serverId,
-          tx: maxGasTx.rawTx,
-        });
+      : await wallet.openapi.gasMarket(chain.serverId);
     const maxGasMarketPrice = maxBy(gasLevels, (level) => level.price)!.price;
     await wallet.sendRequest({
       method: 'eth_sendTransaction',
@@ -193,10 +190,7 @@ export const TransactionItem = ({
       ? await wallet.getCustomTestnetGasMarket({
           chainId: chain.id,
         })
-      : await wallet.openapi.gasMarket({
-          chainId: chain.serverId,
-          tx: originTx.rawTx,
-        });
+      : await wallet.openapi.gasMarket(chain.serverId);
     const maxGasMarketPrice = maxBy(gasLevels, (level) => level.price)!.price;
     await wallet.sendRequest({
       method: 'eth_sendTransaction',
diff --git a/yarn.lock b/yarn.lock
index cbb964f23ef..8b2b0242a20 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4774,10 +4774,10 @@
   resolved "https://registry.yarnpkg.com/@rabby-wallet/rabby-action/-/rabby-action-0.1.8.tgz#05b258b628a224d51dc471e93117d4106024a916"
   integrity sha512-K0euVX55tW2mbnudm3bHPAbbLYlnDQD5PgAvM1mwPPFHhF/Ve/U5MYdg1XERJPxkoXKqiVti46idFFB+s8sv7A==
 
-"@rabby-wallet/rabby-api@0.8.7":
-  version "0.8.7"
-  resolved "https://registry.yarnpkg.com/@rabby-wallet/rabby-api/-/rabby-api-0.8.7.tgz#8834fd1388417890aece0611ebec879dc32e1475"
-  integrity sha512-TFMPU44zmvXkXCuGviMntV68qGEylfoHH2YTYKyhg9LCgei9kbpBTTxr53f7x3zs8GwPU5e69BtlIiwEW3JQ2Q==
+"@rabby-wallet/rabby-api@0.8.5":
+  version "0.8.5"
+  resolved "https://registry.yarnpkg.com/@rabby-wallet/rabby-api/-/rabby-api-0.8.5.tgz#b2c7820c52ffe2aa8cb3226304593eaca1231b88"
+  integrity sha512-yykwK/pZA/5eCn/QCRwgP6uDQQhOdG3Zl1CAjFqK5AVNyc5DE1BCcZWkABWzXjt63KJHePVcAX7rP8rhzbmsTQ==
   dependencies:
     "@rabby-wallet/rabby-sign" "0.4.0"
     axios "^0.27.2"