#!/usr/bin/env bash
# Optimize gas usage for bridge operations
# Usage: ./optimize-gas-usage.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}"

# Get optimal gas price based on network conditions
get_optimal_gas_price() {
    local current_gas=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    local multiplier=1.2  # Use 1.2x for optimal balance between speed and cost
    echo "scale=0; $current_gas * $multiplier / 1" | bc
}

# Estimate gas for operation
estimate_gas() {
    local contract="$1"
    local function="$2"
    local args="$3"
    
    cast estimate "$contract" "$function" $args --rpc-url "$RPC_URL" 2>/dev/null || echo "0"
}

# Batch operations to reduce gas
batch_operations() {
    echo "=== Gas Optimization Strategies ==="
    echo ""
    echo "1. Use optimal gas price: $(echo "scale=2; $(get_optimal_gas_price) / 1000000000" | bc) gwei"
    echo "2. Batch multiple approvals into single transaction when possible"
    echo "3. Use gas estimation before sending transactions"
    echo "4. Send transactions during low network congestion"
    echo ""
    
    # Get current gas price
    local current_gas=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    local optimal_gas=$(get_optimal_gas_price)
    
    echo "Current Network Gas: $(echo "scale=2; $current_gas / 1000000000" | bc) gwei"
    echo "Optimal Gas Price: $(echo "scale=2; $optimal_gas / 1000000000" | bc) gwei"
    echo ""
    echo "Recommendation: Use $(echo "scale=2; $optimal_gas / 1000000000" | bc) gwei for transactions"
}

batch_operations

