refactor(nostr): capturePublicKey from signedEvent instead of nostr api call

This commit is contained in:
enes 2024-12-31 12:10:56 +01:00
parent 1f980201dd
commit ec43324cae

View File

@ -1,9 +1,9 @@
import { EventTemplate, UnsignedEvent } from 'nostr-tools' import { EventTemplate, UnsignedEvent } from 'nostr-tools'
import { WindowNostr } from 'nostr-tools/nip07'
import { EventEmitter } from 'tseep' import { EventEmitter } from 'tseep'
import store from '../store/store' import store from '../store/store'
import { SignedEvent } from '../types' import { SignedEvent } from '../types'
import { LoginMethodContext } from '../services/LoginMethodStrategy/loginMethodContext' import { LoginMethodContext } from '../services/LoginMethodStrategy/loginMethodContext'
import { unixNow } from '../utils'
export class NostrController extends EventEmitter { export class NostrController extends EventEmitter {
private static instance: NostrController private static instance: NostrController
@ -11,13 +11,6 @@ export class NostrController extends EventEmitter {
private constructor() { private constructor() {
super() super()
} }
private getNostrObject = () => {
if (window.nostr) return window.nostr as WindowNostr
throw new Error(
`window.nostr object not present. Make sure you have an nostr extension installed/working properly.`
)
}
public static getInstance(): NostrController { public static getInstance(): NostrController {
if (!NostrController.instance) { if (!NostrController.instance) {
@ -97,23 +90,37 @@ export class NostrController extends EventEmitter {
} }
/** /**
* Function will capture the public key from the nostr extension or if no extension present * Function will capture the public key from signedEvent
* function wil capture the public key from the local storage
*/ */
capturePublicKey = async (): Promise<string> => { capturePublicKey = async (): Promise<string> => {
const nostr = this.getNostrObject() try {
const pubKey = await nostr.getPublicKey().catch((err: unknown) => { const timestamp = unixNow()
if (err instanceof Error) { const { href } = window.location
return Promise.reject(err.message)
} else { const authEvent: EventTemplate = {
return Promise.reject(JSON.stringify(err)) kind: 27235,
tags: [
['u', href],
['method', 'GET']
],
content: '',
created_at: timestamp
} }
})
if (!pubKey) { const signedAuthEvent = await this.signEvent(authEvent)
return Promise.reject('Error getting public key, user canceled') const pubkey = signedAuthEvent.pubkey
if (!pubkey) {
return Promise.reject('Error getting public key, user canceled')
}
return Promise.resolve(pubkey)
} catch (error) {
if (error instanceof Error) {
return Promise.reject(error.message)
} else {
return Promise.reject(JSON.stringify(error))
}
} }
return Promise.resolve(pubKey)
} }
} }