import asyncio
import aiohttp
import json

bscscan_api_key = '<TRUFFLEHOG_REDACTED_BSCSCAN>'

# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
api_request_delay = 0.2  # Set a 200ms delay between API requests

async def get_external_transactions(block_number):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
            try:
                async with session.get(url) as response:
                    data = await response.json()
            except Exception as e:
                print(f'Error in API request: {e}')
                return []
            if data['result'] is None or isinstance(data['result'], str):
                print(f"Error: Cannot find the block")
                return []

            return data['result'].get('transactions', [])

async def get_contract_address(tx_hash):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
            try:
                async with session.get(url) as response:
                    data = await response.json()
            except Exception as e:
                print(f'Error in API request: {e}')
                return None

            if data['result'] is None or not isinstance(data['result'], dict):
                return None

            return data['result'].get('contractAddress')

async def get_contract_verification_status(contract_address: str) -> bool:
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            url = f"https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey={bscscan_api_key}"

            try:
                async with session.get(url) as response:
                    data = await response.json()
            except Exception as e:
                print(f"Error in API request: {e}")
                return False

            if data["result"] is None or not isinstance(data["result"], str):
                return False

            return data["result"] != "Contract source code not verified"

async def get_contract_abi(contract_address: str) -> str:
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            url = f"https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey={bscscan_api_key}"

            # Retry mechanism in case of failures
            retries = 3
            while retries > 0:
                try:
                    await asyncio.sleep(api_request_delay)
                    async with session.get(url) as response:
                        data = await response.json()

                    if data["result"] is None or not isinstance(data["result"], str):
                        retries -= 1
                        continue

                    return data["result"]
                except Exception as e:
                    print(f"Error in API request: {e}")
                    retries -= 1

            return ""  # Return an empty string if retries are exhausted

async def get_token_name_from_abi(contract_address: str) -> str:
    abi_str = await get_contract_abi(contract_address)
    if not abi_str:  # empty string
        return ""

    try:
        contract_abi = json.loads(abi_str)
        for contract_item in contract_abi:
            if contract_item.get("type") == "function" and contract_item.get("name") == "name":
                return "YES"
        return ""
    except Exception as e:
        print(f"Error parsing ABI: {e}")
        return "NO"

def check_method_id(input_data):
    method_id = input_data[:10]
    return method_id[-4:] == '6040'

async def is_contract_verified(contract_address: str) -> bool:
    return await get_contract_verification_status(contract_address)

async def display_transactions(block_start, block_end):
    async def process_block(block_number_int):
        block_number = hex(block_number_int)
        transactions = await get_external_transactions(block_number)

        if not transactions:
            print(f'No transactions found in block {block_number_int}')
        else:
            print(f'Transactions in block {block_number_int}:')
            for tx in transactions:
                if tx["to"] is None:
                    if check_method_id(tx["input"]):
                        contract_address = await get_contract_address(tx["hash"])
                        if contract_address:
                            token_details_task = asyncio.gather(
                                get_contract_verification_status(contract_address),
                                get_token_name_from_abi(contract_address)
                            )
                            verified, token_name = await token_details_task

                            # Only display addresses with verified code and token name
                            if verified and token_name.startswith("YES"):
                                print(
                                    f"New contract creation: Contract Address: {contract_address}, Token Name: {token_name}, Verified: {verified}")
            print("\n")  # Print an empty line between blocks

    tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
    await asyncio.gather(*tasks)

async def main():
    block_start = 28866499  # Replace with your desired starting block number
    block_end = 28866930  # Replace with your desired ending block number

    await display_transactions(block_start, block_end)

try:
    asyncio.run(main())
except Exception as e:
    print(f"Error: {e}")

Change the code above to process the latest issued blocks in the blockchain, and not the blocks specified in the interval