Skip to content

Commit bb7d0aa

Browse files
committed
Removed redundant _get_token_address() parameters
1 parent 24f97a1 commit bb7d0aa

File tree

3 files changed

+59
-48
lines changed

3 files changed

+59
-48
lines changed

pytoros/token.py

Lines changed: 55 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,61 +3,77 @@
33

44
class Token:
55
"""
6-
A class to represent a leveraged token on Toros Finance
6+
A class to represent a leveraged token on Toros Finance.
77
"""
8+
CHAIN_IDS = {
9+
"POL": 137, # Polygon
10+
"OP": 10, # Optimism
11+
"ARB": 42161, # Arbitrum
12+
"BASE": 8453, # Base
13+
}
14+
TOROS_URL = "https://toros.finance/_next/data/mw471zlJ9uL1Ee-_If1FI/category/leverage.json?category=leverage"
15+
GRAPHQL_URL = "https://api-v2.dhedge.org/graphql"
16+
SCALE_FACTOR = 10**18
17+
818
def __init__(self, ticker: str) -> None:
919
"""
10-
Initialize the Token with a contract address.
20+
Initialize the Token with a ticker string.
1121
12-
:param symbol: str: The token's contract address (e.g., "ARB:BTCBULL3X").
22+
:param ticker: str: The token's ticker in "CHAIN:SYMBOL" format (e.g., "ARB:BTCBULL3X").
1323
"""
24+
if ':' not in ticker:
25+
raise ValueError("Ticker must be in 'CHAIN:SYMBOL' format.")
26+
1427
self.ticker: str = ticker
15-
splits = ticker.split(':')
16-
self.chain_name: str = splits[0]
17-
self.symbol: str = splits[1]
18-
19-
def _get_chain_id(self, chain_name: str) -> int:
20-
chain_names = {
21-
"POL": 137, # Polygon
22-
"OP": 10, # Optimism
23-
"ARB": 42161, # Arbitrum
24-
"BASE": 8453, # Base
25-
}
26-
27-
chain_id = chain_names.get(chain_name.upper())
28+
self.chain_name, self.symbol = ticker.split(':', 1)
29+
30+
def _get_chain_id(self) -> int:
31+
chain_id = self.CHAIN_IDS.get(self.chain_name.upper())
2832
if chain_id is None:
29-
raise ValueError(f"Chain ID not found for chain name: {chain_name}")
30-
33+
raise ValueError(f"Invalid chain name '{self.chain_name}'. Valid options: {', '.join(self.CHAIN_IDS.keys())}")
3134
return chain_id
3235

33-
def _get_token_address(self, chain_name: str, symbol: str) -> str:
34-
chain_id = self._get_chain_id(chain_name)
35-
36-
url = "https://toros.finance/_next/data/mw471zlJ9uL1Ee-_If1FI/category/leverage.json?category=leverage"
37-
response = requests.get(url)
36+
def _get_token_address(self) -> str:
37+
response = requests.get(self.TOROS_URL, timeout=10)
3838
response.raise_for_status()
3939
data = response.json()
4040

41-
products = data.get('pageProps', {}).get('products', {})
42-
41+
chain_id = self._get_chain_id()
42+
products = data.get('pageProps', {}).get('products', [])
43+
4344
for product in products:
44-
if product.get('chainId') == chain_id and product.get('symbol') == symbol:
45+
if product.get('chainId') == chain_id and product.get('symbol') == self.symbol:
4546
return product.get('address')
46-
47-
raise ValueError(f"Token with symbol '{symbol}' and chain '{chain_name}' not found.")
47+
48+
raise ValueError(f"Token with symbol '{self.symbol}' and chain '{self.chain_name}' not found.")
4849

