# CCIP Integration: Chain-138 to Ethereum Mainnet

## Overview

Production-grade CCIP integration that turns Chain-138 activity into verified, on-chain Ethereum transactions using Chainlink CCIP.

## Architecture

```
Chain-138 (Source)                    Chainlink CCIP                    Ethereum Mainnet (Destination)
┌──────────────────┐                  ┌──────────────┐                  ┌──────────────────┐
│ CCIPTxReporter   │ ────ccipSend───> │ CCIP Router  │ ────ccipReceive─> │ CCIPLogger       │
│ (Sender)         │                  │ / Oracle     │                  │ (Receiver)       │
└──────────────────┘                  │ Network      │                  └──────────────────┘
         ▲                            └──────────────┘                           │
         │                                                                         │
         │                                                                         ▼
┌──────────────────┐                                                      ┌──────────────┐
│ Watcher/Relayer   │                                                      │ Events &     │
│ (Off-chain)       │                                                      │ State        │
└──────────────────┘                                                      └──────────────┘
```

## Components

### 1. Smart Contracts

#### CCIPLogger (Ethereum Mainnet)
- **Location**: `contracts/ccip-integration/CCIPLogger.sol`
- **Purpose**: Receives and logs Chain-138 transactions via CCIP
- **Features**:
  - Replay protection (batch ID tracking)
  - Optional signature verification
  - Source chain validation
  - Event emission for indexing

#### CCIPTxReporter (Chain-138)
- **Location**: `archive/solidity/contracts/ccip-integration/CCIPTxReporter.sol`
- **Purpose**: Reports Chain-138 transactions to Ethereum via CCIP
- **Status**: Historical source archived out of the active compile graph
- **Features**:
  - Single transaction reporting
  - Batch reporting (cost optimization)
  - Fee estimation
  - Automatic refund of excess fees

### 2. Deployment Scripts

- **CCIPLogger**: `scripts/ccip-deployment/deploy-ccip-logger.js`
- **CCIPTxReporter**: `scripts/ccip-deployment/deploy-ccip-reporter.js` (archival note only; restore source before redeploying)

### 3. Watcher/Relayer Service

- **Location**: `watcher/`
- **Purpose**: Off-chain service that watches Chain-138 and relays transactions
- **Features**:
  - WebSocket/HTTP subscription to Chain-138
  - Postgres outbox pattern for reliability
  - Batching for cost optimization
  - Retry logic with exponential backoff
  - Metrics and monitoring

## Deployment Guide

### Prerequisites

1. Install dependencies:
```bash
npm install
cd watcher && npm install
```

2. Configure `.env`:
```env
# Ethereum Mainnet
ETHEREUM_MAINNET_RPC=https://mainnet.infura.io/v3/YOUR_KEY
ETHERSCAN_API_KEY=your_etherscan_key
CCIP_ETH_ROUTER=0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D
ETH_MAINNET_SELECTOR=0x500147

# Chain-138
CHAIN138_RPC_URL=https://rpc.d-bis.org
CHAIN138_RPC_WS=wss://rpc.d-bis.org/ws
CCIP_CHAIN138_ROUTER=<chain-138-ccip-router-address>
CHAIN138_SELECTOR=0x000000000000008a

# Deployment
PRIVATE_KEY=your_deployer_private_key
AUTHORIZED_SIGNER=optional_signer_address

# Relayer
RELAYER_PRIVATE_KEY=relayer_private_key
BATCH_SIGNER_PRIVATE_KEY=batch_signer_private_key
DATABASE_URL=postgresql://user:pass@localhost:5432/ccip_relayer
```

### Step 1: Deploy CCIPLogger to Ethereum Mainnet

```bash
npm run deploy:logger:mainnet
```

This will:
1. Deploy CCIPLogger contract
2. Display deployment address
3. Provide verification command

### Step 2: Deploy CCIPTxReporter to Chain-138

```bash
export CHAIN138_CCIP_REPORTER=0x...
```

This will:
1. Point the flow at the existing historical deployment
2. Keep verification scripts aware of the reporter address
3. Avoid restoring archived source unless a fresh redeploy is truly needed

### Step 3: Verify Contracts

```bash
# Verify CCIPLogger on Etherscan
npx hardhat verify --network mainnet <CCIP_LOGGER_ADDRESS> <ROUTER> <SIGNER> <SELECTOR>

# Verify CCIPTxReporter (if explorer available)
npx hardhat verify --network chain138 <CCIP_REPORTER_ADDRESS> <ROUTER> <SELECTOR> <RECEIVER>
```

### Step 4: Start Watcher/Relayer

```bash
cd watcher
npm run build
npm start
```

## Configuration

### CCIP Directory

Use the [Chainlink CCIP Directory](https://docs.chain.link/ccip/supported-networks) to get:
- Chain selectors for each network
- Router addresses
- Supported tokens

### Chain Selectors

Update chain selectors in `.env` based on CCIP Directory:
- Ethereum Mainnet: Check CCIP Directory
- Chain-138: Check CCIP Directory or contact Chainlink support

## Security Checklist

- [ ] Use multisig (Gnosis Safe) for contract ownership
- [ ] Store private keys in hardware KMS (AWS KMS, GCP KMS, YubiKey)
- [ ] Set `authorizedSigner` for batch verification
- [ ] Configure `expectedSourceChainSelector` correctly
- [ ] Implement rate limiting in watcher
- [ ] Set up monitoring and alerting
- [ ] Test on testnets before mainnet deployment
- [ ] Review gas limits and fee management
- [ ] Implement circuit breakers for error conditions

## Monitoring

### Metrics

The watcher exposes Prometheus metrics:
- `ccip_batches_sent_total`
- `ccip_batches_success_total`
- `ccip_batches_failed_total`
- `ccip_tx_queue_size`
- `ccip_fee_estimate_gwei`

### Alerts

Set up alerts for:
- Failed batch deliveries
- Low LINK/ETH balance
- High queue size
- CCIP delivery latency

## Testing

### Local Testing with Chainlink Local

1. Start Chainlink Local:
```bash
docker run -p 6688:6688 chainlink/local:latest
```

2. Run integration tests:
```bash
npm test
```

### Testnet Testing

1. Deploy to Sepolia (Ethereum testnet)
2. Deploy to Chain-138 testnet (if available)
3. Test full flow end-to-end

## Cost Optimization

1. **Batching**: Group multiple transactions per CCIP message
2. **Compression**: Store only hashes on-chain, full data off-chain
3. **Adaptive Batching**: Adjust batch size based on mempool activity
4. **Fee Management**: Monitor and optimize CCIP fees

## References

- [Chainlink CCIP Documentation](https://docs.chain.link/ccip)
- [CCIP Directory](https://docs.chain.link/ccip/supported-networks)
- [CCIP Starter Kit](https://github.com/smartcontractkit/ccip-starter-kit)
- [Chainlink Local](https://github.com/smartcontractkit/chainlink-local)

## Support

For issues or questions:
1. Check Chainlink CCIP documentation
2. Review contract code comments
3. Check watcher logs
4. Contact Chainlink support for CCIP-specific issues
