Skip to content

Commit

Permalink
refactor(app): extract event handling and notification logic
Browse files Browse the repository at this point in the history
- Moved event handling and notification logic from `src/routes/sections/index.tsx` to `src/App.tsx`.
- Created `AppContent` component in `src/App.tsx` for better encapsulation.
- Replaced redundant logic in `Router` with streamlined routing logic, reducing complexity.
- Simplified imports and removed unused constants and hooks in `src/routes/sections/index.tsx`.

This improves maintainability by centralizing event watch and notification logic in a dedicated component.
  • Loading branch information
cswni committed Jan 22, 2025
1 parent eba18f4 commit cadae73
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 93 deletions.
115 changes: 110 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,17 @@ import { AuthProvider } from '@src/auth/context/web3Auth';
import { ResponsiveOverlay } from '@src/components/responsive-overlay';

import { Buffer } from 'buffer';
import { Provider } from 'react-redux';
import {Provider, useDispatch, useSelector} from 'react-redux';
import { MetaMaskProvider } from '@metamask/sdk-react';
import {useNotifications} from "@src/hooks/use-notifications.ts";
import {useSnackbar} from "notistack";
import {useEffect} from "react";
import {setGlobalNotifier} from "@notifications/internal-notifications.ts";
import {publicClientWebSocket} from "@src/clients/viem/publicClient.ts";
import {GLOBAL_CONSTANTS} from "@src/config-global.ts";
import LedgerVaultAbi from "@src/config/abi/LedgerVault.json";
import {setBlockchainEvents} from "@redux/blockchain-events";
import {subscribeToNotifications} from "@src/utils/subscribe-notifications-supabase.ts";

window.Buffer = Buffer;

Expand Down Expand Up @@ -103,10 +112,7 @@ export default function App() {
<ThemeProvider>
<MotionLazy>
<SnackbarProvider>
<SettingsDrawer />
<ProgressBar />
<Router />
<ResponsiveOverlay />
<AppContent />
</SnackbarProvider>
</MotionLazy>
</ThemeProvider>
Expand All @@ -117,3 +123,102 @@ export default function App() {
</MetaMaskProvider>
);
}


interface EventArgs {
recipient?: string;
origin?: string;
}
const AppContent = () => {
const dispatch = useDispatch();
const sessionData = useSelector((state: any) => state.auth.session);
const { getNotifications } = useNotifications();
const { enqueueSnackbar } = useSnackbar();

useEffect(() => {
// Set the global reference so we can call notify(...) anywhere.
setGlobalNotifier(enqueueSnackbar);
}, [enqueueSnackbar]);

const watchEvent = (eventName: string, args: EventArgs, logText: string) => {
const results = publicClientWebSocket.watchContractEvent({
address: GLOBAL_CONSTANTS.LEDGER_VAULT_ADDRESS,
abi: LedgerVaultAbi.abi,
eventName,
args,
onLogs: (logs) => {
console.log(logText, logs);
dispatch(setBlockchainEvents(logs));
},
});

console.log('Watching', eventName, 'events');
console.log('Results', results);

return results;
};

/**
* Deposit Deposited Verde Fuente, monto, TX.
* Transfer From Transfer from Verde Origen, monto, TX.
* Transfer To Transfer to Rojo Destino, monto, TX.
* Withdraw To Withdraw to Rojo Destino, monto, TX.
* Reserve To Reserved Amarillo Propósito, monto, TX.
* Collect From Collected Verde Origen, monto, TX.
* Locked Locked Azul Propósito, monto, TX.
* Release Released Verde Destino (si aplica), monto, TX.
* Claim Claimed Verde Propósito/acuerdo, monto, TX.
*/

useEffect(() => {
if (!sessionData?.address) return;

// @TODO Add the rest of the events
// Analiazed taking care of the user as the recipient or origin
const newEvents = [
{ name: 'FundsDeposited', args: { recipient: sessionData?.address }, logText: 'Deposited' },
{ name: 'FundsTransferFrom', args: { origin: sessionData?.address }, logText: 'Transfer from' },
{ name: 'FundsTransferTo', args: { recipient: sessionData?.address }, logText: 'Transfer to' },
{ name: 'FundsWithdrawTo', args: { recipient: sessionData?.address }, logText: 'Withdraw to' },
{ name: 'FundsReserved', args: { recipient: sessionData?.address }, logText: 'Reserved' },
{ name: 'FundsCollected', args: { origin: sessionData?.address }, logText: 'Collected' },
{ name: 'FundsLocked', args: { recipient: sessionData?.address }, logText: 'Locked' },
{ name: 'FundsReleased', args: { origin: sessionData?.address }, logText: 'Released' },
{ name: 'FundsClaimed', args: { recipient: sessionData?.address }, logText: 'Claimed' },
]

const events = [
{ name: 'FundsDeposited', args: { recipient: sessionData?.address }, logText: 'New deposit (user as recipient):' },
{ name: 'FundsWithdrawn', args: { origin: sessionData?.address }, logText: 'New withdraw (user as origin):' },
{ name: 'FundsTransferred', args: { origin: sessionData?.address }, logText: 'New transfer from me:' },
{ name: 'FundsTransferred', args: { recipient: sessionData?.address }, logText: 'New transfer to me:' },
];


const unwatchers = events.map(event => watchEvent(event.name, event.args, event.logText));

return () => {
unwatchers.forEach(unwatch => unwatch());
};
}, [sessionData?.address]);


useEffect(() => {
if (sessionData?.profile?.id) {
// Subscribe to notifications channel
subscribeToNotifications(sessionData?.profile?.id, dispatch, ['notifications']);

// Set the notifications in first render
getNotifications(sessionData?.profile?.id).then(() => {});
}
}, [sessionData?.profile?.id, dispatch]);

return (
<>
<SettingsDrawer />
<ProgressBar />
<Router />
<ResponsiveOverlay />
</>
)
}
89 changes: 1 addition & 88 deletions src/routes/sections/index.tsx
Original file line number Diff line number Diff line change
@@ -1,96 +1,9 @@
import { Navigate, useRoutes } from 'react-router-dom';
import { GLOBAL_CONSTANTS, PATH_AFTER_LOGIN } from '@src/config-global';
import { PATH_AFTER_LOGIN } from '@src/config-global';
import { dashboardRoutes } from './dashboard';
import NotFoundPage from '../../pages/404';
import { useEffect } from 'react';
import { subscribeToNotifications } from '@src/utils/subscribe-notifications-supabase.ts';
import { useDispatch, useSelector } from 'react-redux';
import { useNotifications } from '@src/hooks/use-notifications.ts';
import { publicClientWebSocket } from '@src/clients/viem/publicClient.ts';
import LedgerVaultAbi from '@src/config/abi/LedgerVault.json';
import { setBlockchainEvents } from '@redux/blockchain-events';
import { setGlobalNotifier } from '@notifications/internal-notifications.ts';
import { useSnackbar } from 'notistack';

