# CCIP Fees

## Overview

CCIP messages require LINK tokens to pay for cross-chain message delivery. This document explains how fees are calculated and managed.

## Fee Calculation

CCIP fees are calculated based on:

1. **Message Size**: Larger messages cost more
2. **Target Chain**: Different chains have different fee rates
3. **Gas Price**: Current gas prices on target chain
4. **Token Type**: Native tokens vs LINK tokens

## Calculating Fees

Use the `calculateFee()` function to get the required fee:

```solidity
CCIPSender sender = CCIPSender(senderAddress);
uint256 fee = sender.calculateFee(targetChainSelector, messageData);
```

## Fee Payment

Fees are paid when sending the message:

```solidity
sender.sendOracleUpdate{value: fee}(targetChainSelector, receiverAddress, messageData);
```

## Fee Estimation

### Typical Fees (as of 2024)

- **Small message** (< 100 bytes): ~0.01-0.05 LINK
- **Medium message** (100-500 bytes): ~0.05-0.2 LINK
- **Large message** (> 500 bytes): ~0.2-1.0 LINK

*Note: Fees vary by chain and network conditions*

## Managing LINK Balance

### Check Balance

```solidity
IERC20 linkToken = IERC20(LINK_TOKEN_ADDRESS);
uint256 balance = linkToken.balanceOf(address(this));
```

### Transfer LINK

```bash
# Transfer LINK to sender contract
cast send $LINK_TOKEN "transfer(address,uint256)" $SENDER_CONTRACT $AMOUNT \
  --rpc-url $RPC_URL --private-key $PRIVATE_KEY
```

### Approve Spending

```solidity
IERC20 linkToken = IERC20(LINK_TOKEN_ADDRESS);
linkToken.approve(senderAddress, amount);
```

## Fee Monitoring

Monitor fee consumption:

- Track total fees spent
- Monitor fee per message
- Alert on high fee usage
- Set fee budgets

### Metrics

- `ccip_fees_total`: Total LINK spent on fees
- `ccip_fees_per_message`: Average fee per message
- `ccip_fee_errors`: Failed transactions due to insufficient fees

## Cost Optimization

### 1. Minimize Message Size

- Use efficient encoding
- Remove unnecessary data
- Compress data when possible

### 2. Batch Updates

- Combine multiple updates into one message
- Reduce number of messages sent
- Lower total fee cost

### 3. Monitor Gas Prices

- Send during low gas price periods
- Use gas price oracles
- Schedule updates strategically

### 4. Use Native Tokens

- Some chains support native token payments
- May be cheaper than LINK in some cases

## Fee Limits

Set maximum fee limits to prevent excessive spending:

```solidity
uint256 constant MAX_FEE_PER_MESSAGE = 1 ether; // 1 LINK

require(fee <= MAX_FEE_PER_MESSAGE, "Fee too high");
```

## Refunds

CCIP may refund unused fees if:
- Message fails to deliver
- Target chain is unavailable
- Message is rejected

Check refund status in transaction logs.

## Troubleshooting

### Insufficient LINK

**Error**: "Insufficient LINK balance"

**Solution**:
1. Check LINK balance
2. Transfer more LINK tokens
3. Verify token address is correct

### Fee Too High

**Error**: "Fee exceeds limit"

**Solution**:
1. Reduce message size
2. Wait for lower gas prices
3. Increase fee limit (if appropriate)

### Fee Calculation Failed

**Error**: "Failed to calculate fee"

**Solution**:
1. Verify CCIP Router is accessible
2. Check target chain selector is valid
3. Ensure router is properly configured

## Best Practices

1. **Maintain Buffer**: Keep 2-3x expected fees in balance
2. **Monitor Regularly**: Check fee consumption daily
3. **Set Alerts**: Alert on low balance or high fees
4. **Budget Planning**: Plan for fee costs in operations budget
5. **Test Fees**: Test fee calculation in staging environment

## References

- [CCIP Integration Guide](CCIP_INTEGRATION.md)
- [CCIP Router Setup](CCIP_ROUTER_SETUP.md)
- [Chainlink CCIP Fees](https://docs.chain.link/ccip/fees)
