forked from Larsenvini/EazyChains
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_calls.py
84 lines (70 loc) · 2.76 KB
/
api_calls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import os
import requests
from dotenv import load_dotenv
from clean_api_calls import *
load_dotenv()
BASE_URL = os.getenv('BASE_URL')
if not BASE_URL:
raise ValueError("A URL base não foi encontrada. Verifique o arquivo .env.")
def make_api_url(module: str, action: str, **params) -> str:
api_key = os.getenv('ETHERSCAN_API_KEY')
if not api_key:
raise ValueError("A chave de API não foi encontrada. Verifique o arquivo .env.")
params_list = [f"{key}={value}" for key, value in params.items()]
params_str = "&".join(params_list)
url = f"{BASE_URL}?module={module}&action={action}&{params_str}&apikey={api_key}"
return url
def get_balance_by_address(address: str) -> dict:
url = make_api_url(module="account", action="balance", address=address, tag="latest")
try:
response = requests.get(url)
response.raise_for_status() # Lançar HTTPError para respostas ruins
data = response.json()
return clean_account_balance(data)
except requests.exceptions.RequestException as e:
return {"error": f"HTTP request failed: {str(e)}"}
except ValueError as e:
return {"error": f"JSON decoding failed: {str(e)}"}
def get_last_block() -> dict:
url = make_api_url(module="proxy", action="eth_blockNumber")
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
return clean_last_block(data)
except requests.exceptions.RequestException as e:
return {"error": f"HTTP request failed: {str(e)}"}
except ValueError as e:
return {"error": f"JSON decoding failed: {str(e)}"}
def get_last_transactions(address: str, start_block: int = 0, end_block: int = 99999999, sort: str = "desc") -> dict:
url = make_api_url(
module="account",
action="txlist",
address=address,
startblock=start_block,
endblock=end_block,
sort=sort
)
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
return clean_transactions(data)
except requests.exceptions.RequestException as e:
return {"error": f"HTTP request failed: {str(e)}"}
except ValueError as e:
return {"error": f"JSON decoding failed: {str(e)}"}
def eth_getTransactionByHash(hash: str) -> dict:
url = make_api_url(
module="proxy",
action="eth_getTransactionByHash",
txhash=hash
)
try:
response = requests.get(url)
response.raise_for_status()
return clean_TransactionbyHash(response.json())
except requests.exceptions.RequestException as e:
return {"error": f"HTTP request failed: {str(e)}"}
except ValueError as e:
return {"error": f"JSON decoding failed: {str(e)}"}