diff --git a/CHANGELOG.md b/CHANGELOG.md index 465ae28..32abf93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,59 @@ All notable changes to this package are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). +## [0.6.0] - 2026-10-28 + +White-label: a platform keeps its own login, imports its users (by its own user id, +`external_id`) with the wallets they already have, and uses their trades, PnL, leaderboards +and trading competitions through the Data API. Sync and async. + +### Added + +- Platform users (`/v1/platform-users/*`) on `CabalSpyID` and `AsyncCabalSpyID`: + `upsert_platform_user`, `import_platform_users`, `platform_user`, `update_platform_user`, + `platform_users` / `iter_platform_users`, `delete_platform_user`, `add_platform_user_wallets`, + `delete_platform_user_wallet`, `start_wallet_verification`, `wallet_verification`, + `wallet_verification_qr` (SVG), `cancel_wallet_verification`, `platform_user_profile`, + `platform_leaderboard` / `iter_platform_leaderboard`, `platform_settings`, + `update_platform_settings`, `platform_inbound`, `enable_platform_inbound`, + `disable_platform_inbound`, `platform_user_session`, `platform_user_claim_link`, + `connect_platform_user_x`, `disconnect_platform_user_x`, `link_platform_user_telegram`, + `platform_user_telegram`, `unlink_platform_user_telegram`, `platform_user_kol`, + `request_platform_user_volume_check`, `apply_platform_user_kol`. Methods that take a user + accept `external_id` or `csid_id=`. +- `bulk_import_platform_users(users)`: any number of users in chunks of at most 1,000 and under + the 1 MB body limit, aggregated results in input order. Retries a chunk refused with 429 + (`Retry-After` wins) and re-sends only the users rejected with `rate_limited` once the + minute is over; a chunk that succeeded is never sent again. Other failures raise + `PlatformImportError` with `result` and `remaining` (to resume). +- Trading competitions (`/v1/competitions*`): `create_competition`, `competitions` / + `iter_competitions`, `competition`, `update_competition`, `cancel_competition`, + `join_competition`, `leave_competition`, `competition_participants` / + `iter_competition_participants`, `competition_standings` / `iter_competition_standings`. + The offset-paginated routes are walked with the new `offset_items()`. +- `get_text()` for non-JSON answers (the verification QR code). +- `ConflictError` (409): `account_claimed`, `last_wallet`, `too_many_wallets`, + `wallet_already_verified`, `kol_badge`, `x_required`, `kol_not_eligible`, `competition_limit`, + `competition_closed`, `competition_full`, `late_join_closed`. It subclasses + `CabalSpyIDError`, which 409 responses raised before. +- New codes on the existing classes: `wallet_required`, `invalid_address`, `invalid_return_url` + (`BadRequestError`), `claim_disabled` (`PermissionError`), `plan_user_limit` on creating a + user (`PlanUserLimitError`, `body` has `user_limit`), `platform_user_not_found`, + `verification_not_found`, `competition_not_found` (`NotFoundError`), `rate_limited` and + `too_many_open_verifications` (`RateLimitError`). +- Webhook events `platform_user.created`, `platform_user.claimed`, `platform_user.x_connected`, + `wallet.added`, `verification.expired`, `competition.started`, `competition.updated`, + `competition.standings`, `competition.ended` in `WEBHOOK_EVENTS`, plus + `PLATFORM_WEBHOOK_EVENTS` and `COMPETITION_WEBHOOK_EVENTS`. +- Types: `PlatformUser`, `PlatformUserUpsert`, `PlatformWallet`, `PlatformUserInput`, + `PlatformWalletInput`, `PlatformImportResult`, `PlatformBulkImportResult`, `PlatformSettings`, + `PlatformUserProfile`, `PlatformLeaderboardEntry`, `WalletVerification`, `Competition`, + `CompetitionDetail`, `CompetitionStanding`, `CompetitionStandings` and more; constants + `PLATFORM_IMPORT_MAX`, `PLATFORM_MAX_WALLETS_PER_REQUEST`, `MAX_REQUEST_BODY_BYTES`, + `WALLET_TRUST`, `DATA_SCOPES`, `INBOUND_FORMATS`, `COMPETITION_METRICS`, + `COMPETITION_STATUSES`, `COMPETITION_ENROLLMENTS`, `MAX_OPEN_COMPETITIONS`. +- README section "White-label (platform users)" and `examples/white_label.py`. + ## [0.5.2] - 2026-10-15 The public thesis API (`https://id.cabalspy.xyz/thesis/v1/...`) and its live socket @@ -121,6 +174,7 @@ First release. `NotFoundError`, `RateLimitError`, `ServerError`, `APIConnectionError`, `InvalidResponseError`, `OAuthError`, `TokenVerificationError`, `WebhookVerificationError`. +[0.6.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.2...v0.6.0 [0.5.2]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.1...v0.5.2 [0.5.1]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.4.1...v0.5.0 diff --git a/README.md b/README.md index 5527911..ad12af8 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ pip install "cabalspy-id[stream]" | | | |---|---| | `CabalSpyIDAuth` / `AsyncCabalSpyIDAuth` | OpenID Connect for your server: PKCE, code exchange, refresh, revoke, userinfo, ID token verification (ES256 / JWKS) | -| `CabalSpyID` / `AsyncCabalSpyID` | Data API client for `https://api-id.cabalspy.xyz/v1`, typed responses, pagination, live trade stream | +| `CabalSpyID` / `AsyncCabalSpyID` | Data API client for `https://api-id.cabalspy.xyz/v1`, typed responses, pagination, live trade stream, white-label platform users and trading competitions | | `ThesisClient` / `AsyncThesisClient` | public token thesis API with your public `client_id` and a user's access token, plus `live()` updates | | `verify_webhook` | Standard Webhooks signature verification | @@ -37,6 +37,7 @@ Everything for developers — instance (client_id), client secrets, redirect URI - **Token theses** — holders-only opinions on a token with the author's real position, as a SocialFi widget or your own UI - **Trader profiles** — X profile, verified wallets, holdings, PnL calendar - **KOL badges** — reviewed badges for influential traders, shown wherever they sign in +- **White-label** — keep your own login, import your users and their wallets, run trading competitions ## Packages @@ -229,19 +230,104 @@ except RateLimitError as err: | Class | Status | Codes | |---|---|---| -| `BadRequestError` | 400 | `missing_parameter`, `invalid_parameter`, `instance_required` | +| `BadRequestError` | 400 | `missing_parameter`, `invalid_parameter`, `instance_required`, `wallet_required`, `invalid_address`, `invalid_return_url` | | `AuthenticationError` | 401 | `missing_api_key` | -| `PermissionError` | 403 | `invalid_api_key`, `product_not_enabled`, `no_instance`, `scope_not_allowed` | +| `PermissionError` | 403 | `invalid_api_key`, `product_not_enabled`, `no_instance`, `scope_not_allowed`, `claim_disabled` | | `PlanUserLimitError` | 403 | `plan_user_limit` | -| `NotFoundError` | 404 | `profile_not_found`, `wallet_not_found`, `instance_not_found` | -| `RateLimitError` | 429 | `rate_limit_exceeded` | +| `NotFoundError` | 404 | `profile_not_found`, `wallet_not_found`, `instance_not_found`, `platform_user_not_found`, `verification_not_found`, `competition_not_found` | +| `ConflictError` | 409 | `account_claimed`, `last_wallet`, `too_many_wallets`, `wallet_already_verified`, `kol_badge`, `x_required`, `kol_not_eligible`, `competition_limit`, `competition_closed`, `competition_full`, `late_join_closed` | +| `RateLimitError` | 429 | `rate_limit_exceeded`, `rate_limited`, `too_many_open_verifications` | | `ServerError` | 5xx | `internal_error`, `service_unavailable` | | `APIConnectionError` | – | network failure, timeout | | `OAuthError` | 4xx | OAuth errors from the login endpoints (`invalid_grant`, `invalid_client`, …) | | `TokenVerificationError` | – | ID / access token failed verification | | `WebhookVerificationError` | – | webhook signature or timestamp invalid | +| `PlatformImportError` | – | `bulk_import_platform_users` stopped; carries `result` and `remaining` | -`429`, `5xx` and network errors are retried with exponential backoff (default 2 retries); `Retry-After` wins. The rate limit of the last call is in `csid.last_rate_limit` (`X-RateLimit-Limit/Remaining/Reset`). +`429`, `5xx` and network errors are retried with exponential backoff (default 2 retries); `Retry-After` wins. Writes (POST) are retried only after the API-wide rate limit (`rate_limit_exceeded`), since they did not run. The rate limit of the last call is in `csid.last_rate_limit` (`X-RateLimit-Limit/Remaining/Reset`). + +## White-label (platform users) + +Keep your own login. Your platform imports its users — by **your own user id** (`external_id`) — together with the wallets they already have (Privy, Dynamic, any provider), and then uses their trades, PnL, leaderboards and trading competitions through the API. No CabalSpy ID login, no wallet connect: imported wallets count right away (unless you set `wallet_trust="verified_only"`), and the on-chain payment verification stays available as a badge. + +```python +from cabalspy_id import CabalSpyID, PlanUserLimitError + +csid = CabalSpyID() + +# One user: create or update (a new user needs 1-10 wallets) +user = csid.upsert_platform_user( + "user_42", + wallets=["So1...", {"address": "0xabc...", "chains": ["base"], "source": "privy"}], + display_name="Alice", +) + +# Everyone else: any number of users, sent in chunks of 1,000 +result = csid.bulk_import_platform_users( + {"external_id": u.id, "wallets": u.wallet_addresses, "display_name": u.name} for u in all_users +) +print(result["summary"]) # {"created": ..., "updated": ..., "unchanged": ..., "rejected": ...} + +# A profile page in one call, and your own leaderboard +profile = csid.platform_user_profile("user_42", period="7d") +board = csid.platform_leaderboard(blockchain="solana", period="7d", sort="pnl_usd") +for entry in board["leaderboard"]: + print(entry["rank"], entry["external_id"], entry["period_stats"]["realized_pnl_usd"]) + +# A trading competition between your users +comp = csid.create_competition(name="Weekly PnL", chain="solana", metric="pnl_usd", + duration_hours=168, enrollment="all_users") +standings = csid.competition_standings(comp["id"]) +``` + +Every platform-users method that takes a user accepts the `external_id` positionally or `csid_id=` (exactly one). The rest of the API also accepts `external_id` in place of `csid_id` (pass it with `get_raw` / `post_raw`), and every platform user carries its `csid_id` for the other SDK methods. A full tour is in [`examples/white_label.py`](examples/white_label.py). + +**Bulk import.** `import_platform_users(users)` is one call (at most 1,000 users). `bulk_import_platform_users(users)` takes any number: it sends chunks of at most 1,000 users and under the server's 1 MB body limit, retries a chunk refused with 429 (`Retry-After` wins), and sends users rejected with `rate_limited` (too many new users per minute) again on their own once the minute is over. A chunk that succeeded is never sent again. Results come back aggregated, one per user in input order. If anything else stops it, `PlatformImportError` carries `result` (what was imported) and `remaining` (pass it again to resume). Each user is handled on its own on the server: a bad item or the plan's user limit (`plan_user_limit`) never undoes the others. + +| Method | Endpoint | +|---|---| +| `upsert_platform_user(external_id, wallets=, display_name=, avatar_url=)` | `POST /v1/platform-users` | +| `import_platform_users(users)` / `bulk_import_platform_users(users)` | `POST /v1/platform-users/import` | +| `platform_user(external_id \| csid_id=)` | `GET /v1/platform-users` | +| `update_platform_user(external_id, display_name=, avatar_url=)` | `POST /v1/platform-users/update` | +| `platform_users(limit=, cursor=)` / `iter_platform_users()` | `GET /v1/platform-users/list` | +| `delete_platform_user(external_id)` | `POST /v1/platform-users/delete` | +| `add_platform_user_wallets(external_id, wallets=)` | `POST /v1/platform-users/wallets/add` | +| `delete_platform_user_wallet(external_id, address=)` | `POST /v1/platform-users/wallets/delete` | +| `start_wallet_verification(external_id, chain=, address=)` | `POST /v1/platform-users/wallets/verify` | +| `wallet_verification(id)` / `wallet_verification_qr(id)` (SVG) / `cancel_wallet_verification(id)` | `/v1/platform-users/wallets/verification[/qr\|/cancel]` | +| `platform_user_profile(external_id, period=)` | `GET /v1/platform-users/profile` | +| `platform_leaderboard(blockchain=, period=, sort=, limit=, cursor=, trust=)` / `iter_platform_leaderboard()` | `GET /v1/platform-users/leaderboard` | +| `platform_settings()` / `update_platform_settings(...)` | `GET` / `POST /v1/platform-users/settings` | +| `platform_inbound()` / `enable_platform_inbound()` / `disable_platform_inbound()` | `/v1/platform-users/inbound[/enable\|/disable]` | +| `platform_user_session(external_id)` | `POST /v1/platform-users/session` (verify widget, 15 min) | +| `platform_user_claim_link(external_id, return_url=)` | `POST /v1/platform-users/claim-link` | +| `connect_platform_user_x(external_id, return_url=)` / `disconnect_platform_user_x(external_id)` | `POST /v1/platform-users/x/connect`, `/x/disconnect` | +| `link_platform_user_telegram` / `platform_user_telegram` / `unlink_platform_user_telegram` | `/v1/platform-users/telegram[/link\|/unlink]` | +| `platform_user_kol` / `request_platform_user_volume_check` / `apply_platform_user_kol` | `/v1/platform-users/kol[/volume-check\|/apply]` | + +**Settings** (`update_platform_settings`): `white_label`, `data_scope` (`csid`: part of the CabalSpy ID network, default; `platform`: only you see your users), `wallet_trust` and `leaderboard_trust` (`all` or `verified_only`), `claim_links`, `telegram_alerts`. Wallets carry a `status`: `verified`, `active` (unverified, counts), `needs_verification`, `verified_elsewhere` or `pending`. + +**Inbound URL.** `enable_platform_inbound()` returns a secret URL (shown once) that your platform or its auth provider calls on sign-up; users are then created like `upsert_platform_user`. Formats: `csid`, `privy`, `dynamic`, `generic`. + +### Trading competitions + +Individual competitions between your platform users, at most 5 scheduled + running at a time per account. A competition starts at `starts_at` (or at once) once `min_participants` joined, then runs `duration_hours`. Metrics: `pnl_usd`, `pnl`, `volume_usd`, `volume`, `trades`, `win_rate`. Traders below `min_trades` / `min_volume_usd` are listed but not ranked. Rules can change at any time, also while running; every change is recorded (`changes`, `rules_version`). + +| Method | Endpoint | +|---|---| +| `create_competition(name=, chain=, metric=, duration_hours=, ...)` | `POST /v1/competitions` | +| `competitions(status=, limit=, offset=)` / `iter_competitions()` | `GET /v1/competitions` | +| `competition(id)` | `GET /v1/competitions/detail` | +| `update_competition(id, note=, **fields)` | `POST /v1/competitions/update` | +| `cancel_competition(id)` | `POST /v1/competitions/cancel` | +| `join_competition(id, external_id)` / `leave_competition(id, external_id)` | `POST /v1/competitions/join`, `/leave` | +| `competition_participants(id, limit=, offset=)` / `iter_competition_participants(id)` | `GET /v1/competitions/participants` | +| `competition_standings(id, limit=, offset=)` / `iter_competition_standings(id)` | `GET /v1/competitions/standings` | + +The competition routes page by `offset`; the `iter_*` helpers walk them until `pagination.total`. + +Webhooks: `platform_user.created`, `platform_user.claimed`, `platform_user.x_connected`, `wallet.added`, `verification.expired`, and per instance `competition.started`, `competition.updated`, `competition.standings`, `competition.ended` (`PLATFORM_WEBHOOK_EVENTS`, `COMPETITION_WEBHOOK_EVENTS`). ## Token theses @@ -391,7 +477,7 @@ The server sends a heartbeat every 30 seconds. The client reconnects with expone ## Webhooks -Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com) spec (`webhook-id`, `webhook-timestamp`, `webhook-signature`, secret `whsec_...`) and are retried for about 2 days. Events: `wallet.verified`, `wallet.removed`, `profile.updated`, `kol.granted`, `consent.revoked`, `thesis.created`, `thesis.reply`, `thesis.reaction` — only for users within the plan's limit. +Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com) spec (`webhook-id`, `webhook-timestamp`, `webhook-signature`, secret `whsec_...`) and are retried for about 2 days. Events: `wallet.verified`, `wallet.removed`, `profile.updated`, `kol.granted`, `consent.revoked`, `thesis.created`, `thesis.reply`, `thesis.reaction` — only for users within the plan's limit. White-label adds `platform_user.created`, `platform_user.claimed`, `platform_user.x_connected`, `wallet.added`, `verification.expired` and the instance-level `competition.started`, `competition.updated`, `competition.standings`, `competition.ended` (these carry `competition_id` instead of `sub`). ```python from cabalspy_id import verify_webhook diff --git a/cabalspy_id/__init__.py b/cabalspy_id/__init__.py index 66cabfb..8472578 100644 --- a/cabalspy_id/__init__.py +++ b/cabalspy_id/__init__.py @@ -1,8 +1,8 @@ """CabalSpy ID — the verified social layer for crypto trading. Login with CabalSpy ID (OpenID Connect), the Data API for verified wallets, KOL -badges, trading stats and token theses, the live stream, the public thesis API -and webhook verification. +badges, trading stats and token theses, white-label platform users and trading +competitions, the live stream, the public thesis API and webhook verification. from cabalspy_id import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -18,16 +18,27 @@ from ._constants import ( CHAINS, CLIENT_ID_HEADER, + COMPETITION_ENROLLMENTS, + COMPETITION_METRICS, + COMPETITION_STATUSES, + COMPETITION_WEBHOOK_EVENTS, CURRENCY_BY_CHAIN, + DATA_SCOPES, DEFAULT_BASE_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, DEFAULT_THESIS_URL, DEFAULT_THESIS_WS_URL, + INBOUND_FORMATS, LEADERBOARD_SORTS, + MAX_OPEN_COMPETITIONS, + MAX_REQUEST_BODY_BYTES, MAX_THESES_STREAM_TOKENS, PERIODS, + PLATFORM_IMPORT_MAX, + PLATFORM_MAX_WALLETS_PER_REQUEST, + PLATFORM_WEBHOOK_EVENTS, SCOPES, SDK_VERSION, STREAM_TOPICS, @@ -35,12 +46,20 @@ THESIS_MAX_BODY, THESIS_REPORT_REASONS, THESIS_SCOPES, + WALLET_TRUST, WEBHOOK_EVENTS, Chain, + CompetitionEnrollment, + CompetitionMetric, + CompetitionStatus, Currency, + DataScope, LeaderboardSort, + LeaderboardTrust, OidcScope, Period, + PlatformImportStatus, + PlatformWalletStatus, Scope, StreamTopic, ThesisEmoji, @@ -48,16 +67,20 @@ ThesisScope, ThesisSort, ThesisStance, + VerificationStatus, + WalletTrust, ) from ._errors import ( APIConnectionError, AuthenticationError, BadRequestError, CabalSpyIDError, + ConflictError, InvalidResponseError, NotFoundError, OAuthError, PlanUserLimitError, + PlatformImportError, RateLimit, RateLimitError, ServerError, @@ -79,6 +102,13 @@ ActiveHoldings, ActiveTokens, CabalSpyIDClaims, + Competition, + CompetitionChange, + CompetitionDetail, + CompetitionMembership, + CompetitionParticipant, + CompetitionStanding, + CompetitionStandings, DiscoveryDocument, HealthResponse, HistoryResponse, @@ -86,12 +116,49 @@ HistoryTrade, HoldingsResponse, HoldingToken, + InboundEventResult, + KolApplicationStatus, LeaderboardEntry, LeaderboardResponse, LifetimeStats, MeResponse, Pagination, PeriodStats, + PlatformBulkImportResult, + PlatformClaimLink, + PlatformImportItem, + PlatformImportResult, + PlatformImportSummary, + PlatformInbound, + PlatformInboundEnabled, + PlatformInboundStatus, + PlatformItemError, + PlatformKolApply, + PlatformKolStatus, + PlatformKolVolumeCheck, + PlatformLeaderboardEntry, + PlatformLeaderboardResponse, + PlatformProfileLinks, + PlatformSession, + PlatformSettings, + PlatformTelegramLink, + PlatformTelegramStatus, + PlatformTrading, + PlatformTradingWallet, + PlatformUser, + PlatformUserDeleted, + PlatformUserInput, + PlatformUserProfile, + PlatformUserTelegram, + PlatformUserUpsert, + PlatformUserX, + PlatformWallet, + PlatformWalletInput, + PlatformWalletRemoved, + PlatformWalletsResponse, + PlatformWalletVerification, + PlatformXConnect, + PlatformXDisconnect, PnlCalendarDay, PnlCalendarMonth, PnlCalendarResponse, @@ -118,8 +185,10 @@ TradeOwner, TraderProfile, VerifiedWallet, + WalletAdded, WalletClaim, WalletLookupResponse, + WalletVerification, WebhookEvent, WinRateBuckets, WinRateDistribution, @@ -185,6 +254,8 @@ def __getattr__(name: str) -> object: "TokenVerificationError", "WebhookVerificationError", "RateLimit", + "ConflictError", + "PlatformImportError", # constants "SDK_VERSION", "CHAINS", @@ -221,6 +292,27 @@ def __getattr__(name: str) -> object: "Currency", "Scope", "OidcScope", + "PLATFORM_IMPORT_MAX", + "PLATFORM_MAX_WALLETS_PER_REQUEST", + "MAX_REQUEST_BODY_BYTES", + "WALLET_TRUST", + "DATA_SCOPES", + "INBOUND_FORMATS", + "PLATFORM_WEBHOOK_EVENTS", + "COMPETITION_WEBHOOK_EVENTS", + "COMPETITION_METRICS", + "COMPETITION_STATUSES", + "COMPETITION_ENROLLMENTS", + "MAX_OPEN_COMPETITIONS", + "WalletTrust", + "DataScope", + "LeaderboardTrust", + "PlatformWalletStatus", + "PlatformImportStatus", + "VerificationStatus", + "CompetitionMetric", + "CompetitionStatus", + "CompetitionEnrollment", # response types "ResponseMeta", "Pagination", @@ -270,4 +362,51 @@ def __getattr__(name: str) -> object: "ThesisNotices", "ThesisReactor", "ThesisReactions", + # white-label and competitions + "PlatformWalletInput", + "PlatformUserInput", + "PlatformWallet", + "WalletAdded", + "WalletVerification", + "PlatformWalletVerification", + "PlatformUserX", + "PlatformUserTelegram", + "PlatformUser", + "PlatformUserUpsert", + "PlatformWalletsResponse", + "PlatformItemError", + "PlatformImportItem", + "PlatformImportSummary", + "PlatformImportResult", + "PlatformBulkImportResult", + "PlatformUserDeleted", + "PlatformWalletRemoved", + "PlatformInbound", + "PlatformInboundStatus", + "PlatformInboundEnabled", + "PlatformSettings", + "PlatformSession", + "PlatformClaimLink", + "PlatformXConnect", + "PlatformXDisconnect", + "PlatformTelegramLink", + "PlatformTelegramStatus", + "KolApplicationStatus", + "PlatformKolStatus", + "PlatformKolVolumeCheck", + "PlatformKolApply", + "PlatformTrading", + "PlatformTradingWallet", + "PlatformProfileLinks", + "PlatformUserProfile", + "PlatformLeaderboardEntry", + "PlatformLeaderboardResponse", + "InboundEventResult", + "Competition", + "CompetitionDetail", + "CompetitionChange", + "CompetitionParticipant", + "CompetitionStanding", + "CompetitionStandings", + "CompetitionMembership", ] diff --git a/cabalspy_id/_client.py b/cabalspy_id/_client.py index 13bc31e..d2717a9 100644 --- a/cabalspy_id/_client.py +++ b/cabalspy_id/_client.py @@ -12,28 +12,42 @@ from __future__ import annotations import asyncio +import json import os import random import time -from collections.abc import AsyncIterator, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Literal +from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping, Sequence +from datetime import datetime +from typing import TYPE_CHECKING, Any, Literal, TypeVar import httpx from ._constants import ( CHAINS, + COMPETITION_ENROLLMENTS, + COMPETITION_METRICS, + COMPETITION_STATUSES, + DATA_SCOPES, DEFAULT_BASE_URL, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, LEADERBOARD_SORTS, PERIODS, + PLATFORM_IMPORT_MAX, + PLATFORM_MAX_WALLETS_PER_REQUEST, SCOPES, THESIS_EMOJIS, THESIS_REPORT_REASONS, THESIS_SCOPES, USER_AGENT, + WALLET_TRUST, Chain, + CompetitionEnrollment, + CompetitionMetric, + CompetitionStatus, + DataScope, LeaderboardSort, + LeaderboardTrust, Period, Scope, StreamTopic, @@ -42,6 +56,7 @@ ThesisScope, ThesisSort, ThesisStance, + WalletTrust, ) from ._errors import ( APIConnectionError, @@ -49,16 +64,20 @@ BadRequestError, CabalSpyIDError, InvalidResponseError, + PlatformImportError, RateLimit, RateLimitError, error_from_status, is_retryable, ) +from ._types import PlatformBulkImportResult, PlatformUserInput, PlatformWalletInput if TYPE_CHECKING: from ._stream import CabalSpyIDStream from ._theses_stream import ThesesStream +_T = TypeVar("_T") + __all__ = ["CabalSpyID", "AsyncCabalSpyID", "Envelope"] @@ -174,6 +193,161 @@ def _page_pagination(page: Envelope) -> dict[str, Any] | None: return page.pagination or inner +# ── white-label helpers ────────────────────────────────────────────────────── + + +class _NotGiven: + """Sentinel for "not passed", where ``None`` means "clear the value".""" + + def __repr__(self) -> str: + return "NOT_GIVEN" + + def __bool__(self) -> bool: + return False + + +NOT_GIVEN: Any = _NotGiven() + +_IMPORT_PATH = "/platform-users/import" +#: Bulk imports keep each request body below this (the server takes up to 1 MB). +_IMPORT_BODY_BYTES = 900_000 + + +def _given(**fields: Any) -> dict[str, Any]: + return {k: v for k, v in fields.items() if not isinstance(v, _NotGiven)} + + +def _who(external_id: str | None, csid_id: str | None) -> dict[str, Any]: + """The user of a platform-users call: exactly one of external_id, csid_id.""" + if bool(external_id) == bool(csid_id): + raise BadRequestError( + "Pass exactly one of: external_id, csid_id.", code="missing_parameter", parameter="external_id|csid_id" + ) + return {"external_id": external_id} if external_id else {"csid_id": csid_id} + + +def _wallet_items(wallets: Any, *, required: bool = True) -> list[Any]: + if isinstance(wallets, (str, Mapping)): + raise BadRequestError("wallets must be a list of wallets.", code="invalid_parameter", parameter="wallets") + items = [w if isinstance(w, str) else dict(w) for w in wallets] + if required and not items: + raise BadRequestError( + 'Pass at least one wallet: wallets=[{"address": "..."}].', code="wallet_required", parameter="wallets" + ) + if len(items) > PLATFORM_MAX_WALLETS_PER_REQUEST: + raise BadRequestError( + f"At most {PLATFORM_MAX_WALLETS_PER_REQUEST} wallets per request.", + code="invalid_parameter", + parameter="wallets", + ) + return items + + +def _platform_leaderboard_query( + blockchain: Any, period: Any, sort: Any, trust: Any, limit: Any, cursor: Any +) -> dict[str, Any]: + _required(blockchain, "blockchain") + _one_of(blockchain, CHAINS, "blockchain") + _one_of(period, PERIODS, "period") + _one_of(sort, LEADERBOARD_SORTS, "sort") + _one_of(trust, ("all", "verified"), "trust") + return {"blockchain": blockchain, "period": period, "sort": sort, "trust": trust, "limit": limit, "cursor": cursor} + + +def _competition_fields(**fields: Any) -> dict[str, Any]: + out = _given(**fields) + _one_of(out.get("chain"), CHAINS, "chain") + _one_of(out.get("metric"), COMPETITION_METRICS, "metric") + _one_of(out.get("wallet_trust"), WALLET_TRUST, "wallet_trust") + _one_of(out.get("enrollment"), COMPETITION_ENROLLMENTS, "enrollment") + if isinstance(out.get("starts_at"), datetime): + out["starts_at"] = out["starts_at"].isoformat() + return out + + +def _import_items(users: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]: + if isinstance(users, (str, Mapping)): + raise BadRequestError("users must be a list of users.", code="invalid_parameter", parameter="users") + return [dict(u) for u in users] + + +def _import_wait() -> float: + """Seconds until the server's per-minute window for new users resets (UTC minutes), plus 1.""" + return 61.0 - time.time() % 60.0 + + +class _ImportRun: + """State of one bulk import: the users, their chunks and the results so far.""" + + def __init__(self, users: Iterable[Mapping[str, Any]], chunk_size: int, max_body_bytes: int, attempts: int): + if not 1 <= chunk_size <= PLATFORM_IMPORT_MAX: + raise ValueError(f"chunk_size must be 1-{PLATFORM_IMPORT_MAX}") + if attempts < 1: + raise ValueError("max_attempts must be at least 1") + self.items = _import_items(users) + self.results: list[dict[str, Any] | None] = [None] * len(self.items) + self.requests = 0 + self.chunks: list[list[int]] = [] + current: list[int] = [] + size = len('{"users": []}') + for i, item in enumerate(self.items): + # json.dumps' defaults (ASCII escapes, spaced separators) never encode smaller than httpx + n = len(json.dumps(item).encode()) + 2 + if current and (len(current) >= chunk_size or size + n > max_body_bytes): + self.chunks.append(current) + current, size = [], len('{"users": []}') + current.append(i) + size += n + if current: + self.chunks.append(current) + + def body(self, pending: list[int]) -> dict[str, Any]: + self.requests += 1 + return {"users": [self.items[i] for i in pending]} + + def record(self, sent: list[int], data: Any) -> list[int]: + """Stores the results of one call; returns the users rejected with rate_limited.""" + results = data.get("results") if isinstance(data, dict) else None + if not isinstance(results, list) or len(results) != len(sent): + raise InvalidResponseError( + f"Unexpected import response: {len(sent)} users sent, results do not match", + code="invalid_response", + ) + retry: list[int] = [] + for index, res in zip(sent, results, strict=True): + self.results[index] = res + error = res.get("error") if isinstance(res, dict) else None + if isinstance(error, dict) and error.get("code") == "rate_limited": + retry.append(index) + return retry + + def result(self, skip: Iterable[int] = ()) -> dict[str, Any]: + skipped = set(skip) + results = [r for i, r in enumerate(self.results) if r is not None and i not in skipped] + summary = {"created": 0, "updated": 0, "unchanged": 0, "rejected": 0} + for r in results: + status = r.get("status") + if status in summary: + summary[status] += 1 + return {"summary": summary, "results": results, "requests": self.requests} + + def failed(self, exc: CabalSpyIDError, chunk_no: int, pending: list[int]) -> PlatformImportError: + left = pending + [i for chunk in self.chunks[chunk_no + 1 :] for i in chunk] + return PlatformImportError( + f"Import stopped, {len(left)} of {len(self.items)} users not imported: {exc}", + result=self.result(left), + remaining=[self.items[i] for i in left], + status=exc.status, + code=exc.code, + request_id=exc.request_id, + docs=exc.docs, + parameter=exc.parameter, + allowed=exc.allowed, + rate_limit=exc.rate_limit, + body=exc.body, + ) + + # ═══════════════════════════════════════════════════════════════════════════ # ENDPOINTS (shared between the sync and async clients) # ═══════════════════════════════════════════════════════════════════════════ @@ -186,6 +360,9 @@ def _get(self, path: str, params: Mapping[str, Any] | None = None, *, auth: bool def _post(self, path: str, body: Mapping[str, Any]) -> Any: # pragma: no cover raise NotImplementedError + def _get_text(self, path: str, params: Mapping[str, Any] | None = None) -> Any: # pragma: no cover + raise NotImplementedError + # ── account ────────────────────────────────────────────────────────── def health(self) -> Any: @@ -537,6 +714,468 @@ def delete_thesis(self, *, thesis_id: str, csid_id: str) -> Any: _required(csid_id, "csid_id") return self._post("/theses/delete", {"thesis_id": thesis_id, "csid_id": csid_id}) + # ── white-label: platform users ────────────────────────────────────── + # Your platform keeps its own login and addresses its users by its own user + # id (``external_id``). Every method that takes a user accepts either + # ``external_id`` (positional) or ``csid_id=`` — exactly one. + + def upsert_platform_user( + self, + external_id: str, + *, + wallets: Sequence[PlatformWalletInput | str] | None = None, + display_name: str | _NotGiven | None = NOT_GIVEN, + avatar_url: str | _NotGiven | None = NOT_GIVEN, + ) -> Any: + """POST /v1/platform-users — creates the user or updates an existing one. + + A new user needs 1-10 ``wallets`` (objects or plain addresses) and a free + place in your plan (else :class:`~cabalspy_id.PlanUserLimitError`). For an + existing user, wallets are added and the profile fields you pass are set + (``None`` clears them). Returns :class:`~cabalspy_id.PlatformUserUpsert` + (``created`` says which happened). + """ + _required(external_id, "external_id") + body: dict[str, Any] = {"external_id": external_id} + if wallets is not None: + body["wallets"] = _wallet_items(wallets, required=False) + body.update(_given(display_name=display_name, avatar_url=avatar_url)) + return self._post("/platform-users", body) + + def import_platform_users(self, users: Iterable[PlatformUserInput]) -> Any: + """POST /v1/platform-users/import — creates or updates up to 1,000 users in one call. + + Each user is handled on its own: a bad item or the plan limit never undoes + the others. Returns :class:`~cabalspy_id.PlatformImportResult` (one result + per user, in order). For more users, or automatic retries, use + ``bulk_import_platform_users``. + """ + items = _import_items(users) + if not items: + raise BadRequestError("Pass at least one user.", code="missing_parameter", parameter="users") + if len(items) > PLATFORM_IMPORT_MAX: + raise BadRequestError( + f"At most {PLATFORM_IMPORT_MAX} users per import call; use bulk_import_platform_users().", + code="invalid_parameter", + parameter="users", + ) + return self._post(_IMPORT_PATH, {"users": items}) + + def platform_user(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """GET /v1/platform-users — one of your users. Returns :class:`~cabalspy_id.PlatformUser`.""" + return self._get("/platform-users", _who(external_id, csid_id)) + + def update_platform_user( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + display_name: str | _NotGiven | None = NOT_GIVEN, + avatar_url: str | _NotGiven | None = NOT_GIVEN, + ) -> Any: + """POST /v1/platform-users/update — sets ``display_name`` and/or ``avatar_url`` (``None`` clears). + + Returns :class:`~cabalspy_id.PlatformUser`. + """ + fields = _given(display_name=display_name, avatar_url=avatar_url) + if not fields: + raise BadRequestError( + "Pass display_name and/or avatar_url.", code="missing_parameter", parameter="display_name" + ) + return self._post("/platform-users/update", {**_who(external_id, csid_id), **fields}) + + def platform_users(self, *, limit: int | None = None, cursor: str | None = None) -> Any: + """GET /v1/platform-users/list — your users, newest first (``limit`` 1-100, default 50). + + Returns a list of :class:`~cabalspy_id.PlatformUser`; see ``iter_platform_users``. + """ + return self._get("/platform-users/list", {"limit": limit, "cursor": cursor}) + + def delete_platform_user(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/delete — deletes the user and their data. + + A claimed user keeps their CabalSpy ID: only the link to your platform goes + (``deleted`` False, ``unlinked`` True). Returns :class:`~cabalspy_id.PlatformUserDeleted`. + """ + return self._post("/platform-users/delete", _who(external_id, csid_id)) + + def add_platform_user_wallets( + self, + external_id: str | None = None, + *, + wallets: Sequence[PlatformWalletInput | str], + csid_id: str | None = None, + ) -> Any: + """POST /v1/platform-users/wallets/add — adds 1-10 existing wallets (no payment verification). + + Returns :class:`~cabalspy_id.PlatformWalletsResponse`. + """ + return self._post( + "/platform-users/wallets/add", {**_who(external_id, csid_id), "wallets": _wallet_items(wallets)} + ) + + def delete_platform_user_wallet( + self, external_id: str | None = None, *, address: str, csid_id: str | None = None + ) -> Any: + """POST /v1/platform-users/wallets/delete — removes a wallet. The last one cannot go + (:class:`~cabalspy_id.ConflictError` ``last_wallet``). Returns :class:`~cabalspy_id.PlatformWalletRemoved`. + """ + _required(address, "address") + return self._post("/platform-users/wallets/delete", {**_who(external_id, csid_id), "address": address}) + + def start_wallet_verification( + self, external_id: str | None = None, *, chain: Chain, address: str, csid_id: str | None = None + ) -> Any: + """POST /v1/platform-users/wallets/verify — starts the payment verification of a wallet. + + The user sends the exact ``amount`` from that wallet to ``receiver`` before + ``expires_at`` (``payment_uri`` for wallets and QR codes). Returns + :class:`~cabalspy_id.PlatformWalletVerification`. + """ + _required(chain, "chain") + _one_of(chain, CHAINS, "chain") + _required(address, "address") + return self._post( + "/platform-users/wallets/verify", {**_who(external_id, csid_id), "chain": chain, "address": address} + ) + + def wallet_verification(self, id: str) -> Any: + """GET /v1/platform-users/wallets/verification — status of a verification + (pending, verified, cancelled, expired). Returns :class:`~cabalspy_id.PlatformWalletVerification`. + """ + _required(id, "id") + return self._get("/platform-users/wallets/verification", {"id": id}) + + def wallet_verification_qr(self, id: str) -> Any: + """GET /v1/platform-users/wallets/verification/qr — the payment URI as a QR code (SVG text).""" + _required(id, "id") + return self._get_text("/platform-users/wallets/verification/qr", {"id": id}) + + def cancel_wallet_verification(self, id: str) -> Any: + """POST /v1/platform-users/wallets/verification/cancel. + + Returns :class:`~cabalspy_id.PlatformWalletVerification`. + """ + _required(id, "id") + return self._post("/platform-users/wallets/verification/cancel", {"id": id}) + + def platform_user_profile( + self, external_id: str | None = None, *, csid_id: str | None = None, period: Period | None = None + ) -> Any: + """GET /v1/platform-users/profile — everything for a profile page in one call: the user, + trading per chain (default period 7d), recent trades, theses, Trade Feed and KOL status. + + Returns :class:`~cabalspy_id.PlatformUserProfile`. + """ + _one_of(period, PERIODS, "period") + return self._get("/platform-users/profile", {**_who(external_id, csid_id), "period": period}) + + def platform_leaderboard( + self, + *, + blockchain: Chain, + period: Period | None = None, + sort: LeaderboardSort | None = None, + limit: int | None = None, + cursor: str | None = None, + trust: LeaderboardTrust | None = None, + ) -> Any: + """GET /v1/platform-users/leaderboard — your platform users ranked (default 7d, pnl_usd; + ``limit`` 1-500, default 100), each entry with ``external_id`` and ``verified``. + + ``trust="verified"`` ranks only payment-verified wallets; it can only narrow the + instance's ``leaderboard_trust``. Returns :class:`~cabalspy_id.PlatformLeaderboardResponse`; + see ``iter_platform_leaderboard``. + """ + return self._get( + "/platform-users/leaderboard", _platform_leaderboard_query(blockchain, period, sort, trust, limit, cursor) + ) + + def platform_settings(self) -> Any: + """GET /v1/platform-users/settings. Returns :class:`~cabalspy_id.PlatformSettings`.""" + return self._get("/platform-users/settings") + + def update_platform_settings( + self, + *, + white_label: bool | None = None, + data_scope: DataScope | None = None, + wallet_trust: WalletTrust | None = None, + leaderboard_trust: WalletTrust | None = None, + claim_links: bool | None = None, + telegram_alerts: bool | None = None, + ) -> Any: + """POST /v1/platform-users/settings — changes the settings you pass (None = unchanged). + + ``data_scope``: ``csid`` (part of the CabalSpy ID network) or ``platform`` (only you + see your users). ``wallet_trust`` / ``leaderboard_trust``: ``all`` or ``verified_only``. + Returns :class:`~cabalspy_id.PlatformSettings`. + """ + _one_of(data_scope, DATA_SCOPES, "data_scope") + _one_of(wallet_trust, WALLET_TRUST, "wallet_trust") + _one_of(leaderboard_trust, WALLET_TRUST, "leaderboard_trust") + changes = { + k: v + for k, v in { + "white_label": white_label, + "data_scope": data_scope, + "wallet_trust": wallet_trust, + "leaderboard_trust": leaderboard_trust, + "claim_links": claim_links, + "telegram_alerts": telegram_alerts, + }.items() + if v is not None + } + if not changes: + raise BadRequestError("Pass at least one setting.", code="missing_parameter", parameter="settings") + return self._post("/platform-users/settings", changes) + + def platform_inbound(self) -> Any: + """GET /v1/platform-users/inbound — whether the inbound URL is on, its last event and + the payload formats it understands. Returns :class:`~cabalspy_id.PlatformInboundStatus`. + """ + return self._get("/platform-users/inbound") + + def enable_platform_inbound(self) -> Any: + """POST /v1/platform-users/inbound/enable — a new secret inbound URL for sign-up events + from your platform or its auth provider (Privy, Dynamic, ...). Shown once; calling + again replaces it. Returns :class:`~cabalspy_id.PlatformInboundEnabled`. + """ + return self._post("/platform-users/inbound/enable", {}) + + def disable_platform_inbound(self) -> Any: + """POST /v1/platform-users/inbound/disable. Returns ``{"enabled": False}``.""" + return self._post("/platform-users/inbound/disable", {}) + + def platform_user_session(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/session — a 15-minute token for the embeddable verify widget. + + Returns :class:`~cabalspy_id.PlatformSession`. + """ + return self._post("/platform-users/session", _who(external_id, csid_id)) + + def platform_user_claim_link( + self, external_id: str | None = None, *, return_url: str | None = None, csid_id: str | None = None + ) -> Any: + """POST /v1/platform-users/claim-link — a 24-hour link that lets the person take the account + into their own CabalSpy ID. ``return_url`` must be on your verified domains or registered + origins. Off with ``white_label`` unless ``claim_links`` is on (``claim_disabled``). + + Returns :class:`~cabalspy_id.PlatformClaimLink`. + """ + body = _who(external_id, csid_id) + if return_url: + body["return_url"] = return_url + return self._post("/platform-users/claim-link", body) + + def connect_platform_user_x( + self, external_id: str | None = None, *, return_url: str, csid_id: str | None = None + ) -> Any: + """POST /v1/platform-users/x/connect — a 10-minute ``authorize_url`` that connects the + user's X account, then returns to ``return_url``. Returns :class:`~cabalspy_id.PlatformXConnect`. + """ + _required(return_url, "return_url") + return self._post("/platform-users/x/connect", {**_who(external_id, csid_id), "return_url": return_url}) + + def disconnect_platform_user_x(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/x/disconnect. Not possible with the KOL badge (``kol_badge``). + + Returns :class:`~cabalspy_id.PlatformXDisconnect`. + """ + return self._post("/platform-users/x/disconnect", _who(external_id, csid_id)) + + def link_platform_user_telegram(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/telegram/link — a t.me ``deep_link`` that links the user's Telegram. + + Returns :class:`~cabalspy_id.PlatformTelegramLink`. + """ + return self._post("/platform-users/telegram/link", _who(external_id, csid_id)) + + def platform_user_telegram(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """GET /v1/platform-users/telegram. Returns :class:`~cabalspy_id.PlatformTelegramStatus`.""" + return self._get("/platform-users/telegram", _who(external_id, csid_id)) + + def unlink_platform_user_telegram(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/telegram/unlink. Returns ``{"external_id", "linked": False}``.""" + return self._post("/platform-users/telegram/unlink", _who(external_id, csid_id)) + + def platform_user_kol(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """GET /v1/platform-users/kol — badge, eligibility criteria, 7-day volume and application. + + Returns :class:`~cabalspy_id.PlatformKolStatus`. + """ + return self._get("/platform-users/kol", _who(external_id, csid_id)) + + def request_platform_user_volume_check(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/kol/volume-check — queues an on-chain volume check (202). + + Returns :class:`~cabalspy_id.PlatformKolVolumeCheck`. + """ + return self._post("/platform-users/kol/volume-check", _who(external_id, csid_id)) + + def apply_platform_user_kol(self, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/platform-users/kol/apply — applies for the KOL badge (needs X: ``x_required``; + ``kol_not_eligible`` lists the criteria in ``body``). Returns :class:`~cabalspy_id.PlatformKolApply`. + """ + return self._post("/platform-users/kol/apply", _who(external_id, csid_id)) + + # ── trading competitions ───────────────────────────────────────────── + # Between your platform users; at most 5 scheduled + running at a time per account. + + def create_competition( + self, + *, + name: str, + chain: Chain, + metric: CompetitionMetric, + duration_hours: float, + starts_at: str | datetime | _NotGiven | None = NOT_GIVEN, + min_participants: int | _NotGiven = NOT_GIVEN, + max_participants: int | _NotGiven | None = NOT_GIVEN, + min_trades: int | _NotGiven = NOT_GIVEN, + min_volume_usd: float | _NotGiven = NOT_GIVEN, + wallet_trust: WalletTrust | _NotGiven = NOT_GIVEN, + enrollment: CompetitionEnrollment | _NotGiven = NOT_GIVEN, + late_join: bool | _NotGiven = NOT_GIVEN, + prizes: Any = NOT_GIVEN, + description: str | _NotGiven | None = NOT_GIVEN, + ) -> Any: + """POST /v1/competitions — a trading competition between your platform users. + + It starts at ``starts_at`` (or at once) once ``min_participants`` joined, then runs + ``duration_hours`` (1-8760). ``enrollment="all_users"`` enters every platform user. + Traders below ``min_trades`` / ``min_volume_usd`` are listed but not ranked. + Returns :class:`~cabalspy_id.CompetitionDetail`. + """ + _required(name, "name") + _required(chain, "chain") + _required(metric, "metric") + _required(duration_hours, "duration_hours") + body = _competition_fields( + name=name, + chain=chain, + metric=metric, + duration_hours=duration_hours, + starts_at=starts_at, + min_participants=min_participants, + max_participants=max_participants, + min_trades=min_trades, + min_volume_usd=min_volume_usd, + wallet_trust=wallet_trust, + enrollment=enrollment, + late_join=late_join, + prizes=prizes, + description=description, + ) + return self._post("/competitions", body) + + def competitions( + self, *, status: CompetitionStatus | None = None, limit: int | None = None, offset: int | None = None + ) -> Any: + """GET /v1/competitions — your competitions, newest first (``limit`` 1-500, default 50). + + Returns a list of :class:`~cabalspy_id.Competition`; see ``iter_competitions``. + """ + _one_of(status, COMPETITION_STATUSES, "status") + return self._get("/competitions", {"status": status, "limit": limit, "offset": offset}) + + def competition(self, id: str) -> Any: + """GET /v1/competitions/detail — one competition with every rule change. + + Returns :class:`~cabalspy_id.CompetitionDetail`. + """ + _required(id, "id") + return self._get("/competitions/detail", {"id": id}) + + def update_competition( + self, + id: str, + *, + note: str | None = None, + name: str | _NotGiven = NOT_GIVEN, + chain: Chain | _NotGiven = NOT_GIVEN, + metric: CompetitionMetric | _NotGiven = NOT_GIVEN, + duration_hours: float | _NotGiven = NOT_GIVEN, + starts_at: str | datetime | _NotGiven | None = NOT_GIVEN, + min_participants: int | _NotGiven = NOT_GIVEN, + max_participants: int | _NotGiven | None = NOT_GIVEN, + min_trades: int | _NotGiven = NOT_GIVEN, + min_volume_usd: float | _NotGiven = NOT_GIVEN, + wallet_trust: WalletTrust | _NotGiven = NOT_GIVEN, + enrollment: CompetitionEnrollment | _NotGiven = NOT_GIVEN, + late_join: bool | _NotGiven = NOT_GIVEN, + prizes: Any = NOT_GIVEN, + description: str | _NotGiven | None = NOT_GIVEN, + ) -> Any: + """POST /v1/competitions/update — changes any rule, at any time (also while running). + + Every change is recorded (``changes``, ``rules_version``) and sent as the webhook + ``competition.updated``; ``note`` (max 500 characters) explains it. Pass ``None`` to + clear ``starts_at``, ``max_participants``, ``prizes`` or ``description``. + Returns :class:`~cabalspy_id.CompetitionDetail`. + """ + _required(id, "id") + fields = _competition_fields( + name=name, + chain=chain, + metric=metric, + duration_hours=duration_hours, + starts_at=starts_at, + min_participants=min_participants, + max_participants=max_participants, + min_trades=min_trades, + min_volume_usd=min_volume_usd, + wallet_trust=wallet_trust, + enrollment=enrollment, + late_join=late_join, + prizes=prizes, + description=description, + ) + if not fields: + raise BadRequestError("Pass at least one field to change.", code="missing_parameter", parameter="fields") + body: dict[str, Any] = {"id": id, **fields} + if note is not None: + body["note"] = note + return self._post("/competitions/update", body) + + def cancel_competition(self, id: str) -> Any: + """POST /v1/competitions/cancel. Returns :class:`~cabalspy_id.CompetitionDetail`.""" + _required(id, "id") + return self._post("/competitions/cancel", {"id": id}) + + def join_competition(self, id: str, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/competitions/join — enters one of your users (``already`` True if they were in). + + Returns :class:`~cabalspy_id.CompetitionMembership`. + """ + _required(id, "id") + return self._post("/competitions/join", {"id": id, **_who(external_id, csid_id)}) + + def leave_competition(self, id: str, external_id: str | None = None, *, csid_id: str | None = None) -> Any: + """POST /v1/competitions/leave — removes one of your users (``left`` False if they were not in). + + Returns :class:`~cabalspy_id.CompetitionMembership`. + """ + _required(id, "id") + return self._post("/competitions/leave", {"id": id, **_who(external_id, csid_id)}) + + def competition_participants(self, id: str, *, limit: int | None = None, offset: int | None = None) -> Any: + """GET /v1/competitions/participants — in join order (``limit`` 1-1000, default 100). + + Returns a list of :class:`~cabalspy_id.CompetitionParticipant`. + """ + _required(id, "id") + return self._get("/competitions/participants", {"id": id, "limit": limit, "offset": offset}) + + def competition_standings(self, id: str, *, limit: int | None = None, offset: int | None = None) -> Any: + """GET /v1/competitions/standings — ranked traders first, then the unranked (below the + minimums). Updated every 5 minutes; ``final`` once the competition ended. + + Returns :class:`~cabalspy_id.CompetitionStandings`. + """ + _required(id, "id") + return self._get("/competitions/standings", {"id": id, "limit": limit, "offset": offset}) + # ═══════════════════════════════════════════════════════════════════════════ # CLIENTS @@ -597,14 +1236,24 @@ def _prepare( url = f"{self.base_url}{path if path.startswith('/') else '/' + path}" return url, query, headers - def _interpret(self, response: httpx.Response, path: str, method: str = "GET") -> Envelope: - """Turns an HTTP response into an Envelope, or raises the right error.""" - rate_limit = RateLimit( + def _rate_limit(self, response: httpx.Response) -> RateLimit: + self.last_rate_limit = RateLimit( _int_header(response.headers, "X-RateLimit-Limit"), _int_header(response.headers, "X-RateLimit-Remaining"), _int_header(response.headers, "X-RateLimit-Reset"), ) - self.last_rate_limit = rate_limit + return self.last_rate_limit + + def _interpret_text(self, response: httpx.Response, path: str) -> str: + """The body of a non-JSON answer (an SVG), or raises the API's error.""" + if response.status_code >= 400: + self._interpret(response, path) + self._rate_limit(response) + return response.text + + def _interpret(self, response: httpx.Response, path: str, method: str = "GET") -> Envelope: + """Turns an HTTP response into an Envelope, or raises the right error.""" + rate_limit = self._rate_limit(response) try: parsed: Any = response.json() if response.content else None except ValueError: @@ -705,6 +1354,18 @@ def close(self) -> None: def get_raw(self, path: str, params: Mapping[str, Any] | None = None, *, auth: bool = True) -> Envelope: """Any GET, returning the full envelope (data, pagination, meta, rate limit).""" + return self._send_get(path, params, auth, self._interpret) + + def get_text(self, path: str, params: Mapping[str, Any] | None = None) -> str: + """Any GET whose answer is not JSON (the verification QR code), as text.""" + return self._send_get(path, params, True, self._interpret_text) + + def _get_text(self, path: str, params: Mapping[str, Any] | None = None) -> Any: + return self.get_text(path, params) + + def _send_get( + self, path: str, params: Mapping[str, Any] | None, auth: bool, parse: Callable[[httpx.Response, str], _T] + ) -> _T: url, query, headers = self._prepare(path, params, auth) last: BaseException | None = None for attempt in range(self.max_retries + 1): @@ -716,7 +1377,7 @@ def get_raw(self, path: str, params: Mapping[str, Any] | None = None, *, auth: b last = self._connection_error(exc, path) continue try: - return self._interpret(response, path) + return parse(response, path) except CabalSpyIDError as exc: if is_retryable(exc) and attempt < self.max_retries: last = exc @@ -812,6 +1473,104 @@ def iter_thesis_replies( for page in self.pages("/theses/replies", {"id": id, "limit": limit, "csid_id": csid_id}): yield from page.data + # ── white-label ────────────────────────────────────────────────────── + + def bulk_import_platform_users( + self, + users: Iterable[PlatformUserInput], + *, + chunk_size: int = PLATFORM_IMPORT_MAX, + max_attempts: int = 5, + max_body_bytes: int = _IMPORT_BODY_BYTES, + ) -> PlatformBulkImportResult: + """Imports any number of users in chunks of at most ``chunk_size`` (1,000) users and + ``max_body_bytes``, and returns the aggregated results in input order. + + A chunk refused with 429 is sent again after a backoff (``Retry-After`` wins). + Users the server rejected with ``rate_limited`` (too many new users per minute) + are sent again on their own once the minute is over. A chunk that succeeded is + never sent again. Each chunk gets ``max_attempts`` rounds (on top of the client's + own ``max_retries`` for ``rate_limit_exceeded``); users still rate limited after + that stay ``rejected`` in the results. + + Any other error raises :class:`~cabalspy_id.PlatformImportError` with ``result`` + (what was imported) and ``remaining`` (the users to pass again to resume). + """ + run = _ImportRun(users, chunk_size, max_body_bytes, max_attempts) + for chunk_no, chunk in enumerate(run.chunks): + pending, attempt = chunk, 0 + while pending: + attempt += 1 + try: + data = self._post(_IMPORT_PATH, run.body(pending)) + except RateLimitError as exc: + if attempt >= max_attempts: + raise run.failed(exc, chunk_no, pending) from exc + time.sleep(_backoff(attempt, exc)) + continue + except CabalSpyIDError as exc: + raise run.failed(exc, chunk_no, pending) from exc + pending = run.record(pending, data) + if pending and attempt >= max_attempts: + break + if pending: + time.sleep(_import_wait()) + return run.result() # type: ignore[return-value] + + def iter_platform_users(self, *, limit: int | None = None) -> Iterator[dict[str, Any]]: + """Every platform user of your instance, newest first, following ``next_cursor``.""" + for page in self.pages("/platform-users/list", {"limit": limit}): + yield from page.data + + def iter_platform_leaderboard( + self, + *, + blockchain: Chain, + period: Period | None = None, + sort: LeaderboardSort | None = None, + limit: int | None = None, + trust: LeaderboardTrust | None = None, + ) -> Iterator[dict[str, Any]]: + """Every entry of the platform leaderboard, following ``next_cursor``.""" + query = _platform_leaderboard_query(blockchain, period, sort, trust, limit, None) + for page in self.pages("/platform-users/leaderboard", query): + yield from page.data.get("leaderboard", []) + + def offset_items( + self, path: str, params: Mapping[str, Any] | None = None, *, key: str | None = None + ) -> Iterator[Any]: + """Walks an offset-paginated route (competitions) until ``pagination.total`` is reached. + + ``key``: the list inside ``data`` (e.g. ``"standings"``); None when ``data`` is the list. + """ + query = dict(params or {}) + offset = int(query.pop("offset", None) or 0) + while True: + page = self.get_raw(path, {**query, "offset": offset or None}) + items = page.data if key is None else page.data.get(key, []) + yield from items + offset += len(items) + total = (page.pagination or {}).get("total") + if not items or total is None or offset >= total: + return + + def iter_competitions( + self, *, status: CompetitionStatus | None = None, limit: int | None = None + ) -> Iterator[dict[str, Any]]: + """Every competition of your instance, newest first.""" + _one_of(status, COMPETITION_STATUSES, "status") + yield from self.offset_items("/competitions", {"status": status, "limit": limit}) + + def iter_competition_participants(self, id: str, *, limit: int | None = None) -> Iterator[dict[str, Any]]: + """Every participant of a competition, in join order.""" + _required(id, "id") + yield from self.offset_items("/competitions/participants", {"id": id, "limit": limit}) + + def iter_competition_standings(self, id: str, *, limit: int | None = None) -> Iterator[dict[str, Any]]: + """Every trader of a competition's standings: ranked first, then the unranked.""" + _required(id, "id") + yield from self.offset_items("/competitions/standings", {"id": id, "limit": limit}, key="standings") + class AsyncCabalSpyID(_BaseClient): """Asynchronous Data API client. @@ -841,6 +1600,18 @@ async def aclose(self) -> None: async def get_raw(self, path: str, params: Mapping[str, Any] | None = None, *, auth: bool = True) -> Envelope: """Any GET, returning the full envelope (data, pagination, meta, rate limit).""" + return await self._send_get(path, params, auth, self._interpret) + + async def get_text(self, path: str, params: Mapping[str, Any] | None = None) -> str: + """Async version of :meth:`CabalSpyID.get_text`.""" + return await self._send_get(path, params, True, self._interpret_text) + + async def _get_text(self, path: str, params: Mapping[str, Any] | None = None) -> Any: + return await self.get_text(path, params) + + async def _send_get( + self, path: str, params: Mapping[str, Any] | None, auth: bool, parse: Callable[[httpx.Response, str], _T] + ) -> _T: url, query, headers = self._prepare(path, params, auth) last: BaseException | None = None for attempt in range(self.max_retries + 1): @@ -852,7 +1623,7 @@ async def get_raw(self, path: str, params: Mapping[str, Any] | None = None, *, a last = self._connection_error(exc, path) continue try: - return self._interpret(response, path) + return parse(response, path) except CabalSpyIDError as exc: if is_retryable(exc) and attempt < self.max_retries: last = exc @@ -949,6 +1720,97 @@ async def iter_thesis_replies( for item in page.data: yield item + # ── white-label ────────────────────────────────────────────────────── + + async def bulk_import_platform_users( + self, + users: Iterable[PlatformUserInput], + *, + chunk_size: int = PLATFORM_IMPORT_MAX, + max_attempts: int = 5, + max_body_bytes: int = _IMPORT_BODY_BYTES, + ) -> PlatformBulkImportResult: + """Async version of :meth:`CabalSpyID.bulk_import_platform_users`.""" + run = _ImportRun(users, chunk_size, max_body_bytes, max_attempts) + for chunk_no, chunk in enumerate(run.chunks): + pending, attempt = chunk, 0 + while pending: + attempt += 1 + try: + data = await self._post(_IMPORT_PATH, run.body(pending)) + except RateLimitError as exc: + if attempt >= max_attempts: + raise run.failed(exc, chunk_no, pending) from exc + await asyncio.sleep(_backoff(attempt, exc)) + continue + except CabalSpyIDError as exc: + raise run.failed(exc, chunk_no, pending) from exc + pending = run.record(pending, data) + if pending and attempt >= max_attempts: + break + if pending: + await asyncio.sleep(_import_wait()) + return run.result() # type: ignore[return-value] + + async def iter_platform_users(self, *, limit: int | None = None) -> AsyncIterator[dict[str, Any]]: + """Every platform user of your instance, newest first, following ``next_cursor``.""" + async for page in self.pages("/platform-users/list", {"limit": limit}): + for user in page.data: + yield user + + async def iter_platform_leaderboard( + self, + *, + blockchain: Chain, + period: Period | None = None, + sort: LeaderboardSort | None = None, + limit: int | None = None, + trust: LeaderboardTrust | None = None, + ) -> AsyncIterator[dict[str, Any]]: + """Every entry of the platform leaderboard, following ``next_cursor``.""" + query = _platform_leaderboard_query(blockchain, period, sort, trust, limit, None) + async for page in self.pages("/platform-users/leaderboard", query): + for entry in page.data.get("leaderboard", []): + yield entry + + async def offset_items( + self, path: str, params: Mapping[str, Any] | None = None, *, key: str | None = None + ) -> AsyncIterator[Any]: + """Async version of :meth:`CabalSpyID.offset_items`.""" + query = dict(params or {}) + offset = int(query.pop("offset", None) or 0) + while True: + page = await self.get_raw(path, {**query, "offset": offset or None}) + items = page.data if key is None else page.data.get(key, []) + for item in items: + yield item + offset += len(items) + total = (page.pagination or {}).get("total") + if not items or total is None or offset >= total: + return + + async def iter_competitions( + self, *, status: CompetitionStatus | None = None, limit: int | None = None + ) -> AsyncIterator[dict[str, Any]]: + """Every competition of your instance, newest first.""" + _one_of(status, COMPETITION_STATUSES, "status") + async for item in self.offset_items("/competitions", {"status": status, "limit": limit}): + yield item + + async def iter_competition_participants( + self, id: str, *, limit: int | None = None + ) -> AsyncIterator[dict[str, Any]]: + """Every participant of a competition, in join order.""" + _required(id, "id") + async for item in self.offset_items("/competitions/participants", {"id": id, "limit": limit}): + yield item + + async def iter_competition_standings(self, id: str, *, limit: int | None = None) -> AsyncIterator[dict[str, Any]]: + """Every trader of a competition's standings: ranked first, then the unranked.""" + _required(id, "id") + async for item in self.offset_items("/competitions/standings", {"id": id, "limit": limit}, key="standings"): + yield item + def _users_query(params: Mapping[str, Any]) -> dict[str, Any]: allowed = {"limit", "kol", "cursor", "scope"} diff --git a/cabalspy_id/_constants.py b/cabalspy_id/_constants.py index 218c144..af38275 100644 --- a/cabalspy_id/_constants.py +++ b/cabalspy_id/_constants.py @@ -4,7 +4,7 @@ from typing import Literal -SDK_VERSION = "0.5.2" +SDK_VERSION = "0.6.0" USER_AGENT = f"cabalspy-id-python/{SDK_VERSION}" DEFAULT_BASE_URL = "https://api-id.cabalspy.xyz/v1" @@ -40,6 +40,21 @@ "rh": "ETH", } +#: Webhook events about platform users (white-label). ``data.sub`` is the user's csid_id. +PLATFORM_WEBHOOK_EVENTS: tuple[str, ...] = ( + "platform_user.created", + "platform_user.claimed", + "platform_user.x_connected", + "wallet.added", + "verification.expired", +) +#: Webhook events about trading competitions. Sent per instance, not per user. +COMPETITION_WEBHOOK_EVENTS: tuple[str, ...] = ( + "competition.started", + "competition.updated", + "competition.standings", + "competition.ended", +) #: Webhook event types. WEBHOOK_EVENTS: tuple[str, ...] = ( "wallet.verified", @@ -51,6 +66,8 @@ "thesis.reply", "thesis.reaction", "webhook.test", + *PLATFORM_WEBHOOK_EVENTS, + *COMPETITION_WEBHOOK_EVENTS, ) #: Reactions: "like" plus a fixed emoji set. @@ -68,3 +85,39 @@ DEFAULT_THESIS_WS_URL = "wss://id.cabalspy.xyz/thesis/v1/ws" #: Header that carries the instance's public client_id on every public thesis API call. CLIENT_ID_HEADER = "X-CSID-Client-Id" + +# ── white-label: platform users ────────────────────────────────────────────── + +#: Users per POST /v1/platform-users/import call. +PLATFORM_IMPORT_MAX = 1000 +#: Wallets per user in one create / import item / wallets-add call. +PLATFORM_MAX_WALLETS_PER_REQUEST = 10 +#: The server rejects request bodies above 1 MB; bulk imports stay below this. +MAX_REQUEST_BODY_BYTES = 1_000_000 +#: all: imported (unverified) wallets count; verified_only: only payment-verified ones. +WalletTrust = Literal["all", "verified_only"] +WALLET_TRUST: tuple[WalletTrust, ...] = ("all", "verified_only") +#: csid: part of the CabalSpy ID network (default); platform: only your platform sees its users. +DataScope = Literal["csid", "platform"] +DATA_SCOPES: tuple[DataScope, ...] = ("csid", "platform") +#: ``trust`` filter of the platform leaderboard: it can only narrow the instance setting. +LeaderboardTrust = Literal["all", "verified"] +#: Trust status of a platform user's wallet. +PlatformWalletStatus = Literal["verified", "active", "needs_verification", "verified_elsewhere", "pending"] +PlatformImportStatus = Literal["created", "updated", "unchanged", "rejected"] +VerificationStatus = Literal["pending", "verified", "cancelled", "expired"] +#: Payload formats the inbound URL understands. +INBOUND_FORMATS: tuple[str, ...] = ("csid", "privy", "dynamic", "generic") + +# ── trading competitions ───────────────────────────────────────────────────── + +CompetitionMetric = Literal["pnl_usd", "pnl", "volume_usd", "volume", "trades", "win_rate"] +COMPETITION_METRICS: tuple[CompetitionMetric, ...] = ("pnl_usd", "pnl", "volume_usd", "volume", "trades", "win_rate") +#: waiting: the start time passed, but fewer than min_participants joined. +CompetitionStatus = Literal["scheduled", "waiting", "running", "ended", "cancelled"] +COMPETITION_STATUSES: tuple[CompetitionStatus, ...] = ("scheduled", "waiting", "running", "ended", "cancelled") +#: opt_in: users join through the API; all_users: every platform user of the instance takes part. +CompetitionEnrollment = Literal["opt_in", "all_users"] +COMPETITION_ENROLLMENTS: tuple[CompetitionEnrollment, ...] = ("opt_in", "all_users") +#: Scheduled + running competitions at a time per developer account. +MAX_OPEN_COMPETITIONS = 5 diff --git a/cabalspy_id/_errors.py b/cabalspy_id/_errors.py index fa58b27..e180086 100644 --- a/cabalspy_id/_errors.py +++ b/cabalspy_id/_errors.py @@ -79,7 +79,8 @@ def __str__(self) -> str: class BadRequestError(CabalSpyIDError): - """400 — missing_parameter, invalid_parameter, instance_required.""" + """400 — missing_parameter, invalid_parameter, instance_required; platform users: + wallet_required, invalid_address, invalid_return_url, invalid_body.""" class AuthenticationError(CabalSpyIDError): @@ -88,25 +89,41 @@ class AuthenticationError(CabalSpyIDError): class PermissionError_(CabalSpyIDError): """403 — invalid_api_key, product_not_enabled, no_instance, scope_not_allowed; - public thesis API: origin_not_allowed.""" + public thesis API: origin_not_allowed; platform users: claim_disabled.""" class PlanUserLimitError(PermissionError_): """403 — plan_user_limit. The person signed in beyond the plan's user limit: the platform receives no - data for them until it upgrades. + data for them until it upgrades. Creating a platform user beyond the limit + raises it too; ``body`` then carries ``user_limit`` (and ``users``, ``plan`` + on live instances). """ limited = True class NotFoundError(CabalSpyIDError): - """404 — profile_not_found, wallet_not_found, instance_not_found.""" + """404 — profile_not_found, wallet_not_found, instance_not_found; platform users: + platform_user_not_found, verification_not_found, invalid_inbound_url; + competitions: competition_not_found.""" + + +class ConflictError(CabalSpyIDError): + """409 — the request conflicts with the current state. + + Platform users: account_claimed, last_wallet, too_many_wallets, + wallet_already_verified, already_verified, kol_badge, x_required, + kol_not_eligible, volume_check_unavailable. Competitions: competition_limit, + competition_closed, competition_full, late_join_closed. + """ class RateLimitError(CabalSpyIDError): - """429 — rate_limit_exceeded; public thesis API: rate_limited (Retry-After 60).""" + """429 — rate_limit_exceeded; public thesis API: rate_limited (Retry-After 60); + platform users: rate_limited (new users or inbound events per minute), + too_many_open_verifications.""" def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None: super().__init__(message, **kwargs) @@ -147,6 +164,21 @@ class WebhookVerificationError(CabalSpyIDError): """A webhook failed signature or timestamp verification.""" +class PlatformImportError(CabalSpyIDError): + """A bulk import stopped before every user was sent. + + ``result`` holds the results of the users that were imported (same shape as + the return value), ``remaining`` the users that were not; pass them to + ``bulk_import_platform_users`` again to resume. The error that stopped the + import is ``__cause__`` (its ``status`` and ``code`` are copied here). + """ + + def __init__(self, message: str, *, result: dict[str, Any], remaining: list[dict[str, Any]], **kwargs: Any) -> None: + super().__init__(message, **kwargs) + self.result = result + self.remaining = remaining + + def error_from_status( status: int, body: dict[str, Any] | None, @@ -178,6 +210,8 @@ def error_from_status( return PermissionError_(message, **kwargs) if status == 404: return NotFoundError(message, **kwargs) + if status == 409: + return ConflictError(message, **kwargs) if status == 429: return RateLimitError(message, retry_after=retry_after, **kwargs) if status >= 500: diff --git a/cabalspy_id/_types.py b/cabalspy_id/_types.py index 3223135..2b23468 100644 --- a/cabalspy_id/_types.py +++ b/cabalspy_id/_types.py @@ -13,7 +13,21 @@ from typing import Any, Literal, TypedDict -from ._constants import Chain, Currency, LeaderboardSort, Period, Scope +from ._constants import ( + Chain, + CompetitionEnrollment, + CompetitionMetric, + CompetitionStatus, + Currency, + DataScope, + LeaderboardSort, + Period, + PlatformImportStatus, + PlatformWalletStatus, + Scope, + VerificationStatus, + WalletTrust, +) # ── envelope ───────────────────────────────────────────────────────────────── @@ -564,7 +578,10 @@ class WebhookEvent(TypedDict): type: str created_at: str sandbox: bool - #: Always carries "sub" (the user's CabalSpy ID), except for webhook.test. + #: Carries "sub" (the user's CabalSpy ID), except for webhook.test and the + #: instance-level competition.* events (those carry "competition_id"). + #: Events about one of your platform users (white-label) also carry + #: "external_id" (your own user id) and "csid_id". data: dict[str, Any] @@ -708,3 +725,486 @@ class ThesisNotices(TypedDict): class ThesisReactions(TypedDict): id: str reactions: dict[str, int] + + +# ── white-label: platform users ────────────────────────────────────────────── +# A platform that keeps its own login manages its users by its own user id +# (``external_id``). Responses below come from /v1/platform-users/*. + + +class PlatformWalletInput(TypedDict, total=False): + """A wallet you submit for a platform user (no payment verification). + + Plain address strings work too. Default ``chains``: solana for a Solana + address, every enabled EVM chain for an EVM address. + """ + + address: str + chains: list[Chain] + #: Where the wallet comes from, e.g. "privy" (1-40 characters a-z 0-9 _ . -). + source: str + + +class PlatformUserInput(TypedDict, total=False): + """One user of an import. ``external_id`` always, ``wallets`` for new users.""" + + #: Your own user id: 1-128 printable ASCII characters, no spaces. + external_id: str + #: 1-10 wallets (objects or plain address strings). + wallets: list[PlatformWalletInput | str] + #: 1-60 characters, or None to clear. + display_name: str | None + #: An https URL (max 500 characters), or None to clear. + avatar_url: str | None + + +class PlatformWallet(TypedDict): + address: str + #: "solana" or "evm". + family: str + chains: list[Chain] + #: Payment-verified on at least one chain. + verified: bool + verified_chains: list[Chain] + status: PlatformWalletStatus + #: Whether the wallet counts for tracking, data and leaderboards. + counts: bool + source: str | None + verified_at: str | None + added_at: str | None + + +class WalletAdded(TypedDict): + """A wallet (or new chains of it) added by the platform.""" + + address: str + family: str + chains: list[Chain] + source: str | None + + +class WalletVerification(TypedDict): + """A payment verification of a wallet, started by the platform.""" + + verification_id: str + status: VerificationStatus + chain: Chain + chain_name: str + address: str + #: Amount to send, formatted in the chain's currency. + amount: str + #: Amount in base units (lamports / wei), as a string. + amount_base: str + currency: str + decimals: int + receiver: str + expires_at: str + seconds_left: int + #: solana:... or ethereum:...@chainId URI for wallets and QR codes. + payment_uri: str + evm_chain_id: int | None + instructions: str + tx_hash: str | None + explorer_url: str | None + created_at: str | None + + +class PlatformWalletVerification(WalletVerification): + """The verification endpoints' answer: the verification plus whose it is.""" + + external_id: str + + +class PlatformUserX(TypedDict): + id: str + username: str + name: str | None + avatar_url: str | None + followers: int | None + following: int | None + verified: bool | None + verified_type: str | None + created_at: str | None + url: str + + +class PlatformUserTelegram(TypedDict): + username: str | None + name: str | None + linked_at: str | None + + +class PlatformUser(TypedDict): + """One platform user (no trading data; see :class:`PlatformUserProfile`).""" + + csid_id: str + external_id: str + #: True once the person took the account into their own CabalSpy ID (claim link). + claimed: bool + claimed_at: str | None + managed: bool + display_name: str | None + avatar_url: str | None + #: Beyond the plan's user limit: no data until the platform upgrades. + limited: bool + x: PlatformUserX | None + telegram: PlatformUserTelegram | None + kol: KolBadge + wallets: list[PlatformWallet] + pending_verifications: list[WalletVerification] + created_at: str | None + + +class PlatformUserUpsert(PlatformUser): + """POST /v1/platform-users: the user plus what this call changed.""" + + created: bool + wallets_added: list[WalletAdded] + + +class PlatformWalletsResponse(TypedDict): + external_id: str + wallets_added: list[WalletAdded] + wallets: list[PlatformWallet] + + +class PlatformItemError(TypedDict): + code: str + message: str + + +class PlatformImportItem(TypedDict, total=False): + external_id: str | None + #: Absent for rejected items. + csid_id: str + status: PlatformImportStatus + wallets_added: list[WalletAdded] + #: Only for rejected items (plan_user_limit, wallet_required, rate_limited, ...). + error: PlatformItemError + + +class PlatformImportSummary(TypedDict): + created: int + updated: int + unchanged: int + rejected: int + + +class PlatformImportResult(TypedDict): + summary: PlatformImportSummary + #: One result per submitted user, in the same order. + results: list[PlatformImportItem] + + +class PlatformBulkImportResult(PlatformImportResult): + """The aggregated result of ``bulk_import_platform_users``.""" + + #: Import calls made (chunks plus retries). + requests: int + + +class PlatformUserDeleted(TypedDict): + external_id: str + #: False for claimed users: only the link to your platform goes. + deleted: bool + unlinked: bool + + +class PlatformWalletRemoved(TypedDict): + external_id: str + address: str + removed: bool + + +class PlatformInbound(TypedDict): + enabled: bool + last_event_at: str | None + + +class PlatformInboundStatus(PlatformInbound): + #: Payload formats the inbound URL understands (csid, privy, dynamic, generic). + formats: list[str] + + +class PlatformInboundEnabled(TypedDict): + enabled: bool + #: The secret inbound URL. Shown once; enabling again replaces it. + url: str + note: str + + +class PlatformSettings(TypedDict): + name: str + white_label: bool | None + data_scope: DataScope + #: The same as data_scope == "csid". + network_sharing: bool + wallet_trust: WalletTrust + leaderboard_trust: WalletTrust + claim_links: bool | None + telegram_alerts: bool | None + inbound: PlatformInbound + + +class PlatformSession(TypedDict): + external_id: str + client_id: str + #: pvs_... token for the embeddable verify widget. + session: str + expires_at: str + expires_in: int + + +class PlatformClaimLink(TypedDict): + external_id: str + url: str + expires_at: str + + +class PlatformXConnect(TypedDict): + external_id: str + #: Send the user here to connect X; they come back to ``return_url``. + authorize_url: str + expires_at: str + + +class PlatformXDisconnect(TypedDict): + external_id: str + disconnected: bool + + +class PlatformTelegramLink(TypedDict): + external_id: str + code: str + #: t.me deep link that links the user's Telegram. + deep_link: str + expires_at: str | None + + +class PlatformTelegramStatus(TypedDict): + external_id: str + linked: bool + username: str | None + linked_at: str | None + + +class KolApplicationStatus(TypedDict): + status: str + applied_at: str | None + reviewed_at: str | None + + +class PlatformKolStatus(TypedDict): + external_id: str + badge: bool + eligible: bool + criteria: list[dict[str, Any]] + volume_7d_usd: float | None + volume_check_next_at: str | None + application: KolApplicationStatus | None + + +class PlatformKolVolumeCheck(TypedDict): + external_id: str + queued: bool + + +class PlatformKolApply(TypedDict): + external_id: str + application: Literal["pending"] + + +class PlatformTradingWallet(TypedDict, total=False): + """Period stats of one wallet (the leaderboard ``period_stats`` fields plus these).""" + + address: str + verified: bool + win_rate_percentage: float + total_volume_usd: float + realized_pnl_usd: float + total_txn: int + + +class PlatformTrading(TypedDict): + """A user's trading on one chain, summed over their wallets that count.""" + + blockchain: Chain + currency: Currency + period: Period + total_buy: float + total_buy_usd: float + total_sell: float + total_sell_usd: float + total_volume: float + total_volume_usd: float + realized_pnl: float + realized_pnl_usd: float + total_txn: int + buy_txn: int + sell_txn: int + win_count: int + closed_count: int + win_rate_percentage: float + tokens: int + wallets: list[PlatformTradingWallet] + + +class PlatformProfileLinks(TypedDict): + blockchain: Chain + address: str + tracker: str + history: str + holdings: str + pnl_calendar: str + + +class PlatformUserProfile(PlatformUser): + """GET /v1/platform-users/profile: everything for a profile page in one call. + + ``kol`` additionally carries ``application`` ({status, applied_at, note} or None). + """ + + period: Period + trading: list[PlatformTrading] + #: Newest 20 trades (the :class:`Trade` fields without ``trader``). + recent_trades: list[dict[str, Any]] + #: {"total": int, "latest": [Thesis, ...]} + theses: dict[str, Any] + #: {"traders": int, "in_trade_feeds": int} + trade_feed: dict[str, int] + links: list[PlatformProfileLinks] + + +class PlatformLeaderboardEntry(LeaderboardEntry): + external_id: str | None + #: The wallet is payment-verified on this chain. + verified: bool + + +class PlatformLeaderboardResponse(TypedDict): + """GET /v1/platform-users/leaderboard. Pagination is in the envelope.""" + + blockchain: Chain + period: Period + sort: LeaderboardSort + currency: Currency + #: "verified" when only payment-verified wallets are ranked. + trust: Literal["all", "verified"] + leaderboard: list[PlatformLeaderboardEntry] + + +class InboundEventResult(TypedDict, total=False): + """What the inbound URL answers to a sign-up event.""" + + accepted: bool + #: created | updated | deleted | wallets_removed | ignored | unknown_user | waiting_for_wallet + result: str + external_id: str + csid_id: str + wallets_added: list[WalletAdded] + #: wallets_removed: the addresses removed, and {address, code} for each one kept + wallets_removed: list[str] + wallets_not_removed: list[dict[str, str]] + #: ignored: why (wallet removals from auth providers are not applied) + note: str + error: PlatformItemError + + +# ── trading competitions ───────────────────────────────────────────────────── + + +class CompetitionChange(TypedDict): + rules_version: int + changed_at: str | None + #: The phase the change happened in (scheduled, running). + during: str + #: {field: {"from": old, "to": new}} + changes: dict[str, dict[str, Any]] + note: str | None + + +class Competition(TypedDict): + """A competition as listed (GET /v1/competitions).""" + + id: str + name: str + description: str | None + chain: Chain + chain_name: str + metric: CompetitionMetric + wallet_trust: WalletTrust + enrollment: CompetitionEnrollment + status: CompetitionStatus + starts_at: str | None + duration_hours: float + started_at: str | None + ends_at: str | None + ended_at: str | None + min_participants: int + max_participants: int | None + participants: int + min_trades: int + min_volume_usd: float + late_join: bool + prizes: Any + rules_version: int + standings_updated_at: str | None + created_at: str | None + updated_at: str | None + + +class CompetitionDetail(Competition): + """Create, detail and update: the competition plus every rule change.""" + + changes: list[CompetitionChange] + changed_while_running: bool + + +class CompetitionParticipant(TypedDict): + external_id: str | None + csid_id: str + joined_at: str | None + + +class CompetitionStanding(TypedDict, total=False): + """One trader. Unranked traders (below the minimums) have ``rank`` None.""" + + rank: int | None + ranked: bool + external_id: str | None + csid_id: str + #: The value of the competition's metric. + score: float + pnl: float + pnl_usd: float + volume: float + volume_usd: float + trades: int + buys: int + sells: int + win_count: int + closed_count: int + win_rate: float + tokens: int + wallets: int + + +class CompetitionStandings(TypedDict): + competition_id: str + status: CompetitionStatus + metric: CompetitionMetric + rules_version: int + updated_at: str | None + #: True once the competition ended: these are the results. + final: bool + standings: list[CompetitionStanding] + + +class CompetitionMembership(TypedDict, total=False): + competition_id: str + external_id: str + #: join: True; ``already`` says whether the user was in before. + joined: bool + already: bool + #: leave: whether the user was a participant. + left: bool diff --git a/cabalspy_id/api.py b/cabalspy_id/api.py index a71774b..2dfc5b1 100644 --- a/cabalspy_id/api.py +++ b/cabalspy_id/api.py @@ -1,6 +1,7 @@ """``cabalspy_id.api`` — the SocialFi API: Data API clients (users, profiles, -verified wallets, trading stats, leaderboards), the live trade stream, Login -with CabalSpy ID (OpenID Connect) and webhook verification. +verified wallets, trading stats, leaderboards, white-label platform users and +trading competitions), the live trade stream, Login with CabalSpy ID (OpenID +Connect) and webhook verification. from cabalspy_id.api import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -12,15 +13,27 @@ import cabalspy_id as _root from cabalspy_id import ( CHAINS, + COMPETITION_ENROLLMENTS, + COMPETITION_METRICS, + COMPETITION_STATUSES, + COMPETITION_WEBHOOK_EVENTS, CURRENCY_BY_CHAIN, + DATA_SCOPES, DEFAULT_BASE_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, + INBOUND_FORMATS, LEADERBOARD_SORTS, + MAX_OPEN_COMPETITIONS, + MAX_REQUEST_BODY_BYTES, PERIODS, + PLATFORM_IMPORT_MAX, + PLATFORM_MAX_WALLETS_PER_REQUEST, + PLATFORM_WEBHOOK_EVENTS, SCOPES, SDK_VERSION, STREAM_TOPICS, + WALLET_TRUST, WEBHOOK_EVENTS, ActiveHoldings, ActiveTokens, @@ -35,7 +48,19 @@ CabalSpyIDClaims, CabalSpyIDError, Chain, + Competition, + CompetitionChange, + CompetitionDetail, + CompetitionEnrollment, + CompetitionMembership, + CompetitionMetric, + CompetitionParticipant, + CompetitionStanding, + CompetitionStandings, + CompetitionStatus, + ConflictError, Currency, + DataScope, DiscoveryDocument, Envelope, HandleKind, @@ -46,10 +71,13 @@ HistoryTrade, HoldingsResponse, HoldingToken, + InboundEventResult, InvalidResponseError, + KolApplicationStatus, LeaderboardEntry, LeaderboardResponse, LeaderboardSort, + LeaderboardTrust, LifetimeStats, LoginResult, MeResponse, @@ -62,6 +90,44 @@ PermissionError, PkcePair, PlanUserLimitError, + PlatformBulkImportResult, + PlatformClaimLink, + PlatformImportError, + PlatformImportItem, + PlatformImportResult, + PlatformImportStatus, + PlatformImportSummary, + PlatformInbound, + PlatformInboundEnabled, + PlatformInboundStatus, + PlatformItemError, + PlatformKolApply, + PlatformKolStatus, + PlatformKolVolumeCheck, + PlatformLeaderboardEntry, + PlatformLeaderboardResponse, + PlatformProfileLinks, + PlatformSession, + PlatformSettings, + PlatformTelegramLink, + PlatformTelegramStatus, + PlatformTrading, + PlatformTradingWallet, + PlatformUser, + PlatformUserDeleted, + PlatformUserInput, + PlatformUserProfile, + PlatformUserTelegram, + PlatformUserUpsert, + PlatformUserX, + PlatformWallet, + PlatformWalletInput, + PlatformWalletRemoved, + PlatformWalletsResponse, + PlatformWalletStatus, + PlatformWalletVerification, + PlatformXConnect, + PlatformXDisconnect, PnlCalendarDay, PnlCalendarMonth, PnlCalendarResponse, @@ -81,9 +147,13 @@ Trade, TradeOwner, TraderProfile, + VerificationStatus, VerifiedWallet, + WalletAdded, WalletClaim, WalletLookupResponse, + WalletTrust, + WalletVerification, WebhookEvent, WebhookVerificationError, WinRateBuckets, @@ -135,6 +205,8 @@ "TokenVerificationError", "WebhookVerificationError", "RateLimit", + "ConflictError", + "PlatformImportError", # constants "CHAINS", "PERIODS", @@ -154,6 +226,27 @@ "Scope", "OidcScope", "StreamTopic", + "PLATFORM_IMPORT_MAX", + "PLATFORM_MAX_WALLETS_PER_REQUEST", + "MAX_REQUEST_BODY_BYTES", + "WALLET_TRUST", + "DATA_SCOPES", + "INBOUND_FORMATS", + "PLATFORM_WEBHOOK_EVENTS", + "COMPETITION_WEBHOOK_EVENTS", + "COMPETITION_METRICS", + "COMPETITION_STATUSES", + "COMPETITION_ENROLLMENTS", + "MAX_OPEN_COMPETITIONS", + "WalletTrust", + "DataScope", + "LeaderboardTrust", + "PlatformWalletStatus", + "PlatformImportStatus", + "VerificationStatus", + "CompetitionMetric", + "CompetitionStatus", + "CompetitionEnrollment", # response types "ResponseMeta", "Pagination", @@ -191,6 +284,53 @@ "TokenResponse", "DiscoveryDocument", "WebhookEvent", + # white-label and competitions + "PlatformWalletInput", + "PlatformUserInput", + "PlatformWallet", + "WalletAdded", + "WalletVerification", + "PlatformWalletVerification", + "PlatformUserX", + "PlatformUserTelegram", + "PlatformUser", + "PlatformUserUpsert", + "PlatformWalletsResponse", + "PlatformItemError", + "PlatformImportItem", + "PlatformImportSummary", + "PlatformImportResult", + "PlatformBulkImportResult", + "PlatformUserDeleted", + "PlatformWalletRemoved", + "PlatformInbound", + "PlatformInboundStatus", + "PlatformInboundEnabled", + "PlatformSettings", + "PlatformSession", + "PlatformClaimLink", + "PlatformXConnect", + "PlatformXDisconnect", + "PlatformTelegramLink", + "PlatformTelegramStatus", + "KolApplicationStatus", + "PlatformKolStatus", + "PlatformKolVolumeCheck", + "PlatformKolApply", + "PlatformTrading", + "PlatformTradingWallet", + "PlatformProfileLinks", + "PlatformUserProfile", + "PlatformLeaderboardEntry", + "PlatformLeaderboardResponse", + "InboundEventResult", + "Competition", + "CompetitionDetail", + "CompetitionChange", + "CompetitionParticipant", + "CompetitionStanding", + "CompetitionStandings", + "CompetitionMembership", ] diff --git a/examples/white_label.py b/examples/white_label.py new file mode 100644 index 0000000..f86aa4b --- /dev/null +++ b/examples/white_label.py @@ -0,0 +1,88 @@ +"""White-label tour: your own login, your users' wallets, leaderboards and competitions. + + CABALSPY_API_KEY=... python examples/white_label.py + +The key is your CabalSpy API key with "CabalSpy ID" enabled on the API keys page. +The users and wallets below are placeholders: replace them with your own. +""" + +from __future__ import annotations + +from typing import Any + +from cabalspy_id import CabalSpyID, ConflictError, PlanUserLimitError, PlatformImportError + +# Your platform's users, e.g. from your database and your wallet provider (Privy, Dynamic, ...) +MY_USERS: list[dict[str, Any]] = [ + {"id": "user_1", "name": "Alice", "wallets": ["7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"]}, + {"id": "user_2", "name": "Bob", "wallets": ["0x52908400098527886E0F7030069857D2E4169EE7"]}, +] + +with CabalSpyID() as csid: # reads CABALSPY_ID_API_KEY or CABALSPY_API_KEY + # Settings: count imported wallets, keep your users to yourself + settings = csid.update_platform_settings(wallet_trust="all", data_scope="platform") + print("settings:", settings["wallet_trust"], settings["data_scope"]) + + # 1. Import every user with the wallets they already have (chunks of 1,000, retries on 429) + try: + result = csid.bulk_import_platform_users( + {"external_id": u["id"], "display_name": u["name"], "wallets": u["wallets"]} for u in MY_USERS + ) + except PlatformImportError as err: + print("import stopped:", err, "- resume with err.remaining") + raise + print("import:", result["summary"], "in", result["requests"], "call(s)") + for item in result["results"]: + if item["status"] == "rejected": + print(" rejected", item["external_id"], item["error"]["code"]) + + # 2. A new sign-up later: one call (creates, or updates an existing user) + try: + user = csid.upsert_platform_user( + "user_3", wallets=[{"address": "So11111111111111111111111111111111111111112", "source": "privy"}] + ) + print("user_3 created" if user["created"] else "user_3 updated", user["csid_id"]) + except PlanUserLimitError as err: + print("plan user limit reached:", err.body) + + # 3. A profile page in one call + profile = csid.platform_user_profile("user_1", period="7d") + for chain in profile["trading"]: + pnl, win_rate = chain["realized_pnl_usd"], chain["win_rate_percentage"] + print(f"{chain['blockchain']}: PnL {pnl:.2f} USD, win rate {win_rate}%") + print("wallets:", [(w["address"], w["status"]) for w in profile["wallets"]]) + + # 4. Your own leaderboard (follows the cursor for you) + for entry in csid.iter_platform_leaderboard(blockchain="solana", period="7d", sort="pnl_usd", limit=100): + print(entry["rank"], entry["external_id"], entry["period_stats"]["realized_pnl_usd"]) + + # 5. Optional: a verified badge through the on-chain payment verification + v = csid.start_wallet_verification("user_1", chain="solana", address=MY_USERS[0]["wallets"][0]) + print(v["instructions"]) + svg = csid.wallet_verification_qr(v["verification_id"]) # an SVG QR code to show the user + print(len(svg), "bytes of SVG") + csid.cancel_wallet_verification(v["verification_id"]) + + # 6. A trading competition between your users + try: + comp = csid.create_competition( + name="Weekly PnL", + chain="solana", + metric="pnl_usd", + duration_hours=168, + min_participants=2, + min_trades=3, + prizes=[{"rank": 1, "prize": "100 USDC"}], + ) + except ConflictError as err: # competition_limit: 5 scheduled + running at a time + print("cannot create:", err.code) + else: + for u in MY_USERS: + csid.join_competition(comp["id"], u["id"]) + csid.update_competition(comp["id"], min_trades=1, note="Lower entry bar") + standings = csid.competition_standings(comp["id"]) + print(comp["name"], standings["status"], [(s["rank"], s["external_id"]) for s in standings["standings"]]) + csid.cancel_competition(comp["id"]) # this is only a demo + + # 7. Clean up the demo user + csid.delete_platform_user("user_3") diff --git a/pyproject.toml b/pyproject.toml index 89ae5d7..b744e93 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cabalspy-id" -version = "0.5.2" +version = "0.6.0" description = "SocialFi API & SDK for CabalSpy ID — add a social layer to any app: login with X + verified wallets, live trades and PnL of your users, token theses, leaderboards and copy trading on Solana, BNB Chain, Base, Ethereum and Robinhood Chain." readme = "README.md" license = "MIT" diff --git a/tests/test_competitions.py b/tests/test_competitions.py new file mode 100644 index 0000000..24bba44 --- /dev/null +++ b/tests/test_competitions.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +from datetime import datetime, timezone + +import httpx +import pytest + +from cabalspy_id import ( + COMPETITION_WEBHOOK_EVENTS, + AsyncCabalSpyID, + BadRequestError, + ConflictError, +) + +from .conftest import Recorder, api_error, ok +from .test_platform_users import call, make, query + +KEY = "csid_api_testkey" + + +def test_every_competition_endpoint() -> None: + csid, rec = make() + csid.create_competition( + name="Weekly PnL", + chain="solana", + metric="pnl_usd", + duration_hours=168, + starts_at=datetime(2026, 11, 1, 18, tzinfo=timezone.utc), + min_participants=2, + min_volume_usd=100.0, + enrollment="all_users", + prizes=[{"rank": 1, "prize": "100 USDC"}], + ) + csid.create_competition(name="Quick", chain="base", metric="trades", duration_hours=1) + csid.competitions(status="running", limit=10, offset=20) + csid.competition("c1") + csid.update_competition("c1", duration_hours=48, max_participants=None, note="longer") + csid.update_competition("c1", description=None) + csid.cancel_competition("c1") + csid.join_competition("c1", "u1") + csid.join_competition("c1", csid_id="4b7c") + csid.leave_competition("c1", "u1") + csid.competition_participants("c1", limit=100, offset=100) + csid.competition_standings("c1", limit=5) + + assert [call(r) for r in rec.requests] == [ + ( + "POST", + "/v1/competitions", + { + "name": "Weekly PnL", + "chain": "solana", + "metric": "pnl_usd", + "duration_hours": 168, + "starts_at": "2026-11-01T18:00:00+00:00", + "min_participants": 2, + "min_volume_usd": 100.0, + "enrollment": "all_users", + "prizes": [{"rank": 1, "prize": "100 USDC"}], + }, + ), + ("POST", "/v1/competitions", {"name": "Quick", "chain": "base", "metric": "trades", "duration_hours": 1}), + ("GET", "/v1/competitions", {"status": "running", "limit": "10", "offset": "20"}), + ("GET", "/v1/competitions/detail", {"id": "c1"}), + ( + "POST", + "/v1/competitions/update", + {"id": "c1", "duration_hours": 48, "max_participants": None, "note": "longer"}, + ), + ("POST", "/v1/competitions/update", {"id": "c1", "description": None}), + ("POST", "/v1/competitions/cancel", {"id": "c1"}), + ("POST", "/v1/competitions/join", {"id": "c1", "external_id": "u1"}), + ("POST", "/v1/competitions/join", {"id": "c1", "csid_id": "4b7c"}), + ("POST", "/v1/competitions/leave", {"id": "c1", "external_id": "u1"}), + ("GET", "/v1/competitions/participants", {"id": "c1", "limit": "100", "offset": "100"}), + ("GET", "/v1/competitions/standings", {"id": "c1", "limit": "5"}), + ] + + +def test_competition_validation() -> None: + csid, rec = make() + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", chain="solana", metric="best", duration_hours=1) # type: ignore[arg-type] + assert e.value.parameter == "metric" + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", chain="tron", metric="pnl", duration_hours=1) # type: ignore[arg-type] + assert e.value.parameter == "chain" + with pytest.raises(BadRequestError): + csid.create_competition(name="", chain="solana", metric="pnl", duration_hours=1) + with pytest.raises(BadRequestError) as e: + csid.update_competition("c1", enrollment="everyone") # type: ignore[arg-type] + assert e.value.allowed == ["opt_in", "all_users"] + with pytest.raises(BadRequestError): + csid.update_competition("c1") + with pytest.raises(BadRequestError): + csid.update_competition("c1", note="only a note") + with pytest.raises(BadRequestError) as e: + csid.competitions(status="live") # type: ignore[arg-type] + assert e.value.parameter == "status" + with pytest.raises(BadRequestError): + csid.join_competition("c1") + with pytest.raises(BadRequestError): + csid.competition("") + assert rec.requests == [] + + +@pytest.mark.parametrize("code", ["competition_limit", "competition_closed", "competition_full", "late_join_closed"]) +def test_competition_conflicts(code: str) -> None: + csid, _ = make(lambda r: api_error(409, code)) + with pytest.raises(ConflictError) as e: + csid.join_competition("c1", "u1") + assert e.value.code == code + + +def test_iter_competition_standings_follows_offset() -> None: + def handler(r: httpx.Request) -> httpx.Response: + offset = int(query(r).get("offset", 0)) + rows = [{"rank": i + 1, "external_id": f"u{i}"} for i in range(offset, min(offset + 2, 5))] + # the server's has_more is always false on offset routes; the total decides + return ok( + {"competition_id": "c1", "standings": rows}, + pagination={"limit": 2, "total": 5, "has_more": False, "next_cursor": None}, + ) + + csid, rec = make(handler) + assert [s["external_id"] for s in csid.iter_competition_standings("c1", limit=2)] == [f"u{i}" for i in range(5)] + assert [query(r) for r in rec.requests] == [ + {"id": "c1", "limit": "2"}, + {"id": "c1", "limit": "2", "offset": "2"}, + {"id": "c1", "limit": "2", "offset": "4"}, + ] + + +def test_iter_competitions_and_participants() -> None: + def handler(r: httpx.Request) -> httpx.Response: + offset = int(query(r).get("offset", 0)) + rows = [{"id": f"c{i}", "csid_id": f"a{i}"} for i in range(offset, min(offset + 2, 3))] + return ok(rows, pagination={"limit": 2, "total": 3, "has_more": False, "next_cursor": None}) + + csid, rec = make(handler) + assert [c["id"] for c in csid.iter_competitions(status="ended", limit=2)] == ["c0", "c1", "c2"] + assert query(rec.requests[0]) == {"status": "ended", "limit": "2"} + assert [p["csid_id"] for p in csid.iter_competition_participants("c1", limit=2)] == ["a0", "a1", "a2"] + assert rec.requests[-1].url.path == "/v1/competitions/participants" + + +def test_iter_stops_on_empty_page() -> None: + csid, rec = make(lambda r: ok([], pagination={"limit": 50, "total": 10, "has_more": False})) + assert list(csid.iter_competitions()) == [] + assert len(rec.requests) == 1 + + +def test_competition_webhook_events() -> None: + assert COMPETITION_WEBHOOK_EVENTS == ( + "competition.started", + "competition.updated", + "competition.standings", + "competition.ended", + ) + + +async def test_async_competitions() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if r.url.path == "/v1/competitions/standings": + offset = int(query(r).get("offset", 0)) + return ok({"standings": [{"rank": offset + 1}]}, pagination={"limit": 1, "total": 2}) + if r.url.path == "/v1/competitions" and r.method == "GET": + return ok([{"id": "c1"}], pagination={"limit": 50, "total": 1}) + if r.url.path == "/v1/competitions/participants": + return ok([{"csid_id": "a"}], pagination={"limit": 100, "total": 1}) + return ok({"id": "c1", "joined": True, "already": False}) + + rec = Recorder(handler) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + assert (await csid.join_competition("c1", "u1"))["joined"] is True + assert (await csid.create_competition(name="n", chain="eth", metric="volume", duration_hours=2))["id"] == "c1" + assert [s["rank"] async for s in csid.iter_competition_standings("c1", limit=1)] == [1, 2] + assert [c["id"] async for c in csid.iter_competitions()] == ["c1"] + assert [p["csid_id"] async for p in csid.iter_competition_participants("c1")] == ["a"] + assert call(rec.requests[0]) == ("POST", "/v1/competitions/join", {"id": "c1", "external_id": "u1"}) diff --git a/tests/test_platform_users.py b/tests/test_platform_users.py new file mode 100644 index 0000000..06c2001 --- /dev/null +++ b/tests/test_platform_users.py @@ -0,0 +1,512 @@ +from __future__ import annotations + +import json +from typing import Any +from urllib.parse import parse_qs + +import httpx +import pytest + +from cabalspy_id import ( + PLATFORM_WEBHOOK_EVENTS, + WEBHOOK_EVENTS, + AsyncCabalSpyID, + BadRequestError, + CabalSpyID, + ConflictError, + NotFoundError, + PermissionError, + PlanUserLimitError, + PlatformImportError, + RateLimitError, + ServerError, +) + +from .conftest import Recorder, api_error, ok + +KEY = "csid_api_testkey" +SOL = "So11111111111111111111111111111111111111112" +EVM = "0x52908400098527886E0F7030069857D2E4169EE7" + + +def make(handler: Any = None, **kwargs: Any) -> tuple[CabalSpyID, Recorder]: + rec = Recorder(handler or (lambda r: ok({}))) + kwargs.setdefault("max_retries", 0) + return CabalSpyID(KEY, http_client=rec.client(), **kwargs), rec + + +def query(req: httpx.Request) -> dict[str, str]: + return {k: v[0] for k, v in parse_qs(req.url.query.decode()).items()} + + +def body(req: httpx.Request) -> Any: + return json.loads(req.content) + + +def call(req: httpx.Request) -> tuple[str, str, Any]: + """(method, path, query or JSON body) of a recorded request.""" + if req.method == "GET": + return req.method, req.url.path, query(req) + return req.method, req.url.path, body(req) + + +# ── every endpoint: method, path, query / body ─────────────────────────────── + + +def test_every_platform_user_endpoint() -> None: + csid, rec = make() + csid.upsert_platform_user("u1", wallets=[SOL, {"address": EVM, "chains": ["base"], "source": "privy"}]) + csid.upsert_platform_user("u1", display_name=None, avatar_url="https://cdn.example.com/a.png") + csid.import_platform_users([{"external_id": "u2", "wallets": [SOL]}]) + csid.platform_user("u1") + csid.platform_user(csid_id="4b7c") + csid.update_platform_user("u1", display_name="Alice") + csid.platform_users(limit=10, cursor="c1") + csid.delete_platform_user("u1") + csid.add_platform_user_wallets("u1", wallets=[EVM]) + csid.delete_platform_user_wallet("u1", address=EVM) + csid.start_wallet_verification("u1", chain="solana", address=SOL) + csid.wallet_verification("v1") + csid.cancel_wallet_verification("v1") + csid.platform_user_profile("u1", period="30d") + csid.platform_leaderboard(blockchain="solana", period="1d", sort="volume", limit=5, cursor="w", trust="verified") + csid.platform_settings() + csid.update_platform_settings(white_label=True, data_scope="platform", wallet_trust="verified_only") + csid.platform_inbound() + csid.enable_platform_inbound() + csid.disable_platform_inbound() + csid.platform_user_session("u1") + csid.platform_user_claim_link("u1", return_url="https://app.example.com/done") + csid.platform_user_claim_link(csid_id="4b7c") + csid.connect_platform_user_x("u1", return_url="https://app.example.com/x") + csid.disconnect_platform_user_x("u1") + csid.link_platform_user_telegram("u1") + csid.platform_user_telegram("u1") + csid.unlink_platform_user_telegram("u1") + csid.platform_user_kol("u1") + csid.request_platform_user_volume_check("u1") + csid.apply_platform_user_kol("u1") + + P = "/v1/platform-users" + assert [call(r) for r in rec.requests] == [ + ( + "POST", + P, + { + "external_id": "u1", + "wallets": [SOL, {"address": EVM, "chains": ["base"], "source": "privy"}], + }, + ), + ("POST", P, {"external_id": "u1", "display_name": None, "avatar_url": "https://cdn.example.com/a.png"}), + ("POST", P + "/import", {"users": [{"external_id": "u2", "wallets": [SOL]}]}), + ("GET", P, {"external_id": "u1"}), + ("GET", P, {"csid_id": "4b7c"}), + ("POST", P + "/update", {"external_id": "u1", "display_name": "Alice"}), + ("GET", P + "/list", {"limit": "10", "cursor": "c1"}), + ("POST", P + "/delete", {"external_id": "u1"}), + ("POST", P + "/wallets/add", {"external_id": "u1", "wallets": [EVM]}), + ("POST", P + "/wallets/delete", {"external_id": "u1", "address": EVM}), + ("POST", P + "/wallets/verify", {"external_id": "u1", "chain": "solana", "address": SOL}), + ("GET", P + "/wallets/verification", {"id": "v1"}), + ("POST", P + "/wallets/verification/cancel", {"id": "v1"}), + ("GET", P + "/profile", {"external_id": "u1", "period": "30d"}), + ( + "GET", + P + "/leaderboard", + { + "blockchain": "solana", + "period": "1d", + "sort": "volume", + "trust": "verified", + "limit": "5", + "cursor": "w", + }, + ), + ("GET", P + "/settings", {}), + ("POST", P + "/settings", {"white_label": True, "data_scope": "platform", "wallet_trust": "verified_only"}), + ("GET", P + "/inbound", {}), + ("POST", P + "/inbound/enable", {}), + ("POST", P + "/inbound/disable", {}), + ("POST", P + "/session", {"external_id": "u1"}), + ("POST", P + "/claim-link", {"external_id": "u1", "return_url": "https://app.example.com/done"}), + ("POST", P + "/claim-link", {"csid_id": "4b7c"}), + ("POST", P + "/x/connect", {"external_id": "u1", "return_url": "https://app.example.com/x"}), + ("POST", P + "/x/disconnect", {"external_id": "u1"}), + ("POST", P + "/telegram/link", {"external_id": "u1"}), + ("GET", P + "/telegram", {"external_id": "u1"}), + ("POST", P + "/telegram/unlink", {"external_id": "u1"}), + ("GET", P + "/kol", {"external_id": "u1"}), + ("POST", P + "/kol/volume-check", {"external_id": "u1"}), + ("POST", P + "/kol/apply", {"external_id": "u1"}), + ] + assert all(r.headers["authorization"] == f"Bearer {KEY}" for r in rec.requests) + assert all(r.headers["content-type"] == "application/json" for r in rec.requests if r.method == "POST") + + +def test_instance_is_added_to_posts() -> None: + csid, rec = make(instance="csid_abc") + csid.delete_platform_user("u1") + assert query(rec.requests[0]) == {"instance": "csid_abc"} + + +def test_verification_qr_returns_svg() -> None: + svg = '' + csid, rec = make( + lambda r: httpx.Response(200, text=svg, headers={"content-type": "image/svg+xml", "X-RateLimit-Limit": "5"}) + ) + assert csid.wallet_verification_qr("v1") == svg + assert rec.requests[0].url.path == "/v1/platform-users/wallets/verification/qr" + assert query(rec.requests[0]) == {"id": "v1"} + assert csid.last_rate_limit.limit == 5 + + +def test_verification_qr_error() -> None: + csid, _ = make(lambda r: api_error(404, "verification_not_found")) + with pytest.raises(NotFoundError) as e: + csid.wallet_verification_qr("v1") + assert e.value.code == "verification_not_found" + + +def test_validation_happens_before_the_request() -> None: + csid, rec = make() + with pytest.raises(BadRequestError) as e: + csid.platform_user() + assert e.value.parameter == "external_id|csid_id" + with pytest.raises(BadRequestError): + csid.platform_user("u1", csid_id="x") + with pytest.raises(BadRequestError) as e: + csid.update_platform_user("u1") + assert e.value.code == "missing_parameter" + with pytest.raises(BadRequestError) as e: + csid.add_platform_user_wallets("u1", wallets=[]) + assert e.value.code == "wallet_required" + with pytest.raises(BadRequestError) as e: + csid.add_platform_user_wallets("u1", wallets=[SOL] * 11) + assert e.value.parameter == "wallets" + with pytest.raises(BadRequestError): + csid.add_platform_user_wallets("u1", wallets=SOL) + with pytest.raises(BadRequestError) as e: + csid.start_wallet_verification("u1", chain="tron", address=SOL) # type: ignore[arg-type] + assert e.value.parameter == "chain" + with pytest.raises(BadRequestError) as e: + csid.platform_leaderboard(blockchain="solana", trust="everyone") # type: ignore[arg-type] + assert e.value.allowed == ["all", "verified"] + with pytest.raises(BadRequestError): + csid.platform_user_profile("u1", period="2d") # type: ignore[arg-type] + with pytest.raises(BadRequestError): + csid.update_platform_settings() + with pytest.raises(BadRequestError) as e: + csid.update_platform_settings(data_scope="world") # type: ignore[arg-type] + assert e.value.allowed == ["csid", "platform"] + with pytest.raises(BadRequestError): + csid.connect_platform_user_x("u1", return_url="") + with pytest.raises(BadRequestError) as e: + csid.import_platform_users([]) + with pytest.raises(BadRequestError) as e: + csid.import_platform_users([{"external_id": str(i), "wallets": [SOL]} for i in range(1001)]) + assert e.value.parameter == "users" + assert rec.requests == [] + + +@pytest.mark.parametrize( + ("status", "code", "cls"), + [ + (400, "wallet_required", BadRequestError), + (400, "invalid_address", BadRequestError), + (403, "plan_user_limit", PlanUserLimitError), + (403, "claim_disabled", PermissionError), + (404, "platform_user_not_found", NotFoundError), + (404, "competition_not_found", NotFoundError), + (409, "account_claimed", ConflictError), + (409, "last_wallet", ConflictError), + (409, "competition_full", ConflictError), + (429, "rate_limited", RateLimitError), + (503, "service_unavailable", ServerError), + ], +) +def test_platform_error_codes(status: int, code: str, cls: type) -> None: + csid, _ = make(lambda r: api_error(status, code, user_limit=25)) + with pytest.raises(cls) as e: + csid.upsert_platform_user("u1", wallets=[SOL]) + assert e.value.code == code and e.value.status == status + if code == "plan_user_limit": + assert e.value.body["user_limit"] == 25 + + +def test_posts_are_not_retried_on_platform_rate_limit(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("time.sleep", lambda s: None) + csid, rec = make(lambda r: api_error(429, "rate_limited"), max_retries=2) + with pytest.raises(RateLimitError): + csid.upsert_platform_user("u1", wallets=[SOL]) + assert len(rec.requests) == 1 # writes retry only the API-wide limit (rate_limit_exceeded) + + +def test_webhook_event_names() -> None: + for name in ("platform_user.created", "platform_user.claimed", "wallet.added", "verification.expired"): + assert name in PLATFORM_WEBHOOK_EVENTS and name in WEBHOOK_EVENTS + assert "competition.ended" in WEBHOOK_EVENTS + + +# ── pagination ─────────────────────────────────────────────────────────────── + + +def test_iter_platform_users_follows_cursor() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if "cursor" not in query(r): + return ok( + [{"external_id": "a"}, {"external_id": "b"}], + pagination={"limit": 2, "total": 3, "has_more": True, "next_cursor": "Yw=="}, + ) + return ok([{"external_id": "c"}], pagination={"limit": 2, "total": 3, "has_more": False, "next_cursor": None}) + + csid, rec = make(handler) + assert [u["external_id"] for u in csid.iter_platform_users(limit=2)] == ["a", "b", "c"] + assert [r.url.path for r in rec.requests] == ["/v1/platform-users/list"] * 2 + assert query(rec.requests[0]) == {"limit": "2"} + assert query(rec.requests[1]) == {"limit": "2", "cursor": "Yw=="} + + +def test_iter_platform_leaderboard_reads_envelope_pagination() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if "cursor" not in query(r): + return ok( + {"blockchain": "solana", "leaderboard": [{"wallet": "w1", "external_id": "a"}]}, + pagination={"limit": 1, "total": 2, "has_more": True, "next_cursor": "w1"}, + ) + return ok( + {"blockchain": "solana", "leaderboard": [{"wallet": "w2", "external_id": "b"}]}, + pagination={"limit": 1, "total": 2, "has_more": False, "next_cursor": None}, + ) + + csid, rec = make(handler) + entries = list(csid.iter_platform_leaderboard(blockchain="solana", sort="pnl_usd", limit=1)) + assert [e["external_id"] for e in entries] == ["a", "b"] + assert query(rec.requests[1]) == {"blockchain": "solana", "sort": "pnl_usd", "limit": "1", "cursor": "w1"} + + +# ── bulk import: chunking, retries, resuming ───────────────────────────────── + + +def users(n: int, start: int = 0) -> list[dict[str, Any]]: + return [{"external_id": f"u{i}", "wallets": [SOL]} for i in range(start, start + n)] + + +def created(items: list[dict[str, Any]]) -> dict[str, Any]: + n = len(items) + return { + "summary": {"created": n, "updated": 0, "unchanged": 0, "rejected": 0}, + "results": [ + {"external_id": u["external_id"], "csid_id": f"id-{u['external_id']}", "status": "created"} for u in items + ], + } + + +def test_bulk_import_chunks_and_aggregates(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("time.sleep", lambda s: pytest.fail("no sleep expected")) + csid, rec = make(lambda r: ok(created(body(r)["users"]))) + result = csid.bulk_import_platform_users(users(2500)) + sizes = [len(body(r)["users"]) for r in rec.requests] + assert sizes == [1000, 1000, 500] + assert all(r.url.path == "/v1/platform-users/import" for r in rec.requests) + assert result["summary"] == {"created": 2500, "updated": 0, "unchanged": 0, "rejected": 0} + assert [r["external_id"] for r in result["results"]] == [f"u{i}" for i in range(2500)] + assert result["requests"] == 3 + + +def test_bulk_import_respects_chunk_size_and_body_limit() -> None: + csid, rec = make(lambda r: ok(created(body(r)["users"]))) + csid.bulk_import_platform_users(users(5), chunk_size=2) + assert [len(body(r)["users"]) for r in rec.requests] == [2, 2, 1] + + csid, rec = make(lambda r: ok(created(body(r)["users"]))) + big = [{"external_id": f"u{i}", "wallets": [SOL], "display_name": "x" * 400} for i in range(30)] + csid.bulk_import_platform_users(big, max_body_bytes=5_000) + assert all(len(r.content) <= 5_000 for r in rec.requests) + assert sum(len(body(r)["users"]) for r in rec.requests) == 30 + assert len(rec.requests) > 1 + + +def test_bulk_import_retries_429_with_retry_after_without_resending_done_chunks( + monkeypatch: pytest.MonkeyPatch, +) -> None: + sleeps: list[float] = [] + monkeypatch.setattr("time.sleep", sleeps.append) + calls = {"n": 0} + + def handler(r: httpx.Request) -> httpx.Response: + calls["n"] += 1 + if calls["n"] == 2: # the second chunk is refused once + return api_error(429, "rate_limit_exceeded", headers={"Retry-After": "3"}) + return ok(created(body(r)["users"])) + + csid, rec = make(handler) + result = csid.bulk_import_platform_users(users(4), chunk_size=2) + sent = [[u["external_id"] for u in body(r)["users"]] for r in rec.requests] + assert sent == [["u0", "u1"], ["u2", "u3"], ["u2", "u3"]] + assert sleeps == [3.0] + assert result["summary"]["created"] == 4 + assert result["requests"] == 3 + + +def test_bulk_import_resends_only_rate_limited_users(monkeypatch: pytest.MonkeyPatch) -> None: + sleeps: list[float] = [] + monkeypatch.setattr("time.sleep", sleeps.append) + monkeypatch.setattr("time.time", lambda: 1_000_065.0) # 45 s into a minute + + def handler(r: httpx.Request) -> httpx.Response: + items = body(r)["users"] + if len(items) == 3: # first call: the last two hit the per-minute limit for new users + res = created(items[:1])["results"] + [ + { + "external_id": u["external_id"], + "status": "rejected", + "error": {"code": "rate_limited", "message": "At most 2000 new platform users per minute."}, + } + for u in items[1:] + ] + return ok({"summary": {}, "results": res}) + return ok(created(items)) + + csid, rec = make(handler) + result = csid.bulk_import_platform_users(users(3)) + sent = [[u["external_id"] for u in body(r)["users"]] for r in rec.requests] + assert sent == [["u0", "u1", "u2"], ["u1", "u2"]] + assert sleeps == [16.0] # until the next minute, plus one second + assert [r["status"] for r in result["results"]] == ["created"] * 3 + assert result["summary"] == {"created": 3, "updated": 0, "unchanged": 0, "rejected": 0} + + +def test_bulk_import_gives_up_on_rate_limited_users_after_max_attempts(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("time.sleep", lambda s: None) + limited = {"status": "rejected", "error": {"code": "rate_limited", "message": "slow down"}} + csid, rec = make( + lambda r: ok({"results": [{**limited, "external_id": u["external_id"]} for u in body(r)["users"]]}) + ) + result = csid.bulk_import_platform_users(users(2), max_attempts=3) + assert len(rec.requests) == 3 + assert result["summary"]["rejected"] == 2 + + +def test_bulk_import_keeps_other_rejections() -> None: + def handler(r: httpx.Request) -> httpx.Response: + return ok( + { + "results": [ + {"external_id": "u0", "status": "unchanged", "csid_id": "a"}, + { + "external_id": "u1", + "status": "rejected", + "error": {"code": "plan_user_limit", "message": "full"}, + }, + ] + } + ) + + csid, rec = make(handler) + result = csid.bulk_import_platform_users(users(2)) + assert len(rec.requests) == 1 + assert result["summary"] == {"created": 0, "updated": 0, "unchanged": 1, "rejected": 1} + + +def test_bulk_import_stops_with_partial_result_and_remaining(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("time.sleep", lambda s: None) + calls = {"n": 0} + + def handler(r: httpx.Request) -> httpx.Response: + calls["n"] += 1 + if calls["n"] == 2: + return api_error(500, "internal_error") + return ok(created(body(r)["users"])) + + csid, rec = make(handler, max_retries=2) + with pytest.raises(PlatformImportError) as e: + csid.bulk_import_platform_users(users(6), chunk_size=2) + err = e.value + assert len(rec.requests) == 2 # a 500 on a write is not retried + assert err.status == 500 and err.code == "internal_error" + assert isinstance(err.__cause__, ServerError) + assert [r["external_id"] for r in err.result["results"]] == ["u0", "u1"] + assert err.result["summary"]["created"] == 2 + assert [u["external_id"] for u in err.remaining] == ["u2", "u3", "u4", "u5"] + + # resume with the rest + csid, rec = make(lambda r: ok(created(body(r)["users"]))) + assert csid.bulk_import_platform_users(err.remaining)["summary"]["created"] == 4 + + +def test_bulk_import_gives_up_on_429_after_max_attempts(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("time.sleep", lambda s: None) + csid, rec = make(lambda r: api_error(429, "rate_limit_exceeded")) + with pytest.raises(PlatformImportError) as e: + csid.bulk_import_platform_users(users(3), max_attempts=2) + assert len(rec.requests) == 2 + assert e.value.status == 429 + assert len(e.value.remaining) == 3 and e.value.result["results"] == [] + + +def test_bulk_import_arguments() -> None: + csid, rec = make() + with pytest.raises(ValueError): + csid.bulk_import_platform_users(users(1), chunk_size=1001) + with pytest.raises(ValueError): + csid.bulk_import_platform_users(users(1), max_attempts=0) + with pytest.raises(BadRequestError): + csid.bulk_import_platform_users({"external_id": "u1"}) # type: ignore[arg-type] + assert csid.bulk_import_platform_users([]) == { + "summary": {"created": 0, "updated": 0, "unchanged": 0, "rejected": 0}, + "results": [], + "requests": 0, + } + assert rec.requests == [] + + +# ── async ──────────────────────────────────────────────────────────────────── + + +async def test_async_platform_users(monkeypatch: pytest.MonkeyPatch) -> None: + sleeps: list[float] = [] + + async def fake_sleep(s: float) -> None: + sleeps.append(s) + + monkeypatch.setattr("asyncio.sleep", fake_sleep) + calls = {"import": 0} + + def handler(r: httpx.Request) -> httpx.Response: + if r.url.path == "/v1/platform-users/import": + calls["import"] += 1 + if calls["import"] == 1: + return api_error(429, "rate_limit_exceeded", headers={"Retry-After": "2"}) + return ok(created(body(r)["users"])) + if r.url.path == "/v1/platform-users/list": + if "cursor" not in query(r): + return ok([{"external_id": "a"}], pagination={"has_more": True, "next_cursor": "x"}) + return ok([{"external_id": "b"}], pagination={"has_more": False, "next_cursor": None}) + if r.url.path == "/v1/platform-users/leaderboard": + return ok({"leaderboard": [{"wallet": "w"}]}, pagination={"has_more": False, "next_cursor": None}) + if r.url.path.endswith("/qr"): + return httpx.Response(200, text="") + return ok({"external_id": "u1", "created": True}) + + rec = Recorder(handler) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + assert (await csid.upsert_platform_user("u1", wallets=[SOL]))["created"] is True + assert (await csid.platform_user_kol("u1"))["external_id"] == "u1" + assert await csid.wallet_verification_qr("v1") == "" + result = await csid.bulk_import_platform_users(users(3), chunk_size=2) + assert result["summary"]["created"] == 3 and result["requests"] == 3 + assert [u["external_id"] async for u in csid.iter_platform_users()] == ["a", "b"] + assert [e["wallet"] async for e in csid.iter_platform_leaderboard(blockchain="base")] == ["w"] + assert sleeps == [2.0] + imports = [[u["external_id"] for u in body(r)["users"]] for r in rec.requests if r.url.path.endswith("/import")] + assert imports == [["u0", "u1"], ["u0", "u1"], ["u2"]] + assert call(rec.requests[1]) == ("GET", "/v1/platform-users/kol", {"external_id": "u1"}) + + +async def test_async_bulk_import_failure() -> None: + rec = Recorder(lambda r: api_error(403, "invalid_api_key")) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + with pytest.raises(PlatformImportError) as e: + await csid.bulk_import_platform_users(users(2)) + assert e.value.code == "invalid_api_key" + assert len(e.value.remaining) == 2