Compare commits

..

No commits in common. "c4a96af5d3f7774a23531aa5e67f5f2ea96705f6" and "555601c7de8ed9acf4fd134f4faace1bda11702d" have entirely different histories.

33 changed files with 153 additions and 378 deletions

View File

@ -1,6 +1,6 @@
import { createHodlInvoice, createInvoice, parsePaymentRequest } from 'ln-service'
import { datePivot } from '@/lib/time'
import { PAID_ACTION_TERMINAL_STATES, USER_ID } from '@/lib/constants'
import { USER_ID } from '@/lib/constants'
import { createHmac } from '../resolvers/wallet'
import { Prisma } from '@prisma/client'
import * as ITEM_CREATE from './itemCreate'
@ -215,30 +215,13 @@ export async function retryPaidAction (actionType, args, context) {
}
const INVOICE_EXPIRE_SECS = 600
const MAX_PENDING_PAID_ACTIONS_PER_USER = 100
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
const { cost, models, lnd, me } = context
const { cost, models, lnd } = context
const userId = await paidActions[actionType]?.invoiceablePeer?.(args, context)
// 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')
}
if (userId) {
try {
const description = await paidActions[actionType].describe(args, context)

View File

@ -21,10 +21,8 @@ export async function getCost ({ subName, parentId, uploadIds, boost = 0, bio },
FROM image_fees_info(${me?.id || USER_ID.anon}::INTEGER, ${uploadIds}::INTEGER[]))
+ ${satsToMsats(boost)}::INTEGER as cost`
// sub allows freebies (or is a bio or a comment), cost is less than baseCost, not anon,
// cost must be greater than user's balance, and user has not disabled freebies
const freebie = (parentId || bio || sub?.allowFreebies) && cost <= baseCost && !!me &&
cost > me?.msats && !me?.disableFreebies
// sub allows freebies (or is a bio or a comment), cost is less than baseCost, not anon, and cost must be greater than user's balance
const freebie = (parentId || bio || sub?.allowFreebies) && cost <= baseCost && !!me && cost > me?.msats
return freebie ? BigInt(0) : BigInt(cost)
}

View File

@ -622,19 +622,6 @@ export default {
},
Mutation: {
disableFreebies: async (parent, args, { me, models }) => {
if (!me) {
throw new GraphQLError('you must be logged in', { extensions: { code: 'UNAUTHENTICATED' } })
}
// disable freebies if it hasn't been set yet
await models.user.update({
where: { id: me.id, disableFreebies: null },
data: { disableFreebies: true }
})
return true
},
setName: async (parent, data, { me, models }) => {
if (!me) {
throw new GraphQLError('you must be logged in', { extensions: { code: 'UNAUTHENTICATED' } })

View File

@ -32,7 +32,7 @@ function injectResolvers (resolvers) {
return await upsertWallet({
wallet: { field: w.walletField, type: w.walletType },
testCreateInvoice: (data) => w.testCreateInvoice(data, { me, models })
testConnectServer: (data) => w.testConnectServer(data, { me, models })
}, { settings, data }, { me, models })
}
}
@ -571,15 +571,15 @@ export const addWalletLog = async ({ wallet, level, message }, { models }) => {
}
async function upsertWallet (
{ wallet, testCreateInvoice }, { settings, data }, { me, models }) {
{ wallet, testConnectServer }, { settings, data }, { me, models }) {
if (!me) {
throw new GraphQLError('you must be logged in', { extensions: { code: 'UNAUTHENTICATED' } })
}
assertApiKeyNotPermitted({ me })
if (testCreateInvoice) {
if (testConnectServer) {
try {
await testCreateInvoice(data)
await testConnectServer(data)
} catch (err) {
console.error(err)
const message = 'failed to create test invoice: ' + (err.message || err.toString?.())

View File

@ -43,7 +43,6 @@ export default gql`
toggleMute(id: ID): User
generateApiKey(id: ID!): String
deleteApiKey(id: ID!): User
disableFreebies: Boolean
}
type User {
@ -73,7 +72,6 @@ export default gql`
noReferralLinks: Boolean!
fiatCurrency: String!
satsFilter: Int!
disableFreebies: Boolean
hideBookmarks: Boolean!
hideCowboyHat: Boolean!
hideGithub: Boolean!
@ -143,7 +141,6 @@ export default gql`
noReferralLinks: Boolean!
fiatCurrency: String!
satsFilter: Int!
disableFreebies: Boolean
greeterMode: Boolean!
hideBookmarks: Boolean!
hideCowboyHat: Boolean!

View File

@ -79,7 +79,7 @@ export function FeeButtonProvider ({ baseLineItems = {}, useRemoteLineItems = ()
const lines = { ...baseLineItems, ...lineItems, ...remoteLineItems }
const total = Object.values(lines).reduce((acc, { modifier }) => modifier(acc), 0)
// freebies: there's only a base cost and we don't have enough sats
const free = total === lines.baseCost?.modifier(0) && lines.baseCost?.allowFreebies && me?.privates?.sats < total && !me?.privates?.disableFreebies
const free = total === lines.baseCost?.modifier(0) && lines.baseCost?.allowFreebies && me?.privates?.sats < total
return {
lines,
merge: mergeLineItems,
@ -88,7 +88,7 @@ export function FeeButtonProvider ({ baseLineItems = {}, useRemoteLineItems = ()
setDisabled,
free
}
}, [me?.privates?.sats, me?.privates?.disableFreebies, baseLineItems, lineItems, remoteLineItems, mergeLineItems, disabled, setDisabled])
}, [me?.privates?.sats, baseLineItems, lineItems, remoteLineItems, mergeLineItems, disabled, setDisabled])
return (
<FeeButtonContext.Provider value={value}>

View File

@ -139,8 +139,7 @@ export default function useCrossposter () {
</Button>
</>,
{
onClose: () => handleSkip(),
autohide: false
onCancel: () => handleSkip()
}
)
})

View File

@ -53,7 +53,6 @@ export const ME = gql`
lnAddr
autoWithdrawMaxFeePercent
autoWithdrawThreshold
disableFreebies
}
optional {
isContributor
@ -106,7 +105,6 @@ export const SETTINGS_FIELDS = gql`
nostrRelays
wildWestMode
satsFilter
disableFreebies
nsfwMode
authMethods {
lightning

View File

@ -134,9 +134,6 @@ export const WALLET = gql`
url
invoiceKey
}
... on WalletNwc {
nwcUrlRecv
}
}
}
}
@ -170,9 +167,6 @@ export const WALLET_BY_TYPE = gql`
url
invoiceKey
}
... on WalletNwc {
nwcUrlRecv
}
}
}
}

View File

@ -3,7 +3,6 @@
export const DEFAULT_SUBS = ['bitcoin', 'nostr', 'tech', 'meta', 'jobs']
export const DEFAULT_SUBS_NO_JOBS = DEFAULT_SUBS.filter(s => s !== 'jobs')
export const PAID_ACTION_TERMINAL_STATES = ['FAILED', 'PAID', 'RETRYING']
export const NOFOLLOW_LIMIT = 1000
export const UNKNOWN_LINK_REL = 'noreferrer nofollow noopener'
export const BOOST_MULT = 5000

View File

@ -2,7 +2,6 @@ import { bech32 } from 'bech32'
import { nip19 } from 'nostr-tools'
import WebSocket from 'isomorphic-ws'
import { callWithTimeout, withTimeout } from '@/lib/time'
import crypto from 'crypto'
export const NOSTR_PUBKEY_HEX = /^[0-9a-fA-F]{64}$/
export const NOSTR_PUBKEY_BECH32 = /^npub1[02-9ac-hj-np-z]+$/
@ -30,13 +29,11 @@ export class Relay {
}
ws.onerror = function (err) {
console.error('websocket error:', err.message)
this.error = err.message
console.error('websocket error: ' + err)
this.error = err
}
this.ws = ws
this.url = relayUrl
this.error = null
}
static async connect (url, { timeout } = {}) {
@ -86,6 +83,8 @@ export class Relay {
let listener
const ackPromise = new Promise((resolve, reject) => {
ws.send(JSON.stringify(['EVENT', event]))
listener = function onmessage (msg) {
const [type, eventId, accepted, reason] = JSON.parse(msg.data)
@ -99,8 +98,6 @@ export class Relay {
}
ws.addEventListener('message', listener)
ws.send(JSON.stringify(['EVENT', event]))
})
try {
@ -115,15 +112,17 @@ export class Relay {
let listener
const ackPromise = new Promise((resolve, reject) => {
const id = crypto.randomBytes(16).toString('hex')
const id = crypto.randomUUID()
ws.send(JSON.stringify(['REQ', id, ...filter]))
const events = []
let eose = false
listener = function onmessage (msg) {
const [type, subId, event] = JSON.parse(msg.data)
const [type, eventId, event] = JSON.parse(msg.data)
if (subId !== id) return
if (eventId !== id) return
if (type === 'EVENT') {
events.push(event)
@ -151,8 +150,6 @@ export class Relay {
}
ws.addEventListener('message', listener)
ws.send(JSON.stringify(['REQ', id, ...filter]))
})
try {

View File

@ -159,33 +159,6 @@ addMethod(string, 'hex', function (msg) {
})
})
addMethod(string, 'nwcUrl', function () {
return this.test({
test: async (nwcUrl, context) => {
if (!nwcUrl) return true
// run validation in sequence to control order of errors
// inspired by https://github.com/jquense/yup/issues/851#issuecomment-1049705180
try {
await string().matches(/^nostr\+?walletconnect:\/\//, { message: 'must start with nostr+walletconnect://' }).validate(nwcUrl)
let relayUrl, walletPubkey, secret
try {
({ relayUrl, walletPubkey, secret } = parseNwcUrl(nwcUrl))
} catch {
// invalid URL error. handle as if pubkey validation failed to not confuse user.
throw new Error('pubkey must be 64 hex chars')
}
await string().required('pubkey required').trim().matches(NOSTR_PUBKEY_HEX, 'pubkey must be 64 hex chars').validate(walletPubkey)
await string().required('relay url required').trim().wss('relay must use wss://').validate(relayUrl)
await string().required('secret required').trim().matches(/^[0-9a-fA-F]{64}$/, 'secret must be 64 hex chars').validate(secret)
} catch (err) {
return context.createError({ message: err.message })
}
return true
}
})
})
const titleValidator = string().required('required').trim().max(
MAX_TITLE_LENGTH,
({ max, value }) => `-${Math.abs(max - value.length)} characters remaining`
@ -629,7 +602,6 @@ export const settingsSchema = object().shape({
diagnostics: boolean(),
noReferralLinks: boolean(),
hideIsContributor: boolean(),
disableFreebies: boolean().nullable(),
satsFilter: intValidator.required('required').min(0, 'must be at least 0').max(1000, 'must be at most 1000'),
zapUndos: intValidator.nullable().min(0, 'must be greater or equal to 0')
// exclude from cyclic analysis. see https://github.com/jquense/yup/issues/720
@ -714,22 +686,31 @@ export const lnbitsSchema = object().shape({
// see https://github.com/jquense/yup/issues/176#issuecomment-367352042
}, ['adminKey', 'invoiceKey'])
export const nwcSchema = object().shape({
nwcUrl: string().nwcUrl().when(['nwcUrlRecv'], ([nwcUrlRecv], schema) => {
if (!nwcUrlRecv) return schema.required('required if connection for receiving not set')
return schema.test({
test: nwcUrl => nwcUrl !== nwcUrlRecv,
message: 'connection for sending cannot be the same as for receiving'
export const nwcSchema = object({
nwcUrl: string()
.required('required')
.test(async (nwcUrl, context) => {
// run validation in sequence to control order of errors
// inspired by https://github.com/jquense/yup/issues/851#issuecomment-1049705180
try {
await string().required('required').validate(nwcUrl)
await string().matches(/^nostr\+?walletconnect:\/\//, { message: 'must start with nostr+walletconnect://' }).validate(nwcUrl)
let relayUrl, walletPubkey, secret
try {
({ relayUrl, walletPubkey, secret } = parseNwcUrl(nwcUrl))
} catch {
// invalid URL error. handle as if pubkey validation failed to not confuse user.
throw new Error('pubkey must be 64 hex chars')
}
await string().required('pubkey required').trim().matches(NOSTR_PUBKEY_HEX, 'pubkey must be 64 hex chars').validate(walletPubkey)
await string().required('relay url required').trim().wss('relay must use wss://').validate(relayUrl)
await string().required('secret required').trim().matches(/^[0-9a-fA-F]{64}$/, 'secret must be 64 hex chars').validate(secret)
} catch (err) {
return context.createError({ message: err.message })
}
return true
})
}),
nwcUrlRecv: string().nwcUrl().when(['nwcUrl'], ([nwcUrl], schema) => {
if (!nwcUrl) return schema.required('required if connection for sending not set')
return schema.test({
test: nwcUrlRecv => nwcUrlRecv !== nwcUrl,
message: 'connection for receiving cannot be the same as for sending'
})
})
}, ['nwcUrl', 'nwcUrlRecv'])
})
export const blinkSchema = object({
apiKey: string()

16
package-lock.json generated
View File

@ -57,7 +57,7 @@
"node-s3-url-encode": "^0.0.4",
"nodemailer": "^6.9.6",
"nostr": "^0.2.8",
"nostr-tools": "^2.7.2",
"nostr-tools": "^2.1.5",
"nprogress": "^0.2.0",
"opentimestamps": "^0.4.9",
"page-metadata-parser": "^1.1.4",
@ -3990,9 +3990,9 @@
}
},
"node_modules/@noble/ciphers": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
"integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==",
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.2.0.tgz",
"integrity": "sha512-6YBxJDAapHSdd3bLDv6x2wRPwq4QFMUaB3HvljNBUTThDd12eSm7/3F+2lnfzx2jvM+S6Nsy0jEt9QbPqSwqRw==",
"funding": {
"url": "https://paulmillr.com/funding/"
}
@ -14852,11 +14852,11 @@
}
},
"node_modules/nostr-tools": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.7.2.tgz",
"integrity": "sha512-Bq3Ug0SZFtgtL1+0wCnAe8AJtI7yx/00/a2nUug9SkhfOwlKS92Tef12iCK9FdwXw+oFZWMtRnSwcLayQso+xA==",
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.1.5.tgz",
"integrity": "sha512-Gug/j54YGQ0ewB09dZW3mS9qfXWFlcOQMlyb1MmqQsuNO/95mfNOQSBi+jZ61O++Y+jG99SzAUPFLopUsKf0MA==",
"dependencies": {
"@noble/ciphers": "^0.5.1",
"@noble/ciphers": "0.2.0",
"@noble/curves": "1.2.0",
"@noble/hashes": "1.3.1",
"@scure/base": "1.1.1",

View File

@ -62,7 +62,7 @@
"node-s3-url-encode": "^0.0.4",
"nodemailer": "^6.9.6",
"nostr": "^0.2.8",
"nostr-tools": "^2.7.2",
"nostr-tools": "^2.1.5",
"nprogress": "^0.2.0",
"opentimestamps": "^0.4.9",
"page-metadata-parser": "^1.1.4",

View File

@ -116,7 +116,6 @@ export default function Settings ({ ssrData }) {
tipRandomMin: settings?.tipRandomMin || 1,
tipRandomMax: settings?.tipRandomMax || 10,
turboTipping: settings?.turboTipping,
disableFreebies: settings?.disableFreebies,
zapUndos: settings?.zapUndos || (settings?.tipDefault ? 100 * settings.tipDefault : 2100),
zapUndosEnabled: settings?.zapUndos !== null,
fiatCurrency: settings?.fiatCurrency || 'USD',
@ -253,20 +252,6 @@ export default function Settings ({ ssrData }) {
required
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<Checkbox
label={
<div className='d-flex align-items-center'>disable freebies
<Info>
<p>Some posts and comments can be created without paying. However, that content has limited visibility.</p>
<p>If you disable freebies, you will always pay for your posts and comments and get standard visibility.</p>
<p>If you attach a sending wallet, we disable freebies for you unless you have checked/unchecked this value already.</p>
</Info>
</div>
}
name='disableFreebies'
/>
<div className='form-label'>notify me when ...</div>
<Checkbox
label='I stack sats from posts and comments'

View File

@ -1,23 +0,0 @@
-- AlterEnum
ALTER TYPE "WalletType" ADD VALUE 'NWC';
-- CreateTable
CREATE TABLE "WalletNWC" (
"int" SERIAL NOT NULL,
"walletId" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"nwcUrlRecv" TEXT NOT NULL,
CONSTRAINT "WalletNWC_pkey" PRIMARY KEY ("int")
);
-- CreateIndex
CREATE UNIQUE INDEX "WalletNWC_walletId_key" ON "WalletNWC"("walletId");
-- AddForeignKey
ALTER TABLE "WalletNWC" ADD CONSTRAINT "WalletNWC_walletId_fkey" FOREIGN KEY ("walletId") REFERENCES "Wallet"("id") ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TRIGGER wallet_nwc_as_jsonb
AFTER INSERT OR UPDATE ON "WalletNWC"
FOR EACH ROW EXECUTE PROCEDURE wallet_wallet_type_as_jsonb();

View File

@ -1,2 +0,0 @@
-- AlterTable
ALTER TABLE "users" ADD COLUMN "disableFreebies" BOOLEAN;

View File

@ -1,14 +0,0 @@
/*
Warnings:
- The primary key for the `WalletLNbits` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to drop the column `int` on the `WalletLNbits` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "WalletLNbits" RENAME COLUMN "int" TO "id";
UPDATE "Wallet"
SET wallet = to_jsonb("WalletLNbits")
FROM "WalletLNbits"
WHERE "Wallet".id = "WalletLNbits"."walletId";

View File

@ -64,7 +64,6 @@ model User {
zapUndos Int?
imgproxyOnly Boolean @default(false)
hideWalletBalance Boolean @default(false)
disableFreebies Boolean?
referrerId Int?
nostrPubkey String?
greeterMode Boolean @default(false)
@ -170,7 +169,6 @@ enum WalletType {
LND
CLN
LNBITS
NWC
}
model Wallet {
@ -195,7 +193,6 @@ model Wallet {
walletLND WalletLND?
walletCLN WalletCLN?
walletLNbits WalletLNbits?
walletNWC WalletNWC?
withdrawals Withdrawl[]
InvoiceForward InvoiceForward[]
@ -246,7 +243,7 @@ model WalletCLN {
}
model WalletLNbits {
id Int @id @default(autoincrement())
int Int @id @default(autoincrement())
walletId Int @unique
wallet Wallet @relation(fields: [walletId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
@ -255,15 +252,6 @@ model WalletLNbits {
invoiceKey String
}
model WalletNWC {
int Int @id @default(autoincrement())
walletId Int @unique
wallet Wallet @relation(fields: [walletId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
nwcUrlRecv String
}
model Mute {
muterId Int
mutedId Int

View File

@ -153,9 +153,9 @@ The badges that are shown inside the card.
A wallet that supports paying invoices must export the following properties in client.js which are only available if this wallet is imported on the client:
- `testSendPayment: async (config, context) => Promise<void>`
- `testConnectClient: async (config, context) => Promise<void>`
`testSendPayment` will be called during submit on the client to validate the configuration (that is passed as the first argument) more thoroughly than the initial validation by `fieldValidation`. It contains validation code that should only be called during submits instead of possibly on every change like `fieldValidation`.
`testConnectClient` will be called during submit on the client to validate the configuration (that is passed as the first argument) more thoroughly than the initial validation by `fieldValidation`. It contains validation code that should only be called during submits instead of possibly on every change like `fieldValidation`.
How this validation is implemented depends heavily on the wallet. For example, for NWC, this function attempts to fetch the info event from the relay specified in the connection string whereas for LNbits, it makes an HTTP request to /api/v1/wallet using the given URL and API key.
@ -167,7 +167,7 @@ The `context` argument is an object. It makes the wallet logger for this wallet
`sendPayment` will be called if a payment is required. Therefore, this function should implement the code to pay invoices from this wallet.
The first argument is the [BOLT11 payment request](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md). The `config` argument is the current configuration of this wallet (that was validated before). The `context` argument is the same as for `testSendPayment`.
The first argument is the [BOLT11 payment request](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md). The `config` argument is the current configuration of this wallet (that was validated before). The `context` argument is the same as for `testConnectClient`.
> [!IMPORTANT]
> As mentioned above, this file must exist for every wallet and at least reexport everything in index.js so make sure that the following line is included:
@ -199,17 +199,17 @@ The first argument is the [BOLT11 payment request](https://github.com/lightning/
A wallet that supports receiving must export the following properties in server.js which are only available if this wallet is imported on the server:
- `testCreateInvoice: async (config, context) => Promise<void>`
- `testConnectServer: async (config, context) => Promise<void>`
`testCreateInvoice` is called on the server during submit and can thus use server dependencies like [`ln-service`](https://github.com/alexbosworth/ln-service).
`testConnectServer` is called on the server during submit and can thus use server dependencies like [`ln-service`](https://github.com/alexbosworth/ln-service).
It should attempt to create a test invoice to make sure that this wallet can later create invoices for receiving.
Again, like `testSendPayment`, the first argument is the wallet configuration that we should validate and this should thrown an error if validation fails. However, unlike `testSendPayment`, the `context` argument here contains `me` (the user object) and `models` (the Prisma client).
Again, like `testConnectClient`, the first argument is the wallet configuration that we should validate and this should thrown an error if validation fails. However, unlike `testConnectClient`, the `context` argument here contains `me` (the user object) and `models` (the Prisma client).
- `createInvoice: async (amount: int, config, context) => Promise<bolt11: string>`
`createInvoice` will be called whenever this wallet should receive a payment. It should return a BOLT11 payment request. The first argument `amount` specifies the amount in satoshis. The second argument `config` is the current configuration of this wallet. The third argument `context` is the same as in `testCreateInvoice` except it also includes `lnd` which is the return value of [`authenticatedLndGrpc`](https://github.com/alexbosworth/ln-service?tab=readme-ov-file#authenticatedlndgrpc) using the SN node credentials.
`createInvoice` will be called whenever this wallet should receive a payment. It should return a BOLT11 payment request. The first argument `amount` specifies the amount in satoshis. The second argument `config` is the current configuration of this wallet. The third argument `context` is the same as in `testConnectServer` except it also includes `lnd` which is the return value of [`authenticatedLndGrpc`](https://github.com/alexbosworth/ln-service?tab=readme-ov-file#authenticatedlndgrpc) using the SN node credentials.
> [!IMPORTANT]

View File

@ -1,7 +1,7 @@
import { galoyBlinkUrl } from 'wallets/blink'
export * from 'wallets/blink'
export async function testSendPayment ({ apiKey, currency }, { logger }) {
export async function testConnectClient ({ apiKey, currency }, { logger }) {
currency = currency ? currency.toUpperCase() : 'BTC'
logger.info('trying to fetch ' + currency + ' wallet')
await getWallet(apiKey, currency)

View File

@ -2,7 +2,7 @@ import { createInvoice as clnCreateInvoice } from '@/lib/cln'
export * from 'wallets/cln'
export const testCreateInvoice = async ({ socket, rune, cert }) => {
export const testConnectServer = async ({ socket, rune, cert }) => {
return await createInvoice({ msats: 1000, expiry: 1, description: '' }, { socket, rune, cert })
}

View File

@ -6,7 +6,7 @@ import { SSR } from '@/lib/constants'
import { bolt11Tags } from '@/lib/bolt11'
import walletDefs from 'wallets/client'
import { gql, useApolloClient, useMutation, useQuery } from '@apollo/client'
import { gql, useApolloClient, useQuery } from '@apollo/client'
import { REMOVE_WALLET, WALLET_BY_TYPE } from '@/fragments/wallet'
import { autowithdrawInitial } from '@/components/autowithdraw-shared'
import { useShowModal } from '@/components/modal'
@ -25,7 +25,6 @@ export function useWallet (name) {
const me = useMe()
const showModal = useShowModal()
const toaster = useToast()
const [disableFreebies] = useMutation(gql`mutation { disableFreebies }`)
const wallet = name ? getWalletByName(name) : getEnabledWallet(me)
const { logger, deleteLogs } = useWalletLogger(wallet)
@ -37,7 +36,6 @@ export function useWallet (name) {
const enablePayments = useCallback(() => {
enableWallet(name, me)
logger.ok('payments enabled')
disableFreebies().catch(console.error)
}, [name, me, logger])
const disablePayments = useCallback(() => {
@ -79,7 +77,17 @@ export function useWallet (name) {
}, [wallet, config, toaster])
const save = useCallback(async (newConfig) => {
await saveConfig(newConfig, { logger })
// testConnectClient should log custom INFO and OK message
// testConnectClient is optional since validation might happen during save on server
// TODO: add timeout
let validConfig
try {
validConfig = await wallet.testConnectClient?.(newConfig, { me, logger })
} catch (err) {
logger.error(err.message)
throw err
}
await saveConfig(validConfig ?? newConfig, { logger })
}, [saveConfig, me, logger])
// delete is a reserved keyword
@ -189,17 +197,6 @@ function useConfig (wallet) {
}
if (valid) {
try {
// XXX: testSendPayment can return a new config (e.g. lnc)
const newerConfig = await wallet.testSendPayment?.(newConfig, { me, logger })
if (newerConfig) {
newClientConfig = newerConfig
}
} catch (err) {
logger.error(err.message)
throw err
}
setClientConfig(newClientConfig)
logger.ok(wallet.isConfigured ? 'payment details updated' : 'wallet attached for payments')
if (newConfig.enabled) wallet.enablePayments()
@ -236,16 +233,10 @@ function isConfigured ({ fields, config }) {
if (!config || !fields) return false
// a wallet is configured if all of its required fields are set
let val = fields.every(f => {
return f.optional ? true : !!config?.[f.name]
const val = fields.every(field => {
return field.optional ? true : !!config?.[field.name]
})
// however, a wallet is not configured if all fields are optional and none are set
// since that usually means that one of them is required
if (val && fields.length > 0) {
val = !(fields.every(f => f.optional) && fields.every(f => !config?.[f.name]))
}
return val
}

View File

@ -3,7 +3,7 @@ import { lnAddrOptions } from '@/lib/lnurl'
export * from 'wallets/lightning-address'
export const testCreateInvoice = async ({ address }) => {
export const testConnectServer = async ({ address }) => {
return await createInvoice({ msats: 1000 }, { address })
}

View File

@ -1,6 +1,6 @@
export * from 'wallets/lnbits'
export async function testSendPayment ({ url, adminKey, invoiceKey }, { logger }) {
export async function testConnectClient ({ url, adminKey, invoiceKey }, { logger }) {
logger.info('trying to fetch wallet')
url = url.replace(/\/+$/, '')

View File

@ -2,7 +2,7 @@ import { msatsToSats } from '@/lib/format'
export * from 'wallets/lnbits'
export async function testCreateInvoice ({ url, invoiceKey }) {
export async function testConnectServer ({ url, invoiceKey }) {
return await createInvoice({ msats: 1000, expiry: 1 }, { url, invoiceKey })
}

View File

@ -30,7 +30,7 @@ async function disconnect (lnc, logger) {
}
}
export async function testSendPayment (credentials, { logger }) {
export async function testConnectClient (credentials, { logger }) {
let lnc
try {
lnc = await getLNC(credentials)

View File

@ -3,7 +3,7 @@ import { authenticatedLndGrpc, createInvoice as lndCreateInvoice } from 'ln-serv
export * from 'wallets/lnd'
export const testCreateInvoice = async ({ cert, macaroon, socket }) => {
export const testConnectServer = async ({ cert, macaroon, socket }) => {
return await createInvoice({ msats: 1000, expiry: 1 }, { cert, macaroon, socket })
}

View File

@ -1,21 +1,74 @@
import { nwcCall, supportedMethods } from 'wallets/nwc'
import { parseNwcUrl } from '@/lib/url'
import { finalizeEvent, nip04 } from 'nostr-tools'
import { Relay } from '@/lib/nostr'
export * from 'wallets/nwc'
export async function testSendPayment ({ nwcUrl }, { logger }) {
const timeout = 15_000
export async function testConnectClient ({ nwcUrl }, { logger }) {
const { relayUrl, walletPubkey } = parseNwcUrl(nwcUrl)
const supported = await supportedMethods(nwcUrl, { logger, timeout })
if (!supported.includes('pay_invoice')) {
throw new Error('pay_invoice not supported')
logger.info(`requesting info event from ${relayUrl}`)
const relay = await Relay.connect(relayUrl)
logger.ok(`connected to ${relayUrl}`)
try {
const [info] = await relay.fetch([{
kinds: [13194],
authors: [walletPubkey]
}])
if (info) {
logger.ok(`received info event from ${relayUrl}`)
} else {
throw new Error('info event not found')
}
} finally {
relay?.close()
logger.info(`closed connection to ${relayUrl}`)
}
}
export async function sendPayment (bolt11, { nwcUrl }, { logger }) {
const result = await nwcCall({
nwcUrl,
method: 'pay_invoice',
params: { invoice: bolt11 }
},
{ logger })
return result.preimage
const { relayUrl, walletPubkey, secret } = parseNwcUrl(nwcUrl)
const relay = await Relay.connect(relayUrl)
logger.ok(`connected to ${relayUrl}`)
try {
const payload = {
method: 'pay_invoice',
params: { invoice: bolt11 }
}
const encrypted = await nip04.encrypt(secret, walletPubkey, JSON.stringify(payload))
const request = finalizeEvent({
kind: 23194,
created_at: Math.floor(Date.now() / 1000),
tags: [['p', walletPubkey]],
content: encrypted
}, secret)
await relay.publish(request)
const [response] = await relay.fetch([{
kinds: [23195],
authors: [walletPubkey],
'#e': [request.id]
}])
if (!response) {
throw new Error('no response')
}
const decrypted = await nip04.decrypt(secret, walletPubkey, response.content)
const content = JSON.parse(decrypted)
if (content.error) throw new Error(content.error.message)
if (content.result) return { preimage: content.result.preimage }
throw new Error('invalid response')
} finally {
relay?.close()
logger.info(`closed connection to ${relayUrl}`)
}
}

View File

@ -1,7 +1,4 @@
import { Relay } from '@/lib/nostr'
import { parseNwcUrl } from '@/lib/url'
import { nwcSchema } from '@/lib/validate'
import { finalizeEvent, nip04 } from 'nostr-tools'
export const name = 'nwc'
@ -9,80 +6,14 @@ export const fields = [
{
name: 'nwcUrl',
label: 'connection',
type: 'password',
optional: 'for sending',
clientOnly: true,
editable: false
},
{
name: 'nwcUrlRecv',
label: 'connection',
type: 'password',
optional: 'for receiving',
serverOnly: true,
editable: false
type: 'password'
}
]
export const card = {
title: 'NWC',
subtitle: 'use Nostr Wallet Connect for payments',
badges: ['send & receive', 'budgetable']
badges: ['send only', 'budgetable']
}
export const fieldValidation = nwcSchema
export const walletType = 'NWC'
export const walletField = 'walletNWC'
export async function nwcCall ({ nwcUrl, method, params }, { logger, timeout } = {}) {
const { relayUrl, walletPubkey, secret } = parseNwcUrl(nwcUrl)
const relay = await Relay.connect(relayUrl, { timeout })
logger?.ok(`connected to ${relayUrl}`)
try {
const payload = { method, params }
const encrypted = await nip04.encrypt(secret, walletPubkey, JSON.stringify(payload))
const request = finalizeEvent({
kind: 23194,
created_at: Math.floor(Date.now() / 1000),
tags: [['p', walletPubkey]],
content: encrypted
}, secret)
await relay.publish(request, { timeout })
logger?.info(`published ${method} request`)
logger?.info('waiting for response ...')
const [response] = await relay.fetch([{
kinds: [23195],
authors: [walletPubkey],
'#e': [request.id]
}], { timeout })
if (!response) {
throw new Error('no response')
}
logger?.ok('response received')
const decrypted = await nip04.decrypt(secret, walletPubkey, response.content)
const content = JSON.parse(decrypted)
if (content.error) throw new Error(content.error.message)
if (content.result) return content.result
throw new Error('invalid response')
} finally {
relay?.close()
logger?.info(`closed connection to ${relayUrl}`)
}
}
export async function supportedMethods (nwcUrl, { logger, timeout } = {}) {
const result = await nwcCall({ nwcUrl, method: 'get_info' }, { logger, timeout })
return result.methods
}

View File

@ -1,39 +0,0 @@
import { withTimeout } from '@/lib/time'
import { nwcCall, supportedMethods } from 'wallets/nwc'
export * from 'wallets/nwc'
export async function testCreateInvoice ({ nwcUrlRecv }) {
const timeout = 15_000
const supported = await supportedMethods(nwcUrlRecv, { timeout })
const supports = (method) => supported.includes(method)
if (!supports('make_invoice')) {
throw new Error('make_invoice not supported')
}
const mustNotSupport = ['pay_invoice', 'multi_pay_invoice', 'pay_keysend', 'multi_pay_keysend']
for (const method of mustNotSupport) {
if (supports(method)) {
throw new Error(`${method} must not be supported`)
}
}
return await withTimeout(createInvoice({ msats: 1000, expiry: 1 }, { nwcUrlRecv }), timeout)
}
export async function createInvoice (
{ msats, description, expiry },
{ nwcUrlRecv }) {
const result = await nwcCall({
nwcUrl: nwcUrlRecv,
method: 'make_invoice',
params: {
amount: msats,
description,
expiry
}
})
return result.invoice
}

View File

@ -2,15 +2,12 @@ import * as lnd from 'wallets/lnd/server'
import * as cln from 'wallets/cln/server'
import * as lnAddr from 'wallets/lightning-address/server'
import * as lnbits from 'wallets/lnbits/server'
import * as nwc from 'wallets/nwc/server'
import { addWalletLog } from '@/api/resolvers/wallet'
import walletDefs from 'wallets/server'
import { parsePaymentRequest } from 'ln-service'
import { toPositiveNumber } from '@/lib/validate'
import { PAID_ACTION_TERMINAL_STATES } from '@/lib/constants'
export default [lnd, cln, lnAddr, lnbits, nwc]
const MAX_PENDING_INVOICES_PER_WALLET = 25
export default [lnd, cln, lnAddr, lnbits]
export async function createInvoice (userId, { msats, description, descriptionHash, expiry = 360 }, { models }) {
// get the wallets in order of priority
@ -47,31 +44,6 @@ export async function createInvoice (userId, { msats, description, descriptionHa
throw new Error(`no ${walletType} wallet found`)
}
// check for pending withdrawals
const pendingWithdrawals = await models.withdrawl.count({
where: {
walletId: walletFull.id,
status: null
}
})
// and pending forwards
const pendingForwards = await models.invoiceForward.count({
where: {
walletId: walletFull.id,
invoice: {
actionState: {
notIn: PAID_ACTION_TERMINAL_STATES
}
}
}
})
console.log('pending invoices', pendingWithdrawals + pendingForwards)
if (pendingWithdrawals + pendingForwards >= MAX_PENDING_INVOICES_PER_WALLET) {
throw new Error('wallet has too many pending invoices')
}
const invoice = await createInvoice({
msats,
description: wallet.user.hideInvoiceDesc ? undefined : description,

View File

@ -1,6 +1,6 @@
import { getPaymentFailureStatus, hodlInvoiceCltvDetails } from '@/api/lnd'
import { paidActions } from '@/api/paidAction'
import { LND_PATHFINDING_TIMEOUT_MS, PAID_ACTION_TERMINAL_STATES } from '@/lib/constants'
import { LND_PATHFINDING_TIMEOUT_MS } from '@/lib/constants'
import { datePivot } from '@/lib/time'
import { toPositiveNumber } from '@/lib/validate'
import { Prisma } from '@prisma/client'
@ -21,7 +21,7 @@ async function transitionInvoice (jobName, { invoiceId, fromState, toState, tran
const currentDbInvoice = await models.invoice.findUnique({ where: { id: invoiceId } })
console.log('invoice is in state', currentDbInvoice.actionState)
if (PAID_ACTION_TERMINAL_STATES.includes(currentDbInvoice.actionState)) {
if (['FAILED', 'PAID', 'RETRYING'].includes(currentDbInvoice.actionState)) {
console.log('invoice is already in a terminal state, skipping transition')
return
}