There are many many interesting wallets on public blockchains. Think big trading firms, exchanges, hackers, NFT creators.. Being able to watch these wallets in real time, noticing their every move, is very powerful. Here we will make a short script to alert us of ethereum transactions coming from a particular account/address. With transaction alerts we can quickly decide whether to take actions such as: copy trading a good trader, shorting a coin that's about to get doomped, or buy NFTs similar to a collector's new purchase. This will provide a foundation for later on, where we try automated trading based on on-chain events. If you haven't already been interested in trawling through high value or perculiar transactions on etherscan, then this isnt for you.
There are two main ways to interact with Ethereum using python:
The idea is basic, we refresh the transactions of a wallet every x seconds. Whenever there is a new transaction, we play a sound or alert. Let's use the etherscan API to fetch the transactions of an address:
import requests
API_KEY = "LOG IN TO etherscan.io/myapikey AND PUT TOKEN HERE"
def get_txns(address, block):
etherscan_url = f'https://api.etherscan.io/api?module=account&action=txlist&address={address}&startblock={block}&sort=asc&apikey={API_KEY}'
resp = requests.get(etherscan_url).json()['result']
return resp
Now, `get_txns(address, block)` will get any 'Normal' transactions since block. Note you can change this URL endpoint to fetch internal or token transactions if you so desire. Now to set up an alert for new transactions, let's put it in a loop:
import time
while True:
txns = get_txns("0x5b5b487aed7d18ac677c73859270b0f6cf5bb69c", 0)
print(txns)
time.sleep(1)
Here we are just checking out the transactions from some address "0x5b5b487aed7d18ac677c73859270b0f6cf5bb69c" since block 0, and display using pretty print so there isnt JSON spam everywhere (v useful). Now we want to play an alert if there are no transactions since some block, ie `len(txns) == 0`. On UNIX can play an mp3 or sound (windows plebs) with something like:
def beep():
# we play a file with a `mpg123` command, opening a subprocess, then closing it.
cmd = "mpg123 ./alert.mp3"
# we play the sound 3 times
for i in range(3):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
time.sleep(2)
p.kill()
return
# WINDOWS
import winsound
def winbeep():
winsound.Beep(2500, 100)
return
Now we have:
while True:
txns = get_txns("0x5b5b487aed7d18ac677c73859270b0f6cf5bb69c", 0)
if len(txns) != 0:
pprint(txns)
beep()
time.sleep(1)
Some difference included in script above:
usage: Watch ERC-20 send txs from an address and sound alarms [-h] -a ADDRESS [-b BLOCK]
optional arguments:
-h, --help show this help message and exit
-a ADDRESS, --address ADDRESS
Watch address
-b BLOCK, --block BLOCK
Start block, send txs after this block height will sound the alarm.