stacker.news/api/paidAction/index.js

355 lines
11 KiB
JavaScript
Raw Normal View History

not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
import { createHodlInvoice, createInvoice, parsePaymentRequest } from 'ln-service'
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
import { datePivot } from '@/lib/time'
2024-08-21 19:45:51 +00:00
import { PAID_ACTION_TERMINAL_STATES, USER_ID } from '@/lib/constants'
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
import { createHmac } from '../resolvers/wallet'
import { Prisma } from '@prisma/client'
import * as ITEM_CREATE from './itemCreate'
import * as ITEM_UPDATE from './itemUpdate'
import * as ZAP from './zap'
import * as DOWN_ZAP from './downZap'
import * as POLL_VOTE from './pollVote'
import * as TERRITORY_CREATE from './territoryCreate'
import * as TERRITORY_UPDATE from './territoryUpdate'
import * as TERRITORY_BILLING from './territoryBilling'
import * as TERRITORY_UNARCHIVE from './territoryUnarchive'
import * as DONATE from './donate'
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
import wrapInvoice from 'wallets/wrap'
import { createInvoice as createUserInvoice } from 'wallets/server'
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
export const paidActions = {
ITEM_CREATE,
ITEM_UPDATE,
ZAP,
DOWN_ZAP,
POLL_VOTE,
TERRITORY_CREATE,
TERRITORY_UPDATE,
TERRITORY_BILLING,
TERRITORY_UNARCHIVE,
DONATE
}
export default async function performPaidAction (actionType, args, context) {
try {
const { me, models, forceFeeCredits } = context
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
const paidAction = paidActions[actionType]
console.group('performPaidAction', actionType, args)
if (!paidAction) {
throw new Error(`Invalid action type ${actionType}`)
}
context.me = me ? await models.user.findUnique({ where: { id: me.id } }) : undefined
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
context.cost = await paidAction.getCost(args, context)
if (!me) {
if (!paidAction.anonable) {
throw new Error('You must be logged in to perform this action')
}
console.log('we are anon so can only perform pessimistic action')
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
return await performPessimisticAction(actionType, args, context)
}
const isRich = context.cost <= context.me.msats
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
if (isRich) {
try {
console.log('enough fee credits available, performing fee credit action')
return await performFeeCreditAction(actionType, args, context)
} catch (e) {
console.error('fee credit action failed', e)
// if we fail with fee credits, but not because of insufficient funds, bail
if (!e.message.includes('\\"users\\" violates check constraint \\"msats_positive\\"')) {
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
throw e
}
}
}
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
// this is set if the worker executes a paid action in behalf of a user.
// in that case, only payment via fee credits is possible
// since there is no client to which we could send an invoice.
// example: automated territory billing
if (forceFeeCredits) {
throw new Error('forceFeeCredits is set, but user does not have enough fee credits')
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
}
// if we fail to do the action with fee credits, we should fall back to optimistic
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
if (paidAction.supportsOptimism) {
console.log('performing optimistic action')
return await performOptimisticAction(actionType, args, context)
}
console.error('action does not support optimism and fee credits failed, performing pessimistic action')
return await performPessimisticAction(actionType, args, context)
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
} catch (e) {
console.error('performPaidAction failed', e)
throw e
} finally {
console.groupEnd()
}
}
async function performFeeCreditAction (actionType, args, context) {
const { me, models, cost } = context
const action = paidActions[actionType]
return await models.$transaction(async tx => {
context.tx = tx
await tx.user.update({
where: {
id: me.id
},
data: {
msats: {
decrement: cost
}
}
})
const result = await action.perform(args, context)
await action.onPaid?.(result, context)
return {
result,
paymentMethod: 'FEE_CREDIT'
}
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
}
async function performOptimisticAction (actionType, args, context) {
const { models } = context
const action = paidActions[actionType]
context.optimistic = true
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const invoiceArgs = await createLightningInvoice(actionType, args, context)
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
return await models.$transaction(async tx => {
context.tx = tx
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const invoice = await createDbInvoice(actionType, args, context, invoiceArgs)
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
return {
invoice,
result: await action.perform?.({ invoiceId: invoice.id, ...args }, context),
paymentMethod: 'OPTIMISTIC'
}
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
}
async function performPessimisticAction (actionType, args, context) {
const action = paidActions[actionType]
if (!action.supportsPessimism) {
throw new Error(`This action ${actionType} does not support pessimistic invoicing`)
}
// just create the invoice and complete action when it's paid
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const invoiceArgs = await createLightningInvoice(actionType, args, context)
return {
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
invoice: await createDbInvoice(actionType, args, context, invoiceArgs),
paymentMethod: 'PESSIMISTIC'
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
}
}
export async function retryPaidAction (actionType, args, context) {
const { models, me } = context
const { invoiceId } = args
console.log('retryPaidAction', actionType, args)
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
const action = paidActions[actionType]
if (!action) {
throw new Error(`retryPaidAction - invalid action type ${actionType}`)
}
if (!me) {
throw new Error(`retryPaidAction - must be logged in ${actionType}`)
}
if (!action.supportsOptimism) {
throw new Error(`retryPaidAction - action does not support optimism ${actionType}`)
}
if (!action.retry) {
throw new Error(`retryPaidAction - action does not support retrying ${actionType}`)
}
if (!invoiceId) {
throw new Error(`retryPaidAction - missing invoiceId ${actionType}`)
}
context.optimistic = true
context.me = await models.user.findUnique({ where: { id: me.id } })
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const { msatsRequested, actionId } = await models.invoice.findUnique({ where: { id: invoiceId, actionState: 'FAILED' } })
context.cost = BigInt(msatsRequested)
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
context.actionId = actionId
const invoiceArgs = await createSNInvoice(actionType, args, context)
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
return await models.$transaction(async tx => {
context.tx = tx
// update the old invoice to RETRYING, so that it's not confused with FAILED
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
await tx.invoice.update({
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
where: {
id: invoiceId,
actionState: 'FAILED'
},
data: {
actionState: 'RETRYING'
}
})
// create a new invoice
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const invoice = await createDbInvoice(actionType, args, context, invoiceArgs)
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
return {
result: await action.retry({ invoiceId, newInvoiceId: invoice.id }, context),
invoice,
paymentMethod: 'OPTIMISTIC'
}
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
}
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const INVOICE_EXPIRE_SECS = 600
2024-08-21 19:45:51 +00:00
const MAX_PENDING_PAID_ACTIONS_PER_USER = 100
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
export async function createLightningInvoice (actionType, args, context) {
// if the action has an invoiceable peer, we'll create a peer invoice
// wrap it, and return the wrapped invoice
2024-08-21 19:45:51 +00:00
const { cost, models, lnd, me } = context
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const userId = await paidActions[actionType]?.invoiceablePeer?.(args, context)
2024-08-21 19:45:51 +00:00
// count pending invoices and bail if we're over the limit
const pendingInvoices = await models.invoice.count({
where: {
userId: me?.id ?? USER_ID.anon,
actionState: {
// not in a terminal state. Note: null isn't counted by prisma
notIn: PAID_ACTION_TERMINAL_STATES
}
}
})
console.log('pending paid actions', pendingInvoices)
if (pendingInvoices >= MAX_PENDING_PAID_ACTIONS_PER_USER) {
throw new Error('You have too many pending paid actions, cancel some or wait for them to expire')
}
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
if (userId) {
try {
const description = await paidActions[actionType].describe(args, context)
const { invoice: bolt11, wallet } = await createUserInvoice(userId, {
// this is the amount the stacker will receive, the other 1/10th is the fee
msats: cost * BigInt(9) / BigInt(10),
description,
expiry: INVOICE_EXPIRE_SECS
}, { models })
const { invoice: wrappedInvoice, maxFee } = await wrapInvoice(
bolt11, { msats: cost, description }, { lnd })
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
return {
bolt11,
wrappedBolt11: wrappedInvoice.request,
wallet,
maxFee
}
} catch (e) {
console.error('failed to create stacker invoice, falling back to SN invoice', e)
}
}
return await createSNInvoice(actionType, args, context)
}
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
// we seperate the invoice creation into two functions because
// because if lnd is slow, it'll timeout the interactive tx
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
async function createSNInvoice (actionType, args, context) {
const { me, lnd, cost, optimistic } = context
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
const action = paidActions[actionType]
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const createLNDInvoice = optimistic ? createInvoice : createHodlInvoice
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
if (cost < 1000n) {
// sanity check
throw new Error('The cost of the action must be at least 1 sat')
}
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const expiresAt = datePivot(new Date(), { seconds: INVOICE_EXPIRE_SECS })
const invoice = await createLNDInvoice({
description: me?.hideInvoiceDesc ? undefined : await action.describe(args, context),
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
lnd,
mtokens: String(cost),
expires_at: expiresAt
})
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
return { bolt11: invoice.request, preimage: invoice.secret }
}
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
async function createDbInvoice (actionType, args, context,
{ bolt11, wrappedBolt11, preimage, wallet, maxFee }) {
const { me, models, tx, cost, optimistic, actionId } = context
const db = tx ?? models
if (cost < 1000n) {
// sanity check
throw new Error('The cost of the action must be at least 1 sat')
}
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
const servedBolt11 = wrappedBolt11 ?? bolt11
const servedInvoice = parsePaymentRequest({ request: servedBolt11 })
const expiresAt = new Date(servedInvoice.expires_at)
const invoiceData = {
hash: servedInvoice.id,
msatsRequested: BigInt(servedInvoice.mtokens),
preimage: optimistic ? undefined : preimage,
bolt11: servedBolt11,
userId: me?.id ?? USER_ID.anon,
actionType,
actionState: wrappedBolt11 ? 'PENDING_HELD' : optimistic ? 'PENDING' : 'PENDING_HELD',
actionOptimistic: optimistic,
actionArgs: args,
expiresAt,
actionId
}
let invoice
if (wrappedBolt11) {
invoice = (await db.invoiceForward.create({
include: { invoice: true },
data: {
bolt11,
maxFeeMsats: maxFee,
invoice: {
create: invoiceData
},
wallet: {
connect: {
id: wallet.id
}
}
}
})).invoice
} else {
invoice = await db.invoice.create({ data: invoiceData })
}
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
// insert a job to check the invoice after it's set to expire
await db.$executeRaw`
INSERT INTO pgboss.job (name, data, retrylimit, retrybackoff, startafter, expirein, priority)
VALUES ('checkInvoice',
not-custodial zap beta (#1178) * not-custodial zap scaffolding * invoice forward state machine * small refinements to state machine * make wrap invoice work * get state machine working end to end * untested logic layout for paidAction invoice wraps * perform pessimisitic actions before outgoing payment * working end to end * remove unneeded params from wallets/server/createInvoice * fix cltv relative/absolute confusion + cancelling forwards * small refinements * add p2p wrap info to paidAction docs * fallback to SN invoice when wrap fails * fix paidAction retry description * consistent naming scheme for state machine * refinements * have sn pay bounded outbound fee * remove debug logging * reenable lnc permissions checks * don't p2p zap on item forward splits * make createInvoice params json encodeable * direct -> p2p badge on notifications * allow no tls in dev for core lightning * fix autowithdraw to create invoice with msats * fix autowithdraw msats/sats inconsitency * label p2p zaps properly in satistics * add fees to autowithdrawal notifications * add RETRYING as terminal paid action state * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * Update api/lnd/index.js Co-authored-by: ekzyis <ek@stacker.news> * ek suggestions * add bugetable to nwc card * get paranoid with numbers * better finalize retries and better max timeout height * refine forward failure transitions * more accurate satistics p2p status * make sure paidaction cancel in state machine only * dont drop bolt11s unless status is not null * only allow PENDING_HELD to transition to FORWARDING * add mermaid state machine diagrams to paid action doc * fix cancel transition name * cleanup readme * move forwarding outside of transition * refine testServerConnect and make sure ensureB64 transforms * remove unused params from testServerConnect --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: k00b <k00b@stacker.news>
2024-08-13 14:48:30 +00:00
jsonb_build_object('hash', ${invoice.hash}::TEXT), 21, true,
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
${expiresAt}::TIMESTAMP WITH TIME ZONE,
${expiresAt}::TIMESTAMP WITH TIME ZONE - now() + interval '10m', 100)`
// the HMAC is only returned during invoice creation
// this makes sure that only the person who created this invoice
// has access to the HMAC
invoice.hmac = createHmac(invoice.hash)
return invoice
}