11import { useLocalStorage } from "usehooks-ts" ;
22import { HYDRA_DOOM_SESSION_KEY } from "../constants" ;
3- import { useCallback , useEffect , useState } from "react" ;
3+ import { useEffect , useState , useCallback } from "react" ;
44import { Lucid , toHex } from "lucid-cardano" ;
55import * as bech32 from "bech32-buffer" ;
66import * as ed25519 from "@noble/ed25519" ;
@@ -24,35 +24,47 @@ const useKeys = () => {
2424 ) ;
2525 const [ keys , setKeys ] = useState < Keys > ( { } ) ;
2626
27- const generateKeys = useCallback ( async ( ) => {
28- const lucid = await Lucid . new ( undefined , "Preprod" ) ;
29-
30- let key = sessionKeyBech32 ;
31- if ( ! import . meta. env . PERSISTENT_SESSION || ! sessionKeyBech32 ) {
32- console . log ( "Generating new session key" ) ;
33- key = lucid . utils . generatePrivateKey ( ) ;
34- setSessionKey ( key ) ;
35- }
36-
37- const privateKeyBytes = bech32 . decode ( key ) . data ;
38- const publicKeyBytes = await ed25519 . getPublicKeyAsync ( privateKeyBytes ) ;
39- const publicKeyHashBytes = blake2b ( publicKeyBytes , { dkLen : 224 / 8 } ) ;
40- const publicKeyHashHex = toHex ( publicKeyHashBytes ) ;
41- setKeys ( {
42- sessionKeyBech32,
43- privateKeyBytes,
44- privateKeyHex : toHex ( privateKeyBytes ) ,
45- publicKeyBytes,
46- publicKeyHex : toHex ( publicKeyBytes ) ,
47- publicKeyHashBytes,
48- publicKeyHashHex,
49- address : lucid . utils . credentialToAddress ( { type : "Key" , hash : publicKeyHashHex } )
50- } ) ;
51- } , [ sessionKeyBech32 , setSessionKey ] ) ;
27+ const generateKeys = useCallback (
28+ async ( lucid : Lucid , existingKey : string | null ) => {
29+ const key = existingKey || lucid . utils . generatePrivateKey ( ) ;
30+ if ( ! existingKey ) setSessionKey ( key ) ;
31+
32+ const privateKeyBytes = bech32 . decode ( key ) . data ;
33+ const publicKeyBytes = await ed25519 . getPublicKeyAsync ( privateKeyBytes ) ;
34+ const publicKeyHashBytes = blake2b ( publicKeyBytes , { dkLen : 224 / 8 } ) ;
35+ const publicKeyHashHex = toHex ( publicKeyHashBytes ) ;
36+
37+ return {
38+ sessionKeyBech32 : key ,
39+ privateKeyBytes,
40+ privateKeyHex : toHex ( privateKeyBytes ) ,
41+ publicKeyBytes,
42+ publicKeyHex : toHex ( publicKeyBytes ) ,
43+ publicKeyHashBytes,
44+ publicKeyHashHex,
45+ address : lucid . utils . credentialToAddress ( {
46+ type : "Key" ,
47+ hash : publicKeyHashHex ,
48+ } ) ,
49+ } ;
50+ } ,
51+ [ setSessionKey ] ,
52+ ) ;
5253
5354 useEffect ( ( ) => {
54- generateKeys ( ) ;
55- } , [ generateKeys , sessionKeyBech32 ] ) ;
55+ const initKeys = async ( ) => {
56+ const lucid = await Lucid . new ( undefined , "Preprod" ) ;
57+
58+ if ( ! keys . sessionKeyBech32 ) {
59+ const newKeys = await generateKeys ( lucid , sessionKeyBech32 ) ;
60+ setKeys ( newKeys ) ;
61+ }
62+ } ;
63+
64+ initKeys ( ) ;
65+ } , [ keys . sessionKeyBech32 , sessionKeyBech32 , generateKeys ] ) ;
66+
67+ console . log ( "keys" , keys ) ;
5668
5769 return keys ;
5870} ;
0 commit comments