Skip to content

Commit

Permalink
Merge branch '@benisgold/raps' of https://github.com/rainbow-me/rainbow
Browse files Browse the repository at this point in the history
… into @benisgold/claim-panel-ui
  • Loading branch information
benisgold committed Sep 30, 2024
2 parents 45a9552 + 198310c commit 529e513
Show file tree
Hide file tree
Showing 12 changed files with 55 additions and 72 deletions.
1 change: 1 addition & 0 deletions scripts/networks.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ async function fetchData() {
badgeURL
}
testnet
internal
opStack
defaultExplorer {
url
Expand Down
5 changes: 3 additions & 2 deletions src/__swaps__/screens/Swap/Swap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { parseSearchAsset } from '@/__swaps__/utils/assets';
import { AbsolutePortalRoot } from '@/components/AbsolutePortal';
import { useDelayedMount } from '@/hooks/useDelayedMount';
import { userAssetsStore } from '@/state/assets/userAssets';
import { useSwapsStore } from '@/state/swaps/swapsStore';
import { swapsStore, useSwapsStore } from '@/state/swaps/swapsStore';
import { SwapWarning } from './components/SwapWarning';
import { clearCustomGasSettings } from './hooks/useCustomGas';
import { SwapProvider, useSwapContext } from './providers/swap-provider';
Expand Down Expand Up @@ -109,6 +109,7 @@ const useCleanupOnUnmount = () => {
useEffect(() => {
return () => {
const highestValueEth = userAssetsStore.getState().getHighestValueEth();
const preferredNetwork = swapsStore.getState().preferredNetwork;
const parsedAsset = highestValueEth
? parseSearchAsset({
assetWithPrice: undefined,
Expand All @@ -123,7 +124,7 @@ const useCleanupOnUnmount = () => {
outputAsset: null,
outputSearchQuery: '',
quote: null,
selectedOutputChainId: parsedAsset?.chainId ?? ChainId.mainnet,
selectedOutputChainId: parsedAsset?.chainId ?? preferredNetwork ?? ChainId.mainnet,
});

userAssetsStore.setState({ filter: 'all', inputSearchQuery: '' });
Expand Down
6 changes: 4 additions & 2 deletions src/__swaps__/screens/Swap/components/GasButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ function EstimatedGasFee() {
}

function SelectedGas({ isPill }: { isPill?: boolean }) {
const chainId = swapsStore(s => s.inputAsset?.chainId || ChainId.mainnet);
const preferredNetwork = swapsStore(s => s.preferredNetwork);
const chainId = swapsStore(s => s.inputAsset?.chainId || preferredNetwork || ChainId.mainnet);
const selectedGasSpeed = useSelectedGasSpeed(chainId);

return (
Expand Down Expand Up @@ -108,7 +109,8 @@ function keys<const T extends string>(obj: Record<T, unknown> | undefined) {
const GasMenu = ({ backToReview = false, children }: { backToReview?: boolean; children: ReactNode }) => {
const { SwapNavigation } = useSwapContext();

const chainId = swapsStore(s => s.inputAsset?.chainId || ChainId.mainnet);
const preferredNetwork = swapsStore(s => s.preferredNetwork);
const chainId = swapsStore(s => s.inputAsset?.chainId || preferredNetwork || ChainId.mainnet);
const metereologySuggestions = useMeteorologySuggestions({ chainId });
const customGasSettings = useCustomGasSettings(chainId);

Expand Down
34 changes: 10 additions & 24 deletions src/__swaps__/screens/Swap/hooks/useEstimatedGasFee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import { useMemo } from 'react';
import { formatUnits } from 'viem';

import { useAccountSettings } from '@/hooks';
import { useSyncedSwapQuoteStore } from '../providers/SyncSwapStateAndSharedValues';
import { calculateGasFeeWorklet, useSyncedSwapQuoteStore } from '../providers/SyncSwapStateAndSharedValues';
import { GasSettings } from './useCustomGas';
import { useSelectedGas } from './useSelectedGas';
import { useSwapEstimatedGasLimit } from './useSwapEstimatedGasLimit';
import { useSwapsStore } from '@/state/swaps/swapsStore';

function safeBigInt(value: string) {
try {
Expand All @@ -19,24 +20,6 @@ function safeBigInt(value: string) {
}
}

const isFeeNaN = (value: string | undefined) => isNaN(Number(value)) || typeof value === 'undefined';

export function calculateGasFee(gasSettings: GasSettings, gasLimit: string) {
if (gasSettings.isEIP1559) {
if (isFeeNaN(gasSettings.maxBaseFee) || isFeeNaN(gasSettings.maxPriorityFee)) {
return null;
}

return add(gasSettings.maxBaseFee, gasSettings.maxPriorityFee);
}

if (isFeeNaN(gasSettings.gasPrice)) {
return null;
}

return multiply(gasLimit, gasSettings.gasPrice);
}

export function useEstimatedGasFee({
chainId,
gasLimit,
Expand All @@ -52,21 +35,24 @@ export function useEstimatedGasFee({
return useMemo(() => {
if (!gasLimit || !gasSettings || !nativeNetworkAsset?.price) return;

const fee = calculateGasFee(gasSettings, gasLimit);
if (!fee) return;
const gasFee = calculateGasFeeWorklet(gasSettings, gasLimit);
if (isNaN(Number(gasFee))) {
return;
}

const networkAssetPrice = nativeNetworkAsset.price.value?.toString();
if (!networkAssetPrice) return `${formatNumber(weiToGwei(fee))} Gwei`;
if (!networkAssetPrice) return `${formatNumber(weiToGwei(gasFee))} Gwei`;

const feeFormatted = formatUnits(safeBigInt(fee), nativeNetworkAsset.decimals).toString();
const feeFormatted = formatUnits(safeBigInt(gasFee), nativeNetworkAsset.decimals).toString();
const feeInUserCurrency = multiply(networkAssetPrice, feeFormatted);

return convertAmountToNativeDisplayWorklet(feeInUserCurrency, nativeCurrency, true);
}, [gasLimit, gasSettings, nativeCurrency, nativeNetworkAsset?.decimals, nativeNetworkAsset?.price]);
}

export function useSwapEstimatedGasFee(overrideGasSettings?: GasSettings) {
const { assetToSell, quote, chainId = ChainId.mainnet } = useSyncedSwapQuoteStore();
const preferredNetwork = useSwapsStore(s => s.preferredNetwork);
const { assetToSell, quote, chainId = preferredNetwork || ChainId.mainnet } = useSyncedSwapQuoteStore();
const gasSettings = useSelectedGas(chainId);

const { data: estimatedGasLimit, isFetching } = useSwapEstimatedGasLimit({ chainId, assetToSell, quote });
Expand Down
3 changes: 2 additions & 1 deletion src/__swaps__/screens/Swap/hooks/useNativeAssetForChain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { ChainId } from '@/chains/types';
import { SharedValue, runOnJS, useAnimatedReaction, useDerivedValue, useSharedValue } from 'react-native-reanimated';
import { ParsedAddressAsset } from '@/entities';
import { ethereumUtils } from '@/utils';
import { swapsStore } from '@/state/swaps/swapsStore';

export const useNativeAssetForChain = ({ inputAsset }: { inputAsset: SharedValue<ExtendedAnimatedAssetWithColors | null> }) => {
const chainId = useDerivedValue(() => inputAsset.value?.chainId ?? ChainId.mainnet);
const chainId = useDerivedValue(() => inputAsset.value?.chainId ?? swapsStore.getState().preferredNetwork ?? ChainId.mainnet);
const nativeAsset = useSharedValue<ParsedAddressAsset | undefined>(ethereumUtils.getNetworkNativeAsset({ chainId: chainId.value }));

const getNativeAssetForNetwork = useCallback(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { GasSettings } from '../hooks/useCustomGas';
import { useSelectedGas } from '../hooks/useSelectedGas';
import { useSwapEstimatedGasLimit } from '../hooks/useSwapEstimatedGasLimit';
import { useSwapContext } from './swap-provider';
import { useSwapsStore } from '@/state/swaps/swapsStore';

const BUFFER_RATIO = 0.5;

Expand Down Expand Up @@ -89,18 +90,13 @@ export function calculateGasFeeWorklet(gasSettings: GasSettings, gasLimit: strin
'worklet';

if (gasSettings.isEIP1559) {
if (isFeeNaNWorklet(gasSettings.maxBaseFee) || isFeeNaNWorklet(gasSettings.maxPriorityFee)) {
return null;
}

return sumWorklet(gasSettings.maxBaseFee || '0', gasSettings.maxPriorityFee || '0');
}

if (isFeeNaNWorklet(gasSettings.gasPrice)) {
return null;
const maxBaseFee = isFeeNaNWorklet(gasSettings.maxBaseFee) ? '0' : gasSettings.maxBaseFee;
const maxPriorityFee = isFeeNaNWorklet(gasSettings.maxPriorityFee) ? '0' : gasSettings.maxPriorityFee;
return mulWorklet(gasLimit, sumWorklet(maxBaseFee, maxPriorityFee));
}

return mulWorklet(gasLimit, gasSettings.gasPrice);
const gasPrice = isFeeNaNWorklet(gasSettings.gasPrice) ? '0' : gasSettings.gasPrice;
return mulWorklet(gasLimit, gasPrice);
}

export function formatUnitsWorklet(value: string, decimals: number) {
Expand Down Expand Up @@ -138,8 +134,12 @@ const getHasEnoughFundsForGasWorklet = ({

export function SyncGasStateToSharedValues() {
const { hasEnoughFundsForGas, internalSelectedInputAsset } = useSwapContext();
const preferredNetwork = useSwapsStore(s => s.preferredNetwork);

const initialChainId = useMemo(() => internalSelectedInputAsset.value?.chainId || ChainId.mainnet, [internalSelectedInputAsset]);
const initialChainId = useMemo(
() => internalSelectedInputAsset.value?.chainId || preferredNetwork || ChainId.mainnet,
[internalSelectedInputAsset, preferredNetwork]
);
const { assetToSell, chainId = initialChainId, quote } = useSyncedSwapQuoteStore();

const gasSettings = useSelectedGas(chainId);
Expand Down Expand Up @@ -198,7 +198,7 @@ export function SyncGasStateToSharedValues() {
}

const gasFee = calculateGasFeeWorklet(gasSettings, estimatedGasLimit);
if (gasFee === null || isNaN(Number(gasFee))) {
if (isNaN(Number(gasFee))) {
return;
}

Expand Down
1 change: 1 addition & 0 deletions src/chains/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ export interface BackendNetwork {
badgeURL: string;
};
testnet: boolean;
internal: boolean;
opStack: boolean;
defaultExplorer: {
url: string;
Expand Down
4 changes: 2 additions & 2 deletions src/chains/utils/backendNetworks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Chain } from 'viem';
import { mainnet } from 'viem/chains';

import { RPC_PROXY_API_KEY } from '@/env';
import { IS_DEV, RPC_PROXY_API_KEY } from '@/env';
import { BackendNetwork } from '../types';

const proxyBackendNetworkRpcEndpoint = (endpoint: string) => {
Expand Down Expand Up @@ -45,5 +45,5 @@ export function transformBackendNetworksToChains(networks?: BackendNetwork[]): C
if (!networks) {
return [];
}
return networks.map(network => transformBackendNetworkToChain(network));
return networks.filter(network => IS_DEV || !network.internal).map(network => transformBackendNetworkToChain(network));
}
30 changes: 7 additions & 23 deletions src/components/DappBrowser/BrowserTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import {
USER_AGENT,
USER_AGENT_APPLICATION_NAME,
} from './constants';
import { handleProviderRequestApp } from './handleProviderRequest';
import { getDappHost, handleProviderRequestApp } from './handleProviderRequest';
import { useAnimatedTab } from './hooks/useAnimatedTab';
import { useTabScreenshotProvider } from './hooks/useTabScreenshotProvider';
import { freezeWebsite, getWebsiteMetadata, unfreezeWebsite } from './scripts';
Expand Down Expand Up @@ -254,35 +254,22 @@ const FreezableWebViewComponent = ({
[addRecent, animatedActiveTabIndex, backgroundColor, currentlyOpenTabIds, setLogo, setTitle, tabId, tabUrl]
);

const handleOnLoadStart = useCallback(
(event: { nativeEvent: { url: string | URL; title: string } }) => {
const handleOnLoad = useCallback(
(event: WebViewEvent) => {
if (event.nativeEvent.loading) return;
const { origin } = new URL(event.nativeEvent.url);

if (typeof webViewRef !== 'function' && webViewRef?.current) {
if (!webViewRef?.current) {
return;
}

const messenger = appMessenger(webViewRef.current, tabId, origin);
currentMessengerRef.current = messenger;
}
},
[webViewRef, tabId]
);

const handleOnLoad = useCallback((event: WebViewEvent) => {
if (event.nativeEvent.loading) return;
// placeholder
}, []);

const handleOnLoadEnd = useCallback(() => {
return;
}, []);

const handleOnError = useCallback(() => {
return;
}, []);

const handleShouldStartLoadWithRequest = useCallback(
(request: { url: string }) => {
if (request.url.startsWith('rainbow://wc') || request.url.startsWith('https://rnbwappdotcom.app.link/')) {
Expand Down Expand Up @@ -310,13 +297,13 @@ const FreezableWebViewComponent = ({

const handleNavigationStateChange = useCallback(
(navState: WebViewNavigation) => {
if (navState.url) {
runOnUI(updateTabUrlWorklet)(navState.url, tabId);
if (navState.navigationType !== 'other' || getDappHost(navState.url) === getDappHost(tabUrl)) {
// ⚠️ TODO: Reintegrate canGoBack/canGoForward - we can just set it here now, reliably, because this
// function no longer modifies the same URL state that's passed to the WebView's source prop.
runOnUI(updateTabUrlWorklet)(navState.url, tabId);
}
},
[tabId, updateTabUrlWorklet]
[tabUrl, updateTabUrlWorklet, tabId]
);

const handleOnOpenWindow = useCallback(
Expand Down Expand Up @@ -364,10 +351,7 @@ const FreezableWebViewComponent = ({
<Freeze freeze={!isActiveTab}>
<TabWebView
onContentProcessDidTerminate={handleOnContentProcessDidTerminate}
onError={handleOnError}
onLoad={handleOnLoad}
onLoadStart={handleOnLoadStart}
onLoadEnd={handleOnLoadEnd}
onLoadProgress={handleOnLoadProgress}
onMessage={handleOnMessage}
onNavigationStateChange={handleNavigationStateChange}
Expand Down
2 changes: 0 additions & 2 deletions src/components/DappBrowser/handleProviderRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { Messenger } from '@/browserMessaging/AppMessenger';
import { AddEthereumChainProposedChain, RequestArguments, RequestResponse, handleProviderRequest } from '@rainbow-me/provider';
import * as lang from '@/languages';

import { Provider } from '@ethersproject/providers';

import { getProvider } from '@/handlers/web3';
import { UserRejectedRequestError } from 'viem';
import { logger } from '@/logger';
Expand Down
13 changes: 11 additions & 2 deletions src/model/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1006,13 +1006,22 @@ export const getPrivateKey = async (
lang.t('wallet.authenticate.alert.current_authentication_not_secure_enough')
);
return kc.ErrorType.NotAuthenticated;
case kc.ErrorType.Unavailable:
case kc.ErrorType.Unavailable: {
// Retry with checksummed address if needed
// (This is to mimic the behavior of other wallets like CB)
const checksumAddress = toChecksumAddress(address);
if (address !== checksumAddress) {
return getPrivateKey(checksumAddress);
}
// This means we couldn't find any matches for this key.
logger.error(new RainbowError('KC unavailable for PKEY lookup'), { error });
break;
}
default:
// This is an unknown error
logger.error(new RainbowError('KC unknown error for PKEY lookup'), { error });
if (error) {
logger.error(new RainbowError('KC unknown error for PKEY lookup'), { error });
}
break;
}
return pkey || null;
Expand Down
4 changes: 2 additions & 2 deletions src/utils/ethereumUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ const getDataString = (func: string, arrVals: string[]) => {
*/
function getEtherscanHostForNetwork({ chainId }: { chainId: ChainId }): string {
const base_host = 'etherscan.io';
const blockExplorer = defaultChains[chainId].blockExplorers?.default?.url;
const blockExplorer = defaultChains[chainId]?.blockExplorers?.default?.url;
const network = chainsName[chainId];

if (network && isTestnetChain({ chainId })) {
Expand Down Expand Up @@ -354,7 +354,7 @@ export const getFirstTransactionTimestamp = async (address: EthereumAddress): Pr
};

function getBlockExplorer({ chainId }: { chainId: ChainId }) {
return defaultChains[chainId].blockExplorers?.default.name || 'etherscan';
return defaultChains[chainId]?.blockExplorers?.default.name || 'etherscan';
}

function openAddressInBlockExplorer({ address, chainId }: { address: EthereumAddress; chainId: ChainId }) {
Expand Down

0 comments on commit 529e513

Please sign in to comment.