Crypto Casino Deposit/Withdrawal System Development
The financial system of a crypto casino is the technically most critical component. It must handle thousands of transactions, support instant deposits, minimize withdrawal latency, and ensure zero errors in user fund accounting.
Architecture: Internal Ledger
A crypto casino does not store user funds directly on the blockchain. The correct architecture is internal ledger:
User → Deposit Address (blockchain) → Hot Wallet → Internal Balance
↓
Withdrawal: Internal Balance → Hot Wallet → User's Wallet (blockchain)
The internal balance is a database record. Real coins are held in the casino's hot wallet. This is the standard model for all casinos and exchanges.
Advantages:
- Instant operations within the system (bets, bonuses, inter-game transfers)
- No need to wait for blockchain confirmations for each bet
- Ability to support fractional balances below the minimum transaction amount
Deposit Flow
class DepositService:
REQUIRED_CONFIRMATIONS = {
"BTC": 2,
"ETH": 12,
"USDT_TRC20": 20,
"SOL": 30,
"BNB": 15,
}
async def get_deposit_address(self, user_id: str, currency: str) -> str:
"""Returns a unique deposit address for the user"""
# Check for existing address
existing = await self.address_repo.get(user_id=user_id, currency=currency)
if existing:
return existing.address
# Generate new address from HD Wallet
address = await self.wallet_manager.generate_address(currency, user_id)
await self.address_repo.save(
user_id=user_id,
currency=currency,
address=address
)
return address
async def on_incoming_transaction(self, tx: BlockchainTransaction):
"""Called on each incoming transaction"""
# Find user by address
address_record = await self.address_repo.find_by_address(
tx.to_address, tx.currency
)
if not address_record:
return # Not our address
# Save pending deposit
deposit = PendingDeposit(
user_id=address_record.user_id,
currency=tx.currency,
amount=tx.amount,
tx_hash=tx.hash,
required_confirmations=self.REQUIRED_CONFIRMATIONS.get(tx.currency, 12),
current_confirmations=tx.confirmations,
status="PENDING",
)
await self.deposit_repo.save(deposit)
async def on_confirmation_update(self, tx_hash: str, confirmations: int):
"""Update confirmation count"""
deposit = await self.deposit_repo.get_by_tx(tx_hash)
if not deposit or deposit.status != "PENDING":
return
if confirmations >= deposit.required_confirmations:
await self.credit_user(deposit)
async def credit_user(self, deposit: PendingDeposit):
"""Credit to internal balance (idempotent operation)"""
async with self.db.transaction():
# Check that we haven't already credited (idempotency)
if await self.deposit_repo.is_credited(deposit.id):
return
await self.balance_repo.credit(
user_id=deposit.user_id,
currency=deposit.currency,
amount=deposit.amount,
reference=f"DEPOSIT:{deposit.tx_hash}",
)
await self.deposit_repo.mark_credited(deposit.id)
# Notify the user
await self.notifier.send_deposit_confirmed(
user_id=deposit.user_id,
amount=deposit.amount,
currency=deposit.currency,
)
Internal Balance Ledger
All fund accounting is done through a ledger with double-entry bookkeeping:
CREATE TABLE ledger_entries (
id BIGSERIAL PRIMARY KEY,
entry_time TIMESTAMPTZ NOT NULL DEFAULT NOW(),
user_id UUID NOT NULL,
currency VARCHAR(16) NOT NULL,
amount NUMERIC(24, 8) NOT NULL, -- positive = credit, negative = debit
balance_after NUMERIC(24, 8) NOT NULL,
type VARCHAR(32) NOT NULL, -- DEPOSIT, WITHDRAWAL, BET_WIN, BET_LOSS, BONUS, etc.
reference_id VARCHAR(64), -- tx_hash, bet_id, bonus_id
description VARCHAR(255),
INDEX(user_id, currency, entry_time DESC)
);
Each balance operation creates a ledger entry. The current balance is the sum of all entries for a user by currency:
-- Get current balance
SELECT currency, SUM(amount) as balance
FROM ledger_entries
WHERE user_id = $1
GROUP BY currency;
-- Or a denormalized balance table (updated atomically)
CREATE TABLE user_balances (
user_id UUID NOT NULL,
currency VARCHAR(16) NOT NULL,
balance NUMERIC(24, 8) NOT NULL DEFAULT 0,
locked NUMERIC(24, 8) NOT NULL DEFAULT 0, -- in withdrawal process
PRIMARY KEY (user_id, currency),
CHECK (balance >= 0),
CHECK (locked >= 0),
CHECK (balance >= locked)
);
Withdrawal Flow
class WithdrawalService:
MIN_WITHDRAWAL = {
"BTC": Decimal("0.0001"),
"ETH": Decimal("0.005"),
"USDT_TRC20": Decimal("5"),
}
async def request_withdrawal(
self,
user_id: str,
currency: str,
amount: Decimal,
destination_address: str,
) -> WithdrawalRequest:
# Validate
if amount < self.MIN_WITHDRAWAL.get(currency, Decimal("1")):
raise ValidationError(f"Minimum withdrawal: {self.MIN_WITHDRAWAL[currency]} {currency}")
user_balance = await self.balance_repo.get_balance(user_id, currency)
if user_balance.available < amount:
raise InsufficientFundsError()
# Blockchain address validation
if not self.validate_address(destination_address, currency):
raise ValidationError("Invalid destination address")
# AML check
aml_result = await self.aml_service.check_address(destination_address, currency)
if aml_result.risk_score > 7:
raise ComplianceError("Destination address failed AML check")
async with self.db.transaction():
# Lock funds
await self.balance_repo.lock_funds(user_id, currency, amount)
# Create request
request = WithdrawalRequest(
user_id=user_id,
currency=currency,
amount=amount,
destination=destination_address,
status="PENDING",
aml_score=aml_result.risk_score,
)
await self.withdrawal_repo.save(request)
# Queue for processing
await self.withdrawal_queue.enqueue(request.id)
return request
async def process_withdrawal(self, request_id: str):
"""Processed by worker from queue"""
request = await self.withdrawal_repo.get(request_id)
# Manual verification for large withdrawals
if request.amount_usd > 10_000:
if not request.manual_approved:
await self.notify_compliance_team(request)
return
# Send transaction from hot wallet
try:
tx_hash = await self.hot_wallet.send(
currency=request.currency,
to=request.destination,
amount=request.amount - self.get_network_fee(request.currency),
)
await self.withdrawal_repo.mark_sent(request.id, tx_hash)
except InsufficientHotWalletFunds:
# Hot wallet needs to be replenished from cold storage
await self.alert_treasury("Hot wallet needs refill")
await self.withdrawal_repo.mark_queued(request.id)
Hot/Cold Wallet Management
Hot wallet is an online wallet for processing withdrawals. It should contain only operational reserves: 15–20% of total user funds.
Cold wallet is offline storage. Multi-signature (3-of-5 keys), keys held by different responsible persons, hot wallet replenishment is a manual process with multiple signatures.
class HotWalletManager:
TARGET_BALANCE_PCT = 0.15 # 15% of total deposits
LOW_BALANCE_THRESHOLD_PCT = 0.05 # alert if < 5%
async def check_balance_health(self, currency: str):
hot_balance = await self.get_hot_wallet_balance(currency)
total_user_balances = await self.balance_repo.get_total_user_balance(currency)
ratio = float(hot_balance / total_user_balances) if total_user_balances > 0 else 1.0
if ratio < self.LOW_BALANCE_THRESHOLD_PCT:
await self.alert_treasury(
f"Hot wallet {currency} low: {ratio:.1%} of user balances. "
f"Refill needed: {total_user_balances * Decimal('0.15') - hot_balance:.4f} {currency}"
)
Reconciliation
Daily reconciliation of internal balances with real blockchain data:
async def daily_reconciliation(self, currency: str):
"""Reconcile internal data with blockchain"""
# Total internal user balance
internal_total = await self.balance_repo.get_total_user_balance(currency)
# Real balance on our addresses
hot_balance = await self.wallet.get_balance(currency, 'hot')
cold_balance = await self.wallet.get_balance(currency, 'cold')
real_total = hot_balance + cold_balance
# Pending withdrawals (not yet sent)
pending = await self.withdrawal_repo.get_pending_total(currency)
discrepancy = real_total + pending - internal_total
if abs(discrepancy) > Decimal("0.0001"):
await self.alert_finance(
f"RECONCILIATION DISCREPANCY {currency}: {discrepancy}"
)
The reconciliation system is insurance against coding errors and potential misconduct. Any discrepancy requires immediate investigation.







