GithubHelp home page GithubHelp logo

pcko1 / etherscan-python Goto Github PK

View Code? Open in Web Editor NEW
402.0 15.0 113.0 1.77 MB

A minimal, yet complete, python API for Etherscan.io.

License: MIT License

Python 99.78% Shell 0.22%
etherscan api eth ethereum erc20 erc721 etherscan-python

etherscan-python's Introduction

etherscan-python

Build Status codecov Codacy Badge Maintainability CodeFactor

PyPI PyPI - Downloads GitHub Python 3.8 DOI

A minimal, yet complete, Python API for Etherscan.io.

All standard and pro endpoints are provided. Kovan, Rinkeby and Ropsten testnets are also supported.

Available on PyPI. Powered by Etherscan.io APIs.


Endpoints

The following endpoints are provided:

Accounts (source)

  • get_eth_balance
  • get_eth_balance_multiple
  • get_normal_txs_by_address
  • get_normal_txs_by_address_paginated
  • get_internal_txs_by_address
  • get_internal_txs_by_address_paginated
  • get_internal_txs_by_txhash
  • get_internal_txs_by_block_range_paginated
  • get_erc20_token_transfer_events_by_address
  • get_erc20_token_transfer_events_by_contract_address_paginated
  • get_erc20_token_transfer_events_by_address_and_contract_paginated
  • get_erc721_token_transfer_events_by_address
  • get_erc721_token_transfer_events_by_contract_address_paginated
  • get_erc721_token_transfer_events_by_address_and_contract_paginated
  • get_mined_blocks_by_address
  • get_mined_blocks_by_address_paginated
Contracts (source)

  • get_contract_abi
  • get_contract_source_code
Transactions (source)

  • get_contract_execution_status
  • get_tx_receipt_status
Blocks (source)

  • get_block_reward_by_block_number
  • get_est_block_countdown_time_by_block_number
  • get_block_number_by_timestamp
GETH/Parity Proxy (source)

  • get_proxy_block_number
  • get_proxy_block_by_number
  • get_proxy_uncle_by_block_number_and_index
  • get_proxy_block_transaction_count_by_number
  • get_proxy_transaction_by_hash
  • get_proxy_transaction_by_block_number_and_index
  • get_proxy_transaction_count
  • get_proxy_transaction_receipt
  • get_proxy_call
  • get_proxy_code_at
  • get_proxy_storage_position_at
  • get_proxy_gas_price
  • get_proxy_est_gas
Tokens (source)

  • get_total_supply_by_contract_address
  • get_acc_balance_by_token_and_contract_address
Gas Tracker (source)

  • get_est_confirmation_time
  • get_gas_oracle
Stats (source)

  • get_total_eth_supply
  • get_eth_last_price
  • get_eth_nodes_size
Pro (PRO API key needed) (source)

  • get_hist_eth_balance_for_address_by_block_no
  • get_daily_average_block_size
  • get_daily_block_count_and_rewards
  • get_daily_block_rewards
  • get_daily_average_block_time
  • get_daily_uncle_block_count_and_rewards
  • get_hist_erc20_token_total_supply_by_contract_address_and_block_no
  • get_hist_erc20_token_account_balance_for_token_contract_address_by_block_no
  • get_token_info_by_contract_address
  • get_daily_average_gas_limit
  • get_eth_daily_total_gas_used
  • get_eth_daily_average_gas_price
  • get_eth_daily_network_tx_fee
  • get_daily_new_address_count
  • get_daily_network_utilization
  • get_daily_average_network_hash_rate
  • get_daily_tx_count
  • get_daily_average_network_difficulty
  • get_eth_hist_daily_market_cap
  • get_eth_hist_price

If you think that a newly-added method is missing, kindly open an issue as a feature request and I will do my best to add it.

Installation

Before proceeding, you should register an account on Etherscan.io and generate a personal API key to use.

If you wish to have access to the PRO endpoints, you should obtain elevated privileges via Etherscan's subscription service.

Install from source:

pip install git+https://github.com/pcko1/etherscan-python.git

Alternatively, install from PyPI:

pip install etherscan-python

Unit tests

In bash, test that everything looks OK on your end using your YOUR_API_KEY (without quotation marks) before proceeding:

bash run_tests.sh YOUR_API_KEY

This will regenerate the logs under logs/ with the most recent results and the timestamp of the execution.

The tests also include the PRO endpoints so if your key is not PRO, the correspondings tests are expected to fail.

Usage

In python, create a client with your personal Etherscan.io API key:

from etherscan import Etherscan
eth = Etherscan(YOUR_API_KEY) # key in quotation marks

Then you can call all available methods, e.g.:

eth.get_eth_balance(address="0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a")

