From 713227b2553bbf20a84bac156ab2160c7f8fde5a Mon Sep 17 00:00:00 2001 From: Keyan <34140557+huumn@users.noreply.github.com> Date: Wed, 4 Dec 2024 12:10:30 -0600 Subject: [PATCH] invite paid action (#1681) --- api/paidAction/README.md | 26 ++++--- api/paidAction/index.js | 11 ++- api/paidAction/inviteGift.js | 59 ++++++++++++++ api/resolvers/serial.js | 76 ------------------- lib/validate.js | 2 +- pages/invites/[id].js | 13 ++-- pages/invites/index.js | 1 + .../migration.sql | 8 ++ prisma/schema.prisma | 19 ++--- worker/territory.js | 11 ++- 10 files changed, 110 insertions(+), 116 deletions(-) create mode 100644 api/paidAction/inviteGift.js delete mode 100644 api/resolvers/serial.js create mode 100644 prisma/migrations/20241203235457_invite_denormalized_count/migration.sql diff --git a/api/paidAction/README.md b/api/paidAction/README.md index 13661b56f..a2f9c6904 100644 --- a/api/paidAction/README.md +++ b/api/paidAction/README.md @@ -92,18 +92,20 @@ stateDiagram-v2 ### Table of existing paid actions and their supported flows -| action | fee credits | optimistic | pessimistic | anonable | qr payable | p2p wrapped | side effects | -| ----------------- | ----------- | ---------- | ----------- | -------- | ---------- | ----------- | ------------ | -| zaps | x | x | x | x | x | x | x | -| posts | x | x | x | x | x | | x | -| comments | x | x | x | x | x | | x | -| downzaps | x | x | | | x | | x | -| poll votes | x | x | | | x | | | -| territory actions | x | | x | | x | | | -| donations | x | | x | x | x | | | -| update posts | x | | x | | x | | x | -| update comments | x | | x | | x | | x | -| receive | | x | | x | x | x | x | +| action | fee credits | optimistic | pessimistic | anonable | qr payable | p2p wrapped | side effects | reward sats | p2p direct | +| ----------------- | ----------- | ---------- | ----------- | -------- | ---------- | ----------- | ------------ | ----------- | ---------- | +| zaps | x | x | x | x | x | x | x | | | +| posts | x | x | x | x | x | | x | x | | +| comments | x | x | x | x | x | | x | x | | +| downzaps | x | x | | | x | | x | x | | +| poll votes | x | x | | | x | | | x | | +| territory actions | x | | x | | x | | | x | | +| donations | x | | x | x | x | | | x | | +| update posts | x | | x | | x | | x | x | | +| update comments | x | | x | | x | | x | x | | +| receive | | x | | | x | x | x | | x | +| buy fee credits | | | x | | x | | | x | | +| invite gift | x | | | | | | x | x | | ## Not-custodial zaps (ie p2p wrapped payments) Zaps, and possibly other future actions, can be performed peer to peer and non-custodially. This means that the payment is made directly from the client to the recipient, without the server taking custody of the funds. Currently, in order to trigger this behavior, the recipient must have a receiving wallet attached and the sender must have insufficient funds in their custodial wallet to perform the requested zap. diff --git a/api/paidAction/index.js b/api/paidAction/index.js index 834bac974..cc9ced4ae 100644 --- a/api/paidAction/index.js +++ b/api/paidAction/index.js @@ -18,6 +18,7 @@ import * as TERRITORY_UNARCHIVE from './territoryUnarchive' import * as DONATE from './donate' import * as BOOST from './boost' import * as RECEIVE from './receive' +import * as INVITE_GIFT from './inviteGift' export const paidActions = { ITEM_CREATE, @@ -31,7 +32,8 @@ export const paidActions = { TERRITORY_BILLING, TERRITORY_UNARCHIVE, DONATE, - RECEIVE + RECEIVE, + INVITE_GIFT } export default async function performPaidAction (actionType, args, incomingContext) { @@ -52,7 +54,7 @@ export default async function performPaidAction (actionType, args, incomingConte // treat context as immutable const contextWithMe = { ...incomingContext, - me: me ? await models.user.findUnique({ where: { id: me.id } }) : undefined + me: me ? await models.user.findUnique({ where: { id: parseInt(me.id) } }) : undefined } const context = { ...contextWithMe, @@ -100,7 +102,8 @@ export default async function performPaidAction (actionType, args, incomingConte } catch (e) { // if we fail with fee credits or reward sats, but not because of insufficient funds, bail console.error(`${paymentMethod} action failed`, e) - if (!e.message.includes('\\"users\\" violates check constraint \\"msats_positive\\"')) { + if (!e.message.includes('\\"users\\" violates check constraint \\"msats_positive\\"') && + !e.message.includes('\\"users\\" violates check constraint \\"mcredits_positive\\"')) { throw e } } @@ -312,7 +315,7 @@ export async function retryPaidAction (actionType, args, incomingContext) { const retryContext = { ...incomingContext, optimistic: actionOptimistic, - me: await models.user.findUnique({ where: { id: me.id } }), + me: await models.user.findUnique({ where: { id: parseInt(me.id) } }), cost: BigInt(msatsRequested), actionId } diff --git a/api/paidAction/inviteGift.js b/api/paidAction/inviteGift.js new file mode 100644 index 000000000..0cc52cae3 --- /dev/null +++ b/api/paidAction/inviteGift.js @@ -0,0 +1,59 @@ +import { PAID_ACTION_PAYMENT_METHODS } from '@/lib/constants' +import { satsToMsats } from '@/lib/format' +import { notifyInvite } from '@/lib/webPush' + +export const anonable = false + +export const paymentMethods = [ + PAID_ACTION_PAYMENT_METHODS.FEE_CREDIT +] + +export async function getCost ({ id }, { models, me }) { + const invite = await models.invite.findUnique({ where: { id, userId: me.id, revoked: false } }) + if (!invite) { + throw new Error('invite not found') + } + return satsToMsats(invite.gift) +} + +export async function perform ({ id, userId }, { me, cost, tx }) { + const invite = await tx.invite.findUnique({ + where: { id, userId: me.id, revoked: false } + }) + + if (invite.giftedCount >= invite.limit) { + throw new Error('invite limit reached') + } + + // check that user was created in last hour + // check that user did not already redeem an invite + await tx.user.update({ + where: { + id: userId, + inviteId: null, + createdAt: { + gt: new Date(Date.now() - 1000 * 60 * 60) + } + }, + data: { + msats: { + increment: cost + }, + inviteId: id, + referrerId: me.id + } + }) + + return await tx.invite.update({ + where: { id, userId: me.id, giftedCount: { lt: invite.limit }, revoked: false }, + data: { + giftedCount: { + increment: 1 + } + } + }) +} + +export async function nonCriticalSideEffects (_, { me }) { + notifyInvite(me.id) +} diff --git a/api/resolvers/serial.js b/api/resolvers/serial.js deleted file mode 100644 index 633358405..000000000 --- a/api/resolvers/serial.js +++ /dev/null @@ -1,76 +0,0 @@ -import retry from 'async-retry' -import Prisma from '@prisma/client' -import { msatsToSats, numWithUnits } from '@/lib/format' -import { BALANCE_LIMIT_MSATS } from '@/lib/constants' -import { GqlInputError } from '@/lib/error' - -export default async function serialize (trx, { models, lnd }) { - // wrap first argument in array if not array already - const isArray = Array.isArray(trx) - if (!isArray) trx = [trx] - - // conditional queries can be added inline using && syntax - // we filter any falsy value out here - trx = trx.filter(q => !!q) - - const results = await retry(async bail => { - try { - const [, ...results] = await models.$transaction( - [models.$executeRaw`SELECT ASSERT_SERIALIZED()`, ...trx], - { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }) - return results - } catch (error) { - console.log(error) - // two cases where we get insufficient funds: - // 1. plpgsql function raises - // 2. constraint violation via a prisma call - // XXX prisma does not provide a way to distinguish these cases so we - // have to check the error message - if (error.message.includes('SN_INSUFFICIENT_FUNDS') || - error.message.includes('\\"users\\" violates check constraint \\"msats_positive\\"')) { - bail(new GqlInputError('insufficient funds')) - } - if (error.message.includes('SN_NOT_SERIALIZABLE')) { - bail(new Error('wallet balance transaction is not serializable')) - } - if (error.message.includes('SN_CONFIRMED_WITHDRAWL_EXISTS')) { - bail(new Error('withdrawal invoice already confirmed (to withdraw again create a new invoice)')) - } - if (error.message.includes('SN_PENDING_WITHDRAWL_EXISTS')) { - bail(new Error('withdrawal invoice exists and is pending')) - } - if (error.message.includes('SN_INELIGIBLE')) { - bail(new Error('user ineligible for gift')) - } - if (error.message.includes('SN_UNSUPPORTED')) { - bail(new Error('unsupported action')) - } - if (error.message.includes('SN_DUPLICATE')) { - bail(new Error('duplicate not allowed')) - } - if (error.message.includes('SN_REVOKED_OR_EXHAUSTED')) { - bail(new Error('faucet has been revoked or is exhausted')) - } - if (error.message.includes('SN_INV_PENDING_LIMIT')) { - bail(new Error('too many pending invoices')) - } - if (error.message.includes('SN_INV_EXCEED_BALANCE')) { - bail(new Error(`pending invoices and withdrawals must not cause balance to exceed ${numWithUnits(msatsToSats(BALANCE_LIMIT_MSATS))}`)) - } - if (error.message.includes('40001') || error.code === 'P2034') { - throw new Error('wallet balance serialization failure - try again') - } - if (error.message.includes('23514') || ['P2002', 'P2003', 'P2004'].includes(error.code)) { - bail(new Error('constraint failure')) - } - bail(error) - } - }, { - minTimeout: 10, - maxTimeout: 100, - retries: 10 - }) - - // if first argument was not an array, unwrap the result - return isArray ? results : results[0] -} diff --git a/lib/validate.js b/lib/validate.js index 39de723bf..86b03bded 100644 --- a/lib/validate.js +++ b/lib/validate.js @@ -480,7 +480,7 @@ export const inviteSchema = object({ gift: intValidator.positive('must be greater than 0').required('required'), limit: intValidator.positive('must be positive'), description: string().trim().max(40, 'must be at most 40 characters'), - id: string().matches(/^[\w-_]+$/, 'only letters, numbers, underscores, and hyphens').min(4, 'must be at least 4 characters').max(32, 'must be at most 32 characters') + id: string().matches(/^[\w-_]+$/, 'only letters, numbers, underscores, and hyphens').min(8, 'must be at least 8 characters').max(32, 'must be at most 32 characters') }) export const pushSubscriptionSchema = object({ diff --git a/pages/invites/[id].js b/pages/invites/[id].js index c33076cf0..d7ee861fb 100644 --- a/pages/invites/[id].js +++ b/pages/invites/[id].js @@ -2,14 +2,13 @@ import Login from '@/components/login' import { getProviders } from 'next-auth/react' import { getServerSession } from 'next-auth/next' import models from '@/api/models' -import serialize from '@/api/resolvers/serial' import { gql } from '@apollo/client' import { INVITE_FIELDS } from '@/fragments/invites' import getSSRApolloClient from '@/api/ssrApollo' import Link from 'next/link' import { CenterLayout } from '@/components/layout' import { getAuthOptions } from '@/pages/api/auth/[...nextauth]' -import { notifyInvite } from '@/lib/webPush' +import performPaidAction from '@/api/paidAction' export async function getServerSideProps ({ req, res, query: { id, error = null } }) { const session = await getServerSession(req, res, getAuthOptions(req)) @@ -36,12 +35,10 @@ export async function getServerSideProps ({ req, res, query: { id, error = null try { // attempt to send gift // catch any errors and just ignore them for now - await serialize( - models.$queryRawUnsafe('SELECT invite_drain($1::INTEGER, $2::TEXT)', session.user.id, id), - { models } - ) - const invite = await models.invite.findUnique({ where: { id } }) - notifyInvite(invite.userId) + await performPaidAction('INVITE_GIFT', { + id, + userId: session.user.id + }, { models, me: { id: data.invite.user.id } }) } catch (e) { console.log(e) } diff --git a/pages/invites/index.js b/pages/invites/index.js index a7ee743d4..7692c9d2e 100644 --- a/pages/invites/index.js +++ b/pages/invites/index.js @@ -81,6 +81,7 @@ function InviteForm () { {`${process.env.NEXT_PUBLIC_URL}/invites/`}} label={<>invite code optional} + hint='leave blank for a random code that is hard to guess' name='id' autoComplete='off' /> diff --git a/prisma/migrations/20241203235457_invite_denormalized_count/migration.sql b/prisma/migrations/20241203235457_invite_denormalized_count/migration.sql new file mode 100644 index 000000000..522696754 --- /dev/null +++ b/prisma/migrations/20241203235457_invite_denormalized_count/migration.sql @@ -0,0 +1,8 @@ +-- AlterTable +ALTER TABLE "Invite" ADD COLUMN "giftedCount" INTEGER NOT NULL DEFAULT 0; + +-- denormalize giftedCount +UPDATE "Invite" +SET "giftedCount" = (SELECT COUNT(*) FROM "users" WHERE "users"."inviteId" = "Invite".id) +WHERE "Invite"."id" = "Invite".id; + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 94eac2fb4..65b6b7a36 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -467,15 +467,16 @@ model LnWith { } model Invite { - id String @id @default(cuid()) - createdAt DateTime @default(now()) @map("created_at") - updatedAt DateTime @default(now()) @updatedAt @map("updated_at") - userId Int - gift Int? - limit Int? - revoked Boolean @default(false) - user User @relation("Invites", fields: [userId], references: [id], onDelete: Cascade) - invitees User[] + id String @id @default(cuid()) + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") + userId Int + gift Int? + limit Int? + giftedCount Int @default(0) + revoked Boolean @default(false) + user User @relation("Invites", fields: [userId], references: [id], onDelete: Cascade) + invitees User[] description String? diff --git a/worker/territory.js b/worker/territory.js index e687b6125..3aa386f96 100644 --- a/worker/territory.js +++ b/worker/territory.js @@ -1,6 +1,5 @@ import lnd from '@/api/lnd' import performPaidAction from '@/api/paidAction' -import serialize from '@/api/resolvers/serial' import { PAID_ACTION_PAYMENT_METHODS } from '@/lib/constants' import { nextBillingWithGrace } from '@/lib/territory' import { datePivot } from '@/lib/time' @@ -53,8 +52,10 @@ export async function territoryBilling ({ data: { subName }, boss, models }) { } export async function territoryRevenue ({ models }) { - await serialize( - models.$executeRaw` + // this is safe nonserializable because it only acts on old data that won't + // be affected by concurrent updates ... and the update takes a lock on the + // users table + await models.$executeRaw` WITH revenue AS ( SELECT coalesce(sum(msats), 0) as revenue, "subName", "userId" FROM ( @@ -88,7 +89,5 @@ export async function territoryRevenue ({ models }) { SET msats = users.msats + "SubActResultTotal".total_msats, "stackedMsats" = users."stackedMsats" + "SubActResultTotal".total_msats FROM "SubActResultTotal" - WHERE users.id = "SubActResultTotal"."userId"`, - { models } - ) + WHERE users.id = "SubActResultTotal"."userId"` }