Skip to main content

Unified async Python SDK for Telegram Gifts marketplaces (Tonnel, Portals, Fragment)

Project description

tg-gifts-sdk

Unified async Python SDK for Telegram Gifts marketplaces (Tonnel, Portals, Fragment).

CI PyPI Python License

Status (v0.1.0)

Read-only. This SDK provides a unified async surface for querying gift listings, floor stats, and account balance across Telegram Gifts marketplaces.

Marketplace Listings Floor stats Balance Writes
Tonnel — (out of scope)
Portals scaffolded scaffolded
Fragment scaffolded scaffolded

Tonnel is fully implemented and tested. Portals and Fragment are interface stubs that raise NotImplementedYetError with documented hints — contributions welcome (see CONTRIBUTING.md).

Write operations (buyGift, listGift) are deliberately out of scope to keep the public SDK conservative; downstream users can reverse-engineer the marketplace signing protocol themselves.

Install

pip install tg-gifts-sdk

Quick start

import asyncio
from tg_gifts_sdk import TonnelClient, find_deals

async def main():
    auth = "user=...&hash=..."  # see "Capturing auth_data" below

    async with TonnelClient(auth_data=auth) as client:
        listings = await client.fetch_listings(gift_name="Plush Pepe", limit=30)
        stats = await client.fetch_floor_stats()
        balance = await client.fetch_balance()

    print(f"Balance: {balance.balance_ton} TON ({balance.memo=})")
    print(f"Found {len(listings)} Plush Pepe listings")

    deals = find_deals(listings, stats, min_discount=0.15)
    for d in deals:
        print(f"  {d.listing.gift_name} #{d.listing.gift_num}: "
              f"{d.listing.price} TON (fair ~{d.fair_value_ton:.1f}, "
              f"{d.discount_pct*100:.1f}% discount)")

asyncio.run(main())

Capturing auth_data (Tonnel)

auth_data is the URL-encoded Telegram WebApp initData string that Tonnel uses to authenticate. To capture it:

  1. Open https://marketplace.tonnel.network in your browser (you must be logged in).
  2. Open DevTools → Console.
  3. Run: localStorage.getItem("web-initData")
  4. Copy the result. The string starts with user= and ends with &hash=....

auth_data expires every 24-72 hours. Re-capture it when API calls start returning 401/403.

API surface

Clients

  • TonnelClient(auth_data: str, timeout: float = 30.0) — fully implemented
    • fetch_listings(gift_name=, model=, backdrop=, symbol=, sort=, limit=, page=, asset="TON") -> list[Listing]
    • fetch_floor_stats() -> list[FloorStats]
    • fetch_balance() -> BalanceInfo
  • PortalsClient — stub (raises NotImplementedYetError)
  • FragmentClient — stub (raises NotImplementedYetError)
  • UnifiedClient(tonnel_auth=, portals_auth=, fragment_auth=) — aggregates across venues

Models (pydantic v2)

  • Listing — gift for sale (price, asset, traits, seller, raw)
  • Gift — gift identifier with traits
  • FloorStats — per-collection floor + per-trait floor breakdown
  • Trait — single trait variant (model / backdrop / symbol) with rarity + floor
  • BalanceInfo — operator's balance + deposit memo

Scoring (the public differentiator)

  • score_listing(listing, floor_stats) -> FairValueQuote | None — trait-aware fair value
  • find_deals(listings, floor_stats, min_discount=0.10) -> list[FairValueQuote] — filtered + sorted

The scorer takes MAX(model_premium, backdrop_premium, symbol_premium) instead of the sum — a conservative choice that minimises false positives when joint-distribution data on trait co-occurrence is unavailable. Calibrated against weeks of paper-mode trading on Tonnel.

Design choices

Read-only scope. This SDK does not implement gift purchases or sales. The marketplace signing protocol (wtf field on Tonnel) is left out deliberately — public availability of a buy/sell SDK would accelerate bot-on-bot competition. If you need writes, reverse-engineer the protocol yourself; the surface here covers everything needed for monitoring and price discovery.

curl_cffi + Firefox 133 impersonation. Tonnel's CloudFlare rules reject plain httpx/aiohttp requests via TLS fingerprinting. curl_cffi ships TLS impersonation profiles matching real browsers; Firefox 133 is the profile that currently passes Tonnel's checks. If a future migration breaks this, update the impersonate= argument in tg_gifts_sdk._http.post_json.

No retry on 4xx. A 401/403 from Tonnel almost always means expired auth_data. Retrying is wasteful and noisy; the caller should refresh auth and try again. Retry-on-5xx is configurable per-call via the timeout parameter (the underlying curl_cffi call enforces it).

Stubs over fakes. Portals and Fragment are not yet implemented. Rather than ship fake implementations that look fine on paper but fail in production, they raise NotImplementedYetError with explicit hints about what's needed. UnifiedClient silently skips unimplemented venues by default (configurable via raise_on_unimplemented=True).

Contributing

Contributions to fill in Portals and Fragment are most welcome. See CONTRIBUTING.md for setup and how to share captured cURL from marketplace API calls.

License

Apache 2.0 — see LICENSE.


Краткое описание на русском

tg-gifts-sdk — асинхронный Python SDK для маркетплейсов Telegram Gifts. v0.1.0 покрывает Tonnel полностью (читающие операции: листинги, флор-статы, баланс); Portals и Fragment — заглушки с документированными подсказками для контрибьюторов. Записывающие операции (покупка/листинг) намеренно вне scope, чтобы не разгонять bot-войны.

Установка: pip install tg-gifts-sdk

Trait-aware скорер (find_deals) — публичный differentiator: ищет листинги, недооценённые по сравнению с trait-aware fair value, а не просто по collection floor.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tg_gifts_sdk-0.1.0.tar.gz (26.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tg_gifts_sdk-0.1.0-py3-none-any.whl (24.0 kB view details)

Uploaded Python 3

File details

Details for the file tg_gifts_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: tg_gifts_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 26.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for tg_gifts_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cfcb5dd49fa90de6aff226e44739f27cd57f00cca6a17e5a11c13d99207affcb
MD5 527475483cd142ccbee493f73c9ce014
BLAKE2b-256 f878c9fde770e8cd888602466287822de97ab923325ec01d3d3aaf0dc33b45b0

See more details on using hashes here.

File details

Details for the file tg_gifts_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: tg_gifts_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 24.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for tg_gifts_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 aa3bbe3a09ee47bb94c7eb0195eb2d65aebf5b98525c53c11b476135ce29f0ee
MD5 41a29016ff24eeb71c6f8ae277041529
BLAKE2b-256 f496a74eb9e19fe5ef76c18027d69f54164372c23afd26931fb184ac5018ff72

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page