feat: agregar endpoint /v2/rates con soporte multi-pais
Browse filesEndpoint nuevo GET /v2/rates?country=XX que devuelve seccion Venezuela
(BCV + P2P/VES) + seccion local opcional con USDT en el fiat del pais.
Aislamiento total respecto a /v1: ninguna funcion ni handler existente
se modifica. Se agregan fetch_p2p_v2, fetch_p2p_v2_safe, validate_country
y SUPPORTED_COUNTRIES (15 paises). Cache namespace separado (p2p_v2:fiat)
para garantizar cero regresion en clientes legacy.
- DESIGN_TAZAS_WORLDWIDE.md +453 -0
- NOTAS_DEV.md +120 -0
- main.py +146 -0
DESIGN_TAZAS_WORLDWIDE.md
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DiseΓ±o tΓ©cnico β Backend Tazas API (cambio tazas-worldwide)
|
| 2 |
+
|
| 3 |
+
> Asume conocimiento del `proposal` y `spec` del cambio `tazas-worldwide`.
|
| 4 |
+
> Persistidos en Engram con topic_keys `sdd/tazas-worldwide/proposal` y `sdd/tazas-worldwide/spec` (project `widget_test`).
|
| 5 |
+
> Este documento cubre **ΓΊnicamente** el backend (`C:\dev\Tazas_API\main.py`).
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## Objetivo del backend
|
| 10 |
+
|
| 11 |
+
Agregar el endpoint `GET /v2/rates?country={cc}` que devuelve, en un solo response, la secciΓ³n Venezuela completa (BCV + P2P/VES β sin cambios respecto a hoy) y, opcionalmente, una secciΓ³n `local` con USDT en el fiat del paΓs solicitado.
|
| 12 |
+
|
| 13 |
+
`/v1/rates`, `/v1/bcv` y `/v1/p2p` quedan intactos para los clientes ya instalados.
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## 1. CatΓ‘logo de paΓses soportados
|
| 18 |
+
|
| 19 |
+
Constante hardcoded en `main.py`. Mapea cΓ³digo ISO 3166-1 alpha-2 β fiat ISO 4217 para Binance P2P.
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
SUPPORTED_COUNTRIES: dict[str, str] = {
|
| 23 |
+
"AR": "ARS", # Argentina β peso argentino
|
| 24 |
+
"BO": "BOB", # Bolivia β boliviano
|
| 25 |
+
"CL": "CLP", # Chile β peso chileno
|
| 26 |
+
"CO": "COP", # Colombia β peso colombiano
|
| 27 |
+
"CR": "CRC", # Costa Rica β colΓ³n
|
| 28 |
+
"DO": "DOP", # RepΓΊblica Dominicana β peso dominicano
|
| 29 |
+
"GT": "GTQ", # Guatemala β quetzal
|
| 30 |
+
"HN": "HNL", # Honduras β lempira
|
| 31 |
+
"MX": "MXN", # MΓ©xico β peso mexicano
|
| 32 |
+
"NI": "NIO", # Nicaragua β cΓ³rdoba
|
| 33 |
+
"PY": "PYG", # Paraguay β guaranΓ
|
| 34 |
+
"PE": "PEN", # PerΓΊ β sol
|
| 35 |
+
"UY": "UYU", # Uruguay β peso uruguayo
|
| 36 |
+
"VE": "VES", # Venezuela β bolΓvar (caso especial: local = null)
|
| 37 |
+
"ES": "EUR", # EspaΓ±a β euro
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
ValidaciΓ³n: cualquier cΓ³digo no presente en este diccionario devuelve `400`.
|
| 42 |
+
|
| 43 |
+
---
|
| 44 |
+
|
| 45 |
+
## 2. Contrato del endpoint `/v2/rates`
|
| 46 |
+
|
| 47 |
+
### 2.1 Request
|
| 48 |
+
|
| 49 |
+
```
|
| 50 |
+
GET /v2/rates?country=AR HTTP/1.1
|
| 51 |
+
Host: andervier-tazas-api.hf.space
|
| 52 |
+
X-Firebase-AppCheck: <token>
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
ParΓ‘metros obligatorios:
|
| 56 |
+
- `country` (query string, string, mayΓΊsculas, exactamente 2 caracteres, debe estar en `SUPPORTED_COUNTRIES`).
|
| 57 |
+
|
| 58 |
+
### 2.2 Response 200 β paΓs distinto de Venezuela
|
| 59 |
+
|
| 60 |
+
```json
|
| 61 |
+
{
|
| 62 |
+
"venezuela": {
|
| 63 |
+
"bcvUsd": 36.85,
|
| 64 |
+
"bcvEur": 41.20,
|
| 65 |
+
"bcvCny": 5.12,
|
| 66 |
+
"bcvTry": 1.10,
|
| 67 |
+
"bcvRub": 0.42,
|
| 68 |
+
"p2pBuyMax": 44.10,
|
| 69 |
+
"p2pSellMax": 44.80,
|
| 70 |
+
"updatedAt": "27/05/2026"
|
| 71 |
+
},
|
| 72 |
+
"local": {
|
| 73 |
+
"countryCode": "AR",
|
| 74 |
+
"currency": "ARS",
|
| 75 |
+
"usdtBuy": 1190.50,
|
| 76 |
+
"usdtSell": 1210.75,
|
| 77 |
+
"updatedAt": null
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Notas:
|
| 83 |
+
- `venezuela.updatedAt` es el string parseado del BCV (formato propio del BCV, mismo que hoy).
|
| 84 |
+
- `local.updatedAt` queda en `null` en esta iteraciΓ³n (Binance P2P no devuelve timestamp utilizable). Reservado para futuro.
|
| 85 |
+
|
| 86 |
+
### 2.3 Response 200 β paΓs igual a Venezuela
|
| 87 |
+
|
| 88 |
+
```json
|
| 89 |
+
{
|
| 90 |
+
"venezuela": {
|
| 91 |
+
"bcvUsd": 36.85,
|
| 92 |
+
"bcvEur": 41.20,
|
| 93 |
+
"bcvCny": 5.12,
|
| 94 |
+
"bcvTry": 1.10,
|
| 95 |
+
"bcvRub": 0.42,
|
| 96 |
+
"p2pBuyMax": 44.10,
|
| 97 |
+
"p2pSellMax": 44.80,
|
| 98 |
+
"updatedAt": "27/05/2026"
|
| 99 |
+
},
|
| 100 |
+
"local": null
|
| 101 |
+
}
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
### 2.4 Response 200 β fallo parcial en el P2P local
|
| 105 |
+
|
| 106 |
+
Si Binance falla solo para el fiat local pero Venezuela responde correctamente:
|
| 107 |
+
|
| 108 |
+
```json
|
| 109 |
+
{
|
| 110 |
+
"venezuela": { "...": "...poblado normalmente..." },
|
| 111 |
+
"local": {
|
| 112 |
+
"countryCode": "PY",
|
| 113 |
+
"currency": "PYG",
|
| 114 |
+
"usdtBuy": null,
|
| 115 |
+
"usdtSell": null,
|
| 116 |
+
"updatedAt": null
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
El status sigue siendo `200`. El cliente decide cΓ³mo renderizar valores `null` (mostrar "β").
|
| 122 |
+
|
| 123 |
+
### 2.5 Responses de error
|
| 124 |
+
|
| 125 |
+
**400 β parΓ‘metro ausente:**
|
| 126 |
+
```json
|
| 127 |
+
{
|
| 128 |
+
"detail": "Query param 'country' es requerido"
|
| 129 |
+
}
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
**400 β paΓs no soportado:**
|
| 133 |
+
```json
|
| 134 |
+
{
|
| 135 |
+
"detail": "PaΓs 'US' no estΓ‘ soportado en esta versiΓ³n"
|
| 136 |
+
}
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
**400 β formato invΓ‘lido:**
|
| 140 |
+
```json
|
| 141 |
+
{
|
| 142 |
+
"detail": "CΓ³digo de paΓs debe ser ISO 3166-1 alpha-2 (2 letras mayΓΊsculas)"
|
| 143 |
+
}
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
**401 β App Check ausente o invΓ‘lido:**
|
| 147 |
+
```json
|
| 148 |
+
{
|
| 149 |
+
"detail": "Token App Check requerido"
|
| 150 |
+
}
|
| 151 |
+
```
|
| 152 |
+
(Igual al comportamiento actual de `/v1`.)
|
| 153 |
+
|
| 154 |
+
---
|
| 155 |
+
|
| 156 |
+
## 3. DiseΓ±o del cache
|
| 157 |
+
|
| 158 |
+
### 3.1 Estructura
|
| 159 |
+
|
| 160 |
+
Reutilizar el `_cache: dict` y `_locks: dict[str, asyncio.Lock]` existentes. **No introducir Redis ni infra externa.**
|
| 161 |
+
|
| 162 |
+
### 3.2 ConvenciΓ³n de keys
|
| 163 |
+
|
| 164 |
+
| Recurso | Key | TTL |
|
| 165 |
+
|---------|-----|-----|
|
| 166 |
+
| BCV (scraping) | `"bcv"` | 4 h (sin cambio) |
|
| 167 |
+
| P2P por fiat | `f"p2p:{fiat}"` (e.g. `"p2p:VES"`, `"p2p:ARS"`, `"p2p:EUR"`) | 2 min |
|
| 168 |
+
|
| 169 |
+
Una key por fiat. Cada paΓs consultado por primera vez crea su propia entrada de cache. La key `"p2p"` actual (sin sufijo) **desaparece** despuΓ©s del refactor β la sustituye `"p2p:VES"`.
|
| 170 |
+
|
| 171 |
+
### 3.3 Locks
|
| 172 |
+
|
| 173 |
+
Un lock por key. Si llegan N requests simultΓ‘neos al mismo `(fiat)` y el cache estΓ‘ expirado, solo uno hace el fetch a Binance β los demΓ‘s esperan y consumen el resultado cacheado (patrΓ³n actual, sin cambios estructurales).
|
| 174 |
+
|
| 175 |
+
### 3.4 Capacidad
|
| 176 |
+
|
| 177 |
+
Con 15 paΓses Γ 1 entrada P2P + 1 entrada BCV = 16 entradas mΓ‘ximo. No es necesaria polΓtica de evicciΓ³n.
|
| 178 |
+
|
| 179 |
+
---
|
| 180 |
+
|
| 181 |
+
## 4. Refactor de `fetch_p2p()`
|
| 182 |
+
|
| 183 |
+
### 4.1 Signature
|
| 184 |
+
|
| 185 |
+
```python
|
| 186 |
+
# Antes
|
| 187 |
+
async def fetch_p2p() -> dict: ...
|
| 188 |
+
|
| 189 |
+
# DespuΓ©s
|
| 190 |
+
async def fetch_p2p(fiat: str) -> dict: ...
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
### 4.2 LΓ³gica
|
| 194 |
+
|
| 195 |
+
```python
|
| 196 |
+
async def fetch_p2p(fiat: str) -> dict:
|
| 197 |
+
cache_key = f"p2p:{fiat}"
|
| 198 |
+
cached = _cached(cache_key, P2P_TTL)
|
| 199 |
+
if cached:
|
| 200 |
+
return cached
|
| 201 |
+
|
| 202 |
+
async with _lock(cache_key):
|
| 203 |
+
# Double-check post-lock
|
| 204 |
+
cached = _cached(cache_key, P2P_TTL)
|
| 205 |
+
if cached:
|
| 206 |
+
return cached
|
| 207 |
+
|
| 208 |
+
headers = {
|
| 209 |
+
"User-Agent": "Mozilla/5.0",
|
| 210 |
+
"Content-Type": "application/json",
|
| 211 |
+
}
|
| 212 |
+
body_base = {
|
| 213 |
+
"fiat": fiat, # β parametrizado
|
| 214 |
+
"page": 1,
|
| 215 |
+
"rows": 20,
|
| 216 |
+
"asset": "USDT",
|
| 217 |
+
"countries": [],
|
| 218 |
+
"proMerchantAds": False,
|
| 219 |
+
"shieldMerchantAds": False,
|
| 220 |
+
"publisherType": None,
|
| 221 |
+
"payTypes": [],
|
| 222 |
+
"classifies": ["mass", "profession"],
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
buy_ads_res, sell_ads_res = await asyncio.gather(
|
| 226 |
+
_http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "BUY"}, headers=headers),
|
| 227 |
+
_http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "SELL"}, headers=headers),
|
| 228 |
+
)
|
| 229 |
+
buy_ads_res.raise_for_status()
|
| 230 |
+
sell_ads_res.raise_for_status()
|
| 231 |
+
|
| 232 |
+
# first_eligible_price() sin cambios (lΓ³gica de saltar ads 0-2 y promediar 3-5)
|
| 233 |
+
p2p_buy = first_eligible_price(sell_ads_res.json().get("data", []))
|
| 234 |
+
p2p_sell = first_eligible_price(buy_ads_res.json().get("data", []))
|
| 235 |
+
|
| 236 |
+
data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
|
| 237 |
+
_store(cache_key, data)
|
| 238 |
+
return data
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
`first_eligible_price()` queda sin tocar β opera igual sobre cualquier fiat.
|
| 242 |
+
|
| 243 |
+
### 4.3 Wrapper de tolerancia (renombrar)
|
| 244 |
+
|
| 245 |
+
```python
|
| 246 |
+
async def fetch_p2p_safe(fiat: str) -> dict:
|
| 247 |
+
try:
|
| 248 |
+
return await fetch_p2p(fiat)
|
| 249 |
+
except Exception as e:
|
| 250 |
+
logger.error("fetch_p2p(%s) failed: %s", fiat, e, exc_info=True)
|
| 251 |
+
return {"p2pBuyMax": None, "p2pSellMax": None}
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
### 4.4 Compatibilidad con `/v1`
|
| 255 |
+
|
| 256 |
+
Los handlers `/v1/rates` y `/v1/p2p` se actualizan para llamar `fetch_p2p_safe("VES")` y `fetch_p2p("VES")` respectivamente. **El response del `/v1` NO cambia**, solo el call interno.
|
| 257 |
+
|
| 258 |
+
---
|
| 259 |
+
|
| 260 |
+
## 5. Handler `/v2/rates`
|
| 261 |
+
|
| 262 |
+
### 5.1 ValidaciΓ³n
|
| 263 |
+
|
| 264 |
+
```python
|
| 265 |
+
COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$")
|
| 266 |
+
|
| 267 |
+
def validate_country(country: str | None) -> str:
|
| 268 |
+
if not country:
|
| 269 |
+
raise HTTPException(400, "Query param 'country' es requerido")
|
| 270 |
+
if not COUNTRY_CODE_PATTERN.match(country):
|
| 271 |
+
raise HTTPException(400, "CΓ³digo de paΓs debe ser ISO 3166-1 alpha-2 (2 letras mayΓΊsculas)")
|
| 272 |
+
if country not in SUPPORTED_COUNTRIES:
|
| 273 |
+
raise HTTPException(400, f"PaΓs '{country}' no estΓ‘ soportado en esta versiΓ³n")
|
| 274 |
+
return country
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
### 5.2 Handler
|
| 278 |
+
|
| 279 |
+
```python
|
| 280 |
+
@app.get("/v2/rates", dependencies=[Depends(verify_app_check)])
|
| 281 |
+
async def rates_v2(country: str | None = None):
|
| 282 |
+
cc = validate_country(country)
|
| 283 |
+
fiat = SUPPORTED_COUNTRIES[cc]
|
| 284 |
+
|
| 285 |
+
if cc == "VE":
|
| 286 |
+
# Caso especial: local = null, no duplicar fetch P2P/VES
|
| 287 |
+
bcv_data, ve_p2p = await asyncio.gather(
|
| 288 |
+
fetch_bcv(),
|
| 289 |
+
fetch_p2p_safe("VES"),
|
| 290 |
+
)
|
| 291 |
+
return {
|
| 292 |
+
"venezuela": {**bcv_data, **ve_p2p},
|
| 293 |
+
"local": None,
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
# Caso normal: 3 fetches en paralelo (BCV + P2P/VES + P2P/<fiat>)
|
| 297 |
+
bcv_data, ve_p2p, local_p2p = await asyncio.gather(
|
| 298 |
+
fetch_bcv(),
|
| 299 |
+
fetch_p2p_safe("VES"),
|
| 300 |
+
fetch_p2p_safe(fiat),
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
return {
|
| 304 |
+
"venezuela": {**bcv_data, **ve_p2p},
|
| 305 |
+
"local": {
|
| 306 |
+
"countryCode": cc,
|
| 307 |
+
"currency": fiat,
|
| 308 |
+
"usdtBuy": local_p2p.get("p2pBuyMax"),
|
| 309 |
+
"usdtSell": local_p2p.get("p2pSellMax"),
|
| 310 |
+
"updatedAt": None, # reservado
|
| 311 |
+
},
|
| 312 |
+
}
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
### 5.3 Por quΓ© `fetch_p2p_safe` (no `fetch_p2p`) para `local`
|
| 316 |
+
|
| 317 |
+
El requisito de spec dice que si el fiat local falla, `venezuela` debe seguir respondiendo. Usar la versiΓ³n `_safe` (que captura excepciones y devuelve `null`) cumple eso sin try/except en el handler.
|
| 318 |
+
|
| 319 |
+
Para `venezuela.p2p` tambiΓ©n se usa `_safe` (igual que hoy en `/v1/rates`) β coherente con la polΓtica actual de no tumbar el response por un fallo de P2P.
|
| 320 |
+
|
| 321 |
+
---
|
| 322 |
+
|
| 323 |
+
## 6. Estrategia de tolerancia a fallos parciales
|
| 324 |
+
|
| 325 |
+
| Caso | Comportamiento |
|
| 326 |
+
|------|----------------|
|
| 327 |
+
| BCV scraping cae | `fetch_bcv()` lanza `HTTPException 503` (comportamiento actual). Para mantener consistencia con `/v1`, el handler `/v2` propaga el 503. Es aceptable: si BCV cae, no hay nada ΓΊtil que mostrar para Venezuela. |
|
| 328 |
+
| P2P/VES cae pero BCV OK | `venezuela.p2pBuyMax = null`, resto poblado. Status 200. |
|
| 329 |
+
| P2P/local cae pero VE OK | `local.usdtBuy = null`, `local.usdtSell = null`, `venezuela` poblado. Status 200. |
|
| 330 |
+
| Binance entero cae | `venezuela.p2p* = null`, `local.usdt* = null`, BCV poblado. Status 200. |
|
| 331 |
+
| PaΓs no soportado | Status 400 sin tocar Binance. |
|
| 332 |
+
|
| 333 |
+
DecisiΓ³n: el **ΓΊnico** error 5xx que `/v2/rates` puede devolver es el del BCV scraping (heredado de `fetch_bcv`). Todo lo demΓ‘s se degrada gracefully a campos `null`.
|
| 334 |
+
|
| 335 |
+
---
|
| 336 |
+
|
| 337 |
+
## 7. Cambios a aplicar en `main.py`
|
| 338 |
+
|
| 339 |
+
| Cambio | AcciΓ³n |
|
| 340 |
+
|--------|--------|
|
| 341 |
+
| Constante `SUPPORTED_COUNTRIES` | Agregar (secciΓ³n de configuraciΓ³n) |
|
| 342 |
+
| Constante `BINANCE_P2P_URL` | Extraer la URL hardcoded a constante |
|
| 343 |
+
| Constante `COUNTRY_CODE_PATTERN` | Agregar (regex compilada) |
|
| 344 |
+
| `fetch_p2p()` | Modificar: aceptar `fiat: str`, cambiar cache key a `f"p2p:{fiat}"`, parametrizar body |
|
| 345 |
+
| `fetch_p2p_safe()` | Modificar: aceptar `fiat: str` y pasarlo a `fetch_p2p` |
|
| 346 |
+
| `validate_country()` | Agregar |
|
| 347 |
+
| `rates_v2()` handler | Agregar |
|
| 348 |
+
| `/v1/rates`, `/v1/p2p`, `/v1/p2p/debug` | Modificar: pasar `"VES"` explΓcito al llamar `fetch_p2p*` |
|
| 349 |
+
| Logger | Agregar log INFO al inicio de cada fetch P2P con el fiat (ΓΊtil para diagnosticar trΓ‘fico por paΓs) |
|
| 350 |
+
|
| 351 |
+
### Snippet del `/v1` actualizado (sin romper contrato)
|
| 352 |
+
|
| 353 |
+
```python
|
| 354 |
+
@app.get("/v1/rates", dependencies=[Depends(verify_app_check)])
|
| 355 |
+
async def rates_v1():
|
| 356 |
+
bcv_data, p2p_data = await asyncio.gather(
|
| 357 |
+
fetch_bcv(),
|
| 358 |
+
fetch_p2p_safe("VES"), # β ΓΊnico cambio
|
| 359 |
+
)
|
| 360 |
+
return {**bcv_data, **p2p_data} # β shape idΓ©ntico al actual
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
---
|
| 364 |
+
|
| 365 |
+
## 8. Plan de testing manual
|
| 366 |
+
|
| 367 |
+
Antes del deploy a HF Spaces, validar en local o staging:
|
| 368 |
+
|
| 369 |
+
### 8.1 RegresiΓ³n `/v1` (crΓtico β no romper producciΓ³n)
|
| 370 |
+
|
| 371 |
+
- [ ] `GET /v1/rates` con AppCheck vΓ‘lido β response 200 con shape exacto del legacy
|
| 372 |
+
- [ ] `GET /v1/bcv` β response 200 con campos BCV
|
| 373 |
+
- [ ] `GET /v1/p2p` β response 200 con `p2pBuyMax` y `p2pSellMax`
|
| 374 |
+
- [ ] `GET /v1/p2p/debug` β response con anuncios crudos
|
| 375 |
+
|
| 376 |
+
### 8.2 Funcionalidad `/v2`
|
| 377 |
+
|
| 378 |
+
- [ ] `GET /v2/rates?country=AR` β `venezuela` y `local` poblados, `local.currency = "ARS"`
|
| 379 |
+
- [ ] `GET /v2/rates?country=VE` β `local = null`
|
| 380 |
+
- [ ] `GET /v2/rates?country=ES` β `local.currency = "EUR"`
|
| 381 |
+
- [ ] `GET /v2/rates?country=MX` β `local.currency = "MXN"`
|
| 382 |
+
- [ ] `GET /v2/rates?country=PY` β respuesta 200 incluso si `local.usdtBuy = null` (baja liquidez aceptable)
|
| 383 |
+
|
| 384 |
+
### 8.3 ValidaciΓ³n de errores
|
| 385 |
+
|
| 386 |
+
- [ ] `GET /v2/rates` (sin country) β 400 "es requerido"
|
| 387 |
+
- [ ] `GET /v2/rates?country=US` β 400 "no estΓ‘ soportado"
|
| 388 |
+
- [ ] `GET /v2/rates?country=ar` (minΓΊsculas) β 400 formato
|
| 389 |
+
- [ ] `GET /v2/rates?country=ARG` β 400 formato
|
| 390 |
+
- [ ] `GET /v2/rates?country=AR` sin AppCheck β 401
|
| 391 |
+
|
| 392 |
+
### 8.4 Comportamiento del cache
|
| 393 |
+
|
| 394 |
+
- [ ] Dos requests consecutivos a `?country=CO` dentro de 2 min β el segundo NO llega a Binance (revisar logs)
|
| 395 |
+
- [ ] Request a `?country=AR` y a `?country=CO` en paralelo β ambos hacen su propio fetch (locks por key distintos)
|
| 396 |
+
- [ ] `/v1/rates` y `/v2/rates?country=VE` consecutivos β comparten cache `p2p:VES` (el segundo no llega a Binance)
|
| 397 |
+
|
| 398 |
+
### 8.5 Tolerancia a fallos (simular con `DISABLE_APP_CHECK=1` y bloqueo de red)
|
| 399 |
+
|
| 400 |
+
- [ ] Bloquear Binance (firewall local) y consultar `?country=AR` β status 200, todos los `p2p*` y `usdt*` en `null`, BCV poblado
|
| 401 |
+
- [ ] Bloquear BCV y consultar `?country=AR` β status 503 (aceptable)
|
| 402 |
+
|
| 403 |
+
---
|
| 404 |
+
|
| 405 |
+
## 9. Plan de deploy a HF Spaces
|
| 406 |
+
|
| 407 |
+
### 9.1 Pre-deploy
|
| 408 |
+
|
| 409 |
+
1. Backup mental del ΓΊltimo commit working (anotar SHA actual de producciΓ³n).
|
| 410 |
+
2. Verificar tests manuales en local con `uvicorn main:app --reload`.
|
| 411 |
+
3. Si se necesita, exportar `DISABLE_APP_CHECK=1` localmente para pruebas sin token.
|
| 412 |
+
|
| 413 |
+
### 9.2 Deploy
|
| 414 |
+
|
| 415 |
+
HF Spaces hace deploy automΓ‘tico con cada push a `main`. Procedimiento:
|
| 416 |
+
|
| 417 |
+
1. `git add main.py DESIGN_TAZAS_WORLDWIDE.md NOTAS_DEV.md` (si NOTAS_DEV.md se actualiza)
|
| 418 |
+
2. `git commit -m "feat: agregar endpoint /v2/rates con soporte multi-paΓs"`
|
| 419 |
+
3. `git push origin main` β usar el token HF de `C:\dev\widget_test\backend.txt`
|
| 420 |
+
4. HF Spaces detecta el push y reconstruye el container (~2-3 min).
|
| 421 |
+
5. Verificar el build en https://huggingface.co/spaces/andervier/Tazas_API/logs
|
| 422 |
+
|
| 423 |
+
### 9.3 Smoke test post-deploy (sin AppCheck)
|
| 424 |
+
|
| 425 |
+
Estos checks NO requieren el token AppCheck:
|
| 426 |
+
|
| 427 |
+
```bash
|
| 428 |
+
curl https://andervier-tazas-api.hf.space/ # ping
|
| 429 |
+
curl https://andervier-tazas-api.hf.space/v1/p2p/debug # P2P debug
|
| 430 |
+
```
|
| 431 |
+
|
| 432 |
+
Para los endpoints autenticados, usar el cliente Android en build debug (que ya tiene AppCheck debug provider).
|
| 433 |
+
|
| 434 |
+
### 9.4 Rollback
|
| 435 |
+
|
| 436 |
+
Si el deploy rompe `/v1`:
|
| 437 |
+
- `git revert HEAD && git push origin main` β HF Spaces redeploya en ~3 min.
|
| 438 |
+
- Confirmar que el cliente legacy (`/v1/rates`) vuelve a responder.
|
| 439 |
+
|
| 440 |
+
No hay datos persistidos (cache en memoria), asΓ que rollback es solo cΓ³digo.
|
| 441 |
+
|
| 442 |
+
### 9.5 Monitoreo post-deploy
|
| 443 |
+
|
| 444 |
+
- HF Spaces tiene tab de logs. Vigilar las primeras 24 h por errores nuevos en `fetch_p2p` con fiats distintos a VES.
|
| 445 |
+
- Si aparecen errores repetidos para un fiat especΓfico (e.g. PYG), considerar agregar lΓ³gica defensiva especΓfica o quitarlo del catΓ‘logo en futuro.
|
| 446 |
+
|
| 447 |
+
---
|
| 448 |
+
|
| 449 |
+
## 10. Open questions
|
| 450 |
+
|
| 451 |
+
- [ ] ΒΏAgregar endpoint `GET /v1/countries` que liste los cΓ³digos soportados, para que el cliente no tenga que mantener una lista hardcoded duplicada? **DecisiΓ³n propuesta**: no en este release. El cliente puede mantener su propia lista hardcoded β son 15, cambia rara vez. Reevaluar si crece a 30+.
|
| 452 |
+
- [ ] ΒΏReducir TTL de cache de 2 min a 1 min para fiats con alta volatilidad (ARS, VES)? **DecisiΓ³n propuesta**: no, mantener 2 min uniforme. Si en producciΓ³n se observa que ARS varΓa mucho, ajustar.
|
| 453 |
+
- [ ] ΒΏLoguear el `country` de cada request a `/v2/rates` para entender quΓ© paΓses usan los usuarios? **DecisiΓ³n propuesta**: sΓ, INFO log con `country=XX` al entrar al handler. Γtil para evaluar adopciΓ³n.
|
NOTAS_DEV.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tazas API β Notas de desarrollo
|
| 2 |
+
|
| 3 |
+
## Repositorio
|
| 4 |
+
|
| 5 |
+
- **Hugging Face Space:** `andervier/Tazas_API`
|
| 6 |
+
- **URL del Space:** https://huggingface.co/spaces/andervier/Tazas_API
|
| 7 |
+
- **URL pΓΊblica de la API:** https://andervier-tazas-api.hf.space
|
| 8 |
+
- **SDK:** Docker
|
| 9 |
+
- **Directorio local:** `C:\dev\Tazas_API`
|
| 10 |
+
|
| 11 |
+
## Token de acceso
|
| 12 |
+
|
| 13 |
+
El token de Hugging Face estΓ‘ en:
|
| 14 |
+
```
|
| 15 |
+
C:\dev\widget_test\backend.txt
|
| 16 |
+
```
|
| 17 |
+
Formato: `HUGGINGS_TOKEN=hf_...`
|
| 18 |
+
|
| 19 |
+
Para configurar el remote con autenticaciΓ³n:
|
| 20 |
+
```bash
|
| 21 |
+
git remote set-url origin https://andervier:{TOKEN}@huggingface.co/spaces/andervier/Tazas_API
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Deploy
|
| 25 |
+
|
| 26 |
+
El Space hace redeploy automΓ‘tico con cada `git push`. No hay CI/CD manual.
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
cd C:/dev/Tazas_API
|
| 30 |
+
git add .
|
| 31 |
+
git commit -m "descripciΓ³n del cambio"
|
| 32 |
+
git push
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## Endpoints
|
| 36 |
+
|
| 37 |
+
Todos los endpoints `/v1/*` requieren el header:
|
| 38 |
+
```
|
| 39 |
+
X-Firebase-AppCheck: {token JWT}
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
| MΓ©todo | Ruta | DescripciΓ³n |
|
| 43 |
+
|--------|-------------|--------------------------------------|
|
| 44 |
+
| GET | `/` | Health check β `{"status":"ok"}` |
|
| 45 |
+
| GET | `/v1/rates` | Todas las tasas (BCV + P2P) |
|
| 46 |
+
| GET | `/v1/bcv` | Solo tasas BCV |
|
| 47 |
+
| GET | `/v1/p2p` | Solo tasas Binance P2P |
|
| 48 |
+
|
| 49 |
+
### Respuesta de `/v1/rates`
|
| 50 |
+
|
| 51 |
+
```json
|
| 52 |
+
{
|
| 53 |
+
"bcvUsd": 73.50,
|
| 54 |
+
"bcvEur": 80.12,
|
| 55 |
+
"bcvCny": 10.23,
|
| 56 |
+
"bcvTry": 2.15,
|
| 57 |
+
"bcvRub": 0.82,
|
| 58 |
+
"p2pBuyMax": 75.20,
|
| 59 |
+
"p2pSellMax": 74.80,
|
| 60 |
+
"updatedAt": "Martes, 01 de Abril de 2026"
|
| 61 |
+
}
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
## Arquitectura
|
| 65 |
+
|
| 66 |
+
### Firebase App Check
|
| 67 |
+
- Protege los endpoints contra llamadas no autorizadas
|
| 68 |
+
- Solo la app Android oficial puede llamar la API
|
| 69 |
+
- `PROJECT_NUMBER`: `748155614527`
|
| 70 |
+
- `APP_ID`: `1:748155614527:android:c29d203cf594986dda8f8a`
|
| 71 |
+
- Los tokens se validan contra los JWKS de Firebase
|
| 72 |
+
|
| 73 |
+
### Cache en memoria
|
| 74 |
+
| Dato | TTL | Motivo |
|
| 75 |
+
|------|-----------|----------------------------------------|
|
| 76 |
+
| BCV | 4 horas | El BCV actualiza una vez al dΓa |
|
| 77 |
+
| P2P | 20 minutos| Binance P2P fluctΓΊa frecuentemente |
|
| 78 |
+
|
| 79 |
+
### Scraping BCV (`fetch_bcv`)
|
| 80 |
+
- Scrapea `https://www.bcv.org.ve/`
|
| 81 |
+
- `verify=False` porque bcv.org.ve tiene cadena de certificados incompleta
|
| 82 |
+
- Busca los divs por id: `#dolar`, `#euro`, `#yuan`, `#lira`, `#rublo`
|
| 83 |
+
- Parsea formato venezolano: punto = miles, coma = decimal β `36.853,12` β `36853.12`
|
| 84 |
+
|
| 85 |
+
### Tasas Binance P2P (`fetch_p2p`)
|
| 86 |
+
- Llama a `https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search`
|
| 87 |
+
- Moneda: USDT/VES, mΓnimo de transacciΓ³n de referencia: **10 USDT**
|
| 88 |
+
- LΓ³gica correcta (corregida 2026-03-31):
|
| 89 |
+
|
| 90 |
+
| Campo | tradeType | LΓ³gica |
|
| 91 |
+
|-------------|-----------|---------------------------------------------------------------|
|
| 92 |
+
| `p2pBuyMax` | `SELL` | Vendedores de USDT β primer elegible = precio mΓ‘s bajo (compra mΓ‘s barata) |
|
| 93 |
+
| `p2pSellMax`| `BUY` | Compradores de USDT β primer elegible = precio mΓ‘s alto (mejor venta) |
|
| 94 |
+
|
| 95 |
+
Binance ya ordena los resultados del mejor al peor precio, por eso se toma el **primer anuncio elegible** en lugar de calcular max/min manualmente.
|
| 96 |
+
|
| 97 |
+
Un anuncio es elegible si:
|
| 98 |
+
- Tiene al menos 10 USDT disponibles (`surplusAmount >= 10`)
|
| 99 |
+
- El monto en VES para 10 USDT cae dentro de sus lΓmites (`minSingleTransAmount` / `maxSingleTransAmount`)
|
| 100 |
+
|
| 101 |
+
## Dependencias principales
|
| 102 |
+
|
| 103 |
+
```
|
| 104 |
+
fastapi
|
| 105 |
+
uvicorn
|
| 106 |
+
httpx
|
| 107 |
+
beautifulsoup4
|
| 108 |
+
lxml
|
| 109 |
+
PyJWT
|
| 110 |
+
cryptography
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Ver `requirements.txt` para versiones exactas.
|
| 114 |
+
|
| 115 |
+
## Consumidor principal
|
| 116 |
+
|
| 117 |
+
App Android **Tazas** (`com.rivsballabs.tazas`)
|
| 118 |
+
- Directorio local: `C:\dev\widget_test`
|
| 119 |
+
- Clase que consume la API: `DolarSyncWorker.kt`
|
| 120 |
+
- Cliente HTTP: Retrofit + OkHttp con interceptor de Firebase App Check
|
main.py
CHANGED
|
@@ -22,6 +22,32 @@ _cache: dict = {}
|
|
| 22 |
BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓa)
|
| 23 |
P2P_TTL = 60 * 2 # 2 minutos
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
# Un Lock por clave: si el cachΓ© vence y llegan 1000 requests simultΓ‘neas,
|
| 26 |
# solo la primera hace el fetch β las demΓ‘s esperan y consumen el cachΓ©.
|
| 27 |
_locks: dict[str, asyncio.Lock] = {}
|
|
@@ -255,6 +281,88 @@ async def fetch_p2p_safe() -> dict:
|
|
| 255 |
return {"p2pBuyMax": None, "p2pSellMax": None}
|
| 256 |
|
| 257 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 259 |
# Endpoints
|
| 260 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -316,3 +424,41 @@ async def p2p_debug():
|
|
| 316 |
"buy_ads": extract(buy_res.json().get("data", [])),
|
| 317 |
"sell_ads": extract(sell_res.json().get("data", [])),
|
| 318 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓa)
|
| 23 |
P2P_TTL = 60 * 2 # 2 minutos
|
| 24 |
|
| 25 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
# v2 β Constantes (aislamiento total respecto a v1)
|
| 27 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
P2P_V2_TTL = 60 * 2
|
| 29 |
+
BINANCE_P2P_URL = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search"
|
| 30 |
+
COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$")
|
| 31 |
+
|
| 32 |
+
# ISO 3166-1 alpha-2 β ISO 4217 (fiat para Binance P2P)
|
| 33 |
+
SUPPORTED_COUNTRIES: dict[str, str] = {
|
| 34 |
+
"AR": "ARS", # Argentina
|
| 35 |
+
"BO": "BOB", # Bolivia
|
| 36 |
+
"CL": "CLP", # Chile
|
| 37 |
+
"CO": "COP", # Colombia
|
| 38 |
+
"CR": "CRC", # Costa Rica
|
| 39 |
+
"DO": "DOP", # RepΓΊblica Dominicana
|
| 40 |
+
"GT": "GTQ", # Guatemala
|
| 41 |
+
"HN": "HNL", # Honduras
|
| 42 |
+
"MX": "MXN", # MΓ©xico
|
| 43 |
+
"NI": "NIO", # Nicaragua
|
| 44 |
+
"PY": "PYG", # Paraguay
|
| 45 |
+
"PE": "PEN", # PerΓΊ
|
| 46 |
+
"UY": "UYU", # Uruguay
|
| 47 |
+
"VE": "VES", # Venezuela (caso especial: local = null)
|
| 48 |
+
"ES": "EUR", # EspaΓ±a
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
# Un Lock por clave: si el cachΓ© vence y llegan 1000 requests simultΓ‘neas,
|
| 52 |
# solo la primera hace el fetch β las demΓ‘s esperan y consumen el cachΓ©.
|
| 53 |
_locks: dict[str, asyncio.Lock] = {}
|
|
|
|
| 281 |
return {"p2pBuyMax": None, "p2pSellMax": None}
|
| 282 |
|
| 283 |
|
| 284 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 285 |
+
# v2 β Fetchers aislados (no afectan a /v1)
|
| 286 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 287 |
+
async def fetch_p2p_v2(fiat: str) -> dict:
|
| 288 |
+
cache_key = f"p2p_v2:{fiat}"
|
| 289 |
+
cached = _cached(cache_key, P2P_V2_TTL)
|
| 290 |
+
if cached:
|
| 291 |
+
return cached
|
| 292 |
+
|
| 293 |
+
async with _lock(cache_key):
|
| 294 |
+
cached = _cached(cache_key, P2P_V2_TTL)
|
| 295 |
+
if cached:
|
| 296 |
+
return cached
|
| 297 |
+
|
| 298 |
+
headers = {
|
| 299 |
+
"User-Agent": "Mozilla/5.0",
|
| 300 |
+
"Content-Type": "application/json",
|
| 301 |
+
}
|
| 302 |
+
body_base = {
|
| 303 |
+
"fiat": fiat,
|
| 304 |
+
"page": 1,
|
| 305 |
+
"rows": 20,
|
| 306 |
+
"asset": "USDT",
|
| 307 |
+
"countries": [],
|
| 308 |
+
"proMerchantAds": False,
|
| 309 |
+
"shieldMerchantAds": False,
|
| 310 |
+
"publisherType": None,
|
| 311 |
+
"payTypes": [],
|
| 312 |
+
"classifies": ["mass", "profession"],
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
logger.info("fetch_p2p_v2 fiat=%s", fiat)
|
| 316 |
+
|
| 317 |
+
buy_ads_res, sell_ads_res = await asyncio.gather(
|
| 318 |
+
_http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "BUY"}, headers=headers),
|
| 319 |
+
_http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "SELL"}, headers=headers),
|
| 320 |
+
)
|
| 321 |
+
buy_ads_res.raise_for_status()
|
| 322 |
+
sell_ads_res.raise_for_status()
|
| 323 |
+
|
| 324 |
+
def first_eligible_price(ads: list) -> float | None:
|
| 325 |
+
if not ads:
|
| 326 |
+
return None
|
| 327 |
+
sample = []
|
| 328 |
+
for item in ads[3:6]:
|
| 329 |
+
try:
|
| 330 |
+
sample.append(float(item["adv"]["price"]))
|
| 331 |
+
except (KeyError, ValueError, TypeError):
|
| 332 |
+
pass
|
| 333 |
+
if not sample:
|
| 334 |
+
return None
|
| 335 |
+
return round(sum(sample) / len(sample), 2)
|
| 336 |
+
|
| 337 |
+
p2p_buy = first_eligible_price(sell_ads_res.json().get("data", []))
|
| 338 |
+
p2p_sell = first_eligible_price(buy_ads_res.json().get("data", []))
|
| 339 |
+
|
| 340 |
+
data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
|
| 341 |
+
_store(cache_key, data)
|
| 342 |
+
return data
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
async def fetch_p2p_v2_safe(fiat: str) -> dict:
|
| 346 |
+
try:
|
| 347 |
+
return await fetch_p2p_v2(fiat)
|
| 348 |
+
except Exception as e:
|
| 349 |
+
logger.error("fetch_p2p_v2(%s) failed: %s", fiat, e, exc_info=True)
|
| 350 |
+
return {"p2pBuyMax": None, "p2pSellMax": None}
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def validate_country(country: str | None) -> str:
|
| 354 |
+
if not country:
|
| 355 |
+
raise HTTPException(status_code=400, detail="Query param 'country' es requerido")
|
| 356 |
+
if not COUNTRY_CODE_PATTERN.match(country):
|
| 357 |
+
raise HTTPException(
|
| 358 |
+
status_code=400,
|
| 359 |
+
detail="CΓ³digo de paΓs debe ser ISO 3166-1 alpha-2 (2 letras mayΓΊsculas)",
|
| 360 |
+
)
|
| 361 |
+
if country not in SUPPORTED_COUNTRIES:
|
| 362 |
+
raise HTTPException(status_code=400, detail=f"PaΓs '{country}' no estΓ‘ soportado en esta versiΓ³n")
|
| 363 |
+
return country
|
| 364 |
+
|
| 365 |
+
|
| 366 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 367 |
# Endpoints
|
| 368 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 424 |
"buy_ads": extract(buy_res.json().get("data", [])),
|
| 425 |
"sell_ads": extract(sell_res.json().get("data", [])),
|
| 426 |
}
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 430 |
+
# v2 β Endpoint multi-paΓs (aislado de /v1)
|
| 431 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 432 |
+
@app.get("/v2/rates", dependencies=[Depends(verify_app_check)])
|
| 433 |
+
async def rates_v2(country: str | None = None):
|
| 434 |
+
cc = validate_country(country)
|
| 435 |
+
fiat = SUPPORTED_COUNTRIES[cc]
|
| 436 |
+
|
| 437 |
+
logger.info("/v2/rates country=%s fiat=%s", cc, fiat)
|
| 438 |
+
|
| 439 |
+
if cc == "VE":
|
| 440 |
+
bcv_data, ve_p2p = await asyncio.gather(
|
| 441 |
+
fetch_bcv(),
|
| 442 |
+
fetch_p2p_v2_safe("VES"),
|
| 443 |
+
)
|
| 444 |
+
return {
|
| 445 |
+
"venezuela": {**bcv_data, **ve_p2p},
|
| 446 |
+
"local": None,
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
bcv_data, ve_p2p, local_p2p = await asyncio.gather(
|
| 450 |
+
fetch_bcv(),
|
| 451 |
+
fetch_p2p_v2_safe("VES"),
|
| 452 |
+
fetch_p2p_v2_safe(fiat),
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
return {
|
| 456 |
+
"venezuela": {**bcv_data, **ve_p2p},
|
| 457 |
+
"local": {
|
| 458 |
+
"countryCode": cc,
|
| 459 |
+
"currency": fiat,
|
| 460 |
+
"usdtBuy": local_p2p.get("p2pBuyMax"),
|
| 461 |
+
"usdtSell": local_p2p.get("p2pSellMax"),
|
| 462 |
+
"updatedAt": None,
|
| 463 |
+
},
|
| 464 |
+
}
|