diff --git a/src/providers/NostrProvider/index.tsx b/src/providers/NostrProvider/index.tsx index abe07063..bea0eb45 100644 --- a/src/providers/NostrProvider/index.tsx +++ b/src/providers/NostrProvider/index.tsx @@ -192,6 +192,7 @@ export function NostrProvider({ children }: { children: React.ReactNode }) { const nip07Login = async () => { try { const nip07Signer = new Nip07Signer() + await nip07Signer.init() const pubkey = await nip07Signer.getPublicKey() if (!pubkey) { throw new Error('You did not allow to access your pubkey') @@ -253,6 +254,7 @@ export function NostrProvider({ children }: { children: React.ReactNode }) { } } else if (account.signerType === 'nip-07') { const nip07Signer = new Nip07Signer() + await nip07Signer.init() return login(nip07Signer, account) } else if (account.signerType === 'bunker') { if (account.bunker && account.bunkerClientSecretKey) { diff --git a/src/providers/NostrProvider/nip-07.signer.ts b/src/providers/NostrProvider/nip-07.signer.ts index c8c5d1ac..0736bd36 100644 --- a/src/providers/NostrProvider/nip-07.signer.ts +++ b/src/providers/NostrProvider/nip-07.signer.ts @@ -1,19 +1,30 @@ import { ISigner, TDraftEvent, TNip07 } from '@/types' export class Nip07Signer implements ISigner { - private signer: TNip07 + private signer: TNip07 | undefined private pubkey: string | null = null - constructor() { - if (!window.nostr) { - throw new Error( - 'You need to install a nostr signer extension to login. Such as alby, nostr-keyx or nos2x.' - ) + async init() { + const checkInterval = 100 + const maxAttempts = 50 + + for (let attempt = 0; attempt < maxAttempts; attempt++) { + if (window.nostr) { + this.signer = window.nostr + return + } + await new Promise((resolve) => setTimeout(resolve, checkInterval)) } - this.signer = window.nostr + + throw new Error( + 'You need to install a nostr signer extension to login. Such as alby, nostr-keyx or nos2x.' + ) } async getPublicKey() { + if (!this.signer) { + throw new Error('Should call init() first') + } if (!this.pubkey) { this.pubkey = await this.signer.getPublicKey() } @@ -21,12 +32,15 @@ export class Nip07Signer implements ISigner { } async signEvent(draftEvent: TDraftEvent) { + if (!this.signer) { + throw new Error('Should call init() first') + } return await this.signer.signEvent(draftEvent) } async nip04Encrypt(pubkey: string, plainText: string) { if (!this.signer) { - throw new Error('Not logged in') + throw new Error('Should call init() first') } if (!this.signer.nip04?.encrypt) { throw new Error('The extension you are using does not support nip04 encryption') @@ -36,7 +50,7 @@ export class Nip07Signer implements ISigner { async nip04Decrypt(pubkey: string, cipherText: string) { if (!this.signer) { - throw new Error('Not logged in') + throw new Error('Should call init() first') } if (!this.signer.nip04?.decrypt) { throw new Error('The extension you are using does not support nip04 decryption')