on 91efb05 help sign in
bridge/src/lib/trezor.ts
55 lines 1.4 kB history raw
1import TrezorConnect from 'trezor-connect';
2import { convertToInt } from './convertToInt';
3import BN from 'bn.js';
5const TREZOR_PATH = "m/44'/60'/0'/0/x";
7// handles 0x-prefixed hex string as well as number type
8const formatChainId = val =>
9 typeof val === 'number' ? val : convertToInt(val.slice(2), 16);
11const trezorSignTransaction = async (txn, hdpath) => {
12 const trezorFormattedTxn = {
13 to: txn.to.toString('hex'),
14 value: txn.value.toString('hex'),
15 data: txn.data.toString('hex'),
16 gasLimit: txn.gasLimit.toString('hex'),
17 gasPrice: txn.gasPrice.toString('hex'),
18 nonce: txn.nonce.length === 0 ? '00' : txn.nonce.toString('hex'),
19 chainId: formatChainId(txn.common.chainId()),
20 };
22 const sig = await TrezorConnect.ethereumSignTransaction({
23 path: hdpath,
24 transaction: trezorFormattedTxn,
25 });
27 if (!sig.success) {
28 throw new Error(sig.payload.error);
29 }
31 const payload = sig.payload;
33 txn.v = new BN(payload.v.slice(2), 'hex');
34 txn.r = new BN(payload.r.slice(2), 'hex');
35 txn.s = new BN(payload.s.slice(2), 'hex');
37 return txn;
38};
40export const trezorSignMessage = async (message, hdPath) => {
41 const sig = await TrezorConnect.ethereumSignMessage({
42 path: hdPath,
43 message,
44 });
46 if (!sig.success) {
47 throw new Error(sig.payload.error);
48 }
50 const { signature } = sig.payload;
52 return signature;
53};
55export { TREZOR_PATH, trezorSignTransaction };