#!/usr/bin/env bash
# Bridge with dynamic gas pricing
# Usage: ./bridge-with-dynamic-gas.sh [token] [amount] [chain]

set -euo pipefail

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

source "$SOURCE_PROJECT/.env"

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-0xe0E93247376aa097dB308B92e6Ba36bA015535D0}"

TOKEN="${1:-weth9}"
AMOUNT="${2:-1.0}"
CHAIN="${3:-all}"

# Get dynamic gas price
CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
MULTIPLIER=1.5
OPTIMAL_GAS=$(echo "scale=0; $CURRENT_GAS * $MULTIPLIER / 1" | bc)

echo "=== Bridge with Dynamic Gas ==="
echo "Current gas: $(echo "scale=2; $CURRENT_GAS / 1000000000" | bc) gwei"
echo "Using gas: $(echo "scale=2; $OPTIMAL_GAS / 1000000000" | bc) gwei (1.5x for faster inclusion)"
echo ""

# Use optimal gas price for bridge operations
export OPTIMAL_GAS_PRICE="$OPTIMAL_GAS"

if [ "$CHAIN" = "all" ]; then
    bash "$SCRIPT_DIR/bridge-to-all-7-chains.sh" "$TOKEN" "$AMOUNT"
else
    # Single chain transfer with dynamic gas
    DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)
    AMOUNT_WEI=$(cast --to-wei "$AMOUNT" ether 2>/dev/null)
    
    declare -A SELECTORS=(
        ["bsc"]="11344663589394136015"
        ["polygon"]="4051577828743386545"
        ["avalanche"]="6433500567565415381"
        ["base"]="15971525489660198786"
        ["arbitrum"]="4949039107694359620"
        ["optimism"]="3734403246176062136"
        ["ethereum"]="5009297550715157269"
    )
    
    selector="${SELECTORS[$CHAIN]}"
    bridge="$WETH9_BRIDGE"
    [ "$TOKEN" = "weth10" ] && bridge="$WETH10_BRIDGE"
    
    cast send "$bridge" \
        "sendCrossChain(uint64,address,uint256)" \
        "$selector" \
        "$DEPLOYER" \
        "$AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "$OPTIMAL_GAS" \
        2>&1
fi

