This implementation adds comprehensive error monitoring and logging for wallet operations using Sentry. The system tracks wallet connection errors, transaction failures, and other critical wallet events while protecting user privacy by redacting sensitive information.
Client-side Sentry configuration for Next.js applications:
- Performance monitoring with configurable sampling rates
- Session replay for debugging user interactions
- PII filtering to protect sensitive data
- Error filtering to ignore expected errors (user cancellations, network issues)
Helper functions for Sentry integration:
initSentry()- Initialize Sentry clientcaptureWalletError()- Capture wallet-specific errors with contextcaptureWalletEvent()- Track wallet events (success, warnings)addWalletBreadcrumb()- Add breadcrumbs for operation trackingsetSentryUser()- Set user context for error reportsredactAddress()- Redact wallet addresses for logging
Lightweight error tracking utility that works with or without Sentry:
- Falls back to console logging if Sentry is not available
- PII redaction for all logged data
- Structured logging for wallet operations
- React hook for easy integration
Key Functions:
captureWalletError(error, operation, context)- Capture errors with contextcaptureWalletEvent(event, context)- Track eventsaddWalletBreadcrumb(message, category, data)- Add breadcrumbslogWalletOperation(operation, status, data)- Log operationswithWalletErrorTracking(fn)- Wrap functions with error trackingsetWalletUserContext(user)- Set user context
Error tracking added to all wallet operations:
connectMetaMask()- MetaMask connection errorsconnectPhantom()- Phantom connection errorsconnectStellar()- Stellar wallet creation/connection errorsimportStellarKey()- Secret key import errors
Error tracking added to multi-wallet operations:
addWallet()- Wallet addition errorsremoveWallet()- Wallet removal errorsswitchWallet()- Wallet switching errorssetPrimaryWallet()- Primary wallet change errorsupdateWallet()- Wallet metadata update errors
npm install @sentry/nextjsAdd to .env.local:
# Sentry DSN (get from Sentry.io)
NEXT_PUBLIC_SENTRY_DSN=https://your-dsn@sentry.io/project-id
# Environment (development, staging, production)
NEXT_PUBLIC_SENTRY_ENVIRONMENT=production
# Release identifier (optional, uses git commit SHA on Vercel)
NEXT_PUBLIC_SENTRY_RELEASE=v1.0.0The Sentry configuration is automatically loaded by Next.js when you create the config files:
sentry.client.config.ts- Client-side configurationsentry.server.config.ts- Server-side configuration (optional)sentry.edge.config.ts- Edge runtime configuration (optional)
import { captureWalletError, logWalletOperation } from "@/app/lib/walletErrorTracking";
try {
await someWalletOperation();
logWalletOperation("operation_name", "success", { walletAddress: "0x..." });
} catch (error) {
captureWalletError(error, "operation_name", {
walletType: "metamask",
walletAddress: "0x...",
});
throw error;
}import { useWalletErrorTracking } from "@/app/lib/walletErrorTracking";
function MyComponent() {
const { captureError, logOperation, addBreadcrumb } = useWalletErrorTracking();
const handleConnect = async () => {
addBreadcrumb("Starting wallet connection", "wallet");
try {
await connectWallet();
logOperation("connect_wallet", "success", { walletType: "metamask" });
} catch (error) {
captureError(error, "connect_wallet", { walletType: "metamask" });
}
};
return <button onClick={handleConnect}>Connect</button>;
}import { withWalletErrorTracking } from "@/app/lib/walletErrorTracking";
const connectWallet = withWalletErrorTracking(
"connect_wallet",
async () => {
// Your wallet connection logic
}
);User context is automatically set in MultiWalletProvider when a user authenticates. For manual context setting:
import { setWalletUserContext } from "@/app/lib/walletErrorTracking";
// Set user context
setWalletUserContext({ id: "user-123", email: "user@example.com" });
// Clear user context
setWalletUserContext(null);connect_metamask- MetaMask wallet connectionconnect_phantom- Phantom wallet connectionconnect_stellar- Stellar wallet creation/connectionimport_stellar_key- Stellar secret key import
add_wallet- Add wallet to multi-wallet listremove_wallet- Remove wallet from listswitch_wallet- Switch active walletset_primary_wallet- Set primary walletupdate_wallet- Update wallet metadata
send_payment- Send XLM paymentfund_wallet- Fund wallet via Friendbotrefresh_balance- Refresh wallet balance
All sensitive data is automatically redacted before logging:
- Wallet Addresses: Shows first 6 and last 4 characters (e.g.,
0x1234...5678) - Email Addresses: Shows first character and domain (e.g.,
j***@example.com) - Secret Keys: Completely redacted (
[REDACTED]) - Private Keys: Completely redacted (
[REDACTED]) - Mnemonic Phrases: Completely redacted (
[REDACTED])
Sentry is configured to ignore expected errors:
ignoreErrors: [
"Network request failed",
"Failed to fetch",
"User rejected the request",
"User cancelled the request",
"Extension context invalidated",
]Performance monitoring is enabled with configurable sampling rates:
// Production: 10% of transactions
tracesSampleRate: 0.1
// Development: 100% of transactions
tracesSampleRate: 1.0Session replay captures user interactions for debugging:
// Production: 10% of sessions
replaysSessionSampleRate: 0.1
// All error sessions
replaysOnErrorSampleRate: 1.0Privacy Settings:
- Mask all text:
false(allows reading UI text) - Mask all inputs:
true(protects sensitive input) - Block all media:
true(protects images/videos)
- Full performance tracing (100%)
- Full session replay (100%)
- Console logging enabled
- Sentry DSN optional (falls back to console)
- Sampled performance tracing (10%)
- Sampled session replay (10%)
- Error-only session replay (100%)
- Sentry DSN required
Error tracking works alongside the existing analytics system:
import analytics from "@/lib/analytics";
import { captureWalletError } from "@/app/lib/walletErrorTracking";
try {
await connectWallet();
// Track success in analytics
analytics.trackWalletConnect("metamask");
} catch (error) {
// Track error in Sentry
captureWalletError(error, "connect_metamask", { walletType: "metamask" });
// Track failure in analytics
analytics.trackEvent('wallet_connection_failed', { wallet_type: 'metamask' });
}Without a Sentry DSN configured, the system falls back to console logging:
// Console output:
[Wallet Error] connect_metamask Error: MetaMask is not installed
{
operation: "connect_metamask",
walletType: "metamask",
walletAddress: "[REDACTED]"
}To test Sentry integration:
- Configure
NEXT_PUBLIC_SENTRY_DSN - Trigger a wallet error (e.g., try to connect without MetaMask installed)
- Check Sentry dashboard for the error report
- Check
NEXT_PUBLIC_SENTRY_DSNis set correctly - Verify Sentry is initialized (check browser console for Sentry logs)
- Ensure error is not in the
ignoreErrorslist - Check network connectivity to Sentry
Adjust sampling rates in sentry.client.config.ts:
// Reduce performance monitoring
tracesSampleRate: 0.05 // 5% instead of 10%
// Reduce session replay
replaysSessionSampleRate: 0.05 // 5% instead of 10%Ensure all sensitive fields are redacted:
- Check custom context objects for PII
- Verify breadcrumbs don't contain secrets
- Review error messages for embedded sensitive data
- All wallet addresses are redacted before logging
- Secret keys are never logged
- User emails are partially redacted
- Custom context data is sanitized
Configure data retention in Sentry:
- Error events: 30-90 days
- Performance data: 30 days
- Session replays: 7-30 days
- Restrict Sentry access to authorized team members
- Use Sentry's team-based access controls
- Enable IP allowlisting for production
- Use Sentry's data scrubbing features
- New:
sentry.client.config.ts- Sentry client configuration - New:
app/lib/sentry.ts- Sentry helper utilities - New:
app/lib/walletErrorTracking.ts- Wallet error tracking utility - Modified:
components/WalletProvider.tsx- Added error tracking to wallet operations - Modified:
components/MultiWalletProvider.tsx- Added error tracking to multi-wallet operations
- Server-Side Monitoring: Add server-side Sentry configuration for API routes
- Custom Alerting: Configure Sentry alerts for critical wallet errors
- Dashboards: Create Sentry dashboards for wallet operation metrics
- Error Rate Monitoring: Set up error rate alerts for wallet operations
- Performance Budgets: Configure performance budgets for wallet operations