Ethereum: Convert a chain to a list indexed to Python
As mentioned, the use of the “Applications” Library is not sufficient for this task. You have to manually analyze the JSON response of the Ethereum API. Here is an article that goes through how to achieve this:
Previous requirements
Before you start, make sure you have the following installed:
- Python 3.x
Ethers.py
library (available in Pypi)
- A Bitcoin wallet or test account with an Ethereum address
Install the required library
If you do not yet have ethers.py
, install it with PIP:
`Bash
PIP Install Ethers.Py
Convert a chain to an indexed list
Here is a step -by -step guide on how to convert a chain that represents a hexadecimal value to an indexed list (for example, a list of whole numbers) in Python:
- Get Ethereum API URL: You have to get [Ethereum laboratories] ( Replace
your_pi_Key
with your real key:
`Python
Import requests
Api_key = "your_api_key"
Api_url = f "
- Send a Geta to API : Use library “applications” to send a Get to API Ethereum app:
`Python
Import requests
URL = api_url
Answer = Requests.Get (URL)
- Pass the JSON answer : The API returns a JSON object, which we will have to analyze a Python dictionary using the “JSON ()” method:
`Python
Data = json.loads (reply.text)
- Remove the number of transactions : We are interested in the amount of transactions that can be performed in our specific direction (0x …). Eliminate this value from JSON response:
`Python
transaction_count = data ['result'] [0] ['number']
- Rotate an indexed list : Convert the hexadecimal chain (
" 0x ... "
) into a whole number, then to a list of integers using theMAP () function:
Python
indexed_list = [int (hex_value) for hex_value in data ['result'] [0] ['hex']]
putting everything together
Here is the complete code:
`Python
Import requests
Import Json
Api_key = "your_api_key"
URL = f " &;
Answer = Requests.Get (URL)
Data = json.loads (reply.text)
transaction_count = data ['result'] [0] ['number']
indexed_list = [int (hex_value) for hex_value in data ['result'] [0] ['hex']]
print (indexed_list)
Example of case use
Suppose you have the next hexadecimal chain representing an Ethereum address:
`Bash
0x1234567890ABCDEF
You can use this chain to turn it into an indexed list:
`Python
indexed_list = [int ("0x" + hex_value) for hex_value in data ['result'] [0] ['hex']]]
print (indexed_list)
Production:
`
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
`
In this example, the hexadecimal chain becomes an integer, and then a list of whole numbers representing the index values.