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/send token confirm page #138

Merged
merged 4 commits into from
Aug 20, 2024
Merged

Feat/send token confirm page #138

merged 4 commits into from
Aug 20, 2024

Conversation

rustin01
Copy link
Contributor

@rustin01 rustin01 commented Aug 20, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a dedicated confirmation page for sending tokens, enhancing user experience by providing clarity in the token transfer process.
    • Added utility functions for generating transaction and address links based on blockchain chain IDs.
  • Bug Fixes

    • Improved error handling in the number formatting function to prevent issues with undefined or null inputs.
  • Refactor

    • Streamlined state management for token transfers, resulting in a more decoupled and maintainable code structure.

Copy link
Contributor

coderabbitai bot commented Aug 20, 2024

Walkthrough

The recent updates enhance the wallet application by introducing a new confirmation page for token transfers, streamlining state management for token sending, and improving fee estimation across different blockchain wallets. These changes collectively enhance user experience, ensuring clearer workflows and greater usability when initiating and confirming transactions.

Changes

Files Change Summary
apps/wallet/src/App.tsx, apps/wallet/src/pages/send-token/confirm-page.tsx Introduced SendTokenConfirmPage for token transfer confirmation, adding a new route and lazy-loaded component, improving user flow after sending tokens.
apps/wallet/src/pages/send-token/index.tsx, apps/wallet/src/pages/send-token/store.ts Refactored SendTokenPage to utilize centralized state management through sendTokenStore, decoupling responsibilities and enhancing user experience.
apps/wallet/src/utils/chain/chain-wallets/ethereum/index.ts, .../ton/index.ts, .../index.ts Added getEstimatedFee method in various wallet classes to calculate transaction fees based on asset type, enhancing functionality across different wallets.
apps/wallet/src/utils/chain/chain-wallets/types.ts Introduced abstract method getEstimatedFee in ChainWallet class, providing a standardized way to estimate fees across different wallet implementations.
apps/wallet/src/utils/formatter/numberFormatter.ts Enhanced formatNumber function to handle undefined and null inputs, improving robustness and error handling.
apps/wallet/src/utils/link.ts Introduced utility functions for generating transaction and address links based on blockchain chain IDs, enhancing link generation capabilities within the app.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SendTokenPage
    participant SendTokenConfirmPage
    participant sendTokenStore
    participant EthereumChainWallet

    User->>SendTokenPage: Initiates token transfer
    SendTokenPage->>sendTokenStore: Updates toAddress and amount
    SendTokenPage->>SendTokenConfirmPage: Navigates to confirmation
    SendTokenConfirmPage->>EthereumChainWallet: Calls getEstimatedFee
    EthereumChainWallet-->>SendTokenConfirmPage: Returns estimated fee
    User->>SendTokenConfirmPage: Confirms transfer
    SendTokenConfirmPage->>sendTokenStore: Triggers transfer mutation
    sendTokenStore-->>User: Displays success message
Loading

Poem

🐇 In the wallet, tokens fly,
Hopping from here to the sky.
A page for confirmation now,
To make the process smoother—wow!
With fees estimated right,
Our transactions take flight! 🌟


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 testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 testing code 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 and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • 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/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Deploy preview for hibit-id ready!

✅ Preview
https://hibit-rnp5493g8-delandlabs-projects.vercel.app

Built with commit 045c13f.
This pull request is being automatically deployed with vercel-action

Copy link
Contributor

@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.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (9)
apps/wallet/src/pages/send-token/store.ts (1)

1-2: Consider importing only necessary functions or types.

If RootAssetInfo and makeAutoObservable are the only imports needed from their respective modules, this is fine. However, if there are more specific imports, consider importing only what is necessary to reduce bundle size and improve readability.

apps/wallet/src/pages/send-token/confirm-page.tsx (5)

1-18: Review Imports for Optimization and Consistency

The imports are well-structured, but consider the following:

  • Ensure all imported assets are used in the component.
  • Group similar imports together for better readability, such as React hooks and components.
  • Verify if all imported modules are necessary for this file.

19-27: Initialize State with Type Annotations

The useState hooks for errMsg and transferResult are correctly used, but consider adding explicit type annotations for better clarity and maintainability.

const [errMsg, setErrMsg] = useState<string>('');
const [transferResult, setTransferResult] = useState<{
  state: 'pending' | 'done';
  txId: string;
}>({
  state: 'pending',
  txId: '',
});

59-68: Enhance Error Message Logic

The useEffect for setting error messages is well-implemented. Ensure that all possible states are covered, and consider logging or handling unexpected states for debugging.


