Some threats are immediate and easy to spot in a single transaction. Others develop gradually, hidden across many interactions over time, unfolding over hours, days, or even weeks.
If your bot only analyzes one transaction at a time, it may miss long-term patterns and behaviors that only reveal themselves when you zoom out.
Today, we learn to give our agents memory, so they can watch, compare, and detect patterns over time.
What Is a Stateful Agent?
Most basic Forta agents are stateless.
They process one event (a block or transaction) and make a decision with no knowledge of the past.
A stateful agent stores data between runs. It can:
Count events (e.g. 5 large swaps in 10 minutes)
Compare values (e.g. token price now vs. 1 hour ago)
Correlate behaviors (e.g. address interacted with phishing contract AND drained funds)
Use Cases That Require State
Types of State in Forta Bots
1. In-Memory (Short-Lived)
Works during agent runtime
Lost if the bot restarts
Great for things like caching one or two blocks back
let lastBlockNumber = 0;
function handleBlock(blockEvent: BlockEvent) {
if (lastBlockNumber === 0) {
lastBlockNumber = blockEvent.block.number;
return [];
}
// Do comparison
}
2. Disk-Based (Persistent Local Storage)
Use the built-in Forta Cache class for local storage:
import { createPersistence } from "forta-agent";
const store = createPersistence();
async function handleTransaction(tx: TransactionEvent) {
const count = (await store.get(tx.from)) || 0;
await store.set(tx.from, count + 1);
}
Good for tracking:
Number of interactions per address
Token balance snapshots
Last seen timestamp per contract
3. External Storage (Cloud/DB)
If you need cross-scan-node memory (e.g., across chains or distributed bots), use:
Firebase
Redis
DynamoDB
PostgreSQL
You’ll need to handle authentication, API rate limits, and write your own wrapper logic.
Best Practices for Managing State
Stateful Detection Example: Whale Accumulation Tracker
Goal: detect a wallet that accumulates $1M in stablecoins over 1 hour.
Steps:
Track
fromandvalueof stablecoin transfersAggregate total received by address per hour
Emit alert if value > $1,000,000
This requires storing:
Cumulative balances
Timestamps
Possibly a rolling window of events
When NOT to Use State
If your detection logic is simple (e.g. value > threshold in single tx)
If uptime and speed are more important than history
If storing state would expose sensitive data or cause legal issues
Key Concepts Recap
Stateful agents remember, letting you detect patterns across time
Use in-memory, disk-based, or external storage depending on needs
Design keys, limits, and cleanup routines carefully
Not every bot needs state, choose wisely
In the next lesson, we will explore more the DevOps side of things: CI/CD for Forta bots (automating testing, linting, and safe deployment).
Until next meditation,
The Blockchain Security Monk




