aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2023-03-11 10:20:46 -0800
committerAdam Soltys <[email protected]>2023-03-11 10:20:46 -0800
commit5955ff6969a5301c4413631b76cf2300d193f8ed (patch)
tree92d1269a098cb7c764ca92f7a40af9ee236ae5b1 /lib
parent7fec7cc3e7c51a9892869732b5bfe65922ee7818 (diff)
downloadcoinos-server-5955ff6969a5301c4413631b76cf2300d193f8ed.tar.gz
coinos-server-5955ff6969a5301c4413631b76cf2300d193f8ed.zip
separate tips from amounts
Diffstat (limited to 'lib')
-rw-r--r--lib/app.js17
-rw-r--r--lib/auth.js12
-rw-r--r--lib/countries.js2
-rw-r--r--lib/db.js2
-rw-r--r--lib/invoices.js4
-rw-r--r--lib/lightning.js2
-rw-r--r--lib/locations.js3
-rw-r--r--lib/nostr.js12
-rw-r--r--lib/payments.js22
-rw-r--r--lib/rates.js6
-rw-r--r--lib/register.js4
-rw-r--r--lib/rpc.js38
-rw-r--r--lib/sockets.js8
-rw-r--r--lib/store.js2
-rw-r--r--lib/upload.js11
-rw-r--r--lib/utils.js12
-rw-r--r--lib/webhooks.js4
-rw-r--r--lib/whitelist.js2
18 files changed, 78 insertions, 85 deletions
diff --git a/lib/app.js b/lib/app.js
index eaef00d1..ae1687a4 100644
--- a/lib/app.js
+++ b/lib/app.js
@@ -15,11 +15,11 @@ import { socketServer } from "$lib/sockets";
const app = fastify({
logger: pino(),
disableRequestLogging: true,
- maxParamLength: 500
+ maxParamLength: 500,
});
app.register(fastifySecureSession, {
- key: Buffer.from(config.jwt, "hex")
+ key: Buffer.from(config.jwt, "hex"),
});
app.register(fastifyPassport.initialize());
@@ -31,7 +31,7 @@ app.register(fastifyMultipart);
app.register(fastifyStatic, {
root: path.join("/app/data/uploads"),
- prefix: "/public/"
+ prefix: "/public/",
});
app.register(fastifyWs);
@@ -39,17 +39,14 @@ app.register(socketServer);
app.setErrorHandler((error, request, reply) => {
if (error instanceof fastify.errorCodes.FST_ERR_BAD_STATUS_CODE) {
- reply.status(500).send({ ok: false })
+ reply.status(500).send({ ok: false });
} else {
- reply.send(error)
+ reply.send(error);
}
-})
+});
app.setNotFoundHandler((request, reply) => {
- reply
- .code(404)
- .type("text/html")
- .send("Not Found");
+ reply.code(404).type("text/html").send("Not Found");
});
export default app;
diff --git a/lib/auth.js b/lib/auth.js
index 0533de31..d9d2a8e5 100644
--- a/lib/auth.js
+++ b/lib/auth.js
@@ -7,17 +7,17 @@ export const optional = {
preValidation: fastifyPassport.authenticate(
"jwt",
{ session: false },
- function(req, res, err, user, info) {
+ function (req, res, err, user, info) {
req.user = user;
}
- )
+ ),
};
export const auth = {
preValidation: fastifyPassport.authenticate("jwt", {
authInfo: false,
- session: false
- })
+ session: false,
+ }),
};
export const requirePin = async ({ body, user }) => {
@@ -29,9 +29,9 @@ export const jwtStrategy = new jwt.Strategy(
{
jwtFromRequest: jwt.ExtractJwt.fromExtractors([
jwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
- req => (req.cookies ? req.cookies.token : null)
+ (req) => (req.cookies ? req.cookies.token : null),
]),
- secretOrKey: config.jwt
+ secretOrKey: config.jwt,
},
async (payload, next) => {
let user;
diff --git a/lib/countries.js b/lib/countries.js
index 4d5a48dc..71bc2344 100644
--- a/lib/countries.js
+++ b/lib/countries.js
@@ -245,5 +245,5 @@ export default {
VN: "VNM",
YE: "YEM",
ZM: "ZMB",
- ZW: "ZWE"
+ ZW: "ZWE",
};
diff --git a/lib/db.js b/lib/db.js
index b22af94a..f1c15ebd 100644
--- a/lib/db.js
+++ b/lib/db.js
@@ -7,7 +7,7 @@ export const db = createClient({ url: config.db });
await db.connect();
export default db;
-export let g = async k => {
+export let g = async (k) => {
let v = await db.get(k);
try {
return JSON.parse(v);
diff --git a/lib/invoices.js b/lib/invoices.js
index 5d68d09d..95a81104 100644
--- a/lib/invoices.js
+++ b/lib/invoices.js
@@ -13,7 +13,7 @@ export let generate = async ({ invoice, user, sender, memo }) => {
let { currency, tip, amount, rate, request_id, prompt, type } = invoice;
amount = parseInt(amount || 0);
- tip = parseInt(tip || 0);
+ tip = parseInt(tip) || null;
if (amount < 0) fail("amount out of range");
@@ -54,7 +54,7 @@ export let generate = async ({ invoice, user, sender, memo }) => {
invoice = {
amount,
- created: Date.now(),
+ created: Date.now(),
currency,
hash,
rate,
diff --git a/lib/lightning.js b/lib/lightning.js
index 2915b7c7..c9b41533 100644
--- a/lib/lightning.js
+++ b/lib/lightning.js
@@ -15,7 +15,7 @@ export async function listenForLightning() {
pay_index,
status,
msatoshi_received,
- payment_preimage: preimage
+ payment_preimage: preimage,
} = event;
await s("pay_index", pay_index);
diff --git a/lib/locations.js b/lib/locations.js
index 39883555..6df50e0c 100644
--- a/lib/locations.js
+++ b/lib/locations.js
@@ -8,7 +8,8 @@ export let getLocations = async () => {
).json();
locations = locations.filter(
- l => l["osm_json"].tags && l["osm_json"].tags["payment:coinos"] === "yes"
+ (l) =>
+ l["osm_json"].tags && l["osm_json"].tags["payment:coinos"] === "yes"
);
await s("locations", locations);
diff --git a/lib/nostr.js b/lib/nostr.js
index 604d207d..2ecd1c5c 100644
--- a/lib/nostr.js
+++ b/lib/nostr.js
@@ -10,7 +10,7 @@ export let pool;
export let fillPool = () => {
pool = RelayPool(config.relays);
- pool.on("open", relay => {
+ pool.on("open", (relay) => {
if (relay.url.includes(config.nostr)) coinos = relay;
relay.subscribe("live", { limit: 1 });
});
@@ -62,7 +62,7 @@ export let fillPool = () => {
user = {
...user,
...content,
- updated: ev.created_at
+ updated: ev.created_at,
};
await s(`user:${pubkey}`, JSON.stringify(user));
@@ -112,7 +112,7 @@ export let q = async (
let done = { [sub]: [] };
- let check = s => {
+ let check = (s) => {
let elapsed = Date.now() - start;
if (rejected) return true;
if (
@@ -147,7 +147,7 @@ export let q = async (
rejected = true;
}, timeout);
},
- timer: undefined
+ timer: undefined,
};
timeouts[sub].extend();
@@ -167,14 +167,14 @@ export let q = async (
let seen = [];
-let getUser = async pubkey => {
+let getUser = async (pubkey) => {
let id = await g(`user:${pubkey}`);
let user = await g(`user:${id}`);
return (
user || {
username: pubkey.substr(0, 6),
pubkey,
- anon: true
+ anon: true,
}
);
};
diff --git a/lib/payments.js b/lib/payments.js
index ff6e9ba5..0a59a868 100644
--- a/lib/payments.js
+++ b/lib/payments.js
@@ -13,7 +13,7 @@ export const types = {
bitcoin: "bitcoin",
lightning: "lightning",
pot: "pot",
- classic: "classic"
+ classic: "classic",
};
export let debit = async (
@@ -25,7 +25,7 @@ export let debit = async (
type = types.internal,
id = v4()
) => {
- let ref, tip;
+ let ref;
let { id: uid, currency, username } = user;
let rate = store.rates[currency];
@@ -36,7 +36,7 @@ export let debit = async (
if (Math.abs(invoice.rate / rate - 1) < 0.01) rate = invoice.rate;
}
- amount = parseInt(amount);
+ let tip = parseInt(invoice?.tip) || null;
if (!amount || amount < 0) fail("Amount must be greater than zero");
@@ -54,24 +54,20 @@ export let debit = async (
user.username,
balance,
amount,
+ tip,
fee,
ourfee,
- amount + fee + ourfee
+ amount + fee + ourfee + tip
);
- if (balance < amount + fee + ourfee) fail("Insufficient funds");
+ if (balance < amount + tip + fee + ourfee) fail("Insufficient funds");
await db
.multi()
.decrBy(`credit:${type}:${uid}`, covered)
- .decrBy(`balance:${uid}`, amount + fee + ourfee)
+ .decrBy(`balance:${uid}`, amount + tip + fee + ourfee)
.exec();
});
});
- if (invoice?.tip) {
- tip = invoice.tip;
- amount -= tip;
- }
-
let p = {
id,
amount: -amount,
@@ -85,7 +81,7 @@ export let debit = async (
type,
ref,
tip,
- created: Date.now()
+ created: Date.now(),
};
await s(`payment:${id}`, p);
@@ -120,7 +116,7 @@ export let credit = async (hash, amount, memo, ref, type = types.internal) => {
ref,
type,
confirmed: true,
- created: Date.now()
+ created: Date.now(),
};
let { tip } = invoice;
diff --git a/lib/rates.js b/lib/rates.js
index 362aaa98..0b2daab2 100644
--- a/lib/rates.js
+++ b/lib/rates.js
@@ -15,11 +15,11 @@ let connect = async () => {
ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");
- ws.onmessage = async function(event) {
+ ws.onmessage = async function (event) {
try {
let msg = JSON.parse(event.data);
- Object.keys(store.fx).map(symbol => {
+ Object.keys(store.fx).map((symbol) => {
store.rates[symbol] = msg.c * store.fx[symbol];
});
@@ -31,7 +31,7 @@ let connect = async () => {
}
};
- ws.onerror = async function(error) {
+ ws.onerror = async function (error) {
err("binance socket error", error.message);
};
diff --git a/lib/register.js b/lib/register.js
index d222a363..ccf6d902 100644
--- a/lib/register.js
+++ b/lib/register.js
@@ -29,8 +29,8 @@ export default async (user, ip, requireChallenge) => {
try {
let {
location: {
- country: { code }
- }
+ country: { code },
+ },
} = await got(
`https://api.ipregistry.co/${ip}?key=${config.ipregistry}&fields=location.country.code`
).json();
diff --git a/lib/rpc.js b/lib/rpc.js
index b8a2d0dd..e8b4572c 100644
--- a/lib/rpc.js
+++ b/lib/rpc.js
@@ -4,23 +4,25 @@ export default ({ host, port, wallet, username, password }) =>
new Proxy(
{},
{
- get: (target, prop) => (...params) =>
- ((method, ...params) => {
- let url = `http://${host}:${port}/wallet/${wallet}`;
- return got
- .post(url, {
- json: {
- method,
- params
- },
- headers: {
- authorization: `Basic ${Buffer.from(
- `${username}:${password}`
- ).toString("base64")}`
- }
- })
- .json()
- .then(({ result }) => result);
- })(prop.toLowerCase(), ...params)
+ get:
+ (target, prop) =>
+ (...params) =>
+ ((method, ...params) => {
+ let url = `http://${host}:${port}/wallet/${wallet}`;
+ return got
+ .post(url, {
+ json: {
+ method,
+ params,
+ },
+ headers: {
+ authorization: `Basic ${Buffer.from(
+ `${username}:${password}`
+ ).toString("base64")}`,
+ },
+ })
+ .json()
+ .then(({ result }) => result);
+ })(prop.toLowerCase(), ...params),
}
);
diff --git a/lib/sockets.js b/lib/sockets.js
index 458c77a9..55cd642e 100644
--- a/lib/sockets.js
+++ b/lib/sockets.js
@@ -41,7 +41,7 @@ export const broadcast = (type, data) => {
}
}
- Object.values(all).map(ws => {
+ Object.values(all).map((ws) => {
if (!sent.includes(ws.id)) ws.send(JSON.stringify({ type, data }));
});
};
@@ -56,7 +56,7 @@ export async function socketServer(app) {
ws.send(JSON.stringify({ type: "connected", data: id }));
all[id] = ws;
- ws.on("message", async message => {
+ ws.on("message", async (message) => {
let type, data;
try {
({ type, data } = JSON.parse(message));
@@ -87,7 +87,7 @@ export async function socketServer(app) {
if (!store.sockets[uid]) store.sockets[uid] = {};
const existing = Object.keys(store.sockets[uid]);
if (existing.length > 4) {
- const p = existing.find(sid => sid !== uid);
+ const p = existing.find((sid) => sid !== uid);
store.sockets[uid][p].send(JSON.stringify({ type: "logout" }));
setTimeout(() => {
if (store.sockets[uid][p])
@@ -132,7 +132,7 @@ export async function socketServer(app) {
ws.on("error", console.log);
- ws.on("close", function(code, reason) {
+ ws.on("close", function (code, reason) {
try {
const uid = users[id];
if (store.sockets[uid] && store.sockets[uid][id]) {
diff --git a/lib/store.js b/lib/store.js
index bf71219e..4c86761c 100644
--- a/lib/store.js
+++ b/lib/store.js
@@ -18,5 +18,5 @@ export default {
last: {},
payments: [],
fetching: {},
- timeouts: {}
+ timeouts: {},
};
diff --git a/lib/upload.js b/lib/upload.js
index 50c26cbf..cb14f459 100644
--- a/lib/upload.js
+++ b/lib/upload.js
@@ -10,9 +10,9 @@ import { g, s, db } from "$lib/db";
export default async (req, res) => {
let {
params: { type },
- user
+ user,
} = req;
-
+
if (!["banner", "profile"].includes(type)) throw new Error("invalid upload");
let data = await req.file();
@@ -28,12 +28,9 @@ export default async (req, res) => {
let path = `/app/data/uploads/${name}`;
let size = type === "banner" ? 1920 : 240;
- let t = sharp()
- .rotate()
- .resize(size)
- .webp();
+ let t = sharp().rotate().resize(size).webp();
- await new Promise(r => pipeline(s2, t, fs.createWriteStream(path), r));
+ await new Promise((r) => pipeline(s2, t, fs.createWriteStream(path), r));
user[type] = true;
await s(`user:${user.id}`, user);
diff --git a/lib/utils.js b/lib/utils.js
index da95b5ad..929adbf1 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -4,7 +4,7 @@ import config from "$config";
export const nada = () => {};
-export const sleep = n => new Promise(r => setTimeout(r, n));
+export const sleep = (n) => new Promise((r) => setTimeout(r, n));
export const wait = async (f, s = 300, n = 50) => {
let i = 0;
while (!(await f()) && i < s) (await sleep(n)) && i++;
@@ -18,17 +18,17 @@ export const requirePin = async ({ body, user }) => {
};
export const prod = process.env.NODE_ENV === "production";
-export const fail = msg => {
+export const fail = (msg) => {
throw new Error(msg);
};
export const bail = (res, msg) => res.code(500).send(msg);
export const SATS = 100000000;
-export const sats = n => Math.round(n * SATS);
-export const btc = n => parseFloat((n / SATS).toFixed(8));
+export const sats = (n) => Math.round(n * SATS);
+export const btc = (n) => parseFloat((n / SATS).toFixed(8));
-export const uniq = (a, k) => [...new Map(a.map(x => [k(x), x])).values()];
+export const uniq = (a, k) => [...new Map(a.map((x) => [k(x), x])).values()];
export const pick = (O, K) =>
K.reduce((o, k) => (typeof O[k] !== "undefined" && (o[k] = O[k]), o), {});
@@ -58,5 +58,5 @@ export const fields = [
"haspin",
"profile",
"prompt",
- "banner"
+ "banner",
];
diff --git a/lib/webhooks.js b/lib/webhooks.js
index 1158fe9d..2ae5a890 100644
--- a/lib/webhooks.js
+++ b/lib/webhooks.js
@@ -20,8 +20,8 @@ export const callWebhook = async (invoice, payment) => {
hash,
memo,
received,
- text
- }
+ text,
+ },
}).res();
return res;
}
diff --git a/lib/whitelist.js b/lib/whitelist.js
index 9b2225e2..8f1f65ee 100644
--- a/lib/whitelist.js
+++ b/lib/whitelist.js
@@ -27,5 +27,5 @@ export default [
"theme",
"twofa",
"username",
- "verified"
+ "verified",
];