get_token_info

Function

def get_token_info(token_address, attempts=18):
    os.makedirs(token_folder := "./data/tokens".format(token_address), exist_ok=True)
    token_info_file = "{}/{}.json".format(token_folder, token_address)
    if os.path.isfile(token_info_file):
        token_info = json.load(open(token_info_file))
        if token_info['decimals'] is not None:
            return token_info
    token_name, token_symbol, token_decimals = None, None, None
    token_contract = load_contract(token_address)
    _attempts = attempts
    while _attempts > 0:
        try:
            token_name = token_contract.functions.name().call()
        except Web3Exception:
            _attempts -= 1
            continue
        else:
            break
    _attempts = attempts
    while _attempts > 0:
        try:
            token_symbol = token_contract.functions.symbol().call()
        except Web3Exception:
            _attempts -= 1
            continue
        else:
            break
    _attempts = attempts
    while _attempts > 0:
        try:
            token_decimals = token_contract.functions.decimals().call()
        except Web3Exception:
            _attempts -= 1
            continue
        else:
            break
    token_info = {"name": token_name, "symbol": token_symbol, "decimals": token_decimals}
    open(token_info_file, 'w').write(json.dumps(token_info, indent=4))
    return token_info

Description

  • Create the cache folder for token info if it doesn’t exist

  • Set the file path for the token info as JSON

  • If the file already exists then return load the JSON string from the file and return it

  • Set placeholders for the token info as 3 null variables

  • Load the contract from token address

  • Set max attempts

  • Get the token contract’s name

  • Get the token contract’s Symbol

  • Get the token contract’s Decimals

  • Prepare a dictionary with the token info

  • Save it as JSON to the file path

  • Return the token info