#!/usr/bin/env bash
# Automatic retry for failed bridge transactions
# Usage: ./retry-failed-transactions.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

source "$SOURCE_PROJECT/.env" 2>/dev/null || true

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
MAX_RETRIES=3
RETRY_DELAY=30

# Get dynamic gas price
get_optimal_gas() {
    local current_gas=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    local multiplier=1.5
    echo "scale=0; $current_gas * $multiplier / 1" | bc
}

# Retry transaction with higher gas
retry_transaction() {
    local command="$1"
    local retry=0
    
    while [ $retry -lt $MAX_RETRIES ]; do
        local gas_price=$(get_optimal_gas)
        echo "Retry $((retry + 1))/$MAX_RETRIES with gas: $(echo "scale=2; $gas_price / 1000000000" | bc) gwei"
        
        if eval "$command --gas-price $gas_price"; then
            echo "✓ Transaction succeeded"
            return 0
        fi
        
        ((retry++))
        if [ $retry -lt $MAX_RETRIES ]; then
            echo "Waiting $RETRY_DELAY seconds before retry..."
            sleep $RETRY_DELAY
        fi
    done
    
    echo "✗ Transaction failed after $MAX_RETRIES retries"
    return 1
}

# Check for pending/failed transactions
check_pending_transactions() {
    DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")
    if [ -z "$DEPLOYER" ]; then
        echo "ERROR: Cannot determine deployer address"
        return 1
    fi
    
    local current_nonce=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    local pending_nonce=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" --pending 2>/dev/null || echo "0")
    
    if [ "$pending_nonce" -gt "$current_nonce" ]; then
        echo "Found $((pending_nonce - current_nonce)) pending transactions"
        return 0
    fi
    
    return 1
}

main() {
    echo "=== Retry Failed Transactions ==="
    
    if check_pending_transactions; then
        echo "Pending transactions detected. Monitor them first."
    else
        echo "No pending transactions found"
    fi
}

main "$@"

