import { fromRpcSig, ecrecover } from 'ethereumjs-util';
import { publicKeyConvert } from 'secp256k1';
import { TypedDataUtils, SignTypedDataVersion } from '@metamask/eth-sig-util';

export const recoverTypedSignaturePubKey = (
         data: any,
         signature: string
       ): string => {
         console.log('data', data);
         console.log('compare', JSON.stringify(data));
         console.log('signature', signature);
         const compressedPubKeyPrefix = Buffer.from('04', 'hex');
         console.log('compressedPubKeyPrefix', compressedPubKeyPrefix);
         const message = TypedDataUtils.eip712Hash(
           data,
           SignTypedDataVersion.V4
         );
         console.log('message', message);
         const sigParams = fromRpcSig(signature);
         console.log('sigParams', sigParams);
         const publicKey = ecrecover(
           message,
           sigParams.v,
           sigParams.r,
           sigParams.s
         );
         console.log('publicKey', publicKey);
         const prefixedKey = Buffer.concat([compressedPubKeyPrefix, publicKey]);
         console.log('prefixedKey', prefixedKey);
         const compressedKey = Buffer.from(publicKeyConvert(prefixedKey));
         console.log('compressedKey', compressedKey);
         return `0x${compressedKey.toString('hex')}`;
       };
