from web3 import Web3
from collections import defaultdict
import heapq
from concurrent.futures import ThreadPoolExecutor
# Connect to a Klaytn node
w3 = Web3(Web3.HTTPProvider('CHAINSTACK_NODE'))
# Data structure to hold the count of interactions per contract
contract_interactions = defaultdict(int)
# Priority queue to maintain top 3 contracts
top_contracts = []
# Cache for storing contract check results
is_contract_cache = {}
def is_contract(address):
if address not in is_contract_cache:
code = w3.eth.get_code(address)
is_contract = code != '0x'
is_contract_cache[address] = is_contract
return is_contract_cache[address]
def process_block(block_number):
print(f"Processing block {block_number}")
block = w3.eth.get_block(block_number, full_transactions=True)
for tx in block.transactions:
if tx.to and is_contract(tx.to):
contract_interactions[tx.to] += 1
# Main loop to process 100 blocks
def main():
latest_block = w3.eth.block_number
print("Starting to process blocks...")
with ThreadPoolExecutor(max_workers=10) as executor:
executor.map(process_block, range(latest_block - 100, latest_block))
# Identify top 3 contracts
for contract, interactions in contract_interactions.items():
heapq.heappush(top_contracts, (interactions, contract))
if len(top_contracts) > 3:
heapq.heappop(top_contracts)
# Print top 3 contracts
print("Top contracts:", top_contracts)
while top_contracts:
interactions, contract = heapq.heappop(top_contracts)
print(f'Contract {contract} had {interactions} interactions')
if __name__ == '__main__':
try:
main()
except Exception as e:
print(f"An error occurred: {e}")