-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathclient.py
More file actions
178 lines (148 loc) · 6.48 KB
/
client.py
File metadata and controls
178 lines (148 loc) · 6.48 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import logging
from typing import Dict, List, Optional
import requests
from models import SwapQuote
logger = logging.getLogger(__name__)
WELL_KNOWN_ASSETS = {
"XOR": "0x0200000000000000000000000000000000000000000000000000000000000000",
"VAL": "0x0200040000000000000000000000000000000000000000000000000000000000",
"PSWAP": "0x0200050000000000000000000000000000000000000000000000000000000000",
"DAI": "0x0200060000000000000000000000000000000000000000000000000000000000",
"ETH": "0x0200070000000000000000000000000000000000000000000000000000000000",
"XSTUSD": "0x0200080000000000000000000000000000000000000000000000000000000000",
}
class SoraClient:
"""Client for the SORA v2 decentralized economy platform API.
Provides methods for querying account balances, obtaining swap
quotes through the Polkaswap DEX, listing liquidity pools,
and fetching network-level information.
"""
def __init__(self, config: dict) -> None:
self.api_url = config.get("api_url", "").rstrip("/")
self.dex_id = config.get("default_dex_id", 0)
self.timeout = config.get("timeout", 30)
self._session = requests.Session()
self._session.headers.update({
"Accept": "application/json",
"Content-Type": "application/json",
})
def _resolve_asset_id(self, asset: str) -> str:
return WELL_KNOWN_ASSETS.get(asset.upper(), asset)
def _get(self, path: str, params: dict = None) -> Optional[dict]:
url = f"{self.api_url}{path}"
try:
resp = self._session.get(url, params=params, timeout=self.timeout)
resp.raise_for_status()
return resp.json()
except requests.RequestException as exc:
logger.error("GET %s failed: %s", path, exc)
return None
def _post(self, path: str, payload: dict = None) -> Optional[dict]:
url = f"{self.api_url}{path}"
try:
resp = self._session.post(url, json=payload or {}, timeout=self.timeout)
resp.raise_for_status()
return resp.json()
except requests.RequestException as exc:
logger.error("POST %s failed: %s", path, exc)
return None
def get_balances(self, address: str) -> List[Dict[str, str]]:
data = self._get(f"/accounts/{address}/balances")
if data is None:
return []
results = []
for item in data if isinstance(data, list) else data.get("balances", []):
asset_id = item.get("assetId", "")
symbol = item.get("symbol", "")
name = item.get("name", symbol)
balance = item.get("balance", item.get("free", "0"))
if not symbol:
for sym, aid in WELL_KNOWN_ASSETS.items():
if aid == asset_id:
symbol = sym
break
results.append({
"asset_id": asset_id,
"symbol": symbol or asset_id[:10],
"name": name or symbol,
"balance": str(balance),
})
return results
def get_swap_quote(
self,
input_asset: str,
output_asset: str,
amount: str,
slippage: float = 0.5,
) -> Optional[SwapQuote]:
input_id = self._resolve_asset_id(input_asset)
output_id = self._resolve_asset_id(output_asset)
data = self._get("/dex/quote", params={
"dexId": self.dex_id,
"inputAssetId": input_id,
"outputAssetId": output_id,
"amount": amount,
"swapVariant": "WithDesiredInput",
"selectedSourceTypes": "XYKPool,MulticollateralBondingCurvePool",
})
if data is None:
return None
return SwapQuote(
input_asset=input_asset.upper(),
output_asset=output_asset.upper(),
amount_in=amount,
amount_out=data.get("amount", "0"),
price_impact=data.get("priceImpact", "0"),
fee=data.get("fee", "0"),
route=data.get("route", [input_asset.upper(), output_asset.upper()]),
)
def execute_swap(
self,
input_asset: str,
output_asset: str,
amount: str,
slippage: float = 0.5,
) -> str:
input_id = self._resolve_asset_id(input_asset)
output_id = self._resolve_asset_id(output_asset)
result = self._post("/dex/swap", payload={
"dexId": self.dex_id,
"inputAssetId": input_id,
"outputAssetId": output_id,
"amount": amount,
"slippageTolerance": slippage,
"swapVariant": "WithDesiredInput",
"selectedSourceTypes": ["XYKPool", "MulticollateralBondingCurvePool"],
})
if result is None:
raise RuntimeError("Swap request failed")
return result.get("txHash", result.get("hash", str(result)))
def get_pools(self) -> List[Dict[str, str]]:
data = self._get("/dex/pools", params={"dexId": self.dex_id})
if data is None:
return []
results = []
for pool in data if isinstance(data, list) else data.get("pools", []):
base_sym = pool.get("baseAssetSymbol", pool.get("baseAssetId", "?")[:10])
target_sym = pool.get("targetAssetSymbol", pool.get("targetAssetId", "?")[:10])
results.append({
"pair": f"{base_sym}/{target_sym}",
"base_reserve": str(pool.get("baseAssetReserves", "0")),
"target_reserve": str(pool.get("targetAssetReserves", "0")),
"total_liquidity": str(pool.get("totalLiquidity", "0")),
})
return results
def get_network_info(self) -> Dict[str, str]:
data = self._get("/network/info")
if data is None:
return {"status": "unavailable"}
return {
"Network": data.get("name", "SORA"),
"Chain": data.get("chain", "N/A"),
"Node Version": data.get("nodeVersion", "N/A"),
"Spec Version": str(data.get("specVersion", "N/A")),
"Block Height": str(data.get("blockHeight", "N/A")),
"Finalized Block": str(data.get("finalizedBlock", "N/A")),
"Peer Count": str(data.get("peerCount", "N/A")),
"Total Issuance (XOR)": data.get("totalIssuance", "N/A"),
}