from flask import Flask
from web3 import Web3
from eth_account.messages import defunct_hash_message
from web3.auto import w3

web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/890b1d656a714da79aa46f7ef9b090e2'))

signature = '0x5d54a9441d385acbb9116575111f6757c56687b070b7272da19d3a27ea2ec68847a74be80cf54cccb1fdab905fb5a20fe553a96a88cfae5d50aa8c7b10624ee81c'
message = 'Bonjour cher ami jai vote et cest pour1 o 2'


app = Flask(__name__)


def recover_address(message, signature):
    message_hash = defunct_hash_message(text=message)
    address = w3.eth.account._recover_hash(message_hash, signature=signature)
    return address

# def recover_address(message, signature):
#     message_hash = defunct_hash_message(text=message)
#     address = w3.eth.account._recover_hash(message_hash, signature=signature)
#     return address


@app.route("/")
def get_eth_balance():
    web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/890b1d656a714da79aa46f7ef9b090e2'))
    try:
        recover_add = recover_address(message, signature)
        checksum_address = Web3.to_checksum_address(recover_add)
        balance_wei = web3.eth.get_balance(checksum_address)
        return f"<h4>balance_wei    {balance_wei}<br> recover address {str(recover_add)}</h4> "  
    except Exception as e:
        # Exception handling code goes here
        return "An error occurred during address recovery"
    


@app.route("/<string:name>/")
def say_hello(name):
    return f"Hello {name}"


if __name__ == "__main__":
    app.run()