Smart Contract Data System
The smart contract data system forms the blockchain interaction layer of RitoSwap, managing real-time synchronization between on-chain NFT state and the user interface. This sophisticated architecture combines wagmi hooks, TanStack Query, and Zustand state management to deliver responsive, accurate token data across the application.
System Overview
RitoSwap’s architecture requires seamless integration between smart contracts deployed across multiple networks and the React-based user interface. The smart contract data system accomplishes this through a carefully orchestrated stack of technologies that work together to provide real-time updates, efficient caching, and consistent state management.
Core Architecture Components
The system consists of four primary layers that work in harmony:
- Contract Configuration Layer - Manages contract addresses and ABIs across networks
- Blockchain Interaction Layer - Uses wagmi hooks for reading and writing contract data
- Data Synchronization Layer - Leverages TanStack Query for intelligent caching and polling
- State Management Layer - Maintains application state through Zustand stores
This layered approach ensures that blockchain data flows efficiently from smart contracts to UI components while maintaining consistency and performance.
Data Flow Architecture
Understanding how data flows through the system is crucial for effective development:
Step 1: Contract Address Resolution
The system determines which contract address to use based on environment configuration, selecting between local RitoNet, Sepolia testnet, or Ethereum mainnet.
Step 2: Blockchain Query
Wagmi hooks query the appropriate smart contract using the resolved address and ABI, fetching token ownership and metadata.
Step 3: Data Synchronization
TanStack Query manages the caching and synchronization of blockchain data with the off-chain database through API endpoints.
Step 4: State Updates
The NFT store receives updates from the data layer and propagates changes to subscribed React components.
Step 5: UI Rendering
Components reflect the current state, showing token ownership, colors, and usage status in real-time.
Integration with Broader Ecosystem
The smart contract data system doesn’t operate in isolation. It forms critical connections with other parts of the RitoSwap architecture:
Smart Contract Deployment
Contract addresses are automatically managed through the monorepo’s deployment system. When contracts are deployed via the colored-keys workspace, addresses are saved to JSON files stored in the root workspace (one folder level above dapp
or `colored-keys“) that the dApp references:
- local-blockchain.json
- hardhat.json
- mainnet.json
- sepolia.json
This automation ensures contract addresses remain synchronized between deployment and application configuration.
API Integration
The smart contract data system works closely with RitoSwap’s API endpoints to maintain consistency between on-chain and off-chain state:
- Token Status API - Synchronizes on-chain existence with database records
- Gate Access API - Verifies ownership before granting access to gated content
- Verify Token Gate API - Updates usage records after successful verification
These endpoints rely on the same contract configuration and use identical blockchain queries to ensure data consistency.
Database Synchronization
While smart contracts maintain the authoritative state for token ownership, the Prisma database layer tracks additional metadata like usage status. The smart contract data system bridges these two sources of truth, ensuring they remain synchronized through careful orchestration of queries and updates.
Key Technologies
Wagmi
Wagmi provides type-safe React hooks for Ethereum interactions. The system uses several key wagmi hooks:
Hook | Purpose | Usage in RitoSwap |
---|---|---|
useAccount | Manages wallet connection state | Determines if user is connected and provides their address |
useReadContract | Reads data from smart contracts | Fetches token ownership and color metadata |
useWriteContract | Sends transactions to contracts | Handles minting and burning operations |
useWaitForTransactionReceipt | Monitors transaction confirmations | Provides feedback during minting/burning processes |
TanStack Query
TanStack Query enhances the blockchain querying experience through intelligent caching and deduplication. In RitoSwap, it specifically manages token usage status queries, preventing redundant API calls when multiple components request the same data.
Zustand
Zustand provides lightweight state management that bridges the gap between blockchain queries and React components. The NFT store maintains current token state, handles account switching scenarios, and persists critical data like token gate usage across sessions.
Component Architecture
The smart contract data system supports two primary interaction patterns:
Read Operations
Components like NFTScreen
display token state without modifying it. These components subscribe to the NFT store and react to state changes, showing appropriate UI based on token ownership and metadata.
Write Operations
Components like ButtonSection
enable users to mint and burn tokens. These components orchestrate complex flows involving transaction initiation, wallet interactions, confirmation monitoring, and state updates.
Performance Considerations
The system implements several strategies to ensure optimal performance:
Intelligent Polling - Adjusts polling frequency based on user activity and account switching states to balance responsiveness with resource usage.
Request Deduplication - TanStack Query automatically deduplicates simultaneous requests for the same data, reducing unnecessary blockchain queries.
Selective Re-rendering - Components subscribe only to specific store slices, preventing unnecessary re-renders when unrelated state changes.
Development Workflow
When working with the smart contract data system, follow these patterns for consistency:
Reading Contract Data
// Use the custom hook for comprehensive NFT data
const { forceRefresh, isLoading } = useNFTData();
// Access store state in components
const { hasNFT, tokenId, backgroundColor, keyColor } = useNFTStore();
Writing Contract Data
// Use wagmi hooks with proper error handling
const { writeContract, isPending, error } = useWriteContract();
// Execute with network validation
executeWithNetworkCheck(() => {
writeContract({
address: KEY_TOKEN_ADDRESS,
abi: fullKeyTokenAbi,
functionName: 'mint'
});
});
Handling State Updates
// Let the useNFTData hook manage state synchronization
useEffect(() => {
if (transactionSuccess) {
forceRefresh(); // Triggers comprehensive state update
}
}, [transactionSuccess]);
Error Handling and Recovery
The system implements robust error handling at multiple levels:
Contract Errors - Wagmi hooks provide detailed error information for failed transactions, which components display through toast notifications.
Network Mismatches - The network check hook prevents transactions on incorrect networks, guiding users to switch chains.
State Recovery - The account switching mechanism preserves token state during wallet changes, preventing UI flashing and data loss.
Fallback Rendering - Components implement loading and error states to maintain usability even when blockchain queries fail.
Testing Considerations
Effective testing of the smart contract data system requires understanding its asynchronous nature:
The system’s reliance on real blockchain state makes traditional unit testing challenging. Consider using mock providers for wagmi hooks and controlling TanStack Query’s cache during tests to ensure predictable behavior.
Key testing strategies include:
- Mocking wagmi providers to simulate various blockchain states
- Using TanStack Query’s test utilities to control cache behavior
- Testing state transitions in the NFT store independently
- Implementing integration tests that verify the complete data flow
Summary
The smart contract data system represents a sophisticated integration of modern Web3 technologies, delivering real-time blockchain data to React components through carefully orchestrated layers of caching, state management, and error handling. By understanding how contract configuration, wagmi hooks, TanStack Query, and Zustand work together, developers can effectively build features that seamlessly bridge the gap between smart contracts and user interfaces.
The system’s design prioritizes developer experience through type safety, predictable state updates, and comprehensive error handling while maintaining the performance and reliability required for production blockchain applications.