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