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

feat: support intent URL to start a new WalletConnect session #271

Merged
merged 21 commits into from
Jan 31, 2024

Conversation

manu0466
Copy link

@manu0466 manu0466 commented Jan 31, 2024

Description

Closes: DPM-190

This PR adds support for a new intent URI to start a new WalletConnect session from an external application.
The new intent URI has the following schema: dpm://wcV2?uri=${WALLET_CONNECT_URI}&returnToApp=${true | false}.
Here are the details about the query parameters:

  • uri - The URL-encoded WalletConnect URI to start the new session;
  • returnToApp - Indicates whether the application should return to the application that has triggered the session start after the session is established.

Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

  • included the correct type prefix in the PR title
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed

Summary by CodeRabbit

  • New Features

    • Added support for custom URL schemes to enhance app interoperability.
    • Enhanced URI action handling with new parsing and caching capabilities.
    • Improved WalletConnect functionality with new hooks for session management and action handling.
    • Introduced a more flexible GraphQL client setup to support child components.
    • Updated theme provider to support child components for better theme management.
  • Enhancements

    • Refined navigation logic to better handle cached URI actions and return to the current screen accurately.
    • Streamlined the handling of received actions and WalletConnect session proposals with updated logic and hooks.
    • Enhanced loading modal styling for better user experience.
  • Bug Fixes

    • Fixed issues related to WalletConnect session establishment tracking and proposal handling.
  • Refactor

    • Simplified WalletConnect hooks and removed unnecessary dependencies to streamline the codebase.
    • Updated the UnlockApplication and WalletConnectRequest components for improved logic and user flow.
  • Documentation

    • Added comments to clarify the logic in WalletConnect session request handling.

@manu0466 manu0466 added Type: Enhancement New feature or request C: Logic Related to the logic part of the app automerge Related to mergify labels Jan 31, 2024
@manu0466 manu0466 requested a review from RiccardoM January 31, 2024 13:53
Copy link

coderabbitai bot commented Jan 31, 2024

Walkthrough

The application underwent significant updates to enhance its deep linking capabilities, wallet connection management, and UI/UX improvements. Key changes include the addition of new URI schemes for better inter-app communication, refactoring of hooks and components to support new functionalities like handling wallet connect actions and URI actions more efficiently, and updates to the navigation and theme management to provide a smoother user experience. These changes collectively aim to make the app more intuitive, responsive, and integrated with external services.

Changes

Files Summary
ios/.../Info.plist Added CFBundleURLSchemes with dpm scheme.
src/App.tsx
src/hooks/uriactions/useHandleUriAction.tsx
src/navigation/RootNavigator/index.tsx
src/screens/DevScreen/index.tsx
Enhanced URI action handling and integration.
src/contexts/GraphQLClientProvider.tsx
src/contexts/ThemeProvider.tsx
Enabled PropsWithChildren for wrapping children with providers.
src/hooks/analytics/useTrackWalletConnectSessionEstablished.ts
src/hooks/walletconnect/...
Modified wallet connect hooks for improved session management.
src/hooks/useHandleReceivedActions.ts
src/hooks/useReturnToCurrentScreen.ts
Improved background action handling and navigation.
src/lib/UriActions/caching.ts
src/lib/UriActions/parsing.ts
Updated URI action caching and parsing logic.
src/modals/LoadingModal/useStyles.ts Updated styles for better UI consistency.
src/recoil/uriaction.ts Introduced recoil management for URI actions.
src/screens/UnlockApplication/index.tsx
src/screens/WalletConnectRequest/index.tsx
src/screens/WalletConnectSessionProposal/index.tsx
Updated screens for better flow and error handling.
src/types/uri.ts
src/types/walletConnect.ts
Updated types for extended functionality and cleaner code.

"In the realm of code, where changes abound,
A rabbit hopped, making leaps and bounds.
With each push and pull, a new feature found,
🎉 Here's to progress, where our hopes are crowned!"
🐰✨

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

github-actions bot commented Jan 31, 2024