> '40891631566070000000000'

You can also choose one of the other testnets:

eth = Etherscan(YOUR_API_KEY, net="ropsten") # net name is case-insensitive, default is main

Examples

Examples (arguments and results) for all methods may be found as JSON files here. For example, if you want to use the method get_block_number_by_timestamp, you can find the supported arguments and the format of its output in its respective JSON file:

{
  "method": "get_block_number_by_timestamp",
  "module": "blocks",
  "kwargs": {
    "timestamp": "1578638524",
    "closest": "before"
  },
  "log_timestamp": "2020-10-28-12:34:44",
  "res": "9251482"
}

where kwargs refer to the required named arguments and res refers to the expected result if you were to run:

eth.get_block_number_by_timestamp(timestamp="1578638524", closest="before")

> '9251482'

Disclaimer: Those examples blindly use the arguments originally showcased here and the selected wallets/contracts do not reflect any personal preference. You should refer to the same source for additional information regarding specific argument values.

Issues

For problems regarding installing or using the package please open an issue. Kindly avoid disclosing potentially sensitive information such as your API keys or your wallet addresses.

Cite

Kotsias, P. C., pcko1/etherscan-python. https://github.com/pcko1/etherscan-python (2020). doi:10.5281/zenodo.4306855

or in bibtex:

