8000 atomic swaps [APP-2658] by derHowie · Pull Request #6695 · rainbow-me/rainbow · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

atomic swaps [APP-2658] #6695

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

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2666,7 +2666,7 @@ SPEC CHECKSUMS:
ToolTipMenu: 8ac61aded0fbc4acfe7e84a7d0c9479d15a9a382
TurboHaptics: 7e828d882aa98ccc6f68818b0c1fa2cf3c596a60
VisionCamera: 168f46071274ce58c50adef4c82ae3367b2ba2a6
Yoga: 04f1db30bb810187397fa4c37dd1868a27af229c
Yoga: 88480008ccacea6301ff7bf58726e27a72931c8d

PODFILE CHECKSUM: 98c3fc206d7041ac7388693bb0753109d1884b57

Expand Down
11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@
"@notifee/react-native": "7.8.2",
"@rainbow-me/provider": "0.1.2",
"@rainbow-me/react-native-animated-number": "0.0.2",
"@rainbow-me/swaps": "0.36.0",
"@rainbow-me/swaps": "file:vendor/rainbow-me-swaps-0.36.0.tgz",
"@rainbow-me/token-launcher": "0.1.0",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-camera-roll/camera-roll": "7.7.0",
Expand Down Expand Up @@ -204,6 +204,7 @@
"qrcode": "1.4.4",
"qs": "6.9.7",
"querystring-es3": "0.2.1",
"rainbow-delegation": "file:vendor/rainbow-delegation-v1.0.0.tgz",
"react": "18.2.0",
"react-coin-icon": "rainbow-me/react-coin-icon#06464588a3d986f6ef3a7d7341b2d7ea0c5ac50b",
"react-fast-compare": "3.2.2",
Expand Down Expand Up @@ -303,7 +304,7 @@
"use-debounce": "10.0.0",
"use-deep-compare": "1.3.0",
"use-memo-one": "1.1.1",
"viem": "2.21.54",
"viem": "2.31.0",
"vm-browserify": "0.0.4",
"w2t": "3.0.2",
"zeego": "1.10.0",
Expand Down Expand Up @@ -381,7 +382,11 @@
"packageManager": "yarn@4.2.2",
"resolutions": {
"react-native/react-devtools-core": "4.28.4",
"cross-fetch": "3.1.5"
"cross-fetch": "3.1.5",
"@rainbow-me/rainbow-delegation/viem": "2.31.0",
"viem": "2.31.0",
"@rainbow-me/provider/viem": "2.31.0",
"mipd/viem": "2.31.0"
},
"react-native": {
"@tanstack/query-async-storage-persister": "@tanstack/query-async-storage-persister/build/esm/index",
Expand Down
36 changes: 22 additions & 14 deletions src/__swaps__/screens/Swap/hooks/useSwapEstimatedGasLimit.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { CrosschainQuote, Quote, QuoteError, SwapType } from '@rainbow-me/swaps';
import { useQuery } from '@tanstack/react-query';

import { ParsedSearchAsset } from '@/__swaps__/types/assets';
import { ParsedAsset, ParsedSearchAsset } from '@/__swaps__/types/assets';
import { ChainId } from '@/state/backendNetworks/types';
import { estimateUnlockAndCrosschainSwap } from '@/raps/actions/crosschainSwap';
import { estimateUnlockAndSwap } from '@/raps/actions/swap';
import { QueryConfigWithSelect, QueryFunctionArgs, QueryFunctionResult, createQueryKey } from '@/react-query';
import { gasUnits } from '@/references/gasUnits';
import { estimateDelegatedApproveAndSwapGasLimit, getShouldDelegate } from '@/delegateActions';

// ///////////////////////////////////////////////
// Query Types
Expand Down Expand Up @@ -39,19 +40,26 @@ async function estimateSwapGasLimitQueryFunction({
};
}

const gasLimit = await (quote.swapType === SwapType.crossChain
? estimateUnlockAndCrosschainSwap({
chainId,
quote: quote as CrosschainQuote,
sellAmount: quote.sellAmount.toString(),
assetToSell,
})
: estimateUnlockAndSwap({
chainId,
quote,
sellAmount: quote.sellAmount.toString(),
assetToSell,
}));
let gasLimit: string | null;

const shouldDelegate = await getShouldDelegate(chainId, quote as Quote | CrosschainQuote, assetToSell as ParsedAsset);
if (shouldDelegate) {
gasLimit = BigInt((await estimateDelegatedApproveAndSwapGasLimit(quote as Quote | CrosschainQuote)) || '0').toString();
} else {
gasLimit = await (quote.swapType === SwapType.crossChain
? estimateUnlockAndCrosschainSwap({
chainId,
quote: quote as CrosschainQuote,
sellAmount: quote.sellAmount.toString(),
assetToSell,
})
: estimateUnlockAndSwap({
chainId,
quote,
sellAmount: quote.sellAmount.toString(),
assetToSell,
}));
}

if (!gasLimit) {
return {
Expand Down
137 changes: 88 additions & 49 deletions src/__swaps__/screens/Swap/providers/swap-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ import { SwapAssetType, InputKeys } from '@/__swaps__/types/swap';
import { clamp, getDefaultSlippageWorklet, parseAssetAndExtend, trimTrailingZeros } from '@/__swaps__/utils/swaps';
import { analytics } from '@/analytics';
import { LegacyTransactionGasParamAmounts, TransactionGasParamAmounts } from '@/entities';
import { getProvider } from '@/handlers/web3';
import { getProvider, getProviderViem } from '@/handlers/web3';
import { WrappedAlert as Alert } from '@/helpers/alert';
import { useAnimatedInterval } from '@/hooks/reanimated/useAnimatedInterval';
import * as i18n from '@/languages';
import { logger, RainbowError } from '@/logger';
import { loadWallet } from '@/model/wallet';
import { loadWallet, loadWalletViem } from '@/model/wallet';
import { Navigation } from '@/navigation';
import Routes from '@/navigation/routesNames';
import { walletExecuteRap } from '@/raps/execute';
Expand All @@ -59,11 +59,13 @@ import { useConnectedToAnvilStore } from '@/state/connectedToAnvil';
import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks';
import { userAssetsStoreManager } from '@/state/assets/userAssetsStoreManager';
import { getSwapsNavigationParams } from '../navigateToSwaps';
import { LedgerSigner } from '@/handlers/LedgerSigner';
import showWalletErrorAlert from '@/helpers/support';
import { getRemoteConfig } from '@/model/remoteConfig';
import { getRemoteConfig, useRemoteConfig } from '@/model/remoteConfig';
import { getInputValuesForSliderPositionWorklet, updateInputValuesAfterFlip } from '@/__swaps__/utils/flipAssets';
import { trackSwapEvent } from '@/__swaps__/utils/trackSwapEvent';
import { useIsHardwareWallet } from '@/state/wallets/walletsStore';
import { getShouldDelegate, walletExecuteWithDelegate } from '@/delegateActions';
import { ATOMIC_SWAPS, useExperimentalFlag } from '@/config';

const swapping = i18n.t(i18n.l.swap.actions.swapping);
const holdToSwap = i18n.t(i18n.l.swap.actions.hold_to_swap);
Expand Down Expand Up @@ -175,6 +177,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
initialValues: getSwapsNavigationParams(),
nativeChainAssets: useBackendNetworksStore.getState().getChainsNativeAsset(),
}));
const isHardwareWallet = useIsHardwareWallet();

