File size: 920 Bytes
9705b6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
35
36
37
38
39
const mongoose = require('mongoose');
const balanceSchema = require('./schema/balance');
const { getMultiplier } = require('./tx');

balanceSchema.statics.check = async function ({ user, model, valueKey, tokenType, amount, debug }) {
  const multiplier = getMultiplier({ valueKey, tokenType, model });
  const tokenCost = amount * multiplier;
  const { tokenCredits: balance } = (await this.findOne({ user }, 'tokenCredits').lean()) ?? {};

  if (debug) {
    console.log('balance check', {
      user,
      model,
      valueKey,
      tokenType,
      amount,
      debug,
      balance,
      multiplier,
    });
  }

  if (!balance) {
    return {
      canSpend: false,
      balance: 0,
      tokenCost,
    };
  }

  if (debug) {
    console.log('balance check', { tokenCost });
  }

  return { canSpend: balance >= tokenCost, balance, tokenCost };
};

module.exports = mongoose.model('Balance', balanceSchema);