aboutsummaryrefslogtreecommitdiffstats
path: root/lib/account.js
blob: 1576546aebf7651e3ccbf43d4133001d46dc358a (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import axios from "axios";
import db from "$db";
import store from "$lib/store";

export default async (asset, user, transaction) => {
  const account = await db.Account.findOne({
    where: {
      user_id: user.id,
      asset,
      pubkey: null
    },
    lock: transaction.LOCK.UPDATE,
    transaction
  });

  if (account) return account;

  let params = {
    user_id: user.id,
    asset
  };
  let name = asset.substr(0, 6);
  let domain = "";
  let ticker = asset.substr(0, 3).toUpperCase();
  let precision = 8;

  if (store.assets[asset]) {
    ({ domain, ticker, precision, name } = store.assets[asset]);
  } else {
    const existing = await db.Account.findOne({
      where: {
        asset
      },
      order: [["id", "ASC"]],
      limit: 1,
      lock: transaction.LOCK.UPDATE,
      transaction
    });

    if (existing) {
      ({ domain, ticker, precision, name } = existing);
    }
  }

  params = { ...params, ...{ domain, ticker, precision, name } };
  params.balance = 0;
  params.pending = 0;
  return db.Account.create(params, { transaction });
};