import { useMutation, useQueryClient } from '@tanstack/react-query'; import { getPublicKey, nip19 } from 'nostr-tools'; import { useState } from 'react'; import { Resolver, useForm } from 'react-hook-form'; import { useNavigate } from 'react-router-dom'; import { createAccount } from '@libs/storage'; import { LoaderIcon } from '@shared/icons'; import { useOnboarding } from '@stores/onboarding'; import { useStronghold } from '@stores/stronghold'; type FormValues = { privkey: string; }; const resolver: Resolver = async (values) => { return { values: values.privkey ? values : {}, errors: !values.privkey ? { privkey: { type: 'required', message: 'This is required.', }, } : {}, }; }; export function ImportStep1Screen() { const queryClient = useQueryClient(); const navigate = useNavigate(); const setPrivkey = useStronghold((state) => state.setPrivkey); const setPubkey = useOnboarding((state) => state.setPubkey); const [loading, setLoading] = useState(false); const account = useMutation({ mutationFn: (data: { npub: string; pubkey: string; follows: null | string[]; is_active: number | boolean; }) => { return createAccount(data.npub, data.pubkey, null, 1); }, onSuccess: (data) => { queryClient.setQueryData(['currentAccount'], data); }, }); const { register, setError, handleSubmit, formState: { errors, isDirty, isValid }, } = useForm({ resolver }); const onSubmit = async (data: { [x: string]: string }) => { try { setLoading(true); let privkey = data['privkey']; if (privkey.substring(0, 4) === 'nsec') { privkey = nip19.decode(privkey).data as string; } if (typeof getPublicKey(privkey) === 'string') { const pubkey = getPublicKey(privkey); const npub = nip19.npubEncode(pubkey); // use for onboarding process only setPubkey(pubkey); // add stronghold state setPrivkey(privkey); // add account to local database account.mutate({ npub, pubkey, follows: null, is_active: 1, }); // redirect to step 2 setTimeout(() => navigate('/auth/import/step-2', { replace: true }), 1200); } } catch (error) { setError('privkey', { type: 'custom', message: 'Private Key is invalid, please check again', }); } }; return (

Import your key

Private key {errors.privkey &&

{errors.privkey.message}

}
); }