import json,requests
from rpc import call
NR=["https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3"]
FJ="0x90c8889f428f9ebb77bb8f15cad3a50a9ac680df"; TRE="0x7c34e9e21ee28a49ff0b84b61774119e6633359f"
TR="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
d=json.load(open('day.json')); a,b=d['first'],d['last']
res={}
def blk(n): x=call("eth_getBlockByNumber",[hex(n),False]); return dict(number=n,hash=x['hash'],ts=int(x['timestamp'],16))
res['boundary']={'prev':blk(a-1),'first':blk(a),'last':blk(b),'next':blk(b+1)}
def bal(addr,n):
    data="0x70a08231"+"0"*24+addr[2:]
    return int(call("eth_call",[{"to":FJ,"data":data},hex(n)],NR),16)
res['tre_bal_before']=bal(TRE,a-1); res['tre_bal_after']=bal(TRE,b)
# inflows
topic_to="0x"+"0"*24+TRE[2:]
inl=[];s=a
while s<=b:
    e=min(s+4999,b)
    j=requests.post(NR[0],json={"jsonrpc":"2.0","id":1,"method":"eth_getLogs","params":[{"address":FJ,"topics":[TR,None,topic_to],"fromBlock":hex(s),"toBlock":hex(e)}]},timeout=60).json()
    inl+=j['result'];s=e+1
res['inflows']=[dict(tx=l['transactionHash'],block=int(l['blockNumber'],16),frm='0x'+l['topics'][1][26:],amt=str(int(l['data'],16))) for l in inl]
res['tre_nonce_before']=int(call("eth_getTransactionCount",[TRE,hex(a-1)],NR),16)
res['tre_nonce_after']=int(call("eth_getTransactionCount",[TRE,hex(b)],NR),16)
# tx details
L=json.load(open('logs.json')); txs=[]
for l in L:
    h=l['transactionHash']; t=call("eth_getTransactionByHash",[h]); r=call("eth_getTransactionReceipt",[h])
    txs.append(dict(tx=h,block=int(l['blockNumber'],16),ts=int(l['blockTimestamp'],16),frm=t['from'],to=t['to'],input4=t['input'][:10],status=r['status'],nlogs=len(r['logs']),recipient='0x'+l['topics'][2][26:],amt=str(int(l['data'],16)),logIndex=int(l['logIndex'],16)))
res['txs']=txs
json.dump(res,open('verify.json','w'),indent=1)
print(json.dumps({k:v for k,v in res.items() if k!='txs'},indent=1))
for t in txs: print(t['tx'][:10],t['frm'][:10],t['to'][:10],t['input4'],t['status'],t['nlogs'])
