# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

import asyncio

# +
async def count():
    print('One')
    y = await asyncio.sleep(1)
    print('Two')
    return y
    
async def main():
    await asyncio.gather(count(), count(), count())
    #await count(),count()

# -

import time
s = time.perf_counter()
await main()
elapsed = time.perf_counter() - s
print(f' executed in {elapsed:0.2f} seconds.')


def count():
    print('One')
    time.sleep(1)
    print('Two')


def main ():
    for _ in range(3):
        count()


s = time.perf_counter()
main()
elapsed = time.perf_counter() - s
print(f' executed in {elapsed:0.2f} seconds.')

import random

c = (
    "\033[0m",   # End of color
    "\033[36m",  # Cyan
    "\033[91m",  # Red
    "\033[35m",  # Magenta
)

# +
async def makerandom(idx: int, threshold: int = 6) -> int:
    print(c[idx + 1] + f'Initiated makerandom({idx})')
    i = random.randint(0,10)
    while i <= threshold:
        print(c[idx + 1] + f"makerandom({idx}) == {i} too low; retrying.")
        await asyncio.sleep(idx + 1)
        i = random.randint(0, 10)
    print(c[idx + 1] + f"---> Finished: makerandom({idx}) == {i}" + c[0])
    return i

async def main():
    res = await asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3)))
    return res
# -

random.seed(444)
r1, r2, r3 = await (main())
print()
print(f"r1: {r1}, r2: {r2}, r3: {r3}")

# ## ASYNC LOGGER 

import json
import os
import pandas as pd
import numpy as np
import asyncio
from eth_account import account
from web3 import Web3
from src import s3_services
from src import sql_manager
from datetime import datetime
from importlib import reload

# +
#Web3 Connection Handler
projectID = '69765a3368f44f5c8cc3691d2361e496'

infura_url = f'https://mainnet.infura.io/v3/{projectID}'
web3 = Web3(Web3.HTTPProvider(infura_url))

infura_url = f'wss://mainnet.infura.io/ws/v3/{projectID}'
web3ws = Web3(Web3.WebsocketProvider(infura_url))

if web3.isConnected() and web3ws.isConnected():
    print('The connection with Ethereum network is successfull')
else:
    print('Network connection error')
# -



web3ws.eth.get_transaction_by_block()

# Ronin Bridge Smart Contract
address = '0x1A2a1c938CE3eC39b6D47113c7955bAa9DD454F2'
abi = json.loads('[{"inputs":[{"internalType":"address","name":"_proxyTo","type":"address"},{"internalType":"address","name":"_registry","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_oldAdmin","type":"address"},{"indexed":true,"internalType":"address","name":"_newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_oldAdmin","type":"address"}],"name":"AdminRemoved","type":"event"},{"anonymous":false,"inputs":[],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_new","type":"address"},{"indexed":true,"internalType":"address","name":"_old","type":"address"}],"name":"ProxyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"_depositId","type":"uint256"},{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":false,"internalType":"address","name":"_sidechainAddress","type":"address"},{"indexed":false,"internalType":"uint32","name":"_standard","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"_tokenNumber","type":"uint256"}],"name":"TokenDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"_withdrawId","type":"uint256"},{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tokenNumber","type":"uint256"}],"name":"TokenWithdrew","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpaused","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":true,"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_newAdmin","type":"address"}],"name":"changeAdmin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"depositCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"deposits","outputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sidechainAddress","type":"address"},{"internalType":"uint32","name":"standard","type":"uint32"},{"internalType":"uint256","name":"tokenNumber","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"proxyType","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"registry","outputs":[{"internalType":"contract Registry","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"removeAdmin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_newProxyTo","type":"address"}],"name":"updateProxyTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_registry","type":"address"}],"name":"updateRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"withdrawals","outputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"tokenNumber","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]')
contract = web3.eth.contract(address=address, abi = abi)

contract.events.TokenWithdrew.event_name

block_data = pd.DataFrame()

web3.eth.get_transaction()


def handle_event(event, df):
    #print(Web3.toJSON(event))
    #event_frame = pd.DataFrame.from_dict(event.args)
    print(event['args'])
    print(f'Movement found in {event.blockNumber}')
    print(f'address: {event.address}')
    print(f'TransactionHash: {event.transactionHash}')
    #print(web3.eth.get_block(event_blockNumber))
    print(web3.eth.get_transaction(web3.toHex(event.transactionHash)))
    #df = df.append(event_frame)
    #print(df)


async def log_loop(event_filter, poll_interval):
    for i in range(10):
        for TokenDeposited in event_filter_1.get_new_entries():
            print('New Deposit')
            handle_event(TokenDeposited, block_data)
        for TokenWithdrew in event_filter_2.get_new_entries():
            print('New Withdrawal')
            handle_event(TokenWithdrew, block_data)
        
        await asyncio.sleep(poll_interval)

# +
event_filter_1 = contract.events.TokenDeposited.createFilter(fromBlock='latest')
event_filter_2 = contract.events.TokenWithdrew.createFilter(fromBlock='latest')
#block_filter = web3.eth.filter('latest')
#tx_filter = web3.eth.filter('pending')

async def main():
    loop = asyncio.get_event_loop()
    await (asyncio.gather(log_loop(event_filter,poll_interval=2)))
# -

await main()

block_data

# +
import asyncio

async def rxer():
    i=0
    while True:
        i+=1
        print ('Rxer ',i)
        await asyncio.sleep(1)

async def WsServe():
    for i in range(5):
        print ('WsServe',i)
        await asyncio.sleep(1)

    print ('Finish')
    loop.stop()
    loop.close()

loop=asyncio.get_event_loop()
loop.create_task(rxer())
loop.run_until_complete(WsServe())
loop.run_forever()

# +
async def WsServe(stop_event):
    for i in range(5):
        print ('WsServe',i)
        await asyncio.sleep(1)

    print ('Finish')
    stop_event.set()
    await asyncio.sleep(1)

async def main():
    asyncio.get_event_loop().create_task(rxer())
    stop_event = asyncio.Event()
    asyncio.get_event_loop().create_task(WsServe(stop_event))
    await stop_event.wait()

asyncio.run(main())

# python 3.6 and older:
#asyncio.get_event_loop().run_until_complete(main())

StarcoderdataJupyterScriptsDedupFiltered