#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/init.sh"
load_env --file "$ROOT_DIR/.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="get-contract-tx.sh"
SCRIPT_DESC="Query contract transactions on ChainID 138 via Etherscan-like API"
SCRIPT_USAGE="${SCRIPT_NAME} --address <addr> [--start <n>] [--end <n>] [--sort asc|desc] [--apikey <key>] [--url <api>]"
SCRIPT_OPTIONS="--address ADDR     Contract address
--start N          Start block (default: 0)
--end N            End block (default: 99999999)
--sort asc|desc    Sort order (default: desc)
--apikey KEY       API key (default: CHAIN138_ETHERSCAN_API_KEY)
--url URL          API base (default: CHAIN138_ETHERSCAN_API_URL)"
handle_help "${1:-}"

ADDR=""; START=0; END=99999999; SORT="desc"; KEY="${CHAIN138_ETHERSCAN_API_KEY:-}"; API="${CHAIN138_ETHERSCAN_API_URL:-}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --address) ADDR="$2"; shift 2;;
    --start) START="$2"; shift 2;;
    --end) END="$2"; shift 2;;
    --sort) SORT="$2"; shift 2;;
    --apikey) KEY="$2"; shift 2;;
    --url) API="$2"; shift 2;;
    --help) handle_help "--help";;
    *) log_error "Unknown arg: $1"; exit 1;;
  esac
done

[ -n "$ADDR" ] || { log_error "Missing --address"; exit 1; }
[ -n "$API" ] || { log_error "Set CHAIN138_ETHERSCAN_API_URL or pass --url"; exit 1; }

URL="${API}?module=account&action=txlist&address=${ADDR}&startblock=${START}&endblock=${END}&sort=${SORT}${KEY:+&apikey=$KEY}"
curl -s "$URL" | jq .


