games_app/backend/src/services/shareCardService.ts
2026-09-24 19:09:26 +02:00

539 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Share Cards: eligibility, signed verify tokens, and share payloads
* for prediction results and wallet operations (deposit / withdrawal / transfer).
*/
import crypto from 'crypto';
import { config } from '../config';
import { query } from '../db/connection';
import { getPublicWebBaseUrl, buildReferralRegisterLink } from '../utils/publicWebUrl';
import * as shareCardRepository from '../repositories/shareCardRepository';
import * as candlePredictRepository from '../repositories/candlePredictRepository';
import * as referralRepository from '../repositories/referralRepository';
import * as transactionRepository from '../repositories/transactionRepository';
import * as walletRepository from '../repositories/walletRepository';
import type { ShareCardSettingsRow } from '../repositories/shareCardRepository';
import type { Transaction } from '../models';
export type ShareableBetStatus = 'won' | 'lost' | 'refunded';
export type StakeAccountKind = 'main' | 'bonus' | 'test';
export type ShareableWalletOpType =
| 'deposit'
| 'withdrawal'
| 'transfer'
| 'bonus'
| 'admin_adjustment';
const STAKE_DECIMALS = 6;
export function mapSettingsForClient(
row: ShareCardSettingsRow,
extras?: {
hasDeposited?: boolean;
}
) {
const testWalletShareRequiresRealDeposit =
row.test_wallet_share_requires_real_deposit !== false;
return {
enabled: Boolean(row.enabled),
allowMainWallet: Boolean(row.allow_main_wallet),
allowBonusWallet: Boolean(row.allow_bonus_wallet),
allowTestWallet: Boolean(row.allow_test_wallet),
allowWon: Boolean(row.allow_won),
allowLost: Boolean(row.allow_lost),
allowRefunded: Boolean(row.allow_refunded),
walletOpsEnabled: row.wallet_ops_enabled !== false,
allowDeposit: row.allow_deposit !== false,
allowWithdrawal: row.allow_withdrawal !== false,
allowTransfer: row.allow_transfer !== false,
testWalletShareRequiresRealDeposit,
// Alias for clients that still read the old referral-tied field.
referrerMustHaveDeposited: testWalletShareRequiresRealDeposit,
hasDeposited: extras?.hasDeposited === true,
updatedAt: row.updated_at.toISOString(),
};
}
/** Ledger row used to decide whether a user has ever deposited real funds. */
export type LedgerActivityRow = {
type: string;
status: string;
};
/**
* A real-funds deposit is a ledger `deposit` that reached `completed`.
* Test-wallet credits, bonus grants, admin adjustments, pending/failed
* deposits, and the current Main Wallet balance are ignored.
*/
export function isConfirmedRealDeposit(tx: LedgerActivityRow): boolean {
return tx.type === 'deposit' && tx.status === 'completed';
}
export function hasConfirmedRealDeposit(history: LedgerActivityRow[]): boolean {
return history.some(isConfirmedRealDeposit);
}
async function userHasConfirmedRealDeposit(userId: string): Promise<boolean> {
const rows = await query<Array<{ n: string }>>(
`SELECT 1 AS n
FROM transactions
WHERE user_id = $1
AND type = 'deposit'
AND status = 'completed'
LIMIT 1`,
[userId]
);
return Boolean(rows[0]);
}
export function canSharePredictionResult(
settings: ShareCardSettingsRow,
input: {
stakeAccountKind: StakeAccountKind;
status: string;
testWalletShareRequiresRealDeposit?: boolean;
hasDeposited?: boolean;
}
): boolean {
if (!settings.enabled) return false;
if (input.status !== 'won' && input.status !== 'lost' && input.status !== 'refunded') {
return false;
}
if (input.stakeAccountKind === 'main' && !settings.allow_main_wallet) return false;
if (input.stakeAccountKind === 'bonus' && !settings.allow_bonus_wallet) return false;
if (input.stakeAccountKind === 'test') {
if (!settings.allow_test_wallet) return false;
const requiresDeposit =
input.testWalletShareRequiresRealDeposit ??
settings.test_wallet_share_requires_real_deposit !== false;
// Public verify omits hasDeposited — do not revoke an already-issued card.
if (requiresDeposit && input.hasDeposited === false) return false;
}
if (input.status === 'won' && !settings.allow_won) return false;
if (input.status === 'lost' && !settings.allow_lost) return false;
if (input.status === 'refunded' && !settings.allow_refunded) return false;
return true;
}
export function canShareWalletOperation(
settings: ShareCardSettingsRow,
input: { type: string }
): boolean {
if (!settings.enabled || !settings.wallet_ops_enabled) return false;
// Deposits tab also lists bonus credits and admin balance adjustments.
if (
input.type === 'deposit' ||
input.type === 'bonus' ||
input.type === 'admin_adjustment'
) {
return settings.allow_deposit;
}
if (input.type === 'withdrawal') return settings.allow_withdrawal;
if (input.type === 'transfer') return settings.allow_transfer;
return false;
}
function rawToDisplay(raw: bigint, decimals = STAKE_DECIMALS): string {
const neg = raw < 0n;
const abs = neg ? -raw : raw;
const base = 10n ** BigInt(decimals);
const whole = abs / base;
const frac = (abs % base).toString().padStart(decimals, '0');
const trimmed = frac.replace(/0+$/, '');
const body = trimmed ? `${whole}.${trimmed}` : whole.toString();
return neg ? `-${body}` : body;
}
/**
* Amount shown on share cards — matches Wallet/Recent Predictions UI:
* - won: full payout (stake + profit), e.g. +9.5
* - lost: −stake
* - refunded: +payout when stake is returned, else 0
*/
export function computeResultAmount(
status: ShareableBetStatus,
stakeRaw: bigint,
payoutRaw: bigint
): {
resultSignedDisplay: string;
resultRaw: string;
pnlSign: '+' | '-' | '';
} {
if (status === 'won') {
const display = rawToDisplay(payoutRaw);
return {
resultSignedDisplay: `+${display}`,
resultRaw: payoutRaw.toString(),
pnlSign: '+',
};
}
if (status === 'lost') {
const display = rawToDisplay(stakeRaw);
return {
resultSignedDisplay: `-${display}`,
resultRaw: (-stakeRaw).toString(),
pnlSign: '-',
};
}
if (payoutRaw > 0n) {
const display = rawToDisplay(payoutRaw);
return {
resultSignedDisplay: `+${display}`,
resultRaw: payoutRaw.toString(),
pnlSign: '+',
};
}
return {
resultSignedDisplay: '0',
resultRaw: '0',
pnlSign: '',
};
}
function b64url(buf: Buffer | string): string {
const b = typeof buf === 'string' ? Buffer.from(buf, 'utf8') : buf;
return b.toString('base64url');
}
function shareSecret(): string {
return process.env.SHARE_CARD_SECRET?.trim() || config.jwt.secret;
}
export type ShareTokenKind = 'bet' | 'tx';
export function createShareVerifyToken(
kind: ShareTokenKind,
resourceId: string,
userId: string
): string {
const payload = b64url(JSON.stringify({ k: kind, id: resourceId, u: userId, v: 2 }));
const sig = crypto.createHmac('sha256', shareSecret()).update(payload).digest();
return `${payload}.${b64url(sig)}`;
}
/** @deprecated Prefer createShareVerifyToken('bet', ...) — kept for call-site clarity. */
export function createBetShareVerifyToken(betId: string, userId: string): string {
return createShareVerifyToken('bet', betId, userId);
}
export function parseShareVerifyToken(
token: string
): { kind: ShareTokenKind; id: string; userId: string } | null {
const parts = token.split('.');
if (parts.length !== 2) return null;
const [payload, sig] = parts;
if (!payload || !sig) return null;
const expected = b64url(crypto.createHmac('sha256', shareSecret()).update(payload).digest());
const a = Buffer.from(sig);
const b = Buffer.from(expected);
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
try {
const json = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as {
k?: string;
id?: string;
b?: string;
u?: string;
v?: number;
};
if (!json.u) return null;
// v2: { k, id, u }
if (json.k === 'bet' || json.k === 'tx') {
if (!json.id) return null;
return { kind: json.k, id: json.id, userId: json.u };
}
// v1 legacy prediction tokens: { b, u }
if (json.b) {
return { kind: 'bet', id: json.b, userId: json.u };
}
return null;
} catch {
return null;
}
}
export function buildShareVerifyUrl(token: string): string {
return `${getPublicWebBaseUrl()}/share/r/${encodeURIComponent(token)}`;
}
function buildPredictionCardPayload(
bet: candlePredictRepository.CandlePredictBetWithSettlement,
opts: { includeReferral: boolean; referralCode: string | null }
) {
const status = bet.status as ShareableBetStatus;
const stakeRaw = BigInt(bet.stake_raw);
const payoutRaw = BigInt(bet.payout_raw);
const result = computeResultAmount(status, stakeRaw, payoutRaw);
const token = createShareVerifyToken('bet', bet.id, bet.user_id);
const verifyUrl = buildShareVerifyUrl(token);
const registerUrl = opts.referralCode
? buildReferralRegisterLink(opts.referralCode)
: `${getPublicWebBaseUrl()}/register`;
return {
kind: 'prediction' as const,
betId: bet.id,
gameName: 'Candle Predict',
direction: bet.direction,
sequence: bet.sequence_directions,
multiLevel: bet.multi_level,
predictionMode: bet.prediction_mode,
isAuto: bet.is_auto,
status,
stakeDisplay: Number(bet.stake_display),
stakeRaw: bet.stake_raw,
payoutRaw: bet.payout_raw,
resultSignedDisplay: result.resultSignedDisplay,
resultRaw: result.resultRaw,
pnlSign: result.pnlSign,
intervalMinutes: bet.interval_minutes,
stakeAccountKind: bet.stake_account_kind,
settledAt: bet.settled_at?.toISOString() ?? bet.created_at.toISOString(),
verifyUrl,
verifyToken: token,
referralCode: opts.includeReferral ? opts.referralCode : null,
registerUrl,
};
}
function shortAssetSymbol(code: string): string {
const base = code.split('_')[0] || code;
return base.toUpperCase();
}
/** Human network label for share cards (prefer rail metadata over ledger type). */
function shareNetworkLabel(network: string | null, assetCode: string): string | null {
if (!network && !assetCode) return null;
const code = assetCode.toUpperCase();
const net = (network || '').toUpperCase();
if (code.includes('BEP20') || net === 'BSC') return 'BSC (BEP20)';
if (code.includes('TRC20') || net === 'TRON') return 'TRON (TRC20)';
return network;
}
async function buildWalletOpCardPayload(
tx: Transaction,
opts: { includeReferral: boolean; referralCode: string | null }
) {
const ledgerWt = await walletRepository.getWalletTypeById(tx.wallet_type_id);
const meta = (tx.metadata ?? {}) as Record<string, unknown>;
const railCode =
typeof meta.rail_wallet_type === 'string'
? meta.rail_wallet_type
: typeof meta.source_wallet_type === 'string'
? meta.source_wallet_type
: null;
// Withdrawals/deposits credit a unified ledger (often USDT_TRC20) but custody/payout
// rail is stored in metadata — prefer that for share-card asset/network labels.
let displayWt = ledgerWt;
if (railCode) {
const rail = await walletRepository.getWalletTypeByCode(railCode);
if (rail) displayWt = rail;
}
const decimals = ledgerWt?.decimals ?? STAKE_DECIMALS;
const amountRaw = BigInt(tx.amount);
const amountDisplay = rawToDisplay(amountRaw, decimals);
const assetCode = displayWt?.code ?? ledgerWt?.code ?? 'USDT';
const assetSymbol = shortAssetSymbol(assetCode);
const network = shareNetworkLabel(
(typeof meta.network === 'string' && meta.network.trim()
? meta.network.trim()
: null) ??
displayWt?.network ??
null,
assetCode
);
const token = createShareVerifyToken('tx', tx.id, tx.user_id);
const verifyUrl = buildShareVerifyUrl(token);
const registerUrl = opts.referralCode
? buildReferralRegisterLink(opts.referralCode)
: `${getPublicWebBaseUrl()}/register`;
// Share cards are marketing-facing: show received/sent principal only (no platform fee).
const signedDisplay =
tx.type === 'withdrawal'
? `-${amountDisplay}`
: tx.type === 'transfer'
? amountDisplay
: `+${amountDisplay}`;
return {
kind: 'wallet' as const,
transactionId: tx.id,
operationType: tx.type as ShareableWalletOpType,
status: tx.status,
amountRaw: tx.amount,
amountDisplay,
amountSignedDisplay: signedDisplay,
feeRaw: '0',
assetCode,
assetSymbol,
assetName: displayWt?.name ?? assetCode,
network,
createdAt: tx.created_at.toISOString(),
blockchainTxId: tx.blockchain_tx_id,
verifyUrl,
verifyToken: token,
referralCode: opts.includeReferral ? opts.referralCode : null,
registerUrl,
};
}
export async function getConfigForUser(userId: string) {
const [settings, hasDeposited] = await Promise.all([
shareCardRepository.getSettings(),
userHasConfirmedRealDeposit(userId),
]);
return mapSettingsForClient(settings, { hasDeposited });
}
export async function getSettingsForAdmin() {
const settings = await shareCardRepository.getSettings();
return mapSettingsForClient(settings);
}
export async function updateSettings(input: {
enabled?: boolean;
allowMainWallet?: boolean;
allowBonusWallet?: boolean;
allowTestWallet?: boolean;
allowWon?: boolean;
allowLost?: boolean;
allowRefunded?: boolean;
walletOpsEnabled?: boolean;
allowDeposit?: boolean;
allowWithdrawal?: boolean;
allowTransfer?: boolean;
testWalletShareRequiresRealDeposit?: boolean;
}) {
const row = await shareCardRepository.updateSettings(input);
return mapSettingsForClient(row);
}
export class ShareCardError extends Error {
status: number;
constructor(message: string, status = 400) {
super(message);
this.name = 'ShareCardError';
this.status = status;
}
}
export async function getSharePayloadForOwner(userId: string, betId: string) {
const settings = await shareCardRepository.getSettings();
const bet = await candlePredictRepository.getBetById(betId);
if (!bet || bet.user_id !== userId) {
throw new ShareCardError('Prediction not found', 404);
}
const hasDeposited = await userHasConfirmedRealDeposit(userId);
if (
!canSharePredictionResult(settings, {
stakeAccountKind: bet.stake_account_kind,
status: bet.status,
testWalletShareRequiresRealDeposit:
settings.test_wallet_share_requires_real_deposit !== false,
hasDeposited,
})
) {
if (
bet.stake_account_kind === 'test' &&
settings.test_wallet_share_requires_real_deposit !== false &&
!hasDeposited
) {
throw new ShareCardError(
'You must make at least one real-funds deposit before sharing Test Wallet results and using your referral link.',
403
);
}
throw new ShareCardError('Sharing is not available for this prediction', 403);
}
const referralCode = await referralRepository.getUserReferralCode(userId);
return buildPredictionCardPayload(bet, { includeReferral: true, referralCode });
}
export async function getWalletOpSharePayloadForOwner(userId: string, transactionId: string) {
const settings = await shareCardRepository.getSettings();
const tx = await transactionRepository.findById(transactionId);
if (!tx || tx.user_id !== userId) {
throw new ShareCardError('Transaction not found', 404);
}
if (!canShareWalletOperation(settings, { type: tx.type })) {
throw new ShareCardError('Sharing is not available for this operation', 403);
}
const referralCode = await referralRepository.getUserReferralCode(userId);
return buildWalletOpCardPayload(tx, { includeReferral: true, referralCode });
}
export async function getPublicVerifyPayload(token: string) {
const parsed = parseShareVerifyToken(token);
if (!parsed) {
throw new ShareCardError('Invalid or tampered share token', 400);
}
const settings = await shareCardRepository.getSettings();
if (!settings.enabled) {
throw new ShareCardError('Share cards are disabled', 404);
}
if (parsed.kind === 'tx') {
if (!settings.wallet_ops_enabled) {
throw new ShareCardError('Wallet share cards are disabled', 404);
}
const tx = await transactionRepository.findById(parsed.id);
if (!tx || tx.user_id !== parsed.userId) {
throw new ShareCardError('Transaction not found', 404);
}
if (!canShareWalletOperation(settings, { type: tx.type })) {
throw new ShareCardError('This operation is no longer shareable', 404);
}
const referralCode = await referralRepository.getUserReferralCode(tx.user_id);
const card = await buildWalletOpCardPayload(tx, { includeReferral: true, referralCode });
return {
authentic: true as const,
kind: 'wallet' as const,
operationType: card.operationType,
status: card.status,
amountSignedDisplay: card.amountSignedDisplay,
amountDisplay: card.amountDisplay,
assetSymbol: card.assetSymbol,
assetCode: card.assetCode,
network: card.network,
createdAt: card.createdAt,
registerUrl: card.registerUrl,
referralCode: card.referralCode,
};
}
const bet = await candlePredictRepository.getBetById(parsed.id);
if (!bet || bet.user_id !== parsed.userId) {
throw new ShareCardError('Prediction not found', 404);
}
if (
!canSharePredictionResult(settings, {
stakeAccountKind: bet.stake_account_kind,
status: bet.status,
})
) {
throw new ShareCardError('This result is no longer shareable', 404);
}
const referralCode = await referralRepository.getUserReferralCode(bet.user_id);
const card = buildPredictionCardPayload(bet, { includeReferral: true, referralCode });
return {
authentic: true as const,
kind: 'prediction' as const,
gameName: card.gameName,
direction: card.direction,
sequence: card.sequence,
multiLevel: card.multiLevel,
predictionMode: card.predictionMode,
isAuto: card.isAuto,
status: card.status,
resultSignedDisplay: card.resultSignedDisplay,
stakeDisplay: card.stakeDisplay,
intervalMinutes: card.intervalMinutes,
settledAt: card.settledAt,
registerUrl: card.registerUrl,
referralCode: card.referralCode,
};
}