#!/usr/bin/env bash
# Error handling utilities

handle_rpc_error() {
    local error="$1"
    if echo "$error" | grep -q "insufficient funds"; then
        echo "ERROR: Insufficient balance for transaction"
        return 1
    elif echo "$error" | grep -q "nonce too low"; then
        echo "ERROR: Transaction nonce too low. Wait for pending transactions."
        return 1
    elif echo "$error" | grep -q "replacement transaction underpriced"; then
        echo "ERROR: Pending transaction exists. Wait or increase gas price."
        return 1
    elif echo "$error" | grep -q "execution reverted"; then
        echo "ERROR: Transaction reverted. Check contract state."
        return 1
    fi
    return 0
}

retry_transaction() {
    local command="$1"
    local max_retries=3
    local retry=0
    
    while [ $retry -lt $max_retries ]; do
        if eval "$command"; then
            return 0
        fi
        ((retry++))
        sleep 5
    done
    return 1
}
