approve_token_spending

Function

def approve_token_spending(account, token_address, spender_address, amount, attempts=18):
    token_contract = load_contract(token_address)
    token_info = get_token_info(token_address)
    token_amount = to_token_decimals(amount, token_info['decimals'])
    if token_contract.functions.allowance(account.address, spender_address).call() < token_amount:
        try:
            tx = token_contract.functions.approve(spender_address, token_amount).build_transaction({
                'nonce': get_nonce(account.address),
                'from': account.address
            })
            return broadcast_transaction(account, tx, True, attempts)
        except Exception as e:
            if error := interpret_exception_message(e):
                logging.error("{}. Failed to approve {} ({})".format(error, token_info['name'], token_info['symbol']))
            return False

Description

  • Load the token contract from the address

  • Get the token info

  • Convert the amount to decimals

  • Check if the token allowance is less than the amount in decimals

  • Create a transaction to approve the spender for the amount in decimals

  • Broadcast the transaction and return True/False