Create UseVote Hook For Voting Transactions

by Admin 44 views
Create useVote Hook for Voting Transactions

Let's dive into creating a useVote hook for handling voting transactions on the frontend. This hook will encapsulate the entire blockchain logic required for voting, making it reusable and easier to manage. We'll cover everything from token approval to depositing into the vault, along with error handling, state management, and retry logic. So, buckle up, guys!

Description

The primary goal here is to create a custom React hook that manages the entire voting process. This includes approving the TRUST token, depositing it into the vault, and handling all the intermediate states. By encapsulating this logic, we can ensure that our voting mechanism is both efficient and maintainable.

Objectif

Our main objective is to encapsulate all the blockchain logic related to voting into a reusable hook. This hook should handle errors, manage states, and implement retry mechanisms, ensuring a smooth and reliable voting experience for the users. This approach not only simplifies the codebase but also enhances the user experience by providing clear feedback on the voting process. With this, we can make sure that even if something goes wrong, users can easily retry without losing their progress. The reusability of this hook will save us a lot of time and effort in the long run, as we can use it across different components and applications.

Tâches

Let's break down the tasks involved in creating this useVote hook.

Hook useVote

  • Interface TypeScript claire: Define a clear TypeScript interface for the hook to ensure type safety and ease of use.
  • Gestion des Ă©tats: Implement state management to handle different states such as idle, approving, depositing, success, and error. These states will help in providing real-time feedback to the user about the voting process.
  • Fonction vote(amount) principale: Create a main vote(amount) function that initiates the voting process.
  • Fonction checkApproval pour vĂ©rifier allowance: Implement a checkApproval function to verify the allowance before proceeding with the deposit.
  • Fonction approveToken si nĂ©cessaire: Create an approveToken function to handle token approval if the allowance is insufficient.
  • Fonction depositToVault: Implement a depositToVault function to deposit the tokens into the vault.
  • Retourner isLoading, error, status, vote(): Return isLoading, error, status, and the vote() function from the hook to provide necessary information and functionalities to the components using it.

Vérification Allowance

  • Utiliser wagmi useReadContract pour lire allowance: Use wagmi's useReadContract hook to read the allowance of the token.
  • Comparer allowance actuelle vs montant Ă  dĂ©poser: Compare the current allowance with the amount to be deposited to determine if approval is needed.
  • Skip approval si allowance suffisante: Skip the approval step if the allowance is already sufficient to save gas fees and time for the user.
  • Force re-check avant chaque vote: Ensure that the allowance is re-checked before each vote to account for any changes in the allowance.

Transaction Approval

  • Utiliser wagmi useWriteContract pour approve(): Utilize wagmi's useWriteContract hook to execute the approve() function on the token contract.
  • Target: MultiVault contract address: Target the MultiVault contract address for the approval transaction. The MultiVault contract is where the tokens will be deposited for voting.
  • Amount: montant Ă  voter (ou max uint256 pour approuver une fois pour toutes): Set the amount to be approved to the amount being voted or max uint256 to approve once and for all.
  • Attendre confirmation transaction: Wait for the transaction to be confirmed on the blockchain.
  • Toast notification pendant approval: Display a toast notification during the approval process to keep the user informed.

Transaction Deposit

  • Utiliser INTUITION SDK depositTriple(): Use the INTUITION SDK's depositTriple() function to deposit the tokens.
  • Paramètres: tripleId, amount, isPositive=true (FOR vault): Set the parameters for the depositTriple() function, including the tripleId, amount, and isPositive=true for depositing into the vault.
  • Attendre confirmation transaction: Wait for the transaction to be confirmed on the blockchain. Waiting ensures that the deposit is successfully recorded on the blockchain.
  • RĂ©cupĂ©rer receipt et event logs: Retrieve the transaction receipt and event logs for further processing and debugging.
  • Toast notification pendant deposit: Display a toast notification during the deposit process to keep the user informed.

Gestion des États

  • idle: No action is being performed.
  • checking: Checking the allowance.
  • approving: Transaction approval in progress.
  • depositing: Transaction deposit in progress.
  • success: Vote registered successfully.
  • error: Failure at one of the steps. It’s crucial to handle the error state properly. When an error occurs, display a user-friendly message and provide options for the user to retry the process. Logging the error details can also help in debugging and identifying potential issues.
  • Progress indicator: Display a step-by-step progress indicator (e.g., 1/2, 2/2) to show the user where they are in the voting process. This helps manage user expectations and provides a sense of progress, making the experience more transparent and user-friendly. Use clear and concise labels for each step to avoid confusion.

