Implement full MVP: auth, HD wallet, Electrum client, deposits, bets, round/draw engine, payout, withdrawals, RBF, admin+audit

All 10 build-order stages complete and unit-tested (49 tests). Verified live on
mainnet: registration/address derivation, deposit crediting, a real 10 PLM bet
(broadcast + confirmed + change credited). A full round close->draw->payout
cycle was triggered live and was in progress at commit time. Withdrawal and RBF
bump are unit-tested but not yet exercised against a live broadcast. Known gaps
(scheduler doesn't resume mid-flight rounds after restart, payout has no retry,
no deployment setup, etc.) are documented in CLAUDE.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-20 23:52:20 +02:00
co-authored by Claude Sonnet 5
parent bae48c46dc
commit df72367f02
76 changed files with 3506 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.
+85
View File
@@ -0,0 +1,85 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
from app.config import settings
from app.db.base import Base
from app.db import models # noqa: F401 (registers models on Base.metadata)
target_metadata = Base.metadata
config.set_main_option("sqlalchemy.url", settings.database_url)
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,153 @@
"""initial schema
Revision ID: 274efdcbfbcc
Revises:
Create Date: 2026-07-20 22:11:47.766165
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '274efdcbfbcc'
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('round_config',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('fee_address', sa.String(length=128), nullable=False),
sa.Column('bet_amount_sats', sa.BigInteger(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=64), nullable=False),
sa.Column('password_hash', sa.String(length=256), nullable=False),
sa.Column('derivation_index', sa.Integer(), nullable=False),
sa.Column('address', sa.String(length=128), nullable=False),
sa.Column('cached_balance_sats', sa.BigInteger(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('address'),
sa.UniqueConstraint('derivation_index')
)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('rounds',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('status', sa.String(length=16), nullable=False),
sa.Column('opened_at', sa.DateTime(), nullable=False),
sa.Column('closed_at', sa.DateTime(), nullable=True),
sa.Column('draw_block_height', sa.Integer(), nullable=True),
sa.Column('draw_block_hash', sa.String(length=64), nullable=True),
sa.Column('seed_int', sa.String(length=128), nullable=True),
sa.Column('winner_user_id', sa.Integer(), nullable=True),
sa.Column('pool_amount_sats', sa.BigInteger(), nullable=True),
sa.Column('winner_amount_sats', sa.BigInteger(), nullable=True),
sa.Column('fee_amount_sats', sa.BigInteger(), nullable=True),
sa.Column('payout_txid', sa.String(length=64), nullable=True),
sa.ForeignKeyConstraint(['winner_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('utxo_events',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('txid', sa.String(length=64), nullable=False),
sa.Column('vout', sa.Integer(), nullable=False),
sa.Column('amount_sats', sa.BigInteger(), nullable=False),
sa.Column('confirmed_height', sa.Integer(), nullable=False),
sa.Column('confirmed_at', sa.DateTime(), nullable=False),
sa.Column('spent_txid', sa.String(length=64), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('txid', 'vout')
)
op.create_index(op.f('ix_utxo_events_user_id'), 'utxo_events', ['user_id'], unique=False)
op.create_table('withdrawals',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('external_address', sa.String(length=128), nullable=False),
sa.Column('amount_requested_sats', sa.BigInteger(), nullable=False),
sa.Column('amount_sent_sats', sa.BigInteger(), nullable=True),
sa.Column('txid', sa.String(length=64), nullable=True),
sa.Column('status', sa.String(length=16), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_withdrawals_user_id'), 'withdrawals', ['user_id'], unique=False)
op.create_table('audit_log',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_type', sa.String(length=32), nullable=False),
sa.Column('payload_json', sa.String(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('round_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['round_id'], ['rounds.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('pending_transactions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(length=16), nullable=False),
sa.Column('round_id', sa.Integer(), nullable=True),
sa.Column('withdrawal_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('current_txid', sa.String(length=64), nullable=False),
sa.Column('fee_rate_sat_vb', sa.Integer(), nullable=False),
sa.Column('raw_tx_hex', sa.String(), nullable=False),
sa.Column('broadcast_at', sa.DateTime(), nullable=False),
sa.Column('status', sa.String(length=16), nullable=False),
sa.Column('replaced_by_txid', sa.String(length=64), nullable=True),
sa.Column('attempt_count', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['round_id'], ['rounds.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['withdrawal_id'], ['withdrawals.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('round_participants',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('round_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('bet_amount_sats', sa.BigInteger(), nullable=False),
sa.Column('bet_txid', sa.String(length=64), nullable=False),
sa.Column('broadcast_at', sa.DateTime(), nullable=False),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.Column('status', sa.String(length=16), nullable=False),
sa.ForeignKeyConstraint(['round_id'], ['rounds.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('round_id', 'user_id')
)
op.create_index(op.f('ix_round_participants_round_id'), 'round_participants', ['round_id'], unique=False)
op.create_index(op.f('ix_round_participants_user_id'), 'round_participants', ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_round_participants_user_id'), table_name='round_participants')
op.drop_index(op.f('ix_round_participants_round_id'), table_name='round_participants')
op.drop_table('round_participants')
op.drop_table('pending_transactions')
op.drop_table('audit_log')
op.drop_index(op.f('ix_withdrawals_user_id'), table_name='withdrawals')
op.drop_table('withdrawals')
op.drop_index(op.f('ix_utxo_events_user_id'), table_name='utxo_events')
op.drop_table('utxo_events')
op.drop_table('rounds')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_table('users')
op.drop_table('round_config')
# ### end Alembic commands ###