

# https://docs.alchemy.com/reference/eth-getbalance
# https://docs.alchemy.com/reference/alchemy-gettokenbalances


from base_class import BaseVariableFunction
from base_class import *

from base_library import BaseLibrary
old_print = print


def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)


print = timestamped_print
baseclass = BaseVariableFunction(__file__)



print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
            
 
url_0 = "https://eth-mainnet.g.alchemy.com/v2/WLI0ohbUlvbsJVmoIvB1wTSwUA8qP5qS"
url_1 = "https://eth-mainnet.g.alchemy.com/v2/ck1dtOx8tHkjAH2PX2FwTGN2T2gDaGtV"
url_2 = "https://eth-mainnet.g.alchemy.com/v2/pxF-cEkEE1JxzxgotGyww5ra5w1IvAkJ"

arr_rpc = [

    url_0,
    url_1,
    url_2,
    url_0,
    url_1,
    url_2,
    url_0,
    url_1,
    url_2,
]
 
 
url = "https://eth-mainnet.g.alchemy.com/v2/WLI0ohbUlvbsJVmoIvB1wTSwUA8qP5qS"

getBalance_eth_payload = {
    "id": 1,
    "jsonrpc": "2.0",
    "params": ["", "latest"],
    "method": "eth_getBalance"
}
headers = {
    "accept": "application/json",
    "content-type": "application/json"
}
df =  pd.read_csv( baseclass.dalao_merge_path / f"ori_merge.csv", dtype=object)
df= df.astype({
    "eth":float
})

df_not_getbalance =df[ df["eth"]==-1]
arr_str_dalaoaddress = df_not_getbalance['dalaoaddress'].tolist()
len_arr_str_dalaoaddress= len(arr_str_dalaoaddress)

arr_payload = [  {
 "id": 1,
    "jsonrpc": "2.0",
    "params": [str_dalaoaddress, "latest"],
    "method": "eth_getBalance"

}  for str_dalaoaddress in arr_str_dalaoaddress
]




# getBalance_eth_payload


async def get_one_eth_balance(str_dalaoaddress ,payload,url ):
    global df


    req_response = requests.post(url, json=payload, headers=headers)
    if req_response.status_code != 200:
        return
    response = json.loads(
                req_response.text)

    eth_value = int(response["result"], 16)/10**18
    eth_value=  round(eth_value , 3)


    df.loc[ df["dalaoaddress"] ==str_dalaoaddress , "eth"] = eth_value
    print(f"str_dalaoaddress= {str_dalaoaddress} eth_value= {eth_value}")
   

    return
async def get_eth_balance():
    global arr_payload
    global arr_str_dalaoaddress
    global asyncio_len
     

    for str_dalaoaddress_idx in range(0, len(arr_str_dalaoaddress) , asyncio_len):
        cur_arr_str_dalaoaddress = []
        cur_arr_payload = []
        
        for idx_dalao  in range(0 ,asyncio_len ):
            if str_dalaoaddress_idx + idx_dalao  >= len(arr_str_dalaoaddress):
                continue
            temp_str_dalaoaddress = arr_str_dalaoaddress[str_dalaoaddress_idx + idx_dalao ]
            temp_payload = arr_payload[str_dalaoaddress_idx +  idx_dalao ]

            cur_arr_str_dalaoaddress.append( temp_str_dalaoaddress )
            cur_arr_payload.append( temp_payload )
        
        tasks_for_wait = [asyncio.create_task(get_one_eth_balance(
              cur_arr_str_dalaoaddress[idx] , cur_arr_payload[idx]  ,arr_rpc[idx]) ) for idx in range(0, len(cur_arr_str_dalaoaddress))]
 

        done, pending = await asyncio.wait(tasks_for_wait, timeout=30)

        if str_dalaoaddress_idx%10==0 or str_dalaoaddress_idx%10==1  :
                df.to_csv( baseclass.dalao_merge_path / f"ori_merge.csv", index=False)
        if str_dalaoaddress_idx%50==0 or str_dalaoaddress_idx%50==1 or str_dalaoaddress_idx%50==2 :
                print(f" {str_dalaoaddress_idx}/{len_arr_str_dalaoaddress}")
        
    df.to_csv( baseclass.dalao_merge_path / f"ori_merge.csv", index=False)
    return
async def main():
    await get_eth_balance()



asyncio_len =5
asyncio.run(main())
 
 
print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

