> 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/token-economics-technical/inflation-mechanism.md).

# Inflation Mechanism

## Overview

The x/brahma module distributes inflation rewards to AI creators, Application operators, and contributors every block. Rather than minting tokens directly, it **siphons** a percentage of newly minted tokens from the BitSDK distribution module. The siphon percentage is controlled by governance.

**Key Mechanism:** x/brahma intercepts inflation from standard validator rewards, ensuring compatibility with existing staking mechanisms while enabling AI-specific distribution.

## System Architecture

{% @mermaid/diagram content="graph TD
A\[Mint Module - New Token Inflation] -->|Flows to| B\[Distribution Module]
B -->|Siphon % default 50%| C\[Brahma Module Account]
B -->|Remaining % default 50%| AA\[Standard Staking Distribution]
C --> D\[Market Cap Calculation]
D -->|AI #1: 75% of Total| E\[AI #1 Inflation Share]
D -->|AI #2: 25% of Total| F\[AI #2 Inflation Share]

```
E --> G[Allocation Splits for AI #1]
F --> H[Allocation Splits for AI #2]

G -->|30% default| I[AI #1 Application Claimable Balance]
G -->|50% default| J[AI #1 Creator Claimable Balance]
G -->|20% default| K[AI #1 Contributors Portion]

H -->|30% default| L[AI #2 Application Claimable Balance]
H -->|50% default| M[AI #2 Creator Claimable Balance]
H -->|20% default| N[AI #2 Contributors Portion]

K --> O[AI #1 Contribution Matrix]
N --> P[AI #2 Contribution Matrix]

O --> Q[AI #1 Contributors Claimable Balances]
P --> R[AI #2 Contributors Claimable Balances]

Q -->|Contrib A: 50% of 20% of 75%| S[Contrib A Claimable Balance]
Q -->|Contrib B: 30% of 20% of 75%| T[Contrib B Claimable Balance]
Q -->|Contrib C: 20% of 20% of 75%| U[Contrib C Claimable Balance]

R -->|Contrib A: 20% of 20% of 25%| V[Contrib A Claimable Balance]
R -->|Contrib C: 80% of 20% of 25%| W[Contrib C Claimable Balance]

I --> X[User Calls claimRewards]
J --> X
L --> X
M --> X
S --> X
T --> X
U --> X
V --> X
W --> X

X --> Y[Brahma Module processes claim]
Y --> Z[Tokens sent from Brahma Module Account]
Z --> ZZ[bplcoin tokens transferred to user wallet]

AA --> BB[Normal staking rewards continue]

classDef contractCall fill:#FFE4B5,stroke:#FF8C00,stroke-width:2px,color:#000
classDef cosmosSDK fill:#E6F3FF,stroke:#0066CC,stroke-width:2px,color:#000
classDef userAction fill:#F0F8E6,stroke:#4CAF50,stroke-width:2px,color:#000

class Y,Z cosmosSDK
class A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,AA,BB cosmosSDK
class X,ZZ userAction" %}
```

## Process Flow (BeginBlock)

Every block, the x/brahma module executes the following steps (as visualized in the diagram above):

1. **Siphon Tokens** → Query distribution module balance, transfer `siphonPercentage` = 50% to x/brahma module. The remaining 50% stays in the distribution module and flows through standard BitSDK staking reward mechanisms (community tax, validator commission, delegator rewards). *Note: This ratio is governance-adjustable.* [Why this distribution ratio?](/tokenomics/token-economics.md#why-this-distribution-ratio)
2. **Query Market Caps** → For first 500 AIs, query ERC1155 contract for total gem supply (30-90 day rolling average window)
3. **Calculate Proportions** → Each AI's share = `aiMarketCap / totalMarketCap` (e.g., AI #1: 75%, AI #2: 25% in the diagram)
4. **Distribute Per AI** → Split rewards three ways (Creator 50%, Application 30%, contributors 20%)
5. **Allocate to Contributors** → Query historical tensor data, distribute proportionally by cores contributed (e.g., Contrib A: 50%, Contrib B: 30%, Contrib C: 20% of their AI's contributor portion)
6. **Accumulate** → Add amounts to claimable balances (users claim separately via `claimRewards` transaction)

## Distribution Algorithm

### Step 1: Siphon Tokens from Distribution Module

```go
// Query distribution module account balance
distBalance := k.bankKeeper.GetAllBalances(ctx, distributionModuleAddress).AmountOf("bplcoin")

// Calculate amount to siphon
toSiphon := distBalance.Mul(siphonPercentage)

// Transfer to brahma module account
k.bankKeeper.SendCoinsFromModuleToModule(ctx, "distribution", "brahma", toSiphon)
```

### Step 2: Query Market Caps and Calculate Proportions

```go
// Get first 500 AIs (insertion order)
aiIDs := k.GetAllAIIDs(ctx)[:maxAIsForRewards]

for _, aiID := range aiIDs {
  // Query ERC1155 contract for total gem supply
  gemSupply := k.evmKeeper.QueryERC1155TotalSupply(ctx, aiID)

  // Add to 30-90 day rolling average
  k.UpdateMarketCapHistory(ctx, aiID, gemSupply)
}

// Calculate each AI's proportional share
aiProportions := make(map[string]sdk.Dec)
totalMarketCap := sdk.ZeroDec()

for _, aiID := range aiIDs {
  avgMarketCap := k.GetAverageMarketCap(ctx, aiID)
  totalMarketCap = totalMarketCap.Add(avgMarketCap)
}

for _, aiID := range aiIDs {
  avgMarketCap := k.GetAverageMarketCap(ctx, aiID)
  aiProportions[aiID] = avgMarketCap.Quo(totalMarketCap)
}
```

### Step 3: Distribute Per AI

```go
for aiID, proportion := range aiProportions {
  ai := k.GetAI(ctx, aiID)

  // Calculate this AI's total allocation
  aiRewards := toSiphon.Mul(proportion)

  // Split three ways
  applicationRewards := aiRewards.Mul(applicationSplit)  // 30%
  creatorRewards := aiRewards.Mul(creatorSplit)          // 50%
  contributorRewards := aiRewards.Mul(contributorSplit)  // 20%

  // Allocate to claimable balances
  k.AddClaimableReward(ctx, ai.Creator, creatorRewards)
  k.AddClaimableReward(ctx, ai.ApplicationAddress, applicationRewards)
  k.AllocateToContributors(ctx, contributorRewards, ai)
}
```

### Step 4: Distribute to Contributors

```go
func (k Keeper) AllocateToContributors(ctx sdk.Context, amount sdk.Dec, ai types.AI) {
  // Get historical tensor data (max 1000 blocks)
  blockHeights := k.GetBlockHeightsForAI(ctx, ai.ID)

  // Tally cores per contributor
  contributorCores := make(map[string]sdk.Int)
  totalCores := sdk.ZeroInt()

  for _, height := range blockHeights {
    tensor := k.GetAITensor(ctx, ai.ID, height)

    for _, row := range tensor.Tensor {
      // Validate tensor before counting
      if !k.ValidateAITensor(ctx, tensor) {
        continue
      }

      cores := SumContributions(row.Contributions)
      contributorCores[row.Address] = contributorCores[row.Address].Add(cores)
      totalCores = totalCores.Add(cores)
    }
  }

  // Distribute proportionally
  for address, cores := range contributorCores {
    share := sdk.NewDecFromInt(cores).Quo(sdk.NewDecFromInt(totalCores))
    reward := amount.Mul(share)
    k.AddClaimableReward(ctx, address, reward)
  }
}
```

**Example:**

```
Contributor rewards pool: 20 bplcoin

Alice: 100 cores → (100/300) × 20 = 6.67 bplcoin
Bob:   150 cores → (150/300) × 20 = 10.00 bplcoin
Carol:  50 cores → (50/300) × 20 = 3.33 bplcoin
Total: 300 cores → 20.00 bplcoin ✓
```

## Module Parameters

| Parameter                   | Default   | Description                                          |
| --------------------------- | --------- | ---------------------------------------------------- |
| `siphon_percentage`         | 0.5 (50%) | % of distribution module balance siphoned each block |
| `application_split`         | 0.3 (30%) | Application operator's share                         |
| `creator_split`             | 0.5 (50%) | Creator's share of AI rewards                        |
| `contributor_split`         | 0.2 (20%) | Contributors' share                                  |
| `max_ais_for_rewards`       | 500       | Max AIs eligible (insertion order)                   |
| `max_ai_block_heights`      | 1,000     | Historical blocks to process per AI                  |
| `max_tensor_rows_per_block` | 1,000     | Max contributor rows per block                       |

**Validation:**

* Splits must sum to 1.0 (100%)
* All values between 0 and 1 (except max parameters)
* Processing limits capped at 10,000 to prevent DoS

## Key Data Structures

### MarketCapHistory

Stores 30-90 day rolling average of AI market cap (gem supply from ERC1155):

```protobuf
message MarketCapHistory {
  string ai_id = 1;
  repeated string market_caps = 2;  // Circular buffer (max 30 entries)
  uint32 current_index = 3;
  uint32 total_entries = 4;
}
```

**Purpose:** Smooths market cap volatility, prevents consensus issues from non-deterministic calculations.

### ClaimableReward

Accumulated rewards per address:

```go
type ClaimableReward struct {
  Address string      // Participant's address
  Amount  sdk.Coins   // Claimable balance
}
```

**Purpose:** Two-step process (allocate → claim) prevents distribution failures from blocking inflation distribution.

## Security & Safety

### Bounded Processing

* **Max 500 AIs** per distribution (first 500 by insertion order)
* **Max 1,000 blocks** of tensor history per AI
* **Max 1,000 rows** per block processed
* Prevents unbounded loops that could halt blockchain

### Overflow Protection

* Uses `sdk.Dec` and `sdk.Int` types with safe math
* Validates all tensor data before counting contributions
* Prevents arithmetic overflow in reward calculations

### Deterministic Consensus

* **30-90 day rolling average** stored in KVStore (not memory)
* Market cap stored as strings to preserve decimal precision
* Circular buffer prevents unbounded storage growth
* All calculations deterministic across validators

### Two-Step Distribution

* **Allocate** rewards to claimable balances (automatic)
* **Claim** rewards via transaction (user-initiated)
* Distribution never fails due to transfer errors
* Users control timing and gas costs

### Validation

* Application authorization enforced (only registered Application can submit tensors)
* AI tensors validated before tallying contributions
* Address format validation (ERC20 hex format)
* Core grant expiry system prevents stale permissions

## Example Distribution

**Setup:**

* Distribution module balance: 1,000 bplcoin
* Siphon percentage: 50%
* 2 AIs with equal market cap (50% each)

**Flow:**

```
1. Siphon: 1,000 × 0.5 = 500 bplcoin to brahma module

2. Market caps:
   - AI Alpha: 1,000 gems (avg over 30-90 days)
   - AI Beta:  1,000 gems
   - Total:    2,000 gems

3. Proportional allocation:
   - AI Alpha: (1,000/2,000) × 500 = 250 bplcoin
   - AI Beta:  (1,000/2,000) × 500 = 250 bplcoin

4. Split per AI (Alpha example):
   - Creator:      250 × 0.5 = 125 bplcoin
   - Application:  250 × 0.3 = 75 bplcoin
   - Contributors: 250 × 0.2 = 50 bplcoin

5. Contributor distribution (Alpha):
   Alice (100 cores): (100/250) × 50 = 20 bplcoin
   Bob   (150 cores): (150/250) × 50 = 30 bplcoin
   Total (250 cores): 50 bplcoin ✓
```

## Key Design Decisions

### Siphoning vs. Direct Minting

x/brahma doesn't mint tokens—it intercepts inflation from the standard BitSDK distribution module. This preserves compatibility with standard staking reward mechanisms. The remaining 50% continues through the distribution module's standard allocation: community tax (\~5%) to the community pool, then staking rewards (\~95%) split between validators (who earn commission) and delegators (who earn the majority proportional to stake).

### Market Cap Metric

**Current (Pre-AMM):** `gem_supply` = ERC1155 totalSupply (queried from EVM precompile). This directly reflects user demand and engagement.

**Future (Post-AMM):** `rolling_average[ (W1 × gem_supply) + (W2 × gem_market_cap) ]` where `gem_market_cap = AMM_price × supply`. W1 and W2 are governance-adjustable weights that allow tuning the balance between supply-based and price-based metrics, mitigating price manipulation attacks on thin liquidity.

### Insertion Order, Not Market Cap Rank

The first 500 AIs created receive rewards, preventing spam attacks where malicious actors create thousands of AIs to dilute rewards.

### Rolling 30-90 Day Average

Smooths market cap volatility over a 30-90 day window to prevent reward manipulation via short-term gem supply spikes.

### Two-Step Distribution

Separating allocation (automatic) from claiming (user-initiated) prevents distribution failures and gives users control over gas costs.

### Historical Tensor Processing

Contributors earn rewards based on all past contributions (up to 1,000 blocks), not just recent ones. This recognizes long-term value creation.

## Summary

x/brahma creates sustainable economic incentives by:

1. **Siphoning** 50% of inflation from distribution module, and it can be adjusted by governance.
2. **Allocating** proportionally by AI market cap metric (currently gem supply; future: weighted combination of supply and AMM price)
3. **Splitting** three ways: Creator (50%), Application (30%), contributors (20%)
4. **Distributing** to contributors by historical contribution cores
5. **Accumulating** in claimable balances for user-controlled claiming

This aligns incentives across all participants: creators, operators, and contributors all benefit from AI success, measured objectively by user engagement (gem holdings and market valuation).
