> 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/developer-guides/module-api.md).

# Module API

## x/brahma Module

The Brahma module implements AI-driven token economics with governance-based core allocation and automated reward distribution.

### Core Transaction Types

The Brahma module uses four main transaction types to manage the lifecycle of Core token allocations and AI contributions:

#### 1. MsgCoreGrantApplication

**Purpose:** Request permission to mint Core tokens through governance approval.

**Use Case:** AI creators or contributors apply for a Core token allocation budget. Once approved by governance, the requester can subsequently mint cores by submitting AI tensor contributions (via MsgRequestForCore) until their allocation is exhausted.

**Workflow:** Typically triggered automatically via Application when it interacts with the Brahma precompile contract. Creates a governance proposal that validators must vote on. If approved, a CoreGrantApplication is stored in state with the allocated amount.

```protobuf
message MsgCoreGrantApplication {
  string authority = 1;          // x/gov module account
  string requester = 2;          // Address to receive allocation
  uint64 core_allocation = 3;    // Number of cores requested
  string title = 4;              // Proposal title (required)
  string description = 5;        // Proposal description (required)
  int64 created_at_height = 6;   // Creation block height (required)
}
```

**All fields are required.** This is a governance-only transaction - users cannot submit it directly via CLI.

#### 2. MsgRequestForCore

**Purpose:** Exchange AI tensor contributions for Core tokens under an approved grant allocation.

**Use Case:** After receiving an approved CoreGrantApplication, the requester submits this message to contribute AI training data (tensors) and receive corresponding Core tokens. Each contribution decrements the remaining allocation.

**Workflow:** Application submits AI tensor data → Module validates sufficient allocation remains → Calculates cores to mint based on contributions → Mints cores via GemCoreNFT contract → Updates allocation balance.

```protobuf
message MsgRequestForCore {
  string requester = 1;                    // Address making the request
  repeated brahma.v1.AITensor AITensors = 2;  // AI tensor contributions
}
```

**Processing:** Tensors are processed in batches with overflow protection. Multiple AIs and contribution types can be included in a single request.

#### 3. MsgRemoveCoreGrantApplication

**Purpose:** Revoke an existing Core token allocation through governance.

**Use Case:** Used when a CoreGrantApplication needs to be cancelled (e.g., project abandoned, misuse detected, policy changes). Prevents the requester from minting additional cores.

**Workflow:** Governance proposal created → Validators vote → If approved, the CoreGrantApplication is removed from state and the requester can no longer mint cores under that allocation.

```protobuf
message MsgRemoveCoreGrantApplication {
  string authority = 1;  // x/gov module account
  string requester = 2;  // Address whose allocation to remove
  string reason = 3;     // Mandatory reason for removal
}
```

**Reason field is required for audit purposes** to maintain transparency about why allocations are revoked. This is a governance-only transaction.

#### 4. MsgUpdateParams

**Purpose:** Modify module parameters through governance.

**Use Case:** Adjust economic parameters (creator/Application/contributor reward splits, siphon percentage), contribution types, processing limits, or EVM gas settings without requiring a chain upgrade.

**Workflow:** Governance proposal created with new parameter values → Validators vote → If approved, parameters are updated in state and take effect immediately.

```protobuf
message MsgUpdateParams {
  string authority = 1;
  Params params = 2;     // All parameters must be supplied
}
```

**Important:** All 12 parameters must be supplied when updating (see Module Parameters section for complete list). This is a governance-only transaction.

### Key Keeper Methods

**Core Token Management:**

```go
// Issue cores to addresses from approved grant applications
// Takes a map of address -> amount to support batch processing
IssueCores(ctx sdk.Context, amountsToMint map[string]uint64) error

// Internal batch processor - called by IssueCores
IssueCoresBatch(ctx sdk.Context, addresses []common.Address, amounts []*big.Int) error

// Calculate ore amounts to mint based on AI tensors
// Returns map of address -> total amount across all tensors
CalculateOresToMint(aiTensors []*types.AITensor) (map[string]uint64, error)
```

**AI Management:**

```go
// Register new AI entity with market cap
SetAI(ctx sdk.Context, ai types.AI, marketCap math.LegacyDec)

// Retrieve AI by identifier (string ID)
GetAI(ctx sdk.Context, id string) (types.AI, bool)

// Get all registered AIs
GetAllAIs(ctx sdk.Context) []AI

// Iterate over all AIs
IterateAIs(ctx sdk.Context, cb func(ai types.AI) (stop bool))
```

**Reward Distribution:**

```go
// Allocate rewards to AI creator
AllocateToCreator(ctx sdk.Context, amount math.LegacyDec, ai AI) error

// Allocate rewards to Application deployer
AllocateToApplication(ctx sdk.Context, amount math.LegacyDec, ai AI) error

// Distribute rewards to tensor contributors
AllocateToContributors(ctx sdk.Context, amount math.LegacyDec, ai AI) error
```

**Market Cap & Inflation:**

```go
// Get historical market cap snapshots for specific AI
GetMarketCaps(ctx sdk.Context, aiID []byte) []math.LegacyDec

// Update market cap for an AI
UpdateMarketCap(ctx sdk.Context, aiID []byte, marketCapUsd math.LegacyDec) error

// Calculate reward split percentages across AIs
SplitInflationPerAI(ctx sdk.Context) map[string]math.LegacyDec
```

**EVM Integration:**

```go
// Deploy GemCoreNFT factory contract from module account
DeployFactory(ctx sdk.Context) (common.Address, error)

// Internal: Deploy contract with no arguments required
DeployContract(ctx sdk.Context) (common.Address, error)

// Call contract method with explicit compiled contract parameter
CallMethod(ctx sdk.Context, method string, contract evmtypes.CompiledContract,
           from common.Address, contractAddr *common.Address, amount *big.Int,
           args ...interface{}) (*evmtypes.MsgEthereumTxResponse, error)

// Execute arbitrary EVM call
CallEVM(ctx sdk.Context, from common.Address, to *common.Address,
        amount *big.Int, data []byte, commit bool) (*evmtypes.MsgEthereumTxResponse, error)
```

### Module Parameters

The brahma module has the following governance-tunable parameters:

```protobuf
message Params {
  // Maximum allowed size for a Core Grant Application
  int64 max_core_grant_allocation = 1;

  // Block height at which a Core Grant Application expires (blocks after creation)
  int64 core_grant_application_expiry_height = 2;

  // List of allowed contribution types with descriptions and active status
  ContributionTypes contribution_types = 3;

  // Percentage of rewards allocated to AI creator (decimal string, e.g., "0.5" for 50%)
  string creator_split = 4;

  // Percentage of rewards allocated to Application (decimal string, e.g., "0.3" for 30%)
  string application_split = 5;

  // Percentage of rewards allocated to contributors (decimal string, e.g., "0.2" for 20%)
  string contributor_split = 6;

  // Percentage of newly minted tokens to siphon for AI rewards (decimal string, e.g., "0.05" for 5%)
  string siphon_percentage = 7;

  // Gas limit for EVM transactions from the module account
  uint64 evm_gas_limit = 8;

  // Gas cap for EVM transactions from the module account
  uint64 evm_gas_cap = 9;

  // Maximum number of AIs eligible for inflation rewards (based on insertion order)
  uint64 max_ais_for_rewards = 10;

  // Maximum number of historical block heights to process per AI when allocating rewards
  uint64 max_ai_block_heights = 11;

  // Maximum number of tensor rows to process per block (prevents unbounded processing)
  uint64 max_tensor_rows_per_block = 12;
}
```

**Parameter Accessors:**

```go
// Get all parameters at once
GetParams(ctx sdk.Context) Params

// Individual parameter getters (return math.LegacyDec for percentage fields)
GetCreatorSplit(ctx sdk.Context) (math.LegacyDec, error)
GetApplicationSplit(ctx sdk.Context) (math.LegacyDec, error)
GetContributorSplit(ctx sdk.Context) (math.LegacyDec, error)
GetSiphonPercentage(ctx sdk.Context) (math.LegacyDec, error)
```

**Constants (NOT tunable parameters):**

* `MaxAddressesPerMint = 100` - Max addresses per mint call
* `MaxBatchSize = 100` - Max items per batch operation
* `MaxMarketCapHistorySize = 100` - Max market cap snapshots per AI

### Query Endpoints

**gRPC/REST API:**

```
/cosmos/evm/brahma/v1/params                                    - Module parameters
/cosmos/evm/brahma/v1/aitensor/{aiId}/{blockHeight}            - Get AI tensor data
/cosmos/evm/brahma/v1/tensorrow/{aiId}/{blockHeight}/{wallet}  - Get contribution by wallet
/cosmos/evm/brahma/v1/CoreGrantApplication/{requester}         - Get grant for requester
/cosmos/evm/brahma/v1/allblockheights/{aiId}                   - All block heights for AI
/cosmos/evm/brahma/v1/core                                     - Core token addresses
/cosmos/evm/brahma/v1/ai/{aiId}                                - AI token addresses (ERC20/ERC1155)
/cosmos/evm/brahma/v1/claimable-rewards/{address}              - Claimable rewards
/cosmos/evm/brahma/v1/claim-statistics                         - Statistics about pending claims
```

**Note:** There is no `/brahma/v1/ais` or `/brahma/v1/grants` endpoint. Query individual items by ID/address.

### State Storage

The module uses prefixed storage with different encoding patterns:

```go
// Storage Key Prefixes (from types/keys.go)
AITensorsPrefix             = 0x01  // AI tensor data
CoreGrantApplicationsPrefix = 0x02  // Active grant applications
AddrsPrefix                 = 0x03  // Address contributions
AIPrefix                    = 0x04  // AI registry
HistoricalAITensorsPrefix   = 0x05  // Historical tensors
KeyPrefixGemErc20Addresses  = 0x01  // Gem token addresses (iota)
KeyPrefixGemErc1155Addresses = 0x02 // Gem NFT addresses (iota)
KeyPrefixOreAdapterContractAddress = 0x03
KeyPrefixOre1155ContractAddress = 0x04
KeyPrefixClaimableRewards   = 0x05  // Pending rewards
KeyPrefixMarketCaps         = 0x06  // Market cap history
KeyPrefixAIIDOrdered        = 0x20  // AI insertion order
KeyPrefixAIIDOrderedCount   = 0x21  // Total AI count
```

**Key Construction Patterns:**

```go
// Simple keys (no length prefix):
// Grant key: prefix + raw address bytes
key := append(CoreGrantApplicationsPrefix, requesterAddress.Bytes()...)

// AI key: prefix + raw AI ID bytes
key := append(AIPrefix, aiID...)

// Tensor keys (WITH length prefix for collision resistance):
// Format: [aiID_length (2 bytes)] + [aiID] + [height (8 bytes)] + [address]
func buildAITensorRowKey(aiID []byte, height int64, address string) []byte {
    // Add 2-byte length prefix for aiID
    aiIDLength := uint16(len(aiID))
    lengthPrefix := make([]byte, 2)
    binary.BigEndian.PutUint16(lengthPrefix, aiIDLength)

    heightBytes := sdk.Uint64ToBigEndian(uint64(height))

    // Build key: [length prefix] + [aiID] + [height] + [address]
    key := append(lengthPrefix, aiID...)
    key = append(key, heightBytes...)
    key = append(key, []byte(address)...)
    return key
}
```

**Critical:** Tensor keys use length-prefix encoding to prevent key-space collisions when aiID is variable-length. This is essential for security and for extracting the address component later.

## x/precompile Module

The Precompile module bridges BitSDK functionality to EVM smart contracts through precompiled contracts at fixed addresses.

### Available Precompiles

**1. Staking (0x0000000000000000000000000000000000000800)**

```solidity
interface IStaking {
    function delegate(address delegator, address validator, uint256 amount) external returns (bool);
    function undelegate(address delegator, address validator, uint256 amount) external returns (bool);
    function redelegate(address delegator, address src, address dst, uint256 amount) external returns (bool);
    function createValidator(address validator, bytes calldata pubkey, uint256 amount) external returns (bool);
}
```

**2. Distribution (0x0000000000000000000000000000000000000801)**

