import { getPublicKey, nip19 } from 'nostr-tools'; import { useEffect, useState } from 'react'; import { Resolver, useForm } from 'react-hook-form'; import { useNavigate } from 'react-router-dom'; import { useStorage } from '@libs/storage/provider'; import { EyeOffIcon, EyeOnIcon, LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon } from '@shared/icons/arrowRightCircle'; 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 navigate = useNavigate(); const setPrivkey = useStronghold((state) => state.setPrivkey); const setTempPubkey = useOnboarding((state) => state.setTempPrivkey); const setPubkey = useOnboarding((state) => state.setPubkey); const setStep = useOnboarding((state) => state.setStep); const [loading, setLoading] = useState(false); const [passwordInput, setPasswordInput] = useState('password'); const { db } = useStorage(); 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); setPrivkey(privkey); setTempPubkey(privkey); // only use if user close app and reopen it setPubkey(pubkey); // add account to local database await db.createAccount(npub, pubkey); // redirect to step 2 with delay 1.2s setTimeout(() => navigate('/auth/import/step-2', { replace: true }), 1200); } } catch (error) { setLoading(false); setError('privkey', { type: 'custom', message: 'Private key is invalid, please check again', }); } }; // toggle private key const showPassword = () => { if (passwordInput === 'password') { setPasswordInput('text'); } else { setPasswordInput('password'); } }; useEffect(() => { // save current step, if user close app and reopen it setStep('/auth/import'); }, []); return (

Import your Nostr key

{errors.privkey &&

{errors.privkey.message}

}
); }