diff options
| author | Adam Soltys <[email protected]> | 2022-09-06 09:20:25 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2022-09-06 09:20:25 -0700 |
| commit | c2464b2407ee23134732fd67586758dbfe18f9b5 (patch) | |
| tree | 3e2d9f009bb325a9a7c4304ea02f6e64dda85bd1 /routes | |
| parent | 8a080ef9a198799e7ee31cf81f92afd5495e4074 (diff) | |
| download | coinos-server-c2464b2407ee23134732fd67586758dbfe18f9b5.tar.gz coinos-server-c2464b2407ee23134732fd67586758dbfe18f9b5.zip | |
prettier
Diffstat (limited to 'routes')
| -rw-r--r-- | routes/admin.js | 550 | ||||
| -rw-r--r-- | routes/assets.js | 699 | ||||
| -rw-r--r-- | routes/funding.js | 168 | ||||
| -rw-r--r-- | routes/info.js | 24 | ||||
| -rw-r--r-- | routes/lnurl.js | 4 | ||||
| -rw-r--r-- | routes/payments.js | 2 | ||||
| -rw-r--r-- | routes/referrals.js | 270 | ||||
| -rw-r--r-- | routes/swaps.js | 417 | ||||
| -rw-r--r-- | routes/users.js | 5 |
9 files changed, 1048 insertions, 1091 deletions
diff --git a/routes/admin.js b/routes/admin.js index 918f9423..3053d813 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -1,8 +1,8 @@ -import express from 'express'; +import express from "express"; var router = express.Router(); -import * as parseInput from '../scripts/apiParse'; -import Sequelize from '@sequelize/core'; +import * as parseInput from "../scripts/apiParse"; +import Sequelize from "@sequelize/core"; const Op = Sequelize.Op; /** @@ -11,8 +11,8 @@ const Op = Sequelize.Op; * @apiGroup Admin * * @apiPermission admin - * - * @apiSuccess {Object} users List of users + * + * @apiSuccess {Object} users List of users * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { @@ -26,25 +26,32 @@ router.get( "/users", // auth, async (req, res) => { - var {search, starts_with, contains} = req.query + var { search, starts_with, contains } = req.query; var users = knex - .select('username', 'email', 'phone', 'verified', knex.raw('LEFT(createdAt,10) as created_at')) - .from('users') - - var timeCondition = parseInput.addTimeSearch(req.query, 'users.createdAt') - var userCondition = parseInput.addUserSearch(req.query) + .select( + "username", + "email", + "phone", + "verified", + knex.raw("LEFT(createdAt,10) as created_at") + ) + .from("users"); + + var timeCondition = parseInput.addTimeSearch(req.query, "users.createdAt"); + var userCondition = parseInput.addUserSearch(req.query); + + if (timeCondition) users = users.whereRaw(timeCondition); + if (userCondition) users = users.whereRaw(userCondition); - if (timeCondition) users = users.whereRaw(timeCondition) - if (userCondition) users = users.whereRaw(userCondition) - // Alternative Sequelize query syntax // await db.User.findAll({ // attributes: ['username', 'email', 'phone', 'verified', 'createdAt'] // }) - const found = await users - return res.send({users: found}) - }) + const found = await users; + return res.send({ users: found }); + } +); /** * @api {get} /referrals Retrieve list of referral tokens @@ -52,7 +59,7 @@ router.get( * @apiGroup Admin * * @apiPermission admin - * + * * @apiSuccess returns list of referral tokens * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK @@ -63,43 +70,43 @@ router.get( * ] * } */ -router.get( - "/referrals", - auth, - async (req, res) => { - var referrals = knex - .select( - 'token', - 'users.username as user', - 'sponsor.username as sponsor', - knex.raw('LEFT(created_at, 10) as created_at'), - 'referrals.status' - ) - .from('referrals') - .leftJoin('users', 'users.id', 'referrals.user_id') - .leftJoin('users as sponsor', 'sponsor.id', 'referrals.sponsor_id') +router.get("/referrals", auth, async (req, res) => { + var referrals = knex + .select( + "token", + "users.username as user", + "sponsor.username as sponsor", + knex.raw("LEFT(created_at, 10) as created_at"), + "referrals.status" + ) + .from("referrals") + .leftJoin("users", "users.id", "referrals.user_id") + .leftJoin("users as sponsor", "sponsor.id", "referrals.sponsor_id"); - // Alternative Sequelize query syntax (returns sub-tables as hash) - // var referrals = await db.Referral.findAll({ - // include: [ - // {model: db.User, as: 'user', attributes: [['username', 'user']]}, - // {model: db.User, as: 'sponsor', attributes: [['username', 'sponsor']]} - // ] - // }) + // Alternative Sequelize query syntax (returns sub-tables as hash) + // var referrals = await db.Referral.findAll({ + // include: [ + // {model: db.User, as: 'user', attributes: [['username', 'user']]}, + // {model: db.User, as: 'sponsor', attributes: [['username', 'sponsor']]} + // ] + // }) - var timeCondition = parseInput.addTimeSearch(req.query, 'referrals.updated_at') - var userCondition = parseInput.addUserSearch(req.query, 'sponsor') + var timeCondition = parseInput.addTimeSearch( + req.query, + "referrals.updated_at" + ); + var userCondition = parseInput.addUserSearch(req.query, "sponsor"); - if (userCondition) { - referrals = referrals.whereRaw(userCondition) - } - if (timeCondition) { - referrals = referrals.whereRaw(timeCondition) - } + if (userCondition) { + referrals = referrals.whereRaw(userCondition); + } + if (timeCondition) { + referrals = referrals.whereRaw(timeCondition); + } - var found = await referrals - return res.send({referrals: found}) - }) + var found = await referrals; + return res.send({ referrals: found }); +}); /** * @api {get} /waiting_list Retrieve waiting_list @@ -107,7 +114,7 @@ router.get( * @apiGroup Admin * * @apiPermission admin - * + * * @apiSuccess returns list of referral tokens * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK @@ -119,32 +126,36 @@ router.get( * } */ router.get( - "/waiting_list", - // auth, - async (req, res) => { - var {search, starts_with, contains} = req.query + "/waiting_list", + // auth, + async (req, res) => { + var { search, starts_with, contains } = req.query; - var queue = knex - .select( - 'waiting_list.email', - 'waiting_list.phone', - 'waiting_list.created_at as requested', - 'users.id as current_user_id' - ) - .from('waiting_list') - .leftJoin('users', 'users.email', 'waiting_list.email') - .where('waiting_list.id', '>', 0) + var queue = knex + .select( + "waiting_list.email", + "waiting_list.phone", + "waiting_list.created_at as requested", + "users.id as current_user_id" + ) + .from("waiting_list") + .leftJoin("users", "users.email", "waiting_list.email") + .where("waiting_list.id", ">", 0); - var timeCondition = parseInput.addTimeSearch(req.query, 'waiting_list.updated_at') - var userCondition = parseInput.addUserSearch(req.query) + var timeCondition = parseInput.addTimeSearch( + req.query, + "waiting_list.updated_at" + ); + var userCondition = parseInput.addUserSearch(req.query); - if (timeCondition) queue = queue.whereRaw(timeCondition) - if (userCondition) queue = queue.whereRaw(userCondition) + if (timeCondition) queue = queue.whereRaw(timeCondition); + if (userCondition) queue = queue.whereRaw(userCondition); - const found = await queue + const found = await queue; - return res.send({queue: found}) - }) + return res.send({ queue: found }); + } +); /** * @api {get} /accounts Retrieve list of accounts @@ -152,7 +163,7 @@ router.get( * @apiGroup Admin * * @apiPermission admin - * + * * @apiSuccess returns list of accounts * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK @@ -163,32 +174,35 @@ router.get( * ] * } */ -router.get( - "/accounts", - auth, - async (req, res) => { - var {nonZero, search, starts_with, contains} = req.query +router.get("/accounts", auth, async (req, res) => { + var { nonZero, search, starts_with, contains } = req.query; - var accounts = knex - .select('username', 'accounts.id as account_id', 'ticker', 'balance', knex.raw('LEFT(accounts.createdAt, 10) as created'), knex.raw('LEFT(accounts.updatedAt, 10) as updated')) - .from('accounts') - .leftJoin('users', 'users.id', 'accounts.user_id') + var accounts = knex + .select( + "username", + "accounts.id as account_id", + "ticker", + "balance", + knex.raw("LEFT(accounts.createdAt, 10) as created"), + knex.raw("LEFT(accounts.updatedAt, 10) as updated") + ) + .from("accounts") + .leftJoin("users", "users.id", "accounts.user_id"); - if (nonZero) { - accounts = accounts - .where('balance', '>', 0) - } + if (nonZero) { + accounts = accounts.where("balance", ">", 0); + } - var timeCondition = parseInput.addTimeSearch(req.query, 'accounts.updatedAt') - var userCondition = parseInput.addUserSearch(req.query) + var timeCondition = parseInput.addTimeSearch(req.query, "accounts.updatedAt"); + var userCondition = parseInput.addUserSearch(req.query); - if (timeCondition) accounts = accounts.whereRaw(timeCondition) - if (userCondition) accounts = accounts.whereRaw(userCondition) + if (timeCondition) accounts = accounts.whereRaw(timeCondition); + if (userCondition) accounts = accounts.whereRaw(userCondition); - const found = await accounts + const found = await accounts; - return res.send({accounts: found}) - }) + return res.send({ accounts: found }); +}); /** * @api {get} /transactions Retrieve summary of user transactions @@ -212,50 +226,56 @@ router.get( "/transactions", // auth, async (req, res) => { - var {type, since, search, starts_with, contains} = req.query + var { type, since, search, starts_with, contains } = req.query; var transactions = knex .select( - 'users.username', - 'users.email', + "users.username", + "users.email" // knex.raw('LEFT(created_at, 10) as created') // knex.raw('LEFT(updatedAt, 10) as updated') // knex.raw('COUNT(invoices.id) as invoices'), // knex.raw('COUNT(payments.id) as payments'), // knex.raw('COUNT(orders.id) as orders') ) - .from('users') + .from("users"); - const types = ['deposits', 'withdrawals', 'orders', 'payments', 'invoices'] - for (var i=0; i<types.length; i++) { - var stamp = types[i].replace(/s$/,'') + '_date' + const types = ["deposits", "withdrawals", "orders", "payments", "invoices"]; + for (var i = 0; i < types.length; i++) { + var stamp = types[i].replace(/s$/, "") + "_date"; - transactions = transactions + transactions = transactions .select( - knex.raw('COUNT(DISTINCT ' + types[i] + '.id) as ' + types[i]), - knex.raw('LEFT(MAX(' + types[i] + '.updatedAt), 10) as ' + stamp) + knex.raw("COUNT(DISTINCT " + types[i] + ".id) as " + types[i]), + knex.raw("LEFT(MAX(" + types[i] + ".updatedAt), 10) as " + stamp) ) - .leftJoin(types[i], 'users.id', types[i] + '.user_id') - // .havingRaw(types[i] + ' > ?', [0]) - - if (since) { - transactions = transactions - .havingRaw('(' + stamp + ' >= ? OR ' + stamp + ' IS NULL)', [since]) - } + .leftJoin(types[i], "users.id", types[i] + ".user_id"); + // .havingRaw(types[i] + ' > ?', [0]) + + if (since) { + transactions = transactions.havingRaw( + "(" + stamp + " >= ? OR " + stamp + " IS NULL)", + [since] + ); } + } - if (since) transactions = transactions.havingRaw('invoices + payments + deposits + orders > ?', [0]) + if (since) + transactions = transactions.havingRaw( + "invoices + payments + deposits + orders > ?", + [0] + ); - var userCondition = parseInput.addUserSearch(req.query) - if (userCondition) transactions = transactions.whereRaw(userCondition) + var userCondition = parseInput.addUserSearch(req.query); + if (userCondition) transactions = transactions.whereRaw(userCondition); - transactions = transactions - .groupBy('users.id') + transactions = transactions.groupBy("users.id"); - const found = await transactions + const found = await transactions; - return res.send({transactions: found}) - }) + return res.send({ transactions: found }); + } +); /** * @api {get} /orders Retrieve summary of orders @@ -275,43 +295,41 @@ router.get( * ] * } */ -router.get( - "/orders", - auth, - async (req, res) => { - var {type, since, search, starts_with, contains} = req.query +router.get("/orders", auth, async (req, res) => { + var { type, since, search, starts_with, contains } = req.query; - var orders = knex - .select( - 'u1.username as seller', - 'u2.username as buyer', - 'v1 as sell_amount', - 'v2 as buy_amount', - 'rate', - 'a1.name as from', - 'a2.name as to', - knex.raw('Left(completedAt,16) as completed') - ) - .from('orders') - .leftJoin('accounts as a1', 'a1.id', 'orders.a1_id') - .leftJoin('accounts as a2', 'a2.id', 'orders.a2_id') - .leftJoin('users as u1', 'a1.user_id', 'u1.id') - .leftJoin('users as u2', 'a2.user_id', 'u2.id') + var orders = knex + .select( + "u1.username as seller", + "u2.username as buyer", + "v1 as sell_amount", + "v2 as buy_amount", + "rate", + "a1.name as from", + "a2.name as to", + knex.raw("Left(completedAt,16) as completed") + ) + .from("orders") + .leftJoin("accounts as a1", "a1.id", "orders.a1_id") + .leftJoin("accounts as a2", "a2.id", "orders.a2_id") + .leftJoin("users as u1", "a1.user_id", "u1.id") + .leftJoin("users as u2", "a2.user_id", "u2.id"); - var timeCondition = parseInput.addTimeSearch(req.query, 'orders.updatedAt') - if (timeCondition) orders = orders.whereRaw(timeCondition) + var timeCondition = parseInput.addTimeSearch(req.query, "orders.updatedAt"); + if (timeCondition) orders = orders.whereRaw(timeCondition); - var userCondition1 = parseInput.addUserSearch(req.query, 'u1') - var userCondition2 = parseInput.addUserSearch(req.query, 'u2') + var userCondition1 = parseInput.addUserSearch(req.query, "u1"); + var userCondition2 = parseInput.addUserSearch(req.query, "u2"); - if (userCondition1) orders = orders.where( function () { - this.whereRaw(userCondition1) - this.orWhere(knex.raw(userCondition2)) - }) + if (userCondition1) + orders = orders.where(function() { + this.whereRaw(userCondition1); + this.orWhere(knex.raw(userCondition2)); + }); - var found = await orders - return res.send({orders: found}) - }) + var found = await orders; + return res.send({ orders: found }); +}); /** * @api {get} /invoices Retrieve summary of invoices @@ -331,35 +349,31 @@ router.get( * ] * } */ -router.get( - "/invoices", - auth, - async (req, res) => { - var {type, since, search, starts_with, contains} = req.query +router.get("/invoices", auth, async (req, res) => { + var { type, since, search, starts_with, contains } = req.query; - var invoices = knex - .select( - 'username', - 'users.email', - 'invoices.currency', - 'invoices.amount', - 'accounts.network', - knex.raw('Left(invoices.updatedAt,16) as updated') - ) - .from('invoices') - .leftJoin('accounts', 'invoices.account_id', 'accounts.id') - .leftJoin('users', 'accounts.user_id', 'users.id') + var invoices = knex + .select( + "username", + "users.email", + "invoices.currency", + "invoices.amount", + "accounts.network", + knex.raw("Left(invoices.updatedAt,16) as updated") + ) + .from("invoices") + .leftJoin("accounts", "invoices.account_id", "accounts.id") + .leftJoin("users", "accounts.user_id", "users.id"); - var timeCondition = parseInput.addTimeSearch(req.query, 'invoices.updatedAt') - var userCondition = parseInput.addUserSearch(req.query) - - if (timeCondition) invoices = invoices.whereRaw(timeCondition) - if (userCondition) invoices = invoices.whereRaw(userCondition) + var timeCondition = parseInput.addTimeSearch(req.query, "invoices.updatedAt"); + var userCondition = parseInput.addUserSearch(req.query); - var found = await invoices - return res.send({invoices: found}) - }) + if (timeCondition) invoices = invoices.whereRaw(timeCondition); + if (userCondition) invoices = invoices.whereRaw(userCondition); + var found = await invoices; + return res.send({ invoices: found }); +}); /** * @api {get} /deposits Retrieve summary of deposits @@ -379,32 +393,29 @@ router.get( * ] * } */ -router.get( - "/deposits", - auth, - async (req, res) => { - var {type, since, search, starts_with, contains} = req.query +router.get("/deposits", auth, async (req, res) => { + var { type, since, search, starts_with, contains } = req.query; - var deposits = knex - .select( - 'username', - 'users.email', - 'amount', - 'credited', - knex.raw('Left(deposits.updatedAt,16) as deposited') - ) - .from('deposits') - .leftJoin('users', 'deposits.user_id', 'users.id') + var deposits = knex + .select( + "username", + "users.email", + "amount", + "credited", + knex.raw("Left(deposits.updatedAt,16) as deposited") + ) + .from("deposits") + .leftJoin("users", "deposits.user_id", "users.id"); - var timeCondition = parseInput.addTimeSearch(req.query, 'deposits.updatedAt') - var userCondition = parseInput.addUserSearch(req.query) + var timeCondition = parseInput.addTimeSearch(req.query, "deposits.updatedAt"); + var userCondition = parseInput.addUserSearch(req.query); - if (timeCondition) deposits = deposits.whereRaw(timeCondition) - if (userCondition) deposits = deposits.whereRaw(userCondition) + if (timeCondition) deposits = deposits.whereRaw(timeCondition); + if (userCondition) deposits = deposits.whereRaw(userCondition); - var found = await deposits - return res.send({deposits: found}) - }) + var found = await deposits; + return res.send({ deposits: found }); +}); /** * @api {get} /withdrawals Retrieve summary of withdrawals @@ -424,32 +435,32 @@ router.get( * ] * } */ -router.get( - "/withdrawals", - auth, - async (req, res) => { - var {type, since, search, starts_with, contains} = req.query +router.get("/withdrawals", auth, async (req, res) => { + var { type, since, search, starts_with, contains } = req.query; - var withdrawals = knex - .select( - 'username', - 'users.email', - 'amount', - 'notes', - knex.raw('Left(withdrawals.updatedAt,16) as withdrawn') - ) - .from('withdrawals') - .leftJoin('users', 'withdrawals.user_id', 'users.id') + var withdrawals = knex + .select( + "username", + "users.email", + "amount", + "notes", + knex.raw("Left(withdrawals.updatedAt,16) as withdrawn") + ) + .from("withdrawals") + .leftJoin("users", "withdrawals.user_id", "users.id"); + + var timeCondition = parseInput.addTimeSearch( + req.query, + "withdrawals.updatedAt" + ); + var userCondition = parseInput.addUserSearch(req.query); - var timeCondition = parseInput.addTimeSearch(req.query, 'withdrawals.updatedAt') - var userCondition = parseInput.addUserSearch(req.query) - - if (timeCondition) withdrawals = withdrawals.whereRaw(timeCondition) - if (userCondition) withdrawals = withdrawals.whereRaw(userCondition) + if (timeCondition) withdrawals = withdrawals.whereRaw(timeCondition); + if (userCondition) withdrawals = withdrawals.whereRaw(userCondition); - var found = await withdrawals - return res.send({withdrawals: found}) - }) + var found = await withdrawals; + return res.send({ withdrawals: found }); +}); /** * @api {get} /payments Retrieve summary of payments @@ -469,34 +480,31 @@ router.get( * ] * } **/ -router.get( - "/payments", - auth, - async (req, res) => { - var {type, since, search, starts_with, contains} = req.query +router.get("/payments", auth, async (req, res) => { + var { type, since, search, starts_with, contains } = req.query; - var payments = knex - .select( - 'username', - 'users.email', - 'amount', - 'payments.network', - knex.raw('LEFT(hash,20) as hash'), - knex.raw('Left(payments.updatedAt,16) as deposited') - ) - .from('payments') - .leftJoin('accounts', 'payments.account_id', 'accounts.id') - .leftJoin('users', 'accounts.user_id', 'users.id') + var payments = knex + .select( + "username", + "users.email", + "amount", + "payments.network", + knex.raw("LEFT(hash,20) as hash"), + knex.raw("Left(payments.updatedAt,16) as deposited") + ) + .from("payments") + .leftJoin("accounts", "payments.account_id", "accounts.id") + .leftJoin("users", "accounts.user_id", "users.id"); - var timeCondition = parseInput.addTimeSearch(req.query, 'payments.updatedAt') - var userCondition = parseInput.addUserSearch(req.query) + var timeCondition = parseInput.addTimeSearch(req.query, "payments.updatedAt"); + var userCondition = parseInput.addUserSearch(req.query); - if (timeCondition) payments = payments.whereRaw(timeCondition) - if (userCondition) payments = payments.whereRaw(userCondition) + if (timeCondition) payments = payments.whereRaw(timeCondition); + if (userCondition) payments = payments.whereRaw(userCondition); - var found = await payments - return res.send({payments: found}) - }) + var found = await payments; + return res.send({ payments: found }); +}); /** * @api {get} /user_kyc Retrieve user kyc details @@ -516,43 +524,43 @@ router.get( * ] * } */ -router.get( - "/kyc_required", - auth, - async (req, res) => { - var {since, search, starts_with, contains} = req.query - - var threshold = '0.2' - - var kyc = knex +router.get("/kyc_required", auth, async (req, res) => { + var { since, search, starts_with, contains } = req.query; + + var threshold = "0.2"; + + var kyc = knex .select( knex.raw("CONCAT( FORMAT(Max(amount)/1000000, 1), ' M') as max"), - 'username', - 'users.email', - 'users.verified as kyc_verified', + "username", + "users.email", + "users.verified as kyc_verified", // 'payments.currency', // 'payments.network', // knex.raw('LEFT(hash,20) as hash'), // knex.raw('Left(payments.updatedAt,16) as transferred') // knex.raw( parseInput.readableDate('Max(payments.updatedAt)', 'last_changed') ) - knex.raw( 'DATE_FORMAT(Max(payments.updatedAt), ?) AS last_changed', "%M %d, %Y" ) + knex.raw( + "DATE_FORMAT(Max(payments.updatedAt), ?) AS last_changed", + "%M %d, %Y" ) - .from('payments') - .leftJoin('accounts', 'payments.account_id', 'accounts.id') - .leftJoin('users', 'payments.user_id', 'users.id') // should really point to accounts - .groupBy('users.id') - // .groupBy('payments.currency') - // .groupBy('payments.network') + ) + .from("payments") + .leftJoin("accounts", "payments.account_id", "accounts.id") + .leftJoin("users", "payments.user_id", "users.id") // should really point to accounts + .groupBy("users.id"); + // .groupBy('payments.currency') + // .groupBy('payments.network') - var timeCondition = parseInput.addTimeSearch(req.query, 'payments.updatedAt') - var userCondition = parseInput.addUserSearch(req.query) + var timeCondition = parseInput.addTimeSearch(req.query, "payments.updatedAt"); + var userCondition = parseInput.addUserSearch(req.query); - if (timeCondition) kyc = kyc.whereRaw(timeCondition) - if (userCondition) kyc = kyc.whereRaw(userCondition) + if (timeCondition) kyc = kyc.whereRaw(timeCondition); + if (userCondition) kyc = kyc.whereRaw(userCondition); - var found = await kyc.having('max', '>=', threshold) + var found = await kyc.having("max", ">=", threshold); - return res.send({found: found}) - }) + return res.send({ found: found }); +}); export default router; diff --git a/routes/assets.js b/routes/assets.js index 541c9625..826ff2d9 100644 --- a/routes/assets.js +++ b/routes/assets.js @@ -4,16 +4,14 @@ import db from "$db"; import config from "$config"; import app from "$app"; import { auth } from "$lib/passport"; -import axios from 'axios'; -import crypto from 'crypto'; -import fs from 'fs'; +import axios from "axios"; +import crypto from "crypto"; +import fs from "fs"; let fetchAssets; (fetchAssets = async () => { try { - const { data } = await axios.get( - "https://assets.blockstream.info/" - ); + const { data } = await axios.get("https://assets.blockstream.info/"); store.assets = data; } catch (e) { @@ -30,432 +28,415 @@ let fetchAssets; setTimeout(fetchAssets, 7200000); })(); -app.get( - "/assets", - async (req, res) => { - if (store.assets) { - const accounts = await db.Account.findAll({ - // group: ["asset"] - }); - Object.keys(store.assets).map(a => { - store.assets[a].registered = true; - if (!store.assets[a].asset) store.assets[a].asset = store.assets[a].asset_id; - if ( - (store.assets[a].ticker === "BTC" && - store.assets[a].asset !== config.liquid.btcasset) || - (store.assets[a].ticker === "EUR" && - store.assets[a].asset !== config.liquid.eurasset) || - (store.assets[a].ticker === "CAD" && - store.assets[a].asset !== config.liquid.cadasset) || - (store.assets[a].ticker === "USDt" && - store.assets[a].asset !== config.liquid.usdtasset) - ) - delete store.assets[a]; - }); - accounts.map(({ asset, name, domain, ticker, precision }) => { - if (!store.assets[asset]) - store.assets[asset] = { - asset, - name, - domain, - ticker, - precision - }; - }); +app.get("/assets", async (req, res) => { + if (store.assets) { + const accounts = await db.Account.findAll({ + // group: ["asset"] + }); + Object.keys(store.assets).map(a => { + store.assets[a].registered = true; + if (!store.assets[a].asset) + store.assets[a].asset = store.assets[a].asset_id; + if ( + (store.assets[a].ticker === "BTC" && + store.assets[a].asset !== config.liquid.btcasset) || + (store.assets[a].ticker === "EUR" && + store.assets[a].asset !== config.liquid.eurasset) || + (store.assets[a].ticker === "CAD" && + store.assets[a].asset !== config.liquid.cadasset) || + (store.assets[a].ticker === "USDt" && + store.assets[a].asset !== config.liquid.usdtasset) + ) + delete store.assets[a]; + }); + accounts.map(({ asset, name, domain, ticker, precision }) => { + if (!store.assets[asset]) + store.assets[asset] = { + asset, + name, + domain, + ticker, + precision + }; + }); - res.send(store.assets); - } else { - console.log("error getting blockstream assets"); - res.code(500).send("Problem fetching blockstream asset registry data"); - } - }) + res.send(store.assets); + } else { + console.log("error getting blockstream assets"); + res.code(500).send("Problem fetching blockstream asset registry data"); + } +}); -app.post( - "/assets", - auth, - async (req, res) => { - try { - const sha256 = crypto.createHash("sha256"); - const { id: user_id } = req.user; - const blind = false; +app.post("/assets", auth, async (req, res) => { + try { + const sha256 = crypto.createHash("sha256"); + const { id: user_id } = req.user; + const blind = false; - if (!user_id) throw new Error("unauthorized"); + if (!user_id) throw new Error("unauthorized"); - const { - address, - domain, - name, - asset_amount, - filename, - token_amount, - precision, - pubkey, - ticker - } = req.body; + const { + address, + domain, + name, + asset_amount, + filename, + token_amount, + precision, + pubkey, + ticker + } = req.body; - const asset_address = address - ? address - : await lq.getNewAddress("", "legacy"); + const asset_address = address + ? address + : await lq.getNewAddress("", "legacy"); - const token_address = - token_amount && (await lq.getNewAddress("", "legacy")); + const token_address = + token_amount && (await lq.getNewAddress("", "legacy")); - const issuer_pubkey = pubkey - ? pubkey - : (await lq.getAddressInfo(asset_address)).pubkey; - const version = 0; + const issuer_pubkey = pubkey + ? pubkey + : (await lq.getAddressInfo(asset_address)).pubkey; + const version = 0; - let contract = { - entity: { domain }, - issuer_pubkey, - name, - precision, - version - }; + let contract = { + entity: { domain }, + issuer_pubkey, + name, + precision, + version + }; - if (filename) contract.file = filename; - if (ticker) contract.ticker = ticker; + if (filename) contract.file = filename; + if (ticker) contract.ticker = ticker; - contract = Object.keys(contract) - .sort() - .reduce((r, k) => ((r[k] = contract[k]), r), {}); + contract = Object.keys(contract) + .sort() + .reduce((r, k) => ((r[k] = contract[k]), r), {}); - l( - "attempting issuance", - req.user.username, - contract, - "address", - address, - "pubkey", - pubkey - ); + l( + "attempting issuance", + req.user.username, + contract, + "address", + address, + "pubkey", + pubkey + ); - sha256.update(JSON.stringify(contract)); - const hash = sha256.digest("hex"); - const contract_hash = hash - .match(/[a-f0-9]{2}/g) - .reverse() - .join(""); - const rawtx = await lq.createRawTransaction([], [{ data: "00" }]); - const funded = await lq.fundRawTransaction(rawtx, { feeRate: 0.000002 }); - const params = { - asset_amount, - asset_address, - blind, - contract_hash - }; + sha256.update(JSON.stringify(contract)); + const hash = sha256.digest("hex"); + const contract_hash = hash + .match(/[a-f0-9]{2}/g) + .reverse() + .join(""); + const rawtx = await lq.createRawTransaction([], [{ data: "00" }]); + const funded = await lq.fundRawTransaction(rawtx, { feeRate: 0.000002 }); + const params = { + asset_amount, + asset_address, + blind, + contract_hash + }; - params.asset_amount = asset_amount / (SATS / 10 ** precision); + params.asset_amount = asset_amount / (SATS / 10 ** precision); - if (token_amount) { - params.token_amount = token_amount; - params.token_address = token_address; - params.token_amount = parseInt(params.token_amount); - } + if (token_amount) { + params.token_amount = token_amount; + params.token_address = token_address; + params.token_amount = parseInt(params.token_amount); + } - let ria; - try { - ria = await lq.rawIssueAsset(funded.hex, [params]); - } catch (e) { - l(asset_amount, token_amount, params); - throw new Error(e.message); - } + let ria; + try { + ria = await lq.rawIssueAsset(funded.hex, [params]); + } catch (e) { + l(asset_amount, token_amount, params); + throw new Error(e.message); + } - const { asset, hex, token } = ria[0]; - const brt = await lq.blindRawTransaction(hex, true, [], false); - const srt = await lq.signRawTransactionWithWallet(brt); - const allowed = (await lq.testMempoolAccept([srt.hex]))[0].allowed; - if (!allowed) throw new Error("issuance rejected by mempool", srt.hex); - const txid = await lq.sendRawTransaction(srt.hex); + const { asset, hex, token } = ria[0]; + const brt = await lq.blindRawTransaction(hex, true, [], false); + const srt = await lq.signRawTransactionWithWallet(brt); + const allowed = (await lq.testMempoolAccept([srt.hex]))[0].allowed; + if (!allowed) throw new Error("issuance rejected by mempool", srt.hex); + const txid = await lq.sendRawTransaction(srt.hex); - await db.transaction(async transaction => { - let account = await db.Account.findOne({ - where: { - user_id, - asset: config.liquid.btcasset, - pubkey: null - }, - include: { - model: db.User, - as: "user" - }, - order: [["balance", "DESC"]], - transaction - }); + await db.transaction(async transaction => { + let account = await db.Account.findOne({ + where: { + user_id, + asset: config.liquid.btcasset, + pubkey: null + }, + include: { + model: db.User, + as: "user" + }, + order: [["balance", "DESC"]], + transaction + }); - let { user } = account; + let { user } = account; - if (Math.round(funded.fee * SATS) > account.balance) { - err( - "amount exceeds balance", - asset_amount, - funded.fee, - account.balance - ); - throw new Error(`Insufficient funds to pay fee of ${funded.fee} BTC`); - } + if (Math.round(funded.fee * SATS) > account.balance) { + err( + "amount exceeds balance", + asset_amount, + funded.fee, + account.balance + ); + throw new Error(`Insufficient funds to pay fee of ${funded.fee} BTC`); + } + + await account.decrement( + { balance: Math.round(funded.fee * SATS) }, + { transaction } + ); + await account.reload({ transaction }); + emit(user.username, "account", account); + + account = await db.Account.create( + { + asset, + contract, + domain, + user_id, + ticker, + precision, + name, + balance: 0, + network: "liquid", + pending: address ? 0 : Math.round(params.asset_amount * SATS) + }, + { transaction } + ); - await account.decrement( - { balance: Math.round(funded.fee * SATS) }, + emit(user.username, "account", account); + l( + "issued asset", + user.username, + params.asset_amount, + ticker, + name, + account.id + ); + + if (!address) { + const asset_payment = await db.Payment.create( + { + account_id: account.id, + user_id, + hash: txid, + amount: Math.round(params.asset_amount * SATS), + received: true, + confirmed: false, + address: asset_address, + network: "liquid" + }, { transaction } ); - await account.reload({ transaction }); - emit(user.username, "account", account); + emit(user.username, "payment", asset_payment); + + issuances[txid] = { + user_id, + asset, + asset_amount: params.asset_amount, + asset_payment_id: asset_payment.id + }; + } + if (token_amount) { account = await db.Account.create( { - asset, - contract, - domain, + asset: token, user_id, - ticker, - precision, - name, + domain, + ticker: `${ticker}REISSUANCETOKEN`, + precision: 8, + name: `${name} Reissuance Token`, balance: 0, - network: "liquid", - pending: address ? 0 : Math.round(params.asset_amount * SATS) + pending: address ? 0 : Math.round(token_amount * SATS) }, { transaction } ); - emit(user.username, "account", account); - l( - "issued asset", - user.username, - params.asset_amount, - ticker, - name, - account.id - ); if (!address) { - const asset_payment = await db.Payment.create( + const token_payment = await db.Payment.create( { account_id: account.id, user_id, hash: txid, - amount: Math.round(params.asset_amount * SATS), + amount: Math.round(token_amount * SATS), received: true, confirmed: false, - address: asset_address, + address: token_address, network: "liquid" }, { transaction } ); - emit(user.username, "payment", asset_payment); + emit(user.username, "payment", token_payment); - issuances[txid] = { - user_id, - asset, - asset_amount: params.asset_amount, - asset_payment_id: asset_payment.id - }; + issuances[txid].token = token; + issuances[txid].token_amount = token_amount; + issuances[txid].token_payment_id = token_payment.id; } + } + }); - if (token_amount) { - account = await db.Account.create( - { - asset: token, - user_id, - domain, - ticker: `${ticker}REISSUANCETOKEN`, - precision: 8, - name: `${name} Reissuance Token`, - balance: 0, - pending: address ? 0 : Math.round(token_amount * SATS) - }, - { transaction } - ); - emit(user.username, "account", account); - - if (!address) { - const token_payment = await db.Payment.create( - { - account_id: account.id, - user_id, - hash: txid, - amount: Math.round(token_amount * SATS), - received: true, - confirmed: false, - address: token_address, - network: "liquid" - }, - { transaction } - ); - emit(user.username, "payment", token_payment); - - issuances[txid].token = token; - issuances[txid].token_amount = token_amount; - issuances[txid].token_payment_id = token_payment.id; - } - } - }); + res.send(issuances[txid] ? issuances[txid] : { asset }); + } catch (e) { + err("asset issuance failed", e.message, e.stack); + res.code(500).send(e.message); + } +}); - res.send(issuances[txid] ? issuances[txid] : { asset }); - } catch (e) { - err("asset issuance failed", e.message, e.stack); - res.code(500).send(e.message); +app.post("/assets/register", auth, async (req, res) => { + const { asset } = req.body; + const account = await db.Account.findOne({ + where: { + user_id: req.user.id, + asset } - }) + }); -app.post( - "/assets/register", - auth, - async (req, res) => { - const { asset } = req.body; - const account = await db.Account.findOne({ - where: { - user_id: req.user.id, - asset + l("registering", asset, account.contract); + + try { + const { data: result } = await axios.post( + "https://assets.blockstream.info/", + { + asset_id: asset, + contract: account.contract } - }); + ); + l("register asset result", req.user.username, result); + res.send(result); + } catch (e) { + err("asset registration failed", e.message); + res.code(500).send(e.message); + } +}); - l("registering", asset, account.contract); +app.post("/loadFaucet", auth, async (req, res) => { + return res.code(500).send("Faucet feature temporarily disabled"); - try { - const { data: result } = await axios.post( - "https://assets.blockstream.info/", - { - asset_id: asset, - contract: account.contract - } - ); - l("register asset result", req.user.username, result); - res.send(result); - } catch (e) { - err("asset registration failed", e.message); - res.code(500).send(e.message); - } - }) - -app.post( - "/loadFaucet", - auth, - async (req, res) => { - return res.code(500).send("Faucet feature temporarily disabled"); + const { user } = req; + let { asset, amount } = req.body; + amount = parseInt(amount); - const { user } = req; - let { asset, amount } = req.body; - amount = parseInt(amount); + try { + if (amount <= 0) throw new Error("Amount to load cannot be negative"); - try { - if (amount <= 0) throw new Error("Amount to load cannot be negative"); + await db.transaction(async transaction => { + let account = await getAccount(config.liquid.btcasset, user, transaction); - await db.transaction(async transaction => { - let account = await getAccount( - config.liquid.btcasset, - user, - transaction + if (account.asset !== config.liquid.btcasset) + throw new Error( + "Faucet has to be funded with bitcoin. Try sending from another wallet." ); + if (account.balance < amount) throw new Error("Insufficient funds"); - if (account.asset !== config.liquid.btcasset) - throw new Error( - "Faucet has to be funded with bitcoin. Try sending from another wallet." - ); - if (account.balance < amount) throw new Error("Insufficient funds"); - - let fee = 0; + let fee = 0; - await account.decrement({ balance: amount }, { transaction }); - await account.reload({ transaction }); + await account.decrement({ balance: amount }, { transaction }); + await account.reload({ transaction }); - let a2; - let acc = { - user_id: null, - asset - }; + let a2; + let acc = { + user_id: null, + asset + }; - a2 = await db.Account.findOne({ - where: acc, - lock: transaction.LOCK.UPDATE, - transaction - }); + a2 = await db.Account.findOne({ + where: acc, + lock: transaction.LOCK.UPDATE, + transaction + }); - if (a2) { - await a2.increment({ balance: amount }, { transaction }); - await a2.reload({ transaction }); - } else { - let name = asset.substr(0, 6); - let domain; - let ticker = asset.substr(0, 3).toUpperCase(); - let precision = 8; + if (a2) { + await a2.increment({ balance: amount }, { transaction }); + await a2.reload({ transaction }); + } else { + let name = asset.substr(0, 6); + let domain; + let ticker = asset.substr(0, 3).toUpperCase(); + let precision = 8; - const assets = assets; + const assets = assets; - if (assets[asset]) { - ({ domain, ticker, precision, name } = assets[asset]); - } else { - const existing = await db.Account.findOne({ - where: { - asset - }, - order: [["id", "ASC"]], - limit: 1, - lock: transaction.LOCK.UPDATE, - transaction - }); + if (assets[asset]) { + ({ domain, ticker, precision, name } = 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); - } + if (existing) { + ({ domain, ticker, precision, name } = existing); } - - acc = { ...acc, ...{ domain, ticker, precision, name } }; - acc.balance = amount; - acc.pending = 0; - acc.network = "liquid"; - a2 = await db.Account.create(acc, { transaction }); } - let params = { - amount: -amount, - account_id: account.id, - user_id: user.id, - rate: store.rates[user.currency], - currency: user.currency, - confirmed: true, - hash: `Loaded Faucet - ${a2.ticker}`, - network: "COINOS" - }; + acc = { ...acc, ...{ domain, ticker, precision, name } }; + acc.balance = amount; + acc.pending = 0; + acc.network = "liquid"; + a2 = await db.Account.create(acc, { transaction }); + } - let payment = await db.Payment.create(params, { transaction }); + let params = { + amount: -amount, + account_id: account.id, + user_id: user.id, + rate: store.rates[user.currency], + currency: user.currency, + confirmed: true, + hash: `Loaded Faucet - ${a2.ticker}`, + network: "COINOS" + }; - payment = payment.get({ plain: true }); - payment.account = account.get({ plain: true }); + let payment = await db.Payment.create(params, { transaction }); - l("sent internal", user.username, -payment.amount); + payment = payment.get({ plain: true }); + payment.account = account.get({ plain: true }); - emit(user.username, "payment", payment); - emit(user.username, "account", account); - emit(user.username, "user", user); + l("sent internal", user.username, -payment.amount); - l("loaded faucet", asset, amount); - res.send({}); - }); - } catch (e) { - err("problem loading faucet", user.username, e.message); - return res.code(500).send(e.message); - } - }) + emit(user.username, "payment", payment); + emit(user.username, "account", account); + emit(user.username, "user", user); -app.get( - "/faucet", - auth, - async (req, res) => { - let { asset } = req.query; - let faucet = await db.Account.findOne({ - where: { - asset, - user_id: null - } + l("loaded faucet", asset, amount); + res.send({}); }); + } catch (e) { + err("problem loading faucet", user.username, e.message); + return res.code(500).send(e.message); + } +}); - if (!faucet) - faucet = { - asset, - balance: 0, - ticker: "Unknown" - }; +app.get("/faucet", auth, async (req, res) => { + let { asset } = req.query; + let faucet = await db.Account.findOne({ + where: { + asset, + user_id: null + } + }); + + if (!faucet) + faucet = { + asset, + balance: 0, + ticker: "Unknown" + }; - res.send(faucet); - }) + res.send(faucet); +}); diff --git a/routes/funding.js b/routes/funding.js index 9647b301..e65a704e 100644 --- a/routes/funding.js +++ b/routes/funding.js @@ -1,110 +1,96 @@ import { emit } from "$lib/sockets"; import app from "$app"; import config from "$config"; -import mailgunFactory from 'mailgun-js'; +import mailgunFactory from "mailgun-js"; const mailgun = mailgunFactory(config.mailgun); -app.post( - "/id", - auth, - upload.single("id"), - async (req, res) => { - const { user } = req; - if (user.verified === "proof") user.verified = "pending"; - else user.verified = "id"; - await user.save(); - emit(user.username, "user", user); +app.post("/id", auth, upload.single("id"), async (req, res) => { + const { user } = req; + if (user.verified === "proof") user.verified = "pending"; + else user.verified = "id"; + await user.save(); + emit(user.username, "user", user); - let data = { - subject: "KYC Documents", - text: `ID uploaded for ${user.username}`, - from: "[email protected]", - to: "[email protected]" - }; + let data = { + subject: "KYC Documents", + text: `ID uploaded for ${user.username}`, + from: "[email protected]", + to: "[email protected]" + }; - mailgun.messages().send(data); - l("id uploaded", user.username); + mailgun.messages().send(data); + l("id uploaded", user.username); - res.send({}); - }) + res.send({}); +}); -app.post( - "/proof", - auth, - upload.single("proof"), - async (req, res) => { - const { user } = req; - if (user.verified === "id") user.verified = "pending"; - else user.verified = "proof"; - await user.save(); - emit(user.username, "user", user); - l("id proof uploaded", user.username); +app.post("/proof", auth, upload.single("proof"), async (req, res) => { + const { user } = req; + if (user.verified === "id") user.verified = "pending"; + else user.verified = "proof"; + await user.save(); + emit(user.username, "user", user); + l("id proof uploaded", user.username); - res.send({}); - }) + res.send({}); +}); -app.post( - "/funding", - auth, - async (req, res) => { - try { - let { id, amount, code } = req.body; +app.post("/funding", auth, async (req, res) => { + try { + let { id, amount, code } = req.body; - if (!code) { - code = ""; - let d = "ABCDEFGHIJKLMNPQRSTUVWXYZ23456789"; - let l = d.length; - for (let i = 0; i < 8; i++) { - code += d.charAt(Math.floor(Math.random() * l)); - } + if (!code) { + code = ""; + let d = "ABCDEFGHIJKLMNPQRSTUVWXYZ23456789"; + let l = d.length; + for (let i = 0; i < 8; i++) { + code += d.charAt(Math.floor(Math.random() * l)); } - - let params = { - user_id: req.user.id, - amount, - code - }; - - let deposit; - if (id) { - if (!parseFloat(amount) || parseFloat(amount) < 0) - throw new Error("Invalid amount"); - deposit = await db.Deposit.findOne({ where: { id } }); - deposit.update(params); - await deposit.save(); - } else { - deposit = await db.Deposit.create(params); - } - - res.send(deposit); - } catch (e) { - err("funding error", e.message); - res.code(500).send("Funding request failed"); } - }) -app.post( - "/withdrawal", - auth, - async (req, res) => { - try { - const { account, amount, email, institution, transit, notes } = req.body; + let params = { + user_id: req.user.id, + amount, + code + }; + + let deposit; + if (id) { if (!parseFloat(amount) || parseFloat(amount) < 0) throw new Error("Invalid amount"); + deposit = await db.Deposit.findOne({ where: { id } }); + deposit.update(params); + await deposit.save(); + } else { + deposit = await db.Deposit.create(params); + } - await db.Withdrawal.create({ - user_id: req.user.id, - account, - amount, - email, - institution, - transit, - notes - }); + res.send(deposit); + } catch (e) { + err("funding error", e.message); + res.code(500).send("Funding request failed"); + } +}); - res.send({}); - } catch (e) { - err("withdrawaerr", e.message); - res.code(500).send("Withdrawal request failed"); - } - }) +app.post("/withdrawal", auth, async (req, res) => { + try { + const { account, amount, email, institution, transit, notes } = req.body; + if (!parseFloat(amount) || parseFloat(amount) < 0) + throw new Error("Invalid amount"); + + await db.Withdrawal.create({ + user_id: req.user.id, + account, + amount, + email, + institution, + transit, + notes + }); + + res.send({}); + } catch (e) { + err("withdrawaerr", e.message); + res.code(500).send("Withdrawal request failed"); + } +}); diff --git a/routes/info.js b/routes/info.js index d8785333..1b92624b 100644 --- a/routes/info.js +++ b/routes/info.js @@ -1,5 +1,5 @@ import app from "$app"; -import sequelize from '@sequelize/core'; +import sequelize from "@sequelize/core"; import config from "$config"; import store from "$lib/store"; import ln from "$lib/ln"; @@ -21,7 +21,7 @@ app.get("/info", async (req, res, next) => { const info = { nodes: store.networks, - clientVersion, + clientVersion }; res.send(info); @@ -34,35 +34,37 @@ app.get("/balances", async (req, res, next) => { "pubkey", [sequelize.fn("sum", sequelize.col("balance")), "total"] ], - group: ["asset", "pubkey"], + group: ["asset", "pubkey"] }); - let lnchannel; + let lnchannel; let lnwallet; if (config.lna) { if (config.lna.clightning) { const funds = await lna.listfunds(); - lnchannel = parseInt(funds.channels.reduce((a, b) => a + b.channel_sat, 0)); + lnchannel = parseInt( + funds.channels.reduce((a, b) => a + b.channel_sat, 0) + ); lnwallet = parseInt(funds.outputs.reduce((a, b) => a + b.value, 0)); } else { - lnchannel = parseInt((await getChannelBalance({ lnd }).channel_balance)); - lnwallet = parseInt((await getChainBalance({ lnd }).chain_balance)); - } + lnchannel = parseInt(await getChannelBalance({ lnd }).channel_balance); + lnwallet = parseInt(await getChainBalance({ lnd }).chain_balance); + } } let bitcoin, bitcoind; if (config.bitcoin) { bitcoin = parseInt((await bc.getBalance()) * SATS); bitcoind = await bc.getNetworkInfo(); - } + } let assets, liquid, elementsd; if (config.liquid) { assets = await lq.getBalance(); liquid = parseInt(assets.bitcoin * SATS); elementsd = await lq.getNetworkInfo(); - } + } const info = { bitcoind, @@ -72,7 +74,7 @@ app.get("/balances", async (req, res, next) => { bitcoin, liquid, lnchannel, - lnwallet, + lnwallet }; info.total = diff --git a/routes/lnurl.js b/routes/lnurl.js index d7bdcfc2..1cf5e319 100644 --- a/routes/lnurl.js +++ b/routes/lnurl.js @@ -9,7 +9,7 @@ import qs from "query-string"; import persist from "$lib/persist"; import bolt11 from "bolt11"; import { optionalAuth, auth } from "$lib/passport"; -import { createInvoice, getPayments, from "lightning"; +import { createInvoice, getPayments } from "lightning"; import lnd from "$lib/lnd"; export const logins = persist("data/logins.json"); @@ -455,7 +455,7 @@ lnurlServer.bindToHook( try { let { payments } = await ln.getPayments({ lnd, - limit: 5, + limit: 5 }); let p = payments.find(p => p.request === pr); diff --git a/routes/payments.js b/routes/payments.js index 4939394f..6d4076cf 100644 --- a/routes/payments.js +++ b/routes/payments.js @@ -65,7 +65,7 @@ if (config.lna) { // if (config.lnurl) { // let channelRequest = await import("$routes/lightning/channelRequest"); // app.post("/lightning/channelRequest", channelRequest) - // } + // } } if (config.bitcoin) { diff --git a/routes/referrals.js b/routes/referrals.js index 08059c74..b3d53306 100644 --- a/routes/referrals.js +++ b/routes/referrals.js @@ -1,19 +1,19 @@ -import express from 'express'; +import express from "express"; var router = express.Router(); -import { v4 } from 'uuid'; +import { v4 } from "uuid"; -router.get('/', function(req, res, next) { - res.send('list of referrals...'); +router.get("/", function(req, res, next) { + res.send("list of referrals..."); }); // Grant & Retrieve Referral tokens for existing user // usage: GET '/grant?sponsor_id=N&expiry=2021-09-01' // -// Required: +// Required: // sponsor_id (= user.id) -// Changes to DB: +// Changes to DB: // adds record to referrals table: // { token: <uuid>, sponsor_id: <user.id>, status: "available" } @@ -22,9 +22,9 @@ router.get('/', function(req, res, next) { * @apiName Grant * @apiGroup Referrals * - * + * * @apiPermission member - * + * * @apiParam {sponsor_id} user_id of member generating referral code. * @apiParam {expiry} optional expiry date for token. * @@ -34,28 +34,23 @@ router.get('/', function(req, res, next) { * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { - * "token": "*********", - * "status": "available", + * "token": "*********", + * "status": "available", * "expiry": null * } */ -router.post( - "/grant", - auth, - async (req, res) => { - const {sponsor_id, expiry} = req.body - var token = v4() +router.post("/grant", auth, async (req, res) => { + const { sponsor_id, expiry } = req.body; + var token = v4(); - var ref = await knex.table('referrals') - .insert({ - sponsor_id: sponsor_id, - token: token, - status: 'available' - } - ) + var ref = await knex.table("referrals").insert({ + sponsor_id: sponsor_id, + token: token, + status: "available" + }); - return res.send({token: token, status: 'available', expiry: expiry}) - }) + return res.send({ token: token, status: "available", expiry: expiry }); +}); /** * @api {get} /grant Grant Referral code (variation using get) @@ -63,7 +58,7 @@ router.post( * @apiGroup Referrals * * @apiPermission member - * + * * @apiPermission member * @apiParam {sponsor_id} user_id of member generating referral code. * @apiParam {expiry} optional expiry date for token. @@ -74,43 +69,37 @@ router.post( * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { - * "token": "*********", - * "status": "available", + * "token": "*********", + * "status": "available", * "expiry": null * } */ -router.get( - "/grant", - auth, - async (req, res) => { - const {sponsor_id, expiry} = req.query - var token = v4() - - var ref = await knex.table('referrals') - .insert({ - sponsor_id: sponsor_id, - token: token, - status: 'available' - } - ) +router.get("/grant", auth, async (req, res) => { + const { sponsor_id, expiry } = req.query; + var token = v4(); - return res.send({token: token, status: 'available', expiry: expiry}) - }) + var ref = await knex.table("referrals").insert({ + sponsor_id: sponsor_id, + token: token, + status: "available" + }); + return res.send({ token: token, status: "available", expiry: expiry }); +}); /** * @api {get} /checkTokens/:sponsor_id Retrieve list of referral tokens generated by this user - * + * * @apiName checkTokens * @apiGroup Referrals * - * + * * @apiPermission member - * + * * @apiParam {sponsor_id} user_id of member generating referral code. * @apiParam {status} optional token status. * - * @apiSuccess tokens array of token objects + * @apiSuccess tokens array of token objects * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { @@ -122,40 +111,37 @@ router.get( // TO FIX - change sponsor_id so that it is retrieved from current payload (NOT FROM URL) -router.get( - "/checkTokens/:sponsor_id", - auth, - async (req, res) => { - const {sponsor_id} = req.params - const {status} = req.query +router.get("/checkTokens/:sponsor_id", auth, async (req, res) => { + const { sponsor_id } = req.params; + const { status } = req.query; - var tokens = knex - .select( - 'token', - 'created_at', - knex.raw('LEFT(created_at,10) as created'), - 'username', - 'status' - ) - .from('referrals') - .leftJoin('users', 'users.id', 'referrals.user_id') - .where('sponsor_id', 'like', sponsor_id) + var tokens = knex + .select( + "token", + "created_at", + knex.raw("LEFT(created_at,10) as created"), + "username", + "status" + ) + .from("referrals") + .leftJoin("users", "users.id", "referrals.user_id") + .where("sponsor_id", "like", sponsor_id); - if (status && status !== 'all') tokens = tokens.where('status', 'like', status) - const found = await tokens - - return res.send({tokens: found}) - }) + if (status && status !== "all") + tokens = tokens.where("status", "like", status); + const found = await tokens; + return res.send({ tokens: found }); +}); /** * @api {get} /verify/:user_id Verify token and apply to existing user - * + * * @apiName verify * @apiGroup Referrals - * + * * @apiPermission member - * + * * @apiParam {user_id} Current user * @apiParam {token} Token to validate * @@ -165,42 +151,46 @@ router.get( * { * "verified": true * } - * + * * @apiDescription referral token is updated from 'available' to 'used' * @apiDescription referral token is updated with existing user_id */ -router.get( - "/verify/:user_id/:token", - auth, - async (req, res) => { - const { user_id, token } = req.params; +router.get("/verify/:user_id/:token", auth, async (req, res) => { + const { user_id, token } = req.params; - const found = await knex - .select('status') - .from('referrals') - .where('token', 'like', token) - .whereNull('user_id') + const found = await knex + .select("status") + .from("referrals") + .where("token", "like", token) + .whereNull("user_id"); - if (found && found.length) { - if (found[0].status === 'available') { - - await knex('referrals') - .where('token', 'like', token) - .update({ - status: 'used', + if (found && found.length) { + if (found[0].status === "available") { + await knex("referrals") + .where("token", "like", token) + .update({ + status: "used", user_id: user_id, - updated_at: new Date().toISOString().substring(0,10) - }) + updated_at: new Date().toISOString().substring(0, 10) + }); - return res.send({ verified: true, sponsor_id: found.sponsor_id, updated: found.updated_at}); - } else { - res.code(500).send({ verified: false, message: 'Referral already ' + found[0].status }) - } + return res.send({ + verified: true, + sponsor_id: found.sponsor_id, + updated: found.updated_at + }); } else { - res.code(500).send('Invalid referral token') + res + .code(500) + .send({ + verified: false, + message: "Referral already " + found[0].status + }); } - }) - + } else { + res.code(500).send("Invalid referral token"); + } +}); /** * @api {post} /joinQueue Join waiting list (track email & phone) @@ -217,39 +207,39 @@ router.get( * "success": true * "message": 'Added to waiting list' * } - * + * * @apiDescription referral token is updated from 'available' to 'used' * @apiDescription referral token is updated with existing user_id */ -router.post( - "/joinQueue", - async (req, res) => { - const { email, phone, user_id } = req.body; +router.post("/joinQueue", async (req, res) => { + const { email, phone, user_id } = req.body; - await knex.table('waiting_list') - .insert({ - email: email, - phone: phone, - user_id: user_id - }) + await knex.table("waiting_list").insert({ + email: email, + phone: phone, + user_id: user_id + }); - res.send({success: true, message: 'Added ' + email + ' to waiting list ' + phone}) - }) + res.send({ + success: true, + message: "Added " + email + " to waiting list " + phone + }); +}); -router.get( - "/joinQueue", - async (req, res) => { - const {email, phone, user_id} = req.query; +router.get("/joinQueue", async (req, res) => { + const { email, phone, user_id } = req.query; - await knex('waiting_list') - .insert({ - email: email, - phone: phone, - user_id: user_id - }) + await knex("waiting_list").insert({ + email: email, + phone: phone, + user_id: user_id + }); - res.send({success: true, message: 'Added ' + email + ' to waiting list ' + phone}) - }) + res.send({ + success: true, + message: "Added " + email + " to waiting list " + phone + }); +}); /** * @api {get} /isReferred/:user_id Check if user is referred @@ -263,24 +253,22 @@ router.get( * { * true * } - * + * * @apiDescription returns boolean indicating if user is referred or not */ -router.get( - "/isReferred/:user_id", - async (req, res) => { - const { user_id } = req.params; +router.get("/isReferred/:user_id", async (req, res) => { + const { user_id } = req.params; + + var referred = await knex("referrals") + .select("referrals.id") + .where("user_id", "like", user_id) + .where("status", "like", "used"); - var referred = await knex('referrals') - .select('referrals.id') - .where('user_id', 'like', user_id) - .where('status', 'like', 'used') - - if (referred && referred.length) { - res.send({referred: true}) - } else { - res.send({referred: false}) - } - }) + if (referred && referred.length) { + res.send({ referred: true }); + } else { + res.send({ referred: false }); + } +}); export default router; diff --git a/routes/swaps.js b/routes/swaps.js index 31387bec..169c2b8f 100644 --- a/routes/swaps.js +++ b/routes/swaps.js @@ -3,11 +3,11 @@ import app from "$app"; import config from "$config"; import { auth, optionalAuth } from "$lib/passport"; import store from "$lib/store"; -import axios from 'axios'; -import crypto from 'crypto'; -import fs from 'fs'; -import getAccount from '../lib/account'; -import { Op, col } from '@sequelize/core'; +import axios from "axios"; +import crypto from "crypto"; +import fs from "fs"; +import getAccount from "../lib/account"; +import { Op, col } from "@sequelize/core"; const shallow = a => { let b = {}; @@ -335,131 +335,85 @@ const cancel = async (user, id) => { }); }; -app.delete( - "/order/:id", - auth, - async (req, res) => { - const { id } = req.params; - const { user } = req; +app.delete("/order/:id", auth, async (req, res) => { + const { id } = req.params; + const { user } = req; - await cancel(user, id); - res.send({}); - }) + await cancel(user, id); + res.send({}); +}); -app.post( - "/orders", - auth, - async (req, res) => { - return res.code(500).send("Trading temporarily disabled"); - const { user } = req; - try { - await swap(user, req.body); - res.send({}); - } catch (e) { - err(req.user.username, e.message); - res.code(500).send(e.message); - } - }) +app.post("/orders", auth, async (req, res) => { + return res.code(500).send("Trading temporarily disabled"); + const { user } = req; + try { + await swap(user, req.body); + res.send({}); + } catch (e) { + err(req.user.username, e.message); + res.code(500).send(e.message); + } +}); -app.get( - "/orders", - optionalAuth, - async (req, res) => { - try { - let orders = await db.Order.findAll({ - attributes: { - include: [ - [col("acc1.asset"), "a1"], - [col("acc2.asset"), "a2"] - ] - }, +app.get("/orders", optionalAuth, async (req, res) => { + try { + let orders = await db.Order.findAll({ + attributes: { include: [ - { - model: db.Account, - as: "acc1", - attributes: [] - }, - { - model: db.Account, - as: "acc2", - attributes: [] - } + [col("acc1.asset"), "a1"], + [col("acc2.asset"), "a2"] ] - }); + }, + include: [ + { + model: db.Account, + as: "acc1", + attributes: [] + }, + { + model: db.Account, + as: "acc2", + attributes: [] + } + ] + }); - res.send( - orders.map(order => { - if (order.user_id !== req.user.id) order.user_id = null; - return order; - }) - ); - } catch (e) { - res.code(500).send(e.message); - } - }) + res.send( + orders.map(order => { + if (order.user_id !== req.user.id) order.user_id = null; + return order; + }) + ); + } catch (e) { + res.code(500).send(e.message); + } +}); if (config.maker) { - debug('setup maker account...') - config.maker.map(({ amount, c1, c2, currency, askMultiplier, bidMultiplier }) => { - setInterval(async () => { - if (!rates) return; - - const user = await db.User.findOne({ - where: { - username: "maker" - } - }); - - if (!user) { - debug('maker user not defined in database') - } else { - debug('maker: ' + JSON.stringify(user)) - await db.transaction(async transaction => { - let order = await db.Order.findOne( - { - where: { - user_id: user.id, - "$acc1.asset$": c1, - "$acc2.asset$": c2, - accepted: false - }, - include: [ - { - model: db.Account, - as: "acc1" - }, - { - model: db.Account, - as: "acc2" - } - ] - }, - { transaction } - ); + debug("setup maker account..."); + config.maker.map( + ({ amount, c1, c2, currency, askMultiplier, bidMultiplier }) => { + setInterval(async () => { + if (!rates) return; - let params = { - a1: c1, - a2: c2, - v1: amount * SATS, - v2: Math.round( - amount * - SATS * - (((app.get("ask") * store.rates[currency]) / - store.rates["USD"]) * - askMultiplier) - ) - }; + const user = await db.User.findOne({ + where: { + username: "maker" + } + }); - if (order) { - let bestBid = await db.Order.findOne( + if (!user) { + debug("maker user not defined in database"); + } else { + debug("maker: " + JSON.stringify(user)); + await db.transaction(async transaction => { + let order = await db.Order.findOne( { where: { - "$acc1.asset$": c2, - "$acc2.asset$": c1, - accepted: false, - id: { - [Op.ne]: order.id - } + user_id: user.id, + "$acc1.asset$": c1, + "$acc2.asset$": c2, + accepted: false }, include: [ { @@ -470,80 +424,80 @@ if (config.maker) { model: db.Account, as: "acc2" } - ], - order: [["rate", "DESC"]], - limit: 1 + ] }, { transaction } ); - if ( - !bestBid || - (params.v2 / params.v1 > bestBid.rate && - order.acc2.balance >= params.v2) - ) { - order.v1 = params.v1; - order.v2 = params.v2; - await order.save(); - order = order.get({ plain: true }); - order.a1 = params.a1; - order.a2 = params.a2; - order.rate = order.v2 / order.v1; - broadcast("order", shallow(order)); - } - } else { - try { - await swap(user, params); - } catch (e) { - warn("Failed to make ask", e.message); - } - } + let params = { + a1: c1, + a2: c2, + v1: amount * SATS, + v2: Math.round( + amount * + SATS * + (((app.get("ask") * store.rates[currency]) / + store.rates["USD"]) * + askMultiplier) + ) + }; - order = await db.Order.findOne( - { - where: { - user_id: user.id, - "$acc1.asset$": c2, - "$acc2.asset$": c1, - accepted: false - }, - include: [ + if (order) { + let bestBid = await db.Order.findOne( { - model: db.Account, - as: "acc1" + where: { + "$acc1.asset$": c2, + "$acc2.asset$": c1, + accepted: false, + id: { + [Op.ne]: order.id + } + }, + include: [ + { + model: db.Account, + as: "acc1" + }, + { + model: db.Account, + as: "acc2" + } + ], + order: [["rate", "DESC"]], + limit: 1 }, - { - model: db.Account, - as: "acc2" - } - ] - }, - { transaction } - ); + { transaction } + ); + if ( + !bestBid || + (params.v2 / params.v1 > bestBid.rate && + order.acc2.balance >= params.v2) + ) { + order.v1 = params.v1; + order.v2 = params.v2; + await order.save(); + order = order.get({ plain: true }); + order.a1 = params.a1; + order.a2 = params.a2; + order.rate = order.v2 / order.v1; - params = { - a1: c2, - a2: c1, - v1: Math.round( - amount * - SATS * - ((app.get("bid") * store.rates[currency]) / - store.rates["USD"]) * - bidMultiplier - ), - v2: amount * SATS - }; + broadcast("order", shallow(order)); + } + } else { + try { + await swap(user, params); + } catch (e) { + warn("Failed to make ask", e.message); + } + } - if (order) { - let bestAsk = await db.Order.findOne( + order = await db.Order.findOne( { where: { - "$acc1.asset$": c1, - "$acc2.asset$": c2, - accepted: false, - id: { - [Op.ne]: order.id - } + user_id: user.id, + "$acc1.asset$": c2, + "$acc2.asset$": c1, + accepted: false }, include: [ { @@ -554,41 +508,80 @@ if (config.maker) { model: db.Account, as: "acc2" } - ], - order: [["rate", "ASC"]], - limit: 1 + ] }, - transaction + { transaction } ); - if (bestAsk) - if ( - !bestAsk || - (params.v1 / params.v2 < bestAsk.rate && - order.acc1.balance >= params.v1) - ) { - order.v1 = params.v1; - order.v2 = params.v2; - await order.save(); - order = order.get({ plain: true }); - order.a1 = params.a1; - order.a2 = params.a2; - order.rate = order.v2 / order.v1; + params = { + a1: c2, + a2: c1, + v1: Math.round( + amount * + SATS * + ((app.get("bid") * store.rates[currency]) / + store.rates["USD"]) * + bidMultiplier + ), + v2: amount * SATS + }; - broadcast("order", shallow(order)); - } else { - broadcast("removeOrder", order.id); - await order.destroy({ transaction }); + if (order) { + let bestAsk = await db.Order.findOne( + { + where: { + "$acc1.asset$": c1, + "$acc2.asset$": c2, + accepted: false, + id: { + [Op.ne]: order.id + } + }, + include: [ + { + model: db.Account, + as: "acc1" + }, + { + model: db.Account, + as: "acc2" + } + ], + order: [["rate", "ASC"]], + limit: 1 + }, + transaction + ); + + if (bestAsk) + if ( + !bestAsk || + (params.v1 / params.v2 < bestAsk.rate && + order.acc1.balance >= params.v1) + ) { + order.v1 = params.v1; + order.v2 = params.v2; + await order.save(); + order = order.get({ plain: true }); + order.a1 = params.a1; + order.a2 = params.a2; + order.rate = order.v2 / order.v1; + + broadcast("order", shallow(order)); + } else { + broadcast("removeOrder", order.id); + await order.destroy({ transaction }); + } + } else { + try { + await swap(user, params); + } catch (e) { + warn("Failed to make bid", e.message); } - } else { - try { - await swap(user, params); - } catch (e) { - warn("Failed to make bid", e.message); } - } - }); - } - }, 5000); - }); + }); + } + }, 5000); + } + ); } diff --git a/routes/users.js b/routes/users.js index ca1f3a02..dd62fad1 100644 --- a/routes/users.js +++ b/routes/users.js @@ -10,7 +10,7 @@ import { authenticator } from "otplib"; import getAccount from "$lib/account"; import Sequelize from "@sequelize/core"; import bitcoin from "bitcoinjs-lib"; -import liquid from 'liquidjs-lib'; +import liquid from "liquidjs-lib"; import { fromBase58, fromPrivateKey } from "bip32"; import { Mutex } from "async-mutex"; import bip32 from "bip32"; @@ -387,8 +387,7 @@ app.get("/address", async (req, res) => { const release = await mutex.acquire(); try { if (network === "bitcoin") { - if (!config.bitcoin) - return res.code(500).send("Bitcoin not configured"); + if (!config.bitcoin) return res.code(500).send("Bitcoin not configured"); address = await bc.getNewAddress("", type); store.bcAddressIndex = i + 1; |
