On-chain treasuries, managed by DAOs, protocols, or grant programs, represent a significant shift in how organizations control capital. Unlike traditional finance, these funds are stored in smart contracts on public blockchains like Ethereum, Arbitrum, or Optimism. This creates an unprecedented level of transparency, as every transaction is recorded on a public ledger. However, this raw data is not inherently understandable. A Treasury Activity and Spending Monitor is a tool that aggregates, analyzes, and presents this data in a human-readable format, enabling stakeholders to track fund flows, proposal execution, and overall financial health without needing to parse blockchain explorers manually.
Launching a Treasury Activity and Spending Monitor
Introduction
A practical guide to setting up a real-time monitor for on-chain treasury transactions and spending proposals.
The core function of a monitor is to track two primary activities: proposals and executed transactions. Proposals, often created through governance platforms like Snapshot or Tally, outline intended spending. The monitor tracks their lifecycle from submission to voting to execution. Once a proposal passes and is executed on-chain—for example, transferring 100 ETH to a vendor's wallet—the monitor captures this transaction, linking it back to the original proposal. This creates a clear audit trail. Key metrics to monitor include treasury balance over time, outflow by category (e.g., grants, development, marketing), top recipient addresses, and voting participation rates for spending proposals.
Setting up a monitor typically involves several technical components. First, you need a reliable data source, which can be a blockchain node RPC endpoint, a subgraph from The Graph for indexed event data, or an API from a service like Covalent or Dune Analytics. Second, a backend service (written in languages like JavaScript/TypeScript with Ethers.js or Python with Web3.py) listens for new blocks or queries indexed data, processing events from the treasury's Governor contract and Treasury contract. Finally, a frontend dashboard visualizes the data. For developers, a basic implementation might start with a script that polls a subgraph and logs large transactions to a Discord webhook, providing immediate, actionable alerts.
Beyond basic tracking, advanced monitors implement risk detection and compliance rules. These can be programmed to flag unusual activity, such as a transaction exceeding a predefined threshold without a linked proposal, funds moving to a blacklisted address, or a sudden depletion of a specific asset pool. Using multi-signature wallet events from Gnosis Safe or an on-chain governor's timelock can add layers of oversight. For example, a monitor could alert when a proposal is queued in a timelock, giving the community a final window to review the exact calldata before it executes. This transforms the monitor from a passive viewer into an active governance safeguard.
This guide provides the conceptual framework and practical steps to build such a system. We will cover how to identify the relevant smart contracts, choose a data indexing strategy, write event listeners for proposal creation and execution, calculate key treasury metrics, and set up alerts. The goal is to empower developers and community stewards to create tailored transparency tools that bolster trust and informed decision-making in decentralized organizations.
Prerequisites and Tech Stack
Before building a treasury activity and spending monitor, you need the right tools and foundational knowledge. This guide outlines the essential prerequisites and the modern tech stack required to track on-chain treasury operations effectively.
To build a robust treasury monitor, you must first understand the core components of on-chain treasuries. This includes knowledge of multi-signature wallets (like Safe), DAO governance frameworks (such as OpenZeppelin Governor), and treasury management protocols (like Llama). You should be comfortable reading transaction data, understanding proposal lifecycles, and interpreting smart contract events. Familiarity with common treasury actions—like token swaps, payroll distributions, and grant payments—is crucial for designing relevant monitoring logic.
Your development environment requires specific tools. You'll need Node.js (v18 or later) and a package manager like npm or yarn. For interacting with blockchains, install essential libraries: ethers.js v6 or viem for EVM chains, and potentially @solana/web3.js for Solana. A local development chain is invaluable for testing; use Foundry's Anvil or Hardhat Network to fork mainnet state and simulate transactions without spending real gas. Version control with Git and a code editor like VS Code complete the basic setup.
The monitoring application's backend will rely on a stack for data indexing and serving. For most projects, this involves using a Graph Protocol subgraph to index historical treasury events or a RPC provider (like Alchemy, Infura, or a private node) for real-time data. You'll need a database to store processed information; PostgreSQL or TimescaleDB are strong choices for time-series financial data. An API framework (like Express.js or Fastify) will expose endpoints, and a task runner (like BullMQ with Redis) can handle scheduled data aggregation and alerting jobs.
For the frontend or dashboard interface, a modern framework like React or Next.js is standard. Use a state management library such as Zustand or TanStack Query to handle asynchronous blockchain data. Integrate a charting library like Recharts or Chart.js to visualize cash flows and spending categories. To connect to user wallets for permissioned views, incorporate a connector library like RainbowKit or ConnectKit, which abstract wallet provider interactions across multiple chains.
Finally, consider operational and security prerequisites. You will need API keys from your chosen RPC and data providers. For production deployment, set up environment variable management and implement rate limiting on public endpoints. If monitoring involves sensitive financial data, plan for authentication and authorization. Understanding how to verify smart contract ABIs and source code for the treasuries you track is also a key security step to ensure data accuracy and integrity.
Core System Components
Essential tools and protocols for launching a transparent, on-chain treasury activity and spending monitor.
Launching a Treasury Activity and Spending Monitor
This guide explains the core components and data flow for building a system to track on-chain treasury transactions and spending patterns for DAOs and protocols.
A treasury activity monitor is a specialized analytics tool that aggregates, processes, and visualizes financial transactions from a protocol's on-chain treasury. Its primary function is to provide transparency into fund inflows, outflows, and holdings. The system architecture typically consists of three layers: a data ingestion layer that pulls raw blockchain data, a processing and storage layer that transforms and indexes this data, and an application layer that provides an interface for queries and dashboards. This separation of concerns ensures scalability and maintainability.
The data ingestion layer is responsible for sourcing information. It connects to blockchain nodes via RPC providers like Alchemy or Infura to listen for events and query historical data. For Ethereum-based treasuries, key data sources include direct ETH transfers, ERC-20 token transfers, and events from governance contracts like Gnosis Safe or Compound's Governor. A robust ingestion service uses a combination of real-time event listeners and batch historical backfills to build a complete dataset, handling chain reorganizations and ensuring data consistency.
Once raw data is captured, the processing layer structures it into a queryable format. This involves decoding complex transaction inputs using ABI files, calculating token values in a stable denomination like USD using price oracles, and categorizing transactions (e.g., payroll, grants, investment). Processed data is then stored in a time-series database like TimescaleDB or a data warehouse. This layer is where business logic is applied, such as calculating runway based on burn rate or identifying the top recipients of treasury funds over a custom period.
The final component is the application programming interface (API) and frontend. A GraphQL or REST API exposes endpoints for querying aggregated metrics, transaction histories, and wallet balances. The frontend, often built with frameworks like React or Vue, uses this API to render interactive charts and tables. For example, a dashboard might show a pie chart of spending categories, a line graph of net treasury value over time, and a list of recent high-value transactions with links to Etherscan for verification.
Security and reliability are critical in the architecture. The system should implement rate limiting on public APIs, use secure environment variables for RPC endpoints and private keys, and run data integrity checks. For production systems, deploying the ingestion and processing services as containerized applications with orchestration tools like Kubernetes ensures high availability. The end result is a reliable, transparent view into treasury health, empowering stakeholders to make informed governance decisions.
Step 1: Building the Transaction Indexer
The foundation of a treasury monitor is a robust indexer that ingests and structures on-chain transaction data for analysis.
A transaction indexer is a specialized service that listens to blockchain events, processes raw transaction data, and stores it in a queryable database. Unlike a simple block explorer, a custom indexer allows you to define precisely which smart contracts, wallet addresses, and event types you want to track. For treasury monitoring, you would typically index transactions involving the treasury's multisig wallet or DAO vault contracts, focusing on functions like executeTransaction, transfer, or swap. This setup transforms the chaotic stream of blockchain data into a structured dataset ready for analysis.
You can build this using several approaches. A common method is to use The Graph with a custom subgraph, which handles the heavy lifting of event listening and historical indexing. Alternatively, for more control, you can write a script using Ethers.js or Viem that listens to an RPC provider's WebSocket endpoint. The script would filter for events from your target addresses, decode the log data using the contract's ABI, and insert the parsed information—like sender, recipient, amount, asset, and function called—into a PostgreSQL or TimescaleDB database. This database becomes your single source of truth for all treasury activity.
Key technical decisions include choosing an RPC provider for reliable data access (e.g., Alchemy, Infura, QuickNode) and designing your database schema. Your schema should capture essential fields: block_number, timestamp, tx_hash, from_address, to_address, value, token_address, and method_name. For complex DAO transactions, you may also need to parse calldata to understand the nested actions being executed. Implementing robust error handling and a mechanism to backfill missed blocks is crucial for data integrity.
Once operational, your indexer provides the raw material for all subsequent analysis. You'll have a real-time feed of every inflow and outflow, which you can then categorize, tag, and analyze for patterns. This step moves you from reactive manual checking of Etherscan to having a proactive, automated data pipeline. The next steps—enriching this data with labels, calculating metrics, and setting up alerts—all depend on the solid foundation built here.
Step 2: Integrating Live Portfolio Valuation
This guide details how to implement a real-time valuation system for a DAO treasury, tracking assets across multiple chains and protocols.
A live portfolio valuation system aggregates token balances from a treasury's Ethereum Virtual Machine (EVM) and non-EVM wallets. It connects to DeFi protocols like Aave and Compound to account for supplied collateral and borrowed assets, providing a holistic view of the treasury's financial position. The core challenge is fetching accurate, real-time prices for a diverse asset set, including liquid staking tokens (e.g., stETH), governance tokens, and stablecoins, which requires reliable price oracles.
To build this, you'll need to interact with blockchain nodes and indexers. For on-chain data, use the eth_getBalance RPC call for native tokens and ERC-20 balanceOf calls for tokens. For efficiency across many addresses, batch requests using the Multicall3 contract. Off-chain, leverage subgraphs from protocols like Uniswap or Aave to query historical deposits and borrow positions. A common architecture involves a backend service that periodically polls these sources, caches the data, and serves it via an API.
Price feeds are critical. For mainnet assets, use decentralized oracle networks like Chainlink Data Feeds, which provide aggregated price data on-chain. For long-tail assets not on Chainlink, calculate prices using the reserves of their primary decentralized exchange (DEX) pool, such as a Uniswap V3 pool. The formula is generally (reserve1 / reserve0) adjusted for decimals. Always implement circuit breakers and use multiple price sources to mitigate oracle manipulation risks.
Here is a simplified Node.js example using ethers.js and the Multicall3 contract to fetch multiple ERC-20 balances in a single RPC call:
javascriptconst { ethers } = require('ethers'); const { Multicall } = require('ethers-multicall'); const provider = new ethers.providers.JsonRpcProvider(RPC_URL); const multicall = new Multicall(provider); const tokenContracts = addresses.map(addr => new Contract(addr, ['function balanceOf(address) view returns (uint256)'])); const calls = tokenContracts.map(contract => contract.balanceOf(TREASURY_ADDRESS)); const results = await multicall.all(calls); // results now contains an array of balance BigNumbers
Once you have balances and prices, calculate the total portfolio value by summing balance * price for each asset. Display this data on a dashboard with key metrics: Total Value Locked (TVL), asset allocation percentages, and protocol exposure. For actionable monitoring, implement alerts for significant balance changes, low liquidity in DEX pools for key assets, or when borrowing utilization on money markets exceeds a safe threshold (e.g., 80%).
Finally, ensure data integrity and uptime. Run the valuation service as a cron job or using a message queue. Log all data fetches and calculations for auditability. Consider using The Graph for complex historical queries and Covalent or Alchemy APIs for enhanced data reliability. The output is a real-time financial model that empowers DAO members to make informed governance decisions based on the treasury's live health.
Step 3: Implementing Transaction Alerts
Set up real-time notifications for treasury transactions using Chainscore's webhook system and alerting rules.
Transaction alerts are the core of an active treasury monitor. Instead of manually checking dashboards, you configure the system to notify you of specific on-chain events. Chainscore provides this functionality through webhooks—HTTP callbacks triggered by blockchain activity that match your defined rules. You can send these alerts to communication platforms like Slack, Discord, or a custom internal dashboard. The first step is to define the alerting rules that specify which transactions you care about. Common criteria include transaction value (e.g., transfers over $10,000), destination addresses (e.g., unknown or high-risk contracts), specific function calls (like transferOwnership), or interactions with newly deployed contracts.
To implement an alert, you must create a webhook endpoint on your server. This is a secure URL that can receive and process POST requests from Chainscore. The endpoint should return a 200 OK status to acknowledge receipt. Here is a basic Node.js example using Express to log incoming alert data:
javascriptapp.post('/chainscore-webhook', express.json(), (req, res) => { const alert = req.body; console.log('New Treasury Alert:', alert); // Add logic to forward to Slack/Discord res.sendStatus(200); });
The alert payload contains structured data such as the transaction hash, from/to addresses, value, method called, and the blockchain network. You must then register this endpoint URL in your Chainscore dashboard under the Alerts section.
For production systems, consider alert deduplication and priority routing. High-value transfers might go to a dedicated security channel, while routine DEX swaps could go to a general activity log. You can implement this logic in your webhook handler by checking the alert's severity or type field. Furthermore, configure rate limiting on your endpoint to prevent being overwhelmed during periods of high activity, and always validate the incoming request signature (provided in the headers) to ensure it originates from Chainscore. Testing is crucial: use the test button in the dashboard or initiate a small test transaction from a controlled wallet to verify the entire flow—from on-chain event to your notification channel—works correctly before relying on it for live monitoring.
Monitoring Tools and Data Sources Comparison
A comparison of data sources and tools for tracking on-chain treasury activity, spending, and governance.
| Feature / Metric | Dune Analytics | Tenderly | Chainscore API | Custom Indexer |
|---|---|---|---|---|
Real-time Transaction Alerts | ||||
Historical Data Depth | Full history | 30 days (free) | Full history | Configurable |
Multi-Chain Support | ||||
Gas Fee Attribution | Manual query | Automatic | Automatic | Manual implementation |
Programmatic Access (API) | Limited, rate-restricted | Yes | Yes, high-volume | Full control |
Time to First Dashboard | 1-2 days | < 1 hour | < 1 hour | 2+ weeks |
Smart Contract Decoding | Requires ABIs | Automatic | Automatic for major protocols | Manual implementation |
Monthly Cost (Estimate) | $0-$400+ | $0-$100 | $50-$500+ | $1k+ (dev time) |
Step 4: Building the Frontend Dashboard
This guide walks through building a React-based frontend to visualize treasury activity, connect a wallet, and display real-time spending data from your subgraph.
A functional dashboard requires a modern web framework. We'll use React with TypeScript for type safety and Vite for fast development. The core libraries are wagmi and viem for wallet connection and blockchain interaction, @apollo/client for querying the GraphQL subgraph, and Tailwind CSS for styling. Initialize the project with npm create vite@latest treasury-dashboard -- --template react-ts and install the necessary dependencies. This setup provides a robust foundation for handling wallet states, smart contract calls, and asynchronous data fetching.
The dashboard's primary task is fetching data from the deployed subgraph. Using @apollo/client, you create a provider and use the useQuery hook to execute GraphQL queries. A crucial query fetches recent FundsDeposited and FundsWithdrawn events, including fields like amount, token, from, to, and timestamp. You should implement pagination and real-time updates using GraphQL subscriptions or polling to reflect new treasury transactions as they occur. Structuring these queries efficiently is key to a responsive user experience.
User interaction begins with wallet connection. Integrate wagmi and configure it with the relevant chains (e.g., Ethereum Sepolia, Arbitrum Sepolia) and public RPC providers. Use the ConnectButton component from wagmi to let users connect their MetaMask or WalletConnect wallet. Once connected, the app can read the user's address and network, enabling features like displaying their transaction history or simulating approvals. The wagmi hooks abstract away the complexity of managing connection state and switching networks.
The UI should present data clearly. Create components like a TransactionTable to list events, a BalanceCard to show current treasury holdings (fetched via a direct contract read using wagmi's useReadContract), and a ChartComponent (using a library like Recharts) to visualize spending over time. Use Tailwind CSS for responsive design. Ensure the dashboard is informative at a glance, showing key metrics such as total deposits, total withdrawals, net flow, and the most active token addresses.
For a complete demo, the frontend can also include a section to interact with the treasury contract. Using wagmi's useWriteContract and useWaitForTransactionReceipt hooks, you can build simple forms to simulate depositing test ETH or ERC-20 tokens (requires prior approval). This demonstrates the full cycle: a user action triggers a contract write, the transaction is mined, and the subgraph indexes the new event, which then automatically updates the dashboard's transaction list and charts.
Frequently Asked Questions
Common questions and technical troubleshooting for developers implementing on-chain treasury activity and spending monitors.
An on-chain treasury monitor is a tool that tracks and analyzes the financial activity of a DAO or protocol's treasury wallet in real-time. It works by indexing blockchain data to provide insights into inflows, outflows, asset composition, and spending patterns.
Core components include:
- Event Listeners: Smart contracts emit events for transactions; monitors parse these logs.
- Data Indexing: Services like The Graph or custom indexers aggregate transaction history.
- Analytics Engine: Applies logic to categorize transactions (e.g., payroll, grants, investments).
- Alerting System: Triggers notifications based on predefined rules, such as large withdrawals or unauthorized token approvals.
For example, monitoring a Gnosis Safe on Ethereum involves tracking ExecutionSuccess events and decoding the data field to identify recipients and amounts.
Resources and Further Reading
Tools, protocols, and references that help teams design, deploy, and operate a treasury activity and spending monitor across EVM chains.
Conclusion and Next Steps
You have now built a functional on-chain treasury monitor. This guide covered the core concepts and implementation steps.
Your completed monitor provides a foundational framework for tracking treasury activity. The system ingests real-time on-chain data, parses transaction logs for specific events like Transfer or Approval, and presents a clear dashboard of inflows and outflows. By using a service like Chainscore, you avoid the complexity of managing your own RPC nodes and indexers, focusing instead on your application logic. The key components you've implemented are the data ingestion pipeline, the event decoding logic, and the aggregation logic for calculating daily and weekly totals.
To extend this system, consider adding more sophisticated features. Implement alerting for transactions exceeding a predefined threshold, which can be done by adding a conditional check in your data processing function that triggers a notification via email, Discord webhook, or Telegram bot. You could also add support for tracking ERC-20 token approvals, a critical security vector, by monitoring the Approval event and flagging unusually large allowances granted to unknown contracts. For multi-signature treasuries like Safe (formerly Gnosis Safe), you would listen for the ExecutionSuccess event to track executed transactions.
The next logical step is to enhance data persistence and historical analysis. While the current setup may use in-memory storage or a simple database for demonstration, a production system requires a robust time-series database like TimescaleDB or a data warehouse. This allows for complex historical queries, trend analysis over months or years, and the generation of detailed audit reports. You can also integrate with off-chain data sources, such as pulling token prices from an oracle like Chainlink to display the USD value of treasury movements in real-time.
Finally, consider the operational security of the monitor itself. Ensure that any private keys or API secrets are stored securely using environment variables or a secrets management service. Implement rate limiting and error handling for your RPC calls to maintain reliability. The codebase should be version-controlled and include unit tests for the core event parsing and aggregation logic. By treating the monitor as a critical piece of infrastructure, you ensure it provides reliable, actionable intelligence for managing your protocol's financial assets.