Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix swap test #6060

Merged
merged 15 commits into from
Aug 29, 2024
5 changes: 2 additions & 3 deletions e2e/9_swaps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ import {
afterAllcleanApp,
fetchElementAttributes,
tap,
tapByText,
delayTime,
swipeUntilVisible,
tapAndLongPressByText,
tapAndLongPress,
swipe,
} from './helpers';
Expand Down Expand Up @@ -69,10 +67,11 @@ describe('Swap Sheet Interaction Flow', () => {

await tap('token-to-buy-dai-1');
await delayTime('medium');

const swapInput = await fetchElementAttributes('swap-asset-input');

expect(swapInput.label).toContain('ETH');
expect(swapInput.label).toContain('10');
expect(swapInput.label).toContain('ETH');
});

it('Should be able to go to review and execute a swap', async () => {
Expand Down
5 changes: 5 additions & 0 deletions e2e/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,11 @@ export async function sendETHtoTestWallet() {
to: TESTING_WALLET,
value: parseEther('20'),
});
await delayTime('long');
const balance = await provider.getBalance(TESTING_WALLET);
if (balance.lt(parseEther('20'))) {
throw Error('Error sending ETH to test wallet');
}
return true;
}

Expand Down
9 changes: 8 additions & 1 deletion src/__swaps__/screens/Swap/components/SwapActionButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,14 @@ function SwapButton({
)}
{typeof label !== 'undefined' && (
<Column width="content">
<AnimatedText align="center" style={textStyles} numberOfLines={1} size={small ? '17pt' : '20pt'} weight="heavy">
<AnimatedText
testID={`${testID}-text`}
align="center"
style={textStyles}
numberOfLines={1}
size={small ? '17pt' : '20pt'}
weight="heavy"
>
{labelValue}
</AnimatedText>
</Column>
Expand Down
8 changes: 4 additions & 4 deletions src/__swaps__/screens/Swap/hooks/useAssetsToSell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { useUserAssets } from '@/__swaps__/screens/Swap/resources/assets';
import { ParsedAssetsDictByChain, ParsedSearchAsset, UserAssetFilter } from '@/__swaps__/types/assets';
import { useAccountSettings, useDebounce } from '@/hooks';
import { userAssetsStore } from '@/state/assets/userAssets';
import { getIsHardhatConnected } from '@/handlers/web3';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';

const sortBy = (by: UserAssetFilter) => {
switch (by) {
Expand All @@ -22,15 +22,15 @@ const sortBy = (by: UserAssetFilter) => {
};

export const useAssetsToSell = () => {
const { accountAddress: currentAddress, nativeCurrency: currentCurrency, network: currentNetwork } = useAccountSettings();

const connectedToHardhat = getIsHardhatConnected();
const { accountAddress: currentAddress, nativeCurrency: currentCurrency } = useAccountSettings();

const filter = userAssetsStore(state => state.filter);
const searchQuery = userAssetsStore(state => state.inputSearchQuery);

const debouncedAssetToSellFilter = useDebounce(searchQuery, 200);

const { connectedToHardhat } = useConnectedToHardhatStore();

const { data: userAssets = [] } = useUserAssets(
{
address: currentAddress as Address,
Expand Down
8 changes: 4 additions & 4 deletions src/__swaps__/screens/Swap/providers/swap-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { SwapAssetType, inputKeys } from '@/__swaps__/types/swap';
import { getDefaultSlippageWorklet, isUnwrapEthWorklet, isWrapEthWorklet, parseAssetAndExtend } from '@/__swaps__/utils/swaps';
import { analyticsV2 } from '@/analytics';
import { LegacyTransactionGasParamAmounts, TransactionGasParamAmounts } from '@/entities';
import { getFlashbotsProvider, getIsHardhatConnected, getProvider, isHardHat } from '@/handlers/web3';
import { getFlashbotsProvider, getProvider } from '@/handlers/web3';
import { WrappedAlert as Alert } from '@/helpers/alert';
import { useAccountSettings } from '@/hooks';
import { useAnimatedInterval } from '@/hooks/reanimated/useAnimatedInterval';
Expand All @@ -56,6 +56,7 @@ import { useSwapOutputQuotesDisabled } from '../hooks/useSwapOutputQuotesDisable
import { SyncGasStateToSharedValues, SyncQuoteSharedValuesToState } from './SyncSwapStateAndSharedValues';
import { performanceTracking, Screens, TimeToSignOperation } from '@/state/performance/performance';
import { getRemoteConfig } from '@/model/remoteConfig';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';

const swapping = i18n.t(i18n.l.swap.actions.swapping);
const holdToSwap = i18n.t(i18n.l.swap.actions.hold_to_swap);
Expand Down Expand Up @@ -199,8 +200,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
parameters.flashbots && getNetworkObject({ chainId: parameters.chainId }).features.flashbots
? await getFlashbotsProvider()
: getProvider({ chainId: parameters.chainId });
const providerUrl = provider?.connection?.url;
const connectedToHardhat = !!providerUrl && isHardHat(providerUrl);
const connectedToHardhat = useConnectedToHardhatStore.getState().connectedToHardhat;

const isBridge = swapsStore.getState().inputAsset?.mainnetAddress === swapsStore.getState().outputAsset?.mainnetAddress;
const isDegenModeEnabled = swapsStore.getState().degenMode;
Expand Down Expand Up @@ -258,7 +258,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
};
}

const chainId = getIsHardhatConnected() ? ChainId.hardhat : parameters.chainId;
const chainId = connectedToHardhat ? ChainId.hardhat : parameters.chainId;
const { errorMessage } = await performanceTracking.getState().executeFn({
fn: walletExecuteRap,
screen: Screens.SWAPS,
Expand Down
1 change: 0 additions & 1 deletion src/__swaps__/screens/Swap/resources/assets/userAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Address } from 'viem';

import { QueryConfigWithSelect, QueryFunctionArgs, QueryFunctionResult, createQueryKey, queryClient } from '@/react-query';

import { getIsHardhatConnected } from '@/handlers/web3';
import { RainbowError, logger } from '@/logger';
import { RainbowFetchClient } from '@/rainbow-fetch';
import { SupportedCurrencyKey, SUPPORTED_CHAIN_IDS } from '@/references';
Expand Down
2 changes: 1 addition & 1 deletion src/__swaps__/utils/decimalFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function valueBasedDecimalFormatter({
// Format the number to add separators and trim trailing zeros
const numberFormatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: minimumDecimalPlaces,
maximumFractionDigits: maximumDecimalPlaces,
maximumFractionDigits: maximumDecimalPlaces || 0,
useGrouping: !stripSeparators,
});

Expand Down
17 changes: 3 additions & 14 deletions src/handlers/web3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,29 +201,18 @@ export const getCachedProviderForNetwork = (chainId: ChainId = ChainId.mainnet):
export const getProvider = ({ chainId }: { chainId: number }): StaticJsonRpcProvider => {
const cachedProvider = chainsProviders.get(chainId);

if (cachedProvider) {
const networkObject = getNetworkObject({ chainId });

if (cachedProvider && cachedProvider?.connection.url === networkObject.rpc()) {
return cachedProvider;
}

const networkObject = getNetworkObject({ chainId });

const provider = new StaticJsonRpcProvider(networkObject.rpc(), networkObject.id);
chainsProviders.set(chainId, provider);

return provider;
};

/**
* @desc Checks if the active network is Hardhat.
* @returns boolean: `true` if connected to Hardhat.
*/
export const getIsHardhatConnected = (): boolean => {
const currentChainId = store.getState().settings.chainId;
const currentProviderUrl = getCachedProviderForNetwork(currentChainId)?.connection?.url;
const connectedToHardhat = !!currentProviderUrl && isHardHat(currentProviderUrl);
return connectedToHardhat;
};

/**
* @desc Sends an arbitrary RPC call using a given provider, or the default
* cached provider.
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/RainbowContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default function RainbowContextWrapper({ children }: PropsWithChildren) {
// This value is hold here to prevent JS VM from shutting down
// on unmounting all shared values.
useSharedValue(0);
const setConnectedToHardhat = useConnectedToHardhatStore.getState().setConnectedToHardhat;
const { setConnectedToHardhat } = useConnectedToHardhatStore();
const [config, setConfig] = useState<Record<string, boolean>>(
Object.entries(defaultConfig).reduce((acc, [key, { value }]) => ({ ...acc, [key]: value }), {})
);
Expand Down
21 changes: 11 additions & 10 deletions src/hooks/useENSRegistrationStepHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useDispatch } from 'react-redux';
import usePrevious from './usePrevious';
import { useENSRegistration, useInterval } from '.';
import { RegistrationParameters } from '@/entities';
import { getProvider, isHardHat, web3Provider } from '@/handlers/web3';
import { getProvider } from '@/handlers/web3';
import {
ENS_SECONDS_PADDING,
ENS_SECONDS_WAIT,
Expand All @@ -15,15 +15,16 @@ import {
} from '@/helpers/ens';
import { updateTransactionRegistrationParameters } from '@/redux/ensRegistration';
import { ChainId } from '@/networks/types';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';

const checkRegisterBlockTimestamp = async ({
registrationParameters,
secondsSinceCommitConfirmed,
isTestingHardhat,
connectedToHardhat,
}: {
registrationParameters: RegistrationParameters;
secondsSinceCommitConfirmed: number;
isTestingHardhat: boolean;
connectedToHardhat: boolean;
}) => {
try {
const provider = getProvider({ chainId: ChainId.mainnet });
Expand All @@ -34,7 +35,7 @@ const checkRegisterBlockTimestamp = async ({
(secs > ENS_SECONDS_WAIT_WITH_PADDING && secondsSinceCommitConfirmed > ENS_SECONDS_WAIT_WITH_PADDING) ||
// sometimes the provider.getBlock('latest) takes a long time to update to newest block
secondsSinceCommitConfirmed > ENS_SECONDS_WAIT_PROVIDER_PADDING ||
isTestingHardhat
connectedToHardhat
) {
return true;
}
Expand All @@ -61,12 +62,12 @@ export default function useENSRegistrationStepHandler(observer = true) {
-1
);

const isTestingHardhat = useMemo(() => isHardHat(web3Provider.connection.url), []);
const { connectedToHardhat } = useConnectedToHardhatStore();

const [readyToRegister, setReadyToRegister] = useState<boolean>(secondsSinceCommitConfirmed > ENS_SECONDS_WAIT);

// flag to wait 10 secs before we get the tx block, to be able to simulate not confirmed tx when testing
const shouldLoopForConfirmation = useRef(isTestingHardhat);
const shouldLoopForConfirmation = useRef(connectedToHardhat);

const registrationStep = useMemo(() => {
if (mode === REGISTRATION_MODES.EDIT) return REGISTRATION_STEPS.EDIT;
Expand Down Expand Up @@ -100,7 +101,7 @@ export default function useENSRegistrationStepHandler(observer = true) {
const now = Date.now();
const msBlockTimestamp = getBlockMsTimestamp(block);
// hardhat block timestamp is behind
const timeDifference = isTestingHardhat ? now - msBlockTimestamp : 0;
const timeDifference = connectedToHardhat ? now - msBlockTimestamp : 0;
const commitTransactionConfirmedAt = msBlockTimestamp + timeDifference;
const secs = differenceInSeconds(now, commitTransactionConfirmedAt);
setSecondsSinceCommitConfirmed(secondsSinceCommitConfirmed < 0 ? 0 : secs);
Expand All @@ -114,7 +115,7 @@ export default function useENSRegistrationStepHandler(observer = true) {
shouldLoopForConfirmation.current = false;
}
return confirmed;
}, [observer, commitTransactionHash, isTestingHardhat, secondsSinceCommitConfirmed, dispatch]);
}, [observer, commitTransactionHash, connectedToHardhat, secondsSinceCommitConfirmed, dispatch]);

const startPollingWatchCommitTransaction = useCallback(async () => {
if (observer) return;
Expand Down Expand Up @@ -167,15 +168,15 @@ export default function useENSRegistrationStepHandler(observer = true) {
if (!observer && secondsSinceCommitConfirmed % 2 === 0 && secondsSinceCommitConfirmed >= ENS_SECONDS_WAIT && !readyToRegister) {
const checkIfReadyToRegister = async () => {
const readyToRegister = await checkRegisterBlockTimestamp({
isTestingHardhat,
connectedToHardhat,
registrationParameters,
secondsSinceCommitConfirmed,
});
setReadyToRegister(readyToRegister);
};
checkIfReadyToRegister();
}
}, [isTestingHardhat, observer, readyToRegister, registrationParameters, secondsSinceCommitConfirmed]);
}, [connectedToHardhat, observer, readyToRegister, registrationParameters, secondsSinceCommitConfirmed]);

useEffect(
() => () => {
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useImportingWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ export default function useImportingWallet({ showImportModal = true } = {}) {
// Validate ENS
if (isENSAddressFormat(input)) {
try {
const web3Provider = getProvider({ chainId: ChainId.mainnet });
const provider = getProvider({ chainId: ChainId.mainnet });
const [address, avatar] = await Promise.all([
web3Provider.resolveName(input),
provider.resolveName(input),
!avatarUrl && profilesEnabled && fetchENSAvatar(input, { swallowError: true }),
]);
if (!address) {
Expand Down
7 changes: 3 additions & 4 deletions src/hooks/useRefreshAccountData.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import delay from 'delay';
import { useCallback, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import { getIsHardhatConnected } from '@/handlers/web3';
import { walletConnectLoadState } from '../redux/walletconnect';
import { fetchWalletENSAvatars, fetchWalletNames } from '../redux/wallets';
import useAccountSettings from './useAccountSettings';
Expand All @@ -16,13 +15,15 @@ import useNftSort from './useNFTsSortBy';
import { Address } from 'viem';
import { addysSummaryQueryKey } from '@/resources/summary/summary';
import useWallets from './useWallets';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';

export default function useRefreshAccountData() {
const dispatch = useDispatch();
const { accountAddress, nativeCurrency } = useAccountSettings();
const [isRefreshing, setIsRefreshing] = useState(false);
const profilesEnabled = useExperimentalFlag(PROFILES);
const { nftSort } = useNftSort();
const { connectedToHardhat } = useConnectedToHardhatStore();

const { wallets } = useWallets();

Expand All @@ -32,8 +33,6 @@ export default function useRefreshAccountData() {
);

const fetchAccountData = useCallback(async () => {
const connectedToHardhat = getIsHardhatConnected();

queryClient.invalidateQueries(nftsQueryKey({ address: accountAddress, sortBy: nftSort }));
queryClient.invalidateQueries(positionsQueryKey({ address: accountAddress as Address, currency: nativeCurrency }));
queryClient.invalidateQueries(addysSummaryQueryKey({ addresses: allAddresses, currency: nativeCurrency }));
Expand All @@ -56,7 +55,7 @@ export default function useRefreshAccountData() {
logger.error(new RainbowError(`[useRefreshAccountData]: Error refreshing data: ${error}`));
throw error;
}
}, [accountAddress, dispatch, nativeCurrency, profilesEnabled]);
}, [accountAddress, allAddresses, connectedToHardhat, dispatch, nativeCurrency, nftSort, profilesEnabled]);

const refresh = useCallback(async () => {
if (isRefreshing) return;
Expand Down
10 changes: 5 additions & 5 deletions src/hooks/useWatchPendingTxs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { userAssetsQueryKey } from '@/resources/assets/UserAssetsQuery';
import { userAssetsQueryKey as swapsUserAssetsQueryKey } from '@/__swaps__/screens/Swap/resources/assets/userAssets';
import { transactionFetchQuery } from '@/resources/transactions/transaction';
import { RainbowError, logger } from '@/logger';
import { getIsHardhatConnected, getProvider } from '@/handlers/web3';
import { getProvider } from '@/handlers/web3';
import { consolidatedTransactionsQueryKey } from '@/resources/transactions/consolidatedTransactions';
import { RainbowNetworkObjects } from '@/networks';
import { queryClient } from '@/react-query/queryClient';
Expand All @@ -17,12 +17,14 @@ import { nftsQueryKey } from '@/resources/nfts';
import { getNftSortForAddress } from './useNFTsSortBy';
import { ChainId } from '@/networks/types';
import { staleBalancesStore } from '@/state/staleBalances';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';

export const useWatchPendingTransactions = ({ address }: { address: string }) => {
const { storePendingTransactions, setPendingTransactions } = usePendingTransactionsStore(state => ({
storePendingTransactions: state.pendingTransactions,
setPendingTransactions: state.setPendingTransactions,
}));
const { connectedToHardhat } = useConnectedToHardhatStore();

const setNonce = useNonceStore(state => state.setNonce);

Expand All @@ -33,7 +35,6 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) =>
const refreshAssets = useCallback(
(_: RainbowTransaction) => {
// NOTE: We have two user assets stores right now, so let's invalidate both queries and trigger a refetch
const connectedToHardhat = getIsHardhatConnected();
queryClient.invalidateQueries(
userAssetsQueryKey({
address,
Expand All @@ -50,7 +51,7 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) =>
);
queryClient.invalidateQueries(nftsQueryKey({ address, sortBy: getNftSortForAddress(address) }));
},
[address, nativeCurrency]
[address, connectedToHardhat, nativeCurrency]
);

const processFlashbotsTransaction = useCallback(async (tx: RainbowTransaction): Promise<RainbowTransaction> => {
Expand Down Expand Up @@ -165,7 +166,6 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) =>
);

const watchPendingTransactions = useCallback(async () => {
const connectedToHardhat = getIsHardhatConnected();
if (!pendingTransactions?.length) return;
const updatedPendingTransactions = await Promise.all(
pendingTransactions.map((tx: RainbowTransaction) => processPendingTransaction(tx))
Expand Down Expand Up @@ -229,7 +229,7 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) =>
address,
pendingTransactions: newPendingTransactions,
});
}, [address, nativeCurrency, pendingTransactions, processNonces, processPendingTransaction, setPendingTransactions]);
}, [address, connectedToHardhat, nativeCurrency, pendingTransactions, processNonces, processPendingTransaction, setPendingTransactions]);

return { watchPendingTransactions };
};
Expand Down
10 changes: 3 additions & 7 deletions src/redux/gas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
} from '@/entities';

import { rainbowMeteorologyGetData } from '@/handlers/gasFees';
import { getProvider, isHardHat, toHex, web3Provider } from '@/handlers/web3';
import { getProvider, isHardHat, toHex } from '@/handlers/web3';
import {
defaultGasParamsFormat,
gweiToWei,
Expand Down Expand Up @@ -555,12 +555,8 @@ export const gasPricesStartPolling =
// the basefee at the time we fork mainnet during our hardhat tests
let baseFee = baseFeePerGas;
if (chainId === ChainId.mainnet && IS_TESTING === 'true') {
const providerUrl = (
web3Provider ||
({} as {
connection: { url: string };
})
)?.connection?.url;
const provider = getProvider({ chainId: ChainId.mainnet });
const providerUrl = provider?.connection?.url;
if (isHardHat(providerUrl)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could replace this with the connectedToHardhat directly instead of dealing with providerUrl and the isHardHat check?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep pushing

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i went ahead and also removed all instances of isHardhat

baseFee = parseGasFeeParam(gweiToWei(1000));
}
Expand Down
Loading
Loading