Skip to content

Instantly share code, notes, and snippets.

@cassc
Last active August 23, 2024 05:30
Show Gist options
  • Save cassc/62c924423f857f22bcea668ef8a22efe to your computer and use it in GitHub Desktop.
Save cassc/62c924423f857f22bcea668ef8a22efe to your computer and use it in GitHub Desktop.
script to monitor complex transactions
import csv
import argparse
from web3 import Web3
import os
from datetime import datetime
import time
WEB3_PROVIDER_URI = 'https://eth-mainnet.g.alchemy.com/v2/token'
# parse command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('outfile', type=str, help='CSV file to write txhash')
args = parser.parse_args()
outfile = args.outfile
seen = set()
if not os.path.exists(outfile):
print(f"Creating file {outfile}")
output = open(args.outfile, 'a')
outfile = csv.writer(output)
outfile.writerow(['Block', 'Transaction Hash', 'Gas Used', 'Gas Price'])
else:
print(f"Appending to file {outfile}")
with open(outfile, 'r') as f:
reader = csv.reader(f)
for row in reader:
if len(row) > 0:
seen.add(row[2])
output = open(args.outfile, 'a')
outfile = csv.writer(output)
w3 = Web3(Web3.HTTPProvider(WEB3_PROVIDER_URI))
block_filter = w3.eth.filter('latest')
def process_transaction(transaction):
tx_hash = transaction['hash'].hex()
gas_used = transaction.get('gas')
gas_price = transaction.get('gasPrice')
base_gas = 21000
if transaction.get('to') is None:
# contract creation, assuming nobody hacks here
if gas_used > base_gas * 50: # TODO update this threshold if necessary
outfile.writerow([transaction['blockNumber'], tx_hash, gas_used, gas_price])
return tx_hash
if gas_used > base_gas * 20: # TODO update this threshold if necessary
outfile.writerow([transaction['blockNumber'], tx_hash, gas_used, gas_price])
return tx_hash
return None
def handle_block(block_hash):
block = w3.eth.get_block(block_hash, full_transactions=True)
for transaction in block.transactions:
process_transaction(transaction)
while True:
try:
for block_hash in block_filter.get_new_entries():
print(f'{datetime.now()} new block: {block_hash.hex()}')
block = w3.eth.get_block(block_hash)
handle_block(block_hash)
except KeyboardInterrupt:
output.flush()
output.close()
print("Exiting...")
break
except Exception as e:
print(f"Exception: {e}")
time.sleep(5)
if '32000' in str(e):
time.sleep(5)
print('Restarting...')
w3 = Web3(Web3.HTTPProvider(WEB3_PROVIDER_URI))
block_filter = w3.eth.filter('latest')
continue
@cassc
Copy link
Author

cassc commented Aug 21, 2024

    gas_used = transaction.get('gas')

is not the actual gas used might need to treak this

@cassc
Copy link
Author

cassc commented Aug 23, 2024

to get actual gas consumed by the transaction, you need to call web3.eth.get_transaction_receipt(txhash) to get the transaction_receipt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment