# Mainnet Tether and Transaction Mirror Implementation

**Date**: 2025-12-11
**Status**: Ready for Deployment

---

## 📋 Overview

This document describes the implementation of:
1. **MainnetTether** - Anchors Chain-138 state proofs to Ethereum Mainnet (Kaleido-style)
2. **TransactionMirror** - Mirrors Chain-138 transactions to Mainnet for Etherscan visibility

---

## 🔗 MainnetTether Contract

### Purpose

Following Kaleido's pattern, the MainnetTether contract:
- Stores signed state proofs from Chain-138 validators
- Creates immutable, verifiable records of Chain-138 state on Mainnet
- Anchors Chain-138 state at regular intervals
- Provides security and transparency through public verification
- Prevents collusion by requiring collective validator signatures

### Contract Details

**File**: `contracts/tether/MainnetTether.sol`
**Deployment Script**: `script/DeployMainnetTether.s.sol`
**Status**: ✅ Ready for deployment

### Key Features

- **State Proof Storage**: Stores block number, hash, state root, and validator signatures
- **Replay Protection**: Prevents duplicate state proofs
- **Block Anchoring**: Tracks all anchored blocks
- **Admin Control**: Pausable with admin-only functions
- **Query Functions**: Easy lookup of anchored state proofs

### Deployment

```bash
# Set admin address (multisig recommended)
export TETHER_ADMIN=0x...

# Deploy to Mainnet
forge script script/DeployMainnetTether.s.sol \
  --rpc-url $ETH_MAINNET_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify

# Update .env
echo "MAINNET_TETHER_ADDRESS=<deployed_address>" >> .env
```

### Usage

#### Anchor State Proof

```solidity
// Called by off-chain service that collects validator signatures
tether.anchorStateProof(
    blockNumber,        // Chain-138 block number
    blockHash,          // Chain-138 block hash
    stateRoot,          // Chain-138 state root
    previousBlockHash,  // Previous block hash
    timestamp,          // Block timestamp
    signatures,         // Collective validator signatures
    validatorCount      // Number of validators
);
```

#### Query State Proof

```solidity
// Check if block is anchored
bool anchored = tether.isAnchored(blockNumber);

// Get state proof details
StateProof memory proof = tether.getStateProof(blockNumber);
```

---

## 🔍 TransactionMirror Contract

### Purpose

The TransactionMirror contract:
- Logs all Chain-138 transactions as events on Mainnet
- Makes Chain-138 transactions searchable on Etherscan
- Provides transparency and auditability
- Enables cross-chain transaction visibility

### Contract Details

**File**: `contracts/mirror/TransactionMirror.sol`
**Deployment Script**: `script/DeployTransactionMirror.s.sol`
**Status**: ✅ Ready for deployment

### Key Features

- **Transaction Logging**: Stores transaction details (hash, from, to, value, etc.)
- **Event Emission**: Emits indexed events for Etherscan searchability
- **Batch Support**: Can mirror multiple transactions in one call
- **Replay Protection**: Prevents duplicate transaction mirroring
- **Query Functions**: Easy lookup of mirrored transactions

### Deployment

```bash
# Set admin address (multisig recommended)
export MIRROR_ADMIN=0x...

# Deploy to Mainnet
forge script script/DeployTransactionMirror.s.sol \
  --rpc-url $ETH_MAINNET_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify

# Update .env
echo "TRANSACTION_MIRROR_ADDRESS=<deployed_address>" >> .env
```

### Usage

#### Mirror Single Transaction

```solidity
// Called by off-chain service that monitors Chain-138
mirror.mirrorTransaction(
    txHash,          // Chain-138 transaction hash
    from,            // Sender address
    to,              // Recipient address
    value,           // Value transferred
    blockNumber,     // Chain-138 block number
    blockTimestamp,  // Block timestamp
    gasUsed,         // Gas used
    success,         // Transaction success status
    data             // Transaction data (optional)
);
```

#### Mirror Batch Transactions

```solidity
// Mirror multiple transactions at once (more gas efficient)
mirror.mirrorBatchTransactions(
    txHashes,        // Array of transaction hashes
    froms,           // Array of sender addresses
    tos,             // Array of recipient addresses
    values,          // Array of values
    blockNumbers,    // Array of block numbers
    blockTimestamps, // Array of timestamps
    gasUseds,        // Array of gas used
    successes,       // Array of success statuses
    datas            // Array of transaction data
);
```

#### Query Mirrored Transaction

```solidity
// Check if transaction is mirrored
bool mirrored = mirror.isMirrored(txHash);

// Get transaction details
MirroredTransaction memory tx = mirror.getTransaction(txHash);
```

---

## 🔄 Integration with Off-Chain Services

### State Proof Anchoring Service

An off-chain service should:
1. Monitor Chain-138 blocks
2. Collect validator signatures for each block
3. Call `anchorStateProof()` on MainnetTether at regular intervals (e.g., every 6 hours)
4. Handle retries and error cases

### Transaction Mirroring Service

An off-chain service should:
1. Monitor Chain-138 for new transactions
2. Extract transaction details
3. Call `mirrorTransaction()` or `mirrorBatchTransactions()` on TransactionMirror
4. Batch transactions for gas efficiency
5. Handle retries and error cases

### Example Service Architecture

```
Chain-138 Network
  ↓
Off-Chain Monitor Service
  ├─→ State Proof Collector → MainnetTether.anchorStateProof()
  └─→ Transaction Monitor → TransactionMirror.mirrorTransaction()
  ↓
Ethereum Mainnet
  ├─→ MainnetTether (state proofs)
  └─→ TransactionMirror (transaction logs)
  ↓
Etherscan (public visibility)
```

---

## 📊 Benefits

### MainnetTether Benefits

1. **Security**: Immutable record of Chain-138 state on Mainnet
2. **Transparency**: Publicly verifiable state proofs
3. **Integrity**: Prevents state manipulation
4. **Auditability**: Historical state records
5. **Trust**: Validator signatures provide consensus proof

### TransactionMirror Benefits

1. **Visibility**: All Chain-138 transactions visible on Etherscan
2. **Searchability**: Indexed events enable easy searching
3. **Transparency**: Public audit trail
4. **Cross-Chain**: Unified view across chains
5. **Compliance**: Meets regulatory transparency requirements

---

## ⚙️ Configuration

### Environment Variables

Add to `.env`:

```bash
# MainnetTether
TETHER_ADMIN=0x...  # Multisig recommended
MAINNET_TETHER_ADDRESS=  # Set after deployment

# TransactionMirror
MIRROR_ADMIN=0x...  # Multisig recommended (can be same as TETHER_ADMIN)
TRANSACTION_MIRROR_ADDRESS=  # Set after deployment
```

### Recommended Settings

- **Admin Addresses**: Use multisig wallets (Gnosis Safe recommended)
- **Anchoring Frequency**: Every 6 hours (configurable)
- **Mirroring Frequency**: Real-time or batch every block
- **Gas Optimization**: Use batch functions when possible

---

## 🚀 Deployment Plan

### Step 1: Deploy MainnetTether

```bash
forge script script/DeployMainnetTether.s.sol \
  --rpc-url $ETH_MAINNET_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify
```

### Step 2: Deploy TransactionMirror

```bash
forge script script/DeployTransactionMirror.s.sol \
  --rpc-url $ETH_MAINNET_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify
```

### Step 3: Set Up Off-Chain Services

1. Deploy state proof anchoring service
2. Deploy transaction mirroring service
3. Configure monitoring and alerting
4. Test with small batches

### Step 4: Verify on Etherscan

1. Verify both contracts on Etherscan
2. Test transaction mirroring
3. Verify events are visible
4. Test state proof anchoring

---

## 📝 Gas Estimates

### MainnetTether

- **Deployment**: ~1,200,000 gas (~$30-50 at current prices)
- **anchorStateProof()**: ~150,000-300,000 gas (depends on signature size)

### TransactionMirror

- **Deployment**: ~1,000,000 gas (~$25-40 at current prices)
- **mirrorTransaction()**: ~80,000-120,000 gas per transaction
- **mirrorBatchTransactions()**: ~50,000 + (60,000 * count) gas (more efficient)

---

## ⚠️ Important Notes

1. **Admin Security**: Use multisig for admin addresses
2. **Gas Costs**: Monitor gas costs for frequent operations
3. **Off-Chain Services**: Critical for functionality - ensure high availability
4. **Replay Protection**: Built-in, but verify in testing
5. **Pausability**: Can pause in emergency situations
6. **Testing**: Test thoroughly on testnet before mainnet deployment

---

## 🔗 Related Contracts

- **MirrorManager**: Address registry (separate from TransactionMirror)
- **TwoWayTokenBridge**: Token bridging (separate from state anchoring)
- **CCIPWETH9Bridge/CCIPWETH10Bridge**: Existing CCIP bridges

---

## 📚 References

- [Kaleido Tether Documentation](https://docs.kaleido.io/kaleido-services/tether/)
- [Etherscan Event Search](https://etherscan.io/apis#events)
- [Foundry Deployment Guide](MULTICHAIN_DEPLOYMENT_RUNBOOK.md)

---

**Last Updated**: 2025-12-11
**Status**: Contracts ready, deployment pending
