on 2988d5f help sign in
bridge/src/lib/authToken.js
50 lines 1.3 kB history raw
1import * as secp256k1 from 'secp256k1';
3import { keccak256, WALLET_TYPES } from './wallet';
4import { ledgerSignMessage } from './ledger';
6const MESSAGE = 'Bridge Authentication Token';
8function signMessage(privateKey) {
9 const { signature } = secp256k1.sign(
10 keccak256('\x19Ethereum Signed Message:\n' + MESSAGE.length + MESSAGE),
11 privateKey
12 );
13 // add key recovery parameter
14 const ethSignature = new Uint8Array(65);
15 ethSignature.set(signature);
16 const v = (ethSignature[32] & 1) + 27;
17 ethSignature[64] = v;
19 return ethSignature;
22function signatureToHex(v, r, s) {
23 const ethSignature = new Uint8Array(65);
24 ethSignature.set(Buffer.from(r, 'hex'));
25 ethSignature.set(Buffer.from(s, 'hex'), 32);
26 ethSignature[64] = v;
28 return `0x${Buffer.from(ethSignature).toString('hex')}`;
31export const getAuthToken = async ({
32 wallet,
33 walletType,
34 walletHdPath,
35 web3,
36}) => {
37 if (walletType === WALLET_TYPES.METAMASK) {
38 return web3.eth.personal.sign(MESSAGE, wallet.address, '');
39 }
40 if (walletType === WALLET_TYPES.LEDGER) {
41 const { v, r, s } = await ledgerSignMessage(MESSAGE, walletHdPath);
42 return signatureToHex(v, r, s);
43 }
45 const signature = signMessage(wallet.privateKey);
47 const token = `0x${Buffer.from(signature).toString('hex')}`;
49 return token;
50};