105-114: Consider Loading State Enhancements

The loading state UI for pending transfers is clear. Consider adding more detailed loading indicators or messages if the process takes a long time.


140-209: Review UI Elements for Accessibility

The UI elements such as buttons and labels are well-structured. Ensure that all elements are accessible, with appropriate ARIA attributes and keyboard navigation.

apps/wallet/src/utils/chain/chain-wallets/ton/index.ts (3)

Line range hint 1-14: Review Imports for Optimization and Consistency

The imports are well-structured, but consider the following:

  • Ensure all imported modules are used in the file.
  • Group similar imports together for better readability, such as external libraries and internal utilities.

Line range hint 232-250: Review Private Methods for Efficiency

The private methods initWallet, getIsTestNet, and getJettonWallet are well-implemented. Ensure that they are efficient and handle all edge cases, especially in asynchronous operations.


188-231: Enhance Error Handling in getEstimatedFee Method

The getEstimatedFee method should include a try-catch block around the estimateExternalMessageFee call to handle any exceptions that may be thrown by this external API. This will ensure more robust error handling and prevent unhandled exceptions from propagating up the call stack.

  • Consider wrapping the estimateExternalMessageFee call in a try-catch block to handle potential exceptions.
Analysis chain

Ensure Robust Error Handling in getEstimatedFee

The getEstimatedFee method is well-implemented, but ensure robust error handling for all possible scenarios, especially when dealing with external API calls.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify robust error handling in `getEstimatedFee`.

# Test: Check for error handling in external API calls within the method.
rg --type ts "estimateExternalMessageFee"

Length of output: 165


Script:

#!/bin/bash
# Description: Check for error handling mechanisms around the `estimateExternalMessageFee` call.

# Search for try-catch blocks or error handling around the `estimateExternalMessageFee` call in the file.
rg --type ts -A 10 "estimateExternalMessageFee" apps/wallet/src/utils/chain/chain-wallets/ton/index.ts

Length of output: 414

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 140bef0 and 045c13f.

Files ignored due to path filters (4)
  • apps/wallet/src/assets/copy.svg is excluded by !**/*.svg
  • apps/wallet/src/assets/external.svg is excluded by !**/*.svg
  • apps/wallet/src/assets/transfer-loading.svg is excluded by !**/*.svg
  • apps/wallet/src/assets/transfer-success.svg is excluded by !**/*.svg
Files selected for processing (10)
  • apps/wallet/src/App.tsx (2 hunks)
  • apps/wallet/src/pages/send-token/confirm-page.tsx (1 hunks)
  • apps/wallet/src/pages/send-token/index.tsx (4 hunks)
  • apps/wallet/src/pages/send-token/store.ts (1 hunks)
  • apps/wallet/src/utils/chain/chain-wallets/ethereum/index.ts (1 hunks)
  • apps/wallet/src/utils/chain/chain-wallets/index.ts (1 hunks)
  • apps/wallet/src/utils/chain/chain-wallets/ton/index.ts (1 hunks)
  • apps/wallet/src/utils/chain/chain-wallets/types.ts (1 hunks)
  • apps/wallet/src/utils/formatter/numberFormatter.ts (1 hunks)
  • apps/wallet/src/utils/link.ts (1 hunks)
Additional comments not posted (16)
apps/wallet/src/pages/send-token/store.ts (3)

4-8: Ensure type completeness for SendTokenState.

The SendTokenState interface is straightforward, but make sure that the types for token, toAddress, and amount are sufficient for all expected use cases. For instance, if amount might need to handle large numbers or decimals, ensure it is handled correctly.


10-32: Appropriate use of MobX for state management.

The SendTokenStore class correctly uses makeAutoObservable to manage state changes automatically. The methods setState and reset are clear and concise, providing necessary functionality for state management.


34-34: Consider exporting the store as a singleton.

Exporting sendTokenStore as a singleton is a good practice for ensuring a single source of truth in the application state. Make sure this aligns with the overall architecture and usage patterns in your application.

apps/wallet/src/utils/link.ts (2)

4-14: Ensure robustness in URL construction.

The function getChainTxLink constructs URLs for transaction links. Ensure that the explorer field in chainInfo is always a valid URL string to prevent runtime errors. Consider adding validation or error handling if necessary.


16-29: Ensure robustness in URL construction.

Similarly, the function getChainAddressLink constructs URLs for address links. Verify that the explorer field in chainInfo is consistently formatted to prevent issues. Consider adding validation or error handling if necessary.

apps/wallet/src/utils/chain/chain-wallets/types.ts (1)

