import json,requests
from rpc import call
NR="https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3"
def nr(p): return requests.post(NR,json={"jsonrpc":"2.0","id":1,"method":"nr_getAssetTransfers","params":[p]},timeout=60).json()['result']['transfers']
def first_in(a):
    allt=[]
    for cat in ["external","internal"]:
        allt+=nr({"category":[cat],"toAddress":a,"order":"asc","maxCount":"0x5","excludeZeroValue":True})
    allt.sort(key=lambda t:int(t['blockNum'],16))
    return allt[0] if allt else None
bi=json.load(open('bnb_in.json')); d=json.load(open('day.json'))
F={}
for a,lst in bi.items():
    lst=sorted(lst,key=lambda t:int(t['blockNum'],16))
    if not lst:
        F[a]=dict(funded=False,nonce_last=int(call("eth_getTransactionCount",[a,hex(d['last'])],[NR]),16),bal_last=int(call("eth_getBalance",[a,hex(d['last'])],[NR]),16),nonce_now=int(call("eth_getTransactionCount",[a,'latest'],[NR]),16),bal_now=int(call("eth_getBalance",[a,'latest'],[NR]),16),code=call("eth_getCode",[a,'latest'],[NR]))
        print(a,'never',F[a]['nonce_now'],F[a]['bal_now']);continue
    f=lst[0]; blk=int(f['blockNum'],16)
    tx=call("eth_getTransactionByHash",[f['hash']]); rc=call("eth_getTransactionReceipt",[f['hash']])
    bt=int(call("eth_getBlockByNumber",[hex(blk),False])['timestamp'],16)
    pre_bal=int(call("eth_getBalance",[a,hex(blk-1)],[NR]),16); pre_n=int(call("eth_getTransactionCount",[a,hex(blk-1)],[NR]),16)
    post_bal=int(call("eth_getBalance",[a,hex(blk)],[NR]),16)
    funder=f['from']
    fn=int(call("eth_getTransactionCount",[funder,'latest'],[NR]),16); fcode=call("eth_getCode",[funder,'latest'],[NR])
    ff=first_in(funder)
    F[a]=dict(funded=True,category=f['category'],tx=f['hash'],block=blk,ts=bt,funder=funder,value=str(int(f['value'],16)),tx_from=tx['from'],tx_to=tx['to'],tx_value=str(int(tx['value'],16)),status=rc['status'],pre_bal=pre_bal,pre_nonce=pre_n,post_bal=post_bal,funder_nonce=fn,funder_code=len(fcode)>2 and fcode[:8],
              funder_first=ff and dict(frm=ff['from'],tx=ff['hash'],block=int(ff['blockNum'],16),cat=ff['category'],value=str(int(ff['value'],16))),n_in=len(lst))
    print(a,F[a]['category'],blk,funder,'txfrom',tx['from'],'pre',pre_bal,pre_n,'post',post_bal,'fnonce',fn,'fcode',F[a]['funder_code'],'ff',ff and ff['from'])
json.dump(F,open('funders.json','w'),indent=1)
