> For the complete documentation index, see [llms.txt](https://docs.somnia.network/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.somnia.network/concepts/somnia-blockchain/on-chain-reactivity.md).

# On-Chain Reactivity

## The Missing Link

Blockchains have historically had a major limitation: they are passive. They are excellent ledgers, but they are deaf and mute until a user kicks them into action with a transaction. A smart contract cannot "wake up" when a price changes, specific data shows up or when a specific event occurs.

## The Usability

Imagine the world where you can instantly react to events happening on blockchain:

* **DeFi**: Automated responses to price changes, liquidations, or interest accruals. For instance, a lending protocol might need to adjust collateral requirements instantly based on market volatility.
* **Gaming**: Real-time updates for player achievements, in-game economies, or multiplayer interactions. Imagine a blockchain game where earning an NFT trophy automatically triggers rewards or level-ups without off-chain servers.
* **Business Logic**: Supply chain tracking where an item's arrival (logged as an event) auto-initiates payments or audits. Or in insurance, a smart contract that pays out claims upon verified on-chain data like weather reports.

## The Setup

The blockchain is ledger of transaction modifying the common state. Some of these transaction might emit a log, which is defined as an observable event:

```mermaid
sequenceDiagram
    participant User
    participant Blockchain
    participant EventLog
    
    User->>Blockchain: Submit Transaction
    Blockchain->>EventLog: Event Emitted
    Note over EventLog: Observable Event
```

Traditionally the developer would need to create an infrastructure that constantly monitors the blockchain state and event through RPC calls. Then based on the logic the custom app would create a transaction and post it for the inclusion at the next available block:

```mermaid
sequenceDiagram
    participant User
    participant Blockchain
    participant EventLog
    participant Monitor as Off-Chain Monitor
    participant Logic as Custom App Logic
    
    User->>Blockchain: Transaction
    Blockchain->>EventLog: Event Emitted
    
    loop Constant Polling
        Monitor->>Blockchain: RPC Call
        Blockchain-->>Monitor: Current State
    end
    
    Monitor->>Logic: Event Detected
    Logic->>Logic: Process Logic
    Logic->>Blockchain: Submit Reaction Tx

    Note over Monitor: ⚠️ Custom Infrastructure
    Note over Blockchain: Included in NEXT available block
```

As expected this created a large overhead for a typical development team. Additionally it did not meet the requirements of decentralisation, trustlessness, immediate reaction and reliable event handling.

This is why we saw a plethora of services known as indexers or Web3 hooks:

```mermaid
sequenceDiagram
    participant User
    participant Blockchain
    participant EventLog
    participant Indexer as Indexer Service
    participant Config as Custom Config/Logic
    
    User->>Blockchain: Transaction
    Blockchain->>EventLog: Event Emitted
    
    Indexer->>Blockchain: Monitor Events
    Blockchain-->>Indexer: Event Data
    Indexer->>Config: Trigger Hook
    Config->>Config: Execute Logic
    Config->>Blockchain: Submit Reaction Tx
    
    Note over Indexer: ⚠️ Centralized & Trusted
    Note over Blockchain: Included in NEXT available block
```

They alleviate a lot of issues related to the infrastructure, at the same time they add new issues related to the domain-specific configuration or language. Still the key requirements are still not met:

* indexers are centralised and trustfull
* the event handling trasaction can only be included in the next available block
* it is not MEV-resistant
* it's only as reliable as the indexer provider

## The Solution

Enter **Somnia Native On-Chain Reactivity**.

This isn't just an incremental improvement; it's a paradigm shift that enables real-time, trustless and decentralised reactions without relying on external systems:

```mermaid
sequenceDiagram
    participant User
    participant Blockchain as Somnia Blockchain
    participant EventLog
    participant Handler as Event Handler
    
    User->>Blockchain: Transaction
    Blockchain->>EventLog: Event Emitted
    EventLog->>Handler: Trigger Handler
    Handler->>Handler: Execute Reaction Logic
    
    Note over Blockchain: ✅ Same block execution
    Note over Handler: ✅ Decentralized & trustless
    Note over Handler: ✅ MEV-resistant
```

## The Benefits

Once an event is defined, it's handling is happening automatically by blockchain nodes:

* **Real-Time**: Reaction included in the same block.
* **Decentralised**: As decentralised as the blockchain itself.
* **Trustlessness**: No trusted party required.
* **MEV**: Fully MEV-resistant due to deterministic inclusion of event handlers
* **Developer-Friendly**: Familiar paradigms (e.g., subscriptions akin to event listeners in traditional programming) and interface reduce complexity.
* **Cost Efficiency**: Optimized gas usage minimize expenses compared to infrastucture required for constant off-chain monitoring.
* **Security and Resilience**: Backed by the blockchain itself. Reduces attack surfaces by eliminating external dependencies; nested events allow complex chains without intermediaries.
* **Scalability**: Supports high-throughput apps, as seen in Somnia's 1M+ TPS capability, making it ideal for mass-adoption scenarios.

***

### Comparison Table

| Aspect               | Traditional RPC | Indexer/Hooks       | Somnia Reactivity   |
| -------------------- | --------------- | ------------------- | ------------------- |
| **Timing**           | Next block      | Next block          | Same block          |
| **Decentralization** | Developer infra | Centralized service | Fully decentralized |
| **Trust Model**      | Self-hosted     | Trusted third party | Trustless           |
| **MEV Resistance**   | ❌               | ❌                   | ✅                   |
| **Infrastructure**   | High complexity | Medium complexity   | Zero external infra |
| **Reliability**      | Self-managed    | Service-dependent   | Blockchain-native   |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.somnia.network/concepts/somnia-blockchain/on-chain-reactivity.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
