aboutsummaryrefslogtreecommitdiffstats
path: root/lib/db.js
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2023-11-13 01:13:55 -0800
committerAdam Soltys <[email protected]>2023-11-13 01:13:55 -0800
commit545820baa7bf625fdb4abc7ec94154049391b710 (patch)
tree61abc5a4cbc1187efa4a068e20f4d63114e9d585 /lib/db.js
parentd03320dea293fbc9a434273665fc37bc93418192 (diff)
downloadcoinos-server-545820baa7bf625fdb4abc7ec94154049391b710.tar.gz
coinos-server-545820baa7bf625fdb4abc7ec94154049391b710.zip
use lua script for debit
Diffstat (limited to 'lib/db.js')
-rw-r--r--lib/db.js37
1 files changed, 35 insertions, 2 deletions
diff --git a/lib/db.js b/lib/db.js
index b22af94a..197697a0 100644
--- a/lib/db.js
+++ b/lib/db.js
@@ -1,9 +1,42 @@
import config from "$config";
import { sleep } from "$lib/utils";
-import { createClient } from "redis";
+import { createClient, defineScript } from "redis";
import { warn } from "$lib/logging";
-export const db = createClient({ url: config.db });
+let SCRIPT = `
+local balanceKey = KEYS[1]
+local creditKey = KEYS[2]
+local amount = tonumber(ARGV[1])
+local tip = tonumber(ARGV[2])
+local fee = tonumber(ARGV[3])
+local ourfee = tonumber(ARGV[4])
+
+local balance = tonumber(redis.call('get', balanceKey) or '0')
+local credit = tonumber(redis.call('get', creditKey) or '0')
+
+local covered = math.min(credit, ourfee)
+ourfee = ourfee - covered
+
+if balance < amount + tip + fee + ourfee then
+ return {err = 'Insufficient funds'}
+end
+
+redis.call('decrby', creditKey, tostring(math.floor(covered)))
+redis.call('decrby', balanceKey, tostring(math.floor(amount + tip + fee + ourfee)))
+
+return {ok = 'ok'}
+`;
+
+let debit = defineScript({
+ NUMBER_OF_KEYS: 2,
+ SCRIPT,
+ transformArguments: (...args) => args.map(a => a.toString())
+});
+
+export const db = createClient({
+ url: config.db,
+ scripts: { debit }
+});
await db.connect();
export default db;