# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)

import asyncio
import aiohttp

bscscan_api_key = '<TRUFFLEHOG_REDACTED_BSCSCAN>'

# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)

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_and_name(contract_address: 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}"

            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.get("result") is None or not isinstance(data.get("result"), str):
                return False, ""

            result = data.get("result", {})
            verified = data["result"] != "Contract source code not verified"
            contract_name = result.get("ContractName", "") if verified else ""

            return verified, contract_name

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:
                            verified, contract_name = await get_contract_verification_status_and_name(contract_address)
                            print(f"New contract creation: Contract Address: {contract_address}, Verified: {verified}, Contract Name: {contract_name}")
            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 = 28866530 # Replace with your desired starting block number
    block_end = 28866929  # Replace with your desired ending block number

    await display_transactions(block_start, block_end)

asyncio.run(main())

the above code is still throwing an error

Transactions in block 28866929:


New contract creation: Contract Address: 0x77c3da1b2878054175f61417167fe74f2de7cfdb, Verified: False, Contract Name: 


New contract creation: Contract Address: 0x18f82923150a1fece0cc870b21dcdcccf732cf7f, Verified: False, Contract Name: 


Traceback (most recent call last):
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 101, in <module>
    asyncio.run(main())
  File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 99, in main
    await display_transactions(block_start, block_end)
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 93, in display_transactions
    await asyncio.gather(*tasks)
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 88, in process_block
    verified, contract_name = await get_contract_verification_status_and_name(contract_address)
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 63, in get_contract_verification_status_and_name
    contract_name = result.get("ContractName", "") if verified else ""
                    ^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'

Process finished with exit code 1

Fix it