# CCIP Message Tracking Specification

## Overview

This document specifies how CCIP (Cross-Chain Interoperability Protocol) messages are tracked from source chain to destination chain, including status monitoring and execution receipt linking.

## CCIP Message Lifecycle

```mermaid
sequenceDiagram
    participant Source as Source Chain
    participant CCIP as CCIP DON
    participant Dest as Destination Chain
    participant Indexer as Indexer
    
    Source->>Indexer: Emit CCIP MessageSent event
    Indexer->>Indexer: Index source tx + messageId
    CCIP->>Dest: Deliver message
    Dest->>Indexer: Emit CCIP MessageExecuted event
    Indexer->>Indexer: Link messageId to dest tx
    Indexer->>Indexer: Update message status
```

## Message Ingestion

### Source Chain Events

**Event**: `MessageSent(address indexed sender, uint64 indexed destinationChainSelector, bytes receiver, bytes data, address feeToken, uint256 fee)`

**Data Extracted**:
- `messageId`: Unique message identifier
- `sender`: Source address
- `destinationChainSelector`: Destination chain selector
- `receiver`: Destination receiver address
- `data`: Message payload
- `feeToken`: Fee token address
- `fee`: Fee amount
- `transactionHash`: Source transaction hash
- `blockNumber`: Source block number
- `timestamp`: Source transaction timestamp

### Destination Chain Events

**Event**: `MessageExecuted(bytes32 indexed messageId, uint64 indexed sourceChainSelector, bytes sender, bytes data)`

**Data Extracted**:
- `messageId`: Message identifier (matches source)
- `sourceChainSelector`: Source chain selector
- `sender`: Source sender address
- `data`: Message payload
- `transactionHash`: Destination transaction hash
- `blockNumber`: Destination block number
- `timestamp`: Destination transaction timestamp
- `status`: Execution status (success/failure)

## Message ID Normalization

### Message ID Format

**Source**: Generated from transaction hash and event log index
**Format**: `keccak256(transactionHash, logIndex)` or CCIP-provided messageId

### Normalization Strategy

**Goal**: Ensure consistent messageId across source and destination

**Method**:
1. Extract messageId from source event
2. Store with source transaction
3. Match with destination event by messageId
4. Link source and destination transactions

## Delivery Status Tracking

### Status States

**States**:
- `sent`: Message sent on source chain
- `delivered`: Message delivered to CCIP DON
- `executing`: Message executing on destination chain
- `executed`: Message executed successfully
- `failed`: Message execution failed
- `expired`: Message expired (timeout)

### Status Transitions

```
sent → delivered → executing → executed
                ↓
              failed
                ↓
             expired (if timeout)
```

### Status Updates

**Tracking**:
- Monitor destination chain for execution events
- Poll CCIP router for message status (if API available)
- Track timeout periods
- Update status in database

## Execution Receipt Linking

### Receipt Storage

**Database Schema**:
```sql
CREATE TABLE ccip_messages (
    id UUID PRIMARY KEY,
    message_id VARCHAR(66) NOT NULL UNIQUE,
    source_chain_id INTEGER NOT NULL,
    source_tx_hash VARCHAR(66) NOT NULL,
    source_block_number BIGINT NOT NULL,
    destination_chain_id INTEGER NOT NULL,
    destination_tx_hash VARCHAR(66),
    destination_block_number BIGINT,
    status VARCHAR(20) NOT NULL,
    sent_at TIMESTAMP NOT NULL,
    executed_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
```

### Linking Process

**Steps**:
1. Index source transaction with messageId
2. Wait for destination chain event
3. Match messageId from destination event
4. Link destination transaction to source
5. Update status to "executed" or "failed"

## Retry Tracking

### Retry Detection

**Detection**:
- Multiple execution attempts with same messageId
- Track retry count
- Store retry timestamps

### Retry Data

**Fields**:
- `retry_count`: Number of retry attempts
- `retry_timestamps`: Array of retry attempt times
- `last_retry_at`: Last retry timestamp

## API Endpoints

### Get Message by ID

`GET /api/v1/ccip/messages/{message_id}`

**Response**:
```json
{
  "message_id": "0x...",
  "source": {
    "chain_id": 138,
    "tx_hash": "0x...",
    "block_number": 12345,
    "sender": "0x...",
    "timestamp": "2024-01-01T00:00:00Z"
  },
  "destination": {
    "chain_id": 1,
    "tx_hash": "0x...",
    "block_number": 19000000,
    "receiver": "0x...",
    "timestamp": "2024-01-01T00:05:00Z"
  },
  "status": "executed",
  "sent_at": "2024-01-01T00:00:00Z",
  "executed_at": "2024-01-01T00:05:00Z"
}
```

### Get Message by Transaction

`GET /api/v1/ccip/transactions/{chain_id}/{tx_hash}/messages`

**Response**: Array of CCIP messages for transaction

### Search Messages

`GET /api/v1/ccip/messages`

**Query Parameters**:
- `source_chain_id`: Filter by source chain
- `destination_chain_id`: Filter by destination chain
- `status`: Filter by status
- `sender`: Filter by sender address
- `receiver`: Filter by receiver address

## References

- CCIP Observability: See `ccip-observability.md`
- CCIP Event Schema: See `ccip-event-schema.md`
- Graph Database: See `../database/graph-schema.md`