24-24: Ensure all subclasses implement getEstimatedFee.

The addition of the getEstimatedFee method to the ChainWallet class requires all subclasses to implement this method. Ensure that all existing subclasses are updated accordingly to prevent runtime errors.

apps/wallet/src/utils/chain/chain-wallets/index.ts (1)

55-58: Ensure proper error handling for unsupported chains.

The getEstimatedFee method relies on the get method to retrieve a wallet instance. Ensure that the get method handles cases where a chain is not supported, as this could lead to unhandled errors when calling getEstimatedFee.

apps/wallet/src/utils/formatter/numberFormatter.ts (1)

22-28: LGTM! Verify usage of formatNumber.

The update to handle undefined and null inputs by returning '--' is a good improvement for robustness. Ensure that all usages of formatNumber in the codebase expect this behavior.

apps/wallet/src/App.tsx (1)

24-24: LGTM!

The addition of the SendTokenConfirmPage route is a great enhancement for the user flow. Lazy loading the component is a good practice for performance.

Also applies to: 107-107

apps/wallet/src/pages/send-token/index.tsx (1)

17-17: LGTM! Verify sendTokenStore integration.

The refactor to use sendTokenStore for state management simplifies the component and improves maintainability. Ensure that sendTokenStore is correctly integrated and functioning as expected.

Also applies to: 22-22, 63-64, 80-85

Verification successful

Integration of sendTokenStore is verified and correct.

The sendTokenStore is properly integrated and used in the confirm-page.tsx and index.tsx files. Its state is accessed and updated appropriately, and the reset method is utilized as expected. No issues found with the integration.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of `sendTokenStore` in the codebase.

# Test: Search for `sendTokenStore` usage. Expect: The store is correctly used and updated.
rg --type ts -A 5 $'sendTokenStore'

Length of output: 2670

apps/wallet/src/utils/chain/chain-wallets/ethereum/index.ts (1)

106-142: LGTM! Verify getEstimatedFee integration.

The getEstimatedFee method is a valuable addition for estimating transaction fees. Ensure that this method is correctly integrated and utilized within the application.

Verification successful

Integration of getEstimatedFee Verified

The getEstimatedFee method is well-integrated across the codebase. It is implemented for different chains, such as Ethereum and Ton, and is used in key components like the transaction confirmation page. The method's integration is consistent with its intended purpose for estimating transaction fees.

  • Usage Locations:
    • Implemented in: ethereum/index.ts, ton/index.ts
    • Abstract definition: types.ts
    • Utilized in: send-token/confirm-page.tsx, chain-wallets/index.ts

The method is correctly utilized and integrated within the application.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of `getEstimatedFee` in the codebase.

# Test: Search for `getEstimatedFee` usage. Expect: The method is correctly used and integrated.
rg --type ts -A 5 $'getEstimatedFee'

Length of output: 2597

apps/wallet/src/pages/send-token/confirm-page.tsx (4)

212-212: LGTM

The component is well-structured and follows good practices for React and TypeScript.


31-46: Check Query Dependencies and Error Handling

The queries for nativeTokenQuery, nativeBalanceQuery, and feeQuery are correctly set up. However, ensure that:

  • Error handling is in place for failed queries.
  • Dependencies in useQuery hooks are correctly specified to avoid unnecessary re-renders.

28-30: Ensure Navigation Safety

The navigate function from useNavigate is used correctly, but ensure that all navigation paths are valid and handled properly in the application.

Verification successful

Navigation Paths Are Valid

The navigation paths used with useNavigate are properly defined and handled in the application's routing configuration.

  • Routes such as /create-password, /verify-password, /account-manage, /send/confirm, and others are correctly set up in apps/wallet/src/App.tsx.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all navigation paths used with `useNavigate` are valid.

# Test: Search for all instances of `useNavigate` and `navigate` to ensure paths are correct.
rg --type tsx "useNavigate|navigate"

Length of output: 66


Script:

#!/bin/bash
# Description: Verify that all navigation paths used with `useNavigate` are valid.

# Test: Search for all instances of `useNavigate` and `navigate` in TypeScript files.
rg --type-add 'ts:*.{ts,tsx}' --type ts "useNavigate|navigate"

Length of output: 5407


Script:

#!/bin/bash
# Description: Verify that all navigation paths used with `useNavigate` are defined in the routing configuration.

# Test: Search for route definitions in TypeScript files to ensure all navigation paths are valid.
rg --type ts "Route|path" -A 3

Length of output: 6694


116-138: Ensure Transaction Link Safety

