import * as ethUtil from 'ethereumjs-util' ; import { ECSignature , signatureUtils , SignerType } from '0x-v2-order-utils' ; import { utils } from 'ethers' ; type ECSignatureBuffer = { v : number ; r : Buffer ; s : Buffer ; } ; export const personalECSign = ( privateKey , msg ) : ECSignatureBuffer => { const message = ethUtil . toBuffer ( msg ) ; const msgHash = ethUtil . hashPersonalMessage ( message ) ; return ethUtil . ecsign ( msgHash , Buffer . from ( privateKey , 'hex' ) ) ; } ; export const personalSign = ( privateKey , msg ) : string => { const sig = personalECSign ( privateKey , msg ) ; return utils . joinSignature ( { v : sig . v , r : ethUtil . bufferToHex ( sig . r ) , s : ethUtil . bufferToHex ( sig . s ) , } ) ; } ; export const parseSignatureHexAsVRS = ( signatureHex ) : ECSignature => { const signatureBuffer = ethUtil . toBuffer ( signatureHex ) ; let v = signatureBuffer [ 0 ] ; if ( v < 27 ) { v += 27 ; } const r = signatureBuffer . slice ( 1 , 33 ) ; const s = signatureBuffer . slice ( 33 , 65 ) ; const ecSignature = { v , r : ethUtil . bufferToHex ( r ) , s : ethUtil . bufferToHex ( s ) , } ; return ecSignature ; } ; export const parseSignatureHexAsRSV = ( signatureHex ) : ECSignature => { const { v , r , s } = ethUtil . fromRpcSig ( signatureHex ) ; const ecSignature = { v , r : ethUtil . bufferToHex ( r ) , s : ethUtil . bufferToHex ( s ) , } ; return ecSignature ; } ; description author Xaber
 *  param signerPrivateKey param orderHash param signerAddress param signerType export const ecSignOrderHash = ( signerPrivateKey , orderHash , signerAddress , signerType ) => { let msgHashHex = orderHash ; const normalizedSignerAddress = signerAddress . toLowerCase ( ) ; const prefixedMsgHashHex = signatureUtils . addSignedMessagePrefix ( orderHash , signerType ) ; if ( signerType === SignerType . Metamask ) { msgHashHex = prefixedMsgHashHex ; } const signature = personalSign ( signerPrivateKey , msgHashHex ) ; const validVParamValues = [ 27 , 28 ] ; const ecSignatureRSV = parseSignatureHexAsRSV ( signature ) ; if ( validVParamValues . includes ( ecSignatureRSV . v ) ) { const isValidRSVSignature = signatureUtils . isValidECSignature ( prefixedMsgHashHex , ecSignatureRSV , normalizedSignerAddress ) ; if ( isValidRSVSignature ) { const convertedSignatureHex = signatureUtils . convertECSignatureToSignatureHex ( ecSignatureRSV , signerType ) ; return convertedSignatureHex ; } } const ecSignatureVRS = parseSignatureHexAsVRS ( signature ) ; if ( validVParamValues . includes ( ecSignatureVRS . v ) ) { const isValidVRSSignature = signatureUtils . isValidECSignature ( prefixedMsgHashHex , ecSignatureVRS , normalizedSignerAddress ) ; if ( isValidVRSSignature ) { const convertedSignatureHex = signatureUtils . convertECSignatureToSignatureHex ( ecSignatureVRS , signerType ) ; return convertedSignatureHex ; } } throw new Error ( 'InvalidSignature' ) ; } ;