@misc{Kotsias2020,
  author = {Kotsias, P.C.},
  title = {pcko1/etherscan-python},
  year = {2020},
  publisher = {Zenodo},
  url = {https://github.com/pcko1/etherscan-python},
  doi = {10.5281/zenodo.4306855}
}

Feel free to leave a โญ if you found this package useful.


Powered by Etherscan.io APIs.

etherscan-python's People

Contributors

codacy-badger avatar eggpool avatar litneet64 avatar pcko1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

etherscan-python's Issues

[QUESTION] How to know if a transaction incude mint action?

I'm trying to get the list of normal transactions, and then find transactions which include mint action in it. But I'm stuck on the second part.

for example, this transaction page include "Transaction Action" section which include "Mint" section.
https://etherscan.io/tx/0x7d47e77707dee45dff42e4857dcf53e957d37ca3249242838edb897f7da0ad88

seems that I can use method ID (4 bytes signature) to know what is the transaction about, but there are too many signatures. I don't think it's a reliable way to do this.

Is there any API call that I didn't notice include such info? Or I missed some point?

Sorry this is not an issue but just a question, I couldn't find other places to ask for help.

How to get transaction details in more human readable form

Hello am trying to get transaction details using a transaction hash from the proxy.py module but the response I get in return is not readable at all. How do I decode the response to a human readable form.
Here is how am doing it

# file.py
from etherscan import Etherscan
from pprint import pprint
eth = Etherscan(api_key=settings.API_KEY)

txn_hash = '0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1'
txn_details = eth.get_proxy_transaction_receipt(txn_hash)
pprint(txn_details)

Response

{'blockHash': '0xf64a12502afc36db3d29931a2148e5d6ddaa883a2a3c968ca2fb293fa9258c68',
 'blockNumber': '0x70839',
 'contractAddress': None,
 'cumulativeGasUsed': '0x75d5',
 'from': '0xc80fb22930b303b55df9b89901889126400add38',
 'gasUsed': '0x75d5',
 'logs': [{'address': '0x03fca6077d38dd99d0ce14ba32078bd2cda72d74',
           'blockHash': '0xf64a12502afc36db3d29931a2148e5d6ddaa883a2a3c968ca2fb293fa9258c68',
           'blockNumber': '0x70839',
           'data': '0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000a4861636b65726e65777300000000000000000000000000000000000000000000',
           'logIndex': '0x0',
           'removed': False,
           'topics': ['0x24bcf19562365f6510754002f8d7b818d275886315d29c7aa04785570b97a363'],
           'transactionHash': '0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1',
           'transactionIndex': '0x0'}],
 'logsBloom': '0x00000000000000000000000000000400000000020000000000000000400000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
 'root': '0xc659845f1ac4e899ff1b0666dbac5deeda33a4a5d85da71f617f352824146e40',
 'to': '0x03fca6077d38dd99d0ce14ba32078bd2cda72d74',
 'transactionHash': '0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1',
 'transactionIndex': '0x0'}

Any way to get cumulativeGasUsed, status etc in readable form say int, boolean respectively? Something like this...

var receipt = web3.eth.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b')
.then(console.log);

> {
  "status": true,
  "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
  "transactionIndex": 0,
  "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
  "blockNumber": 3,
  "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
  "cumulativeGasUsed": 314159,
  "gasUsed": 30234,
  "logs": [{
         // logs as returned by getPastLogs, etc.
     }, ...]
}

Adopted here https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html#eth-gettransaction-return ?

Image of a transaction details page
image

Get Contract Addresses by Address

I would like to know if there is a way of returning all contract adresses from a given wallet address. I.e. to return all tokens and their contracts within a wallet.

TypeError: expected str, bytes or os.PathLike object, not NoneType

from etherscan.etherscan import Etherscan
api_key = 'xxxxxxx'

eth = Etherscan(api_key)

Traceback (most recent call last):
File "C:/Python39-32/test.py", line 4, in
eth = Etherscan(api_key)
File "C:\Python39-32\lib\site-packages\etherscan\etherscan.py", line 14, in new
with resources.path(configs, "stable.json") as path:
File "C:\Python39-32\lib\importlib\resources.py", line 165, in path
_common.as_file(files(package).joinpath(_normalize_path(resource)))
File "C:\Python39-32\lib\importlib\resources.py", line 147, in files
return _common.from_package(_get_package(package))
File "C:\Python39-32\lib\importlib_common.py", line 14, in from_package
return fallback_resources(package.spec)
File "C:\Python39-32\lib\importlib_common.py", line 18, in fallback_resources
package_directory = pathlib.Path(spec.origin).parent
File "C:\Python39-32\lib\pathlib.py", line 1071, in new
self = cls._from_parts(args, init=False)
File "C:\Python39-32\lib\pathlib.py", line 696, in _from_parts
drv, root, parts = self._parse_args(args)
File "C:\Python39-32\lib\pathlib.py", line 680, in _parse_args
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not NoneType

Add support for testnets

Hi, I'm working on a project that relies on etherscan-python for communicating with Etherscan.io's API, and having support for querying stuff on the other testnets will come really handy for the end goal of it.

Luckily, I already added that feature on a fork I did from this project following the overall "minimalism" (as said on the description) and also adding the testnets to the module tests with their own working/stable test cases (randomly sampled - [*]) along with a minimalist usage example on the README.

[*] Unfortunately, I don't possess a PRO API key, so I couldn't find working test cases for the PRO endpoints nor I know if they are already passing with those parameters or not.

ImportError: cannot import name 'resources'

I get the following error when using the library:

$ python3 run_script.py
Traceback (most recent call last):
  File "run_script.py", line 1, in <module>
    from etherscan.accounts import Account
  File "/home/ubuntu/.local/lib/python3.6/site-packages/etherscan/__init__.py", line 1, in <module>
    from .etherscan import Etherscan
  File "/home/ubuntu/.local/lib/python3.6/site-packages/etherscan/etherscan.py", line 2, in <module>
    from importlib import resources
ImportError: cannot import name 'resources'

I use python 3.6 and installed the library with pip3 install etherscan-python.

bash run_tests.sh My_api_key gives this kinda error

======================================================================
FAIL: test_methods (test.test_modules.TestPro)

Traceback (most recent call last):
File "/home/rk/Documents/etherscan-python/test/test_modules.py", line 33, in test_methods
res = getattr(etherscan, fun)(**v["kwargs"])
File "/home/rk/Documents/etherscan-python/etherscan/etherscan.py", line 33, in wrapper
return parser.parse(r)
File "/home/rk/Documents/etherscan-python/etherscan/utils/parsing.py", line 12, in parse
assert status, f"{result} -- {message}"
AssertionError: Error! Missing Or invalid Action name -- NOTOK

Optional query parameters work like required

When I am using the rest api, i can send request without using endblock parameter:
https://api.etherscan.io/api?module=account&action=tokentx&address=0x4e83362442b8d1bec281594cea3050c8eb01311c&startblock=12328953&sort=asc&apikey=YourApiKeyToken

But the library doesn't allow to do this:

In [5]: eth.get_erc20_token_transfer_events_by_address(address='0x4e83362442b8d1bec281594cea3050c8eb01311c', startblock=12328953)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-e4416848c949> in <module>
----> 1 eth.get_erc20_token_transfer_events_by_address(address='0x4e83362442b8d1bec281594cea3050c8eb01311c', startblock=12328953)

/usr/local/lib/python3.8/dist-packages/etherscan/etherscan.py in wrapper(*args, **kwargs)
     25         def wrapper(*args, **kwargs):
     26             url = (
---> 27                 f"{fields.PREFIX.format(net.lower()).replace('-main','')}"
     28                 f"{func(*args, **kwargs)}"
     29                 f"{fields.API_KEY}"

TypeError: get_erc20_token_transfer_events_by_address() missing 2 required positional arguments: 'endblock' and 'sort'

Constant error after few hours

Hello,

I'm using this package to retrieve the eth gas price every 30 seconds and save it in a HDF5 file, but at a random time after a random times I'm getting an error related to the parsing function in the package:

File "/root/miniconda3/lib/python3.8/site-packages/etherscan/utils/parsing.py", line 12, in parse
    assert status, f"{result} -- {message}"
AssertionError: Error! -- NOTOK

This is my complete code:

import time
import h5py
import pandas as pd
from datetime import datetime
from etherscan import Etherscan

# my api from etherscan.io
eth = Etherscan("MY_API")

# Creating the HDF5 database
store = pd.HDFStore("eth_gas.h5")
while True:
    try:
        gas_db = pd.DataFrame() 
        gas = eth.get_gas_oracle()

        for key in gas:
            gas[key] = int(gas[key]) 

        gas_db = pd.DataFrame(gas, index = [pd.to_datetime(datetime.now(), format="%Y-%m-%d %H:%M:%S.%f")])

        store.append("eth_gas", gas_db, format='table',  encoding = "UTF8", data_columns=True) 
        print("######### Last time read (30 seconds) #########\n", gas_db.iloc[-1], "\n") 
        time.sleep(30)
    except ValueError:
        print("Something was wrong... Trying again...")

And as I said, everything is running smoothly and without problems and randomly I got that error, my script dies and I can not build a consistent data base of historical price gas.

"AssertionError: None -- Query Timeout occured. Please select a smaller result dataset" when queuing a large number of calls

I am trying to call "get_erc721_token_transfer_events_by_address" on a rather large set of wallet addresses (roughly 1000) and iterating over a for loop to do so - I thought it might be an issue with the calls per second cap so I set the sleep time to .22 seconds then to 1 second after the calls - without any luck.

Any ideas as to why this is happening? I'm guessing this is on Etherscan's side but I'm hoping someone might have some insight?

Using package

Hi there!

I'm trying to use etherscan-python in my project. For that, I installed it through pip by using pip install etherscan-python.

Then when I try to import it

from etherscan import Etherscan
eth = Etherscan('mykey')

It throws:

FileNotFoundError: Package has no location <module 'etherscan.configs' (namespace)>

Any suggestion?

Thank you in advance!

USD values

When downloading transaction data as CSV from etherscan it includes "TxnFee(USD)" and "Historical $Price/Eth". Is there any way to get these values from the APIs?

Assert Behavior on scraping wallet without transactions

in commit fb697e1 the following behavior was introduced:

# etherscan/utils/parsing.py 
assert status, f"{result} -- {message}"

to replace the UserWarning behavior:

#etherscan/utils/parsing.py 
warnings.warn(f"{result} -- {message}")

This has made the event of scraping an empty address, "aggressive" and forces downstream applications to catch a generic AssertionError, for this---in my case common---scenario. imho, getting an empty list back in case no records exist, is completely valid behavior?

Could you elaborate on why this behavior was chosen, and this change was made?

Using get_erc721_token_transfer_events_by_address

hi!

I'm new to this package...

from etherscan import Etherscan
eth = Etherscan('MY API KEY') # key in quotation marks

block_number_start=eth.get_block_number_by_timestamp(timestamp="1609490044", closest="before")
block_number_end=eth.get_block_number_by_timestamp(timestamp="1637224444", closest="before")

erc_20_transactions = eth.get_erc20_token_transfer_events_by_address(address='0xd8Fa365f358729Af1D62206BdDaD84cBb2BEFB7d',startblock=block_number_start,endblock=block_number_end,sort='asc')
erc_721_transactions = eth.get_erc721_token_transfer_events_by_address(address='0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a',startblock=block_number_start,endblock=block_number_end,sort='asc')

print(block_number_start)
print(block_number_end)
print(erc_20_transactions)
print(erc_721_transactions)

This is a fragment of code I'm using by I keep getting errors....can anyone help me?

Get all transactions by contract address

First of all, thanks a lot for your library ๐Ÿ‘Œ

I found nearly everything I needed but is it possible, that

https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=CONTRACTADRESS&startblock=0&sort=desc&apikey=YOURAPIKEY

isn't possible at the moment? I find this a very useful function, as I want to filter not by address, I want to filter by contract address. If this is already possible, can you let me know which function is used for it? If it isn't possible at the moment, I want to suggest this feature to keep your library complete.

Best and thanks in advance!

AssertionError: [] -- No transactions found

Hello,

When i try to get last transfer events of my account like that :

eth_erc20_events = eth.get_erc20_token_transfer_events_by_address(address='0xa71ac2c62A1b477186f5CbF45d94fFcd5D7e5711', startblock=0, endblock=1000000, sort='des')

I got AssertionError: [] -- No transactions found

I'm not sure of what i should set on startblock & endblock, can you help please :) ?

My main goal is to find my pending and successfull transaction of last month.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.