All projects

Top Hold / Marcus Mattus

Onchain Finance Intelligence & Tokenized Reserve Infrastructure powered by CRE. 3 workflows: (1) Tokenized RWA Proof of Reserve, (2) AI Risk Monitoring Agent, (3) Cross-Chain Liquidity Router. https://top-hold-opal.vercel.app/

DeFi & Tokenization CRE & AI Privacy Risk & Compliance Prediction Markets Tenderly

What it is

Top Hold https://top-hold-opal.vercel.app/ is an enterprise-grade mission control system for tokenized finance operations—a verifiable, searchable, map-aware financial infrastructure layer combining:

  • ✅ Cross-chain liquidity intelligence – Real-time flows across blockchains
  • ✅ Tokenized RWA reserve verification – Proof of reserves for real-world assets
  • ✅ AI-powered risk detection – Proactive anomaly detection with automated safeguards
  • ✅ Geographic intelligence – Global operations view via map-based entity tracking
  • ✅ Privacy-preserving treasury workflows – Confidential operations execution
    Position: Not just a visualization platform, but a verifiable, searchable financial infrastructure layer orchestrated by Chainlink Runtime Environment (CRE).
    🎯 CORE VALUE PROPOSITIONS
  1. Reserve Intelligence
    Real-time proof of reserves for tokenized assets with custodian/bank verification
  2. Risk Intelligence
    AI-powered anomaly detection that automatically triggers safeguards when thresholds are exceeded
  3. Route Intelligence
    Cross-chain bridge optimization with cost calculation and safety scoring
  4. Geographic Intelligence
    Global map-based operational monitoring of reserve vaults, bridge endpoints, and risk hotspots
  5. Security Intelligence
    Searchable compliance and risk monitoring with audit trails

How it Works

Frontend Architecture
The frontend of Top Hold is built as a modern, type-safe React application using TypeScript and Vite as the build tool. The entire codebase compiles with ES2020 target, allowing for contemporary JavaScript features while maintaining broad browser compatibility. React 19 serves as the core framework, providing a component-based UI structure that enables rapid development and maintainability. The project uses strict TypeScript configuration with full null checking enabled, enforcing type safety throughout the entire application. Path aliases are configured to allow clean imports from the @/ prefix pointing to the src/ directory, improving code readability and reducing relative path complexity.
The styling approach leverages Tailwind CSS v4 with the official Vite plugin integration, enabling utility-first CSS without requiring a separate PostCSS configuration step. The design system is built around OKLCH color space, chosen for perceptual uniformity and better accessibility across different viewing conditions. Primary colors include Deep Slate for backgrounds and primary elements, Electric Teal for accent elements, with supporting colors for status indicators (green for success, amber for warnings, red for destructive actions). The color palette is defined in the tailwind.config.js file, providing consistent theming across all components.
Typography is configured with two font families optimized for different use cases: Space Grotesk for UI elements (weights 400-700) and JetBrains Mono for data display and financial information (weights 400-500). This distinction ensures financial data renders with appropriate monospace clarity while maintaining readability in navigation and labels. Vite is configured to serve the application during development with hot module replacement (HMR) support, enabling rapid iteration during development. The build process produces optimized assets using Vite's rollup-based bundler with appropriate code splitting and asset optimization.
Component Library and UI Foundation
Top Hold integrates shadcn/ui v4, a comprehensive component library built on Radix UI primitives and Tailwind CSS styling. The project includes over 40 pre-integrated components covering all major UI patterns: modals (AlertDialog, Dialog), navigation (Menubar, NavigationMenu, ContextMenu), data display (Tabs, Accordion, Table variants), form controls (Checkbox, RadioGroup, Select, Slider, Toggle, ToggleGroup), and specialized layouts (AspectRatio, ScrollArea, Separator). Each component is customizable while maintaining consistency with the design system.
The component configuration is managed through components.json, which defines component paths, aliases, and import settings. Radix UI provides the accessible, unstyled primitives upon which shadcn components are built, ensuring WCAG 2.1 AA accessibility standards. Form handling uses the @hookform/resolvers library integrated with Zod for schema validation, enabling declarative, type-safe form management. The Sonner library provides toast notifications for user feedback, configured to work seamlessly with the Dark Slate and Electric Teal color scheme.
Phosphor Icons provide the operational aesthetic throughout the interface, offering 30+ outlined and filled icon variants for consistent visual communication. Icon selection emphasizes clarity and operational context, making complex financial states immediately interpretable. Component composition follows React best practices with proper prop typing, memo optimization where appropriate, and clean separation of concerns between display components and container components that manage state and side effects.
State Management and Data Flow
React Query (TanStack Query) v5 provides server state management, handling data fetching, caching, synchronization, and real-time updates from external APIs and blockchain sources. React Query's advanced caching strategies allow efficient background synchronization of reserve data, risk metrics, and route information without overwhelming the UI with requests. The library's built-in request deduplication prevents race conditions when multiple components request the same data simultaneously.
Local state management uses React Hooks exclusively, with custom hooks encapsulating complex state logic and side effects. The application avoids global state management libraries, relying instead on React Context for application-level values like authentication, user preferences, and theme settings. This approach maintains simplicity while avoiding context-related re-render pitfalls through proper memoization strategies.
Key-value persistence uses browser localStorage and IndexedDB for storing user preferences, cached API responses, and temporary workflow state. localStorage handles simple key-value pairs like user settings and theme preferences, while IndexedDB manages larger datasets like historical reserve data and transaction logs. IndexedDB transactions use proper error handling and quota management to prevent exceeding browser storage limits.
Real-time data synchronization is managed through WebSocket connections for live updates from the CRE network about workflow execution status, reserve health changes, and risk alerts. The application implements automatic reconnection with exponential backoff when WebSocket connections drop, ensuring resilient real-time communication. React hooks handle WebSocket lifecycle management, properly cleaning up listeners and connections when components unmount.
Map Visualization Layer
The Universe View map interface is built using @vis.gl/react-google-maps, providing interactive Google Maps integration with custom layers for displaying financial entities, reserve vaults, and bridge endpoints. The map renders geospatial data as custom markers, clustering nodes at higher zoom levels to maintain performance with hundreds or thousands of entities. Each marker displays real-time information about reserve health, TVL, risk score, and network status through interactive info windows.
D3.js provides advanced data visualization capabilities for supplementary displays like reserve trend lines, risk heatmaps, and bridge reliability charts. D3's data binding model enables efficient updates when data changes, ensuring smooth animations and transitions as metrics update. Custom D3 components are wrapped in React to integrate with the component lifecycle and prevent direct DOM manipulation conflicts.
The map view supports multiple overlays that users can toggle on and off: reserve health (showing reserve ratios per location), risk heatmap (color-coded by risk level), bridge reliability (showing success rates and latency), and liquidity flows (animated paths showing cross-chain movement). Users can click on entities to view detailed information, access drill-down analytics, and trigger actions like manual reserve verification or route recalculation. The map automatically zooms to regions with high-risk alerts, drawing operator attention to critical situations.
Blockchain Interaction Layer
Blockchain interaction uses ethers.js v6 for contract interaction, allowing the frontend to read state from smart contracts and submit transactions. The application maintains multiple RPC connections to prevent single points of failure, with automatic failover when a provider becomes unresponsive. The contract interface definitions are auto-generated from ABI files using TypeChain, providing full type safety for contract interactions in TypeScript.
Smart contract state is queried efficiently using multicall aggregation patterns, reducing the number of RPC calls needed to fetch complex nested state. The application caches contract state locally and uses event listeners to detect state changes, updating the cache without requiring full state re-fetches. Custom hooks abstract contract interaction logic, providing clean interfaces for components to query and modify contract state.
Transaction submission includes comprehensive error handling for common failure modes: insufficient gas, contract reverts, network congestion, and user rejection. The application displays clear error messages to users with suggested actions (e.g., increase gas limit, check contract parameters). Pending transactions are tracked in local state, providing real-time feedback on transaction progress and estimated completion time.
API Integration and External Data Sources
External API integration is implemented through a centralized API client that handles authentication, request transformation, error handling, and rate limiting. The client supports multiple authentication schemes including API keys, OAuth 2.0, and mTLS certificates for bank and custodian integrations. Sensitive credentials are never stored in the client; instead, requests are proxied through the backend or CRE for secure credential handling.
The application integrates with custodian APIs to fetch real-world asset reserve balances, bank APIs to verify banking details, bridge aggregator APIs to fetch current bridge pricing and liquidity, and blockchain RPC endpoints to read on-chain state. Each API integration includes proper error handling, timeout management, and circuit breaker patterns to prevent cascading failures when external services become unavailable.
Rate limiting is implemented client-side with request queuing, respecting API rate limits to avoid service interruptions. When rate limits are exceeded, the application queues requests and retries them with exponential backoff. Server-side rate limiting through the backend API ensures fair usage across all users of the system.
Chainlink Runtime Environment (CRE) Integration
The CRE integration represents the core orchestration layer that powers Top Hold's three main workflows. The CRE SDK is used to define workflows that are compiled into WebAssembly (WASM) binaries and executed across the Chainlink Decentralized Oracle Network. Each workflow uses the trigger-and-callback model, where a trigger event (time-based cron, blockchain event, or HTTP webhook) initiates a callback function containing the business logic.
The Reserve Health Monitoring workflow is defined in YAML and executed by the CRE every five minutes via cron trigger. The callback function creates an HTTP client to fetch custodian balance data using encrypted credentials, creates a blockchain client to read the onchain token supply from the smart contract, and aggregates this data to compute the current reserve ratio. The callback then invokes an LLM capability to analyze the reserve health using OpenAI GPT-4, which returns a risk classification and recommended action. Finally, the callback writes the computed reserve ratio and health status to the ReserveHealthOracle smart contract, creating an on-chain audit trail.
The AI Risk Monitoring workflow is triggered by blockchain events (large transfers, TVL drops) and external webhooks (API anomalies). The callback function retrieves recent transaction history and liquidity metrics, analyzes them using the LLM to classify risk severity and likelihood of systemic impact, and optionally triggers the RiskGuardian smart contract to pause vault operations or increase collateral requirements if risk exceeds configured thresholds. All actions are logged for compliance and post-incident analysis.
The Cross-Chain Route Orchestration workflow is initiated when users request a cross-chain transfer. The callback function queries multiple bridge APIs in parallel to fetch current fees, liquidity, and estimated execution times. An optimization algorithm selects the cheapest and fastest route, simulates the route execution on Tenderly Virtual TestNets, and writes the optimal route hash to the RouteRegistry smart contract. The on-chain route serves as the execution plan for bridge relayers or allows the user to manually execute the route knowing it has been verified safe.
All CRE workflows include proper error handling, logging, and retry logic. Failed operations are logged to a dead-letter queue for manual review. The CRE CLI is used to compile workflows into WASM, simulate them locally for testing, and deploy them to the Chainlink DON when ready for production operation.
Smart Contract Architecture
The smart contracts are written in Solidity with full test coverage using Hardhat and ethers.js for JavaScript-based testing. The ReserveHealthOracle contract stores the verified reserve ratio, health status, and update timestamp for each tokenized RWA asset. The contract includes role-based access control (RBAC) restricting write access to authorized CRE operators, with separate roles for different operational functions. Events are emitted for all state changes, providing an on-chain audit trail.
The RiskGuardian contract implements a system of configurable thresholds for risk metrics (reserve ratio minimum, TVL drop maximum, liquidity concentration limits). When risk exceeds thresholds, the contract triggers automated responses: pausing vault withdrawals, increasing collateral requirements, or triggering liquidation protections. The contract is upgradeable using UUPS proxy pattern, allowing protocol improvements without redeploying or migrating state.
The RouteRegistry contract stores optimized cross-chain routes with metadata including fee estimates, liquidity availability, and estimated execution time. Routes are stored as hashes with associated metadata to minimize on-chain storage costs. The contract includes a time-based expiration mechanism, marking routes as stale after 1 hour to prevent use of outdated pricing information.
All contracts include comprehensive NatSpec documentation, allowing automated tools to generate human-readable interfaces. Contracts are deployed to multiple chains (Ethereum mainnet, Arbitrum, Optimism, Polygon) using a standardized deployment script that handles environment-specific configuration and verification. Post-deployment, contracts are verified on block explorers to enable public audit and usage.
Development Tools and Workflow
The development environment uses Node.js with npm as the package manager, with a lock file ensuring reproducible builds across environments. ESLint enforces code style rules, preventing common mistakes and maintaining consistency. TypeScript strict mode is enabled, catching type-related errors at compile time rather than runtime. Pre-commit hooks run linting and type checking, preventing commits with errors.
Vite development server provides instant feedback during development with hot module replacement (HMR), allowing developers to see changes immediately without full page refreshes. The development server is configured to proxy API requests to backend services, avoiding CORS issues during development. Build performance is optimized through Vite's esbuild-based transpilation, enabling near-instant cold starts.
Testing infrastructure uses Vitest for unit tests and Cypress for end-to-end testing. Tests are organized alongside source files with .test.ts extensions, making it easy to locate tests for specific components. Test coverage is tracked and enforced through CI/CD pipelines, preventing merges of code that reduces coverage below configured thresholds.
CI/CD pipelines use GitHub Actions to automatically run tests, linting, and type checking on pull requests. Deployments are triggered automatically on commits to main branch, deploying to staging for QA and then to production after manual approval. Deployment environments are managed through .env files specific to each environment (development, staging, production), with secrets managed through GitHub Secrets.
Performance Optimization
Code splitting is configured to generate separate bundles for vendor dependencies, framework code, and application code. This prevents cache busting of expensive dependencies when application code changes. Route-based code splitting loads different features on-demand, reducing initial bundle size. Lazy loading of heavy components like D3-based visualizations and map libraries ensures fast initial page load.
Image optimization uses modern formats (WebP, AVIF) with fallbacks for older browsers. SVG icons are inlined to reduce HTTP requests. Component memoization using React.memo prevents unnecessary re-renders when parent components update. Custom hooks use proper dependency arrays to prevent unnecessary effect executions.
Bundle size is monitored through build analysis tools, alerting developers when bundle size grows unexpectedly. Third-party dependencies are audited for size, and lighter alternatives are considered when dependencies exceed size budgets. Tree-shaking is verified through build output analysis to ensure unused code is eliminated.
Security Considerations
The application implements Content Security Policy (CSP) headers to prevent XSS attacks, restricting script sources to trusted domains and disabling inline scripts. Sensitive data like private keys and API credentials are never stored client-side; sensitive operations are proxied through the backend or CRE. All user inputs are sanitized before rendering or use in API calls, preventing injection attacks.
API requests include CSRF tokens to prevent cross-site request forgery attacks. Authentication tokens are stored in HTTP-only cookies with secure and same-site flags, preventing access from JavaScript and limiting exposure in CSRF attacks. Token refresh is handled automatically by the authentication layer, maintaining a current valid token for all API requests.
The application uses Subresource Integrity (SRI) for CDN-hosted dependencies, ensuring that external resources have not been modified. Third-party scripts are loaded with the async attribute to prevent blocking page rendering. Service Worker implementation (if used) is configured carefully to cache only safe resources and avoid caching sensitive data.

Links

Created by

  • marcus matters