Skip to content

Commit

Permalink
chore: use new fields from swap sdk and remove extraneous code (#6171)
Browse files Browse the repository at this point in the history
* chore: update swaps

* chore: replace extraneous crosschain logic with needsAllowance field

* chore: get rid of all WRAPPED_ASSET references and use quote swap type

* chore: remove swapType as a param to get quotes

* chore: replace swap unlock logic with needsAllowance field

* chore: code review changes
  • Loading branch information
welps authored Oct 9, 2024
1 parent 25f6904 commit 86e3e6d
Show file tree
Hide file tree
Showing 13 changed files with 48 additions and 215 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
"@notifee/react-native": "7.8.2",
"@rainbow-me/provider": "0.1.1",
"@rainbow-me/react-native-animated-number": "0.0.2",
"@rainbow-me/swaps": "0.27.0",
"@rainbow-me/swaps": "0.28.0",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-camera-roll/camera-roll": "7.7.0",
"@react-native-clipboard/clipboard": "1.13.2",
Expand Down
6 changes: 4 additions & 2 deletions src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {
} from '@/resources/assets/externalAssetsQuery';
import { triggerHapticFeedback } from '@/screens/points/constants';
import { swapsStore } from '@/state/swaps/swapsStore';
import { CrosschainQuote, Quote, QuoteError, SwapType, getCrosschainQuote, getQuote } from '@rainbow-me/swaps';
import { CrosschainQuote, Quote, QuoteError, getCrosschainQuote, getQuote } from '@rainbow-me/swaps';
import { useCallback } from 'react';
import { SharedValue, runOnJS, runOnUI, useAnimatedReaction, useDerivedValue, useSharedValue, withSpring } from 'react-native-reanimated';
import { useDebouncedCallback } from 'use-debounce';
Expand Down Expand Up @@ -445,6 +445,8 @@ export function useSwapInputsController({
outputAsset: internalSelectedOutputAsset.value,
});

const isCrosschainSwap = internalSelectedInputAsset.value?.chainId !== internalSelectedOutputAsset.value?.chainId;

logger.debug(`[useSwapInputsController]: quote params`, {
data: params,
});
Expand All @@ -464,7 +466,7 @@ export function useSwapInputsController({

try {
const [quoteResponse, fetchedPrices] = await Promise.all([
params.swapType === SwapType.crossChain ? getCrosschainQuote(params) : getQuote(params),
isCrosschainSwap ? getCrosschainQuote(params) : getQuote(params),
fetchAssetPrices({
inputAsset: internalSelectedInputAsset.value,
outputAsset: internalSelectedOutputAsset.value,
Expand Down
26 changes: 7 additions & 19 deletions src/__swaps__/screens/Swap/providers/swap-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// @refresh
import React, { ReactNode, createContext, useCallback, useContext, useEffect, useRef } from 'react';
import React, { createContext, ReactNode, useCallback, useContext, useEffect, useRef } from 'react';
import { InteractionManager, NativeModules, StyleProp, TextInput, TextStyle } from 'react-native';
import {
AnimatedRef,
DerivedValue,
SharedValue,
runOnJS,
runOnUI,
SharedValue,
useAnimatedReaction,
useAnimatedRef,
useAnimatedStyle,
Expand All @@ -25,16 +25,16 @@ import { SwapWarningType, useSwapWarning } from '@/__swaps__/screens/Swap/hooks/
import { userAssetsQueryKey as swapsUserAssetsQueryKey } from '@/__swaps__/screens/Swap/resources/assets/userAssets';
import { AddressOrEth, ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from '@/__swaps__/types/assets';
import { ChainId } from '@/chains/types';
import { SwapAssetType, inputKeys } from '@/__swaps__/types/swap';
import { getDefaultSlippageWorklet, isUnwrapEthWorklet, isWrapEthWorklet, parseAssetAndExtend } from '@/__swaps__/utils/swaps';
import { inputKeys, SwapAssetType } from '@/__swaps__/types/swap';
import { getDefaultSlippageWorklet, parseAssetAndExtend } from '@/__swaps__/utils/swaps';
import { analyticsV2 } from '@/analytics';
import { LegacyTransactionGasParamAmounts, TransactionGasParamAmounts } from '@/entities';
import { getFlashbotsProvider, getProvider } from '@/handlers/web3';
import { WrappedAlert as Alert } from '@/helpers/alert';
import { useAccountSettings } from '@/hooks';
import { useAnimatedInterval } from '@/hooks/reanimated/useAnimatedInterval';
import * as i18n from '@/languages';
import { RainbowError, logger } from '@/logger';
import { logger, RainbowError } from '@/logger';
import { loadWallet } from '@/model/wallet';
import { Navigation } from '@/navigation';
import Routes from '@/navigation/routesNames';
Expand All @@ -45,7 +45,7 @@ import { userAssetsQueryKey } from '@/resources/assets/UserAssetsQuery';
import { userAssetsStore } from '@/state/assets/userAssets';
import { swapsStore } from '@/state/swaps/swapsStore';
import { haptics } from '@/utils';
import { CrosschainQuote, Quote, QuoteError } from '@rainbow-me/swaps';
import { CrosschainQuote, Quote, QuoteError, SwapType } from '@rainbow-me/swaps';

import { IS_IOS } from '@/env';
import { Address } from 'viem';
Expand Down Expand Up @@ -397,17 +397,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
const quoteData = q as QuoteTypeMap[typeof type];
const flashbots = (SwapSettings.flashbots.value && !!supportedFlashbotsChainIds.includes(inputAsset.chainId)) ?? false;

const isNativeWrapOrUnwrap =
isWrapEthWorklet({
buyTokenAddress: quoteData.buyTokenAddress,
sellTokenAddress: quoteData.sellTokenAddress,
chainId: inputAsset.chainId,
}) ||
isUnwrapEthWorklet({
buyTokenAddress: quoteData.buyTokenAddress,
sellTokenAddress: quoteData.sellTokenAddress,
chainId: inputAsset.chainId,
});
const isNativeWrapOrUnwrap = quoteData.swapType === SwapType.wrap || quoteData.swapType === SwapType.unwrap;

// Do not deleeeet the comment below 😤
// About to get quote
Expand All @@ -422,8 +412,6 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
buyAmountDisplay: isNativeWrapOrUnwrap ? quoteData.buyAmount : quoteData.buyAmountDisplay,
sellAmountDisplay: isNativeWrapOrUnwrap ? quoteData.sellAmount : quoteData.sellAmountDisplay,
feeInEth: isNativeWrapOrUnwrap ? '0' : quoteData.feeInEth,
fromChainId: inputAsset.chainId,
toChainId: outputAsset.chainId,
},
flashbots,
};
Expand Down
44 changes: 2 additions & 42 deletions src/__swaps__/utils/swaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,17 @@ import {
STABLECOIN_MINIMUM_SIGNIFICANT_DECIMALS,
} from '@/__swaps__/screens/Swap/constants';
import { ChainId } from '@/chains/types';
import { isLowerCaseMatchWorklet } from '@/__swaps__/utils/strings';
import { globalColors } from '@/design-system';
import { ForegroundColor, palettes } from '@/design-system/color/palettes';
import { TokenColors } from '@/graphql/__generated__/metadata';
import * as i18n from '@/languages';
import { RainbowConfig } from '@/model/remoteConfig';
import store from '@/redux/store';
import { ETH_ADDRESS, supportedNativeCurrencies } from '@/references';
import { supportedNativeCurrencies } from '@/references';
import { userAssetsStore } from '@/state/assets/userAssets';
import { colors } from '@/styles';
import { BigNumberish } from '@ethersproject/bignumber';
import { CrosschainQuote, ETH_ADDRESS as ETH_ADDRESS_AGGREGATOR, Quote, QuoteParams, SwapType, WRAPPED_ASSET } from '@rainbow-me/swaps';
import { CrosschainQuote, ETH_ADDRESS as ETH_ADDRESS_AGGREGATOR, Quote, QuoteParams } from '@rainbow-me/swaps';
import { swapsStore } from '../../state/swaps/swapsStore';
import {
divWorklet,
Expand Down Expand Up @@ -497,44 +496,6 @@ export const getCrossChainTimeEstimateWorklet = ({
};
};

export const isUnwrapEthWorklet = ({
buyTokenAddress,
chainId,
sellTokenAddress,
}: {
chainId: ChainId;
sellTokenAddress: string;
buyTokenAddress: string;
}) => {
'worklet';
if (chainId === ChainId.mainnet) {
return isLowerCaseMatchWorklet(sellTokenAddress, WRAPPED_ASSET[chainId]) && isLowerCaseMatchWorklet(buyTokenAddress, ETH_ADDRESS);
} else {
return (
isLowerCaseMatchWorklet(sellTokenAddress, WRAPPED_ASSET[chainId]) && isLowerCaseMatchWorklet(buyTokenAddress, ETH_ADDRESS_AGGREGATOR)
);
}
};

export const isWrapEthWorklet = ({
buyTokenAddress,
chainId,
sellTokenAddress,
}: {
chainId: ChainId;
sellTokenAddress: string;
buyTokenAddress: string;
}) => {
'worklet';
if (chainId === ChainId.mainnet) {
return isLowerCaseMatchWorklet(sellTokenAddress, ETH_ADDRESS) && isLowerCaseMatchWorklet(buyTokenAddress, WRAPPED_ASSET[chainId]);
} else {
return (
isLowerCaseMatchWorklet(sellTokenAddress, ETH_ADDRESS_AGGREGATOR) && isLowerCaseMatchWorklet(buyTokenAddress, WRAPPED_ASSET[chainId])
);
}
};

export const priceForAsset = ({
asset,
assetType,
Expand Down Expand Up @@ -653,7 +614,6 @@ export const buildQuoteParams = ({
: undefined,
slippage: Number(slippage),
refuel: false,
swapType: isCrosschainSwap ? SwapType.crossChain : SwapType.normal,
toChainId: isCrosschainSwap ? outputAsset.chainId : inputAsset.chainId,
currency: store.getState().settings.nativeCurrency,
};
Expand Down
48 changes: 4 additions & 44 deletions src/handlers/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import { Block, StaticJsonRpcProvider } from '@ethersproject/providers';
import {
ALLOWS_PERMIT,
CrosschainQuote,
ETH_ADDRESS as ETH_ADDRESS_AGGREGATORS,
getQuoteExecutionDetails,
getRainbowRouterContractAddress,
getWrappedAssetMethod,
PermitSupportedTokenList,
Quote,
getRainbowRouterContractAddress,
WRAPPED_ASSET,
SwapType,
} from '@rainbow-me/swaps';
import { Contract } from '@ethersproject/contracts';
import { MaxUint256 } from '@ethersproject/constants';
Expand Down Expand Up @@ -195,36 +194,6 @@ export const getSwapGasLimitWithFakeApproval = async (
return getDefaultGasLimitForTrade(tradeDetails, chainId);
};

export const isUnwrapNative = ({
buyTokenAddress,
chainId,
sellTokenAddress,
}: {
chainId: ChainId;
sellTokenAddress: string;
buyTokenAddress: string;
}) => {
return (
sellTokenAddress.toLowerCase() === WRAPPED_ASSET[chainId]?.toLowerCase() &&
buyTokenAddress.toLowerCase() === ETH_ADDRESS_AGGREGATORS.toLowerCase()
);
};

export const isWrapNative = ({
buyTokenAddress,
chainId,
sellTokenAddress,
}: {
chainId: ChainId;
sellTokenAddress: string;
buyTokenAddress: string;
}) => {
return (
sellTokenAddress.toLowerCase() === ETH_ADDRESS_AGGREGATORS.toLowerCase() &&
buyTokenAddress.toLowerCase() === WRAPPED_ASSET[chainId]?.toLowerCase()
);
};

export const estimateSwapGasLimit = async ({
chainId,
requiresApprove,
Expand All @@ -238,17 +207,8 @@ export const estimateSwapGasLimit = async ({
if (!provider || !tradeDetails) {
return ethereumUtils.getBasicSwapGasLimit(Number(chainId));
}
const { sellTokenAddress, buyTokenAddress } = tradeDetails;
const isWrapNativeAsset = isWrapNative({
buyTokenAddress,
sellTokenAddress,
chainId,
});
const isUnwrapNativeAsset = isUnwrapNative({
buyTokenAddress,
sellTokenAddress,
chainId,
});
const isWrapNativeAsset = tradeDetails.swapType === SwapType.wrap;
const isUnwrapNativeAsset = tradeDetails.swapType === SwapType.unwrap;

// Wrap / Unwrap Eth
if (isWrapNativeAsset || isUnwrapNativeAsset) {
Expand Down
18 changes: 3 additions & 15 deletions src/hooks/usePriceImpactDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ import {
subtract,
} from '@/helpers/utilities';

import { CrosschainQuote, Quote } from '@rainbow-me/swaps';
import { CrosschainQuote, Quote, SwapType } from '@rainbow-me/swaps';
import { useNativeAsset } from '@/utils/ethereumUtils';
import { isUnwrapNative, isWrapNative } from '@/handlers/swap';
import { ChainId } from '@/chains/types';

export enum SwapPriceImpactType {
Expand All @@ -37,26 +36,15 @@ export default function usePriceImpactDetails(
const { colors } = useTheme();

const sellChainId = (
(tradeDetails as CrosschainQuote)?.fromChainId ? (tradeDetails as CrosschainQuote)?.fromChainId : chainId
(tradeDetails as CrosschainQuote)?.sellTokenAsset?.chainId ? (tradeDetails as CrosschainQuote)?.sellTokenAsset?.chainId : chainId
) as ChainId;
const buyChainId = (outputCurrency?.chainId || chainId) as ChainId;
const sellNativeAsset = useNativeAsset({ chainId: sellChainId });
const buyNativeAsset = useNativeAsset({ chainId: buyChainId });

const isWrapOrUnwrap = useMemo(() => {
if (!tradeDetails) return false;
return (
isWrapNative({
buyTokenAddress: tradeDetails?.buyTokenAddress,
sellTokenAddress: tradeDetails?.sellTokenAddress,
chainId: buyChainId,
}) ||
isUnwrapNative({
buyTokenAddress: tradeDetails?.buyTokenAddress,
sellTokenAddress: tradeDetails?.sellTokenAddress,
chainId: buyChainId,
})
);
return tradeDetails.swapType === SwapType.wrap || tradeDetails.swapType === SwapType.unwrap;
}, [buyChainId, tradeDetails]);

const inputNativeAmount = useMemo(() => {
Expand Down
2 changes: 0 additions & 2 deletions src/hooks/useSwapDerivedOutputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ const getInputAmount = async (
// Add 5% slippage for testing to prevent flaky tests
slippage: IS_TESTING !== 'true' ? slippage : 5,
...(quoteSource ? { source } : {}),
swapType: SwapType.normal,
currency: store.getState().settings.nativeCurrency,
};

Expand Down Expand Up @@ -192,7 +191,6 @@ const getOutputAmount = async (
// Add 5% slippage for testing to prevent flaky tests
slippage: IS_TESTING !== 'true' ? slippage : 5,
...(quoteSource ? { source } : {}),
swapType: isCrosschainSwap ? SwapType.crossChain : SwapType.normal,
toChainId: Number(outputChainId),
refuel,
currency: store.getState().settings.nativeCurrency,
Expand Down
2 changes: 0 additions & 2 deletions src/raps/actions/claimBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
buyTokenAddress: AddressZero,
sellAmount: sellAmount,
slippage: 2,
swapType: SwapType.crossChain,
currency,
});

Expand Down Expand Up @@ -99,7 +98,6 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
buyTokenAddress: AddressZero,
sellAmount: maxBridgeableAmount,
slippage: 2,
swapType: SwapType.crossChain,
currency,
});

Expand Down
16 changes: 4 additions & 12 deletions src/raps/actions/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import { StaticJsonRpcProvider } from '@ethersproject/providers';
import { Transaction } from '@ethersproject/transactions';
import {
CrosschainQuote,
ETH_ADDRESS as ETH_ADDRESS_AGGREGATORS,
Quote,
ChainId as SwapChainId,
SwapType,
WRAPPED_ASSET,
fillQuote,
getQuoteExecutionDetails,
getRainbowRouterContractAddress,
Expand All @@ -23,8 +21,6 @@ import { ChainId } from '@/chains/types';
import { NewTransaction } from '@/entities/transactions';
import { TxHash } from '@/resources/transactions/types';
import { add } from '@/helpers/utilities';
import { isLowerCaseMatch } from '@/__swaps__/utils/strings';
import { isUnwrapNative, isWrapNative } from '@/handlers/swap';
import { addNewTransaction } from '@/state/pendingTransactions';
import { RainbowError, logger } from '@/logger';

Expand Down Expand Up @@ -67,12 +63,8 @@ export const estimateSwapGasLimit = async ({
return gasUnits.basic_swap[chainId];
}

const { sellTokenAddress, buyTokenAddress } = quote;
const isWrapNativeAsset =
isLowerCaseMatch(sellTokenAddress, ETH_ADDRESS_AGGREGATORS) && isLowerCaseMatch(buyTokenAddress, WRAPPED_ASSET[chainId]);

const isUnwrapNativeAsset =
isLowerCaseMatch(sellTokenAddress, WRAPPED_ASSET[chainId]) && isLowerCaseMatch(buyTokenAddress, ETH_ADDRESS_AGGREGATORS);
const isWrapNativeAsset = quote.swapType === SwapType.wrap;
const isUnwrapNativeAsset = quote.swapType === SwapType.unwrap;

// Wrap / Unwrap Eth
if (isWrapNativeAsset || isUnwrapNativeAsset) {
Expand Down Expand Up @@ -231,10 +223,10 @@ export const executeSwap = async ({
};

// Wrap Eth
if (isWrapNative({ buyTokenAddress, sellTokenAddress, chainId })) {
if (quote.swapType === SwapType.wrap) {
return wrapNativeAsset(quote.buyAmount, wallet, chainId as unknown as SwapChainId, transactionParams);
// Unwrap Weth
} else if (isUnwrapNative({ buyTokenAddress, sellTokenAddress, chainId })) {
} else if (quote.swapType === SwapType.unwrap) {
return unwrapNativeAsset(quote.sellAmount, wallet, chainId as unknown as SwapChainId, transactionParams);
// Swap
} else {
Expand Down
Loading

0 comments on commit 86e3e6d

Please sign in to comment.