const inputSearchRef = useAnimatedRef<TextInput>();
const outputSearchRef = useAnimatedRef<TextInput>();
Expand Down Expand Up @@ -243,6 +246,9 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
slippage,
});

const atomicSwapsEnabled = useExperimentalFlag(ATOMIC_SWAPS);
const config = useRemoteConfig();

const { degenMode } = SwapSettings;

const getNonceAndPerformSwap = async ({
Expand All @@ -253,48 +259,31 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
parameters: Omit<RapSwapActionParameters<typeof type>, 'gasParams' | 'gasFeeParamsBySpeed' | 'selectedGasFee'>;
}) => {
try {
const NotificationManager = IS_IOS ? NativeModules.NotificationManager : null;
NotificationManager?.postNotification('rapInProgress');
const degenMode = swapsStore.getState().degenMode;
// const shouldDelegate =
// (atomicSwapsEnabled || config.atomic_swaps_enabled) &&
// (await getShouldDelegate(parameters.chainId, parameters.quote as Quote | CrosschainQuote, parameters.assetToSell));
const shouldDelegate = await getShouldDelegate(
parameters.chainId,
parameters.quote as Quote | CrosschainQuote,
parameters.assetToSell
);
const selectedGas = getSelectedGas(parameters.chainId);

const provider = getProvider({ chainId: parameters.chainId });
const connectedToAnvil = useConnectedToAnvilStore.getState().connectedToAnvil;
const chainId = connectedToAnvil ? ChainId.anvil : parameters.chainId;
const nonce = await getNextNonce({ address: parameters.quote.from, chainId });

const NotificationManager = IS_IOS ? NativeModules.NotificationManager : null;

const selectedGas = getSelectedGas(parameters.chainId);
if (!selectedGas) {
isSwapping.value = false;
Alert.alert(i18n.t(i18n.l.gas.unable_to_determine_selected_gas));
return;
}

const degenMode = swapsStore.getState().degenMode;

const wallet = await performanceTracking.getState().executeFn({
fn: loadWallet,
screen: Screens.SWAPS,
operation: TimeToSignOperation.KeychainRead,
metadata: { degenMode },
})({
address: parameters.quote.from,
showErrorIfNotLoaded: false,
provider,
timeTracking: {
screen: Screens.SWAPS,
operation: TimeToSignOperation.Authentication,
metadata: { degenMode },
},
});
const isHardwareWallet = wallet instanceof LedgerSigner;

if (!wallet) {
isSwapping.value = false;
triggerHaptics('notificationError');
showWalletErrorAlert();
return;
}

const gasFeeParamsBySpeed = getGasSettingsBySpeed(parameters.chainId);
let gasParams: TransactionGasParamAmounts | LegacyTransactionGasParamAmounts;

if (selectedGas.isEIP1559) {
gasParams = {
maxFeePerGas: sumWorklet(selectedGas.maxBaseFee, selectedGas.maxPriorityFee),
Expand All @@ -304,21 +293,71 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {
gasParams = { gasPrice: selectedGas.gasPrice };
}

const chainId = connectedToAnvil ? ChainId.anvil : parameters.chainId;
const nonce = await getNextNonce({ address: parameters.quote.from, chainId });
NotificationManager?.postNotification('rapInProgress');

const { errorMessage } = await performanceTracking.getState().executeFn({
fn: walletExecuteRap,
screen: Screens.SWAPS,
operation: TimeToSignOperation.SignTransaction,
metadata: { degenMode },
})(wallet, type, {
...parameters,
nonce,
chainId,
gasParams,
gasFeeParamsBySpeed,
});
let errorMessage: string | null;

if (shouldDelegate) {
const publicClient = getProviderViem({ chainId: parameters.chainId });
const walletViem = await loadWalletViem({
address: parameters.quote.from as `0x${string}`,
publicClient: publicClient,
timeTracking: {
screen: Screens.SWAPS,
operation: TimeToSignOperation.Authentication,
metadata: { degenMode },
},
});
if (!walletViem) {
isSwapping.value = false;
triggerHaptics('notificationError');
showWalletErrorAlert();
return;
}
const { error } = await walletExecuteWithDelegate({
walletClient: walletViem,
publicClient,
type,
parameters: { ...parameters, gasParams },
});
errorMessage = error;
} else {
const provider = getProvider({ chainId: parameters.chainId });
const wallet = await performanceTracking.getState().executeFn({
fn: loadWallet,
screen: Screens.SWAPS,
operation: TimeToSignOperation.KeychainRead,
metadata: { degenMode },
})({
address: parameters.quote.from,
showErrorIfNotLoaded: false,
provider,
timeTracking: {
screen: Screens.SWAPS,
operation: TimeToSignOperation.Authentication,
metadata: { degenMode },
},
});
if (!wallet) {
isSwapping.value = false;
triggerHaptics('notificationError');
showWalletErrorAlert();
return;
}
const { errorMessage: errorMessageFromWallet } = await performanceTracking.getState().executeFn({
fn: walletExecuteRap,
screen: Screens.SWAPS,
operation: TimeToSignOperation.SignTransaction,
metadata: { degenMode },
})(wallet, type, {
...parameters,
nonce,
chainId,
gasParams,
gasFeeParamsBySpeed,
});
errorMessage = errorMessageFromWallet;
}

isSwapping.value = false;

Expand Down
2 changes: 2 additions & 0 deletions src/config/experimental.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export const NEW_DISCOVER_CARDS = 'New Discover Cards';
export const RAINBOW_TRENDING_TOKENS_LIST = 'Rainbow Trending Tokens List';
export const PRINCE_OF_THE_HILL = 'Prince of the Hill';
export const LAZY_TABS = 'Lazy Tabs';
export const ATOMIC_SWAPS = 'Atomic Swaps';

/**
* A developer setting that pushes log lines to an array in-memory so that
Expand Down Expand Up @@ -81,6 +82,7 @@ const config = {
[RAINBOW_TRENDING_TOKENS_LIST]: { settings: true, value: false },
[PRINCE_OF_THE_HILL]: { settings: true, value: false },
[LAZY_TABS]: { needsRestart: true, settings: true, value: false },
[ATOMIC_SWAPS]: { settings: true, value: false },
} as const;

/** This flag is not reactive. We use this in a static context. */
Expand Down
Loading
Loading
0