Files
iishko-public/bot/community_economy.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

239 lines
15 KiB
Python

import hashlib
import json
import re
import sqlite3
import time
from contextlib import closing
from typing import NoReturn
SUPPLY = 100_000
DAILY_GRANT_LIMIT = 1_000
MAX_AMOUNT = 10_000
class EconomyError(ValueError):
def __init__(self, status, code, message):
super().__init__(message)
self.status, self.code, self.message = status, code, message
def _fail(status, code, message) -> NoReturn:
raise EconomyError(status, code, message)
def _connect(db):
con = sqlite3.connect(str(db), timeout=10, isolation_level=None)
con.row_factory = sqlite3.Row
return con
def init_db(db):
with closing(_connect(db)) as con:
con.executescript('''
CREATE TABLE IF NOT EXISTS community_wallets (
uid INTEGER PRIMARY KEY, balance INTEGER NOT NULL DEFAULT 0 CHECK(balance>=0));
CREATE TABLE IF NOT EXISTS community_tasks (
id INTEGER PRIMARY KEY, creator INTEGER NOT NULL, worker INTEGER,
title TEXT NOT NULL, criteria TEXT NOT NULL, reward INTEGER NOT NULL CHECK(reward>0),
status TEXT NOT NULL DEFAULT 'open', revision INTEGER NOT NULL DEFAULT 0,
proof TEXT NOT NULL DEFAULT '', dispute TEXT NOT NULL DEFAULT '',
resolution TEXT NOT NULL DEFAULT '', created INTEGER NOT NULL, updated INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS community_ledger (
id INTEGER PRIMARY KEY, actor INTEGER NOT NULL, src INTEGER NOT NULL, dst INTEGER NOT NULL,
amount INTEGER NOT NULL CHECK(amount>0), kind TEXT NOT NULL,
task_id INTEGER, reason TEXT NOT NULL, ts INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS community_operations (
actor INTEGER NOT NULL, request_id TEXT NOT NULL, digest TEXT NOT NULL,
result TEXT NOT NULL, PRIMARY KEY(actor,request_id));
CREATE INDEX IF NOT EXISTS community_tasks_status ON community_tasks(status,id);
CREATE INDEX IF NOT EXISTS community_ledger_ts ON community_ledger(ts);
''')
# A finite non-cash reserve. Restarting never issues another reserve.
con.execute('INSERT OR IGNORE INTO community_wallets(uid,balance) VALUES(0,?)', (SUPPLY,))
def _int(value, name, minimum=1, maximum=MAX_AMOUNT):
if type(value) is not int or not minimum <= value <= maximum:
_fail(400, 'invalid_' + name, 'Некорректное поле: ' + name)
return value
def _text(value, name, minimum, maximum):
if not isinstance(value, str) or not minimum <= len(value.strip()) <= maximum:
_fail(400, 'invalid_' + name, f'{name}: от {minimum} до {maximum} символов.')
return value.strip()
def _user(con, uid):
_int(uid, 'user', maximum=2**53-1)
row = con.execute('SELECT banned,api_blocked FROM users WHERE tg_id=?', (uid,)).fetchone()
if row is None:
_fail(403, 'not_registered', 'Сначала открой бота и зарегистрируйся через /start.')
if row['banned'] or row['api_blocked']:
_fail(403, 'blocked', 'Доступ к экономике ограничен.')
def _wallet(con, uid):
con.execute('INSERT OR IGNORE INTO community_wallets(uid) VALUES(?)', (uid,))
def _move(con, actor, src, dst, amount, kind, reason, now, task_id=None):
_wallet(con, src)
_wallet(con, dst)
changed = con.execute('UPDATE community_wallets SET balance=balance-? WHERE uid=? AND balance>=?',
(amount, src, amount)).rowcount
if not changed:
_fail(409, 'insufficient_coins', 'Недостаточно монет. API-баланс для этого не используется.')
con.execute('UPDATE community_wallets SET balance=balance+? WHERE uid=?', (amount, dst))
con.execute('INSERT INTO community_ledger(actor,src,dst,amount,kind,task_id,reason,ts) VALUES(?,?,?,?,?,?,?,?)',
(actor, src, dst, amount, kind, task_id, reason, now))
def snapshot(db, uid, admins=()):
with closing(_connect(db)) as con:
con.execute('BEGIN')
_user(con, uid)
row = con.execute('SELECT balance FROM community_wallets WHERE uid=?', (uid,)).fetchone()
reserved = con.execute("SELECT COALESCE(SUM(reward),0) FROM community_tasks WHERE creator=? AND status IN ('open','claimed','submitted','disputed')", (uid,)).fetchone()[0]
tasks = []
# Personal work remains accessible even when the public board is busy.
rows = con.execute('''SELECT * FROM community_tasks WHERE (creator=? OR worker=?)
AND status IN ('open','claimed','submitted','disputed') ORDER BY id DESC''', (uid, uid)).fetchall()
rows += con.execute('''SELECT * FROM community_tasks WHERE (creator=? OR worker=?)
AND status IN ('done','cancelled') ORDER BY id DESC LIMIT 30''', (uid, uid)).fetchall()
seen = {r['id'] for r in rows}
rows += [r for r in con.execute("SELECT * FROM community_tasks WHERE status='open' ORDER BY id DESC LIMIT 50") if r['id'] not in seen]
if uid in admins:
seen = {r['id'] for r in rows}
rows += [r for r in con.execute("SELECT * FROM community_tasks WHERE status='disputed' ORDER BY id DESC LIMIT 50") if r['id'] not in seen]
for row_task in rows:
task = dict(row_task)
if uid not in (task['creator'], task['worker']) and uid not in admins:
for field in ('proof', 'dispute', 'resolution'):
task.pop(field, None)
tasks.append(task)
history = [dict(r) for r in con.execute('''SELECT id,src,dst,amount,kind,task_id,reason,ts
FROM community_ledger WHERE src=? OR dst=? ORDER BY id DESC LIMIT 30''', (uid, uid))]
reserve = con.execute('SELECT balance FROM community_wallets WHERE uid=0').fetchone()[0]
granted = con.execute("SELECT COALESCE(SUM(amount),0) FROM community_ledger WHERE kind='grant' AND ts>=?", (int(time.time()) // 86400 * 86400,)).fetchone()[0]
con.commit()
return {'uid': uid, 'currency': 'coins', 'balance': row['balance'] if row else 0,
'reserved': reserved, 'treasury': reserve, 'supply': SUPPLY,
'grant_budget_left': max(0, DAILY_GRANT_LIMIT-granted),
'is_admin': uid in admins, 'tasks': tasks, 'history': history,
'rules': 'Монеты не деньги и не API-кредит. Оплата за принятый результат, не за сообщения. Обмена на деньги или AI-баланс нет.'}
def act(db, uid, body, admins=()):
if not isinstance(body, dict):
_fail(400, 'invalid_body', 'Ожидается JSON-объект.')
request_id = body.get('request_id')
if not isinstance(request_id, str) or not re.fullmatch(r'[A-Za-z0-9:_-]{12,96}', request_id):
_fail(400, 'request_id_required', 'Нужен уникальный идентификатор операции.')
digest = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
with closing(_connect(db)) as con:
try:
con.execute('BEGIN IMMEDIATE')
now = int(time.time())
previous = con.execute('SELECT digest,result FROM community_operations WHERE actor=? AND request_id=?', (uid, request_id)).fetchone()
if previous:
if previous['digest'] != digest:
_fail(409, 'request_conflict', 'Идентификатор уже использован для другой операции.')
con.rollback()
return json.loads(previous['result'])
_user(con, uid)
action = body.get('action')
result = {'ok': True, 'action': action}
if action in ('grant', 'transfer'):
amount = _int(body.get('amount'), 'amount')
target = _int(body.get('target'), 'target', maximum=2**53-1)
_user(con, target)
reason = _text(body.get('reason'), 'Основание', 5, 500)
if action == 'grant':
if uid not in admins:
_fail(403, 'admin_only', 'Начисление доступно только администрации.')
spent = con.execute("SELECT COALESCE(SUM(amount),0) FROM community_ledger WHERE kind='grant' AND ts>=?", (now // 86400 * 86400,)).fetchone()[0]
if spent + amount > DAILY_GRANT_LIMIT:
_fail(409, 'grant_budget', 'Дневной фонд начислений исчерпан.')
src = 0
else:
if target == uid:
_fail(400, 'self_transfer', 'Нельзя перевести монеты самому себе.')
src = uid
_move(con, uid, src, target, amount, action, reason, now)
elif action == 'create':
title = _text(body.get('title'), 'Задание', 8, 300)
criteria = _text(body.get('criteria'), 'Условия приёмки', 15, 1500)
reward = _int(body.get('reward'), 'reward')
count = con.execute("SELECT COUNT(*) FROM community_tasks WHERE creator=? AND status IN ('open','claimed','submitted','disputed')", (uid,)).fetchone()[0]
if count >= 10:
_fail(409, 'task_limit', 'Можно держать не более 10 незакрытых заданий.')
cur = con.execute('INSERT INTO community_tasks(creator,title,criteria,reward,created,updated) VALUES(?,?,?,?,?,?)', (uid, title, criteria, reward, now, now))
task_id = cur.lastrowid
if task_id is None:
raise RuntimeError('SQLite did not return a task id')
_move(con, uid, uid, -task_id, reward, 'escrow', title, now, task_id)
result['task_id'] = task_id
elif action in ('claim', 'release', 'submit', 'accept', 'cancel', 'dispute', 'resolve'):
task_id = _int(body.get('task_id'), 'task_id', maximum=2**53-1)
revision = _int(body.get('revision'), 'revision', minimum=0, maximum=2**31-1)
task = con.execute('SELECT * FROM community_tasks WHERE id=?', (task_id,)).fetchone()
if task is None:
_fail(404, 'task_not_found', 'Задание не найдено.')
if task['revision'] != revision:
_fail(409, 'stale_revision', 'Задание изменилось. Обнови список перед действием.')
status, creator, worker = task['status'], task['creator'], task['worker']
updates: dict[str, object] = {}
if action == 'claim':
if status != 'open' or uid == creator:
_fail(409, 'not_claimable', 'Нельзя взять своё или занятое задание.')
count = con.execute("SELECT COUNT(*) FROM community_tasks WHERE worker=? AND status IN ('claimed','submitted','disputed')", (uid,)).fetchone()[0]
if count >= 5:
_fail(409, 'worker_limit', 'Заверши текущие задания: максимум 5 в работе.')
updates = {'worker': uid, 'status': 'claimed'}
elif action == 'release':
if uid != worker or status != 'claimed':
_fail(403, 'not_releasable', 'Отказаться можно только от своего несданного задания.')
updates = {'worker': None, 'status': 'open'}
elif action == 'submit':
if uid != worker or status != 'claimed':
_fail(403, 'not_submittable', 'Сдать результат может только исполнитель задания в работе.')
updates = {'proof': _text(body.get('proof'), 'Результат', 15, 3000), 'status': 'submitted'}
elif action == 'accept':
if uid != creator or status != 'submitted':
_fail(403, 'not_acceptable', 'Заказчик принимает только сданную работу.')
_move(con, uid, -task_id, worker, task['reward'], 'payout', task['title'], now, task_id)
updates = {'status': 'done'}
elif action == 'cancel':
if uid != creator or status != 'open':
_fail(403, 'not_cancellable', 'Отменить можно только своё ещё не взятое задание.')
_move(con, uid, -task_id, creator, task['reward'], 'refund', task['title'], now, task_id)
updates = {'status': 'cancelled'}
elif action == 'dispute':
if uid not in (creator, worker) or status not in ('claimed', 'submitted'):
_fail(403, 'not_disputable', 'Спор доступен участникам незакрытого задания.')
updates = {'status': 'disputed', 'dispute': _text(body.get('reason'), 'Причина спора', 15, 1500)}
else:
if uid not in admins:
_fail(403, 'admin_only', 'Спор разрешает администрация.')
if uid in (creator, worker):
_fail(403, 'conflict_of_interest', 'Участник задания не может решать собственный спор.')
if status != 'disputed' or body.get('decision') not in ('pay', 'refund'):
_fail(409, 'invalid_resolution', 'Нужен открытый спор и решение pay или refund.')
reason = _text(body.get('reason'), 'Решение', 15, 1500)
pay = body['decision'] == 'pay'
_move(con, uid, -task_id, worker if pay else creator, task['reward'], 'resolution', reason, now, task_id)
updates = {'status': 'done' if pay else 'cancelled', 'resolution': reason}
updates.update(revision=revision+1, updated=now)
assignments = ','.join(key+'=?' for key in updates)
con.execute('UPDATE community_tasks SET '+assignments+' WHERE id=?', (*updates.values(), task_id))
result.update(task_id=task_id, revision=revision+1, status=updates['status'])
else:
_fail(400, 'unknown_action', 'Неизвестное действие экономики.')
con.execute('INSERT INTO community_operations(actor,request_id,digest,result) VALUES(?,?,?,?)', (uid, request_id, digest, json.dumps(result)))
con.commit()
return result
except Exception:
con.rollback()
raise