Created
January 11, 2024 16:23
-
-
Save d10r/b680ea08c8f373fb64d94d883bc45e42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# queries the balance (of native coins, e.g. ETH) of a given account at a given block | |
# requires an archive node if the block lies more than a couple of blocks in the past | |
# | |
# Requirements: python, jq, curl and awk installed and in PATH | |
# | |
# usage: get-eth-balance-of-at.sh <ethereum_address> [block_number]" | |
# env var RPC must be set | |
set -x | |
if [ -z "$1" ]; then | |
echo "Usage: $0 <ethereum_address> [block_number]" | |
exit 1 | |
fi | |
if [ -z "$RPC" ]; then | |
echo "Please set the RPC environment variable to the JSON-RPC endpoint URL." | |
exit 1 | |
fi | |
ETH_ADDRESS="$1" | |
# TODO: this is ugly, fix! | |
BLOCKNR=${2:-"latest"} | |
if [ "$BLOCKNR" != "latest" ]; then | |
BLOCKNR_HEX="0x$(printf '%x' $BLOCKNR)" | |
else | |
BLOCKNR_HEX="latest" | |
fi | |
ETH_BALANCE_JSON='{"jsonrpc":"2.0","method":"eth_getBalance","params":["'$ETH_ADDRESS'", "'$BLOCKNR_HEX'"],"id":1}' | |
echo "ETH_BALANCE_JSON $ETH_BALANCE_JSON" | |
if [[ $ETH_BALANCHE_JSON == null ]]; then | |
echo "failed" | |
exit 1 | |
fi | |
ETH_BALANCE_WEI=$(curl -s -f -X POST -H "Content-Type: application/json" --data "$ETH_BALANCE_JSON" $RPC | jq -r .result) | |
ETH_BALANCE=$(echo "$ETH_BALANCE_WEI" | awk '{ printf "%.18f", $1 / (10^18) }') | |
if [ "$BLOCKNR" != "latest" ]; then | |
BLOCK_TIMESTAMP_JSON='{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["'$BLOCKNR_HEX'", false],"id":1}' | |
BLOCK_TIMESTAMP_HEX=$(curl -s -X POST -H "Content-Type: application/json" --data "$BLOCK_TIMESTAMP_JSON" $RPC | jq -r .result.timestamp) | |
BLOCK_TIMESTAMP=$(python -c "import sys; print(int(sys.argv[1], 16))" "${BLOCK_TIMESTAMP_HEX:2}") | |
# BLOCK_TIMESTAMP=$(echo "ibase=16; ${BLOCK_TIMESTAMP_HEX:2}" | bc) | |
HUMAN_READABLE_TIMESTAMP=$(date -u -d @${BLOCK_TIMESTAMP} +'%Y-%m-%d %H:%M:%S') | |
echo "Ethereum Balance for $ETH_ADDRESS at block $BLOCKNR (timestamp: $HUMAN_READABLE_TIMESTAMP): $ETH_BALANCE ETH" | |
else | |
echo "Ethereum Balance for $ETH_ADDRESS: $ETH_BALANCE ETH" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment