#!/usr/bin/env python3
"""
Discover available functions by checking BSCScan transactions
"""
from web3 import Web3
import requests
import time

BSC_RPC = "https://bsc-dataseed.binance.org/"
CONTRACT_ADDRESS = "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0"

w3 = Web3(Web3.HTTPProvider(BSC_RPC))

print("="*80)
print("🔍 ANALYZING APOLLOX V2 CONTRACT TRANSACTIONS")
print("="*80)

# Get our successful open transaction
open_tx_hash = "0x2acb765216574bd5b015d0cd4f4be9f0b5ae9c53bc41171b87ffc2e59f9f7974"

print(f"\n📊 Analyzing successful OPEN transaction:")
print(f"   TX: {open_tx_hash}")

tx = w3.eth.get_transaction(open_tx_hash)

print(f"\n   Input data (first 10 bytes - function selector):")
print(f"   {tx['input'][:10]}")

# Function selector is first 4 bytes (8 hex chars after 0x)
open_selector = tx['input'][:10]
print(f"\n   ✅ openMarketTrade selector: {open_selector}")

print(f"\n🔍 Now let's search BSCScan for CLOSE transactions to this contract...")
print(f"   We'll look for other common patterns\n")

# Common close/exit function selectors to try
common_close_selectors = {
    '0x2e1a7d4d': 'withdraw(uint256)',
    '0x45e8a627': 'closePosition(bytes32)',
    '0x30d87f05': 'closeTrade(bytes32)',
    '0x96cd4ddb': 'closeMarketTrade(bytes32)',
    '0x48a0d754': 'close(bytes32)',
}

print("Common close function selectors:")
for selector, sig in common_close_selectors.items():
    print(f"   {selector}: {sig}")

print(f"\n📊 Let's manually compute the selector for closeTrade(bytes32):")
from eth_utils import keccak

func_sig = "closeTrade(bytes32)"
selector = '0x' + keccak(text=func_sig).hex()[:8]
print(f"   {func_sig} -> {selector}")

func_sig2 = "closeMarketTrade(bytes32)"
selector2 = '0x' + keccak(text=func_sig2).hex()[:8]
print(f"   {func_sig2} -> {selector2}")

print(f"\n💡 The closeTrade selector we should use: {selector}")

print("\n" + "="*80)
