
# https://docs.alchemy.com/reference/eth-getcode

# 如果是在合约外部判断，则可以使用web3.eth.getCode()，或者是对应的JSON-RPC方法eth_getcode。
# getCode()用来获取参数地址所对应合约的代码，如果参数是一个外部账号地址，则返回"0x"；如果参数是合约，则返回对应的字节码，如下所示：

# web3.eth.getCode("0xa5Acc472597C1e1651270da9081Cc5a0b38258E3")
# "0x"

# web3.eth.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8")

# "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056"

# 这样我们就可以通过getCode()的内容判断是哪一种地址了。

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"

getcode_eth_payload = {
    "id": 1,
    "jsonrpc": "2.0",
    "params": ["", "latest"],
    "method": "eth_getCode"
}
 
 

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,
    "iscontract":int,
})
df_not_getbalance =df[ (df["iscontract"]==-1) &(df["eth"]>=0.5)]
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_getCode"

}  for str_dalaoaddress in arr_str_dalaoaddress
]

 

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)

    code_value =  response["result"].strip()
    iscontract =-1

    if (code_value != "0x"):
        iscontract =1
    else:
         iscontract =0

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

    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 =1
asyncio.run(main())





 
 
print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