SonarQube Quality Gate Result

  • Result: ✅ OK
  • Triggered by @manu0466 on pull_request
Metric Status Value Error Threshold
New reliability rating ✅ OK 1 > 1
New security rating ✅ OK 1 > 1
New maintainability rating ✅ OK 1 > 1
New duplicated lines density ✅ OK 1.55 > 3
New security hotspots reviewed ✅ OK 100 < 100

View on SonarQube

updated: 1/31/2024, 14:07:45 (UTC+0)

@manu0466 manu0466 force-pushed the manuel/DPM-190/wallet-connect-intent-uri branch from 91e431d to 6b8225e Compare January 31, 2024 14:04
Copy link

codecov bot commented Jan 31, 2024

Codecov Report

Attention: 11 lines in your changes are missing coverage. Please review.

Comparison is base (f1bf0c0) 80.87% compared to head (6b8225e) 79.19%.

Files Patch % Lines
src/lib/UriActions/parsing.ts 14.28% 6 Missing ⚠️
src/lib/UriActions/caching.ts 28.57% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #271      +/-   ##
==========================================
- Coverage   80.87%   79.19%   -1.69%     
==========================================
  Files         124      124              
  Lines         481      495      +14     
  Branches       63       64       +1     
==========================================
+ Hits          389      392       +3     
- Misses         92      103      +11     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@manu0466 manu0466 marked this pull request as ready for review January 31, 2024 14:14
@RiccardoM
Copy link
Contributor

@coderabbitai review

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between f1bf0c0 and 6b8225e.
Files ignored due to path filters (2)
  • android/app/src/main/AndroidManifest.xml is excluded by: !**/*.xml
  • src/assets/locales/en/walletConnect.json is excluded by: !**/*.json
Files selected for processing (24)
  • ios/DesmosProfileManager/Info.plist (1 hunks)
  • src/App.tsx (2 hunks)
  • src/contexts/GraphQLClientProvider.tsx (1 hunks)
  • src/contexts/ThemeProvider.tsx (2 hunks)
  • src/hooks/analytics/useTrackWalletConnectSessionEstablished.ts (2 hunks)
  • src/hooks/uriactions/useHandleUriAction.tsx (4 hunks)
  • src/hooks/uriactions/useInitLinkingUriActions.ts (1 hunks)
  • src/hooks/useHandleReceivedActions.ts (1 hunks)
  • src/hooks/useReturnToCurrentScreen.ts (2 hunks)
  • src/hooks/walletconnect/useInitWalletConnectLogic.ts (1 hunks)
  • src/hooks/walletconnect/useWalletConnectApproveSessionProposal.ts (3 hunks)
  • src/hooks/walletconnect/useWalletConnectOnSessionRequest.ts (4 hunks)
  • src/lib/UriActions/caching.ts (2 hunks)
  • src/lib/UriActions/parsing.ts (1 hunks)
  • src/modals/LoadingModal/useStyles.ts (1 hunks)
  • src/navigation/RootNavigator/index.tsx (2 hunks)
  • src/recoil/uriaction.ts (1 hunks)
  • src/screens/DevScreen/index.tsx (3 hunks)
  • src/screens/UnlockApplication/index.tsx (5 hunks)
  • src/screens/WalletConnectRequest/index.tsx (3 hunks)
  • src/screens/WalletConnectRequest/useHooks.ts (2 hunks)
  • src/screens/WalletConnectSessionProposal/index.tsx (1 hunks)
  • src/types/uri.ts (2 hunks)
  • src/types/walletConnect.ts (1 hunks)
Files skipped from review due to trivial changes (4)
  • src/hooks/useReturnToCurrentScreen.ts
  • src/hooks/walletconnect/useInitWalletConnectLogic.ts
  • src/hooks/walletconnect/useWalletConnectOnSessionRequest.ts
  • src/modals/LoadingModal/useStyles.ts
Additional comments: 28
src/contexts/GraphQLClientProvider.tsx (1)
  • 5-5: The modification to GraphQLClientProvider to use PropsWithChildren is correct and aligns with React's type definitions for components that accept children. This change enhances type safety and readability.
