aboutsummaryrefslogtreecommitdiffstats
path: root/routes/bitcoin/util/decrementacc.js
blob: a495435e17278e6bd58d2dfb6a3df0db6a3add77 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const btc = config.liquid.btcasset;

module.exports = async (user, total) => await db.transaction(async transaction => {
    let account = await db.Account.findOne({
        where: {
            id: user.account_id
        },
        lock: transaction.LOCK.UPDATE,
        transaction
    });

    if (account.asset !== btc) {
        account = await db.Account.findOne({
            where: {
                user_id: user.id,
                asset: btc,
                pubkey: null
            },
            lock: transaction.LOCK.UPDATE,
            transaction
        });
    }

    if (total > account.balance) {
        l.error("amount exceeds balance", total, account.balance);
        throw new Error("Insufficient funds");
    }

    await account.decrement({ balance: total }, { transaction });
    await account.reload({ transaction });

    return account;
});