The transaction link is generated and displayed correctly. Ensure that the link is safe and that user data is not exposed in the URL.

Verification successful

Transaction Link Safety Verified

The getChainTxLink function constructs transaction URLs using only the chainId and txId, without exposing any sensitive user data in the URL. This implementation appears safe.

  • Function implementation in apps/wallet/src/utils/link.ts confirms the safety.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the safety of transaction links.

# Test: Ensure transaction links do not expose sensitive user data.
rg --type tsx "getChainTxLink"

Length of output: 58


Script:

#!/bin/bash
# Description: Verify the safety of transaction links.

# Test: Ensure transaction links do not expose sensitive user data.
rg --type ts "getChainTxLink"

Length of output: 367


Script:

#!/bin/bash
# Description: Retrieve the implementation of getChainTxLink to verify URL safety.

# Extract the implementation of getChainTxLink function.
ast-grep --lang typescript --pattern 'export const getChainTxLink = $_' apps/wallet/src/utils/link.ts

Length of output: 807

apps/wallet/src/utils/chain/chain-wallets/ton/index.ts (1)

188-231: LGTM

The getEstimatedFee method is correctly implemented and follows best practices for asynchronous operations.

Comment on lines +48 to +57
const minNativeBalance = useMemo(() => {
if (!feeQuery.data || !state.token) {
return null
}
if (state.token.chainAssetType.equals(ChainAssetType.Native)) {
return new BigNumber(state.amount).plus(feeQuery.data)
} else {
return feeQuery.data
}
}, [state, feeQuery.data])
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize useMemo Calculation

The useMemo hook is used to calculate minNativeBalance. Ensure that the dependencies array is complete and that the calculation is necessary to optimize performance.

const minNativeBalance = useMemo(() => {
  if (!feeQuery.data || !state.token) {
    return null;
  }
  return state.token.chainAssetType.equals(ChainAssetType.Native)
    ? new BigNumber(state.amount).plus(feeQuery.data)
    : feeQuery.data;
}, [state.amount, state.token, feeQuery.data]);

Comment on lines +70 to +84
const transferMutation = useMutation({
mutationFn: async ({ address, amount }: {
address: string
amount: string
}) => {
if (!hibitIdSession.walletPool || !state.token) {
throw new Error('Wallet or token not ready')
}
return await hibitIdSession.walletPool.transfer(
address,
new BigNumber(amount),
state.token
)
}
})
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider Mutation Error Handling

The useMutation hook for transferMutation lacks specific error handling. Consider adding onError and onSuccess callbacks for better control over mutation outcomes.

const transferMutation = useMutation({
  mutationFn: async ({ address, amount }: { address: string; amount: string }) => {
    if (!hibitIdSession.walletPool || !state.token) {
      throw new Error('Wallet or token not ready');
    }
    return await hibitIdSession.walletPool.transfer(address, new BigNumber(amount), state.token);
  },
  onError: (error) => {
    console.error('Transfer failed:', error);
    toaster.error(error instanceof Error ? error.message : JSON.stringify(error));
  },
  onSuccess: (data) => {
    console.log('Transfer successful:', data);
  },
});

Comment on lines +86 to +102
const handleSend = async () => {
if (!hibitIdSession.walletPool || !state.token || errMsg) {
return
}
try {
const txId = await transferMutation.mutateAsync({
address: state.toAddress,
amount: state.amount,
})
console.debug('[txId]', txId)
setTransferResult({ state: 'done', txId })
sendTokenStore.reset()
} catch (e) {
console.error(e)
setTransferResult({ state: 'pending', txId: '' })
toaster.error(e instanceof Error ? e.message : JSON.stringify(e))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve Error Handling in handleSend Function

The handleSend function has basic error handling. Consider enhancing it by categorizing errors and providing user-friendly messages.

const handleSend = async () => {
  if (!hibitIdSession.walletPool || !state.token || errMsg) {
    return;
  }
  try {
    const txId = await transferMutation.mutateAsync({
      address: state.toAddress,
      amount: state.amount,
    });
    console.debug('[txId]', txId);
    setTransferResult({ state: 'done', txId });
    sendTokenStore.reset();
  } catch (e: unknown) {
    console.error('Error during transfer:', e);
    setTransferResult({ state: 'pending', txId: '' });
    const errorMessage = e instanceof Error ? e.message : 'An unknown error occurred';
    toaster.error(errorMessage);
  }
};

@rustin01 rustin01 merged commit 1c4be60 into main Aug 20, 2024
2 checks passed
@rustin01 rustin01 deleted the feat/send-token-confirm-page branch August 20, 2024 06:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant