> 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/precompile-module.md).

# x/precompile Module

The x/precompile module serves as a central registry for precompiled contract addresses, making them accessible from the EVM layer. It also processes specific EVM events through the PostTxProcessing hook for reward claiming operations.

## Overview

The module provides:

1. **Precompile Address Registry**: Stores and manages contract addresses for key system components
2. **Event Processing**: Handles `BplCoinClaimed` events for reward distribution
3. **Governance-Controlled Updates**: All addresses can be updated via governance proposals

**Key Feature:** The module maintains critical contract addresses (GemCoreNFT Factory, Uniswap contracts) and processes reward claiming events from the EVM layer.

## Architecture

### How It Works

```
1. Smart contract operations emit events
2. EVM executes transaction and generates receipt
3. x/precompile PostTxProcessing hook intercepts receipt
4. Module checks for BplCoinClaimed events
5. If found, processes reward claiming
6. Updates claimable balances in x/brahma module
```

**Example Flow:**

```
User → Claims rewards via UI/Contract
     → Event: BplCoinClaimed(address, amount)
     → PostTxProcessing Hook
     → Reward Handler
     → brahmaKeeper.ProcessClaim(ctx, ...)
     → Rewards transferred to user
```

## Registered Contract Addresses

The module maintains a registry of important contract addresses used throughout the system:

### Currently Implemented Addresses

**GemCoreNFT Factory**

* Main factory contract for Core and Gem token operations
* Handles minting, burning, and token management
* Uses UUPS upgradeable pattern for future enhancements
* Deploys ERC-20 and ERC-1155 token contracts via BeaconProxy pattern
* BeaconFactory enables efficient deployment of multiple token instances with shared logic

**CSR Turnstile**

* Contract-secured revenue operations
* Manages revenue distribution mechanisms

**Uniswap Integration**

* **Router**: DEX routing for token swaps
* **Factory**: Liquidity pool creation and management

### Placeholder Addresses (Future Development)

The module structure supports additional precompile addresses for future integration:

* Governance precompile (for on-chain governance from EVM)
* Staking precompile (for validator operations from EVM)
* Brahma precompile (for direct EVM interaction with x/brahma)

These addresses are defined in the module parameters but are not yet implemented in the current version.

## Event Interfaces

The module primarily processes events emitted by smart contracts:

### BplCoinClaimed Event

```solidity
event BplCoinClaimed(
    address indexed user,
    uint256 amount
);
```

This event is emitted when users claim their accumulated rewards through the EVM interface. The module's PostTxProcessing hook listens for this event and triggers the reward distribution from the x/brahma module.

### Future Interface Support

The module architecture supports adding Solidity interfaces for:

* Direct staking operations from smart contracts
* Governance participation from EVM
* Brahma module interactions

These interfaces will be implemented as the system evolves and requirements become clearer.

## Event Processing

### PostTxProcessing Hook

The module implements the EVM `PostTxProcessing` hook to process reward claiming events:

**Flow:**

1. EVM transaction completes
2. Hook receives transaction receipt with logs
3. Scans logs for `BplCoinClaimed` events
4. Decodes event data (user address and amount)
5. Triggers reward distribution through x/brahma module
6. Updates user's claimable balance

**Implementation:**

```go
func (k Keeper) PostTxProcessing(ctx sdk.Context, receipt *ethtypes.Receipt) error {
  for _, log := range receipt.Logs {
    // Check if this is a BplCoinClaimed event
    if isBplCoinClaimedEvent(log) {
      // Decode user address and amount
      user, amount := decodeClaimEvent(log)

      // Process the claim through brahma module
      return k.brahmaKeeper.ProcessRewardClaim(ctx, user, amount)
    }
  }
  return nil
}
```

## Module Parameters

The module stores precompile contract addresses as governance-controlled parameters:

