> 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/custom-modules/brahma-module.md).

# x/brahma Module

The x/brahma module is Bitplanet's core attribution and reward distribution system. It tracks AI contributions through a multi-dimensional tensor matrix and automatically distributes inflation rewards to creators, Application operators, and contributors.

## Overview

The module implements two primary functions:

1. **Contribution Attribution**: Records who contributed what to each AI via Request for Core (RfC) messages
2. **Reward Distribution**: Automatically distributes inflation rewards every block based on AI market capitalization

**Key Features:**

* Multi-dimensional contribution tracking (6 types: TRAIN, REFER, CREATE, PROMPT, REVENUE, MARKET\_CAP)
* Market cap-weighted reward distribution
* Three-way reward split: Creator (50%), Application (30%), Contributors (20%)
* Governance-controlled parameters (12 total)
* Claimable reward system for deferred distribution

## Core Concepts

### Contribution Attribution System

Bitplanet tracks contributions through a two-phase system:

**Phase 1: Authorization (Core Grant Application)**

* Requester submits governance proposal to obtain core issuance permission
* Community votes on proposal
* If approved, requester receives core allocation quota

**Phase 2: Attribution (Request for Core)**

* Approved requester submits contribution tensors
* System validates tensors and deducts from quota
* Contributions recorded immutably at block height
* Cores minted via EVM contract

### Complete Transaction Flow

The following diagram shows the complete lifecycle of Core tokens from governance approval to user claims:

