> For the complete documentation index, see [llms.txt](https://docs.bitplanet.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bitplanet.ai/advanced-topics/blockchain-architecture/hooks-lifecycle.md).

# Hooks & Lifecycle

Bitplanet's block lifecycle includes standard BitSDK hooks (BeginBlock, EndBlock) and custom EVM hooks (PostTxProcessing) that execute at specific points in block processing. This page explains when these hooks run and what operations they perform.

## Block Lifecycle Overview

Each block follows this execution flow:

1. **BeginBlock** (all modules in order)
2. **Transaction Execution**
   * Validate transaction
   * Execute message handlers
   * PostTxProcessing hooks (after each EVM tx)
3. **EndBlock** (all modules in order)
4. **Commit** (state finalized)

## BeginBlock Hooks

### Module Execution Order

BeginBlock hooks execute in this sequence:

1. mint
2. ibc
3. erc20
4. feemarket
5. evm
6. brahma
7. precompile

**Why Order Matters:**

* Mint must run first (creates new tokens for distribution)
* EVM must run after feemarket (gas price updates)
* Brahma must run after EVM (queries EVM state for market caps)
* Feemarket runs last in EndBlock (updates base fee)

### x/brahma BeginBlock

The primary custom hook in Bitplanet's BeginBlock.

**Purpose:** Distributes inflation rewards to AI creators, AI Apps, and contributors.

**Operations:**

1. Query distribution module balance
2. Calculate siphon amount
3. Transfer tokens to brahma module
4. Query AI market caps from EVM contracts
5. Distribute proportionally to stakeholders
6. Update claimable reward balances

**Performance:** O(n) where n = number of AIs (limited by `max_ais_for_rewards` parameter)

For detailed technical implementation, see [**Inflation Mechanism**](/advanced-topics/token-economics-technical/inflation-mechanism.md) and [**Reward Distribution**](/advanced-topics/token-economics-technical/reward-distribution.md).

## EndBlock Hooks

### Module Execution Order

EndBlock hooks execute in this sequence:

1. gov
2. staking
3. auth
4. bank
5. evm
6. erc20
7. feemarket

**Key Operations:**

* **gov**: Tally proposal votes, execute passed proposals
* **staking**: Update validator set, process unbonding
* **feemarket**: Update EIP-1559 base fee (must run last)

**Note:** Most Bitplanet-specific logic runs in BeginBlock. EndBlock primarily handles standard BitSDK operations.

## PostTxProcessing Hooks

Custom hooks that execute after each EVM transaction completes.

### Hook Registration

Hooks are registered in reverse order of execution:

```go
evmKeeper.SetHooks(
  NewMultiEvmHooks(
    precompileKeeper.Hooks(),  // Executes first
    brahmaKeeper.Hooks(),      // Executes second
  )
)
```

### x/precompile PostTxProcessing

**Purpose:** Bridge EVM events to BitSDK operations.

**Flow:**

1. EVM Transaction → Receipt with Logs
2. PostTxProcessing Hook
3. Check logs for precompile addresses
4. Match event signatures
5. Execute BitSDK operations

**Supported Events:**

* **CoreGrantApplication**: Creates governance proposal for core grant - see [**Core Tokens**](/advanced-topics/token-economics-technical/core-tokens.md)
* **OreRequest**: Processes contribution tensors, mints cores - see [**AI Tensor Matrix**](/advanced-topics/token-economics-technical/ai-tensor-matrix.md)
* **ContributionTypes**: Updates contribution type parameters

See [x/precompile Module - Event Processing](/advanced-topics/blockchain-architecture/custom-modules/precompile-module.md#event-processing) for implementation details.

### x/brahma PostTxProcessing

**Purpose:** Process reward claim events from EVM contracts.

**Operation:**

* Listens for `BplCoinClaimed` events
* Validates claim data
* Transfers rewards to claimant

For detailed claiming process, see [**Reward Distribution**](/advanced-topics/token-economics-technical/reward-distribution.md).

## Event Emission

### Event Types

Bitplanet modules emit events for indexing and external monitoring:

**x/brahma Events:**

```
EventTypeCoreGrantApplication
EventTypeRemoveCoreGrantApplication
EventTypeRequestForCore
EventTypeClaimRewards
```

**x/precompile Events:**

```
EventTypeTurnstileRegister
EventTypeTurnstileUpdate
EventTypeParamChange
```

**Standard Cosmos Events:**

* `message`: Module and action
* `transfer`: Token movements
* `delegate`: Staking operations

### Event Structure

Events include typed attributes:

```go
sdk.NewEvent(
  "core_grant_application",
  sdk.NewAttribute("requester", requester),
  sdk.NewAttribute("allocation", amount),
  sdk.NewAttribute("height", height),
)
```

**Use Cases:**

* Block explorers index events for queries
* AI Apps subscribe to specific event types
* Analytics track on-chain activity

## Module Dependencies

### BeginBlock Dependencies

1. **mint** (creates tokens)
2. **brahma** (distributes tokens)
3. **evm** (queries contract state)

Brahma depends on mint running first and queries EVM state for market caps.

### PostTxProcessing Dependencies

1. **EVM transaction** completes
2. **precompile hook** (processes events)
3. **brahma hook** (processes claims)

Both hooks depend on EVM transaction execution completing successfully.

## Performance Considerations

### BeginBlock Limits

Governance parameters prevent unbounded processing:

| Parameter                   | Default | Purpose                           |
| --------------------------- | ------- | --------------------------------- |
| `max_ais_for_rewards`       | 500     | Limits AIs processed per block    |
| `max_ai_block_heights`      | 1,000   | Limits historical data processed  |
| `max_tensor_rows_per_block` | 1,000   | Limits contributor rows processed |

**Why:** Ensures BeginBlock completes within block time (\~6 seconds).

For how these parameters affect reward calculations, see [**Inflation Mechanism**](/advanced-topics/token-economics-technical/inflation-mechanism.md).

### PostTxProcessing Overhead

Each EVM transaction triggers hooks:

* Iterates through transaction logs
* Checks for registered precompile addresses
* Minimal overhead if no matching events

**Optimization:** Hooks exit early if no relevant events detected.

## Hook Execution Guarantees

### Atomicity

BeginBlock/EndBlock operations are atomic:

* All operations succeed or entire block fails
* State changes committed together
* No partial execution

### Determinism

All hooks must be deterministic:

* Same inputs → same outputs
* No randomness or external dependencies
* Consistent ordering across validators

**Example:** Brahma uses rolling averages stored in state (not memory) to ensure deterministic reward calculations.