src/hooks/analytics/useTrackWalletConnectSessionEstablished.ts (1)
  • 13-17: The change to accept appName and namespaces directly instead of a session object simplifies the hook's interface and focuses on the required data, improving the hook's usability and maintainability.
src/recoil/uriaction.ts (1)
  • 8-11: The introduction of uriActionAtom to manage URI actions within the application's state using Recoil is a structured approach to state management, ensuring a centralized and reactive way to handle URI actions.
src/hooks/uriactions/useInitLinkingUriActions.ts (1)
  • 9-31: The implementation of useInitLinkingUriActions to handle initial and background URI actions using React Native's Linking API is well-structured. It ensures that URI actions are processed both at app launch and when the app is brought to the foreground, enhancing the app's responsiveness to external triggers.
src/lib/UriActions/caching.ts (2)
  • 6-15: The addition of NEW_ACTION_EVENT and the use of EventEmitter to notify subscribers about new URI actions is a robust pattern for event-driven updates, improving the modularity and decoupling of components that need to react to new URI actions.
  • 40-44: Implementing onCachedUriActionChange to allow subscription to URI action changes using EventEmitter is a clean and effective way to observe changes, facilitating better separation of concerns and reactivity within the application.
src/contexts/ThemeProvider.tsx (1)
  • 15-15: Similar to GraphQLClientProvider, the update to ThemeProvider to utilize PropsWithChildren is a good practice, ensuring that the component's ability to accept children is explicitly defined and type-safe.
src/screens/WalletConnectRequest/useHooks.ts (1)
  • 53-60: The introduction of useRejectAllRequests hook provides a clear and concise way to reject all pending WalletConnect requests, encapsulating this functionality within a reusable hook to improve code organization and reuse.
src/App.tsx (1)
  • 25-36: The integration of URI action handling in the App component using getCachedUriAction and isUriActionPending functions, along with the useSetUriAction hook, demonstrates a cohesive approach to managing and responding to URI actions at the application level.
src/hooks/walletconnect/useWalletConnectApproveSessionProposal.ts (1)
  • 52-69: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [21-66]

The refactoring of useWalletConnectApproveSessionProposal to return a Promise<Result<void, Error>> and the adjustments to use properties from the proposal object directly enhance the hook's clarity and type safety. This change also simplifies the handling of session proposals by focusing on the essential data, improving the maintainability of the code.

src/hooks/useHandleReceivedActions.ts (1)
  • 18-71: The implementation of useHandleReceivedActions to manage actions received while the application was in the background, including URI actions and WalletConnect session requests, is well-organized. It ensures that the application responds appropriately to external triggers, enhancing the user experience by handling these actions efficiently.
src/types/walletConnect.ts (1)
  • 69-74: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The removal of the url property from the WalletConnectSession interface indicates a refinement in the data model to better align with the actual requirements for managing WalletConnect sessions. This change likely simplifies the session handling by focusing on the necessary properties.

src/types/uri.ts (1)
  • 108-123: The extension of the UriActionType enum to include WalletConnectPair and the addition of the WalletConnectPairActionUri interface are significant improvements. They introduce a structured way to handle WalletConnect pairing requests via URI actions, enhancing the application's capability to interact with external triggers in a type-safe manner.
src/lib/UriActions/parsing.ts (1)
  • 127-140: The implementation of parseNativeActionUri to parse and generate a UriAction from a given URI string is a robust addition. It specifically handles the new WalletConnectPair action type, demonstrating a clear and focused approach to parsing URI actions, which enhances the application's extensibility and interoperability with external triggers.
ios/DesmosProfileManager/Info.plist (1)
  • 35-40: The addition of a new <dict> entry with the <key>CFBundleURLSchemes</key> and the <string>dpm</string> array in the Info.plist file correctly configures the iOS application to recognize the dpm URL scheme. This change is essential for supporting the new intent URI schema, facilitating the application's ability to handle custom URI schemes.