| Parameter              | Description                         |
| ---------------------- | ----------------------------------- |
| `gov_precompile`       | Custom governance interface address |
| `staking_precompile`   | Custom staking interface address    |
| `brahma_precompile`    | Brahma module interface address     |
| `gem_core_nft_factory` | GemCoreNFT factory contract address |
| `csr_turnstile`        | CSR operations contract address     |
| `uniswap_router`       | DEX router contract address         |
| `uniswap_factory`      | DEX factory contract address        |

**Features:**

* All addresses updatable via governance
* Validates Ethereum address format (0x...)
* Empty addresses allowed (precompile disabled)

## Message Types

### MsgUpdateParams

Updates precompile contract addresses:

```protobuf
message MsgUpdateParams {
  string authority = 1;  // Governance module account
  Params params = 2;     // New parameter values
}
```

**Requirements:**

* Authority-only (governance module)
* Validates all addresses are valid Ethereum hex format
* Updates take effect immediately

## Integration Examples

### Example: Claiming Rewards from Smart Contract

```solidity
// Smart contract emitting BplCoinClaimed event
contract RewardClaimer {
    event BplCoinClaimed(address indexed user, uint256 amount);

    function claimRewards(uint256 amount) external {
        // Validation logic here

        // Emit event for x/precompile module to process
        emit BplCoinClaimed(msg.sender, amount);
    }
}
```

**Result:** The PostTxProcessing hook detects the event and triggers reward distribution from the x/brahma module to the user's account.

### Future Integration Patterns

As the system evolves, the precompile module will support more complex integrations:

* Direct governance participation from smart contracts
* Automated staking operations
* Cross-module interactions through EVM

## Type Conversions

The module handles conversions between EVM and Cosmos types:

**Address Conversion:**

```
Ethereum (20 bytes, 0x...) ↔ Cosmos (bech32, cosmos1...)
```

**Amount Conversion:**

```
BigInt (EVM) ↔ sdk.Int (BitSDK)
```

**String Handling:**

```
ABI-encoded strings ↔ Go strings
```

## Security Features

**Address Validation:**

* All precompile addresses validated as proper Ethereum hex
* Invalid addresses rejected at parameter update

**Authorization:**

* Governance-only control for precompile address updates
* Event handlers validate caller permissions

**Safe Type Conversion:**

* Overflow protection when converting BigInt to sdk.Int
* Address format validation before Cosmos operations

**Event Signature Verification:**

* Only registered event signatures processed
* Unknown events ignored (no error)

## Integration with x/brahma

The x/precompile module integrates with x/brahma primarily through:

**Reward Claiming:**

* Processes `BplCoinClaimed` events from EVM contracts
* Triggers reward distribution in x/brahma module
* Updates claimable balances for users

**Contract Address Registry:**

* Stores GemCoreNFT factory address used by x/brahma for core minting
* Maintains addresses for token operations

**Future Integration Points:** The architecture supports future enhancements for:

* Direct Core Grant Application submission from EVM
* Request for Core processing through smart contracts
* Contribution type management via governance

## Query Endpoints

**Params Query:**

```bash
evmd query precompile params
```

Returns all configured precompile contract addresses.

## Benefits

**For Developers:**

* Use familiar Solidity syntax
* Access native Cosmos features
* No need to learn BitSDK message types

**For Users:**

* Interact via standard Web3 wallets (MetaMask)
* Unified interface for EVM and Cosmos operations
* Transparent bridging between ecosystems

**For the Ecosystem:**

* Seamless EVM-Cosmos integration
* Enables hybrid AI Apps using both layers
* Governance-controlled address updates

## Limitations

**Event-Driven Only:**

* Precompiles emit events, not return values
* Cannot query Cosmos state directly from Solidity
* Asynchronous execution model

**Gas Considerations:**

* EVM gas paid by user
* Cosmos gas consumed by module
* Two-layer gas accounting

**Address Format:**

* Must convert between Ethereum and Cosmos addresses
* Users need both address types for full functionality
