aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contracts/src/utils/signing_utils.ts
blob: 61ab1f13803ae3784896e9f8cf849e0f83a814c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import * as ethUtil from 'ethereumjs-util';

import { SignatureType } from './types';

export const signingUtils = {
    signMessage(message: Buffer, privateKey: Buffer, signatureType: SignatureType): Buffer {
        if (signatureType === SignatureType.Ecrecover) {
            const prefixedMessage = ethUtil.hashPersonalMessage(message);
            const ecSignature = ethUtil.ecsign(prefixedMessage, privateKey);
            const signature = Buffer.concat([
                ethUtil.toBuffer(signatureType),
                ethUtil.toBuffer(ecSignature.v),
                ecSignature.r,
                ecSignature.s,
            ]);
            return signature;
        } else if (signatureType === SignatureType.EIP712) {
            const ecSignature = ethUtil.ecsign(message, privateKey);
            const signature = Buffer.concat([
                ethUtil.toBuffer(signatureType),
                ethUtil.toBuffer(ecSignature.v),
                ecSignature.r,
                ecSignature.s,
            ]);
            return signature;
        } else {
            throw new Error(`${signatureType} is not a valid signature type`);
        }
    },
};