src/screens/WalletConnectSessionProposal/index.tsx (2)
  • 24-28: The update to the WalletConnectSessionProposalParams interface to include an optional returnToApp boolean parameter is a thoughtful addition. It allows the component to conditionally adjust its behavior based on whether the user should be directed back to the initiating app after session approval, enhancing the flexibility and user experience of the WalletConnect session proposal flow.
  • 52-66: The conditional logic within showSuccessModal to customize the modal message and action based on the returnToApp parameter is well-implemented. It demonstrates attention to detail in providing a tailored user experience depending on the context of the WalletConnect session initiation.
src/screens/WalletConnectRequest/index.tsx (2)
  • 42-48: The addition of a navigation event listener in the WalletConnectRequest component to reject all requests when navigating back is a proactive measure to ensure that pending requests are not left unaddressed, enhancing the application's robustness in handling WalletConnect requests.
  • 75-77: Enhancing the showErrorModal function to support an additional action allows for more flexible error handling. This change, particularly in the context of rejecting WalletConnect requests, provides a clearer path for cleaning up after an error, improving the application's resilience and user experience.
src/screens/UnlockApplication/index.tsx (1)
  • 73-92: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [34-84]

The changes in the UnlockApplication component, including the removal of useHandleUriAction and the addition of useResetToHomeScreen, streamline the unlocking process. The reorganization of local variable declarations and the modification of the logic for unlocking the application and navigating to the home screen enhance the component's clarity and functionality.

src/hooks/uriactions/useHandleUriAction.tsx (3)
  • 10-10: The import of WalletConnectPairActionUri is correctly added to support the new WalletConnect URI actions.
  • 22-27: The addition of new imports (useActiveAccountAddress, useWalletConnectPair, ErrorModal, LoadingModal, useModal, useGetUriAction, useSetUriAction) aligns with the requirements for handling the new WalletConnect URI actions. Ensure these modules provide the expected functionality and are correctly integrated within the hook.
  • 145-173: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [139-199]

The useHandleUriAction hook's integration of handleWalletConnectPairAction within its switch-case logic is correctly implemented. This ensures that the new WalletConnect pair action is handled alongside other URI actions. Ensure that the UriActionType.WalletConnectPair is correctly defined and that the casting of action to WalletConnectPairActionUri is safe based on the incoming URI structure.

src/screens/DevScreen/index.tsx (3)
  • 24-24: The import of useUriAction from @recoil/uriaction is correctly added to fetch the current URI action within the DevScreen component.
  • 65-65: The initialization of uriAction using useUriAction() is correctly placed to fetch the current URI action for handling within the DevScreen.
  • 202-206: The modification to the Button component's onPress handler to pass uriAction to handleUriAction and the disabling of the button based on the presence of uriAction are correctly implemented. This ensures that the URI action is only handled when one is present, enhancing the user experience by preventing unnecessary button presses.
src/navigation/RootNavigator/index.tsx (2)
  • 65-66: The addition of useInitLinkingUriActions and useHandleReceivedActions imports in place of useWalletConnectAutoReconnect suggests a shift towards a more comprehensive handling of URI actions within the application's navigation setup. Ensure these hooks are correctly implemented to initialize and handle URI actions as the application starts or resumes.
  • 135-136: The use of useInitLinkingUriActions and useHandleReceivedActions within the RootNavigator component is correctly placed to ensure that URI actions are initialized and handled appropriately as part of the application's lifecycle. This integration is crucial for the new feature's functionality, ensuring that URI actions are processed correctly upon app launch or when the app resumes from the background.

