Skip to content

Instantly share code, notes, and snippets.

@reedsa
Last active September 22, 2023 21:40
Show Gist options
  • Save reedsa/addafe9eb852db3267c0e90f1ce9867e to your computer and use it in GitHub Desktop.
Save reedsa/addafe9eb852db3267c0e90f1ce9867e to your computer and use it in GitHub Desktop.
ethereum chain id list to python enums

Generate list of Ethereum Network Chain IDs as enums in Python

Pulling from https://chainid.network/chains_mini.json the json is parsed.

Each record has a shortName and chainId which is used to build each enum.

The names are formatted and written to a file.

Once the networks.py file has been created, it can be copied to the repo and changes can be pushed.

import urllib.request, json
f = open("networks.py", "w")
f.write(
"from enum import (\n" +
" IntEnum,\n" +
")\n\n\n" +
"class ChainId(IntEnum):\n"
)
with urllib.request.urlopen("https://chainid.network/chains_mini.json") as url:
data = json.load(url)
for d in data:
name, chainId = d["shortName"], d["chainId"]
if name[0].isdigit():
name = "_" + name
enum = "".join(["_" if i == "-" else i.upper() for i in name]).lstrip("-") + " = " + str(chainId) + "\n"
enum = f" {enum}"
f.write(enum)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment