# Real-Time Gas Price Updates

**Last Updated**: 2025-01-27

## Overview

This document explains how to use the real-time gas price fetching system to update all deployment cost estimates using live data from configured APIs.

## Quick Start

```bash
# 1. Fetch real-time gas prices for all chains
./scripts/deployment/get-multichain-gas-prices.sh

# 2. Update all documentation with real-time prices
./scripts/deployment/update-gas-estimates.sh
```

## Scripts

### `get-multichain-gas-prices.sh`

Fetches real-time gas prices from configured APIs and calculates deployment costs.

**Features**:
- Fetches gas prices for all 5 chains (Mainnet, Cronos, BSC, Polygon, Gnosis)
- Uses Etherscan API for Ethereum Mainnet (if configured)
- Uses RPC endpoints for other chains
- Calculates costs in native tokens and USD
- Exports values for use in other scripts
- Saves data to JSON file for programmatic access

**Usage**:
```bash
./scripts/deployment/get-multichain-gas-prices.sh
```

**Output**:
- Displays current gas prices for all chains
- Shows deployment cost estimates
- Exports environment variables
- Saves JSON file to `/tmp/multichain_gas_prices.json`

**Example Output**:
```
========================================
Multichain Gas Price Fetcher
========================================

Fetching real-time gas prices...
✓ Gas prices fetched

Current Gas Prices:
  Ethereum Mainnet: 25.5 gwei
  Cronos: 1.2 gwei
  BSC: 3.5 gwei
  Polygon: 45.0 gwei
  Gnosis: 2.1 gwei

Deployment Cost Estimates:

Ethereum Mainnet (CCIPLogger only):
  Gas: 3000000 units
  Cost: 0.0765 ETH (~$191.25)

Cronos (all 5 contracts):
  Gas: 8760000 units
  Cost: 10.512 CRO (~$0.84)
...
```

### `update-gas-estimates.sh`

Updates all documentation files with real-time gas prices and costs.

**Features**:
- Reads gas price data from `get-multichain-gas-prices.sh`
- Updates `GAS_AND_TOKEN_REQUIREMENTS.md`
- Updates `TOKENS_AND_CHAINS_SUMMARY.md`
- Updates `DEPLOYMENT_QUICK_REFERENCE.md`
- Updates timestamps in all files

**Usage**:
```bash
./scripts/deployment/update-gas-estimates.sh
```

**Prerequisites**:
- Must run `get-multichain-gas-prices.sh` first (or it will run automatically)

**Updated Files**:
1. `docs/deployment/GAS_AND_TOKEN_REQUIREMENTS.md`
   - Updates gas price tables
   - Updates cost estimates
   - Updates timestamps

2. `docs/deployment/TOKENS_AND_CHAINS_SUMMARY.md`
   - Updates recommended balances
   - Updates cost estimates
   - Updates timestamps

3. `docs/deployment/DEPLOYMENT_QUICK_REFERENCE.md`
   - Updates quick reference tables
   - Updates minimum balances

## Configuration

### Required Environment Variables

Add these to your `.env` file:

```bash
# Ethereum Mainnet (for Etherscan API)
ETHERSCAN_API_KEY=your_etherscan_api_key_here
ETH_MAINNET_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY

# Other Chains (RPC endpoints)
CRONOS_RPC_URL=https://evm.cronos.org
BSC_RPC_URL=https://bsc-dataseed1.binance.org
POLYGON_RPC_URL=https://polygon-rpc.com
GNOSIS_RPC_URL=https://rpc.gnosischain.com
```

### Optional: Infura Gas API

If you have an Infura account, you can also configure:

```bash
INFURA_GAS_API=your_infura_api_key_here
# Or full URL:
INFURA_GAS_API=https://gas.api.infura.io/networks/1/suggestedGasFees
```

## Gas Price Sources

### Ethereum Mainnet

1. **Etherscan Gas API v2** (Primary)
   - Endpoint: `https://api.etherscan.io/v2/api?chainid=1&module=gastracker&action=gasoracle&apikey={API_KEY}`
   - Returns: SafeGasPrice, ProposeGasPrice, FastGasPrice
   - Uses: FastGasPrice for estimates

2. **RPC Endpoint** (Fallback)
   - Uses `eth_gasPrice` RPC call
   - Via `ETH_MAINNET_RPC_URL`

3. **Default** (Final Fallback)
   - 20 gwei if all APIs fail

### Other Chains

1. **RPC Endpoint** (Primary)
   - Uses `eth_gasPrice` RPC call
   - Via `*_RPC_URL` environment variables

2. **Default** (Fallback)
   - Chain-specific defaults:
     - Cronos: 1,000 gwei (1 gwei in ETH terms)
     - BSC: 5 gwei
     - Polygon: 50 gwei
     - Gnosis: 2 gwei

## Cost Calculation

### Formula

```
Cost (Native Token) = (Gas Units × Gas Price in Wei) / 10^18
Cost (USD) = Cost (Native Token) × Token Price (USD)
```

### Gas Units

- **Ethereum Mainnet**: 3,000,000 gas (CCIPLogger only)
- **Other Chains**: 8,760,000 gas (all 5 contracts with 20% buffer)

### Exchange Rates

Current approximate rates (update as needed):
- ETH: $2,500
- CRO: $0.08
- BNB: $300
- MATIC: $0.80
- xDAI: $1.00

## JSON Output Format

The script saves data to `/tmp/multichain_gas_prices.json`:

```json
{
  "timestamp": "2025-01-27 12:00:00 UTC",
  "gas_prices": {
    "ethereum_mainnet": {
      "gwei": "25.5",
      "wei": "25500000000",
      "gas_units": 3000000,
      "cost_eth": "0.0765",
      "cost_usd": "191.25"
    },
    "cronos": {
      "gwei": "1.2",
      "wei": "1200000000",
      "gas_units": 8760000,
      "cost_cro": "10.512",
      "cost_usd": "0.84"
    },
    ...
  },
  "total_usd": "520.05"
}
```

## Integration with CI/CD

You can integrate this into your deployment pipeline:

```bash
#!/bin/bash
# Pre-deployment gas check

# Fetch real-time prices
./scripts/deployment/get-multichain-gas-prices.sh

# Check if costs are acceptable
ETH_COST=$(jq -r '.gas_prices.ethereum_mainnet.cost_eth' /tmp/multichain_gas_prices.json)
ETH_THRESHOLD=0.20

if (( $(echo "$ETH_COST > $ETH_THRESHOLD" | bc -l) )); then
    echo "⚠️  Gas costs are high ($ETH_COST ETH). Consider waiting."
    exit 1
fi

# Proceed with deployment
echo "✓ Gas costs acceptable. Proceeding with deployment."
```

## Troubleshooting

### Script Fails to Fetch Gas Prices

1. **Check API Keys**:
   ```bash
   echo $ETHERSCAN_API_KEY
   echo $ETH_MAINNET_RPC_URL
   ```

2. **Test API Endpoints**:
   ```bash
   # Test Etherscan API
   curl -s "https://api.etherscan.io/v2/api?chainid=1&module=gastracker&action=gasoracle&apikey=${ETHERSCAN_API_KEY}"

   # Test RPC endpoints
   cast gas-price --rpc-url $ETH_MAINNET_RPC_URL
   ```

3. **Check Network Connectivity**:
   ```bash
   ping -c 1 api.etherscan.io
   ```

### Documentation Not Updating

1. **Check File Permissions**:
   ```bash
   ls -la docs/deployment/*.md
   ```

2. **Verify Script Execution**:
   ```bash
   ./scripts/deployment/get-multichain-gas-prices.sh
   ./scripts/deployment/update-gas-estimates.sh
   ```

3. **Check JSON File**:
   ```bash
   cat /tmp/multichain_gas_prices.json
   ```

## Best Practices

1. **Update Before Deployment**: Always run the scripts before deploying
2. **Monitor Gas Prices**: Gas prices fluctuate - check regularly
3. **Use Buffers**: Recommended balances include 20-50% buffer
4. **Test on Testnets**: Verify everything works before mainnet
5. **Document Changes**: Note any manual adjustments to estimates

## Related Documentation

- [Gas and Token Requirements](./GAS_AND_TOKEN_REQUIREMENTS.md) - Detailed cost breakdown
- [Multichain Deployment Runbook](./MULTICHAIN_DEPLOYMENT_RUNBOOK.md) - Complete deployment guide
- [Environment Variables Template](./ENV_EXAMPLE_CONTENT.md) - .env configuration

---

**Last Updated**: 2025-01-27

