add ndk provider

This commit is contained in:
Ren Amamiya
2023-07-09 07:21:41 +07:00
parent 0109ec28c4
commit 24807b2758
26 changed files with 178 additions and 106 deletions

View File

@@ -5,9 +5,8 @@ import NDK, {
NDKKind,
NDKPrivateKeySigner,
} from '@nostr-dev-kit/ndk';
import { useContext } from 'react';
import { RelayContext } from '@shared/relayProvider';
import { useNDK } from '@libs/ndk/provider';
import { FULL_RELAYS } from '@stores/constants';
@@ -46,34 +45,3 @@ export async function prefetchEvents(
});
});
}
export function usePublish() {
const ndk = useContext(RelayContext);
const { account } = useAccount();
const publish = async ({
content,
kind,
tags,
}: {
content: string;
kind: NDKKind;
tags: string[][];
}): Promise<NDKEvent> => {
const event = new NDKEvent(ndk);
const signer = new NDKPrivateKeySigner(account.privkey);
event.content = content;
event.kind = kind;
event.created_at = Math.floor(Date.now() / 1000);
event.pubkey = account.pubkey;
event.tags = tags;
await event.sign(signer);
await event.publish();
return event;
};
return publish;
}

36
src/libs/ndk/instance.ts Normal file
View File

@@ -0,0 +1,36 @@
// source: https://github.com/nostr-dev-kit/ndk-react/
import NDK from '@nostr-dev-kit/ndk';
import { useEffect, useState } from 'react';
import { getSetting } from '@libs/storage';
const setting = await getSetting('relays');
const relays = JSON.parse(setting);
export const NDKInstance = () => {
const [ndk, setNDK] = useState<NDK | undefined>(undefined);
const [relayUrls, setRelayUrls] = useState<string[]>(relays);
useEffect(() => {
loadNdk(relays);
}, []);
async function loadNdk(explicitRelayUrls: string[]) {
const ndkInstance = new NDK({ explicitRelayUrls });
try {
await ndkInstance.connect();
} catch (error) {
console.error('ERROR loading NDK NDKInstance', error);
}
setNDK(ndkInstance);
setRelayUrls(explicitRelayUrls);
}
return {
ndk,
relayUrls,
loadNdk,
};
};

44
src/libs/ndk/provider.tsx Normal file
View File

@@ -0,0 +1,44 @@
// source: https://github.com/nostr-dev-kit/ndk-react/
import NDK from '@nostr-dev-kit/ndk';
import { PropsWithChildren, createContext, useContext } from 'react';
import { NDKInstance } from '@libs/ndk/instance';
interface NDKContext {
ndk: NDK;
relayUrls: string[];
loadNdk: (_: string[]) => void;
}
const NDKContext = createContext<NDKContext>({
ndk: new NDK({}),
relayUrls: [],
loadNdk: undefined,
});
const NDKProvider = ({ children }: PropsWithChildren<object>) => {
const { ndk, relayUrls, loadNdk } = NDKInstance();
if (ndk)
return (
<NDKContext.Provider
value={{
ndk,
relayUrls,
loadNdk,
}}
>
{children}
</NDKContext.Provider>
);
};
const useNDK = () => {
const context = useContext(NDKContext);
if (context === undefined) {
throw new Error('import NDKProvider to use useNDK');
}
return context;
};
export { NDKProvider, useNDK };