# AUTOGENERATED! DO NOT EDIT! File to edit: ../src/abi.ipynb.

# %% auto 0
__all__ = ['abis_dir', 'download_contract_abi', 'get_abi']

# %% ../src/abi.ipynb 3
import requests, os, json

# %% ../src/abi.ipynb 4
abis_dir="abis"

def download_contract_abi(name, address, abis_dir=os.path.join("sugar", abis_dir), etherscan_api_url="https://api-optimistic.etherscan.io/api"):
    api_key = os.getenv("ETHERSCAN_API_KEY")
    if not api_key: raise Exception("ETHERSCAN_API_KEY not set in environment variables")
    response = requests.get(etherscan_api_url, params={ "chainid": 1, "module": "contract", "action": "getabi", "address": address, "apikey": api_key })
    if response.status_code != 200: raise Exception(f"API request failed with status code {response.status_code}")
    response_data = response.json()
    if response_data.get("message") != "OK": raise Exception(f"API request failed with message: {response_data.get('message')}")
    os.makedirs(abis_dir, exist_ok=True)
    with open(os.path.join(abis_dir, f"{name}.json"), "w") as file:
        json.dump(json.loads(response_data.get("result")), file, indent=4)

def get_abi(name):
    dir, path = None, os.path.abspath(__file__)
    dir_path = os.path.dirname(path)
    abis_locations = [
        abis_dir,
        os.path.join(dir_path, abis_dir),
        os.path.join("../", abis_dir),
        os.path.join("../sugar", abis_dir),
    ]

    for d in abis_locations:
        if os.path.exists(d):
            dir = d
            break

    if not dir: raise Exception("Cannot find abis directory. Did you run download_contract_abi?")
        
    with open(os.path.join(dir, f"{name}.json"), "r") as file:
        return file.read()
