> For the complete documentation index, see [llms.txt](https://docs.astralbeam.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.astralbeam.io/for-developers/system-components.md).

# System Components

This page provides detailed documentation of each component in the AstralBeam architecture.

## EVM Smart Contracts

### MultiSigLocker

The MultiSigLocker contract manages token locking and unlocking on EVM chains.

```mermaid
flowchart TB
    subgraph MultiSigLocker
        Lock[locktoken, amount, recipient]
        Unlock[unlockattestation, signatures]
        Admin[Admin Functions]

        subgraph State
            Lockers[Per-Token Lockers]
            Relayers[Registered Relayers]
            Threshold[M-of-N Threshold]
            ProcessedNonces[Processed Nonces]
        end
    end

    User[User] --> Lock
    Relayer[Relayers] --> Unlock
    Owner[Owner] --> Admin

    Lock --> Lockers
    Unlock --> ProcessedNonces
    Admin --> Relayers
    Admin --> Threshold
```

**Key Functions:**

| Function                               | Access | Description                          |
| -------------------------------------- | ------ | ------------------------------------ |
| `lock(token, amount, casperRecipient)` | Public | Lock ERC-20 tokens for bridging      |
| `unlock(attestation, signatures)`      | Public | Unlock tokens with M-of-N signatures |
| `addRelayer(address)`                  | Owner  | Add a relayer to the whitelist       |
| `removeRelayer(address)`               | Owner  | Remove a relayer                     |
| `setThreshold(m)`                      | Owner  | Set minimum signatures required      |
| `pause()` / `unpause()`                | Owner  | Emergency pause mechanism            |

**Events:**

```solidity
event Locked(
    address indexed token,
    address indexed sender,
    bytes32 casperRecipient,
    uint256 amount,
    uint256 nonce
);

event Unlocked(
    address indexed token,
    address indexed recipient,
    uint256 amount,
    bytes32 indexed casperStateRoot,
    bytes32 eventKey
);
```

### Wrapped Tokens

For Casper-native tokens bridged to EVM chains, wrapped ERC-20 tokens are deployed:

**Key Properties:**

* Deployed by MultiSigLocker when first bridging a Casper-native token
* Standard ERC-20 interface with mint/burn controlled by the locker
* Token metadata (name, symbol, decimals) mirrors the Casper CEP-18 token

## Casper Smart Contracts

### EthClient

Stores EVM block headers and verifies MPT (Merkle Patricia Trie) proofs.

```mermaid
flowchart TB
    subgraph EthClient
        Submit["submit_block_header_with_signatures()"]
        Verify["verify_receipt_proof()"]
        Query[Query Functions/Read-Only]

        subgraph Storage[Per-Chain Storage]
            Headers["Block Headers chain_id, block_number → Header"]
            Latest[Latest Block per chain]
        end
    end

    Relayers[Relayers] --> Submit
    TokenFactory[TokenFactory] --> Verify
    Anyone[Anyone] --> Query

    Submit --> Headers
    Submit --> Latest
    Verify --> Headers
```

**Key Functions:**

| Function                                                           | Access | Description                                |
| ------------------------------------------------------------------ | ------ | ------------------------------------------ |
| `submit_block_header_with_signatures(chain_id, block_number, ...)` | Public | Submit block header with M-of-N signatures |
| `verify_receipt_proof(chain_id, block_number, proof)`              | View   | Verify MPT receipt proof                   |
| `get_block_hash(chain_id, block_number)`                           | View   | Get stored block hash                      |
| `get_receipts_root(chain_id, block_number)`                        | View   | Get stored receipts root                   |
| `is_block_known(chain_id, block_number)`                           | View   | Check if block is stored                   |
| `get_latest_block(chain_id)`                                       | View   | Get latest stored block for chain          |

**Storage Schema:**

```rust
struct EthClient {
    // Per-chain block storage
    block_headers: Mapping<(u64, u64), BlockHeader>,  // (chain_id, block_number)
    latest_blocks: Mapping<u64, u64>,                  // chain_id → latest_block

    // Relayer management
    relayers: Vec<Address>,
    threshold: u32,

    // Administration
    admin: Address,
}

struct BlockHeader {
    block_hash: H256,
    state_root: H256,
    receipts_root: H256,
}
```

### TokenFactory

Manages CEP-18 token deployment, minting, and burning.

```mermaid
flowchart TB
    subgraph TokenFactory
        Mint["mint_with_signatures()"]
        Burn["burn()"]
        LockNative["lock_native()"]
        UnlockNative["unlock_native_with_signatures()"]
        Deploy["deploy_token()"]

        subgraph TokenRegistry
            Mappings[EVM Token → CEP-18 Mapping]
            Deployed[Deployed CEP-18 Contracts]
        end
    end

    Relayers[Relayers] --> Mint
    Relayers --> UnlockNative
    User[User] --> Burn
    User --> LockNative
    Admin[Admin] --> Deploy
    
    Mint --> TokenRegistry
    Burn --> TokenRegistry
```

**Key Functions:**

| Function                                                 | Access | Description                     |
| -------------------------------------------------------- | ------ | ------------------------------- |
| `mint_with_signatures(attestation, proof, signatures)`   | Public | Mint CEP-18 tokens (EVM→Casper) |
| `burn(token, amount, evmRecipient)`                      | Public | Burn CEP-18 tokens (Casper→EVM) |
| `lock_native(evmRecipient)`                              | Public | Lock native CSPR                |
| `unlock_native_with_signatures(attestation, signatures)` | Public | Unlock native CSPR              |
| `deploy_token(evmToken, name, symbol, decimals)`         | Admin  | Deploy new CEP-18 wrapper       |
| `register_token_mapping(chainId, evmToken, cep18Hash)`   | Admin  | Register token mapping          |

**Events/Deploys:**

```rust
// Lock event (for Casper → EVM)
BurnEvent {
    cep18_token: ContractHash,
    evm_token: Address,
    sender: AccountHash,
    evm_recipient: Address,
    amount: U256,
    nonce: u64,
    source_chain_id: u64,
}

// Mint event (EVM → Casper)
MintEvent {
    cep18_token: ContractHash,
    recipient: AccountHash,
    amount: U256,
    source_chain_id: u64,
    evm_tx_hash: H256,
}
```

## Relayer Infrastructure

### Relayer Node

Each relayer node runs multiple workers and services:

```mermaid
flowchart TB
    subgraph RelayerNode[Relayer Node]
        subgraph Workers
            EVM2Casper[EVM→Casper Worker]
            Casper2EVM[Casper→EVM Worker]
        end

        subgraph Services
            P2PService[P2P Service HTTP/HTTPS]
            MetricsService[Metrics Service]
        end

        subgraph Storage
            JSONFiles[JSON Files data/]
            StateCache[State Cache]
        end
    end

    EVM2Casper <--> P2PService
    Casper2EVM <--> P2PService
    EVM2Casper --> JSONFiles
    Casper2EVM --> JSONFiles
    MetricsService --> Prometheus[Prometheus]
```

### EVM → Casper Worker

Handles the EVM to Casper bridge direction:

**Responsibilities:**

1. Monitor EVM chains for `Locked` events
2. Wait for finality (64 blocks on Ethereum)
3. Generate MPT proofs for receipts
4. Create and sign block header attestations
5. Exchange signatures via P2P
6. Submit block headers to EthClient
7. Submit mint attestations to TokenFactory

**State Machine:**

```mermaid
stateDiagram-v2
    [*] --> Monitoring: Start
    Monitoring --> EventDetected: Lock event found
    EventDetected --> WaitingFinality: Record pending
    WaitingFinality --> ProofGeneration: Finality reached
    ProofGeneration --> SignatureCollection: Proof generated
    SignatureCollection --> Submission: M signatures collected
    Submission --> Monitoring: Success
    Submission --> SignatureCollection: Retry on failure
```

### Casper → EVM Worker

Handles the Casper to EVM bridge direction:

**Responsibilities:**

1. Monitor Casper for `Burn` events
2. Generate state proofs
3. Create and sign unlock attestations
4. Exchange signatures via P2P
5. Submit unlock transactions to MultiSigLocker

**State Machine:**

```mermaid
stateDiagram-v2
    [*] --> Monitoring: Start
    Monitoring --> EventDetected: Burn event found
    EventDetected --> ProofGeneration: Instant finality
    ProofGeneration --> SignatureCollection: Proof generated
    SignatureCollection --> Submission: M signatures collected
    Submission --> Monitoring: Success
    Submission --> SignatureCollection: Retry on failure
```

### P2P Network

Relayers communicate via an HTTP/HTTPS-based P2P network with TLS encryption:

```mermaid
flowchart TB
    subgraph P2PNetwork[P2P Network HTTP/HTTPS + TLS]
        subgraph Endpoints
            Signatures[Signature Exchange]
            Status[Status & Health]
            Sync[State Synchronization]
            Auth[Authentication]
        end

        R1[Relayer 1] <--> Signatures
        R2[Relayer 2] <--> Signatures
        R3[Relayer 3] <--> Signatures

        R1 <--> Status
        R2 <--> Status
        R3 <--> Status
    end
```

**Architecture:**

* Express-based HTTP/HTTPS server on each relayer
* TLS encryption for secure communication
* Mutual authentication via auth challenges
* Direct peer-to-peer messaging (no pubsub topics)

**Message Types:**

| Category                   | Message Type          | Purpose                                                                                                                                     |
| -------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Signature Coordination** | `signature_request`   | Request signature from peers for an attestation                                                                                             |
|                            | `signature_response`  | Return signed attestation to requesting peer                                                                                                |
|                            | `signature_broadcast` | Broadcast signature to all peers proactively                                                                                                |
| **Health & Discovery**     | `heartbeat`           | Periodic liveness check between peers                                                                                                       |
|                            | `peer_list`           | Share known peer addresses                                                                                                                  |
|                            | `announce`            | Announce presence to network                                                                                                                |
|                            | `get_peers`           | Request peer list from a node                                                                                                               |
| **Status Queries**         | `status_request`      | Request current processing status                                                                                                           |
|                            | `status_response`     | Return processing status (blocks, events)                                                                                                   |
| **State Sync**             | `sync_request`        | Request missed events/attestations                                                                                                          |
|                            | `sync_response`       | Return requested sync data                                                                                                                  |
| **Authentication**         | `auth_challenge`      | Challenge peer to prove identity                                                                                                            |
|                            | `auth_response`       | Respond to auth challenge with signature                                                                                                    |
| **Event Notification**     | `event_processed`     | Notify peers that an event was processed                                                                                                    |
| **Submission Claims**      | `submission_claimed`  | Claim an in-flight submission at dispatch so backups extend (never reset) their failover deadline — bounded hold, hard-capped               |
|                            | `submission_failed`   | Advise peers of a deterministic (permanent) rejection; receivers verify on-chain and check the tx was claimed for that event before parking |

**Attestation Types:**

| Type           | Direction    | Description                        |
| -------------- | ------------ | ---------------------------------- |
| `lock`         | EVM → Casper | ERC-20 lock event attestation      |
| `unlock`       | Casper → EVM | CEP-18 burn for unlock attestation |
| `wrapped_mint` | EVM → Casper | Mint wrapped token attestation     |
| `wrapped_burn` | Casper → EVM | Burn wrapped token attestation     |
| `block_header` | EVM → Casper | EVM block header attestation       |

## API Server

The API server provides REST endpoints for the frontend and integrators:

```mermaid
flowchart LR
    subgraph APIServer[API Server]
        Routes[Routes]
        Swagger[Swagger UI]

        subgraph Endpoints
            Tokens["/api/v1/tokens"]
            Transactions["/api/v1/transactions"]
            Stats["/api/v1/stats"]
            Chains["/api/v1/chains"]
            Health["/api/v1/health"]
        end
    end

    Client[Client] --> Routes
    Routes --> Endpoints
    Routes --> Swagger
    Endpoints --> DB[MySQL/Aurora]
```

**Endpoints:**

| Endpoint               | Method | Description               |
| ---------------------- | ------ | ------------------------- |
| `/api/v1/tokens`       | GET    | List supported tokens     |
| `/api/v1/transactions` | GET    | Query bridge transactions |
| `/api/v1/stats`        | GET    | Bridge statistics         |
| `/api/v1/chains`       | GET    | Supported chains          |
| `/api/v1/health`       | GET    | Service health check      |
| `/api-docs`            | GET    | Swagger UI                |

## Monitoring Stack

### Prometheus Metrics

Key metrics exposed by relayers:

| Metric                                | Type    | Description                    |
| ------------------------------------- | ------- | ------------------------------ |
| `bridge_events_detected_total`        | Counter | Events detected per chain/type |
| `bridge_attestations_submitted_total` | Counter | Attestations submitted         |
| `bridge_signatures_collected`         | Gauge   | Signatures per attestation     |
| `bridge_block_headers_stored`         | Gauge   | Block headers per chain        |
| `bridge_pending_transactions`         | Gauge   | Pending bridge transactions    |
| `bridge_worker_errors_total`          | Counter | Worker errors                  |

### Grafana Dashboards

Pre-configured dashboards for:

* Bridge Overview (transactions, volume, success rate)
* Per-Chain Metrics (blocks, events, latency)
* Relayer Health (P2P connectivity, signatures)
* Security Alerts (invalid attestations, replay attempts)

## Component Dependencies

```mermaid
flowchart TD
    subgraph External
        EVM[EVM RPC Nodes]
        Casper[Casper RPC Nodes]
    end

    subgraph Infrastructure
        DB[MySQL/Aurora]
        Prometheus[Prometheus]
        Grafana[Grafana]
    end

    subgraph Application
        Relayers[Relayer Nodes]
        API[API Server]
        Web[Web Frontend]
    end

    Relayers --> EVM
    Relayers --> Casper
    Relayers --> Prometheus
    API --> DB
    Web --> API
    Prometheus --> Grafana
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.astralbeam.io/for-developers/system-components.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
