Skip to content

Commit

Permalink
order all zap recipients
Browse files Browse the repository at this point in the history
  • Loading branch information
huumn committed Jul 26, 2024
1 parent 3d1f783 commit 4964e2c
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions api/paidAction/zap.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,23 +74,22 @@ export async function onPaid ({ invoice, actIds }, { models, tx }) {
SELECT "userId", ((${itemAct.msats}::BIGINT * pct) / 100)::BIGINT AS msats
FROM "ItemForward"
WHERE "itemId" = ${itemAct.itemId}::INTEGER
ORDER BY "userId" ASC -- order to prevent deadlocks
), total_forwarded AS (
SELECT COALESCE(SUM(msats), 0) as msats
FROM forwardees
), forward AS (
UPDATE users
SET
msats = users.msats + forwardees.msats,
"stackedMsats" = users."stackedMsats" + forwardees.msats
FROM forwardees
WHERE users.id = forwardees."userId"
), recipients AS (
SELECT "userId", msats FROM forwardees
UNION
SELECT ${itemAct.item.userId}::INTEGER as "userId",
${itemAct.msats}::BIGINT - (SELECT msats FROM total_forwarded)::BIGINT as msats
ORDER BY "userId" ASC -- order to prevent deadlocks
)
UPDATE users
SET
msats = msats + ${itemAct.msats}::BIGINT - (SELECT msats FROM total_forwarded)::BIGINT,
"stackedMsats" = "stackedMsats" + ${itemAct.msats}::BIGINT - (SELECT msats FROM total_forwarded)::BIGINT
WHERE id = ${itemAct.item.userId}::INTEGER`
msats = users.msats + recipients.msats,
"stackedMsats" = users."stackedMsats" + recipients.msats
FROM recipients
WHERE users.id = recipients."userId"`

// perform denomormalized aggregates: weighted votes, upvotes, msats, lastZapAt
// NOTE: for the rows that might be updated by a concurrent zap, we use UPDATE for implicit locking
Expand Down

0 comments on commit 4964e2c

Please sign in to comment.