allora-sdk 0.1.0__tar.gz
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-0.1.0/.gitignore +10 -0
- allora_sdk-0.1.0/LICENSE +13 -0
- allora_sdk-0.1.0/PKG-INFO +121 -0
- allora_sdk-0.1.0/README.md +79 -0
- allora_sdk-0.1.0/pyproject.toml +85 -0
- allora_sdk-0.1.0/src/allora_sdk/__init__.py +0 -0
- allora_sdk-0.1.0/src/allora_sdk/v2/__init__.py +0 -0
- allora_sdk-0.1.0/src/allora_sdk/v2/api_client.py +199 -0
- allora_sdk-0.1.0/tests/__init__.py +0 -0
- allora_sdk-0.1.0/tests/mock_data.py +108 -0
- allora_sdk-0.1.0/tests/test_api_client_integration.py +99 -0
- allora_sdk-0.1.0/tests/test_api_client_unit.py +88 -0
- allora_sdk-0.1.0/tox.toml +26 -0
allora_sdk-0.1.0/LICENSE
ADDED
|
@@ -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.
|
|
@@ -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,79 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
# Allora Network Python SDK
|
|
4
|
+
|
|
5
|
+
Install:
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
pip install allora_sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Run tests:
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
tox
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
```py
|
|
20
|
+
from allora_sdk.v2.api_client import (
|
|
21
|
+
AlloraAPIClient,
|
|
22
|
+
ChainSlug,
|
|
23
|
+
PricePredictionToken,
|
|
24
|
+
PricePredictionTimeframe,
|
|
25
|
+
AlloraTopic,
|
|
26
|
+
AlloraInference,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
client = AlloraAPIClient(
|
|
30
|
+
chain_slug=ChainSlug.TESTNET, # Or MAINNET
|
|
31
|
+
api_key=os.environ.get("ALLORA_API_KEY"), # Optional
|
|
32
|
+
base_api_url=os.environ.get("ALLORA_API_URL"), # Optional
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Each topic is as follows:
|
|
36
|
+
#
|
|
37
|
+
# class AlloraTopic(BaseModel):
|
|
38
|
+
# topic_id: int
|
|
39
|
+
# topic_name: str
|
|
40
|
+
# description: Optional[str] = None
|
|
41
|
+
# epoch_length: int
|
|
42
|
+
# ground_truth_lag: int
|
|
43
|
+
# loss_method: str
|
|
44
|
+
# worker_submission_window: int
|
|
45
|
+
# worker_count: int
|
|
46
|
+
# reputer_count: int
|
|
47
|
+
# total_staked_allo: float
|
|
48
|
+
# total_emissions_allo: float
|
|
49
|
+
# is_active: Optional[bool] = None
|
|
50
|
+
# updated_at: str
|
|
51
|
+
topics = await client.get_all_topics()
|
|
52
|
+
|
|
53
|
+
# Each inference response is as follows:
|
|
54
|
+
#
|
|
55
|
+
# class AlloraInference(BaseModel):
|
|
56
|
+
# signature: str
|
|
57
|
+
# inference_data: AlloraInferenceData
|
|
58
|
+
#
|
|
59
|
+
# class AlloraInferenceData(BaseModel):
|
|
60
|
+
# network_inference: str
|
|
61
|
+
# network_inference_normalized: str
|
|
62
|
+
# confidence_interval_percentiles: List[str]
|
|
63
|
+
# confidence_interval_percentiles_normalized: List[str]
|
|
64
|
+
# confidence_interval_values: List[str]
|
|
65
|
+
# confidence_interval_values_normalized: List[str]
|
|
66
|
+
# topic_id: str
|
|
67
|
+
# timestamp: int
|
|
68
|
+
# extra_data: str
|
|
69
|
+
|
|
70
|
+
# Fetch inferences by topic ID
|
|
71
|
+
result = await client.get_inference_by_topic_id(topics[0].topic_id)
|
|
72
|
+
print(f'{topics[0].topic_name} price inference: {result.inference_data.network_inference_normalized}')
|
|
73
|
+
|
|
74
|
+
# Fetch inferences by asset and timeframe
|
|
75
|
+
result = await client.get_price_prediction(PricePredictionToken.BTC, PricePredictionTimeframe.EIGHT_HOURS)
|
|
76
|
+
print(f'{topics[0].topic_name} price inference: {result.inference_data.network_inference_normalized}')
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "allora_sdk"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
dependencies = [
|
|
5
|
+
"aiohttp",
|
|
6
|
+
"annotated-types==0.7.0",
|
|
7
|
+
"cachetools==5.5.0",
|
|
8
|
+
"certifi==2024.12.14",
|
|
9
|
+
"chardet==5.2.0",
|
|
10
|
+
"charset-normalizer==3.4.1",
|
|
11
|
+
"colorama==0.4.6",
|
|
12
|
+
"distlib==0.3.9",
|
|
13
|
+
"filelock==3.16.1",
|
|
14
|
+
"idna==3.10",
|
|
15
|
+
"packaging==24.2",
|
|
16
|
+
"platformdirs==4.3.6",
|
|
17
|
+
"pluggy==1.5.0",
|
|
18
|
+
"pydantic==2.10.4",
|
|
19
|
+
"pydantic_core==2.27.2",
|
|
20
|
+
"pyproject-api==1.8.0",
|
|
21
|
+
"requests==2.32.3",
|
|
22
|
+
"tox==4.23.2",
|
|
23
|
+
"typing_extensions==4.12.2",
|
|
24
|
+
"urllib3==2.3.0",
|
|
25
|
+
"virtualenv==20.28.1",
|
|
26
|
+
]
|
|
27
|
+
authors = [
|
|
28
|
+
{ name="spooktheducks", email="spooktheducks@protonmail.com" },
|
|
29
|
+
]
|
|
30
|
+
description = "Allora Network SDK"
|
|
31
|
+
readme = "README.md"
|
|
32
|
+
requires-python = ">=3.8"
|
|
33
|
+
classifiers = [
|
|
34
|
+
"Programming Language :: Python :: 3",
|
|
35
|
+
"License :: OSI Approved :: Apache Software License",
|
|
36
|
+
"Operating System :: OS Independent",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[project.optional-dependencies]
|
|
40
|
+
dev = [
|
|
41
|
+
"tox",
|
|
42
|
+
"pytest",
|
|
43
|
+
"pytest-asyncio",
|
|
44
|
+
"fastapi",
|
|
45
|
+
"starlette",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[project.urls]
|
|
49
|
+
Homepage = "https://github.com/allora-network/allora-sdk-py"
|
|
50
|
+
Issues = "https://github.com/allora-network/allora-sdk-py/issues"
|
|
51
|
+
"Allora Network" = "https://allora.network"
|
|
52
|
+
|
|
53
|
+
[build-system]
|
|
54
|
+
requires = ["hatchling"]
|
|
55
|
+
build-backend = "hatchling.build"
|
|
56
|
+
|
|
57
|
+
[tool.hatch.build.targets.wheel]
|
|
58
|
+
packages = ["src/allora_sdk"]
|
|
59
|
+
|
|
60
|
+
[tool.tox]
|
|
61
|
+
requires = ["tox>=4.19"]
|
|
62
|
+
env_list = ["lint", "type", "3.13", "3.12", "3.11", "3.10", "3.9", "3.8"]
|
|
63
|
+
|
|
64
|
+
[tool.tox.env_run_base]
|
|
65
|
+
description = "Run test under {base_python}"
|
|
66
|
+
deps = [
|
|
67
|
+
"pytest>=8",
|
|
68
|
+
"pytest-asyncio",
|
|
69
|
+
"pytest-sugar",
|
|
70
|
+
"fastapi",
|
|
71
|
+
"starlette",
|
|
72
|
+
"httpx",
|
|
73
|
+
]
|
|
74
|
+
commands = [["pytest", { replace = "posargs", default = ["tests"], extend = true }]]
|
|
75
|
+
|
|
76
|
+
[tool.tox.env.type]
|
|
77
|
+
description = "run type check on code base"
|
|
78
|
+
deps = ["mypy==1.11.2", "types-cachetools>=5.5.0.20240820", "types-chardet>=5.0.4.6"]
|
|
79
|
+
commands = [["mypy", { replace = "posargs", default = ["src", "tests"], extend = true} ]]
|
|
80
|
+
|
|
81
|
+
[tool.pytest.ini_options]
|
|
82
|
+
asyncio_mode = "auto"
|
|
83
|
+
markers = [
|
|
84
|
+
"asyncio: mark test as async test",
|
|
85
|
+
]
|
|
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
|
+
|
|
File without changes
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from typing import Dict, List, Any
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from fastapi import FastAPI, Request
|
|
4
|
+
from fastapi.responses import JSONResponse
|
|
5
|
+
from starlette.testclient import TestClient
|
|
6
|
+
from allora_sdk.v2.api_client import Fetcher
|
|
7
|
+
|
|
8
|
+
class MockServer:
|
|
9
|
+
def __init__(self):
|
|
10
|
+
self.app = FastAPI()
|
|
11
|
+
self.mock_responses: List[Any] = []
|
|
12
|
+
self.mock_status_codes: List[int] = []
|
|
13
|
+
|
|
14
|
+
self.app.add_api_route("/{path:path}", self.mock_endpoint, methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
15
|
+
|
|
16
|
+
def add_mock_response(self, response: Any, status_code: int = 200):
|
|
17
|
+
self.mock_responses.append(response)
|
|
18
|
+
self.mock_status_codes.append(status_code)
|
|
19
|
+
|
|
20
|
+
async def mock_endpoint(self, request: Request):
|
|
21
|
+
if self.mock_responses:
|
|
22
|
+
response = self.mock_responses.pop(0)
|
|
23
|
+
status_code = self.mock_status_codes.pop(0) if self.mock_status_codes else 200
|
|
24
|
+
return JSONResponse(content=response, status_code=status_code)
|
|
25
|
+
|
|
26
|
+
return JSONResponse(content={"error": "No mock response available", "status": False}, status_code=404)
|
|
27
|
+
|
|
28
|
+
# def run(self):
|
|
29
|
+
# uvicorn.run(self.app, host="localhost", port=self.port, log_level="error")
|
|
30
|
+
|
|
31
|
+
# def stop(self):
|
|
32
|
+
# raise NotImplementedError("Stopping the server programmatically requires custom signal handling.")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class StarletteMockFetcher(Fetcher):
|
|
36
|
+
def __init__(self, server: MockServer):
|
|
37
|
+
self.server = server
|
|
38
|
+
|
|
39
|
+
async def fetch(self, url: str, headers: dict) -> Any:
|
|
40
|
+
client = TestClient(self.server.app)
|
|
41
|
+
response = client.get(url, headers=headers)
|
|
42
|
+
return response.json()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
mock_topic_1: Dict[str, Any] = {
|
|
47
|
+
"topic_id": 1,
|
|
48
|
+
"topic_name": "Test Topic",
|
|
49
|
+
"description": "Test Description",
|
|
50
|
+
"epoch_length": 300,
|
|
51
|
+
"ground_truth_lag": 60,
|
|
52
|
+
"loss_method": "mse",
|
|
53
|
+
"worker_submission_window": 30,
|
|
54
|
+
"worker_count": 5,
|
|
55
|
+
"reputer_count": 3,
|
|
56
|
+
"total_staked_allo": 1000,
|
|
57
|
+
"total_emissions_allo": 100,
|
|
58
|
+
"is_active": True,
|
|
59
|
+
"updated_at": datetime(2024, 3, 20).isoformat() + "Z",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
mock_topic_2: Dict[str, Any] = {
|
|
63
|
+
"topic_id": 2,
|
|
64
|
+
"topic_name": "Test Topic",
|
|
65
|
+
"description": "Test Description",
|
|
66
|
+
"epoch_length": 300,
|
|
67
|
+
"ground_truth_lag": 60,
|
|
68
|
+
"loss_method": "mse",
|
|
69
|
+
"worker_submission_window": 30,
|
|
70
|
+
"worker_count": 5,
|
|
71
|
+
"reputer_count": 3,
|
|
72
|
+
"total_staked_allo": 1000,
|
|
73
|
+
"total_emissions_allo": 100,
|
|
74
|
+
"is_active": True,
|
|
75
|
+
"updated_at": datetime(2024, 3, 20).isoformat() + "Z",
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
mock_topics_response: Dict[str, Any] = {
|
|
79
|
+
"request_id": "test-request-id",
|
|
80
|
+
"status": True,
|
|
81
|
+
"data": {
|
|
82
|
+
"topics": [mock_topic_1, mock_topic_2],
|
|
83
|
+
"continuation_token": None,
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
mock_inference_data: Dict[str, Any] = {
|
|
88
|
+
"network_inference": "1000000000000000000",
|
|
89
|
+
"network_inference_normalized": "1.0",
|
|
90
|
+
"confidence_interval_percentiles": ["0.25", "0.75"],
|
|
91
|
+
"confidence_interval_percentiles_normalized": ["0.25", "0.75"],
|
|
92
|
+
"confidence_interval_values": ["900000000000000000", "1100000000000000000"],
|
|
93
|
+
"confidence_interval_values_normalized": ["0.9", "1.1"],
|
|
94
|
+
"topic_id": "1",
|
|
95
|
+
"timestamp": 1679529600,
|
|
96
|
+
"extra_data": "",
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
mock_inference: Dict[str, Any] = {
|
|
100
|
+
"signature": "0x1234567890",
|
|
101
|
+
"inference_data": mock_inference_data,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
mock_api_response: Dict[str, Any] = {
|
|
105
|
+
"request_id": "test-request-id",
|
|
106
|
+
"status": True,
|
|
107
|
+
"data": mock_inference,
|
|
108
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import pytest_asyncio
|
|
3
|
+
from allora_sdk.v2.api_client import (
|
|
4
|
+
AlloraAPIClient,
|
|
5
|
+
ChainSlug,
|
|
6
|
+
PricePredictionToken,
|
|
7
|
+
PricePredictionTimeframe,
|
|
8
|
+
AlloraTopic,
|
|
9
|
+
AlloraInference,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
DEFAULT_TEST_TIMEOUT = 30 # 30 seconds
|
|
13
|
+
|
|
14
|
+
@pytest_asyncio.fixture
|
|
15
|
+
def client():
|
|
16
|
+
return AlloraAPIClient(chain_slug=ChainSlug.TESTNET)
|
|
17
|
+
|
|
18
|
+
@pytest.mark.asyncio
|
|
19
|
+
async def test_get_all_topics(client):
|
|
20
|
+
topics = await client.get_all_topics()
|
|
21
|
+
|
|
22
|
+
assert isinstance(topics, list)
|
|
23
|
+
assert len(topics) > 0
|
|
24
|
+
|
|
25
|
+
topic = topics[0]
|
|
26
|
+
assert isinstance(topic, AlloraTopic)
|
|
27
|
+
assert isinstance(topic.topic_id, int)
|
|
28
|
+
assert isinstance(topic.topic_name, str)
|
|
29
|
+
assert topic.topic_name, "Topic name should not be empty"
|
|
30
|
+
|
|
31
|
+
assert isinstance(topic.epoch_length, int)
|
|
32
|
+
assert isinstance(topic.ground_truth_lag, int)
|
|
33
|
+
assert isinstance(topic.worker_submission_window, int)
|
|
34
|
+
assert isinstance(topic.worker_count, int)
|
|
35
|
+
assert isinstance(topic.reputer_count, int)
|
|
36
|
+
assert isinstance(topic.total_staked_allo, float)
|
|
37
|
+
assert isinstance(topic.total_emissions_allo, float)
|
|
38
|
+
|
|
39
|
+
assert isinstance(topic.is_active, bool)
|
|
40
|
+
if topic.description is not None:
|
|
41
|
+
assert isinstance(topic.description, str)
|
|
42
|
+
|
|
43
|
+
@pytest.mark.asyncio
|
|
44
|
+
async def test_get_inference_by_topic_id(client):
|
|
45
|
+
topics = await client.get_all_topics()
|
|
46
|
+
if not topics:
|
|
47
|
+
pytest.skip("No topics available for testing")
|
|
48
|
+
|
|
49
|
+
inference = await client.get_inference_by_topic_id(topics[0].topic_id)
|
|
50
|
+
|
|
51
|
+
assert isinstance(inference, AlloraInference)
|
|
52
|
+
assert isinstance(inference.signature, str)
|
|
53
|
+
assert inference.signature, "Signature should not be empty"
|
|
54
|
+
|
|
55
|
+
data = inference.inference_data
|
|
56
|
+
assert isinstance(data.network_inference, str)
|
|
57
|
+
assert isinstance(data.network_inference_normalized, str)
|
|
58
|
+
assert isinstance(data.topic_id, str)
|
|
59
|
+
assert isinstance(data.timestamp, int)
|
|
60
|
+
|
|
61
|
+
assert isinstance(data.confidence_interval_percentiles, list)
|
|
62
|
+
assert isinstance(data.confidence_interval_values, list)
|
|
63
|
+
assert len(data.confidence_interval_percentiles) == len(data.confidence_interval_values)
|
|
64
|
+
|
|
65
|
+
@pytest.mark.asyncio
|
|
66
|
+
async def test_get_price_prediction(client):
|
|
67
|
+
prediction = await client.get_price_prediction(
|
|
68
|
+
PricePredictionToken.BTC,
|
|
69
|
+
PricePredictionTimeframe.EIGHT_HOURS
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
assert isinstance(prediction, AlloraInference)
|
|
73
|
+
assert isinstance(prediction.signature, str)
|
|
74
|
+
assert prediction.signature, "Signature should not be empty"
|
|
75
|
+
|
|
76
|
+
data = prediction.inference_data
|
|
77
|
+
assert isinstance(data.network_inference, str)
|
|
78
|
+
assert isinstance(data.network_inference_normalized, str)
|
|
79
|
+
assert isinstance(data.topic_id, str)
|
|
80
|
+
assert isinstance(data.timestamp, int)
|
|
81
|
+
|
|
82
|
+
assert isinstance(data.confidence_interval_percentiles, list)
|
|
83
|
+
assert all(isinstance(p, str) for p in data.confidence_interval_percentiles)
|
|
84
|
+
assert isinstance(data.confidence_interval_values, list)
|
|
85
|
+
assert all(isinstance(v, str) for v in data.confidence_interval_values)
|
|
86
|
+
|
|
87
|
+
assert isinstance(data.confidence_interval_percentiles_normalized, list)
|
|
88
|
+
assert isinstance(data.confidence_interval_values_normalized, list)
|
|
89
|
+
assert len(data.confidence_interval_percentiles) == len(data.confidence_interval_values)
|
|
90
|
+
|
|
91
|
+
@pytest.mark.asyncio
|
|
92
|
+
async def test_get_price_prediction_different_assets(client):
|
|
93
|
+
for token in [PricePredictionToken.BTC, PricePredictionToken.ETH]:
|
|
94
|
+
for timeframe in [PricePredictionTimeframe.FIVE_MIN, PricePredictionTimeframe.EIGHT_HOURS]:
|
|
95
|
+
prediction = await client.get_price_prediction(token, timeframe)
|
|
96
|
+
assert isinstance(prediction, AlloraInference)
|
|
97
|
+
assert prediction.inference_data.network_inference.isdigit()
|
|
98
|
+
assert float(prediction.inference_data.network_inference_normalized) > 0
|
|
99
|
+
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import pytest_asyncio
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
import json
|
|
5
|
+
from unittest.mock import MagicMock, patch
|
|
6
|
+
from aiohttp import ClientResponse, ClientSession
|
|
7
|
+
|
|
8
|
+
from allora_sdk.v2.api_client import (
|
|
9
|
+
AlloraAPIClient,
|
|
10
|
+
ChainSlug,
|
|
11
|
+
PricePredictionToken,
|
|
12
|
+
PricePredictionTimeframe,
|
|
13
|
+
SignatureFormat,
|
|
14
|
+
ChainID,
|
|
15
|
+
Fetcher,
|
|
16
|
+
)
|
|
17
|
+
from .mock_data import (
|
|
18
|
+
MockServer,
|
|
19
|
+
StarletteMockFetcher,
|
|
20
|
+
mock_topics_response,
|
|
21
|
+
mock_inference,
|
|
22
|
+
mock_api_response,
|
|
23
|
+
mock_topic_1,
|
|
24
|
+
mock_topic_2,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
server = MockServer()
|
|
28
|
+
fetcher = StarletteMockFetcher(server)
|
|
29
|
+
|
|
30
|
+
@pytest.mark.asyncio
|
|
31
|
+
async def test_get_all_topics_with_pagination():
|
|
32
|
+
# # Prepare paginated responses
|
|
33
|
+
first_response = {
|
|
34
|
+
"status": True,
|
|
35
|
+
"request_id": "test",
|
|
36
|
+
"data": {
|
|
37
|
+
"topics": [mock_topic_1],
|
|
38
|
+
"continuation_token": "next-page"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
second_response = {
|
|
42
|
+
"status": True,
|
|
43
|
+
"request_id": "test",
|
|
44
|
+
"data": {
|
|
45
|
+
"topics": [mock_topic_2],
|
|
46
|
+
"continuation_token": None
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
server.add_mock_response(first_response, 200)
|
|
51
|
+
server.add_mock_response(second_response, 200)
|
|
52
|
+
client = AlloraAPIClient(fetcher=fetcher)
|
|
53
|
+
topics = await client.get_all_topics()
|
|
54
|
+
|
|
55
|
+
assert len(topics) == 2
|
|
56
|
+
assert topics[0].topic_id == 1
|
|
57
|
+
assert topics[1].topic_id == 2
|
|
58
|
+
|
|
59
|
+
@pytest.mark.asyncio
|
|
60
|
+
async def test_get_inference_by_topic_id():
|
|
61
|
+
server.add_mock_response(mock_api_response, 200)
|
|
62
|
+
client = AlloraAPIClient(fetcher=fetcher)
|
|
63
|
+
topic_id = 1
|
|
64
|
+
inference = await client.get_inference_by_topic_id(topic_id, SignatureFormat.ETHEREUM_SEPOLIA)
|
|
65
|
+
|
|
66
|
+
assert inference.inference_data.network_inference == mock_inference["inference_data"]["network_inference"]
|
|
67
|
+
assert inference.inference_data.network_inference_normalized == mock_inference["inference_data"]["network_inference_normalized"]
|
|
68
|
+
|
|
69
|
+
@pytest.mark.asyncio
|
|
70
|
+
async def test_get_price_prediction():
|
|
71
|
+
server.add_mock_response(mock_api_response, 200)
|
|
72
|
+
client = AlloraAPIClient(fetcher=fetcher)
|
|
73
|
+
prediction = await client.get_price_prediction(PricePredictionToken.BTC, PricePredictionTimeframe.FIVE_MIN)
|
|
74
|
+
|
|
75
|
+
assert prediction.inference_data.network_inference == mock_inference["inference_data"]["network_inference"]
|
|
76
|
+
assert prediction.inference_data.network_inference_normalized == mock_inference["inference_data"]["network_inference_normalized"]
|
|
77
|
+
|
|
78
|
+
@pytest.mark.asyncio
|
|
79
|
+
async def test_get_price_prediction_missing_inference_data():
|
|
80
|
+
mock_response = {**mock_api_response, "data": {"signature": "0x1234"}}
|
|
81
|
+
server.add_mock_response(mock_response, 200)
|
|
82
|
+
client = AlloraAPIClient(fetcher=fetcher)
|
|
83
|
+
with pytest.raises(ValueError, match="validation error"):
|
|
84
|
+
await client.get_price_prediction(
|
|
85
|
+
PricePredictionToken.BTC,
|
|
86
|
+
PricePredictionTimeframe.FIVE_MIN,
|
|
87
|
+
)
|
|
88
|
+
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
requires = ["tox>=4"]
|
|
2
|
+
env_list = ["lint", "type", "3.13", "3.12", "3.11", "3.10", "3.9", "3.8"]
|
|
3
|
+
|
|
4
|
+
[env_run_base]
|
|
5
|
+
description = "run unit tests"
|
|
6
|
+
deps = [
|
|
7
|
+
"pytest>=8",
|
|
8
|
+
"pytest-asyncio",
|
|
9
|
+
"pytest-sugar",
|
|
10
|
+
"fastapi",
|
|
11
|
+
"starlette",
|
|
12
|
+
"httpx",
|
|
13
|
+
"-r{toxinidir}/pyproject.toml"
|
|
14
|
+
]
|
|
15
|
+
commands = "pytest" #[["pytest", { replace = "posargs", default = ["tests"], extend = true }]]
|
|
16
|
+
|
|
17
|
+
[env.lint]
|
|
18
|
+
description = "run linters"
|
|
19
|
+
skip_install = true
|
|
20
|
+
deps = ["black"]
|
|
21
|
+
commands = [["black", { replace = "posargs", default = ["."], extend = true} ]]
|
|
22
|
+
|
|
23
|
+
[env.type]
|
|
24
|
+
description = "run type checks"
|
|
25
|
+
deps = ["mypy"]
|
|
26
|
+
commands = [["mypy", { replace = "posargs", default = ["src", "tests"], extend = true} ]]
|