#!/usr/bin/env bash
# Check contract bytecode on-chain
# Usage: ./check-contract-bytecode.sh [address]

set -euo pipefail

RPC_URL="${RPC_URL:-https://rpc-core.d-bis.org}"
ADDRESS="${1:-}"

if [ -z "$ADDRESS" ]; then
    echo "Usage: $0 <contract-address>"
    echo ""
    echo "Example: $0 0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6"
    exit 1
fi

echo "Checking contract bytecode for: $ADDRESS"
echo "RPC: $RPC_URL"
echo ""

BYTECODE=$(cast code "$ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

if [ -z "$BYTECODE" ] || [ "$BYTECODE" = "0x" ]; then
    echo "❌ Contract has no bytecode (not deployed or empty)"
    exit 1
else
    BYTECODE_LENGTH=$((${#BYTECODE} - 2))  # Subtract "0x" prefix
    echo "✅ Contract has bytecode"
    echo "   Length: $BYTECODE_LENGTH characters ($((BYTECODE_LENGTH / 2)) bytes)"
    echo "   First 100 chars: ${BYTECODE:0:100}..."
    echo ""
    echo "✅ Contract is deployed and has code"
fi