export default function Router() {
const dispatch = useDispatch();
const sessionData = useSelector((state: any) => state.auth.session);
const { getNotifications } = useNotifications();
const { enqueueSnackbar } = useSnackbar();

useEffect(() => {
// Set the global reference so we can call notify(...) anywhere.
setGlobalNotifier(enqueueSnackbar);
}, [enqueueSnackbar]);

useEffect(() => {
if (!sessionData?.address) return;

// FundsDeposited (when i am the recipient)
const unwatchDeposit = publicClientWebSocket.watchContractEvent({
address: GLOBAL_CONSTANTS.LEDGER_VAULT_ADDRESS,
abi: LedgerVaultAbi.abi,
eventName: 'FundsDeposited',
args: { recipient: sessionData?.address },
onLogs: (logs) => {
console.log('New deposit (user as recipient):', logs);
dispatch(setBlockchainEvents(logs));
},
});

// FundsWithdrawn (when i am the origin)
const unwatchWithdraw = publicClientWebSocket.watchContractEvent({
address: GLOBAL_CONSTANTS.LEDGER_VAULT_ADDRESS,
abi: LedgerVaultAbi.abi,
eventName: 'FundsWithdrawn',
args: { origin: sessionData?.address },
onLogs: (logs) => {
console.log('New withdraw (user as origin):', logs);
dispatch(setBlockchainEvents(logs));
},
});

// FundsTransferred (when I send)
const unwatchTransferFrom = publicClientWebSocket.watchContractEvent({
address: GLOBAL_CONSTANTS.LEDGER_VAULT_ADDRESS,
abi: LedgerVaultAbi.abi,
eventName: 'FundsTransferred',
args: { origin: sessionData?.address },
onLogs: (logs) => {
console.log('New transfer from me:', logs);
dispatch(setBlockchainEvents(logs));
},
});

// FundsTransferred (when I receive)
const unwatchTransferTo = publicClientWebSocket.watchContractEvent({
address: GLOBAL_CONSTANTS.LEDGER_VAULT_ADDRESS,
abi: LedgerVaultAbi.abi,
eventName: 'FundsTransferred',
args: { recipient: sessionData?.address },
onLogs: (logs) => {
console.log('New transfer to me:', logs);
dispatch(setBlockchainEvents(logs));
},
});

return () => {
unwatchDeposit();
unwatchWithdraw();
unwatchTransferFrom();
unwatchTransferTo();
};
}, [sessionData?.address]);

useEffect(() => {
if (sessionData?.profile?.id) {
// Subscribe to notifications channel
subscribeToNotifications(sessionData?.profile?.id, dispatch, ['notifications']);

// Set the notifications in first render
getNotifications(sessionData?.profile?.id).then(() => {});
}
}, [sessionData?.profile?.id, dispatch]);

return useRoutes([
{
Expand Down

0 comments on commit cadae73

Please sign in to comment.