Gestion des Erreurs

  • User rejected transaction: Handle the case where the user rejects the transaction in their wallet. Display a message indicating that the transaction was rejected and allow them to retry.
  • Insufficient TRUST balance: Handle the case where the user does not have enough TRUST tokens in their balance. Provide guidance on how to acquire more TRUST tokens. Displaying the user's current balance and the required amount can help them understand the situation better.
  • Insufficient ETH for gas: Handle the case where the user does not have enough ETH to pay for gas fees. Provide a message indicating that they need to fund their wallet with ETH. Suggesting ways to get ETH, such as using a faucet or exchanging tokens, can also be helpful.
  • Network error: Handle network-related errors and prompt the user to check their internet connection. Implementing a retry mechanism can also help in these situations.
  • Contract error: Handle errors that occur when interacting with the contract. This can include issues such as invalid parameters or contract exceptions. Parsing the error message can provide more specific information to the user.
  • Parser les messages d erreur: Parse the error messages to provide more user-friendly and informative error messages. Displaying technical error messages can be confusing for users, so it's important to translate them into understandable terms.
  • Retourner error typĂ©: Return a typed error object to provide more structured error information. This allows the components using the hook to handle errors more effectively.

Toast Notifications

  • VĂ©rification de l allowance: Display a toast notification while checking the allowance.
  • Signature requise (approval): Display a toast notification when a signature is required for approval.
  • Transaction approval en cours: Display a toast notification while the approval transaction is in progress. Providing real-time feedback on the transaction status keeps the user informed and engaged. Using a progress bar within the toast can further enhance the user experience.
  • Approval confirmĂ©: Display a toast notification when the approval is confirmed.
  • Signature requise (deposit): Display a toast notification when a signature is required for the deposit.
  • Transaction deposit en cours: Display a toast notification while the deposit transaction is in progress. Include relevant details such as the amount being deposited and the target vault to provide context for the user.
  • Vote enregistrĂ© avec succès: Display a toast notification when the vote is successfully registered.
  • Erreur Ă  chaque Ă©tape possible: Display error notifications for each possible failure point to provide immediate feedback to the user.

Invalidation Cache

  • Invalider cache GraphQL après vote: Invalidate the GraphQL cache after a vote to ensure that the UI reflects the latest data.
  • Refetch proposals du fondateur: Refetch the founder's proposals to update the UI with the latest voting results. Keeping the proposals up-to-date ensures that users see the most current information. Using a polling mechanism can also help in automatically refreshing the data at regular intervals.
  • Refetch user balance TRUST: Refetch the user's TRUST balance to update the UI with the latest balance.
  • Refetch user votes: Refetch the user's votes to update the UI with the latest voting status.
  • Trigger callback onSuccess: Trigger a callback function after a successful vote to perform any necessary post-vote actions.

Retry Logic

  • Permettre de retry après erreur: Allow the user to retry after an error occurs, especially for network-related issues.
  • Reset error state: Reset the error state when retrying to avoid displaying stale error messages.
  • Reprendre Ă  l Ă©tape Ă©chouĂ©e: Resume the process from the step where the error occurred to avoid repeating previous steps. Maintaining the state of the voting process allows for a seamless retry experience. For example, if the approval transaction fails, the retry should start from the approval step, not from the beginning.
  • Max 3 retries automatiques pour network errors: Implement a maximum of 3 automatic retries for network errors to avoid infinite loops. After the maximum number of retries is reached, display an error message and allow the user to manually retry.

Exemple de code (structure)

Interface TypeScript:

interface UseVote {
  vote: (amount: BigNumber) => Promise<void>;
  status: 'idle' | 'checking' | 'approving' | 'depositing' | 'success' | 'error';
  error: Error | null;
  isLoading: boolean;
  currentStep: number;
}

function useVote(tripleId: string): UseVote {
  // Hook logic here
}

États possibles:

  • idle, checking, approving, depositing, success, error

Flux:

  1. Check allowance
  2. If insufficient: approve transaction
  3. Wait approval confirmation
  4. Deposit transaction
  5. Wait deposit confirmation
  6. Success callback

Documentation

Dépendances

  • Issue #37 (VoteModal - utilise useVote)
  • Issue #19 (wagmi setup)
  • @0xintuition/sdk
  • wagmi hooks
  • sonner pour toasts