{% @mermaid/diagram content="graph TD
A\[User or Org submits Core Grant Application] --> B\[Governance module allows validators to vote on proposal]
B --> C\[User or Org submits Request for Core with Contribution Matrix]
C --> D\[Brahma Module sends update to GemCoreNFT smart contract redemption matrix]
D --> E\[GemCoreNFT smart stores redemption matrix of contributor to core allocation]
E --> F\[Contributor calls claimCore]
F --> G\[GemCoreNFT smart contract mints ERC1155 Core tokens to contributor wallet]

```
H[User calls mintGem with devaId and postId] --> I[GemCoreNFT smart contract checks user has Core tokens]
I --> J[GemCoreNFT smart contract burns 1 Core token from user wallet]
J --> K[GemCoreNFT smart contract mints 1 Gem ERC20 token to user wallet]


M[Mint Module - New Token Inflation] --> N[Brahma Module BeginBlock siphons from distribution module]
N --> O[Claimable balances updated every block in Brahma Module]
O --> P[User Calls ClaimABPL via GemCoreNFT smart contract]
P --> Q[Precompile module parses event from GemCoreNFT contract]
Q --> R[Brahma Module sends tokens from module account and are transferred to user wallet]

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 E,G,I,J,K,L contractCall
class B,D,M,N,O,Q,R cosmosSDK
class A,C,F,H,P userAction" %}
```

This flow encompasses:

1. Governance proposal and voting for Core Grant Applications
2. Request for Core submission with contribution matrix
3. Smart contract interactions via GemCoreNFT
4. Core token minting and Gem NFT creation
5. Inflation rewards distribution and claiming mechanisms

### AI Tensor Matrix

The tensor matrix is a 2D structure tracking contributions:

**Example: AI Tensor for "genie-ai" at Block 1000**

| Address       | TRAIN | REFER | CREATE | PROMPT |
| ------------- | ----- | ----- | ------ | ------ |
| cosmos1abc... | 100   | 50    | 1      | 25     |
| cosmos1xyz... | 200   | 0     | 0      | 10     |
| cosmos1def... | 75    | 100   | 0      | 50     |

Each cell represents the quantity of a specific contribution type by a contributor.

## Data Structures

### AITensor

Records contribution state for an AI at a specific block height:

```protobuf
message AITensor {
  bytes AI = 1;
  repeated AITensorRow tensor = 2;
}

message AITensorRow {
  string address = 1;
  repeated uint64 contributions = 2;  // Position-indexed by contribution type
}
```

**Key Properties:**

* Immutable once stored (historical record)
* Multiple RfCs in same block are merged by summing contribution values
* Array indices match ContributionTypes parameter order
* Tensor merging ensures atomic updates when multiple requesters submit in same block

### AI Entity

Metadata for registered AIs:

```protobuf
message AI {
  bytes ID = 1;
  bytes creator = 2;
  bytes applicationAddress = 3;
  repeated uint64 rolling_avg_market_cap = 4;  // Rolling-average market cap history
}
```

### Core Grant Application

Permission to issue cores:

```protobuf
message MsgCoreGrantApplication {
  string authority = 1;              // Governance module account
  string requester = 2;              // Address receiving permission
  uint64 core_allocation = 3;        // Total cores granted
  int64 created_at_height = 6;       // For expiry tracking
  string title = 4;
  string description = 5;
}
```

**Lifecycle:**

* Submitted via governance proposal
* Expires after `CoreGrantApplicationExpiryHeight` blocks
* Can be increased by submitting additional proposals
* Can be removed via `MsgRemoveCoreGrantApplication`

### Contribution Types

Governance-managed list defining contribution categories:

```protobuf
message ContributionType {
  string name = 1;
  string description = 2;
  bool active = 3;
}
```

**Default Types:**

1. **TRAIN** - Training data or model improvements
2. **REFER** - Referrals and community growth
3. **CREATE** - AI creation (required, cannot be deactivated)
4. **PROMPT** - Prompt engineering and testing
5. **REVENUE** - Revenue generation contributions
6. **MARKET\_CAP** - Market capitalization increase

**Critical Constraints:**

* **Append-only**: New types can only be added at the end
* **Immutable order**: Existing types cannot be reordered
* **Immutable names**: Type names cannot be changed
* **CREATE required**: Must always remain active

These constraints prevent corruption of historical contribution data stored as position-indexed arrays.

## Message Types

### MsgRequestForCore (RfC)

Submits contribution data and mints cores:

```protobuf
message MsgRequestForCore {
  string requester = 1;
  repeated AITensor AITensors = 2;
}
```

**Requirements:**

* Requester must have approved CGA with sufficient allocation
* CGA must not be expired
* Factory contract must be configured
* All contribution types must be active
* Application address must match requester (authorization check)

**Processing Flow:**

1. Validate CGA exists and is not expired
2. Validate tensors and filter invalid AI references
3. Calculate total cores needed with overflow protection
4. Check sufficient allocation remaining
5. Deduct from requester's allocation
6. Create new AIs if needed (first contribution must include CREATE)
7. Merge with existing tensors at current height (concurrent RfCs are combined)
8. Store updated tensors
9. Mint cores via EVM contract in batches of 100 addresses to prevent gas limits

### MsgCoreGrantApplication

Creates or updates core grant allocations:

```protobuf
message MsgCoreGrantApplication {
  string authority = 1;
  string requester = 2;
  uint64 core_allocation = 3;
  int64 created_at_height = 6;
  string title = 4;
  string description = 5;
}
```

**Features:**

* Authority-only (governance module)
* Increases existing allocation if CGA already exists
* Resets expiry timer on update
* Validates against `MaxCoreGrantAllocation` parameter

### MsgRemoveCoreGrantApplication

Administratively removes core grant:

```protobuf
message MsgRemoveCoreGrantApplication {
  string authority = 1;
  string requester = 2;
  string reason = 3;  // Mandatory audit trail
}
```

### MsgClaimRewards

Claims accumulated rewards:

```protobuf
message MsgClaimRewards {
  string address = 1;
}
```

Transfers claimable balance from brahma module to user account.

## Reward Distribution

The x/brahma module implements an automatic reward distribution system that runs every block via the BeginBlock hook.

**High-Level Process:**

1. Siphon percentage = 50% of inflation from distribution module (remaining 50% continues through standard staking distribution). This distribution ratio is adjustable via governance.
2. Query AI market cap metrics from EVM contracts (30-90 day rolling average). Currently uses gem supply; future implementation will use `(W1 × gem_supply) + (W2 × gem_market_cap)` with governance-adjustable weights.
3. Distribute proportionally: Creator (50%), Application (30%), Contributors (20%)
4. Accumulate rewards in claimable balances

**Remaining 50% Distribution:** The tokens remaining in the distribution module after siphoning flow through standard BitSDK mechanisms:

* Community tax (\~5%) → Community pool for ecosystem development
* Staking rewards (\~95%) → Validators earn commission, delegators earn majority proportional to stake

**Key Features:**

* Market cap-weighted distribution across AIs
* Bounded processing to prevent blockchain halting
* Two-step allocation and claiming for safety
* Historical tensor processing for contributor rewards

For detailed technical implementation including algorithms, data structures, security considerations, and parameter configuration, see [**Inflation Mechanism**](/advanced-topics/token-economics-technical/inflation-mechanism.md).

## State Storage

### Storage Prefixes

```go
AITensorsPrefix             = 0x01  // AI ID + height → AITensor
CoreGrantApplicationsPrefix = 0x02  // Requester address → CoreGrantApplication
AIPrefix                    = 0x04  // AI ID → AI
KeyPrefixClaimableRewards   = 0x05  // Address → claimable amount
KeyPrefixMarketCaps         = 0x06  // AI ID → MarketCapHistory
KeyPrefixAIIDOrdered        = 0x20  // Index → AI ID (insertion order for efficient iteration)
KeyPrefixAIIDOrderedCount   = 0x21  // Total AI count for quick lookups
```

The `AIIDOrdered` and `AIIDOrderedCount` prefixes enable efficient iteration over AIs in the order they were created, which is crucial for reward distribution performance.

### Key Encoding

AITensor keys use length-prefix encoding for collision resistance:

```
[Length: 2 bytes] + [AI ID: variable] + [Block Height: 8 bytes] + [Address: optional]
```

**Example:**

```
AI "alpha" (5 bytes) at block 1000:
0x0005 616c706861 00000000000003e8
```

**Benefits:**

* Prevents collisions between different AI IDs
* Enables efficient range queries
* Deterministic ordering across validators

## Module Parameters

| Parameter                              | Default                                               | Description                   |
| -------------------------------------- | ----------------------------------------------------- | ----------------------------- |
| `max_core_grant_allocation`            | 100                                                   | Max cores per CGA             |
| `core_grant_application_expiry_height` | 1000                                                  | Blocks before CGA expires     |
| `contribution_types`                   | \[TRAIN, REFER, CREATE, PROMPT, REVENUE, MARKET\_CAP] | Contribution type definitions |
| `creator_split`                        | 0.5 (50%)                                             | Creator reward share          |
| `application_split`                    | 0.3 (30%)                                             | Application reward share      |
| `contributor_split`                    | 0.2 (20%)                                             | Contributor reward share      |
| `siphon_percentage`                    | 0.5 (50%)                                             | % of inflation to siphon      |
| `evm_gas_limit`                        | 25M                                                   | EVM call gas limit            |
| `evm_gas_cap`                          | 25M                                                   | EVM call gas cap              |
| `max_ais_for_rewards`                  | 500                                                   | Max AIs eligible for rewards  |
| `max_ai_block_heights`                 | 1000                                                  | Max historical blocks per AI  |
| `max_tensor_rows_per_block`            | 1000                                                  | Max tensor rows per block     |

**Validation Rules:**

* Split percentages must sum to 1.0 (100%)
* All percentages must be between 0 and 1
* Processing limits capped at 10,000
* At least one contribution type must be active
* CREATE contribution type is mandatory

All parameters are governance-controlled and can be updated via proposals.

## Query Endpoints

**Attribution Queries:**

* `AITensorByBlockHeight` - Get tensor for AI at specific height
* `ContributionByWalletAddress` - Get contributor's specific contributions
* `GetAllBlockHeightsByAIID` - List all heights with tensors for AI

**Grant Queries:**

* `QueryCoreGrantApplication` - Get CGA status by requester
* `QueryCore` - Get Core token contract addresses
* `QueryAITokens` - Get Gem token addresses for AI

**Reward Queries:**

* `QueryClaimableRewards` - Get pending rewards for address
* `QueryClaimStatistics` - Get aggregate statistics

**Parameter Queries:**

* `Params` - Get all module parameters

## Security Features

**Overflow Protection:**

* Safe math operations throughout (math.Int, sdk.Dec)
* Overflow checks before allocation updates
* Bounded processing prevents infinite loops

**Authorization:**

* Governance-only controls for sensitive operations
* Application-only authorization for RfC submissions
* Mandatory audit trails (reason fields)

**Data Integrity:**

* Append-only contribution types
* Length-prefixed keys prevent collisions
* Tensor merging for concurrent submissions
* Immutable historical records

**Performance:**

* Bounded iteration (max AIs, max heights, max rows)
* Batch core minting (100 addresses per call)
* Fixed-size rolling averages (30 entries)
* AI insertion order tracking for efficient queries

## Integration with EVM

The module interacts with EVM contracts for:

**Core Minting:**

* Calls `mintCore` method on GemCoreNFT factory contract
* Batch processes up to 100 addresses per transaction
* Uses module account as caller

**Market Cap Queries:**

* Queries Gem ERC1155 total supply
* Uses precompile addresses for contract interaction
* Stores results in 30-90 day rolling average
