allora-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
allora_sdk/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,199 @@
1
+ import aiohttp
2
+ from enum import Enum
3
+ from typing import List, Optional, TypeVar, Generic, Any
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ class ChainSlug(str, Enum):
8
+ TESTNET = "testnet"
9
+ MAINNET = "mainnet"
10
+
11
+
12
+ class ChainID(str, Enum):
13
+ TESTNET = "allora-testnet-1"
14
+ MAINNET = "allora-mainnet-1"
15
+
16
+
17
+ class PricePredictionToken(str, Enum):
18
+ BTC = "BTC"
19
+ ETH = "ETH"
20
+
21
+
22
+ class PricePredictionTimeframe(str, Enum):
23
+ FIVE_MIN = "5m"
24
+ EIGHT_HOURS = "8h"
25
+
26
+
27
+ class SignatureFormat(str, Enum):
28
+ ETHEREUM_SEPOLIA = "ethereum-11155111"
29
+
30
+
31
+ class AlloraTopic(BaseModel):
32
+ topic_id: int
33
+ topic_name: str
34
+ description: Optional[str] = None
35
+ epoch_length: int
36
+ ground_truth_lag: int
37
+ loss_method: str
38
+ worker_submission_window: int
39
+ worker_count: int
40
+ reputer_count: int
41
+ total_staked_allo: float
42
+ total_emissions_allo: float
43
+ is_active: Optional[bool] = None
44
+ updated_at: str
45
+
46
+
47
+ class AlloraInferenceData(BaseModel):
48
+ network_inference: str
49
+ network_inference_normalized: str
50
+ confidence_interval_percentiles: List[str]
51
+ confidence_interval_percentiles_normalized: List[str]
52
+ confidence_interval_values: List[str]
53
+ confidence_interval_values_normalized: List[str]
54
+ topic_id: str
55
+ timestamp: int
56
+ extra_data: str
57
+
58
+
59
+ class AlloraInference(BaseModel):
60
+ signature: str
61
+ inference_data: AlloraInferenceData
62
+
63
+
64
+ class TopicsResponse(BaseModel):
65
+ topics: List[AlloraTopic]
66
+ continuation_token: Optional[str] = None
67
+
68
+
69
+ T = TypeVar("T")
70
+
71
+
72
+ class AlloraAPIResponse(BaseModel, Generic[T]):
73
+ request_id: str
74
+ status: bool
75
+ api_response_message: Optional[str] = Field(None, alias="apiResponseMessage")
76
+ data: T
77
+
78
+ class Fetcher:
79
+ async def fetch(self, url: str, headers: dict) -> Any:
80
+ pass
81
+
82
+ class DefaultFetcher(Fetcher):
83
+ async def fetch(self, url: str, headers: dict) -> Any:
84
+ async with aiohttp.ClientSession() as session:
85
+ async with session.get(url, headers=headers) as response:
86
+ response.raise_for_status()
87
+ return await response.json()
88
+
89
+
90
+ class AlloraAPIClient:
91
+ def __init__(
92
+ self,
93
+ chain_slug: Optional[ChainSlug] = None,
94
+ api_key: Optional[str] = "UP-8cbc632a67a84ac1b4078661",
95
+ base_api_url: Optional[str] = "https://api.upshot.xyz/v2",
96
+ fetcher: Fetcher = DefaultFetcher(),
97
+ ):
98
+ self.chain_id = (ChainID.TESTNET if chain_slug == ChainSlug.TESTNET else ChainID.MAINNET).value
99
+ self.api_key = api_key
100
+ self.base_api_url = base_api_url
101
+ self.fetcher = fetcher
102
+
103
+ async def get_all_topics(self) -> List[AlloraTopic]:
104
+ """
105
+ Fetches all available topics from the Allora API.
106
+ This method handles pagination automatically by following continuation tokens
107
+ until all topics have been retrieved.
108
+
109
+ :return: A list of all available topics
110
+ :raises: requests.RequestException if the API request fails
111
+ """
112
+ all_topics: List[AlloraTopic] = []
113
+ continuation_token: Optional[str] = None
114
+
115
+ while True:
116
+ response = await self.fetch_api_response(f"allora/{self.chain_id}/topics", TopicsResponse)
117
+ all_topics.extend(response.data.topics)
118
+ continuation_token = response.data.continuation_token
119
+ if not continuation_token:
120
+ break
121
+
122
+ return all_topics
123
+
124
+ async def get_inference_by_topic_id(
125
+ self,
126
+ topic_id: int,
127
+ signature_format: SignatureFormat = SignatureFormat.ETHEREUM_SEPOLIA,
128
+ ) -> AlloraInference:
129
+ """
130
+ Fetches an inference for a specific topic from the Allora API.
131
+
132
+ :param topic_id: The unique identifier of the topic to get inference for
133
+ :param signature_format: The signature format to use
134
+ :return: The inference data
135
+ :raises: requests.RequestException if the API request fails
136
+ """
137
+ response = await self.fetch_api_response(
138
+ f"allora/consumer/{signature_format.value}?allora_topic_id={topic_id}&inference_value_type=uint256",
139
+ AlloraInference,
140
+ )
141
+
142
+ if not response.data.inference_data:
143
+ raise ValueError("Failed to fetch price prediction")
144
+ return response.data
145
+
146
+ async def get_price_prediction(
147
+ self,
148
+ asset: PricePredictionToken,
149
+ timeframe: PricePredictionTimeframe,
150
+ signature_format: SignatureFormat = SignatureFormat.ETHEREUM_SEPOLIA,
151
+ ) -> AlloraInference:
152
+ """
153
+ Fetches a price prediction for a specific asset and timeframe from the Allora API.
154
+
155
+ :param asset: The asset to get price prediction for
156
+ :param timeframe: The timeframe to get price prediction for
157
+ :param signature_format: The signature format to use
158
+ :return: The inference data
159
+ :raises: requests.RequestException if the API request fails
160
+ """
161
+ response = await self.fetch_api_response(
162
+ f"allora/consumer/price/{signature_format.value}/{asset.value}/{timeframe.value}",
163
+ AlloraInference,
164
+ )
165
+
166
+ if not response.data.inference_data:
167
+ raise ValueError("Failed to fetch price prediction")
168
+ return response.data
169
+
170
+ def get_request_url(self, endpoint: str) -> str:
171
+ """
172
+ Constructs the full request URL for a given endpoint.
173
+
174
+ :param endpoint: The API endpoint
175
+ :return: The full request URL
176
+ """
177
+ api_url = self.base_api_url.rstrip("/")
178
+ endpoint = endpoint.lstrip("/")
179
+ return f"{api_url}/{endpoint}"
180
+
181
+ async def fetch_api_response(self, endpoint: str, response_model: type) -> AlloraAPIResponse:
182
+ """
183
+ Fetches and parses the API response for a given endpoint.
184
+
185
+ :param endpoint: The API endpoint to fetch
186
+ :param response_model: The Pydantic model to parse the response data into
187
+ :return: The parsed API response
188
+ :raises: requests.RequestException if the API request fails
189
+ """
190
+ url = self.get_request_url(endpoint)
191
+ headers = {
192
+ "Accept": "application/json",
193
+ "Content-Type": "application/json",
194
+ "x-api-key": self.api_key,
195
+ }
196
+ response_data = await self.fetcher.fetch(url, headers)
197
+
198
+ return AlloraAPIResponse[response_model](**response_data)
199
+
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: allora_sdk
3
+ Version: 0.1.0
4
+ Summary: Allora Network SDK
5
+ Project-URL: Homepage, https://github.com/allora-network/allora-sdk-py
6
+ Project-URL: Issues, https://github.com/allora-network/allora-sdk-py/issues
7
+ Project-URL: Allora Network, https://allora.network
8
+ Author-email: spooktheducks <spooktheducks@protonmail.com>
9
+ License-File: LICENSE
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.8
14
+ Requires-Dist: aiohttp
15
+ Requires-Dist: annotated-types==0.7.0
16
+ Requires-Dist: cachetools==5.5.0
17
+ Requires-Dist: certifi==2024.12.14
18
+ Requires-Dist: chardet==5.2.0
19
+ Requires-Dist: charset-normalizer==3.4.1
20
+ Requires-Dist: colorama==0.4.6
21
+ Requires-Dist: distlib==0.3.9
22
+ Requires-Dist: filelock==3.16.1
23
+ Requires-Dist: idna==3.10
24
+ Requires-Dist: packaging==24.2
25
+ Requires-Dist: platformdirs==4.3.6
26
+ Requires-Dist: pluggy==1.5.0
27
+ Requires-Dist: pydantic-core==2.27.2
28
+ Requires-Dist: pydantic==2.10.4
29
+ Requires-Dist: pyproject-api==1.8.0
30
+ Requires-Dist: requests==2.32.3
31
+ Requires-Dist: tox==4.23.2
32
+ Requires-Dist: typing-extensions==4.12.2
33
+ Requires-Dist: urllib3==2.3.0
34
+ Requires-Dist: virtualenv==20.28.1
35
+ Provides-Extra: dev
36
+ Requires-Dist: fastapi; extra == 'dev'
37
+ Requires-Dist: pytest; extra == 'dev'
38
+ Requires-Dist: pytest-asyncio; extra == 'dev'
39
+ Requires-Dist: starlette; extra == 'dev'
40
+ Requires-Dist: tox; extra == 'dev'
41
+ Description-Content-Type: text/markdown
42
+
43
+
44
+
45
+ # Allora Network Python SDK
46
+
47
+ Install:
48
+
49
+ ```
50
+ pip install allora_sdk
51
+ ```
52
+
53
+ Run tests:
54
+
55
+ ```
56
+ tox
57
+ ```
58
+
59
+
60
+
61
+ ```py
62
+ from allora_sdk.v2.api_client import (
63
+ AlloraAPIClient,
64
+ ChainSlug,
65
+ PricePredictionToken,
66
+ PricePredictionTimeframe,
67
+ AlloraTopic,
68
+ AlloraInference,
69
+ )
70
+
71
+ client = AlloraAPIClient(
72
+ chain_slug=ChainSlug.TESTNET, # Or MAINNET
73
+ api_key=os.environ.get("ALLORA_API_KEY"), # Optional
74
+ base_api_url=os.environ.get("ALLORA_API_URL"), # Optional
75
+ )
76
+
77
+ # Each topic is as follows:
78
+ #
79
+ # class AlloraTopic(BaseModel):
80
+ # topic_id: int
81
+ # topic_name: str
82
+ # description: Optional[str] = None
83
+ # epoch_length: int
84
+ # ground_truth_lag: int
85
+ # loss_method: str
86
+ # worker_submission_window: int
87
+ # worker_count: int
88
+ # reputer_count: int
89
+ # total_staked_allo: float
90
+ # total_emissions_allo: float
91
+ # is_active: Optional[bool] = None
92
+ # updated_at: str
93
+ topics = await client.get_all_topics()
94
+
95
+ # Each inference response is as follows:
96
+ #
97
+ # class AlloraInference(BaseModel):
98
+ # signature: str
99
+ # inference_data: AlloraInferenceData
100
+ #
101
+ # class AlloraInferenceData(BaseModel):
102
+ # network_inference: str
103
+ # network_inference_normalized: str
104
+ # confidence_interval_percentiles: List[str]
105
+ # confidence_interval_percentiles_normalized: List[str]
106
+ # confidence_interval_values: List[str]
107
+ # confidence_interval_values_normalized: List[str]
108
+ # topic_id: str
109
+ # timestamp: int
110
+ # extra_data: str
111
+
112
+ # Fetch inferences by topic ID
113
+ result = await client.get_inference_by_topic_id(topics[0].topic_id)
114
+ print(f'{topics[0].topic_name} price inference: {result.inference_data.network_inference_normalized}')
115
+
116
+ # Fetch inferences by asset and timeframe
117
+ result = await client.get_price_prediction(PricePredictionToken.BTC, PricePredictionTimeframe.EIGHT_HOURS)
118
+ print(f'{topics[0].topic_name} price inference: {result.inference_data.network_inference_normalized}')
119
+ ```
120
+
121
+
@@ -0,0 +1,7 @@
1
+ allora_sdk/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ allora_sdk/v2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ allora_sdk/v2/api_client.py,sha256=mBhLIJ4kwcLTUqjd8Jaig_3tO8LZdcMaOjEmi3Owhds,6336
4
+ allora_sdk-0.1.0.dist-info/METADATA,sha256=86SnDMhtWnTPgeHuRxvb0JQJOFWhP33UZS7w5wOjMzI,3440
5
+ allora_sdk-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ allora_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=BkooYJNBMPs2gTJ1uU5rIOmVJ6cVSoKMCVUR4nwHiJg,551
7
+ allora_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,13 @@
1
+ Copyright 2025 Allora Labs
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.