Skip to content

Commit

Permalink
fix: gasMarketV2
Browse files Browse the repository at this point in the history
  • Loading branch information
heisenberg-2077 committed Dec 18, 2024
1 parent 8173aed commit 218623e
Show file tree
Hide file tree
Showing 11 changed files with 197 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ import {
ParsedActionData,
} from '@rabby-wallet/rabby-action';
import { useGasAccountTxsCheck } from '@/screens/GasAccount/hooks/checkTsx';
import { apiCustomRPC } from '@/core/apis';
import { apiCustomRPC, apiProvider } from '@/core/apis';

interface SignTxProps<TData extends any[] = any[]> {
params: {
Expand Down Expand Up @@ -566,10 +566,11 @@ const MiniSignTx = ({
chain: Chain,
custom?: number,
): Promise<GasLevel[]> => {
const list = await openapi.gasMarket(
chain.serverId,
custom && custom > 0 ? custom : undefined,
);
const list = await apiProvider.gasMarketV2({
chain,
customGas: custom && custom > 0 ? custom : undefined,
tx: txs[0],
});
setGasList(list);
return list;
};
Expand Down Expand Up @@ -926,6 +927,7 @@ const MiniSignTx = ({
task={task}
Header={
<GasSelectorHeader
tx={txs[0]}
gasAccountCost={gasAccountCost}
gasMethod={gasMethod}
onChangeGasMethod={setGasMethod}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,7 @@ export const SignTestnetTx = ({ params, origin }: SignTxProps) => {
<FooterBar
Header={
<GasSelectorHeader
tx={tx}
disabled={false}
isReady={isReady}
gasLimit={gasLimit}
Expand Down
10 changes: 6 additions & 4 deletions apps/mobile/src/components/Approval/components/SignTx/SignTx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -965,10 +965,11 @@ const SignMainnetTx = ({ params, origin }: SignTxProps) => {
chain: Chain,
custom?: number,
): Promise<GasLevel[]> => {
const list = await openapi.gasMarket(
chain.serverId,
custom && custom > 0 ? custom : undefined,
);
const list = await apiProvider.gasMarketV2({
chain,
customGas: custom && custom > 0 ? custom : undefined,
tx,
});
setGasList(list);
return list;
};
Expand Down Expand Up @@ -1486,6 +1487,7 @@ const SignMainnetTx = ({ params, origin }: SignTxProps) => {
<FooterBar
Header={
<GasSelectorHeader
tx={tx}
gasAccountCost={gasAccountCost}
gasMethod={gasMethod}
onChangeGasMethod={setGasMethod}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import React, {
import { useTranslation } from 'react-i18next';
import { calcMaxPriorityFee } from '@/utils/transaction';
import { Result } from '@rabby-wallet/rabby-security-engine';
import { GasLevel, TxPushType } from '@rabby-wallet/rabby-api/dist/types';
import { GasLevel, Tx, TxPushType } from '@rabby-wallet/rabby-api/dist/types';
import {
Image,
NativeSyntheticEvent,
Expand Down Expand Up @@ -61,6 +61,7 @@ import { default as RcIconGasAccountBlurCC } from '@/assets/icons/sign/tx/gas-ac
import { default as RcIconGasAccountActive } from '@/assets/icons/sign/tx/gas-account-active.svg';
import { SvgProps } from 'react-native-svg';
import { RcIconInfoCC } from '@/assets/icons/common';
import { apiProvider } from '@/core/apis';

export interface GasSelectorResponse extends GasLevel {
gasLimit: number;
Expand All @@ -69,6 +70,7 @@ export interface GasSelectorResponse extends GasLevel {
}

interface GasSelectorProps {
tx: Tx;
gasLimit: string | undefined;
gas: {
gasCostUsd: number | string | BigNumber;
Expand Down Expand Up @@ -173,6 +175,7 @@ export const GasSelectorHeader = ({
gasMethod,
gasAccountCost,
onChangeGasMethod,
tx,
}: GasSelectorProps) => {
const { t } = useTranslation();
const customerInputRef = useRef<TextInput>(null);
Expand Down Expand Up @@ -227,10 +230,11 @@ export const GasSelectorHeader = ({
if (chain?.isTestnet) {
return null;
}
const list = await openapi.gasMarket(
chain.serverId,
custom && custom > 0 ? custom : undefined,
);
const list = await apiProvider.gasMarketV2({
chain,
customGas: custom && custom > 0 ? custom : undefined,
tx,
});
return list.find(item => item.level === 'custom')!;
},
);
Expand Down
57 changes: 56 additions & 1 deletion apps/mobile/src/core/apis/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { omit } from 'lodash';
import { Common, Hardfork } from '@ethereumjs/common';
import { TransactionFactory } from '@ethereumjs/tx';
import { bytesToHex } from '@ethereumjs/util';
import { CHAINS_ENUM } from '@/constant/chains';
import { Chain, CHAINS_ENUM } from '@/constant/chains';
import { addresses, abis } from '@eth-optimism/contracts-ts';
import { INTERNAL_REQUEST_SESSION } from '@/constant';
import providerController from '../controllers/provider';
Expand All @@ -15,6 +15,7 @@ import { t } from 'i18next';
import abiCoder, { AbiCoder } from 'web3-eth-abi';
import { IExtractFromPromise } from '@/utils/type';
import { findChain } from '@/utils/chain';
import { Tx } from '@rabby-wallet/rabby-api/dist/types';

function buildTxParams(txMeta) {
return {
Expand Down Expand Up @@ -278,3 +279,57 @@ export const ethSendTransaction = async (
throw e;
}
};

type gasMarketV2ParamsV2 = {
chain: Chain;
tx: Tx;
customGas?: number;
};
type gasMarketV2ParamsV1 = {
chainId: string;
customGas?: number;
};
export const gasMarketV2 = async (
params: gasMarketV2ParamsV1 | gasMarketV2ParamsV2,
) => {
let chainId: string;
let tx: Tx | undefined;

if ('tx' in params) {
if (params.tx.nonce === undefined) {
params.tx.nonce = await getRecommendNonce({
from: params.tx.from,
chainId: params.chain.id,
});
}

if (params.tx.gasPrice === undefined || params.tx.gasPrice === '') {
params.tx.gasPrice = '0x0';
}
if (params.tx.gas === undefined || params.tx.gas === '') {
params.tx.gas = '0x0';
}
if (params.tx.data === undefined || params.tx.data === '') {
params.tx.data = '0x';
}
chainId = params.chain.serverId;
tx = {
chainId: params.tx.chainId,
data: params.tx.data,
from: params.tx.from,
gas: params.tx.gas,
nonce: params.tx.nonce,
to: params.tx.to,
value: params.tx.value,
gasPrice: params.tx.gasPrice,
};
} else {
chainId = params.chainId;
}

return openapi.gasMarketV2({
customGas: params.customGas,
chainId,
tx,
});
};
124 changes: 81 additions & 43 deletions apps/mobile/src/screens/Send/hooks/useSendToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { EventEmitter } from 'events';
import { customTestnetService, preferenceService } from '@/core/services';
import { findChain, findChainByEnum, findChainByServerID } from '@/utils/chain';
import { CHAINS_ENUM, Chain } from '@/constant/chains';
import { GasLevel, TokenItem } from '@rabby-wallet/rabby-api/dist/types';
import { GasLevel, TokenItem, Tx } from '@rabby-wallet/rabby-api/dist/types';
import { atom, useAtom } from 'jotai';
import { openapi, testOpenapi } from '@/core/request';
import { TFunction } from 'i18next';
Expand Down Expand Up @@ -298,10 +298,13 @@ function findInstanceLevel(gasList: GasLevel[]) {
prev.price >= current.price ? prev : current,
);
}
const fetchGasList = async (chainItem: Chain | null) => {
const fetchGasList = async (chainItem: Chain | null, params: Tx) => {
const list: GasLevel[] = chainItem?.isTestnet
? await customTestnetService.getGasMarket({ chainId: chainItem.id })
: await openapi.gasMarket(chainItem?.serverId || '');
: await apiProvider.gasMarketV2({
chain: chainItem!,
tx: params,
});

return list;
};
Expand Down Expand Up @@ -382,37 +385,6 @@ export function useSendTokenForm() {
...DF_SEND_TOKEN_FORM,
});

useEffect(() => {
setFormValues(prev => {
return {
...DF_SEND_TOKEN_FORM,
to: prev.to,
};
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentAccount?.type, currentAccount?.address]);

const { validationSchema } = useMemo(() => {
return {
validationSchema: makeSendTokenValidationSchema({ t }),
};
}, [t]);

const [{ error: loadGasListError }, loadGasList] = useAsyncFn(
async () => fetchGasList(chainItem),
[chainItem, putScreenState],
);

if (__DEV__ && loadGasListError) {
console.error(loadGasListError);
}

useEffect(() => {
loadGasList().then(list => {
putScreenState({ gasList: list });
});
}, [loadGasList, putScreenState]);

const { addressType } = useCheckAddressType(formValues.to, chainItem);

const { isShowMessageDataForToken, isShowMessageDataForContract } =
Expand All @@ -424,18 +396,15 @@ export function useSendTokenForm() {
};
}, [isNativeToken, addressType]);

const handleSubmit = useCallback(
async ({
const getParams = useCallback(
({
to,
amount,
messageDataForSendToEoa,
messageDataForContractCall,
}: FormSendToken) => {
sendTokenEventsRef.current.emit(SendTokenEvents.ON_SEND);

putScreenState({ isSubmitLoading: true });
const chain = findChainByServerID(currentToken.chain)!;
const sendValue = new BigNumber(amount)
const sendValue = new BigNumber(amount || 0)
.multipliedBy(10 ** currentToken.decimals)
.decimalPlaces(0, BigNumber.ROUND_DOWN);
const dataInput = [
Expand All @@ -453,7 +422,10 @@ export function useSendTokenForm() {
},
] as any[],
} as const,
[to, sendValue.toFixed(0)] as any[],
[
to || '0x0000000000000000000000000000000000000000',
sendValue.toFixed(0),
] as any[],
] as const;
const params: Record<string, any> = {
chainId: chain.id,
Expand Down Expand Up @@ -481,6 +453,73 @@ export function useSendTokenForm() {
}

params.value = `0x${sendValue.toString(16)}`;
}

return params;
},
[
currentAccount,
currentToken.chain,
currentToken.decimals,
currentToken.id,
isNativeToken,
isShowMessageDataForContract,
isShowMessageDataForToken,
screenState,
],
);

useEffect(() => {
setFormValues(prev => {
return {
...DF_SEND_TOKEN_FORM,
to: prev.to,
};
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentAccount?.type, currentAccount?.address]);

const { validationSchema } = useMemo(() => {
return {
validationSchema: makeSendTokenValidationSchema({ t }),
};
}, [t]);

const [{ error: loadGasListError }, loadGasList] = useAsyncFn(
async () => fetchGasList(chainItem, getParams(formValues) as Tx),
[chainItem, formValues, putScreenState],
);

if (__DEV__ && loadGasListError) {
console.error(loadGasListError);
}

useEffect(() => {
loadGasList().then(list => {
putScreenState({ gasList: list });
});
}, [loadGasList, putScreenState]);

const handleSubmit = useCallback(
async ({
to,
amount,
messageDataForSendToEoa,
messageDataForContractCall,
}: FormSendToken) => {
sendTokenEventsRef.current.emit(SendTokenEvents.ON_SEND);
putScreenState({ isSubmitLoading: true });
const chain = findChain({
serverId: currentToken.chain,
})!;

const params = getParams({
to,
amount,
messageDataForSendToEoa,
messageDataForContractCall,
});
if (isNativeToken) {
// 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);
Expand Down Expand Up @@ -569,12 +608,11 @@ export function useSendTokenForm() {
[
currentAccount,
currentToken,
getParams,
isNativeToken,
isShowMessageDataForContract,
isShowMessageDataForToken,
putScreenState,
screenState.estimatedGas,
screenState.safeInfo?.nonce,
screenState.selectedGasLevel?.price,
screenState.showGasReserved,
],
Expand Down
Loading

0 comments on commit 218623e

Please sign in to comment.