Skip to content

Commit

Permalink
cleanup and remove logger
Browse files Browse the repository at this point in the history
  • Loading branch information
riccardobl committed Nov 14, 2024
1 parent 4df5af6 commit 1ef9b9f
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 50 deletions.
8 changes: 0 additions & 8 deletions components/use-crossposter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useCallback } from 'react'
import { useToast } from './toast'
import { Button } from 'react-bootstrap'
import Nostr, { DEFAULT_CROSSPOSTING_RELAYS } from '@/lib/nostr'
import { callWithTimeout } from '@/lib/time'
import { gql, useMutation, useQuery, useLazyQuery } from '@apollo/client'
import { SETTINGS } from '@/fragments/users'
import { ITEM_FULL_FIELDS, POLL_FIELDS } from '@/fragments/items'
Expand Down Expand Up @@ -239,13 +238,6 @@ export default function useCrossposter () {
}

const handleCrosspost = useCallback(async (itemId) => {
try {
const pubkey = await callWithTimeout(() => window.nostr.getPublicKey(), 10000)
if (!pubkey) throw new Error('failed to get pubkey')
} catch (e) {
throw new Error(`Nostr extension error: ${e.message}`)
}

let noteId

try {
Expand Down
50 changes: 11 additions & 39 deletions lib/nostr.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { bech32 } from 'bech32'
import { nip19 } from 'nostr-tools'
import createDebug from 'debug'
import NDK, { NDKEvent, NDKRelaySet, NDKPrivateKeySigner, NDKNip07Signer } from '@nostr-dev-kit/ndk'

export const NOSTR_PUBKEY_HEX = /^[0-9a-fA-F]{64}$/
Expand Down Expand Up @@ -33,9 +32,9 @@ export class Nostr {
* @type {NDK}
*/
ndk = null
signer = null
defaultSigner = null

constructor ({ privKey, signer, relays, ...ndkOptions } = {}) {
constructor ({ privKey, defaultSigner, relays, supportNip07 = true, ...ndkOptions } = {}) {
this.ndk = new NDK({
explicitRelayUrls: relays,
blacklistRelayUrls: RELAYS_BLACKLIST,
Expand All @@ -44,42 +43,15 @@ export class Nostr {
clientName: 'stacker.news',
...ndkOptions
})
this.signer = signer ?? (privKey ? new NDKPrivateKeySigner(privKey) : null)
this.defaultSigner = defaultSigner ?? (privKey ? new NDKPrivateKeySigner(privKey) : null) ?? (supportNip07 && typeof window !== 'undefined' && window?.nostr ? new NDKNip07Signer() : null)
}

/**
* @param {string} nwcUrl
* @param {Object} context
* @param {Object} context.logger
* @returns {Promise<NDKNwc>}
*/
async nwc (nwcUrl, { logger } = {}) {
const nwc = await this.ndk.nwc(nwcUrl)
if (logger) {
// inject the wallet logger
createDebug.enable('nwc')
// This is to remove the formatter for the nwc namespace
//
// I couldn't find a better way to do this, basically it is
// just to remove the colors from the logs.
// Regexes would work fine on nodejs, but the formatting for the
// the browser console is more complex
const formatArgs = createDebug.formatArgs
createDebug.formatArgs = (...args) => {
if (debug.namespace !== 'nwc') formatArgs(...args)
}

const debug = createDebug('nwc')
debug.log = (...args) => {
logger.info(args.map(a => {
if (typeof a === 'object' || Array.isArray(a)) return JSON.stringify(a)
return a.toString()
}).join(' '))
}
debug.log(`Starting with wallet service ${nwcUrl}. Debug is ${debug.enabled ? 'enabled' : 'disabled'}`)
nwc.debug = debug
}
return nwc
async nwc (nwcUrl) {
return await this.ndk.nwc(nwcUrl)
}

/**
Expand All @@ -94,21 +66,20 @@ export class Nostr {
* @returns {Promise<NDKEvent>}
*/
/* eslint-disable camelcase */
async sign ({ kind, created_at, content, tags }, { privKey, signer, signWithExtension } = {}) {
async sign ({ kind, created_at, content, tags }, { privKey, signer } = {}) {
const event = new NDKEvent(this.ndk)
event.kind = kind
event.created_at = created_at
event.content = content
event.tags = tags

signer = signer ?? (privKey ? new NDKPrivateKeySigner(privKey) : this.signer) ?? (signWithExtension ? new NDKNip07Signer() : null)
signer = signer ?? (privKey ? new NDKPrivateKeySigner(privKey) : this.defaultSigner)
if (!signer) throw new Error('no way to sign this event, please provide a signer or private key')
await event.sign(signer)
return event
}

/**
*
* @param {Object} rawEvent
* @param {number} rawEvent.kind
* @param {number} rawEvent.created_at
Expand All @@ -118,11 +89,12 @@ export class Nostr {
* @param {Array<string>} context.relays
* @param {string} context.privKey
* @param {NDKSigner} context.signer
* @param {number} context.timeout
* @returns {Promise<NDKEvent>}
*/
/* eslint-disable camelcase */
async publish ({ created_at, content, tags = [], kind }, { relays, privKey, signer, timeout, signWithExtension } = {}) {
const event = await this.sign({ kind, created_at, content, tags }, { privKey, signer, signWithExtension })
async publish ({ created_at, content, tags = [], kind }, { relays, privKey, signer, timeout } = {}) {
const event = await this.sign({ kind, created_at, content, tags }, { privKey, signer })

const successfulRelays = []
const failedRelays = []
Expand All @@ -147,7 +119,7 @@ export class Nostr {
/* eslint-disable camelcase */
async crosspost ({ created_at, content, tags = [], kind }, { relays = DEFAULT_CROSSPOSTING_RELAYS, privKey, signer, timeout } = {}) {
try {
const { event: signedEvent, successfulRelays, failedRelays } = await this.publish({ created_at, content, tags, kind }, { relays, privKey, signer, timeout, signWithExtension: true })
const { event: signedEvent, successfulRelays, failedRelays } = await this.publish({ created_at, content, tags, kind }, { relays, privKey, signer, timeout })

let noteId = null
if (signedEvent.kind !== 1) {
Expand Down
2 changes: 1 addition & 1 deletion wallets/nwc/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function testSendPayment ({ nwcUrl }, { logger }) {
}

export async function sendPayment (bolt11, { nwcUrl }, { logger }) {
const nwc = await Nostr.nwc(nwcUrl, { logger })
const nwc = await Nostr.nwc(nwcUrl)
const { error, result } = await nwc.payInvoice(bolt11)
if (error) throw new Error(error.code + ' ' + error.message)
return result.preimage
Expand Down
2 changes: 1 addition & 1 deletion wallets/nwc/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const card = {
}

export async function supportedMethods (nwcUrl, { logger, timeout } = {}) {
const nwc = await Nostr.nwc(nwcUrl, { logger })
const nwc = await Nostr.nwc(nwcUrl)
const { error, result } = await nwc.getInfo()
if (error) throw new Error(error.code + ' ' + error.message)
return result.methods
Expand Down
2 changes: 1 addition & 1 deletion wallets/nwc/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function testCreateInvoice ({ nwcUrlRecv }, { logger }) {
export async function createInvoice (
{ msats, description, expiry },
{ nwcUrlRecv }, { logger }) {
const nwc = await Nostr.nwc(nwcUrlRecv, { logger })
const nwc = await Nostr.nwc(nwcUrlRecv)
const { error, result } = await nwc.sendReq('make_invoice', { amount: msats, description, expiry })
if (error) throw new Error(error.code + ' ' + error.message)
return result.invoice
Expand Down

0 comments on commit 1ef9b9f

Please sign in to comment.