diff --git a/examples/eth-dm/src/App.tsx b/examples/eth-dm/src/App.tsx index dcad23c0e3..526178f4a5 100644 --- a/examples/eth-dm/src/App.tsx +++ b/examples/eth-dm/src/App.tsx @@ -21,16 +21,25 @@ import { SendMessage } from './SendMessage'; export const PublicKeyContentTopic = '/eth-dm/1/public-key/json'; export const DirectMessageContentTopic = '/eth-dm/1/direct-message/json'; +const EthDmKeyStorageKey = 'ethDmKey'; + declare let window: any; function App() { const [waku, setWaku] = useState(); const [provider, setProvider] = useState(); - const [ethDmKeyPair, setEthDmKeyPair] = useState(); + const [ethDmKeyPair, setEthDmKeyPair] = useState( + retrieveKeysFromStorage + ); const [publicKeyMsg, setPublicKeyMsg] = useState(); const [publicKeys, setPublicKeys] = useState>(new Map()); const [messages, setMessages] = useState([]); + useEffect(() => { + if (!ethDmKeyPair) return; + saveKeysToStorage(ethDmKeyPair); + }, [ethDmKeyPair]); + useEffect(() => { if (provider) return; try { @@ -233,3 +242,22 @@ async function handleDirectMessage( return copy; }); } + +function saveKeysToStorage(ethDmKeyPair: KeyPair) { + // /!\ Bad idea to store keys in clear. At least put a password on it. + localStorage.setItem(EthDmKeyStorageKey, ethDmKeyPair.privateKey); +} + +function retrieveKeysFromStorage() { + const privateKey = window.localStorage.getItem(EthDmKeyStorageKey); + if (privateKey) { + const publicKey = EthCrypto.publicKeyByPrivateKey(privateKey); + const address = EthCrypto.publicKey.toAddress(publicKey); + return { + privateKey, + publicKey, + address, + }; + } + return; +}