Comment on lines +106 to +138
const useHandleWalletConnectPairAction = () => {
const { t } = useTranslation('walletConnect');
const activeAccountAddress = useActiveAccountAddress();
const pair = useWalletConnectPair();
const navigation = useNavigation<StackNavigationProp<RootNavigatorParamList>>();
const { showModal, hideModal } = useModal();

return React.useCallback(
async (action: WalletConnectPairActionUri) => {
if (activeAccountAddress === undefined) {
// Ignore it if we don't have an account.
return;
}

showModal(LoadingModal, {
text: t('initializing new session'),
});
const pairResult = await pair(action.uri);
hideModal();
if (pairResult.isErr()) {
showModal(ErrorModal, {
text: pairResult.error.message,
});
} else {
navigation.navigate(ROUTES.WALLET_CONNECT_SESSION_PROPOSAL, {
proposal: pairResult.value,
returnToApp: action.returnToApp,
});
}
},
[activeAccountAddress, hideModal, navigation, pair, showModal, t],
);
};
Copy link

Choose a reason for hiding this comment

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

The implementation of useHandleWalletConnectPairAction correctly handles the WalletConnect pairing process, including showing loading and error modals as appropriate. However, consider adding error logging for the case when pairResult.isErr() is true, to aid in debugging and monitoring.

if (pairResult.isErr()) {
  showModal(ErrorModal, {
    text: pairResult.error.message,
  });
+ // Consider logging this error for better monitoring and debugging
+ console.error(`WalletConnect pairing failed: ${pairResult.error.message}`);
}

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const useHandleWalletConnectPairAction = () => {
const { t } = useTranslation('walletConnect');
const activeAccountAddress = useActiveAccountAddress();
const pair = useWalletConnectPair();
const navigation = useNavigation<StackNavigationProp<RootNavigatorParamList>>();
const { showModal, hideModal } = useModal();
return React.useCallback(
async (action: WalletConnectPairActionUri) => {
if (activeAccountAddress === undefined) {
// Ignore it if we don't have an account.
return;
}
showModal(LoadingModal, {
text: t('initializing new session'),
});
const pairResult = await pair(action.uri);
hideModal();
if (pairResult.isErr()) {
showModal(ErrorModal, {
text: pairResult.error.message,
});
} else {
navigation.navigate(ROUTES.WALLET_CONNECT_SESSION_PROPOSAL, {
proposal: pairResult.value,
returnToApp: action.returnToApp,
});
}
},
[activeAccountAddress, hideModal, navigation, pair, showModal, t],
);
};
const useHandleWalletConnectPairAction = () => {
const { t } = useTranslation('walletConnect');
const activeAccountAddress = useActiveAccountAddress();
const pair = useWalletConnectPair();
const navigation = useNavigation<StackNavigationProp<RootNavigatorParamList>>();
const { showModal, hideModal } = useModal();
return React.useCallback(
async (action: WalletConnectPairActionUri) => {
if (activeAccountAddress === undefined) {
// Ignore it if we don't have an account.
return;
}
showModal(LoadingModal, {
text: t('initializing new session'),
});
const pairResult = await pair(action.uri);
hideModal();
if (pairResult.isErr()) {
showModal(ErrorModal, {
text: pairResult.error.message,
});
// Consider logging this error for better monitoring and debugging
console.error(`WalletConnect pairing failed: ${pairResult.error.message}`);
} else {
navigation.navigate(ROUTES.WALLET_CONNECT_SESSION_PROPOSAL, {
proposal: pairResult.value,
returnToApp: action.returnToApp,
});
}
},
[activeAccountAddress, hideModal, navigation, pair, showModal, t],
);
};

Copy link
Contributor

@RiccardoM RiccardoM left a comment

Choose a reason for hiding this comment

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

Looks great to me! I only have one minor suggestion about a comment but otherwise looks fantastic 💯

Comment on lines +25 to +26
* Tells if the application should return to the app that
* has triggered the paring request after the session is approved.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
* Tells if the application should return to the app that
* has triggered the paring request after the session is approved.
* Whether the user should be brought back to the app that
* has triggered the paring request after the session is approved.

@mergify mergify bot merged commit f0d9f35 into main Jan 31, 2024
8 of 10 checks passed
@mergify mergify bot deleted the manuel/DPM-190/wallet-connect-intent-uri branch January 31, 2024 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Related to mergify C: Logic Related to the logic part of the app Type: Enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants