import { useCallback , useEffect , useState } from "react" ; import { Keypair } from "@solana/web3.js" ; export function useLocalStorageState < T > ( key , defaultState ? ) { const [ state , setState ] = useState < T > ( ( ) => { const storedState = localStorage . getItem ( key ) ; if ( storedState ) return JSON . parse ( storedState ) ; return defaultState ; } ) ; const setLocalStorageState = useCallback ( ( newState ) => { const changed = state !== newState ; if ( ! changed ) return ; setState ( newState ) ; if ( newState === null ) { localStorage . removeItem ( key ) ; } else { localStorage . setItem ( key , JSON . stringify ( newState ) ) ; } } , [ state , key ] ) ; return [ state , setLocalStorageState ] ; } export function useLocalStorageKey ( name , defaultState ) { const serialise = ( k ) => JSON . stringify ( [ ... ( k . secretKey ) ] ) ; const deserialise = ( keyString ) : Keypair => Keypair . fromSecretKey ( Buffer . from ( JSON . parse ( keyString ) ) ) ; const [ keyString , setKeystring ] = useLocalStorageState < string > ( name ) ; const [ key ] = useState < Keypair > ( keyString ? deserialise ( keyString ) : defaultState ) ; const setLocalStorageKey = useCallback ( ( newKey ) => { setKeystring ( serialise ( newKey ) ) ; } , [ setKeystring ] ) ; useEffect ( ( ) => { if ( ! keyString && defaultState ) { setLocalStorageKey ( defaultState ) ; } } , [ keyString , defaultState , setLocalStorageKey ] ) ; return [ key , setLocalStorageKey ] ; }