aboutsummaryrefslogtreecommitdiffstats
path: root/routes
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2022-09-02 14:47:08 -0700
committerAdam Soltys <[email protected]>2022-09-02 14:47:14 -0700
commit3161dd7ee95b6c7d70f8341298dd4fab84cda8b0 (patch)
tree16cd6c55d5dc481331b1e8b640d179f193e7ea13 /routes
parent7a8d64833de8873afb92982b3f5bfff59b30c542 (diff)
downloadcoinos-server-3161dd7ee95b6c7d70f8341298dd4fab84cda8b0.tar.gz
coinos-server-3161dd7ee95b6c7d70f8341298dd4fab84cda8b0.zip
es6 migration
Diffstat (limited to 'routes')
-rw-r--r--routes/admin.js37
-rw-r--r--routes/assets.js17
-rw-r--r--routes/bitcoin/broadcast.js4
-rw-r--r--routes/bitcoin/conversionFee.js7
-rw-r--r--routes/bitcoin/fee.js27
-rw-r--r--routes/bitcoin/generate.js4
-rw-r--r--routes/bitcoin/index.js13
-rw-r--r--routes/bitcoin/receive.js4
-rw-r--r--routes/bitcoin/send.js65
-rw-r--r--routes/bitcoin/sweep.js15
-rw-r--r--routes/funding.js14
-rw-r--r--routes/info.js15
-rw-r--r--routes/invoices.js184
-rw-r--r--routes/lightning/channel.js16
-rw-r--r--routes/lightning/channelRequest.js9
-rw-r--r--routes/lightning/conversionFee.js7
-rw-r--r--routes/lightning/index.js13
-rw-r--r--routes/lightning/invoice.js5
-rw-r--r--routes/lightning/query.js8
-rw-r--r--routes/lightning/receive.js3
-rw-r--r--routes/lightning/send.js11
-rw-r--r--routes/liquid/broadcast.js4
-rw-r--r--routes/liquid/conversionFee.js7
-rw-r--r--routes/liquid/fee.js20
-rw-r--r--routes/liquid/generate.js4
-rw-r--r--routes/liquid/index.js13
-rw-r--r--routes/liquid/receive.js7
-rw-r--r--routes/liquid/send.js42
-rw-r--r--routes/liquid/taxi.js14
-rw-r--r--routes/lnurl.js513
-rw-r--r--routes/payments.js202
-rw-r--r--routes/referrals.js21
-rw-r--r--routes/send.js11
-rw-r--r--routes/swaps.js36
-rw-r--r--routes/users.js90
35 files changed, 731 insertions, 731 deletions
diff --git a/routes/admin.js b/routes/admin.js
index 1be6612d..bf8a112a 100644
--- a/routes/admin.js
+++ b/routes/admin.js
@@ -1,8 +1,8 @@
import express from 'express';
var router = express.Router();
-import parseInput from '../scripts/apiParse.js';
-import Sequelize from 'sequelize';
+import * as parseInput from '../scripts/apiParse.js';
+import Sequelize from '@sequelize/core';
const Op = Sequelize.Op;
import { v4 as uuidv4 } from 'uuid';
@@ -27,7 +27,7 @@ import { v4 as uuidv4 } from 'uuid';
router.get(
"/users",
// auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {search, starts_with, contains} = req.query
var users = knex
.select('username', 'email', 'phone', 'verified', knex.raw('LEFT(createdAt,10) as created_at'))
@@ -47,7 +47,6 @@ router.get(
const found = await users
return res.send({users: found})
})
-);
/**
* @api {get} /referrals Retrieve list of referral tokens
@@ -69,7 +68,7 @@ router.get(
router.get(
"/referrals",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var referrals = knex
.select(
'token',
@@ -103,7 +102,6 @@ router.get(
var found = await referrals
return res.send({referrals: found})
})
-);
/**
* @api {get} /waiting_list Retrieve waiting_list
@@ -125,7 +123,7 @@ router.get(
router.get(
"/waiting_list",
// auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {search, starts_with, contains} = req.query
var queue = knex
@@ -149,7 +147,6 @@ router.get(
return res.send({queue: found})
})
-);
/**
* @api {get} /accounts Retrieve list of accounts
@@ -171,7 +168,7 @@ router.get(
router.get(
"/accounts",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {nonZero, search, starts_with, contains} = req.query
var accounts = knex
@@ -194,7 +191,6 @@ router.get(
return res.send({accounts: found})
})
-);
/**
* @api {get} /transactions Retrieve summary of user transactions
@@ -217,7 +213,7 @@ router.get(
router.get(
"/transactions",
// auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {type, since, search, starts_with, contains} = req.query
var transactions = knex
@@ -262,7 +258,6 @@ router.get(
return res.send({transactions: found})
})
-);
/**
* @api {get} /orders Retrieve summary of orders
@@ -285,7 +280,7 @@ router.get(
router.get(
"/orders",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {type, since, search, starts_with, contains} = req.query
var orders = knex
@@ -319,7 +314,6 @@ router.get(
var found = await orders
return res.send({orders: found})
})
-);
/**
* @api {get} /invoices Retrieve summary of invoices
@@ -342,7 +336,7 @@ router.get(
router.get(
"/invoices",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {type, since, search, starts_with, contains} = req.query
var invoices = knex
@@ -367,7 +361,6 @@ router.get(
var found = await invoices
return res.send({invoices: found})
})
-);
/**
@@ -391,7 +384,7 @@ router.get(
router.get(
"/deposits",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {type, since, search, starts_with, contains} = req.query
var deposits = knex
@@ -414,7 +407,6 @@ router.get(
var found = await deposits
return res.send({deposits: found})
})
-);
/**
* @api {get} /withdrawals Retrieve summary of withdrawals
@@ -437,7 +429,7 @@ router.get(
router.get(
"/withdrawals",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {type, since, search, starts_with, contains} = req.query
var withdrawals = knex
@@ -460,7 +452,6 @@ router.get(
var found = await withdrawals
return res.send({withdrawals: found})
})
-);
/**
* @api {get} /payments Retrieve summary of payments
@@ -483,7 +474,7 @@ router.get(
router.get(
"/payments",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {type, since, search, starts_with, contains} = req.query
var payments = knex
@@ -508,7 +499,6 @@ router.get(
var found = await payments
return res.send({payments: found})
})
-);
/**
* @api {get} /user_kyc Retrieve user kyc details
@@ -531,7 +521,7 @@ router.get(
router.get(
"/kyc_required",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
var {since, search, starts_with, contains} = req.query
var threshold = '0.2'
@@ -566,6 +556,5 @@ router.get(
return res.send({found: found})
})
-);
export default router;
diff --git a/routes/assets.js b/routes/assets.js
index 884d1c77..1da217ae 100644
--- a/routes/assets.js
+++ b/routes/assets.js
@@ -1,3 +1,5 @@
+import app from "../app.js";
+import { auth } from "../lib/passport.js";
import axios from 'axios';
import crypto from 'crypto';
import fs from 'fs';
@@ -25,7 +27,7 @@ let fetchAssets;
app.get(
"/assets",
- ah(async (req, res) => {
+ async (req, res) => {
if (app.get("assets")) {
const assets = app.get("assets");
@@ -64,12 +66,11 @@ app.get(
res.status(500).send("Problem fetching blockstream asset registry data");
}
})
-);
app.post(
"/assets",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
try {
const sha256 = crypto.createHash("sha256");
const { id: user_id } = req.user;
@@ -293,12 +294,11 @@ app.post(
res.status(500).send(e.message);
}
})
-);
app.post(
"/assets/register",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { asset } = req.body;
const account = await db.Account.findOne({
where: {
@@ -324,12 +324,11 @@ app.post(
res.status(500).send(e.message);
}
})
-);
app.post(
"/loadFaucet",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
return res.status(500).send("Faucet feature temporarily disabled");
const { user } = req;
@@ -435,12 +434,11 @@ app.post(
return res.status(500).send(e.message);
}
})
-);
app.get(
"/faucet",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
let { asset } = req.query;
let faucet = await db.Account.findOne({
where: {
@@ -458,4 +456,3 @@ app.get(
res.send(faucet);
})
-);
diff --git a/routes/bitcoin/broadcast.js b/routes/bitcoin/broadcast.js
index 5ee7d6bb..157d60a4 100644
--- a/routes/bitcoin/broadcast.js
+++ b/routes/bitcoin/broadcast.js
@@ -1,4 +1,4 @@
-export default ah(async (req, res) => {
+export default async (req, res) => {
try {
const { user } = req;
let hash = await bc.sendRawTransaction(req.body.tx);
@@ -47,4 +47,4 @@ export default ah(async (req, res) => {
} catch (e) {
res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/bitcoin/conversionFee.js b/routes/bitcoin/conversionFee.js
index fa7904b1..8a6bfce6 100644
--- a/routes/bitcoin/conversionFee.js
+++ b/routes/bitcoin/conversionFee.js
@@ -2,14 +2,11 @@
// This is in a separate file so that the same function can be used by ./send and ./receive
const conversionFeeMultiplier = 0.01;
-const conversionFeeReceiver = "coinosfees"; // account that receives the fees
+export const conversionFeeReceiver = "coinosfees"; // account that receives the fees
/**
* Returns the fee you have to pay for withdrawing 'amount' bitcoin.
*/
-function computeConversionFee(amount) {
+export function computeConversionFee(amount) {
return Math.floor(amount * conversionFeeMultiplier);
}
-
-module.exports.conversionFeeReceiver = conversionFeeReceiver;
-module.exports.computeConversionFee = computeConversionFee;
diff --git a/routes/bitcoin/fee.js b/routes/bitcoin/fee.js
index 20dc8e9a..8efb59f8 100644
--- a/routes/bitcoin/fee.js
+++ b/routes/bitcoin/fee.js
@@ -1,6 +1,6 @@
-import buildTx from '../../lib/buildtx';
+import buildTx from "../../lib/buildtx.js";
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { user } = req;
let { address, amount, feeRate, replaceable } = req.body;
let tx, fee;
@@ -9,9 +9,9 @@ export default ah(async (req, res) => {
try {
let psbt = await buildTx({ address, amount, feeRate, replaceable, user });
return res.send(psbt);
- } catch(e) {
+ } catch (e) {
return res.status(500).send(e.message);
- }
+ }
}
let invoice = await db.Invoice.findOne({
@@ -19,8 +19,8 @@ export default ah(async (req, res) => {
include: {
attributes: ["username"],
model: db.User,
- as: "user",
- },
+ as: "user"
+ }
});
if (invoice) {
@@ -34,13 +34,18 @@ export default ah(async (req, res) => {
try {
amount = parseInt(amount);
- let partial = await bc.createRawTransaction([], {
- [address]: (amount / SATS).toFixed(8),
- }, 0, replaceable);
+ let partial = await bc.createRawTransaction(
+ [],
+ {
+ [address]: (amount / SATS).toFixed(8)
+ },
+ 0,
+ replaceable
+ );
let params = {
subtractFeeFromOutputs: amount === user.balance ? [0] : [],
- replaceable,
+ replaceable
};
if (feeRate) params.feeRate = (feeRate / SATS).toFixed(8);
@@ -59,4 +64,4 @@ export default ah(async (req, res) => {
l.error("bitcoin fee estimation error", e);
return res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/bitcoin/generate.js b/routes/bitcoin/generate.js
index 92df1e12..1b6c1aa4 100644
--- a/routes/bitcoin/generate.js
+++ b/routes/bitcoin/generate.js
@@ -1,5 +1,5 @@
-export default ah(async (req, res) => {
+export default async (req, res) => {
let address = await bc.getNewAddress();
await bc.generateToAddress(1, address);
res.end();
-});
+};
diff --git a/routes/bitcoin/index.js b/routes/bitcoin/index.js
new file mode 100644
index 00000000..9d096e8f
--- /dev/null
+++ b/routes/bitcoin/index.js
@@ -0,0 +1,13 @@
+import broadcast from "./broadcast.js";
+import generate from "./generate.js";
+import sweep from "./sweep.js";
+import fee from "./fee.js";
+import send from "./send.js";
+
+export default {
+ broadcast,
+ generate,
+ sweep,
+ fee,
+ send
+};
diff --git a/routes/bitcoin/receive.js b/routes/bitcoin/receive.js
index ac9aa1e7..65e96883 100644
--- a/routes/bitcoin/receive.js
+++ b/routes/bitcoin/receive.js
@@ -1,6 +1,8 @@
+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';
+import { Op } from '@sequelize/core';
import { fromBase58 } from 'bip32';
import bitcoin from 'bitcoinjs-lib';
diff --git a/routes/bitcoin/send.js b/routes/bitcoin/send.js
index 85117dbb..d8406075 100644
--- a/routes/bitcoin/send.js
+++ b/routes/bitcoin/send.js
@@ -1,7 +1,11 @@
+import config from "../../config/index.js";
const btc = config.liquid.btcasset;
-import { computeConversionFee, conversionFeeReceiver } from './conversionFee.js';
+import {
+ computeConversionFee,
+ conversionFeeReceiver
+} from "./conversionFee.js";
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { user } = req;
let { address, memo, tx } = req.body;
let { hex } = tx;
@@ -61,7 +65,10 @@ export default ah(async (req, res) => {
// use user's credits to reduce fee, if available
let conversionFeeDeduction = Math.min(account.btc_credits, conversionFee);
if (conversionFeeDeduction) {
- await account.decrement({ btc_credits: conversionFeeDeduction }, { transaction });
+ await account.decrement(
+ { btc_credits: conversionFeeDeduction },
+ { transaction }
+ );
await account.reload({ transaction });
conversionFee -= conversionFeeDeduction;
}
@@ -70,11 +77,19 @@ export default ah(async (req, res) => {
l.error("amount exceeds balance", amount, fee, account.balance);
throw new Error("low balance");
} else if (total + conversionFee > account.balance) {
- l.error("total (after conversion fee) exceeds balance", amount, fee, account.balance);
+ l.error(
+ "total (after conversion fee) exceeds balance",
+ amount,
+ fee,
+ account.balance
+ );
throw new Error("low balance (after conversion fee)");
}
- await account.decrement({ balance: (total + conversionFee) }, { transaction });
+ await account.decrement(
+ { balance: total + conversionFee },
+ { transaction }
+ );
await account.reload({ transaction });
let receiverAccount = await db.Account.findOne({
@@ -85,7 +100,7 @@ export default ah(async (req, res) => {
{
model: db.User,
as: "user"
- },
+ }
],
lock: transaction.LOCK.UPDATE,
transaction
@@ -94,20 +109,26 @@ export default ah(async (req, res) => {
let fee_payment;
let fee_payment_id = null;
if (conversionFee) {
- await receiverAccount.increment({ balance: conversionFee }, { transaction });
+ await receiverAccount.increment(
+ { balance: conversionFee },
+ { transaction }
+ );
await receiverAccount.reload({ transaction });
- fee_payment = await db.Payment.create({
- amount: conversionFee,
- fee: 0,
- memo: "Bitcoin conversion fee",
- account_id: receiverAccount.id,
- user_id: receiverAccount.user_id,
- rate: app.get("rates")[receiverAccount.user.currency],
- currency: receiverAccount.user.currency,
- confirmed: true,
- received: true,
- network: "COINOS"
- }, { transaction });
+ fee_payment = await db.Payment.create(
+ {
+ amount: conversionFee,
+ fee: 0,
+ memo: "Bitcoin conversion fee",
+ account_id: receiverAccount.id,
+ user_id: receiverAccount.user_id,
+ rate: app.get("rates")[receiverAccount.user.currency],
+ currency: receiverAccount.user.currency,
+ confirmed: true,
+ received: true,
+ network: "COINOS"
+ },
+ { transaction }
+ );
fee_payment_id = fee_payment.id;
}
@@ -146,9 +167,11 @@ export default ah(async (req, res) => {
l.info("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";
+ 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);
console.log(e);
return res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/bitcoin/sweep.js b/routes/bitcoin/sweep.js
index f056bdeb..6c0ca580 100644
--- a/routes/bitcoin/sweep.js
+++ b/routes/bitcoin/sweep.js
@@ -1,14 +1,17 @@
-import axios from 'axios';
-import bitcoin from 'bitcoinjs-lib';
-import coinselect from 'coinselect';
-import split from 'coinselect/split';
+import config from "../../config/index.js";
+import { prod } from "../../lib/utils.js";
+import axios from "axios";
+import bitcoin from "bitcoinjs-lib";
+import coinselect from "coinselect";
+import split from "coinselect/split.js";
+
const api = prod ? "https://blockstream.info/api" : config.bitcoin.electrs;
const SATS = 100000000;
const network = prod
? bitcoin.networks["bitcoin"]
: bitcoin.networks["regtest"];
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { address: from, amount, feeRate, target } = req.body;
let utxos;
if (!feeRate) feeRate = (await bc.estimateSmartFee(6)).feerate * SATS;
@@ -81,4 +84,4 @@ export default ah(async (req, res) => {
} catch (e) {
l.error("problem getting address stats", from, e.message);
}
-});
+};
diff --git a/routes/funding.js b/routes/funding.js
index 7edcd713..9d305010 100644
--- a/routes/funding.js
+++ b/routes/funding.js
@@ -1,3 +1,5 @@
+import app from "../app.js";
+import config from "../config/index.js";
import mailgunFactory from 'mailgun-js';
const mailgun = mailgunFactory(config.mailgun);
@@ -5,7 +7,7 @@ app.post(
"/id",
auth,
upload.single("id"),
- ah(async (req, res) => {
+ async (req, res) => {
const { user } = req;
if (user.verified === "proof") user.verified = "pending";
else user.verified = "id";
@@ -24,13 +26,12 @@ app.post(
res.end();
})
-);
app.post(
"/proof",
auth,
upload.single("proof"),
- ah(async (req, res) => {
+ async (req, res) => {
const { user } = req;
if (user.verified === "id") user.verified = "pending";
else user.verified = "proof";
@@ -40,12 +41,11 @@ app.post(
res.end();
})
-);
app.post(
"/funding",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
try {
let { id, amount, code } = req.body;
@@ -81,12 +81,11 @@ app.post(
res.status(500).send("Funding request failed");
}
})
-);
app.post(
"/withdrawal",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
try {
const { account, amount, email, institution, transit, notes } = req.body;
if (!parseFloat(amount) || parseFloat(amount) < 0)
@@ -108,4 +107,3 @@ app.post(
res.status(500).send("Withdrawal request failed");
}
})
-);
diff --git a/routes/info.js b/routes/info.js
index 0be7f27d..537cdc44 100644
--- a/routes/info.js
+++ b/routes/info.js
@@ -1,4 +1,5 @@
-import sequelize from 'sequelize';
+import app from "../app.js";
+import sequelize from '@sequelize/core';
const { Op } = sequelize;
/**
@@ -10,7 +11,7 @@ const { Op } = sequelize;
* @apiSuccess {String[]} networks Array of supported networks; possible values are "bitcoin", "liquid" and "lightning".
* @apiSuccess {String} clientVersion the current git commit of the ui
*/
-app.get("/info", ah(async (req, res, next) => {
+app.get("/info", async (req, res, next) => {
const { clientVersion } = config;
const info = {
@@ -20,9 +21,9 @@ app.get("/info", ah(async (req, res, next) => {
};
res.send(info);
-}));
+});
-app.get("/balances", ah(async (req, res, next) => {
+app.get("/balances", async (req, res, next) => {
const accounts = await db.Account.findAll({
attributes: [
"asset",
@@ -44,8 +45,8 @@ app.get("/balances", ah(async (req, res, next) => {
lnwallet = parseInt(funds.outputs.reduce((a, b) => a + b.value, 0));
} else {
lninfo = await lnp.getInfo({});
- lnchannel = parseInt((await lnp.channelBalance({})).balance);
- lnwallet = parseInt((await lnp.walletBalance({})).total_balance);
+ lnchannel = parseInt((await lnp.channelBalance({}).balance));
+ lnwallet = parseInt((await lnp.walletBalance({}).total_balance));
}
}
@@ -80,4 +81,4 @@ app.get("/balances", ah(async (req, res, next) => {
parseInt(lnwallet);
res.send(info);
-}));
+});
diff --git a/routes/invoices.js b/routes/invoices.js
index 9e3fedb7..a65ff7ba 100644
--- a/routes/invoices.js
+++ b/routes/invoices.js
@@ -1,113 +1,107 @@
-import { Op } from 'sequelize';
-import axios from 'axios';
+import app from "../app.js";
+import { optionalAuth } from "../lib/passport.js";
+import { Op } from "@sequelize/core";
+import axios from "axios";
-app.get(
- "/invoice",
- ah(async (req, res, next) => {
- try {
- const invoice = await db.Invoice.findOne({
- where: {
- uuid: req.query.uuid
- },
- include: {
- model: db.User,
- as: "user",
- attributes: ["username", "currency"]
- }
- });
+app.get("/invoice", async (req, res, next) => {
+ try {
+ const invoice = await db.Invoice.findOne({
+ where: {
+ uuid: req.query.uuid
+ },
+ include: {
+ model: db.User,
+ as: "user",
+ attributes: ["username", "currency"]
+ }
+ });
- res.send(invoice);
- } catch (e) {
- l.error("couldn't find invoice", e);
- }
- })
-);
+ res.send(invoice);
+ } catch (e) {
+ l.error("couldn't find invoice", e);
+ }
+});
-app.post(
- "/invoice",
- optionalAuth,
- ah(async (req, res, next) => {
- try {
- let { liquidAddress, id, invoice, user, tx } = req.body;
- let { blindkey } = invoice;
+app.post("/invoice", optionalAuth, async (req, res, next) => {
+ try {
+ let { liquidAddress, id, invoice, user, tx } = req.body;
+ let { blindkey } = invoice;
- if (invoice.amount < 0) throw new Error("amount out of range");
- if (
- invoice.tip > invoice.amount ||
- invoice.tip > 1000000 ||
- invoice.tip < 0
- )
- throw new Error("tip amount out of range");
+ if (invoice.amount < 0) throw new Error("amount out of range");
+ if (
+ invoice.tip > invoice.amount ||
+ invoice.tip > 1000000 ||
+ invoice.tip < 0
+ )
+ throw new Error("tip amount out of range");
- if (liquidAddress) {
- l.info("conversion request for", liquidAddress, invoice.text);
- convert[invoice.text] = { address: liquidAddress, tx };
- }
+ if (liquidAddress) {
+ l.info("conversion request for", liquidAddress, invoice.text);
+ convert[invoice.text] = { address: liquidAddress, tx };
+ }
- if (!user) ({ user } = req);
- else {
- user = await db.User.findOne({
- where: {
- username: user.username
- }
- });
- }
- 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.tip > invoice.amount || invoice.tip > 1000000)
- throw new Error("tip is too large");
- if (invoice.tip < 0 || invoice.amount < 0)
- throw new Error("invalid amount");
- invoice.user_id = user.id;
- invoice.account_id = user.account_id;
+ if (!user) ({ user } = req);
+ else {
+ user = await db.User.findOne({
+ where: {
+ username: user.username
+ }
+ });
+ }
+ 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.tip > invoice.amount || invoice.tip > 1000000)
+ throw new Error("tip is too large");
+ if (invoice.tip < 0 || invoice.amount < 0)
+ throw new Error("invalid amount");
+ invoice.user_id = user.id;
+ invoice.account_id = user.account_id;
- l.info(
- "creating invoice",
- user.username,
- invoice.network,
- invoice.amount,
- invoice.tip,
- invoice.currency,
- invoice.text &&
- `${invoice.text.substr(0, 8)}..${invoice.text.substr(-6)}`
- );
+ l.info(
+ "creating invoice",
+ user.username,
+ invoice.network,
+ invoice.amount,
+ invoice.tip,
+ invoice.currency,
+ invoice.text && `${invoice.text.substr(0, 8)}..${invoice.text.substr(-6)}`
+ );
- if (!invoice.tip) invoice.tip = 0;
+ if (!invoice.tip) invoice.tip = 0;
- const exists =
- invoice.text &&
- (await db.Invoice.findOne({
- where: {
- [Op.or]: {
- address: invoice.address || "",
- unconfidential: invoice.unconfidential || "",
- text: invoice.text
- }
+ const exists =
+ invoice.text &&
+ (await db.Invoice.findOne({
+ where: {
+ [Op.or]: {
+ address: invoice.address || "",
+ unconfidential: invoice.unconfidential || "",
+ text: invoice.text
}
- }));
-
- invoice = exists
- ? await exists.update(invoice)
- : await db.Invoice.create(invoice);
- addresses[invoice.address] = user.username;
- if (invoice.unconfidential) {
- addresses[invoice.unconfidential] = user.username;
- if (blindkey) await lq.importBlindingKey(invoice.address, blindkey);
- }
+ }
+ }));
- res.send(invoice);
- } catch (e) {
- l.error(e.message, e.stack);
- res.status(500).send(`Problem during invoice creation: ${e.message}`);
+ invoice = exists
+ ? await exists.update(invoice)
+ : await db.Invoice.create(invoice);
+ addresses[invoice.address] = user.username;
+ if (invoice.unconfidential) {
+ addresses[invoice.unconfidential] = user.username;
+ if (blindkey) await lq.importBlindingKey(invoice.address, blindkey);
}
- })
-);
+
+ res.send(invoice);
+ } catch (e) {
+ l.error(e.message, e.stack);
+ res.status(500).send(`Problem during invoice creation: ${e.message}`);
+ }
+});
app.post(
"/:username/:network/invoice",
optionalAuth,
- ah(async (req, res, next) => {
+ async (req, res, next) => {
let { network, username } = req.params;
- })
+ }
);
diff --git a/routes/lightning/channel.js b/routes/lightning/channel.js
index fe6d9520..168f55ab 100644
--- a/routes/lightning/channel.js
+++ b/routes/lightning/channel.js
@@ -1,6 +1,6 @@
-import axios from 'axios';
+import axios from "axios";
-export default ah(async (req, res) => {
+export default async (req, res) => {
const { params } = req.body;
const [pubkey, host] = params.uri.split("@");
@@ -12,7 +12,7 @@ export default ah(async (req, res) => {
perm: true
});
} catch (e) {
- if (!e.message.includes('already connected')) {
+ if (!e.message.includes("already connected")) {
l.error("problem connecting to peer", e.message);
return res.status(500).send(e.message);
}
@@ -22,18 +22,18 @@ export default ah(async (req, res) => {
let remoteid;
try {
remoteid = (await lnp.getInfo({})).identity_pubkey;
- } catch(e) {
+ } catch (e) {
l.error("problem getting lightning node info", e.message);
return res.status(500).send(e.message);
- }
+ }
let url = `${callback}?k1=${k1}&remoteid=${remoteid}&private=0`;
try {
let response = await axios.get(url);
res.send(response.data);
- } catch(e) {
+ } catch (e) {
l.error("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 96b6d71f..3aecaa61 100644
--- a/routes/lightning/channelRequest.js
+++ b/routes/lightning/channelRequest.js
@@ -1,10 +1,13 @@
-export default ah(async (req, res) => {
+import { lnurlServer } from "../lnurl.js";
+
+export default async (req, res) => {
let { localAmt, pushAmt } = req.body;
pushAmt = 0;
try {
- if (localAmt < 20000) throw new Error("amount must be greater than 20000 SAT");
+ if (localAmt < 20000)
+ throw new Error("amount must be greater than 20000 SAT");
if (localAmt > 1000000) throw new Error("amount must be <= 1000000");
const result = await lnurlServer.generateNewUrl("channelRequest", {
@@ -17,4 +20,4 @@ export default ah(async (req, res) => {
l.error("problem generating channel request", e.message);
res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/lightning/conversionFee.js b/routes/lightning/conversionFee.js
index 161f18e6..62c0ec28 100644
--- a/routes/lightning/conversionFee.js
+++ b/routes/lightning/conversionFee.js
@@ -2,14 +2,11 @@
// This is in a separate file so that the same function can be used by ./send and ./receive
const conversionFeeMultiplier = 0.01;
-const conversionFeeReceiver = "coinosfees"; // account that receives the fees
+export const conversionFeeReceiver = "coinosfees"; // account that receives the fees
/**
* Returns the fee you have to pay for withdrawing 'amount' lightning BTC.
*/
-function computeConversionFee(amount) {
+export function computeConversionFee(amount) {
return Math.floor(amount * conversionFeeMultiplier);
}
-
-module.exports.conversionFeeReceiver = conversionFeeReceiver;
-module.exports.computeConversionFee = computeConversionFee;
diff --git a/routes/lightning/index.js b/routes/lightning/index.js
new file mode 100644
index 00000000..5d82cb5b
--- /dev/null
+++ b/routes/lightning/index.js
@@ -0,0 +1,13 @@
+import channel from "./channel.js";
+import channelRequest from "./channelRequest.js";
+import invoice from "./invoice.js";
+import query from "./query.js";
+import send from "./send.js";
+
+export default {
+ channel,
+ channelRequest,
+ invoice,
+ query,
+ send
+};
diff --git a/routes/lightning/invoice.js b/routes/lightning/invoice.js
index 38bad042..7d8a10cc 100644
--- a/routes/lightning/invoice.js
+++ b/routes/lightning/invoice.js
@@ -1,5 +1,4 @@
-
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { amount, memo, tip } = req.body;
if (!tip) tip = 0;
let value = amount + tip;
@@ -22,4 +21,4 @@ export default ah(async (req, res) => {
l.error("problem creating invoice", e.message, e.stack);
res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/lightning/query.js b/routes/lightning/query.js
index 0d034604..36c297f6 100644
--- a/routes/lightning/query.js
+++ b/routes/lightning/query.js
@@ -1,17 +1,17 @@
-export default ah(async (req, res) => {
+export default async (req, res) => {
const { payreq } = req.body;
const invoice = await db.Invoice.findOne({
include: {
- attributes: ['username'],
+ attributes: ["username"],
model: db.User,
as: "user"
},
where: {
- text: payreq,
+ text: payreq
}
});
if (invoice) emit(req.user.username, "to", invoice.user);
res.end();
-});
+};
diff --git a/routes/lightning/receive.js b/routes/lightning/receive.js
index 1c3dc8eb..405eed38 100644
--- a/routes/lightning/receive.js
+++ b/routes/lightning/receive.js
@@ -1,4 +1,7 @@
+import { notify } from "../../lib/notifications.js";
+import { callWebhook } from "../../lib/webhooks.js";
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);
diff --git a/routes/lightning/send.js b/routes/lightning/send.js
index a2eedcc8..807b4bb8 100644
--- a/routes/lightning/send.js
+++ b/routes/lightning/send.js
@@ -1,11 +1,16 @@
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { amount, route, memo, payreq } = req.body;
let { user } = req;
try {
res.send(await send(amount, memo, payreq, user));
} catch (e) {
- l.error("problem sending lightning payment", user.username, payreq, e.message);
+ l.error(
+ "problem sending lightning payment",
+ user.username,
+ payreq,
+ e.message
+ );
res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/liquid/broadcast.js b/routes/liquid/broadcast.js
index 168e9518..2562effc 100644
--- a/routes/liquid/broadcast.js
+++ b/routes/liquid/broadcast.js
@@ -1,4 +1,4 @@
-export default ah(async (req, res) => {
+export default async (req, res) => {
try {
const { user } = req;
let hash = await lq.sendRawTransaction(req.body.tx);
@@ -49,4 +49,4 @@ export default ah(async (req, res) => {
l.error("problem broadcasting liquid transaction", e);
res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/liquid/conversionFee.js b/routes/liquid/conversionFee.js
index f6a9e5b9..36ba6f36 100644
--- a/routes/liquid/conversionFee.js
+++ b/routes/liquid/conversionFee.js
@@ -2,14 +2,11 @@
// This is in a separate file so that the same function can be used by ./send and ./receive
const conversionFeeMultiplier = 0.01;
-const conversionFeeReceiver = "coinosfees"; // account that receives the fees
+export const conversionFeeReceiver = "coinosfees"; // account that receives the fees
/**
* Returns the fee you have to pay for withdrawing 'amount' L-BTC.
*/
-function computeConversionFee(amount) {
+export function computeConversionFee(amount) {
return Math.floor(amount * conversionFeeMultiplier);
}
-
-module.exports.conversionFeeReceiver = conversionFeeReceiver;
-module.exports.computeConversionFee = computeConversionFee;
diff --git a/routes/liquid/fee.js b/routes/liquid/fee.js
index 0488b31e..0a2c330a 100644
--- a/routes/liquid/fee.js
+++ b/routes/liquid/fee.js
@@ -1,4 +1,4 @@
-import buildTx from '../../lib/buildliquidtx';
+import buildTx from "../../lib/buildliquidtx.js";
liquidTx = async ({ address, asset, amount, feeRate, replaceable, user }) => {
let tx, fee;
@@ -49,12 +49,14 @@ liquidTx = async ({ address, asset, amount, feeRate, replaceable, user }) => {
tx = await node.createRawTransaction(
[],
- [{
- [address]: (amount / SATS).toFixed(8),
- asset
- }],
+ [
+ {
+ [address]: (amount / SATS).toFixed(8),
+ asset
+ }
+ ],
0,
- replaceable,
+ replaceable
);
l.info("funding tx for fee estimate", tx);
@@ -71,12 +73,12 @@ liquidTx = async ({ address, asset, amount, feeRate, replaceable, user }) => {
return { feeRate, tx };
};
-export default ah(async (req, res) => {
+export default async (req, res) => {
try {
- let tx = await liquidTx({ ...req.body, user: req.user })
+ let tx = await liquidTx({ ...req.body, user: req.user });
res.send(tx);
} catch (e) {
l.error("error estimating liquid fee", e.message, e.stack);
return res.status(500).send(e.message);
}
-});
+};
diff --git a/routes/liquid/generate.js b/routes/liquid/generate.js
index 50c63dcf..73ad9b59 100644
--- a/routes/liquid/generate.js
+++ b/routes/liquid/generate.js
@@ -1,5 +1,5 @@
-export default ah(async (req, res) => {
+export default async (req, res) => {
let address = await lq.getNewAddress();
await lq.generateToAddress(1, address);
res.end();
-});
+};
diff --git a/routes/liquid/index.js b/routes/liquid/index.js
new file mode 100644
index 00000000..2b6b72b9
--- /dev/null
+++ b/routes/liquid/index.js
@@ -0,0 +1,13 @@
+import broadcast from "./broadcast.js";
+import generate from "./generate.js";
+// import fee from "./fee.js";
+import send from "./send.js";
+// import taxi from "./taxi.js";
+
+export default {
+ broadcast,
+ generate,
+ // fee,
+ send,
+ // taxi
+};
diff --git a/routes/liquid/receive.js b/routes/liquid/receive.js
index 151ffb40..8891292e 100644
--- a/routes/liquid/receive.js
+++ b/routes/liquid/receive.js
@@ -1,9 +1,12 @@
+import { sendLiquid } from "./send.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';
+import { Op } from '@sequelize/core';
import { fromBase58 } from 'bip32';
import bitcoin from 'bitcoinjs-lib';
-import { Block, networks, Transaction } from 'liquidjs-lib';
+// import { Block, networks, Transaction } from 'liquidjs-lib';
import wretch from 'wretch';
import fetch from 'node-fetch';
wretch().polyfills({ fetch });
diff --git a/routes/liquid/send.js b/routes/liquid/send.js
index e5112468..9529a040 100644
--- a/routes/liquid/send.js
+++ b/routes/liquid/send.js
@@ -1,9 +1,13 @@
+import config from "../../config/index.js";
const btc = config.liquid.btcasset;
const lcad = config.liquid.cadasset;
-import { Transaction } from 'liquidjs-lib';
-import { computeConversionFee, conversionFeeReceiver } from './conversionFee.js';
+// import { Transaction } from 'liquidjs-lib';
+import {
+ computeConversionFee,
+ conversionFeeReceiver
+} from "./conversionFee.js";
-sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
+export const sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
try {
l.info("sending liquid", amount, address);
if (!tx) {
@@ -106,9 +110,15 @@ sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
});
// use user's credits to reduce fee, if available
- let conversionFeeDeduction = Math.min(account.liquid_credits, conversionFee);
+ let conversionFeeDeduction = Math.min(
+ account.liquid_credits,
+ conversionFee
+ );
if (conversionFeeDeduction) {
- await account.decrement({ liquid_credits: conversionFeeDeduction }, { transaction });
+ await account.decrement(
+ { liquid_credits: conversionFeeDeduction },
+ { transaction }
+ );
await account.reload({ transaction });
conversionFee -= conversionFeeDeduction;
}
@@ -140,7 +150,10 @@ sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
);
}
- await account.decrement({ balance: (total + conversionFee)}, { transaction });
+ await account.decrement(
+ { balance: total + conversionFee },
+ { transaction }
+ );
await account.reload({ transaction });
let receiverAccount = await db.Account.findOne({
@@ -151,14 +164,17 @@ sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
{
model: db.User,
as: "user"
- },
+ }
],
lock: transaction.LOCK.UPDATE,
transaction
});
if (conversionFee) {
- await receiverAccount.increment({ balance: conversionFee }, { transaction });
+ await receiverAccount.increment(
+ { balance: conversionFee },
+ { transaction }
+ );
await receiverAccount.reload({ transaction });
fee_payment = {
amount: conversionFee,
@@ -173,7 +189,9 @@ sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
network: "COINOS"
};
fee_payment.account = receiverAccount;
- ({ id: fee_payment_id } = await db.Payment.create(fee_payment, { transaction }));
+ ({ id: fee_payment_id } = await db.Payment.create(fee_payment, {
+ transaction
+ }));
}
let payment = {
@@ -188,7 +206,7 @@ sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
confirmed: true,
received: false,
network: "liquid",
- fee_payment_id,
+ fee_payment_id
};
payment.account = account;
@@ -231,7 +249,7 @@ sendLiquid = async ({ asset, amount, user, address, memo, tx, limit }) => {
}
};
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { user } = req;
try {
@@ -240,4 +258,4 @@ export default ah(async (req, res) => {
l.error("problem sending liquid", user.username, e.message);
return res.status(500).send(e);
}
-});
+};
diff --git a/routes/liquid/taxi.js b/routes/liquid/taxi.js
index 5bc3c8b7..e5baeeb9 100644
--- a/routes/liquid/taxi.js
+++ b/routes/liquid/taxi.js
@@ -1,8 +1,8 @@
-import { address as Address, Psbt, payments, networks } from 'liquidjs-lib';
-import { ECPairFactory } from 'ecpair';
-import tinysecp from 'tiny-secp256k1';
-import wretch from 'wretch';
-import fetch from 'node-fetch';
+// import { address as Address, Psbt, payments, networks } from 'liquidjs-lib';
+import { ECPairFactory } from "ecpair";
+import tinysecp from "tiny-secp256k1";
+import wretch from "wretch";
+import fetch from "node-fetch";
wretch().polyfills({ fetch });
@@ -16,7 +16,7 @@ const network = prod ? networks.liquid : networks.regtest;
const ECPair = ECPairFactory(tinysecp);
const key = ECPair.fromPrivateKey(Buffer.from(config.taxi, "hex"));
-export default ah(async (req, res) => {
+export default async (req, res) => {
let { user } = req;
let { psbt } = req.body;
@@ -82,4 +82,4 @@ export default ah(async (req, res) => {
console.log(e);
return res.status(500).send(e);
}
-});
+};
diff --git a/routes/lnurl.js b/routes/lnurl.js
index 9ced0466..7687b248 100644
--- a/routes/lnurl.js
+++ b/routes/lnurl.js
@@ -1,162 +1,109 @@
-import axios from 'axios';
-import lnurl from 'lnurl';
-import jwt from 'jsonwebtoken';
-import qs from 'query-string';
-import persist from '../lib/persist';
-import bolt11 from 'bolt11';
+import app from "../app.js";
+import config from "../config/index.js";
+import axios from "axios";
+import lnurl from "lnurl";
+import jwt from "jsonwebtoken";
+import qs from "query-string";
+import persist from "../lib/persist.js";
+import bolt11 from "bolt11";
+import { optionalAuth, auth } from "../lib/passport.js";
-logins = persist("data/logins.json");
-recipients = persist("data/recipients.json");
-lnurlPayments = persist("data/payments.json");
-withdrawals = persist("data/withdrawals.json");
+export const logins = persist("data/logins.json");
+export const recipients = persist("data/recipients.json");
+export const lnurlPayments = persist("data/payments.json");
+export const withdrawals = persist("data/withdrawals.json");
-lnurlServer = lnurl.createServer(config.lnurl);
+export const lnurlServer = lnurl.createServer(config.lnurl);
-import { computeConversionFee, conversionFeeReceiver } from './lightning/conversionFee.js';
+import {
+ computeConversionFee,
+ conversionFeeReceiver
+} from "./lightning/conversionFee.js";
-var optionalAuth = function(req, res, next) {
- passport.authenticate("jwt", { session: false }, function(err, user, info) {
- req.user = user;
- next();
- })(req, res, next);
-};
-
-app.get(
- "/url",
- ah(async (req, res, next) => {
- try {
- const code = await db.Code.findOne({
- where: {
- code: req.query.code
- }
- });
-
- if (code) {
- res.send(code.text);
- } else {
- throw new Error("code not found");
+app.get("/url", async (req, res, next) => {
+ try {
+ const code = await db.Code.findOne({
+ where: {
+ code: req.query.code
}
- } catch (e) {
- l.error("couldn't find url", e.message);
- }
- })
-);
-
-app.get(
- "/withdraw",
- auth,
- ah(async (req, res, next) => {
- const { min, max } = req.query;
- try {
- const result = await lnurlServer.generateNewUrl("withdrawRequest", {
- minWithdrawable: min * 1000,
- maxWithdrawable: max * 1000,
- defaultDescription: "coinos voucher"
- });
-
- withdrawals[result.secret] = req.user;
-
- res.send(result);
- } catch (e) {
- l.error("problem generating withdrawl url", e.message);
- res.status(500).send(e.message);
- }
- })
-);
-
-app.post(
- "/code",
- ah(async (req, res, next) => {
- try {
- const { encoded } = req.body.lnurl;
- const code = await db.Code.findOrCreate({
- where: {
- code: `lnurl:${encoded.substr(-32)}`,
- text: encoded
- }
- });
+ });
- res.send(code);
- } catch (e) {
- l.error(e.errors);
- res.status(500).send(e.message);
+ if (code) {
+ res.send(code.text);
+ } else {
+ throw new Error("code not found");
}
- })
-);
-
-app.post(
- "/withdraw",
- auth,
- ah(async (req, res, next) => {
- const { user } = req;
- const {
- amount: value,
- params: { callback, k1 }
- } = req.body;
- const invoice = await lnp.addInvoice({ value });
- const { payment_request: pr } = invoice;
- const url = `${callback}?k1=${k1}&pr=${pr}`;
+ } catch (e) {
+ l.error("couldn't find url", e.message);
+ }
+});
- await db.Invoice.create({
- user_id: user.id,
- text: pr,
- rate: app.get("rates")[user.currency],
- currency: user.currency,
- amount: value,
- tip: 0,
- network: "bitcoin"
+app.get("/withdraw", auth, async (req, res, next) => {
+ const { min, max } = req.query;
+ try {
+ const result = await lnurlServer.generateNewUrl("withdrawRequest", {
+ minWithdrawable: min * 1000,
+ maxWithdrawable: max * 1000,
+ defaultDescription: "coinos voucher"
});
- try {
- result = (await axios.get(url)).data;
- res.send(result);
- } catch (e) {
- l.error("failed to withdraw", e.message);
- res.status(500).send(e.message);
- }
- })
-);
-
-app.get(
- "/lnurlp/:username",
- ah(async (req, res, next) => {
- try {
- const { username } = req.params;
- let user = await db.User.findOne({
- where: {
- username
- }
- });
+ withdrawals[result.secret] = req.user;
- if (!user) throw new Error("user not found");
+ res.send(result);
+ } catch (e) {
+ l.error("problem generating withdrawl url", e.message);
+ res.status(500).send(e.message);
+ }
+});
- let { amount, minSendable, maxSendable } = req.query;
- minSendable = minSendable || 1000;
- maxSendable = maxSendable || 1000000000;
- if (parseInt(amount)) minSendable = maxSendable = amount * 1000;
+app.post("/code", async (req, res, next) => {
+ try {
+ const { encoded } = req.body.lnurl;
+ const code = await db.Code.findOrCreate({
+ where: {
+ code: `lnurl:${encoded.substr(-32)}`,
+ text: encoded
+ }
+ });
- let result = await lnurlServer.generateNewUrl("payRequest", {
- minSendable,
- maxSendable,
- metadata: JSON.stringify([["text/plain", `paying ${user.username}`], ["text/identifier", `${user.username}@coinos.io`]])
- });
+ res.send(code);
+ } catch (e) {
+ l.error(e.errors);
+ res.status(500).send(e.message);
+ }
+});
- recipients[result.secret] = user;
- l.info("recipient", user.username, result.secret);
+app.post("/withdraw", auth, async (req, res, next) => {
+ const { user } = req;
+ const {
+ amount: value,
+ params: { callback, k1 }
+ } = req.body;
+ const invoice = await lnp.addInvoice({ value });
+ const { payment_request: pr } = invoice;
+ const url = `${callback}?k1=${k1}&pr=${pr}`;
- result = await axios.get(result.url);
+ await db.Invoice.create({
+ user_id: user.id,
+ text: pr,
+ rate: app.get("rates")[user.currency],
+ currency: user.currency,
+ amount: value,
+ tip: 0,
+ network: "bitcoin"
+ });
- res.send(result.data);
- } catch (e) {
- l.error("problem generating payment url", e.message);
- res.status(500).send(e.message);
- }
- })
-);
+ try {
+ result = (await axios.get(url)).data;
+ res.send(result);
+ } catch (e) {
+ l.error("failed to withdraw", e.message);
+ res.status(500).send(e.message);
+ }
+});
-app.get(
- "/pay/:username",
- ah(async (req, res, next) => {
+app.get("/lnurlp/:username", async (req, res, next) => {
+ try {
const { username } = req.params;
let user = await db.User.findOne({
where: {
@@ -164,133 +111,154 @@ app.get(
}
});
+ if (!user) throw new Error("user not found");
+
let { amount, minSendable, maxSendable } = req.query;
minSendable = minSendable || 1000;
maxSendable = maxSendable || 1000000000;
if (parseInt(amount)) minSendable = maxSendable = amount * 1000;
- try {
- const result = await lnurlServer.generateNewUrl("payRequest", {
- minSendable,
- maxSendable,
- metadata: JSON.stringify([["text/plain", `paying ${user.username}`]])
- });
+ let result = await lnurlServer.generateNewUrl("payRequest", {
+ minSendable,
+ maxSendable,
+ metadata: JSON.stringify([
+ ["text/plain", `paying ${user.username}`],
+ ["text/identifier", `${user.username}@coinos.io`]
+ ])
+ });
- recipients[result.secret] = user;
- l.info("recipient", user.username, result.secret);
- res.send(result);
- } catch (e) {
- l.error("problem generating payment url", e.message);
- res.status(500).send(e.message);
+ recipients[result.secret] = user;
+ l.info("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);
+ res.status(500).send(e.message);
+ }
+});
+
+app.get("/pay/:username", async (req, res, next) => {
+ const { username } = req.params;
+ let user = await db.User.findOne({
+ where: {
+ username
}
- })
-);
+ });
-app.post(
- "/pay",
- auth,
- ah(async (req, res, next) => {
- const { user } = req;
- const {
- amount,
- comment,
- params: { callback, k1 }
- } = req.body;
+ let { amount, minSendable, maxSendable } = req.query;
+ minSendable = minSendable || 1000;
+ maxSendable = maxSendable || 1000000000;
+ if (parseInt(amount)) minSendable = maxSendable = amount * 1000;
- let url = `${callback}${callback.includes("?") ? "&" : "?"}amount=${amount *
- 1000}${comment ? "&comment=" + comment : ""}`;
+ try {
+ const result = await lnurlServer.generateNewUrl("payRequest", {
+ minSendable,
+ maxSendable,
+ metadata: JSON.stringify([["text/plain", `paying ${user.username}`]])
+ });
- try {
- const parts = callback.split("/");
- const secret = parts[parts.length - 1];
- lnurlPayments[secret] = user.id;
+ recipients[result.secret] = user;
+ l.info("recipient", user.username, result.secret);
+ res.send(result);
+ } catch (e) {
+ l.error("problem generating payment url", e.message);
+ res.status(500).send(e.message);
+ }
+});
- if (recipients[secret]) {
- url = `${req.protocol}://${req.get("host")}/api/send`;
- const { data } = await axios.post(
- url,
- {
- amount,
- memo: comment,
- username: recipients[secret].username
- },
- {
- headers: {
- Authorization: req.get("Authorization")
- }
+app.post("/pay", auth, async (req, res, next) => {
+ const { user } = req;
+ const {
+ amount,
+ comment,
+ params: { callback, k1 }
+ } = req.body;
+
+ let url = `${callback}${callback.includes("?") ? "&" : "?"}amount=${amount *
+ 1000}${comment ? "&comment=" + comment : ""}`;
+
+ try {
+ const parts = callback.split("/");
+ const secret = parts[parts.length - 1];
+ lnurlPayments[secret] = user.id;
+
+ if (recipients[secret]) {
+ url = `${req.protocol}://${req.get("host")}/api/send`;
+ const { data } = await axios.post(
+ url,
+ {
+ amount,
+ memo: comment,
+ username: recipients[secret].username
+ },
+ {
+ headers: {
+ Authorization: req.get("Authorization")
}
- );
+ }
+ );
- res.send(data);
- } else {
- const { data } = await axios.get(url);
- res.send(await send(amount, "", data.pr, user));
- }
- } catch (e) {
- l.error("failed to send payment", e.message);
- res.status(500).send(e.message);
+ res.send(data);
+ } else {
+ const { data } = await axios.get(url);
+ res.send(await send(amount, "", data.pr, user));
}
- })
-);
-
-app.get(
- "/login",
- optionalAuth,
- ah(async (req, res, next) => {
- try {
- const result = await lnurlServer.generateNewUrl("login");
+ } catch (e) {
+ l.error("failed to send payment", e.message);
+ res.status(500).send(e.message);
+ }
+});
- if (req.user) {
- logins[result.secret] = req.user.username;
- }
+app.get("/login", optionalAuth, async (req, res, next) => {
+ try {
+ const result = await lnurlServer.generateNewUrl("login");
- res.send(result);
- } catch (e) {
- l.error("problem generating login url", e.message);
- res.status(500).send(e.message);
+ if (req.user) {
+ logins[result.secret] = req.user.username;
}
- })
-);
-app.get(
- "/encode",
- ah(async (req, res, next) => {
- let { domain, name } = req.query;
- let url = `https://${domain}/.well-known/lnurlp/${name}`;
- res.send(lnurl.encode(url));
- })
-);
+ res.send(result);
+ } catch (e) {
+ l.error("problem generating login url", e.message);
+ res.status(500).send(e.message);
+ }
+});
-app.get(
- "/decode",
- ah(async (req, res, next) => {
- const { text } = req.query;
+app.get("/encode", async (req, res, next) => {
+ let { domain, name } = req.query;
+ let url = `https://${domain}/.well-known/lnurlp/${name}`;
+ res.send(lnurl.encode(url));
+});
- try {
- const url = lnurl.decode(text);
- let spl = url.split("?");
- if (spl.length > 1 && qs.parse(spl[1]).tag === "login") {
- return res.send({
- tag: "login",
- k1: qs.parse(spl[1]).k1,
- callback: url,
- domain: url
- .split("://")[1]
- .split("/")[0]
- .split("@")
- .slice(-1)[0]
- .split(":")[0]
- });
- }
+app.get("/decode", async (req, res, next) => {
+ const { text } = req.query;
- const { data: params } = await axios.get(url);
- res.send(params);
- } catch (e) {
- l.error("problem decoding lnurl", e.message);
- res.status(500).send(e.message);
+ try {
+ const url = lnurl.decode(text);
+ let spl = url.split("?");
+ if (spl.length > 1 && qs.parse(spl[1]).tag === "login") {
+ return res.send({
+ tag: "login",
+ k1: qs.parse(spl[1]).k1,
+ callback: url,
+ domain: url
+ .split("://")[1]
+ .split("/")[0]
+ .split("@")
+ .slice(-1)[0]
+ .split(":")[0]
+ });
}
- })
-);
+
+ const { data: params } = await axios.get(url);
+ res.send(params);
+ } catch (e) {
+ l.error("problem decoding lnurl", e.message);
+ res.status(500).send(e.message);
+ }
+});
lnurlServer.on("payRequest:action:processed", async function(event) {
const { secret, params, result } = event;
@@ -414,15 +382,21 @@ lnurlServer.bindToHook(
{
model: db.User,
as: "user"
- },
+ }
],
lock: transaction.LOCK.UPDATE,
transaction
});
- let conversionFeeDeduction = Math.min(account.lightning_credits, conversionFee);
+ let conversionFeeDeduction = Math.min(
+ account.lightning_credits,
+ conversionFee
+ );
if (conversionFeeDeduction) {
- await account.decrement({ lightning_credits: conversionFeeDeduction }, { transaction });
+ await account.decrement(
+ { lightning_credits: conversionFeeDeduction },
+ { transaction }
+ );
await account.reload({ transaction });
conversionFee -= conversionFeeDeduction;
}
@@ -435,20 +409,26 @@ lnurlServer.bindToHook(
let fee_payment_id = null;
if (conversionFee) {
- await receiverAccount.increment({ balance: conversionFee }, { transaction });
+ await receiverAccount.increment(
+ { balance: conversionFee },
+ { transaction }
+ );
await receiverAccount.reload({ transaction });
- let fee_payment = await db.Payment.create({
- amount: conversionFee,
- fee: 0,
- memo: "Bitcoin conversion fee",
- account_id: receiverAccount.id,
- user_id: receiverAccount.user_id,
- rate: app.get("rates")[receiverAccount.user.currency],
- currency: receiverAccount.user.currency,
- confirmed: true,
- received: true,
- network: "COINOS"
- }, { transaction });
+ let fee_payment = await db.Payment.create(
+ {
+ amount: conversionFee,
+ fee: 0,
+ memo: "Bitcoin conversion fee",
+ account_id: receiverAccount.id,
+ user_id: receiverAccount.user_id,
+ rate: app.get("rates")[receiverAccount.user.currency],
+ currency: receiverAccount.user.currency,
+ confirmed: true,
+ received: true,
+ network: "COINOS"
+ },
+ { transaction }
+ );
fee_payment_id = fee_payment.id;
}
@@ -462,7 +442,7 @@ lnurlServer.bindToHook(
currency: user.currency,
confirmed: true,
network: "lightning",
- fee_payment_id,
+ fee_payment_id
},
{ transaction }
);
@@ -494,7 +474,10 @@ lnurlServer.bindToHook(
}
}, 1000);
- await account.decrement({ balance: (amount + conversionFee) }, { transaction });
+ await account.decrement(
+ { balance: amount + conversionFee },
+ { transaction }
+ );
await account.reload({ transaction });
let p = payment.get({ plain: true });
diff --git a/routes/payments.js b/routes/payments.js
index a9ad7d82..6861d2a3 100644
--- a/routes/payments.js
+++ b/routes/payments.js
@@ -1,93 +1,70 @@
-import fs from 'fs';
-import BitcoinCore from '@asoltys/bitcoin-core';
-import { join } from 'path';
-import { Op } from 'sequelize';
+import bc from "../lib/bitcoin.js";
+import app from "../app.js";
+import config from "../config/index.js";
+import { auth, adminAuth, optionalAuth } from "../lib/passport.js";
+import fs from "fs";
+import { join } from "path";
+import { Op } from "@sequelize/core";
+import send from "./send.js";
-app.post("/send", auth, require("./send"));
-app.post(
- "/sendToTokenHolders",
- auth,
- ah(async (req, res, next) => {
- let { asset, amount } = req.body;
+import btcRoutes from "./bitcoin/index.js";
+import lnRoutes from "./lightning/index.js";
+import lqRoutes from "./liquid/index.js";
- let accounts = await db.Account.findAll({
- where: {
- asset,
- "$user.username$": { [Op.ne]: "gh" }
- },
+app.post("/send", auth, send);
+app.post("/sendToTokenHolders", auth, async (req, res, next) => {
+ let { asset, amount } = req.body;
- include: [{ model: db.User, as: "user" }]
- });
+ let accounts = await db.Account.findAll({
+ where: {
+ asset,
+ "$user.username$": { [Op.ne]: "gh" }
+ },
- let totalTokens = accounts.reduce((a, b) => a + b.balance, 0);
- console.log("TOTAL TOKENS", totalTokens);
+ include: [{ model: db.User, as: "user" }]
+ });
- let totalSats = Math.floor(amount / totalTokens);
+ let totalTokens = accounts.reduce((a, b) => a + b.balance, 0);
+ console.log("TOTAL TOKENS", totalTokens);
- console.log("TOTAL SATS", totalSats)
+ let totalSats = Math.floor(amount / totalTokens);
- if (totalSats < 1) throw new Error("amount is too low to distribute");
+ console.log("TOTAL SATS", totalSats);
- for (let i = 0; i < accounts.length; i++) {
- let account = accounts[i];
- console.log(account.user.username, account.balance);
- }
- accounts.map(({ balance, user: { username } }) => ({ username, balance }));
+ if (totalSats < 1) throw new Error("amount is too low to distribute");
- res.send({ success: "it worked" });
- })
-);
+ for (let i = 0; i < accounts.length; i++) {
+ let account = accounts[i];
+ console.log(account.user.username, account.balance);
+ }
+ accounts.map(({ balance, user: { username } }) => ({ username, balance }));
-app.get(
- "/except",
- adminAuth,
- ah((req, res) => {
- let s = fs.createWriteStream("exceptions", { flags: "a" });
- unaccounted.map(tx => s.write(tx.txid + "\n"));
- l.info("updated exceptions");
- res.send("updated exceptions");
- })
-);
+ res.send({ success: "it worked" });
+});
-if (config.lna) {
- if (config.lna.clightning) {
- lna = require("clightning-client")(config.lna.dir);
- } else {
- const lnd = require("../lib/lnd");
- lna = lnd.default;
- lnp = [
- "addInvoice",
- "channelBalance",
- "connectPeer",
- "decodePayReq",
- "getInfo",
- "listInvoices",
- "listPayments",
- "sendPaymentSync",
- "walletBalance"
- ].reduce(
- (a, b) =>
- (a[b] = args => new Promise(r => lna[b](args, (e, v) => r(v)))) && a,
- {}
- );
- }
+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");
+ res.send("updated exceptions");
+});
- app.post("/lightning/channel", require("./lightning/channel"));
- app.post("/lightning/channelRequest", require("./lightning/channelRequest"));
- app.post("/lightning/invoice", require("./lightning/invoice"));
- app.post("/lightning/query", auth, require("./lightning/query"));
- app.post("/lightning/send", auth, require("./lightning/send"));
- require("./lightning/receive");
+if (config.lna) {
+ app.post("/lightning/channel", lnRoutes.channel);
+ app.post("/lightning/channelRequest", lnRoutes.channelRequest);
+ app.post("/lightning/invoice", lnRoutes.invoice);
+ app.post("/lightning/query", auth, lnRoutes.query);
+ app.post("/lightning/send", auth, lnRoutes.send);
+ import("./lightning/receive");
}
if (config.bitcoin) {
- bc = new BitcoinCore(config.bitcoin);
- app.post("/bitcoin/broadcast", optionalAuth, require("./bitcoin/broadcast"));
- app.get("/bitcoin/generate", auth, require("./bitcoin/generate"));
- app.post("/bitcoin/sweep", auth, require("./bitcoin/sweep"));
- app.post("/bitcoin/fee", auth, require("./bitcoin/fee"));
- app.post("/bitcoin/send", auth, require("./bitcoin/send"));
- require("./bitcoin/receive");
+ app.post("/bitcoin/broadcast", optionalAuth, btcRoutes.broadcast);
+ app.get("/bitcoin/generate", auth, btcRoutes.generate);
+ app.post("/bitcoin/sweep", auth, btcRoutes.sweep);
+ app.post("/bitcoin/fee", auth, btcRoutes.fee);
+ app.post("/bitcoin/send", auth, btcRoutes.send);
+ import("./bitcoin/receive");
setTimeout(async () => {
try {
@@ -102,14 +79,12 @@ if (config.bitcoin) {
}
if (config.liquid) {
- lq = new BitcoinCore(config.liquid);
- rare = new BitcoinCore(config.rare);
- app.post("/liquid/broadcast", optionalAuth, require("./liquid/broadcast"));
- app.get("/liquid/generate", auth, require("./liquid/generate"));
- app.post("/liquid/fee", auth, require("./liquid/fee"));
- app.post("/liquid/send", auth, require("./liquid/send"));
- app.post("/taxi", auth, require("./liquid/taxi"));
- require("./liquid/receive");
+ app.post("/liquid/broadcast", optionalAuth, lqRoutes.broadcast);
+ app.get("/liquid/generate", auth, lqRoutes.generate);
+ // app.post("/liquid/fee", auth, lqRoutes.fee);
+ app.post("/liquid/send", auth, lqRoutes.send);
+ // app.post("/taxi", auth, lqRoutes.taxi);
+ import("./liquid/receive");
setTimeout(async () => {
try {
@@ -123,46 +98,39 @@ if (config.liquid) {
}, 50);
}
-app.get(
- "/payments",
- auth,
- ah(async (req, res) => {
- if (!req.user.account_id) return res.send([]);
- let payments = await db.Payment.findAll({
+app.get("/payments", auth, async (req, res) => {
+ if (!req.user.account_id) return res.send([]);
+ let payments = await db.Payment.findAll({
+ where: {
+ account_id: req.user.account_id
+ },
+ order: [["id", "DESC"]],
+ include: {
+ model: db.Account,
+ as: "account"
+ }
+ });
+
+ res.send(payments);
+});
+
+app.get("/payment/:redeemcode", async (req, res) => {
+ try {
+ const { redeemcode } = req.params;
+ let payment = await db.Payment.findOne({
where: {
- account_id: req.user.account_id
+ redeemcode
},
- order: [["id", "DESC"]],
include: {
model: db.Account,
as: "account"
}
});
- res.send(payments);
- })
-);
-
-app.get(
- "/payment/:redeemcode",
- ah(async (req, res) => {
- try {
- const { redeemcode } = req.params;
- let payment = await db.Payment.findOne({
- where: {
- redeemcode
- },
- include: {
- model: db.Account,
- as: "account"
- }
- });
-
- if (!payment) fail("invalid code");
+ if (!payment) fail("invalid code");
- res.send(payment);
- } catch (e) {
- res.status(500).send(e.message);
- }
- })
-);
+ res.send(payment);
+ } catch (e) {
+ res.status(500).send(e.message);
+ }
+});
diff --git a/routes/referrals.js b/routes/referrals.js
index 82bbb3d4..5711532f 100644
--- a/routes/referrals.js
+++ b/routes/referrals.js
@@ -42,7 +42,7 @@ router.get('/', function(req, res, next) {
router.post(
"/grant",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const {sponsor_id, expiry} = req.body
var token = uuidv4()
@@ -56,7 +56,6 @@ router.post(
return res.send({token: token, status: 'available', expiry: expiry})
})
-);
/**
* @api {get} /grant Grant Referral code (variation using get)
@@ -83,7 +82,7 @@ router.post(
router.get(
"/grant",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const {sponsor_id, expiry} = req.query
var token = uuidv4()
@@ -97,7 +96,6 @@ router.get(
return res.send({token: token, status: 'available', expiry: expiry})
})
-);
/**
@@ -127,7 +125,7 @@ router.get(
router.get(
"/checkTokens/:sponsor_id",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const {sponsor_id} = req.params
const {status} = req.query
@@ -148,7 +146,6 @@ router.get(
return res.send({tokens: found})
})
-);
/**
@@ -175,7 +172,7 @@ router.get(
router.get(
"/verify/:user_id/:token",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { user_id, token } = req.params;
const found = await knex
@@ -203,7 +200,6 @@ router.get(
res.status(500).send('Invalid referral token')
}
})
-);
/**
@@ -227,7 +223,7 @@ router.get(
*/
router.post(
"/joinQueue",
- ah(async (req, res) => {
+ async (req, res) => {
const { email, phone, user_id } = req.body;
await knex.table('waiting_list')
@@ -239,11 +235,10 @@ router.post(
res.send({success: true, message: 'Added ' + email + ' to waiting list ' + phone})
})
-);
router.get(
"/joinQueue",
- ah(async (req, res) => {
+ async (req, res) => {
const {email, phone, user_id} = req.query;
await knex('waiting_list')
@@ -255,7 +250,6 @@ router.get(
res.send({success: true, message: 'Added ' + email + ' to waiting list ' + phone})
})
-);
/**
* @api {get} /isReferred/:user_id Check if user is referred
@@ -274,7 +268,7 @@ router.get(
*/
router.get(
"/isReferred/:user_id",
- ah(async (req, res) => {
+ async (req, res) => {
const { user_id } = req.params;
var referred = await knex('referrals')
@@ -288,6 +282,5 @@ router.get(
res.send({referred: false})
}
})
-);
export default router;
diff --git a/routes/send.js b/routes/send.js
index c6de3acb..7cc403e1 100644
--- a/routes/send.js
+++ b/routes/send.js
@@ -1,7 +1,10 @@
-import axios from 'axios';
-import { v4 as uuidv4 } from 'uuid';
+import { callWebhook } from "../lib/webhooks.js";
+import axios from "axios";
+import { v4 as uuidv4 } from "uuid";
+import { notify } from "../lib/notifications.js";
+import { sendLiquid } from "./liquid/send.js";
-export default ah(async (req, res, next) => {
+export default async (req, res, next) => {
let {
amount,
address,
@@ -212,4 +215,4 @@ export default ah(async (req, res, next) => {
l.error("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 e51dc4f0..f8b37cd0 100644
--- a/routes/swaps.js
+++ b/routes/swaps.js
@@ -2,7 +2,7 @@ import axios from 'axios';
import crypto from 'crypto';
import fs from 'fs';
import getAccount from '../lib/account';
-import { Op, col } from 'sequelize';
+import { Op, col } from '@sequelize/core';
import { v4 as uuidv4 } from 'uuid';
const shallow = a => {
@@ -71,8 +71,8 @@ const swap = async (user, { a1, a2, v1, v2 }) => {
{ transaction }
);
- emit(user.username, "payment", payment.get({ plain: true }));
- emit(user.username, "account", a1acc.get({ plain: true }));
+ emit(user.username, "payment", payment.get({ plain: true });
+ emit(user.username, "account", a1acc.get({ plain: true });
const orders = await db.Order.findAll(
{
@@ -123,7 +123,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => {
await order.acc1.increment({ balance: v2 }, { transaction });
await order.acc1.reload({ transaction });
- emit(order.user.username, "account", order.acc1.get({ plain: true }));
+ emit(order.user.username, "account", order.acc1.get({ plain: true });
payment = await db.Payment.create(
{
@@ -140,8 +140,8 @@ const swap = async (user, { a1, a2, v1, v2 }) => {
{ transaction }
);
- emit(user.username, "payment", payment.get({ plain: true }));
- emit(user.username, "account", a1acc.get({ plain: true }));
+ emit(user.username, "payment", payment.get({ plain: true });
+ emit(user.username, "account", a1acc.get({ plain: true });
if (order.fee) {
const btc = await getAccount(
@@ -168,10 +168,10 @@ const swap = async (user, { a1, a2, v1, v2 }) => {
await btc.increment({ balance: order.fee }, { transaction });
await btc.reload({ transaction });
- emit(order.user.username, "account", btc.get({ plain: true }));
+ emit(order.user.username, "account", btc.get({ plain: true });
}
- emit(order.user.username, "payment", payment.get({ plain: true }));
+ emit(order.user.username, "payment", payment.get({ plain: true });
order = order.get({ plain: true });
order.a1 = order.acc1.asset;
@@ -207,8 +207,8 @@ const swap = async (user, { a1, a2, v1, v2 }) => {
await a2acc.increment({ balance: order.v1 }, { transaction });
await a2acc.reload({ transaction });
- emit(user.username, "payment", payment.get({ plain: true }));
- emit(user.username, "account", a2acc.get({ plain: true }));
+ emit(user.username, "payment", payment.get({ plain: true });
+ emit(user.username, "account", a2acc.get({ plain: true });
payment = await db.Payment.create(
{
@@ -225,7 +225,7 @@ const swap = async (user, { a1, a2, v1, v2 }) => {
{ transaction }
);
- emit(order.user.username, "payment", payment.get({ plain: true }));
+ emit(order.user.username, "payment", payment.get({ plain: true });
await order.acc2.increment({ balance: order.v2 }, { transaction });
await order.acc2.reload({ transaction });
@@ -298,8 +298,8 @@ const cancel = async (user, id) => {
{ transaction }
);
- emit(user.username, "account", account.get({ plain: true }));
- emit(user.username, "payment", payment.get({ plain: true }));
+ emit(user.username, "account", account.get({ plain: true });
+ emit(user.username, "payment", payment.get({ plain: true });
if (order.fee) {
const btc = await getAccount(config.liquid.btcasset, user, transaction);
@@ -322,8 +322,8 @@ const cancel = async (user, id) => {
await btc.increment({ balance: order.fee }, { transaction });
await btc.reload({ transaction });
- emit(user.username, "account", btc.get({ plain: true }));
- emit(user.username, "payment", payment.get({ plain: true }));
+ emit(user.username, "account", btc.get({ plain: true });
+ emit(user.username, "payment", payment.get({ plain: true });
}
broadcast("removeOrder", id);
@@ -334,7 +334,7 @@ const cancel = async (user, id) => {
app.delete(
"/order/:id",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { id } = req.params;
const { user } = req;
@@ -346,7 +346,7 @@ app.delete(
app.post(
"/orders",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
return res.status(500).send("Trading temporarily disabled");
const { user } = req;
try {
@@ -362,7 +362,7 @@ app.post(
app.get(
"/orders",
optionalAuth,
- ah(async (req, res) => {
+ async (req, res) => {
try {
let orders = await db.Order.findAll({
attributes: {
diff --git a/routes/users.js b/routes/users.js
index f92c9045..f0fa8c47 100644
--- a/routes/users.js
+++ b/routes/users.js
@@ -1,19 +1,21 @@
+import { getUser } from "../lib/utils.js";
import axios from 'axios';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { authenticator } from 'otplib';
import getAccount from '../lib/account.js';
-import Sequelize from 'sequelize';
+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';
+import whitelist from "../lib/whitelist.js";
const pick = (O, ...K) => K.reduce((o, k) => ((o[k] = O[k]), o), {});
-import '../lib/whitelist.js';
-const twofa = ah((req, res, next) => {
+/*
+const twofa = (req, res, next) => {
let {
user,
body: { token }
@@ -25,12 +27,12 @@ const twofa = ah((req, res, next) => {
) {
return res.status(401).send("2fa required");
} else next();
-});
+}
app.get(
"/me",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
let user = req.user.get({ plain: true });
let payments = await req.user.getPayments({
where: {
@@ -53,11 +55,10 @@ app.get(
user.payments = payments;
res.send(user);
})
-);
app.get(
"/users/:username",
- ah(async (req, res) => {
+ async (req, res) => {
const { username } = req.params;
const user = await db.User.findOne({
@@ -71,11 +72,10 @@ app.get(
if (user) res.send(user);
else res.status(500).send("User not found");
})
-);
app.post(
"/register",
- ah(async (req, res) => {
+ async (req, res) => {
try {
const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
const user = await register(req.body.user, ip, false);
@@ -84,13 +84,12 @@ app.post(
res.status(500).send(e.message);
}
})
-);
app.post(
"/disable2fa",
auth,
twofa,
- ah(async (req, res) => {
+ async (req, res) => {
let { user } = req;
user.twofa = false;
await user.save();
@@ -99,23 +98,21 @@ app.post(
l.info("disabled 2fa", user.username);
res.send({});
})
-);
app.get(
"/otpsecret",
auth,
twofa,
- ah(async (req, res) => {
+ async (req, res) => {
let { user } = req;
emit(user.username, "otpsecret", user.otpsecret);
res.end();
})
-);
app.post(
"/2fa",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
let { user } = req;
try {
const isValid = authenticator.check(req.body.token, req.user.otpsecret);
@@ -133,23 +130,21 @@ app.post(
l.info("enabled 2fa", user.username);
res.send({});
})
-);
app.get(
"/exists",
- ah(async (req, res) => {
+ async (req, res) => {
let exists = await db.User.findOne({
where: { username: req.query.username }
});
res.send(!!exists);
})
-);
app.post(
"/user",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
try {
let { user } = req;
let {
@@ -211,12 +206,11 @@ app.post(
l.error("error updating user", e.message);
}
})
-);
app.post(
"/keys",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { key: hex } = req.body;
const key = await db.Key.create({
user_id: req.user.id,
@@ -225,12 +219,11 @@ app.post(
emit(req.user.username, "key", key);
res.send(key);
})
-);
app.post(
"/keys/delete",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { hex } = req.body;
(
await db.Key.findOne({
@@ -241,12 +234,11 @@ app.post(
})
).destroy();
})
-);
app.post(
"/updateSeeds",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
let { user } = req;
let { seeds } = req.body;
let keys = Object.keys(seeds);
@@ -270,23 +262,21 @@ app.post(
res.end();
})
-);
app.post(
"/accounts/delete",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { id } = req.body;
const account = await db.Account.findOne({ where: { id } });
if (account) await account.destroy();
res.end();
})
-);
app.post(
"/accounts",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const {
name,
seed,
@@ -324,9 +314,8 @@ app.post(
res.send(account);
})
-);
-let login = ah(async (req, res) => {
+let login = async (req, res) => {
try {
const { params, sig, key } = req.body;
@@ -383,7 +372,6 @@ let login = ah(async (req, res) => {
l.error("login error", e.message, req.connection.remoteAddress);
res.status(401).end();
}
-});
app.post("/login", login);
app.post("/taboggan", login);
@@ -392,7 +380,7 @@ app.post("/doggin", login);
app.post(
"/logout",
optionalAuth,
- ah(async (req, res) => {
+ async (req, res) => {
let { subscription } = req.body;
if (!subscription) return res.end();
@@ -414,11 +402,10 @@ app.post(
res.end();
})
-);
app.get(
"/address",
- ah(async (req, res) => {
+ async (req, res) => {
let { network, type } = req.query;
let address, confidentialAddress;
@@ -532,12 +519,11 @@ app.get(
res.send({ address, confidentialAddress });
})
-);
app.post(
"/account",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
const { user } = req;
const {
id,
@@ -590,12 +576,11 @@ app.post(
return res.status(500).send("There was a problem updating the account");
}
})
-);
app.post(
"/shiftAccount",
auth,
- ah(async (req, res) => {
+ async (req, res) => {
let { user } = req;
let { id } = req.body;
@@ -634,7 +619,6 @@ app.post(
return res.status(500).send("There was a problem switching accounts");
}
})
-);
app.get("/vapidPublicKey", function(req, res) {
res.send(config.vapid.publicKey);
@@ -643,7 +627,7 @@ app.get("/vapidPublicKey", function(req, res) {
app.post(
"/subscribe",
auth,
- ah(async function(req, res) {
+ async function(req, res) {
let { subscriptions } = req.user;
let { subscription } = req.body;
if (!subscriptions) subscriptions = [];
@@ -658,13 +642,12 @@ app.post(
await req.user.save();
res.sendStatus(201);
})
-);
let redeeming = {};
app.post(
"/redeem",
optionalAuth,
- ah(async function(req, res) {
+ async function(req, res) {
const { redeemcode } = req.body;
try {
await db.transaction(async transaction => {
@@ -755,35 +738,32 @@ app.post(
return res.status(500).send("There was a problem redeeming the voucher");
}
})
-);
app.post(
"/checkRedeemCode",
auth,
- ah(async function(req, res) {
+ async function(req, res) {
const { redeemcode } = req.body;
const payment = await db.Payment.findOne({ where: { redeemcode } });
res.send(payment);
})
-);
app.post(
"/password",
auth,
- ah(async function(req, res) {
+ async function(req, res) {
const { user } = req;
const { password } = req.body;
if (!user.password) return res.send(true);
res.send(await bcrypt.compare(password, user.password));
})
-);
app.get(
"/isInternal",
auth,
- ah(async function(req, res) {
+ async function(req, res) {
let { user } = req;
let { address } = req.query;
if (!address) throw new Error("Address not provided");
@@ -812,23 +792,21 @@ app.get(
res.send(false);
})
-);
app.get(
"/invoices",
auth,
- ah(async function(req, res) {
+ async function(req, res) {
let invoices = await db.Invoice.findAll({
where: { user_id: req.user.id }
});
res.send(invoices);
- })
-);
+ });
app.post(
"/signMessage",
auth,
- ah(async function(req, res) {
+ async function(req, res) {
let { address, message } = req.body;
let invoices = await db.Invoice.findAll({
@@ -843,4 +821,4 @@ app.post(
res.status(500).send("Address not found for user");
})
-);
+ */