1
0
mirror of https://github.com/trezor/trezor-wallet synced 2024-11-15 21:08:57 +00:00
trezor-wallet/src/actions/TxActions.js

69 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-09-12 11:25:32 +00:00
/* @flow */
import EthereumjsTx from 'ethereumjs-tx';
import EthereumjsUnits from 'ethereumjs-units';
import BigNumber from 'bignumber.js';
2018-09-23 06:49:43 +00:00
import { toHex } from 'web3-utils'; // eslint-disable-line import/no-extraneous-dependencies
import { initWeb3 } from 'actions/Web3Actions';
import * as ethUtils from 'utils/ethUtils';
2018-09-12 11:25:32 +00:00
2019-03-04 12:33:02 +00:00
import type { Dispatch, PromiseAction } from 'flowtype';
2018-09-12 11:25:32 +00:00
2018-09-23 06:49:43 +00:00
import type { EthereumTransaction } from 'trezor-connect';
import type { Token } from 'reducers/TokensReducer';
type EthereumTxRequest = {
2019-03-04 12:33:02 +00:00
network: string,
token: ?Token,
from: string,
to: string,
amount: string,
data: string,
gasLimit: string,
gasPrice: string,
nonce: number,
};
2019-03-04 12:33:02 +00:00
export const prepareEthereumTx = (
tx: EthereumTxRequest
): PromiseAction<EthereumTransaction> => async (
dispatch: Dispatch
): Promise<EthereumTransaction> => {
2018-09-23 06:49:43 +00:00
const instance = await dispatch(initWeb3(tx.network));
const { token } = tx;
2018-10-08 15:52:48 +00:00
let data: string = ethUtils.sanitizeHex(tx.data);
2018-09-23 06:49:43 +00:00
let value: string = toHex(EthereumjsUnits.convert(tx.amount, 'ether', 'wei'));
let to: string = tx.to; // eslint-disable-line prefer-destructuring
2018-09-12 11:25:32 +00:00
if (token) {
// smart contract transaction
const contract = instance.erc20.clone();
contract.options.address = token.address;
2019-03-04 12:33:02 +00:00
const tokenAmount: string = new BigNumber(tx.amount)
.times(10 ** token.decimals)
.toString(10);
2018-09-12 11:25:32 +00:00
data = instance.erc20.methods.transfer(to, tokenAmount).encodeABI();
value = '0x00';
to = token.address;
}
return {
to,
value,
data,
chainId: instance.chainId,
nonce: toHex(tx.nonce),
gasLimit: toHex(tx.gasLimit),
2018-09-23 06:49:43 +00:00
gasPrice: toHex(EthereumjsUnits.convert(tx.gasPrice, 'gwei', 'wei')),
2018-09-12 11:25:32 +00:00
r: '',
s: '',
v: '',
2018-09-23 06:49:43 +00:00
};
2018-09-12 11:25:32 +00:00
};
2019-03-04 12:33:02 +00:00
export const serializeEthereumTx = (
tx: EthereumTransaction
): PromiseAction<string> => async (): Promise<string> => {
2018-09-12 11:25:32 +00:00
const ethTx = new EthereumjsTx(tx);
2018-09-23 06:49:43 +00:00
return `0x${ethTx.serialize().toString('hex')}`;
2019-03-04 12:33:02 +00:00
};