Skip to content

Commit

Permalink
wc: generalize tx request sheet (#5471)
Browse files Browse the repository at this point in the history
* save

* bulk of the work

* clean up

* clean up and add browser request handler

* bug

* add initial connection sheet
  • Loading branch information
skylarbarrera authored Mar 19, 2024
1 parent 0e50972 commit 0c00f6a
Show file tree
Hide file tree
Showing 9 changed files with 310 additions and 267 deletions.
10 changes: 3 additions & 7 deletions src/components/coin-row/RequestCoinRow.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ import { RowWithMargins } from '../layout';
import { Emoji, Text } from '../text';
import CoinName from './CoinName';
import CoinRow from './CoinRow';
import { useNavigation } from '@/navigation';
import { removeRequest } from '@/redux/requests';
import Routes from '@/navigation/routesNames';
import styled from '@/styled-thing';
import { handleWalletConnectRequest } from '@/utils/requestNavigationHandlers';

const getPercentageOfTimeElapsed = (startDate, endDate) => {
const originalDifference = differenceInMinutes(endDate, startDate);
Expand Down Expand Up @@ -50,7 +49,6 @@ const TopRow = ({ expirationColor, expiresAt }) => {
const RequestCoinRow = ({ item, ...props }) => {
const buttonRef = useRef();
const dispatch = useDispatch();
const { navigate } = useNavigation();
const [expiresAt, setExpiresAt] = useState(null);
const [expirationColor, setExpirationColor] = useState(null);
const [percentElapsed, setPercentElapsed] = useState(null);
Expand All @@ -74,10 +72,8 @@ const RequestCoinRow = ({ item, ...props }) => {
}, [dispatch, expiresAt, item.requestId]);

const handlePressOpen = useCallback(() => {
navigate(Routes.CONFIRM_REQUEST, {
transactionDetails: item,
});
}, [item, navigate]);
handleWalletConnectRequest(item);
}, [item]);

useEffect(() => {
handleExpiredRequests();
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/buildTransactionsSectionsSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { FastTransactionCoinRow, RequestCoinRow } from '../components/coin-row';
import { thisMonthTimestamp, thisYearTimestamp, todayTimestamp, yesterdayTimestamp } from './transactions';
import { NativeCurrencyKey, RainbowTransaction, TransactionStatusTypes } from '@/entities';
import * as i18n from '@/languages';
import { RequestData } from '@/redux/requests';
import { WalletconnectRequestData } from '@/redux/requests';
import { ThemeContextProps } from '@/theme';
import { Contact } from '@/redux/contacts';
import { TransactionStatus } from '@/resources/transactions/types';
Expand Down Expand Up @@ -63,7 +63,7 @@ export const buildTransactionsSections = ({
}: {
accountAddress: string;
contacts: { [address: string]: Contact };
requests: RequestData[];
requests: WalletconnectRequestData[];
theme: ThemeContextProps;
transactions: RainbowTransaction[];
nativeCurrency: NativeCurrencyKey;
Expand Down
7 changes: 4 additions & 3 deletions src/navigation/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { HARDWARE_WALLET_TX_NAVIGATOR_SHEET_HEIGHT } from '@/navigation/Hardware
import { StackNavigationOptions } from '@react-navigation/stack';
import { PartialNavigatorConfigOptions } from '@/navigation/types';
import { BottomSheetNavigationOptions } from '@/navigation/bottom-sheet/types';
import { SignTransactionSheetRouteProp } from '@/screens/SignTransactionSheet';

export const sharedCoolModalTopOffset = safeAreaInsetValues.top;

Expand Down Expand Up @@ -228,10 +229,10 @@ export const swapConfig = {
};

export const signTransactionSheetConfig = {
options: ({ route: { params = {} } }) => ({
options: ({ route }: { route: SignTransactionSheetRouteProp }) => ({
...buildCoolModalConfig({
...params,
backgroundOpacity: 1,
...route.params,
backgroundOpacity: route?.params?.requestType === 'walletconnect' ? 1 : 0.3,
cornerRadius: 0,
springDamping: 1,
topOffset: 0,
Expand Down
47 changes: 21 additions & 26 deletions src/redux/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { omitFlatten } from '@/helpers/utilities';
import { getRequestDisplayDetails } from '@/parsers';
import { ethereumUtils } from '@/utils';
import logger from '@/utils/logger';
import { Network } from '@/networks/types';

// -- Constants --------------------------------------- //

Expand All @@ -18,10 +19,19 @@ const EXPIRATION_THRESHOLD_IN_MS = 1000 * 60 * 60;

// -- Actions ----------------------------------------- //

export interface RequestData {
dappName: string;
imageUrl: string | undefined;
address: string;
network: Network;
dappUrl: string;
payload: any;
displayDetails: RequestDisplayDetails | null | Record<string, never>;
}
/**
* A request stored in state.
*/
export interface RequestData {
export interface WalletconnectRequestData extends RequestData {
/**
* The WalletConnect client ID for the request.
*/
Expand All @@ -37,36 +47,16 @@ export interface RequestData {
*/
requestId: number;

/**
* The name of the dapp the user is connecting to.
*/
dappName: string;

/**
* The URL scheme to use for re-opening the dapp, or null.
*/
dappScheme: string | null;

/**
* The URL for the dapp.
*/
dappUrl: string;

/**
* The display details loaded for the request.
*/
displayDetails: RequestDisplayDetails | null | Record<string, never>;

/**
* The image URL for the dapp, or undefined.
*/
imageUrl: string | undefined;

/**
* The payload for the request.
*/
payload: any;

/**
* Adds additional data to the request and serves as a notice that this
* request originated from a WC v2 session
Expand All @@ -75,7 +65,7 @@ export interface RequestData {
sessionRequestEvent: SignClientTypes.EventArguments['session_request'];
address: string;
chainId: number;
onComplete(type: string): void;
onComplete?: (type: string) => void;
};
}

Expand All @@ -99,11 +89,11 @@ interface RequestDisplayDetails {
*/
interface RequestsState {
/**
* Current requests, as an object mapping request IDs to `RequestData`
* Current requests, as an object mapping request IDs to `WalletconnectRequestData`
* objects.
*/
requests: {
[requestId: number]: RequestData;
[requestId: number]: WalletconnectRequestData;
};
}

Expand Down Expand Up @@ -172,6 +162,9 @@ export const addRequestToApprove =
const walletConnector = walletConnectors[peerId];
// @ts-expect-error "_chainId" is private.
const chainId = walletConnector._chainId;
const requestNetwork = ethereumUtils.getNetworkFromChainId(Number(chainId));
// @ts-expect-error "_accounts" is private.
const address = walletConnector._accounts[0];
const dappNetwork = ethereumUtils.getNetworkFromChainId(Number(chainId));
const displayDetails = getRequestDisplayDetails(payload, nativeCurrency, dappNetwork);
const oneHourAgoTs = Date.now() - EXPIRATION_THRESHOLD_IN_MS;
Expand All @@ -189,7 +182,9 @@ export const addRequestToApprove =
const dappUrl = peerMeta?.url || 'Unknown Url';
const dappScheme = peerMeta?.scheme || null;

const request: RequestData = {
const request: WalletconnectRequestData = {
address,
network: requestNetwork,
clientId,
dappName,
dappScheme,
Expand Down Expand Up @@ -217,7 +212,7 @@ export const addRequestToApprove =
*/
export const requestsForTopic =
(topic: string | undefined) =>
(dispatch: unknown, getState: AppGetState): RequestData[] => {
(dispatch: unknown, getState: AppGetState): WalletconnectRequestData[] => {
const { requests } = getState().requests;
return Object.values(requests).filter(({ clientId }) => clientId === topic);
};
Expand Down
22 changes: 10 additions & 12 deletions src/redux/walletconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { sendRpcCall } from '../handlers/web3';
import WalletTypes from '../helpers/walletTypes';
import { Navigation } from '../navigation';
import { isSigningMethod } from '../utils/signingMethods';
import { addRequestToApprove, RequestData } from './requests';
import { addRequestToApprove, WalletconnectRequestData } from './requests';
import { AppGetState, AppState as StoreAppState } from './store';
import { WrappedAlert as Alert } from '@/helpers/alert';
import { analytics } from '@/analytics';
Expand All @@ -31,6 +31,7 @@ import { logger, RainbowError } from '@/logger';
import { IS_DEV, IS_IOS, IS_TEST } from '@/env';
import { RainbowNetworks } from '@/networks';
import { Verify } from '@walletconnect/types';
import { handleWalletConnectRequest } from '@/utils/requestNavigationHandlers';

// -- Variables --------------------------------------- //
let showRedirectSheetThreshold = 300;
Expand Down Expand Up @@ -133,10 +134,10 @@ export interface WalletconnectApprovalSheetRouteParams {
approved: boolean,
chainId: number,
accountAddress: string,
peerId: RequestData['peerId'],
dappScheme: RequestData['dappScheme'],
dappName: RequestData['dappName'],
dappUrl: RequestData['dappUrl']
peerId: WalletconnectRequestData['peerId'],
dappScheme: WalletconnectRequestData['dappScheme'],
dappName: WalletconnectRequestData['dappName'],
dappUrl: WalletconnectRequestData['dappUrl']
) => Promise<unknown>;
receivedTimestamp: number;
meta?: {
Expand All @@ -148,7 +149,7 @@ export interface WalletconnectApprovalSheetRouteParams {
*/
chainIds: number[];
isWalletConnectV2?: boolean;
} & Pick<RequestData, 'dappName' | 'dappScheme' | 'dappUrl' | 'imageUrl' | 'peerId'>;
} & Pick<WalletconnectRequestData, 'dappName' | 'dappScheme' | 'dappUrl' | 'imageUrl' | 'peerId'>;
timeout?: ReturnType<typeof setTimeout> | null;
timedOut?: boolean;
failureExplainSheetVariant?: string;
Expand Down Expand Up @@ -557,10 +558,7 @@ const listenOnNewMessages =
const { requests: pendingRequests } = getState().requests;
const request = !pendingRequests[requestId] ? dispatch(addRequestToApprove(clientId, peerId, requestId, payload, peerMeta)) : null;
if (request) {
Navigation.handleAction(Routes.CONFIRM_REQUEST, {
openAutomatically: true,
transactionDetails: request,
});
handleWalletConnectRequest(request);
InteractionManager.runAfterInteractions(() => {
analytics.track('Showing Walletconnect signing request', {
dappName,
Expand Down Expand Up @@ -741,7 +739,7 @@ export const removeWalletConnector =
* @param chainId The chain ID to use.
*/
export const walletConnectUpdateSessionConnectorByDappUrl =
(dappUrl: RequestData['dappUrl'], accountAddress: string, chainId: number) =>
(dappUrl: WalletconnectRequestData['dappUrl'], accountAddress: string, chainId: number) =>
(dispatch: Dispatch<WalletconnectUpdateConnectorsAction>, getState: AppGetState) => {
const { walletConnectors } = getState().walletconnect;
const connectors = pickBy(walletConnectors, connector => {
Expand Down Expand Up @@ -774,7 +772,7 @@ export const walletConnectApproveSession =
(
peerId: string,
callback: WalletconnectRequestCallback | undefined,
dappScheme: RequestData['dappScheme'],
dappScheme: WalletconnectRequestData['dappScheme'],
chainId: number,
accountAddress: string
) =>
Expand Down
Loading

0 comments on commit 0c00f6a

Please sign in to comment.