Files
iishko-public/bot/daily_checkin.py
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

455 lines
20 KiB
Python

import logging
import os
import random
import sqlite3
import time
from contextlib import closing
import econ_guard
import quest_economy
log = logging.getLogger("daily_checkin")
QUOTA_PER_USD = 500_000
FACES = (5_000_000, 8_000_000, 10_000_000, 12_000_000, 15_000_000, 20_000_000)
# integer multipliers avoid float drift in money math
RANK_MULT = {1: (1, 1), 2: (3, 2), 3: (2, 1), 4: (3, 1)}
KIND_FACE = "ec_ddice:%d:%s"
KIND_LEGACY = "ec_dice:%d:%s"
KIND_WEB = "ec_web_checkin:%d:%s"
REF_FMT = "daily:%d:%s"
def _con(path, timeout=25):
con = sqlite3.connect(path, timeout=timeout)
con.row_factory = sqlite3.Row
con.execute("PRAGMA busy_timeout=%d" % (timeout * 1000))
return con
def _now(now=None):
if now is None:
return int(time.time())
if isinstance(now, (int, float)):
return int(now)
if hasattr(now, "timestamp"):
return int(now.timestamp())
raise ValueError("unsupported now")
def _day(now=None):
return quest_economy.today_iso(now)
def multiplier(rank):
num, den = RANK_MULT.get(int(rank), RANK_MULT[1])
return num / float(den)
def units_for(face, rank):
face = int(face)
if face < 1 or face > 6:
raise ValueError("bad face")
num, den = RANK_MULT.get(int(rank), RANK_MULT[1])
return FACES[face - 1] * num // den
def usd_for(units):
return None if units is None else int(units) / float(QUOTA_PER_USD)
def _faces_table(rank):
return [{"face": i + 1, "units": units_for(i + 1, rank), "usd": usd_for(units_for(i + 1, rank))}
for i in range(6)]
# --------------------------------------------------------------------------- #
# read side
# --------------------------------------------------------------------------- #
def schema_present(bot_db, gw_db):
"""Read-only probe. Never opens a missing file, never creates a table."""
for path in (bot_db, gw_db):
if not path or not os.path.exists(path):
return False
try:
with closing(_con(bot_db, timeout=5)) as b:
names = {row[0] for row in b.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name IN ('kv','users','econ_tx')")}
if names != {"kv", "users", "econ_tx"}:
return False
if "wallet_id" not in {row[1] for row in b.execute("PRAGMA table_info(econ_tx)")}:
return False
with closing(_con(gw_db, timeout=5)) as g:
if not g.execute("SELECT count(*) FROM sqlite_master WHERE type='table' "
"AND name='econ_payouts'").fetchone()[0]:
return False
return True
except sqlite3.Error:
return False
def _streak(con, uid):
row = con.execute("SELECT v FROM kv WHERE k=?", ("ec_streak:%d" % int(uid),)).fetchone()
try:
return int(str(row[0]).split("|")[0]) if row else 0
except (TypeError, ValueError, IndexError):
return 0
def _face_row(con, uid, day):
row = con.execute("SELECT v FROM kv WHERE k=?", (KIND_FACE % (int(uid), day),)).fetchone()
if not row:
return None
try:
face, units, rank = str(row[0]).split("|")
face, units, rank = int(face), int(units), int(rank)
except (TypeError, ValueError):
return None
if not (1 <= face <= 6) or units <= 0 or rank not in (1, 2, 3, 4):
return None
return {"face": face, "units": units, "rank": rank}
def _ledger_row(con, uid, day):
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx "
"WHERE type='daily' AND ref=?", (REF_FMT % (int(uid), day),)).fetchone()
if not row:
return None
return {"dst": int(row[0]), "units": int(row[1]), "type": row[2],
"ref": row[3], "wallet_id": row[4]}
def _legacy_used(con, uid, day):
return con.execute("SELECT 1 FROM kv WHERE k=?",
(KIND_LEGACY % (int(uid), day),)).fetchone() is not None
def _result(day=None, ok=True, error=None, claimed=False, paid=False, pending=False,
face=None, units=None, rank=None, streak=0, already=False, resumed=False,
credited_units=0, legacy=False, eligible=False, wallet=False, checked=None,
faces=None):
return {
"ok": bool(ok),
"error": error,
"claimed": bool(claimed),
"paid": bool(paid),
"pending": bool(pending),
"face": face,
"value": face,
"units": units,
"usd": usd_for(units) if units is not None else None,
"rank": rank,
"multiplier": multiplier(rank) if rank else None,
"streak": int(streak or 0),
"already": bool(already),
"resumed": bool(resumed),
"credited_units": int(credited_units or 0),
"legacy": bool(legacy),
"eligible": bool(eligible),
"wallet": bool(wallet),
"day": day,
"checkin": checked,
"faces": faces if faces is not None else (_faces_table(rank) if rank else None),
}
def status(bot_db, gw_db, uid, now=None, rank=None):
"""Read-only daily state. Performs no DDL and no writes whatsoever.
``rank`` is an optional display rank for the unclaimed preview; a persisted
face always reports the rank it was actually paid at. Missing/unprepared
economy schema yields ``ok=False, error="unavailable"`` (never creates it).
"""
day = _day(now)
try:
uid = int(uid)
if uid <= 0:
raise ValueError
except (TypeError, ValueError):
return _result(day=day, ok=False, error="user")
preview = int(rank) if rank in (1, 2, 3, 4) else None
if not schema_present(bot_db, gw_db):
return _result(day=day, ok=False, error="unavailable", rank=preview)
con = None
try:
con = _con(gw_db)
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
user = con.execute("SELECT tg_id FROM ledger.users WHERE tg_id=?", (uid,)).fetchone()
if not user:
return _result(day=day, ok=False, error="user", rank=preview)
eligible = econ_guard.account_eligible_con(con, uid, "ledger")
streak = _streak(con, uid)
face_row = _face_row(con, uid, day)
ledger = _ledger_row(con, uid, day)
legacy = _legacy_used(con, uid, day) and face_row is None and ledger is None
wallet = econ_guard._resolve_wallet_con(con, uid) if eligible else None
receipt = con.execute("SELECT token_id,units FROM econ_payouts WHERE ref=?",
(REF_FMT % (uid, day),)).fetchone()
except sqlite3.Error:
log.exception("daily status read failed uid=%s", uid)
return _result(day=day, ok=False, error="error", rank=preview)
finally:
if con is not None:
con.close()
if not eligible:
return _result(day=day, ok=False, error="blocked", streak=streak, rank=preview)
if legacy:
# Ambiguous by definition: the pre-upgrade marker was written before its payout,
# so it proves "consumed", not "credited". Never report a paid reward here.
return _result(day=day, claimed=True, paid=False, pending=False, already=True,
legacy=True, streak=streak, eligible=True, wallet=bool(wallet),
rank=preview, faces=_faces_table(1))
if face_row is None and ledger is None:
return _result(day=day, claimed=False, paid=False, pending=False, rank=preview,
streak=streak, eligible=True, wallet=bool(wallet))
face = face_row or {"face": None, "units": int(ledger["units"]), "rank": None}
paid = receipt is not None
return _result(day=day, claimed=True, paid=paid, pending=not paid,
face=face["face"], units=face["units"], rank=face["rank"] or preview,
streak=streak, already=paid, resumed=not paid,
eligible=True, wallet=bool(wallet))
# --------------------------------------------------------------------------- #
# payout
# --------------------------------------------------------------------------- #
def _credit_daily(gw_db, bot_db, uid, ref, wallet_id, units):
"""Gateway-first payout of one daily ref. Never releases on ambiguity.
Returns ``(credited_units, result)`` with result in ok/already/blocked/wallet/error.
"""
if int(units) <= 0:
return 0, "error"
con = None
try:
con = _con(gw_db)
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
con.execute("BEGIN IMMEDIATE")
if not econ_guard.account_eligible_con(con, uid, "ledger"):
con.rollback()
return 0, "blocked"
columns = {row[1] for row in con.execute("PRAGMA ledger.table_info(econ_tx)")}
source = "bounty_source" if "bounty_source" in columns else "NULL AS bounty_source"
rows = con.execute("SELECT dst,units,wallet_id,type,src,%s FROM ledger.econ_tx "
"WHERE type='daily' AND ref=?" % source, (ref,)).fetchall()
if (len(rows) != 1 or int(rows[0]["dst"]) != int(uid)
or int(rows[0]["units"]) != int(units)
or rows[0]["type"] != "daily" or int(rows[0]["src"] or 0) != 0
or bool(rows[0]["bounty_source"])
or (rows[0]["wallet_id"] is not None
and int(rows[0]["wallet_id"]) != int(wallet_id))):
con.rollback()
log.error("daily ledger mismatch ref=%s", ref)
return 0, "error"
if not econ_guard._wallet_owned_con(con, uid, wallet_id):
con.rollback()
return 0, "wallet"
existing = con.execute("SELECT token_id,units FROM econ_payouts WHERE ref=?", (ref,)).fetchone()
if existing:
if (int(existing["token_id"]) not in (0, int(wallet_id))
or int(existing["units"]) != int(units)):
con.rollback()
log.error("daily payout ref conflict ref=%s", ref)
return 0, "error"
con.commit()
return 0, "already"
con.execute("INSERT INTO econ_payouts(ref,token_id,units,created) VALUES(?,?,?,?)",
(ref, int(wallet_id), int(units), int(time.time())))
updated = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
(int(units), int(wallet_id)))
if updated.rowcount != 1:
con.rollback()
return 0, "wallet"
con.commit()
return int(units), "ok"
except sqlite3.Error:
log.exception("daily payout failed ref=%s", ref)
if con is not None:
con.rollback()
return 0, "error"
finally:
if con is not None:
con.close()
# --------------------------------------------------------------------------- #
# claim
# --------------------------------------------------------------------------- #
def _snapshot(bot_db, uid, day):
with closing(_con(bot_db)) as con:
if not econ_guard.account_eligible_con(con, uid):
return {"error": "blocked"}
face = _face_row(con, uid, day)
ledger = _ledger_row(con, uid, day)
return {"face": face, "ledger": ledger, "streak": _streak(con, uid),
"legacy": (face is None and ledger is None and _legacy_used(con, uid, day))}
def _persist_face(bot_db, uid, day, current, rank, face, units, wallet_id):
"""Insert the face token and its ledger row atomically; adopt a concurrent winner."""
con = _con(bot_db)
try:
con.execute("BEGIN IMMEDIATE")
if not econ_guard.account_eligible_con(con, uid):
con.rollback()
return {"error": "blocked"}
existing = _face_row(con, uid, day)
ledger = _ledger_row(con, uid, day)
if existing is not None or ledger is not None:
con.rollback()
return {"face": existing, "ledger": ledger, "won": False, "streak": _streak(con, uid)}
won = con.execute("INSERT OR IGNORE INTO kv(k,v) VALUES(?,?)",
(KIND_FACE % (uid, day), "%d|%d|%d" % (face, units, rank)))
if won.rowcount == 1:
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) "
"VALUES (?,?,?,?,?,?,?)",
(0, uid, units, "daily", current, REF_FMT % (uid, day), int(wallet_id)))
con.commit()
return {"face": {"face": face, "units": units, "rank": rank}, "ledger": _ledger_row(
con, uid, day), "won": True, "streak": _streak(con, uid)}
con.rollback()
return {"face": _face_row(con, uid, day), "ledger": _ledger_row(con, uid, day),
"won": False, "streak": _streak(con, uid)}
except sqlite3.IntegrityError:
con.rollback()
return {"face": _face_row(con, uid, day), "ledger": _ledger_row(con, uid, day),
"won": False, "streak": _streak(con, uid)}
finally:
con.close()
def claim(bot_db, gw_db, uid, rank, now=None, value=None, source="miniapp"):
"""Roll (or resume) today's face and pay it exactly once.
``value`` is a dice face 1..6 from a trusted caller (a native Telegram dice);
``None`` rolls a random face server-side. ``source`` is ``bot`` or ``miniapp``
for the check-in calendar/streak side effect. Retries never roll again and
never release a possibly-credited amount.
"""
day = _day(now)
current = _now(now)
try:
uid = int(uid)
if uid <= 0:
raise ValueError
except (TypeError, ValueError):
return _result(day=day, ok=False, error="user")
if rank not in (1, 2, 3, 4):
return _result(day=day, ok=False, error="bad_input")
rank = int(rank)
if value is not None:
try:
value = int(value)
except (TypeError, ValueError):
return _result(day=day, ok=False, error="bad_input", rank=rank)
if not 1 <= value <= 6:
return _result(day=day, ok=False, error="bad_input", rank=rank)
try:
quest_economy.prepare(bot_db, gw_db)
except sqlite3.Error:
log.exception("daily prepare failed uid=%s", uid)
return _result(day=day, ok=False, error="error", rank=rank)
try:
snap = _snapshot(bot_db, uid, day)
except sqlite3.Error:
log.exception("daily snapshot failed uid=%s", uid)
return _result(day=day, ok=False, error="error", rank=rank)
if snap.get("error"):
return _result(day=day, ok=False, error=snap["error"], rank=rank)
if snap["legacy"]:
return _result(day=day, claimed=True, paid=False, pending=False, already=True,
legacy=True, rank=rank, streak=snap["streak"], eligible=True)
if snap["face"] is not None or snap["ledger"] is not None:
return _settle(bot_db, gw_db, uid, day, current, rank, snap["face"],
snap["ledger"], snap["streak"], fresh=False)
wallet = econ_guard.resolve_wallet(gw_db, bot_db, uid)
if not wallet:
return _result(day=day, ok=False, error="wallet", rank=rank,
streak=snap["streak"], eligible=True)
checked = quest_economy.record_checkin(bot_db, gw_db, uid, current, source=source)
if not checked.get("ok"):
return _result(day=day, ok=False, error=checked.get("error", "error"), rank=rank,
streak=snap["streak"], eligible=True, checked=checked)
face = int(value) if value is not None else random.randint(1, 6)
units = units_for(face, rank)
try:
persisted = _persist_face(bot_db, uid, day, current, rank, face, units, wallet[0])
except sqlite3.Error:
log.exception("daily persist failed uid=%s", uid)
return _result(day=day, ok=False, error="error", rank=rank, checked=checked)
if persisted.get("error"):
return _result(day=day, ok=False, error=persisted["error"], rank=rank,
eligible=True, checked=checked)
if persisted["face"] is None and persisted["ledger"] is None:
log.error("daily face vanished uid=%s day=%s", uid, day)
return _result(day=day, ok=False, error="error", rank=rank, checked=checked)
return _settle(bot_db, gw_db, uid, day, current, rank, persisted["face"],
persisted["ledger"], persisted["streak"], fresh=bool(persisted["won"]),
checked=checked)
def _settle(bot_db, gw_db, uid, day, current, rank, face_row, ledger, streak, fresh=False,
checked=None):
"""Phase 2: pay the persisted ref and report the stored values."""
ref = REF_FMT % (uid, day)
with closing(_con(bot_db)) as con:
face_row = face_row or _face_row(con, uid, day)
ledger = ledger or _ledger_row(con, uid, day)
streak = _streak(con, uid) or streak
if face_row is None and ledger is not None:
face_row = {"face": None, "units": int(ledger["units"]), "rank": None}
if face_row is None:
log.error("daily claim row missing uid=%s day=%s", uid, day)
return _result(day=day, ok=False, error="error", rank=rank, checked=checked)
units = int(face_row["units"])
out_rank = face_row["rank"] or rank
if ledger is None:
# Heal a half-written claim without changing face or amount.
wallet = econ_guard.resolve_wallet(gw_db, bot_db, uid)
if not wallet:
return _result(day=day, ok=False, error="wallet", claimed=True, pending=True,
face=face_row["face"], units=units, rank=out_rank,
streak=streak, eligible=True, checked=checked)
try:
con = _con(bot_db)
try:
con.execute("BEGIN IMMEDIATE")
if _ledger_row(con, uid, day) is None:
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) "
"VALUES (?,?,?,?,?,?,?)",
(0, uid, units, "daily", current, ref, int(wallet[0])))
con.commit()
finally:
con.close()
except sqlite3.Error:
log.exception("daily ledger heal failed uid=%s", uid)
return _result(day=day, ok=False, error="error", claimed=True, pending=True,
face=face_row["face"], units=units, rank=out_rank,
streak=streak, eligible=True, checked=checked)
with closing(_con(bot_db)) as con:
ledger = _ledger_row(con, uid, day)
wallet_id = int(ledger["wallet_id"]) if ledger and ledger["wallet_id"] is not None else None
if wallet_id is None:
wallet = econ_guard.resolve_wallet(gw_db, bot_db, uid)
if not wallet:
return _result(day=day, ok=False, error="wallet", claimed=True, pending=True,
face=face_row["face"], units=units, rank=out_rank,
streak=streak, eligible=True, checked=checked)
wallet_id = int(wallet[0])
credited, result = _credit_daily(gw_db, bot_db, uid, ref, wallet_id, units)
if result == "ok":
return _result(day=day, claimed=True, paid=True, pending=False, face=face_row["face"],
units=units, rank=out_rank, streak=streak, credited_units=credited,
resumed=not fresh, eligible=True, wallet=True, checked=checked)
if result == "already":
return _result(day=day, claimed=True, paid=True, pending=False, face=face_row["face"],
units=units, rank=out_rank, streak=streak, already=True, resumed=True,
eligible=True, wallet=True, checked=checked)
return _result(day=day, ok=False, error=result, claimed=True, pending=True,
face=face_row["face"], units=units, rank=out_rank, streak=streak,
resumed=not fresh, eligible=(result != "blocked"),
wallet=(result != "wallet"), checked=checked)