import re
import requests
import difflib

API_KEY = "<TRUFFLEHOG_REDACTED_BSCSCAN>"
BASE_URL = "https://api.bscscan.com/api"
similarity_threshold = 0.5


def get_contract_source_code(address):
    params = {
    "module": "contract",
    "action": "getsourcecode",
    "address": address,
    "apiKey": API_KEY
    }

    response = requests.get(BASE_URL, params=params)
    data = response.json()

    if data["status"] == "1":
        source_code = data["result"][0]["SourceCode"]
        return remove_comments(source_code)
    else:
        return None


def remove_comments(code):
    lines = code.split('\n')
    lines_without_comments = []
    is_multiline_comment = False

    for line in lines:
        single_line_comment = re.sub(r"//.", "", line)
        match = re.findall(r" /* | */ ", single_line_comment)

        if not match:
            if not is_multiline_comment:
                lines_without_comments.append(single_line_comment)
        elif match:
            if is_multiline_comment and "/" in match:
                is_multiline_comment = False
                pos = single_line_comment.index(" / ") + 2
                single_line_comment = single_line_comment[pos:]
                lines_without_comments.append(single_line_comment)
            elif not is_multiline_comment and "/" in match:
                is_multiline_comment = True
                single_line_comment = single_line_comment[: single_line_comment.index(" / * ")]
                lines_without_comments.append(single_line_comment)

    cleaned_code = "\n".join(lines_without_comments)
    return cleaned_code


def jaccard_similarity(str1, str2):
    a = set(str1.split())
    b = set(str2.split())
    c = a.intersection(b)
    return float(len(c)) / (len(a) + len(b) - len(c))


def find_similar_contracts(reference_addresses, candidate_addresses):
    reference_source_codes = {}
    for reference_address in reference_addresses:
        source_code = get_contract_source_code(reference_address)
        if source_code is not None:
            reference_source_codes[reference_address] = source_code

    if not reference_source_codes:
        print("No source code found for reference contracts")
        return []

    similar_contracts = {}
    for address in candidate_addresses:
        candidate_source_code = get_contract_source_code(address)
        if candidate_source_code is not None:
            for reference_address, reference_source_code in reference_source_codes.items():
                similarity = jaccard_similarity(candidate_source_code, reference_source_code)
                if similarity >= similarity_threshold:
                    if reference_address not in similar_contracts:
                        similar_contracts[reference_address] = [(address, similarity)]
                    else:
                        similar_contracts[reference_address].append((address, similarity))

    return similar_contracts


def print_code_difference(reference_code, candidate_code):
    reference_lines = reference_code.splitlines()
    candidate_lines = candidate_code.splitlines()
    diff = difflib.unified_diff(reference_lines, candidate_lines)

    for line in diff:
        print(line)


if __name__ == "__main__":
    reference_addresses = ["0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb"]
    candidate_addresses = ["0xd481997fbe2D7C7f9E651e5f2450AcbC38Eed750"]

    similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses)
    print("Contracts with similar source code (ignoring comments):")
    for reference_address, similar_addresses in similar_contracts.items():
        reference_code = get_contract_source_code(reference_address)

        print(f"Reference contract: {reference_address}")
        for address, similarity in similar_addresses:
            candidate_code = get_contract_source_code(address)

        print(f"Similar contract: {address} with a similarity of {similarity:.2f}")

        if similarity < 1.0:
            print("Code differences:")
            print_code_difference(reference_code, candidate_code)
            print("\n")

The code above does not remove all comments that are in the source code of the contract.
Comments in code begin with the following characters

// this is a single line comment and the characters after it should not be taken into account when comparing

/*
*/ is a multi-line comment. All characters between them do not need to be taken into account when comparing

/**
  */ is also a multi-line comment. All characters between them do not need to be taken into account when comparing

Inside a multiline comment, comments start with the * character. All characters after * also do not need to be taken into account when comparing