415 lines
16 KiB
TypeScript
415 lines
16 KiB
TypeScript
import { query, getClient, beginAuthorizedTransaction } from '../db/connection';
|
|
import { PoolClient } from 'pg';
|
|
import { LedgerAccount } from '../models';
|
|
|
|
export type AccountKind = 'main' | 'bonus' | 'test';
|
|
|
|
/**
|
|
* Repository for double-entry ledger accounts and balance operations.
|
|
* Manages available and locked balances with transactional credit, debit, and transfer flows.
|
|
*/
|
|
|
|
/**
|
|
* Ensures a ledger account exists for a user and wallet type, then returns it.
|
|
* @param userId - ID of the account owner.
|
|
* @param walletTypeId - Wallet type for the account.
|
|
* @returns The ledger account record (created if it did not exist).
|
|
*/
|
|
export async function getOrCreateAccount(
|
|
userId: string,
|
|
walletTypeId: number,
|
|
accountKind: AccountKind = 'main'
|
|
): Promise<LedgerAccount> {
|
|
await query(
|
|
`INSERT INTO ledger_accounts (user_id, wallet_type_id, account_kind)
|
|
VALUES ($1, $2, $3)
|
|
ON CONFLICT (user_id, wallet_type_id, account_kind) DO NOTHING`,
|
|
[userId, walletTypeId, accountKind]
|
|
);
|
|
const rows = await query<LedgerAccount[]>(
|
|
`SELECT id, user_id, wallet_type_id, available_balance::text, locked_balance::text, updated_at
|
|
FROM ledger_accounts WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = $3`,
|
|
[userId, walletTypeId, accountKind]
|
|
);
|
|
return rows[0];
|
|
}
|
|
|
|
/**
|
|
* @deprecated Use getOrCreateAccount with accountKind. Kept for backward compatibility.
|
|
*/
|
|
export async function getOrCreateMainAccount(userId: string, walletTypeId: number): Promise<LedgerAccount> {
|
|
return getOrCreateAccount(userId, walletTypeId, 'main');
|
|
}
|
|
|
|
export async function getOrCreateBonusAccount(userId: string, walletTypeId: number): Promise<LedgerAccount> {
|
|
return getOrCreateAccount(userId, walletTypeId, 'bonus');
|
|
}
|
|
|
|
export async function getOrCreateTestAccount(userId: string, walletTypeId: number): Promise<LedgerAccount> {
|
|
return getOrCreateAccount(userId, walletTypeId, 'test');
|
|
}
|
|
|
|
/**
|
|
* Retrieves an existing ledger account without creating one.
|
|
* @param userId - ID of the account owner.
|
|
* @param walletTypeId - Wallet type for the account.
|
|
* @returns The ledger account record, or null if it does not exist.
|
|
*/
|
|
export async function getAccount(
|
|
userId: string,
|
|
walletTypeId: number,
|
|
accountKind: AccountKind = 'main'
|
|
): Promise<LedgerAccount | null> {
|
|
const rows = await query<LedgerAccount[]>(
|
|
`SELECT id, user_id, wallet_type_id, available_balance::text, locked_balance::text, updated_at
|
|
FROM ledger_accounts WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = $3`,
|
|
[userId, walletTypeId, accountKind]
|
|
);
|
|
return rows[0] || null;
|
|
}
|
|
|
|
/**
|
|
* Adds funds to an account's available balance and records a ledger entry.
|
|
* Runs inside a database transaction with row-level locking.
|
|
* @param accountId - ID of the ledger account to credit.
|
|
* @param amount - Amount to add in the smallest currency unit.
|
|
* @param type - Ledger entry type identifier.
|
|
* @param referenceType - Optional reference entity type (e.g. transaction).
|
|
* @param referenceId - Optional reference entity ID.
|
|
* @returns Resolves when the balance and entry have been committed.
|
|
* @throws Error if the account is not found.
|
|
*/
|
|
export async function credit(
|
|
accountId: string,
|
|
amount: bigint,
|
|
type: string,
|
|
referenceType: string | null,
|
|
referenceId: string | null
|
|
): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
await creditUsingClient(client, accountId, amount, type, referenceType, referenceId);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Credits an account within an existing authorized transaction (caller manages COMMIT).
|
|
*/
|
|
export async function creditUsingClient(
|
|
client: PoolClient,
|
|
accountId: string,
|
|
amount: bigint,
|
|
type: string,
|
|
referenceType: string | null,
|
|
referenceId: string | null
|
|
): Promise<void> {
|
|
const acc = await client.query(
|
|
'SELECT available_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!acc.rows[0]) throw new Error('Account not found');
|
|
const newBalance = BigInt(acc.rows[0].available_balance) + amount;
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2',
|
|
[newBalance.toString(), accountId]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
[accountId, type, amount.toString(), newBalance.toString(), referenceType, referenceId]
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Removes funds from an account's available balance and records a ledger entry.
|
|
* Runs inside a database transaction with row-level locking.
|
|
* @param accountId - ID of the ledger account to debit.
|
|
* @param amount - Amount to subtract in the smallest currency unit.
|
|
* @param type - Ledger entry type identifier.
|
|
* @param referenceType - Optional reference entity type (e.g. transaction).
|
|
* @param referenceId - Optional reference entity ID.
|
|
* @returns Resolves when the balance and entry have been committed.
|
|
* @throws Error if the account is not found or available balance is insufficient.
|
|
*/
|
|
export async function debit(
|
|
accountId: string,
|
|
amount: bigint,
|
|
type: string,
|
|
referenceType: string | null,
|
|
referenceId: string | null
|
|
): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
const acc = await client.query(
|
|
'SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!acc.rows[0]) throw new Error('Account not found');
|
|
const available = BigInt(acc.rows[0].available_balance);
|
|
if (available < amount) throw new Error('Insufficient balance');
|
|
const newBalance = available - amount;
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2',
|
|
[newBalance.toString(), accountId]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
[accountId, type, (-amount).toString(), newBalance.toString(), referenceType, referenceId]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Moves funds from available balance to locked balance (e.g. pending withdrawal).
|
|
* @param accountId - ID of the ledger account.
|
|
* @param amount - Amount to lock in the smallest currency unit.
|
|
* @returns Resolves when the balance transfer has been committed.
|
|
* @throws Error if the account is not found or available balance is insufficient.
|
|
*/
|
|
export async function lockBalance(accountId: string, amount: bigint): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
const acc = await client.query(
|
|
'SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!acc.rows[0]) throw new Error('Account not found');
|
|
const available = BigInt(acc.rows[0].available_balance);
|
|
const locked = BigInt(acc.rows[0].locked_balance);
|
|
if (available < amount) throw new Error('Insufficient balance');
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET available_balance = $1, locked_balance = $2, updated_at = NOW() WHERE id = $3',
|
|
[(available - amount).toString(), (locked + amount).toString(), accountId]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Moves funds from locked balance back to available balance (e.g. cancelled withdrawal).
|
|
* @param accountId - ID of the ledger account.
|
|
* @param amount - Amount to unlock in the smallest currency unit.
|
|
* @returns Resolves when the balance transfer has been committed.
|
|
* @throws Error if the account is not found.
|
|
*/
|
|
export async function unlockBalance(accountId: string, amount: bigint): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
const acc = await client.query(
|
|
'SELECT locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!acc.rows[0]) throw new Error('Account not found');
|
|
const locked = BigInt(acc.rows[0].locked_balance);
|
|
const newLocked = locked - amount;
|
|
const avail = await client.query('SELECT available_balance FROM ledger_accounts WHERE id = $1', [accountId]);
|
|
const newAvail = BigInt(avail.rows[0].available_balance) + amount;
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET available_balance = $1, locked_balance = $2, updated_at = NOW() WHERE id = $3',
|
|
[newAvail.toString(), newLocked.toString(), accountId]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Permanently removes funds from locked balance (e.g. completed withdrawal).
|
|
* @param accountId - ID of the ledger account.
|
|
* @param amount - Amount to deduct from locked balance in the smallest currency unit.
|
|
* @returns Resolves when the deduction has been committed.
|
|
* @throws Error if the account is not found or locked balance is insufficient.
|
|
*/
|
|
export async function deductLocked(accountId: string, amount: bigint): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
const acc = await client.query(
|
|
'SELECT locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!acc.rows[0]) throw new Error('Account not found');
|
|
const locked = BigInt(acc.rows[0].locked_balance);
|
|
if (locked < amount) throw new Error('Locked balance too low');
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET locked_balance = $1, updated_at = NOW() WHERE id = $2',
|
|
[(locked - amount).toString(), accountId]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Debits the sender and credits the receiver in a single atomic transaction.
|
|
* Used for internal transfers between ledger accounts.
|
|
* @param senderAccountId - ID of the account to debit.
|
|
* @param receiverAccountId - ID of the account to credit.
|
|
* @param amount - Transfer amount in the smallest currency unit.
|
|
* @param referenceType - Reference entity type shared by both ledger entries.
|
|
* @param referenceId - Reference entity ID shared by both ledger entries.
|
|
* @param options.minRemaining - Optional floor that must remain on the sender after debit (peer transfers).
|
|
* @returns Resolves when both balance updates and entries have been committed.
|
|
* @throws Error if either account is not found, the sender has insufficient balance, or minRemaining would be breached.
|
|
*/
|
|
export async function transferBetweenAccounts(
|
|
senderAccountId: string,
|
|
receiverAccountId: string,
|
|
amount: bigint,
|
|
referenceType: string,
|
|
referenceId: string,
|
|
options?: { minRemaining?: bigint }
|
|
): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
const sender = await client.query(
|
|
'SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[senderAccountId]
|
|
);
|
|
if (!sender.rows[0]) throw new Error('Sender account not found');
|
|
const available = BigInt(sender.rows[0].available_balance);
|
|
if (available < amount) throw new Error('Insufficient balance');
|
|
const minRemaining = options?.minRemaining ?? 0n;
|
|
if (minRemaining > 0n && available - amount < minRemaining) {
|
|
const err = new Error(
|
|
'Transfer would leave balance below the minimum required remaining balance'
|
|
) as Error & { code?: string };
|
|
err.code = 'TRANSFER_MIN_REMAINING';
|
|
throw err;
|
|
}
|
|
const senderNew = available - amount;
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2',
|
|
[senderNew.toString(), senderAccountId]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
[senderAccountId, referenceType, (-amount).toString(), senderNew.toString(), referenceType, referenceId]
|
|
);
|
|
const receiver = await client.query(
|
|
'SELECT available_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[receiverAccountId]
|
|
);
|
|
if (!receiver.rows[0]) throw new Error('Recipient account not found');
|
|
const receiverNew = BigInt(receiver.rows[0].available_balance) + amount;
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2',
|
|
[receiverNew.toString(), receiverAccountId]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
[receiverAccountId, referenceType, amount.toString(), receiverNew.toString(), referenceType, referenceId]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Finalizes a withdrawal after on-chain broadcast: removes locked funds and records ledger entry.
|
|
* Does not debit available again (funds were moved to locked during initiation).
|
|
*/
|
|
export async function finalizeWithdrawalFromLocked(
|
|
accountId: string,
|
|
amount: bigint,
|
|
transactionId: string
|
|
): Promise<void> {
|
|
const client = await getClient();
|
|
try {
|
|
await beginAuthorizedTransaction(client);
|
|
const acc = await client.query(
|
|
'SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!acc.rows[0]) throw new Error('Account not found');
|
|
const locked = BigInt(acc.rows[0].locked_balance);
|
|
const available = BigInt(acc.rows[0].available_balance);
|
|
if (locked < amount) throw new Error('Locked balance too low');
|
|
const newLocked = locked - amount;
|
|
await client.query(
|
|
'UPDATE ledger_accounts SET locked_balance = $1, updated_at = NOW() WHERE id = $2',
|
|
[newLocked.toString(), accountId]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
|
VALUES ($1, 'withdrawal', $2, $3, 'transaction', $4)`,
|
|
[accountId, (-amount).toString(), available.toString(), transactionId]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export type LedgerIntegrityRow = {
|
|
id: string;
|
|
user_id: string;
|
|
wallet_type_id: number;
|
|
available_balance: string;
|
|
locked_balance: string;
|
|
entries_sum: string;
|
|
};
|
|
|
|
export async function listAllAccountsForIntegrity(): Promise<LedgerIntegrityRow[]> {
|
|
return query<LedgerIntegrityRow[]>(
|
|
`SELECT la.id, la.user_id, la.wallet_type_id,
|
|
la.available_balance::text, la.locked_balance::text,
|
|
COALESCE(SUM(le.amount), 0)::text AS entries_sum
|
|
FROM ledger_accounts la
|
|
LEFT JOIN ledger_entries le ON le.account_id = la.id
|
|
GROUP BY la.id`
|
|
);
|
|
}
|
|
|
|
export async function listUnauthorizedEntryTypes(
|
|
accountId: string,
|
|
allowedTypes: string[]
|
|
): Promise<string[]> {
|
|
const rows = await query<{ type: string }[]>(
|
|
`SELECT DISTINCT type FROM ledger_entries
|
|
WHERE account_id = $1 AND NOT (type = ANY($2::text[]))`,
|
|
[accountId, allowedTypes]
|
|
);
|
|
return rows.map((r) => r.type);
|
|
}
|