4950
def history(self, period: str = "1y", interval: str = "1d") -> pd.DataFrame:
5051
"""
5152
Fetch historical data for the token.
5253
53-
:param period: str: The period of price history (can be "1d", "1w", "1m", or "1y", default is "1y").
54-
:param interval: str: The interval for data points (can be "1h", "4h", "1d", "1w", default is "1d").
54+
:param period: str: Period of price history ("1d", "1w", "1m", "1y").
55+
:param interval: str: Interval for data points ("1h", "4h", "1d", "1w").
5556
:return: pd.DataFrame: Token's price history as a DataFrame.
5657
"""
57-
address = self._get_token_address(self.chain_name, self.symbol)
58-
url = "https://api-v2.dhedge.org/graphql"
58+
valid_periods = {"1d", "1w", "1m", "1y"}
59+
valid_intervals = {"1h", "4h", "1d", "1w"}
60+
61+
if period not in valid_periods:
62+
raise ValueError(f"Invalid period '{period}'. Valid options: {', '.join(valid_periods)}")
63+
if interval not in valid_intervals:
64+
raise ValueError(f"Invalid interval '{interval}'. Valid options: {', '.join(valid_intervals)}")
65+
66+
address = self._get_token_address()
5967
payload = {
60-
"query": "query GetTokenPriceCandles($address: String!, $period: String!, $interval: String) {\n tokenPriceCandles(address: $address, period: $period, interval: $interval) {\n timestamp\n open\n close\n max\n min\n }\n}\n",
68+
"query": """query GetTokenPriceCandles($address: String!, $period: String!, $interval: String) {
69+
tokenPriceCandles(address: $address, period: $period, interval: $interval) {
70+
timestamp
71+
open
72+
close
73+
max
74+
min
75+
}
76+
}""",
6177
"variables": {
6278
"address": address,
6379
"period": period,
@@ -66,30 +82,25 @@ def history(self, period: str = "1y", interval: str = "1d") -> pd.DataFrame:
6682
"operationName": "GetTokenPriceCandles"
6783
}
6884

69-
response = requests.post(url, json=payload)
85+
response = requests.post(self.GRAPHQL_URL, json=payload, timeout=10)
7086
response.raise_for_status()
7187
data = response.json()
7288

7389
candles = data.get("data", {}).get("tokenPriceCandles", [])
7490
if not candles:
7591
raise ValueError("No data returned for the specified parameters.")
7692

77-
df = pd.DataFrame(candles)
78-
df = df.rename(columns={
93+
df = pd.DataFrame(candles).rename(columns={
7994
"timestamp": "Date",
8095
"open": "Open",
8196
"close": "Close",
8297
"max": "High",
8398
"min": "Low"
8499
})
85-
86-
df["Date"] = pd.to_numeric(df["Date"], errors='coerce')
87-
df["Date"] = pd.to_datetime(df["Date"], unit='ms')
100+
101+
df["Date"] = pd.to_datetime(pd.to_numeric(df["Date"], errors='coerce'), unit='ms')
88102
df.set_index("Date", inplace=True)
89-
90-
scale_factor = 10**18
91103
df[["Open", "Close", "High", "Low"]] = df[["Open", "Close", "High", "Low"]].apply(
92-
lambda x: x.astype(int) / scale_factor
104+
lambda x: x.astype(float) / self.SCALE_FACTOR
93105
)
94-
95-
return df
106+
return df

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
setup(
44
name="pytoros",
5-
version="0.1.0",
5+
version="0.1.1",
66
description="An unoffical pythonic wrapper for Toros Finance",
77
long_description=open("README.md").read(),
88
long_description_content_type="text/markdown",

tests/test_token.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def test_get_token_address_success(self, mock_get):
1919

2020
token = Token("ARB:BTCBULL3X")
2121

22-
address = token._get_token_address('ARB', 'BTCBULL3X')
22+
address = token._get_token_address()
2323
self.assertEqual(address, '0x1234567890abcdef')
2424

2525
@patch('requests.get')
@@ -36,7 +36,7 @@ def test_get_token_address_not_found(self, mock_get):
3636
token = Token("ARB:BTCBULL3X")
3737

3838
with self.assertRaises(ValueError):
39-
token._get_token_address('ARB', 'BTCBULL3X')
39+
token._get_token_address()
4040

4141
@patch('requests.post')
4242
def test_history_success(self, mock_post):
@@ -76,7 +76,7 @@ class LiveTestToken(unittest.TestCase):
7676

7777
def test_get_token_address_live(self):
7878
token = Token("ARB:BTCBULL3X")
79-
address = token._get_token_address("ARB", "BTCBULL3X")
79+
address = token._get_token_address()
8080
self.assertEqual(address, "0xad38255febd566809ae387d5be66ecd287947cb9")
8181

8282
def test_get_token_history(self):

0 commit comments

Comments
 (0)