```solidity
interface IDistribution {
    function claimRewards(address delegator, address validator) external returns (uint256);
    function withdrawDelegatorRewards(address delegator, address validator) external returns (bool);
    function setWithdrawAddress(address delegator, address withdrawAddr) external returns (bool);
}
```

**3. Bank (0x0000000000000000000000000000000000000804)**

```solidity
interface IBank {
    function balances(address account, string calldata denom) external view returns (uint256);
    function totalSupply(string calldata denom) external view returns (uint256);
    function supplyOf() external view returns (Coin[] memory);
}
```

**4. Governance (0x0000000000000000000000000000000000000805)**

```solidity
interface IGovernance {
    function submitProposal(bytes calldata messages, string calldata metadata,
                           string calldata title, string calldata summary) external returns (uint64);
    function vote(uint64 proposalId, uint32 option, string calldata metadata) external returns (bool);
    function deposit(uint64 proposalId, uint256 amount) external returns (bool);
}
```

**5. ICS-20 Transfer (0x0000000000000000000000000000000000000802)**

```solidity
interface ICS20I {
    // Full signature from actual implementation
    function transfer(
        string memory sourcePort,
        string memory sourceChannel,
        string memory denom,
        uint256 amount,
        address sender,              // sender is an address, not bech32
        string memory receiver,      // receiver is bech32 string
        Height memory timeoutHeight, // Height struct, not uint64
        uint64 timeoutTimestamp,
        string memory memo
    ) external returns (uint64 nextSequence);  // returns sequence number
}

struct Height {
    uint64 revisionNumber;
    uint64 revisionHeight;
}
```

**6. Slashing (0x0000000000000000000000000000000000000806)**

```solidity
interface ISlashing {
    function unjail(address validator) external returns (bool);
}
```

**7. Bech32 (0x0000000000000000000000000000000000000400)**

```solidity
interface IBech32 {
    function hexToBech32(address addr, string calldata prefix) external pure returns (string memory);
    function bech32ToHex(string calldata bech32Addr) external pure returns (address);
}
```

**8. Custom: Brahma Precompile**

Address configured via governance parameters. Monitors EVM events to trigger governance actions:

```solidity
// Events monitored by precompile hooks
event CoreGrantApplicationEvent(address indexed proposer, uint256 indexed grantAmount);
event OreRequestEvent(address indexed addr, string name, uint256[] values);
event ContributionTypes(string[] types, string[] descriptions);
```

### Contract Address Management

**Precompile Module Parameters:**

The precompile module maintains addresses for dynamically deployed contracts:

```protobuf
message Params {
  // Address of the governance precompile contract
  string gov_precompile = 1;

  // Address of the GemCoreNFT factory contract
  string gem_core_nft_factory = 2;

  // Address of the CSR (Contract Secured Revenue) turnstile contract
  string csr_turnstile = 3;

  // Address of the Uniswap V2 router contract
  string uniswap_router = 4;

  // Address of the Uniswap V2 factory contract
  string uniswap_factory = 5;

  // Address of the staking precompile contract
  string staking_precompile = 6;

  // Address of the brahma precompile contract (for event monitoring)
  string brahma_precompile = 7;
}
```

**Retrieve addresses via keeper methods:**

```go
params := k.precompileKeeper.GetParams(ctx)
govPrecompile := params.GovPrecompile          // Field 1
gemCoreFactory := params.GemCoreNftFactory     // Field 2
csrTurnstile := params.CsrTurnstile            // Field 3
uniswapRouter := params.UniswapRouter          // Field 4
uniswapFactory := params.UniswapFactory        // Field 5
stakingPrecompile := params.StakingPrecompile  // Field 6
brahmaPrecompile := params.BrahmaPrecompile    // Field 7
```

**Update via governance:**

```protobuf
message MsgUpdateParams {
  string authority = 1;
  Params params = 2;  // All 7 fields must be supplied
}
```

## Next Steps

* Learn how contracts interact with modules in [Smart Contract Integration](/developer-guides/smart-contract.md)
* Understand the complete flow in [Module Interaction](/developer-guides/module-interaction.md)
* Review security best practices in [Security Considerations](/developer-guides/security-considerations.md)
* Get started with development in [Quick Start](/developer-guides/quick-start.md)
