refactor: harden client, clean tests, and fix timeouts

- Security & validation: tighten hash regex, add HTTP timeouts to all
  requests, pass client.timeout through get_fragment_hash and AsyncClient
- Constants: move all constants to types/constants.py; remove re-exports
  from types/__init__.py; add DEFAULT_TIMEOUT, REQUIRED_COOKIE_KEYS
- FragmentClient: add timeout param (default 30 s); async-context-manager
  support; remove WALLET_CLASSES from public API
- Exceptions: remove dead INVALID_USERNAME constant (Fragment validates
  server-side); keep full hierarchy intact
- Tests: add 006_test_methods_mock.py (6 mock tests for all 3 methods);
  DRY-refactor 004_test_balance.py (_patch_wallet context manager);
  clean up 005_test_methods.py (remove fragile network test, rename tests)
- Examples: switch all 4 examples to async-with; align error messages;
  replace %-format with f-strings
- README: rewrite usage section with single comprehensive async-with
  example covering all 3 methods and full exception hierarchy
- CI: add mypy step to lint job; add pytest-mock and mypy to dev deps;
  set FORCE_JAVASCRIPT_ACTIONS_TO_NODE24 on all jobs; fix COOKIES_JSON
  to job-level env var
This commit is contained in:
bohd4nx
2026-03-20 20:16:43 +02:00
parent 2184dc7d98
commit 4e03d2e2f6
22 changed files with 335 additions and 309 deletions
+8 -12
View File
@@ -1,5 +1,5 @@
"""
Example: initializing FragmentClient.
Example: fetch wallet address, state, and balance.
Cookies can be passed as a dict or as a JSON string.
wallet_version defaults to "V5R1" — change to "V4R2" for older wallets.
@@ -9,7 +9,7 @@ import asyncio
from pyfragment import FragmentClient
SEED = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15 word16 word17 word18 word19 word20 word21 word22 word23 word24"
SEED = "word1 word2 ... word24"
API_KEY = "YOUR_TONAPI_KEY"
COOKIES = {
"stel_ssid": "YOUR_STEL_SSID",
@@ -20,20 +20,16 @@ COOKIES = {
async def main() -> None:
client = FragmentClient(
async with FragmentClient(
seed=SEED,
api_key=API_KEY,
cookies=COOKIES,
wallet_version="V5R1", # or "V4R2"
)
wallet = await client.get_wallet()
print("FragmentClient initialized")
print(" %-16s %s" % ("Wallet version:", client.wallet_version))
print(" %-16s %s" % ("Address:", wallet.address))
print(" %-16s %s" % ("State:", wallet.state))
print(" %-16s %s TON" % ("Balance:", wallet.balance))
) as client:
wallet = await client.get_wallet()
print(f"Address: {wallet.address}")
print(f"State: {wallet.state}")
print(f"Balance: {wallet.balance} TON")
if __name__ == "__main__":
+10 -15
View File
@@ -23,22 +23,17 @@ MONTHS = 3 # 3, 6, or 12
async def main() -> None:
client = FragmentClient(seed=SEED, api_key=API_KEY, cookies=COOKIES)
async with FragmentClient(seed=SEED, api_key=API_KEY, cookies=COOKIES) as client:
try:
result = await client.purchase_premium(USERNAME, months=MONTHS, show_sender=True)
except UserNotFoundError:
print(f"User {USERNAME} was not found on fragment.com — check the username and try again.")
return
except ConfigurationError as e:
print(f"Invalid argument: {e}")
return
try:
result = await client.purchase_premium(USERNAME, months=MONTHS, show_sender=True)
except UserNotFoundError:
print(f"User {USERNAME!r} not found on Fragment.")
return
except ConfigurationError as e:
print(f"Invalid parameters: {e}")
return
print("Premium purchased")
print(" %-14s %s" % ("Username:", result.username))
print(" %-14s %s months" % ("Duration:", result.months))
print(" %-14s %s" % ("Transaction:", result.transaction_id))
print(" %-14s %s" % ("Timestamp:", result.timestamp))
print(f"{result.months} months of Premium successfully sent to {result.username} | tx: {result.transaction_id}")
if __name__ == "__main__":
+10 -15
View File
@@ -23,22 +23,17 @@ AMOUNT = 500 # 501 000 000
async def main() -> None:
client = FragmentClient(seed=SEED, api_key=API_KEY, cookies=COOKIES)
async with FragmentClient(seed=SEED, api_key=API_KEY, cookies=COOKIES) as client:
try:
result = await client.purchase_stars(USERNAME, amount=AMOUNT, show_sender=True)
except UserNotFoundError:
print(f"User {USERNAME} was not found on fragment.com — check the username and try again.")
return
except ConfigurationError as e:
print(f"Invalid argument: {e}")
return
try:
result = await client.purchase_stars(USERNAME, amount=AMOUNT, show_sender=True)
except UserNotFoundError:
print(f"User {USERNAME!r} not found on Fragment.")
return
except ConfigurationError as e:
print(f"Invalid parameters: {e}")
return
print("Stars purchased")
print(" %-14s %s" % ("Username:", result.username))
print(" %-14s %s" % ("Stars:", result.stars))
print(" %-14s %s" % ("Transaction:", result.transaction_id))
print(" %-14s %s" % ("Timestamp:", result.timestamp))
print(f"{result.stars} Stars successfully sent to {result.username} | tx: {result.transaction_id}")
if __name__ == "__main__":
+13 -18
View File
@@ -23,25 +23,20 @@ AMOUNT = 10 # TON, integer — 11 000 000 000
async def main() -> None:
client = FragmentClient(seed=SEED, api_key=API_KEY, cookies=COOKIES)
async with FragmentClient(seed=SEED, api_key=API_KEY, cookies=COOKIES) as client:
try:
result = await client.topup_ton(USERNAME, amount=AMOUNT, show_sender=True)
except UserNotFoundError:
print(f"User {USERNAME} was not found on fragment.com — check the username and try again.")
return
except WalletError as e:
print(f"Wallet error — insufficient balance or misconfiguration: {e}")
return
except ConfigurationError as e:
print(f"Invalid argument: {e}")
return
try:
result = await client.topup_ton(USERNAME, amount=AMOUNT, show_sender=True)
except UserNotFoundError:
print(f"User {USERNAME!r} not found on Fragment.")
return
except WalletError as e:
print(f"Wallet error: {e}")
return
except ConfigurationError as e:
print(f"Invalid parameters: {e}")
return
print("TON topped up")
print(" %-14s %s" % ("Username:", result.username))
print(" %-14s %s TON" % ("Amount:", result.amount))
print(" %-14s %s" % ("Transaction:", result.transaction_id))
print(" %-14s %s" % ("Timestamp:", result.timestamp))
print(f"{result.amount} TON successfully sent to {result.username} | tx: {result.transaction_id}")
if __name__ == "__main__":