diff options
| author | Adam Soltys <[email protected]> | 2022-09-02 15:06:43 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2022-09-02 15:06:43 -0700 |
| commit | d1cc66d1a02b75f90fbf0c05910777c76228259a (patch) | |
| tree | 7b93dc6a2fc0ec9d03676d6b4093fedf9733f128 | |
| parent | 3161dd7ee95b6c7d70f8341298dd4fab84cda8b0 (diff) | |
| download | coinos-server-d1cc66d1a02b75f90fbf0c05910777c76228259a.tar.gz coinos-server-d1cc66d1a02b75f90fbf0c05910777c76228259a.zip | |
es6 migration
40 files changed, 240 insertions, 212 deletions
@@ -25,7 +25,7 @@ import { networks } from "./lib/store.js"; // // if (req.user) details.username = req.user.username; // -// l.error("JSON Error: ", JSON.stringify(details)); +// err("JSON Error: ", JSON.stringify(details)); // res.status(500); // res.set({ // "Cache-Control": "no-cache" diff --git a/lib/binance.js b/lib/binance.js index 0f91ce8c..3e25e277 100644 --- a/lib/binance.js +++ b/lib/binance.js @@ -1,9 +1,14 @@ -import WebSocket from 'ws'; +import app from "../app.js"; +import WebSocket from "ws"; +import { err } from "./logging.js"; +import { rates } from "./store.js"; export default () => { - const binance = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker"); + const binance = new WebSocket( + "wss://stream.binance.com:9443/ws/btcusdt@ticker" + ); - binance.onmessage = async function (event) { + binance.onmessage = async function(event) { try { let msg = JSON.parse(event.data); @@ -11,7 +16,7 @@ export default () => { if (!fx) return; let rates = {}; - Object.keys(fx).map((symbol) => { + Object.keys(fx).map(symbol => { rates[symbol] = msg.c * fx[symbol]; }); @@ -20,13 +25,13 @@ export default () => { app.set("last", msg.c); app.set("rates", rates); } catch (e) { - l.error("binance message error", e.message); + err("binance message error", e.message); } }; - binance.onerror = async function (error) { - console.log("binance socket error", error); - } + binance.onerror = async function(error) { + err("binance socket error", error); + }; return binance; }; diff --git a/lib/buildliquidtx.js b/lib/buildliquidtx.js index 014b026c..783e4036 100644 --- a/lib/buildliquidtx.js +++ b/lib/buildliquidtx.js @@ -58,7 +58,7 @@ export default async ({ try { utxos.push(...(await axios.get(url)).data); } catch (e) { - l.error("problem fetching utxos", e.message, url); + err("problem fetching utxos", e.message, url); } } @@ -81,7 +81,7 @@ export default async ({ let { inputs, outputs, fee } = coinselect(utxos, targets, feeRate); if (!inputs || !outputs) { - l.info( + l( "utxos", amount, feeRate, diff --git a/lib/buildtx.js b/lib/buildtx.js index a696062c..e6dde1d2 100644 --- a/lib/buildtx.js +++ b/lib/buildtx.js @@ -28,7 +28,7 @@ export default async ({ address, amount, feeRate, replaceable, user }) => { try { utxos.push(...(await axios.get(`${api}/address/${addresses[i]}/utxo`)).data); } catch (e) { - l.error("problem fetching utxos", e.message); + err("problem fetching utxos", e.message); } } @@ -42,7 +42,7 @@ export default async ({ address, amount, feeRate, replaceable, user }) => { let { inputs, outputs, fee } = coinselect(utxos, targets, feeRate); if (!inputs || !outputs) { - l.info("utxos", amount, feeRate, utxos.map(u => u.value)); + l("utxos", amount, feeRate, utxos.map(u => u.value)); throw new Error("Couldn't find inputs for transaction, check your balance/fee"); } diff --git a/lib/logging.js b/lib/logging.js index 95e48514..5ad3a0b0 100644 --- a/lib/logging.js +++ b/lib/logging.js @@ -1,5 +1,5 @@ import pino from "pino"; - export const l = (...msgs) => pino().info(msgs.join(" ")) - export const warn = (...msgs) => pino().warn(msgs.join(" ")) - export const err = (...msgs) => pino().error(msgs.join(" ")) +export const l = (...msgs) => pino().info(msgs.join(" ")); +export const warn = (...msgs) => pino().warn(msgs.join(" ")); +export const err = (...msgs) => pino().error(msgs.join(" ")); diff --git a/lib/mail.js b/lib/mail.js index 9d2ff7fc..d1b67c37 100644 --- a/lib/mail.js +++ b/lib/mail.js @@ -5,6 +5,7 @@ import Imap from "imap"; import { inspect } from "util"; import persist from "./persist.js"; const emails = persist("data/emails.json"); +import { rates } from "./store.js"; let imap = new Imap(config.imap); function openInbox(cb) { @@ -85,7 +86,7 @@ imap.once("ready", function() { let { user } = account; - let rate = app.get("rates")["CAD"] * 1.02; + let rate = rates["CAD"] * 1.02; let amount = Math.round((cad / rate) * 100000000); await account.increment({ balance: amount }, { transaction }); @@ -109,7 +110,7 @@ imap.once("ready", function() { emit(user.username, "account", account); emit(user.username, "payment", payment); - l.info( + l( "interac deposit detected for", user.username, cad, diff --git a/lib/notifications.js b/lib/notifications.js index c931f09c..40d227c8 100644 --- a/lib/notifications.js +++ b/lib/notifications.js @@ -21,7 +21,7 @@ export const notify = (user, payload) => { user.subscriptions.splice(i, 1); await user.save(); } else { - l.error("problem sending notification", e); + err("problem sending notification", e); } } }); diff --git a/lib/passport.js b/lib/passport.js index 16deef6e..5f987014 100644 --- a/lib/passport.js +++ b/lib/passport.js @@ -46,7 +46,7 @@ fastifyPassport.use( } catch (e) { if (!e.message.includes("locked")) { console.log(e); - l.error("problem logging in", e); + err("problem logging in", e); } next(null, { username: "guest" }); } diff --git a/lib/rates.js b/lib/rates.js index 48c87aa7..5f0c3c42 100644 --- a/lib/rates.js +++ b/lib/rates.js @@ -2,6 +2,8 @@ import app from "../app.js"; import axios from "axios"; import fs from "fs"; import binanceFactory from "./binance.js"; +import { broadcast } from "./sockets.js"; + const binance = binanceFactory(); let fetchRates; @@ -11,7 +13,7 @@ let fetchRates; try { ({ date, fx } = JSON.parse(fs.readFileSync("fx"))); } catch (e) { - l.warn("Failed to read fx file"); + warn("Failed to read fx file"); } let today = JSON.stringify(new Date()) @@ -38,7 +40,7 @@ let fetchRates; }); fs.writeFileSync("fx", JSON.stringify({ date, fx })); } catch (e) { - l.error("error fetching rates", e.message); + err("error fetching rates", e.message); } } } @@ -49,7 +51,7 @@ let fetchRates; })(); app.get("/rates", async (req, res, next) => { - res.send(app.get("rates")); + res.send(rates); }); setInterval(() => { diff --git a/lib/register.js b/lib/register.js index 3dc259f5..f1e8a37c 100644 --- a/lib/register.js +++ b/lib/register.js @@ -58,6 +58,6 @@ export const register = async (user, ip, requireChallenge) => { user.account_id = account.id; await user.save(); - l.info("new user", user.username, ip); + l("new user", user.username, ip); return user; } @@ -1,3 +1,5 @@ +import wretch from "./wretch.js"; + export default ({ host, port, wallet, user, password }) => new Proxy( {}, diff --git a/lib/send.js b/lib/send.js index e589ca6b..15855d55 100644 --- a/lib/send.js +++ b/lib/send.js @@ -1,9 +1,10 @@ +import { rates } from "./store.js"; import bolt11 from 'bolt11'; import { Op } from '@sequelize/core'; import { computeConversionFee, conversionFeeReceiver } from '../routes/lightning/conversionFee.js'; export const send = async (amount, memo, hash, user) => { - l.info("attempting lightning payment", user.username, amount, hash); + l("attempting lightning payment", user.username, amount, hash); let payreq = bolt11.decode(hash); let routingInfo = payreq.tags.find(t => t.tagName === "routing_info"); @@ -11,7 +12,7 @@ export const send = async (amount, memo, hash, user) => { routingInfo && routingInfo.data.find(d => d.fee_proportional_millionths > 10000) ) { - l.warn("fee rate too high", d.fee_proportional_millionths); + warn("fee rate too high", d.fee_proportional_millionths); throw new Error( "Couldn't find a suitable route to pay to your destination" ); @@ -20,7 +21,7 @@ export const send = async (amount, memo, hash, user) => { if (!amount || payreq.satoshis > amount) amount = payreq.satoshis; if (seen.includes(hash)) { - l.warn("attempted to pay a paid invoice", user.username); + warn("attempted to pay a paid invoice", user.username); throw new Error("Invoice has been paid, can't pay again"); } @@ -29,7 +30,7 @@ export const send = async (amount, memo, hash, user) => { let conversionFee = computeConversionFee(amount); let conversionFeeDeduction; await db.transaction(async transaction => { - l.info("starting lightning send transaction"); + l("starting lightning send transaction"); let account; if (user.account.asset === config.liquid.btcasset) account = await db.Account.findOne({ @@ -60,7 +61,7 @@ export const send = async (amount, memo, hash, user) => { ); if (!account || account.balance < amount + conversionFee - conversionFeeDeduction) { - l.warn("user attempting to send more than they have", user.id, amount, conversionFee); + warn("user attempting to send more than they have", user.id, amount, conversionFee); throw new Error("Insufficient funds"); } @@ -70,7 +71,7 @@ export const send = async (amount, memo, hash, user) => { ); await account.reload({ transaction }); - l.info("debited account", account.id); + l("debited account", account.id); if (config.lna.clightning) { let m = await lna.pay(hash); @@ -103,13 +104,13 @@ export const send = async (amount, memo, hash, user) => { preimage = preimage.toString("hex"); if (seen.includes(preimage)) { - l.warn("duplicate payment detected", preimage); + warn("duplicate payment detected", preimage); throw new Error("Duplicate payment detected"); } }); await db.transaction(async transaction => { - l.info("starting lightning fee transaction"); + l("starting lightning fee transaction"); let account; if (user.account.asset === config.liquid.btcasset) @@ -174,7 +175,7 @@ export const send = async (amount, memo, hash, user) => { memo: "Lightning conversion fee", account_id: receiverAccount.id, user_id: receiverAccount.user_id, - rate: app.get("rates")[receiverAccount.user.currency], + rate: rates[receiverAccount.user.currency], currency: receiverAccount.user.currency, confirmed: true, received: true, @@ -193,7 +194,7 @@ export const send = async (amount, memo, hash, user) => { hash, memo, preimage, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed: true, network: "lightning", @@ -203,7 +204,7 @@ export const send = async (amount, memo, hash, user) => { { transaction } ); - l.info("created payment record", payment.id); + l("created payment record", payment.id); payment = payment.get({ plain: true }); @@ -216,7 +217,7 @@ export const send = async (amount, memo, hash, user) => { seen.push(preimage); seen.push(hash); - l.info("sent lightning", user.username, total - fee, fee); + l("sent lightning", user.username, total - fee, fee); }); return payment; diff --git a/lib/sockets.js b/lib/sockets.js index dcb8a840..6ea369c0 100644 --- a/lib/sockets.js +++ b/lib/sockets.js @@ -1,3 +1,4 @@ +import { sockets } from "./store.js"; import app from "../app.js"; import jwt from "jsonwebtoken"; import { v4 as uuidv4 } from "uuid"; @@ -70,7 +71,7 @@ app.register(async function(app) { try { ({ type, data } = JSON.parse(message)); } catch (e) { - l.error("coudn't parse socket message"); + err("coudn't parse socket message"); } switch (type) { @@ -137,7 +138,7 @@ app.register(async function(app) { JSON.stringify({ type: "version", data: config.clientVersion }) ); } catch (e) { - l.error("caught socket error", e.message); + err("caught socket error", e.message); if (e.message.includes("locked")) { ws.send(JSON.stringify({ type: "locked" })); ws.send(JSON.stringify({ type: "logout" })); @@ -178,7 +179,7 @@ app.register(async function(app) { subscriptions.push({ invoice: data, ws }); break; default: - l.warn("received socket message of unknown type", type, data); + warn("received socket message of unknown type", type, data); } }); @@ -192,7 +193,7 @@ app.register(async function(app) { if (all[id]) delete all[id]; } catch (e) { - l.error("problem closing socket", e.message); + err("problem closing socket", e.message); } }); }); diff --git a/lib/store.js b/lib/store.js index fae3e65a..f32ad101 100644 --- a/lib/store.js +++ b/lib/store.js @@ -12,3 +12,4 @@ export const sockets = {}; export const unaccounted = []; export const networks = []; export const convert = persist("data/conversions.json"); +export const fx; diff --git a/lib/sync.js b/lib/sync.js index 1a98c121..6fcf8a10 100644 --- a/lib/sync.js +++ b/lib/sync.js @@ -4,12 +4,13 @@ import { differenceInDays } from "date-fns"; import fs from "fs"; import read from "../lib/read.js"; import { Op } from "@sequelize/core"; +import { addresses, exceptions } from "./store.js"; const init = async () => { try { read(fs.createReadStream("exceptions"), data => exceptions.push(data)); } catch (e) { - l.warn("couldn't read exceptions file", e.message); + warn("couldn't read exceptions file", e.message); } try { @@ -132,11 +133,11 @@ const sync = async () => { await account.increment({ balance: amount }); - l.info("lightning missing from account", account.id, amount); + l("lightning missing from account", account.id, amount); } } } catch (e) { - l.error( + err( "problem syncing lightning payment", JSON.stringify(missed[i]), e.message, @@ -194,9 +195,9 @@ const sync = async () => { emit(p.user.username, "account", p.account); emit(p.user.username, "payment", p); - l.info("unconfirmed tx", p.user_id, p.hash, p.address); + l("unconfirmed tx", p.user_id, p.hash, p.address); } catch (e) { - l.error("problem confirming payment", p, e.message, e.stack); + err("problem confirming payment", p, e.message, e.stack); } } @@ -214,7 +215,7 @@ const sync = async () => { }); if (unaccounted.length) - l.warn( + warn( "wallet transactions missing from database", unaccounted.map(tx => tx.txid) ); @@ -261,7 +262,7 @@ const sync = async () => { user_id } = invoices[i]; - l.info("unaccounted", address); + l("unaccounted", address); let pending = unaccounted.filter( tx => tx.address === address || tx.address === unconfidential @@ -274,7 +275,7 @@ const sync = async () => { try { await db.transaction(async transaction => { - l.info("found pending transaction", user.username, amount, hash); + l("found pending transaction", user.username, amount, hash); payments.push(hash); let p = await db.Payment.create( { @@ -300,7 +301,7 @@ const sync = async () => { emit(user.username, "payment", p); }); } catch (e) { - l.error( + err( "problem updating pending transaction", hash, e.message, @@ -310,7 +311,7 @@ const sync = async () => { } } } catch (e) { - l.error("sync check failed", e.message, e.stack); + err("sync check failed", e.message, e.stack); } setTimeout(sync, 300000); diff --git a/lib/webhooks.js b/lib/webhooks.js index ccebc024..c0919b59 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,6 +1,4 @@ -import wretch from 'wretch'; -import fetch from 'node-fetch'; -wretch().polyfills({ fetch }); +import wretch from './wretch.js'; export const callWebhook = (invoice, payment) => { if (!invoice || !payment) return; @@ -12,7 +10,7 @@ export const callWebhook = (invoice, payment) => { let { asset } = account; let secret = config.webhooks[webhook]; - l.info("calling webhook", webhook, amount, hash, address, text); + l("calling webhook", webhook, amount, hash, address, text); return wretch() .headers({ "x-webhook": secret }) .url(webhook) diff --git a/lib/wretch.js b/lib/wretch.js new file mode 100644 index 00000000..e4427760 --- /dev/null +++ b/lib/wretch.js @@ -0,0 +1,3 @@ +import wretch from "wretch"; +import fetch from 'node-fetch'; +export default wretch().polyfills({ fetch }); diff --git a/routes/assets.js b/routes/assets.js index 1da217ae..451f8b6a 100644 --- a/routes/assets.js +++ b/routes/assets.js @@ -1,3 +1,4 @@ +import { rates } from "../lib/store.js"; import app from "../app.js"; import { auth } from "../lib/passport.js"; import axios from 'axios'; @@ -17,7 +18,7 @@ let fetchAssets; app.set("assets", liquid_assets); console.debug("using static assets..." + e.message); } else { - l.error("error fetching assets", e.message); + err("error fetching assets", e.message); res.status(500).send("error fetching assets"); } } @@ -117,7 +118,7 @@ app.post( .sort() .reduce((r, k) => ((r[k] = contract[k]), r), {}); - l.info( + l( "attempting issuance", req.user.username, contract, @@ -154,7 +155,7 @@ app.post( try { ria = await lq.rawIssueAsset(funded.hex, [params]); } catch (e) { - l.info(asset_amount, token_amount, params); + l(asset_amount, token_amount, params); throw new Error(e.message); } @@ -183,7 +184,7 @@ app.post( let { user } = account; if (Math.round(funded.fee * SATS) > account.balance) { - l.error( + err( "amount exceeds balance", asset_amount, funded.fee, @@ -216,7 +217,7 @@ app.post( ); emit(user.username, "account", account); - l.info( + l( "issued asset", user.username, params.asset_amount, @@ -290,7 +291,7 @@ app.post( res.send(issuances[txid] ? issuances[txid] : { asset }); } catch (e) { - l.error("asset issuance failed", e.message, e.stack); + err("asset issuance failed", e.message, e.stack); res.status(500).send(e.message); } }) @@ -307,7 +308,7 @@ app.post( } }); - l.info("registering", asset, account.contract); + l("registering", asset, account.contract); try { const { data: result } = await axios.post( @@ -317,10 +318,10 @@ app.post( contract: account.contract } ); - l.info("register asset result", req.user.username, result); + l("register asset result", req.user.username, result); res.send(result); } catch (e) { - l.error("asset registration failed", e.message); + err("asset registration failed", e.message); res.status(500).send(e.message); } }) @@ -408,7 +409,7 @@ app.post( amount: -amount, account_id: account.id, user_id: user.id, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed: true, hash: `Loaded Faucet - ${a2.ticker}`, @@ -420,17 +421,17 @@ app.post( payment = payment.get({ plain: true }); payment.account = account.get({ plain: true }); - l.info("sent internal", user.username, -payment.amount); + l("sent internal", user.username, -payment.amount); emit(user.username, "payment", payment); emit(user.username, "account", account); emit(user.username, "user", user); - l.info("loaded faucet", asset, amount); + l("loaded faucet", asset, amount); res.end(); }); } catch (e) { - l.error("problem loading faucet", user.username, e.message); + err("problem loading faucet", user.username, e.message); return res.status(500).send(e.message); } }) diff --git a/routes/bitcoin/broadcast.js b/routes/bitcoin/broadcast.js index 157d60a4..4eb16d3d 100644 --- a/routes/bitcoin/broadcast.js +++ b/routes/bitcoin/broadcast.js @@ -1,3 +1,4 @@ +import { rates } from "../../lib/store.js"; export default async (req, res) => { try { const { user } = req; @@ -20,7 +21,7 @@ export default async (req, res) => { tip: 0, account_id: account.id, user_id: user.id, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed: true, received: false, diff --git a/routes/bitcoin/fee.js b/routes/bitcoin/fee.js index 8efb59f8..35ca4e3d 100644 --- a/routes/bitcoin/fee.js +++ b/routes/bitcoin/fee.js @@ -61,7 +61,7 @@ export default async (req, res) => { res.send({ feeRate, tx }); } catch (e) { - l.error("bitcoin fee estimation error", e); + err("bitcoin fee estimation error", e); return res.status(500).send(e.message); } }; diff --git a/routes/bitcoin/receive.js b/routes/bitcoin/receive.js index 65e96883..1d12bd9b 100644 --- a/routes/bitcoin/receive.js +++ b/routes/bitcoin/receive.js @@ -1,3 +1,4 @@ +import { rates } from "../../lib/store.js"; import { notify } from "../lib/notifications.js"; import { callWebhook } from "../lib/webhooks.js"; import reverse from 'buffer-reverse'; @@ -77,7 +78,7 @@ zmqRawTx.on("message", async (topic, message, sequence) => { const currency = invoice ? invoice.currency : user.currency; const rate = invoice ? invoice.rate - : app.get("rates")[user.currency]; + : rates[user.currency]; const tip = invoice ? invoice.tip : 0; const memo = invoice ? invoice.memo : ""; @@ -139,7 +140,7 @@ zmqRawTx.on("message", async (topic, message, sequence) => { emit(user.username, "account", account); emit(user.username, "payment", payment); - l.info("bitcoin detected", user.username, value); + l("bitcoin detected", user.username, value); notify(user, `${value} SAT payment detected`); callWebhook(invoice, payment); }); @@ -220,13 +221,13 @@ setInterval(async () => { emit(user.username, "account", account); emit(user.username, "payment", p); - l.info("bitcoin confirmed", user.username, p.amount, p.tip); + l("bitcoin confirmed", user.username, p.amount, p.tip); notify(user, `${total} SAT payment confirmed`); callWebhook(p.invoice, p); let c = convert[address]; if (address && c) { - l.info( + l( "bitcoin detected to conversion address", address, c.address, @@ -242,7 +243,7 @@ setInterval(async () => { }); } } else { - l.warn("couldn't find bitcoin payment", hash); + warn("couldn't find bitcoin payment", hash); } } @@ -250,7 +251,7 @@ setInterval(async () => { }); } } catch (e) { - l.error( + err( "problem processing queued bitcoin transaction", e.message, e.stack diff --git a/routes/bitcoin/send.js b/routes/bitcoin/send.js index d8406075..6b991519 100644 --- a/routes/bitcoin/send.js +++ b/routes/bitcoin/send.js @@ -1,3 +1,5 @@ +import { rates } from "../../lib/store.js"; +import { addresses } from "../../lib/store.js"; import config from "../../config/index.js"; const btc = config.liquid.btcasset; import { @@ -74,10 +76,10 @@ export default async (req, res) => { } if (total > account.balance) { - l.error("amount exceeds balance", amount, fee, account.balance); + err("amount exceeds balance", amount, fee, account.balance); throw new Error("low balance"); } else if (total + conversionFee > account.balance) { - l.error( + err( "total (after conversion fee) exceeds balance", amount, fee, @@ -121,7 +123,7 @@ export default async (req, res) => { memo: "Bitcoin conversion fee", account_id: receiverAccount.id, user_id: receiverAccount.user_id, - rate: app.get("rates")[receiverAccount.user.currency], + rate: rates[receiverAccount.user.currency], currency: receiverAccount.user.currency, confirmed: true, received: true, @@ -139,7 +141,7 @@ export default async (req, res) => { memo, account_id: account.id, user_id: user.id, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, address, confirmed: true, @@ -164,13 +166,13 @@ export default async (req, res) => { res.send(payment); payments.push(params.hash); - l.info("sent bitcoin", user.username, total); + l("sent bitcoin", user.username, total); }); } catch (e) { if (e.message.includes("Insufficient")) e.message = "The coinos server hot wallet has insufficient funds to complete the payment, try again later"; - l.error("error sending bitcoin", e.message); + err("error sending bitcoin", e.message); console.log(e); return res.status(500).send(e.message); } diff --git a/routes/bitcoin/sweep.js b/routes/bitcoin/sweep.js index 6c0ca580..eecfebe4 100644 --- a/routes/bitcoin/sweep.js +++ b/routes/bitcoin/sweep.js @@ -16,7 +16,7 @@ export default async (req, res) => { let utxos; if (!feeRate) feeRate = (await bc.estimateSmartFee(6)).feerate * SATS; feeRate = Math.round(feeRate / 1000); - l.info("sweeping", req.user.username, from, amount, feeRate); + l("sweeping", req.user.username, from, amount, feeRate); try { let { @@ -32,7 +32,7 @@ export default async (req, res) => { ({ data: utxos } = await axios.get(`${api}/address/${from}/utxo`)); console.log("got utxos", utxos); } catch (e) { - l.error("problem fetching utxos", e.message); + err("problem fetching utxos", e.message); } let targets = [ @@ -47,7 +47,7 @@ export default async (req, res) => { if (balance === amount) { delete targets[0].value; ({ inputs, outputs, fee } = split(utxos, targets, feeRate)); - l.info("split", inputs, outputs, fee); + l("split", inputs, outputs, fee); } if (!inputs || !outputs) @@ -82,6 +82,6 @@ export default async (req, res) => { if (balance !== amount) total = 0; res.send({ feeRate, psbt, total }); } catch (e) { - l.error("problem getting address stats", from, e.message); + err("problem getting address stats", from, e.message); } }; diff --git a/routes/funding.js b/routes/funding.js index 9d305010..692fe2f8 100644 --- a/routes/funding.js +++ b/routes/funding.js @@ -22,7 +22,7 @@ app.post( }; mailgun.messages().send(data); - l.info("id uploaded", user.username); + l("id uploaded", user.username); res.end(); }) @@ -37,7 +37,7 @@ app.post( else user.verified = "proof"; await user.save(); emit(user.username, "user", user); - l.info("id proof uploaded", user.username); + l("id proof uploaded", user.username); res.end(); }) @@ -77,7 +77,7 @@ app.post( res.send(deposit); } catch (e) { - l.error("funding error", e.message); + err("funding error", e.message); res.status(500).send("Funding request failed"); } }) @@ -103,7 +103,7 @@ app.post( res.end(); } catch (e) { - l.error("withdrawal error", e.message); + err("withdrawaerr", e.message); res.status(500).send("Withdrawal request failed"); } }) diff --git a/routes/info.js b/routes/info.js index 537cdc44..2da1807c 100644 --- a/routes/info.js +++ b/routes/info.js @@ -35,16 +35,16 @@ app.get("/balances", async (req, res, next) => { let lnchannel; let lnwallet; - let lninfo; + let l; if (config.lna) { if (config.lna.clightning) { const funds = await lna.listfunds(); - lninfo = await lna.getinfo(); + l = await lna.getinfo(); lnchannel = parseInt(funds.channels.reduce((a, b) => a + b.channel_sat, 0)); lnwallet = parseInt(funds.outputs.reduce((a, b) => a + b.value, 0)); } else { - lninfo = await lnp.getInfo({}); + l = await lnp.getInfo({}); lnchannel = parseInt((await lnp.channelBalance({}).balance)); lnwallet = parseInt((await lnp.walletBalance({}).total_balance)); } diff --git a/routes/invoices.js b/routes/invoices.js index a65ff7ba..d4a003be 100644 --- a/routes/invoices.js +++ b/routes/invoices.js @@ -1,3 +1,5 @@ +import { rates } from "../lib/store.js"; +import { addresses } from "../lib/store.js"; import app from "../app.js"; import { optionalAuth } from "../lib/passport.js"; import { Op } from "@sequelize/core"; @@ -18,7 +20,7 @@ app.get("/invoice", async (req, res, next) => { res.send(invoice); } catch (e) { - l.error("couldn't find invoice", e); + err("couldn't find invoice", e); } }); @@ -36,7 +38,7 @@ app.post("/invoice", optionalAuth, async (req, res, next) => { throw new Error("tip amount out of range"); if (liquidAddress) { - l.info("conversion request for", liquidAddress, invoice.text); + l("conversion request for", liquidAddress, invoice.text); convert[invoice.text] = { address: liquidAddress, tx }; } @@ -50,7 +52,7 @@ app.post("/invoice", optionalAuth, async (req, res, next) => { } if (!user) throw new Error("user not provided"); if (!invoice.currency) invoice.currency = user.currency; - if (!invoice.rate) invoice.rate = app.get("rates")[invoice.currency]; + if (!invoice.rate) invoice.rate = rates[invoice.currency]; if (invoice.tip > invoice.amount || invoice.tip > 1000000) throw new Error("tip is too large"); if (invoice.tip < 0 || invoice.amount < 0) @@ -58,7 +60,7 @@ app.post("/invoice", optionalAuth, async (req, res, next) => { invoice.user_id = user.id; invoice.account_id = user.account_id; - l.info( + l( "creating invoice", user.username, invoice.network, @@ -93,7 +95,7 @@ app.post("/invoice", optionalAuth, async (req, res, next) => { res.send(invoice); } catch (e) { - l.error(e.message, e.stack); + err(e.message, e.stack); res.status(500).send(`Problem during invoice creation: ${e.message}`); } }); diff --git a/routes/lightning/channel.js b/routes/lightning/channel.js index 168f55ab..4dbcfd20 100644 --- a/routes/lightning/channel.js +++ b/routes/lightning/channel.js @@ -4,7 +4,7 @@ export default async (req, res) => { const { params } = req.body; const [pubkey, host] = params.uri.split("@"); - l.info("connecting to peer", req.user.username, pubkey, host); + l("connecting to peer", req.user.username, pubkey, host); let result; try { result = await lnp.connectPeer({ @@ -13,7 +13,7 @@ export default async (req, res) => { }); } catch (e) { if (!e.message.includes("already connected")) { - l.error("problem connecting to peer", e.message); + err("problem connecting to peer", e.message); return res.status(500).send(e.message); } } @@ -23,7 +23,7 @@ export default async (req, res) => { try { remoteid = (await lnp.getInfo({})).identity_pubkey; } catch (e) { - l.error("problem getting lightning node info", e.message); + err("problem getting lightning node info", e.message); return res.status(500).send(e.message); } @@ -33,7 +33,7 @@ export default async (req, res) => { let response = await axios.get(url); res.send(response.data); } catch (e) { - l.error("problem sending channel request", e.message); + err("problem sending channel request", e.message); return res.status(500).send({ status: "ERROR", reason: e.message }); } }; diff --git a/routes/lightning/channelRequest.js b/routes/lightning/channelRequest.js index 3aecaa61..11c76abf 100644 --- a/routes/lightning/channelRequest.js +++ b/routes/lightning/channelRequest.js @@ -17,7 +17,7 @@ export default async (req, res) => { res.send(result); } catch (e) { - l.error("problem generating channel request", e.message); + err("problem generating channel request", e.message); res.status(500).send(e.message); } }; diff --git a/routes/lightning/invoice.js b/routes/lightning/invoice.js index 7d8a10cc..f744dd22 100644 --- a/routes/lightning/invoice.js +++ b/routes/lightning/invoice.js @@ -18,7 +18,7 @@ export default async (req, res) => { res.send({ text: invoice.payment_request }); } } catch (e) { - l.error("problem creating invoice", e.message, e.stack); + err("problem creating invoice", e.message, e.stack); res.status(500).send(e.message); } }; diff --git a/routes/lightning/receive.js b/routes/lightning/receive.js index 405eed38..e35d91ec 100644 --- a/routes/lightning/receive.js +++ b/routes/lightning/receive.js @@ -4,7 +4,7 @@ import { computeConversionFee } from './conversionFee.js'; import { sendLiquid } from "../liquid/send.js"; const handlePayment = async (msg) => { - l.info("incoming lightning payment", msg.value, msg.payment_request, msg.settled); + l("incoming lightning payment", msg.value, msg.payment_request, msg.settled); if (!msg.settled) return; let account, total, user; @@ -15,7 +15,7 @@ const handlePayment = async (msg) => { }); if (!invoice) - return l.warn("received lightning with no invoice", msg.payment_request); + return warn("received lightning with no invoice", msg.payment_request); try { await db.transaction(async (transaction) => { @@ -85,7 +85,7 @@ const handlePayment = async (msg) => { emit(user.username, "account", payment.account); notify(user, `Received ${total} SAT`); - l.info( + l( "lightning payment received", user.username, payment.amount, @@ -95,7 +95,7 @@ const handlePayment = async (msg) => { let c = convert[msg.payment_request]; if (msg.payment_request && c) { - l.info( + l( "lightning detected for conversion request", msg.payment_request, c.address, @@ -112,11 +112,11 @@ const handlePayment = async (msg) => { limit: total, }); } catch (e) { - l.error("problem sending liquid payment", e.message, e.stack); + err("problem sending liquid payment", e.message, e.stack); } } } catch (e) { - l.error("problem receiving lightning payment", e.message); + err("problem receiving lightning payment", e.message); } }; diff --git a/routes/lightning/send.js b/routes/lightning/send.js index 807b4bb8..a482091a 100644 --- a/routes/lightning/send.js +++ b/routes/lightning/send.js @@ -5,7 +5,7 @@ export default async (req, res) => { try { res.send(await send(amount, memo, payreq, user)); } catch (e) { - l.error( + err( "problem sending lightning payment", user.username, payreq, diff --git a/routes/liquid/broadcast.js b/routes/liquid/broadcast.js index 2562effc..1a44cd2b 100644 --- a/routes/liquid/broadcast.js +++ b/routes/liquid/broadcast.js @@ -1,3 +1,4 @@ +import { rates } from "../../lib/store.js"; export default async (req, res) => { try { const { user } = req; @@ -21,7 +22,7 @@ export default async (req, res) => { tip: 0, account_id: account.id, user_id: user.id, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed: true, received: false, @@ -46,7 +47,7 @@ export default async (req, res) => { res.send(hash); } } catch (e) { - l.error("problem broadcasting liquid transaction", e); + err("problem broadcasting liquid transaction", e); res.status(500).send(e.message); } }; diff --git a/routes/liquid/fee.js b/routes/liquid/fee.js index 0a2c330a..9d8a5bad 100644 --- a/routes/liquid/fee.js +++ b/routes/liquid/fee.js @@ -59,7 +59,7 @@ liquidTx = async ({ address, asset, amount, feeRate, replaceable, user }) => { replaceable ); - l.info("funding tx for fee estimate", tx); + l("funding tx for fee estimate", tx); tx = await node.fundRawTransaction(tx, params); @@ -68,7 +68,7 @@ liquidTx = async ({ address, asset, amount, feeRate, replaceable, user }) => { decoded = await node.decodeRawTransaction(signed.hex); feeRate = Math.round((tx.fee * SATS * 1000) / decoded.vsize); - l.info("estimated", asset, feeRate); + l("estimated", asset, feeRate); return { feeRate, tx }; }; @@ -78,7 +78,7 @@ export default async (req, res) => { let tx = await liquidTx({ ...req.body, user: req.user }); res.send(tx); } catch (e) { - l.error("error estimating liquid fee", e.message, e.stack); + err("error estimating liquid fee", e.message, e.stack); return res.status(500).send(e.message); } }; diff --git a/routes/liquid/receive.js b/routes/liquid/receive.js index 8891292e..380fe4f4 100644 --- a/routes/liquid/receive.js +++ b/routes/liquid/receive.js @@ -1,15 +1,14 @@ +import { rates } from "../../lib/store.js"; +import { addresses } from "../../lib/store.js"; import { sendLiquid } from "./send.js"; -import { notify } from "../lib/notifications.js"; -import { callWebhook } from "../lib/webhooks.js"; +import { notify } from "../../lib/notifications.js"; +import { callWebhook } from "../../lib/webhooks.js"; import reverse from 'buffer-reverse'; import zmq from 'zeromq/v5-compat'; import { Op } from '@sequelize/core'; import { fromBase58 } from 'bip32'; import bitcoin from 'bitcoinjs-lib'; // import { Block, networks, Transaction } from 'liquidjs-lib'; -import wretch from 'wretch'; -import fetch from 'node-fetch'; -wretch().polyfills({ fetch }); const network = networks[ @@ -26,7 +25,7 @@ const getAccount = async (params, transaction) => { }); if (account) { - l.info("found account", params, account.asset, account.id); + l("found account", params, account.asset, account.id); return account; } @@ -68,7 +67,7 @@ const getAccount = async (params, transaction) => { }); if (existing) { - l.info("existing", existing.id); + l("existing", existing.id); ({ domain, ticker, precision, name } = existing); } } @@ -105,7 +104,7 @@ zmqRawTx.on("message", async (topic, message, sequence) => { tx = await lq.decodeRawTransaction(unblinded.hex); blinded = await lq.decodeRawTransaction(hex); } catch (e) { - return l.error("problem decoding liquid tx", e.message); + return err("problem decoding liquid tx", e.message); } Promise.all( @@ -173,7 +172,7 @@ zmqRawTx.on("message", async (topic, message, sequence) => { const currency = invoice ? invoice.currency : user.currency; const rate = invoice ? invoice.rate - : app.get("rates")[user.currency]; + : rates[user.currency]; const tip = invoice ? invoice.tip : 0; const memo = invoice ? invoice.memo : ""; @@ -201,13 +200,13 @@ zmqRawTx.on("message", async (topic, message, sequence) => { emit(user.username, "payment", payment); emit(user.username, "account", payment.account); - l.info("liquid detected", address, user.username, asset, value); + l("liquid detected", address, user.username, asset, value); notify(user, `${value} SAT payment detected`); callWebhook(invoice, payment); }); } } catch (e) { - l.error("Problem processing transaction", e.message, e.stack); + err("Problem processing transaction", e.message, e.stack); } }) ); @@ -357,7 +356,7 @@ setInterval(async () => { emit(user.username, "account", p.account); emit(user.username, "payment", p); - l.info( + l( "liquid confirmed", user.username, p.account.asset, @@ -368,7 +367,7 @@ setInterval(async () => { notify(user, `${total} SAT payment confirmed`); callWebhook(p.invoice, p); } else { - l.warn("couldn't find liquid payment", hash); + warn("couldn't find liquid payment", hash); } delete queue[hash]; @@ -376,7 +375,7 @@ setInterval(async () => { let c = convert[address]; if (address && c && p.account.asset === network.assetHash) { - l.info( + l( "liquid detected for conversion request", address, c.address, @@ -394,6 +393,6 @@ setInterval(async () => { } } } catch (e) { - l.error("problem processing queued liquid transaction", e.message, e.stack); + err("problem processing queued liquid transaction", e.message, e.stack); } }, 1000); diff --git a/routes/liquid/send.js b/routes/liquid/send.js index 9529a040..674b93f2 100644 --- a/routes/liquid/send.js +++ b/routes/liquid/send.js @@ -1,3 +1,5 @@ +import { rates } from "../../lib/store.js"; +import { addresses } from "../../lib/store.js"; import config from "../../config/index.js"; const btc = config.liquid.btcasset; const lcad = config.liquid.cadasset; @@ -9,7 +11,7 @@ import { export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => { try { - l.info("sending liquid", amount, address); + l("sending liquid", amount, address); if (!tx) { ({ tx } = await liquidTx({ address, @@ -96,7 +98,7 @@ export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit throw new Error("Tx amount exceeds authorized amount"); if (asset !== btc || total) { - l.info("creating liquid payment", user.username, asset, total, fee); + l("creating liquid payment", user.username, asset, total, fee); let account = await db.Account.findOne({ where: { @@ -126,7 +128,7 @@ export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit if (asset !== btc) conversionFee = 0; if (total > account.balance) { - l.warn("amount exceeds balance", { + warn("amount exceeds balance", { total, fee, balance: account.balance @@ -137,7 +139,7 @@ export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }, have ${account.balance}` ); } else if (total + conversionFee > account.balance) { - l.warn("amount plus conversion fee exceeds balance", { + warn("amount plus conversion fee exceeds balance", { total, fee, conversionFee, @@ -182,7 +184,7 @@ export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit memo: "Liquid conversion fee", account_id: receiverAccount.id, user_id: receiverAccount.user_id, - rate: app.get("rates")[receiverAccount.user.currency], + rate: rates[receiverAccount.user.currency], currency: receiverAccount.user.currency, confirmed: true, received: true, @@ -200,7 +202,7 @@ export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit fee, memo, user_id: user.id, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, address, confirmed: true, @@ -241,11 +243,11 @@ export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit await lq.walletPassphrase(config.liquid.walletpass, 300); let txid = await lq.sendRawTransaction(signed.hex); - l.info("sent liquid tx", txid, address); + l("sent liquid tx", txid, address); return main; } catch (e) { - l.error("problem sending liquid", e.message); + err("problem sending liquid", e.message); } }; @@ -255,7 +257,7 @@ export default async (req, res) => { try { res.send(await sendLiquid({ ...req.body, user })); } catch (e) { - l.error("problem sending liquid", user.username, e.message); + err("problem sending liquid", user.username, e.message); return res.status(500).send(e); } }; diff --git a/routes/lnurl.js b/routes/lnurl.js index 7687b248..82420734 100644 --- a/routes/lnurl.js +++ b/routes/lnurl.js @@ -1,3 +1,4 @@ +import { rates } from "../lib/store.js"; import app from "../app.js"; import config from "../config/index.js"; import axios from "axios"; @@ -34,7 +35,7 @@ app.get("/url", async (req, res, next) => { throw new Error("code not found"); } } catch (e) { - l.error("couldn't find url", e.message); + err("couldn't find url", e.message); } }); @@ -51,7 +52,7 @@ app.get("/withdraw", auth, async (req, res, next) => { res.send(result); } catch (e) { - l.error("problem generating withdrawl url", e.message); + err("problem generating withdrawl url", e.message); res.status(500).send(e.message); } }); @@ -68,7 +69,7 @@ app.post("/code", async (req, res, next) => { res.send(code); } catch (e) { - l.error(e.errors); + err(e.errors); res.status(500).send(e.message); } }); @@ -86,7 +87,7 @@ app.post("/withdraw", auth, async (req, res, next) => { await db.Invoice.create({ user_id: user.id, text: pr, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, amount: value, tip: 0, @@ -97,7 +98,7 @@ app.post("/withdraw", auth, async (req, res, next) => { result = (await axios.get(url)).data; res.send(result); } catch (e) { - l.error("failed to withdraw", e.message); + err("failed to withdraw", e.message); res.status(500).send(e.message); } }); @@ -128,13 +129,13 @@ app.get("/lnurlp/:username", async (req, res, next) => { }); recipients[result.secret] = user; - l.info("recipient", user.username, result.secret); + l("recipient", user.username, result.secret); result = await axios.get(result.url); res.send(result.data); } catch (e) { - l.error("problem generating payment url", e.message); + err("problem generating payment url", e.message); res.status(500).send(e.message); } }); @@ -160,10 +161,10 @@ app.get("/pay/:username", async (req, res, next) => { }); recipients[result.secret] = user; - l.info("recipient", user.username, result.secret); + l("recipient", user.username, result.secret); res.send(result); } catch (e) { - l.error("problem generating payment url", e.message); + err("problem generating payment url", e.message); res.status(500).send(e.message); } }); @@ -206,7 +207,7 @@ app.post("/pay", auth, async (req, res, next) => { res.send(await send(amount, "", data.pr, user)); } } catch (e) { - l.error("failed to send payment", e.message); + err("failed to send payment", e.message); res.status(500).send(e.message); } }); @@ -221,7 +222,7 @@ app.get("/login", optionalAuth, async (req, res, next) => { res.send(result); } catch (e) { - l.error("problem generating login url", e.message); + err("problem generating login url", e.message); res.status(500).send(e.message); } }); @@ -255,7 +256,7 @@ app.get("/decode", async (req, res, next) => { const { data: params } = await axios.get(url); res.send(params); } catch (e) { - l.error("problem decoding lnurl", e.message); + err("problem decoding lnurl", e.message); res.status(500).send(e.message); } }); @@ -270,16 +271,16 @@ lnurlServer.on("payRequest:action:processed", async function(event) { let i = await db.Invoice.create({ user_id: recipient.id, text: invoice, - rate: app.get("rates")[recipient.currency], + rate: rates[recipient.currency], currency: recipient.currency, amount: payreq.satoshis, tip: 0, network: "lightning" }); - l.info("invoice created", i.text, i.amount); + l("invoice created", i.text, i.amount); } catch (e) { - l.error("problem finding lnurl invoice", e.message); + err("problem finding lnurl invoice", e.message); } }); @@ -421,7 +422,7 @@ lnurlServer.bindToHook( memo: "Bitcoin conversion fee", account_id: receiverAccount.id, user_id: receiverAccount.user_id, - rate: app.get("rates")[receiverAccount.user.currency], + rate: rates[receiverAccount.user.currency], currency: receiverAccount.user.currency, confirmed: true, received: true, @@ -438,7 +439,7 @@ lnurlServer.bindToHook( account_id: account.id, user_id: user.id, hash: pr, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed: true, network: "lightning", @@ -457,7 +458,7 @@ lnurlServer.bindToHook( let p = payments.find(p => p.payment_request === pr); if (p) { - l.info("found payment", pr); + l("found payment", pr); payment.fee = p.fee; await account.decrement({ balance: p.fee }, { transaction }); await account.reload({ transaction }); @@ -467,10 +468,10 @@ lnurlServer.bindToHook( emit(user.username, "account", account); emit(user.username, "payment", payment); } else { - l.warn("payment not found, fee not set", pr); + warn("payment not found, fee not set", pr); } } catch (e) { - l.error("problem trying to get ln withdrawal payment", e); + err("problem trying to get ln withdrawal payment", e); } }, 1000); @@ -487,14 +488,14 @@ lnurlServer.bindToHook( emit(user.username, "payment", p); }); } catch (e) { - l.error("failed to process withdrawal", e.message); + err("failed to process withdrawal", e.message); return next(e); } } if (next) next(req, res); } catch (e) { - l.error("unhandled lnurl error", e.message); + err("unhandled lnurerr", e.message); } } ); @@ -524,11 +525,11 @@ lnurlServer.bindToHook("login", async key => { }); if (created) { - l.info("added key", username, k); + l("added key", username, k); emit(username, "key", k); } } else { - l.info("user not found"); + l("user not found"); user = await register({ username: key.substr(0, 8), password: key @@ -544,6 +545,6 @@ lnurlServer.bindToHook("login", async key => { ws.send(JSON.stringify({ type: "token", data: { token, key } })); } } catch (e) { - l.error("problem with login hook", e.message); + err("problem with login hook", e.message); } }); diff --git a/routes/payments.js b/routes/payments.js index 6861d2a3..f947350b 100644 --- a/routes/payments.js +++ b/routes/payments.js @@ -45,7 +45,7 @@ app.post("/sendToTokenHolders", auth, async (req, res, next) => { app.get("/except", adminAuth, (req, res) => { let s = fs.createWriteStream("exceptions", { flags: "a" }); unaccounted.map(tx => s.write(tx.txid + "\n")); - l.info("updated exceptions"); + l("updated exceptions"); res.send("updated exceptions"); }); @@ -55,7 +55,7 @@ if (config.lna) { app.post("/lightning/invoice", lnRoutes.invoice); app.post("/lightning/query", auth, lnRoutes.query); app.post("/lightning/send", auth, lnRoutes.send); - import("./lightning/receive"); + import("./lightning/receive.js"); } if (config.bitcoin) { @@ -64,7 +64,7 @@ if (config.bitcoin) { app.post("/bitcoin/sweep", auth, btcRoutes.sweep); app.post("/bitcoin/fee", auth, btcRoutes.fee); app.post("/bitcoin/send", auth, btcRoutes.send); - import("./bitcoin/receive"); + import("./bitcoin/receive.js"); setTimeout(async () => { try { @@ -84,7 +84,7 @@ if (config.liquid) { // app.post("/liquid/fee", auth, lqRoutes.fee); app.post("/liquid/send", auth, lqRoutes.send); // app.post("/taxi", auth, lqRoutes.taxi); - import("./liquid/receive"); + import("./liquid/receive.js"); setTimeout(async () => { try { @@ -93,7 +93,7 @@ if (config.liquid) { const parts = hdkeypath.split("/"); app.set("lqAddressIndex", parts[parts.length - 1].slice(0, -1)); } catch (e) { - l.warn("Problem getting liquid address index", e.message); + warn("Problem getting liquid address index", e.message); } }, 50); } diff --git a/routes/send.js b/routes/send.js index 7cc403e1..b0f8accb 100644 --- a/routes/send.js +++ b/routes/send.js @@ -1,3 +1,4 @@ +import { rates } from "../lib/store.js"; import { callWebhook } from "../lib/webhooks.js"; import axios from "axios"; import { v4 as uuidv4 } from "uuid"; @@ -60,7 +61,7 @@ export default async (req, res, next) => { account_id: account.id, memo, user_id: user.id, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed: true, hash: `#${uuidv4().substr(0, 6)} ${ @@ -70,7 +71,7 @@ export default async (req, res, next) => { }; if (!username) { - l.info("creating redeemable payment"); + l("creating redeemable payment"); params.redeemcode = uuidv4(); params.hash = `${req.get("origin")}/redeem/${params.redeemcode}`; } @@ -80,7 +81,7 @@ export default async (req, res, next) => { payment = payment.get({ plain: true }); payment.account = account.get({ plain: true }); - l.info("sent internal", user.username, -payment.amount); + l("sent internal", user.username, -payment.amount); emit(user.username, "payment", payment); emit(user.username, "account", account); @@ -165,7 +166,7 @@ export default async (req, res, next) => { amount, account_id: a2.id, user_id: recipient.id, - rate: app.get("rates")[recipient.currency] * spread, + rate: rates[recipient.currency] * spread, currency: recipient.currency, confirmed: true, hash: `#${uuidv4().substr(0, 6)} Payment from ${user.username}`, @@ -179,7 +180,7 @@ export default async (req, res, next) => { let c = convert[invoice.text]; if (c) { - l.info( + l( "internal payment detected for conversion", invoice.text, c.address, @@ -204,7 +205,7 @@ export default async (req, res, next) => { emit(recipient.username, "payment", p2); emit(recipient.username, "account", p2.account); - l.info("received internal", recipient.username, amount); + l("received internal", recipient.username, amount); notify(recipient, `Received ${amount} ${a2.ticker} sats`); callWebhook(invoice, p2); } @@ -212,7 +213,7 @@ export default async (req, res, next) => { }); } catch (e) { console.log(e); - l.error("problem sending internal payment", user.username, e.message); + err("problem sending internal payment", user.username, e.message); return res.status(500).send(e.message); } }; diff --git a/routes/swaps.js b/routes/swaps.js index f8b37cd0..f1bdcbc8 100644 --- a/routes/swaps.js +++ b/routes/swaps.js @@ -1,9 +1,11 @@ +import { rates } from "../lib/store.js"; import axios from 'axios'; import crypto from 'crypto'; import fs from 'fs'; -import getAccount from '../lib/account'; +import getAccount from '../lib/account.js'; import { Op, col } from '@sequelize/core'; import { v4 as uuidv4 } from 'uuid'; +import { rates } from "../lib/store.js"; const shallow = a => { let b = {}; @@ -48,7 +50,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => { if (v1 > a1acc.balance) throw new Error(`Insufficient funds, ${v1} ${a1acc.balance}`); - l.info( + l( `placing order ${v1} ${a1.substr(0, 6)} for ${v2} ${a2.substr(0, 6)}`, user.username ); @@ -63,7 +65,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => { account_id: a1acc.id, user_id: user.id, currency: user.currency, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], confirmed: true, received: false, network: "COINOS" @@ -132,7 +134,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => { account_id: a1acc.id, user_id: user.id, currency: user.currency, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], confirmed: true, received: true, network: "COINOS" @@ -157,7 +159,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => { account_id: btc.id, user_id: order.user_id, currency: order.user.currency, - rate: app.get("rates")[order.user.currency], + rate: rates[order.user.currency], confirmed: true, received: true, network: "COINOS" @@ -196,7 +198,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => { account_id: a2acc.id, user_id: user.id, currency: user.currency, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], confirmed: true, received: true, network: "COINOS" @@ -217,7 +219,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => { account_id: order.a2_id, user_id: order.user_id, currency: order.user.currency, - rate: app.get("rates")[order.user.currency], + rate: rates[order.user.currency], confirmed: true, received: true, network: "COINOS" @@ -290,7 +292,7 @@ const cancel = async (user, id) => { account_id: account.id, user_id: user.id, currency: user.currency, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], confirmed: true, received: true, network: "COINOS" @@ -311,7 +313,7 @@ const cancel = async (user, id) => { account_id: btc.id, user_id: user.id, currency: user.currency, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], confirmed: true, received: true, network: "COINOS" @@ -353,7 +355,7 @@ app.post( await swap(user, req.body); res.end(); } catch (e) { - l.error(req.user.username, e.message); + err(req.user.username, e.message); res.status(500).send(e.message); } }) @@ -401,7 +403,7 @@ if (config.maker) { debug('setup maker account...') config.maker.map(({ amount, c1, c2, currency, askMultiplier, bidMultiplier }) => { setInterval(async () => { - if (!app.get("rates")) return; + if (!rates) return; const user = await db.User.findOne({ where: { @@ -443,8 +445,8 @@ if (config.maker) { v2: Math.round( amount * SATS * - (((app.get("ask") * app.get("rates")[currency]) / - app.get("rates")["USD"]) * + (((app.get("ask") * rates[currency]) / + rates["USD"]) * askMultiplier) ) }; @@ -494,7 +496,7 @@ if (config.maker) { try { await swap(user, params); } catch (e) { - l.warn("Failed to make ask", e.message); + warn("Failed to make ask", e.message); } } @@ -526,8 +528,8 @@ if (config.maker) { v1: Math.round( amount * SATS * - ((app.get("bid") * app.get("rates")[currency]) / - app.get("rates")["USD"]) * + ((app.get("bid") * rates[currency]) / + rates["USD"]) * bidMultiplier ), v2: amount * SATS @@ -583,7 +585,7 @@ if (config.maker) { try { await swap(user, params); } catch (e) { - l.warn("Failed to make bid", e.message); + warn("Failed to make bid", e.message); } } }); diff --git a/routes/users.js b/routes/users.js index f0fa8c47..d9ab92d5 100644 --- a/routes/users.js +++ b/routes/users.js @@ -95,7 +95,7 @@ app.post( await user.save(); emit(user.username, "user", user); emit(user.username, "otpsecret", user.otpsecret); - l.info("disabled 2fa", user.username); + l("disabled 2fa", user.username); res.send({}); }) @@ -124,10 +124,10 @@ app.post( return res.status(500).send("Invalid token"); } } catch (e) { - l.error("error setting up 2fa", e); + err("error setting up 2fa", e); } - l.info("enabled 2fa", user.username); + l("enabled 2fa", user.username); res.send({}); }) @@ -169,12 +169,12 @@ app.post( let token; if (user.username !== username && exists) { - l.error("username taken", username, user.username, exists.username); + err("username taken", username, user.username, exists.username); return res.status(500).send("Username taken"); } else { sockets[username] = sockets[user.username]; if (user.username !== username) - l.info("changing username", user.username, username); + l("changing username", user.username, username); user.username = username; token = jwt.sign({ username }, config.jwt); @@ -203,7 +203,7 @@ app.post( emit(user.username, "user", user); res.send({ user, token }); } catch (e) { - l.error("error updating user", e.message); + err("error updating user", e.message); } }) @@ -327,7 +327,7 @@ let login = async (req, res) => { const response = await axios.get(url); res.send(response.data); } catch (e) { - l.error("problem calling lnurl login", e.message); + err("problem calling lnurl login", e.message); res.status(500).send(e.message); } @@ -343,7 +343,7 @@ let login = async (req, res) => { (user.password && !(await bcrypt.compare(req.body.password, user.password))) ) { - l.warn("invalid username or password attempt", req.body.username); + warn("invalid username or password attempt", req.body.username); return res.status(401).end(); } @@ -355,7 +355,7 @@ let login = async (req, res) => { return res.status(401).send("2fa required"); } - l.info( + l( "login", req.body.username, req.headers["x-forwarded-for"] || req.connection.remoteAddress @@ -369,7 +369,7 @@ let login = async (req, res) => { user = pick(user, ...whitelist); res.send({ user, token }); } catch (e) { - l.error("login error", e.message, req.connection.remoteAddress); + err("login error", e.message, req.connection.remoteAddress); res.status(401).end(); } @@ -387,7 +387,7 @@ app.post( const { username } = req.user; if (username) { - l.info("logging out", username); + l("logging out", username); let i = req.user.subscriptions.findIndex( s => JSON.stringify(s) === subscription ); @@ -453,7 +453,7 @@ app.get( // async request to node to bump its internal index but don't use result lq.getNewAddress().catch(e => - l.warn("Problem bumping liquid address index", e.message) + warn("Problem bumping liquid address index", e.message) ); i = parseInt(app.get("lqAddressIndex")); @@ -466,7 +466,7 @@ app.get( i = parseInt(parts[parts.length - 1].slice(0, -1)); } - l.info("liquid address index", i); + l("liquid address index", i); if (!i) throw new Error("Problem generating address"); hd = fromBase58(config.liquid.masterkey, n).derivePath(`m/0'/0'/${i}'`); @@ -572,7 +572,7 @@ app.post( res.end(); }); } catch (e) { - l.error("problem updating account", e.message); + err("problem updating account", e.message); return res.status(500).send("There was a problem updating the account"); } }) @@ -615,7 +615,7 @@ app.post( res.send(user); } catch (e) { - l.error("problem switching account", e.message); + err("problem switching account", e.message); return res.status(500).send("There was a problem switching accounts"); } }) @@ -638,7 +638,7 @@ app.post( ) subscriptions.push(subscription); req.user.subscriptions = subscriptions; - l.info("subscribing", req.user.username); + l("subscribing", req.user.username); await req.user.save(); res.sendStatus(201); }) @@ -669,7 +669,7 @@ app.post( transaction }); - l.info("redeeming", redeemcode); + l("redeeming", redeemcode); if (!source) fail("Invalid code"); if (source.redeemed) fail("Voucher has already been redeemed"); @@ -712,7 +712,7 @@ app.post( user_id: user.id, hash: "Voucher " + redeemcode, memo, - rate: app.get("rates")[user.currency], + rate: rates[user.currency], currency: user.currency, confirmed, network, @@ -734,7 +734,7 @@ app.post( }); } catch (e) { delete redeeming[redeemcode]; - l.error("problem redeeming", e.message); + err("problem redeeming", e.message); return res.status(500).send("There was a problem redeeming the voucher"); } }) |
