1
0
mirror of https://github.com/trezor/trezor-wallet synced 2025-01-14 18:10:56 +00:00
trezor-wallet/src/actions/SendFormActions.js

553 lines
16 KiB
JavaScript
Raw Normal View History

2017-12-13 11:01:37 +00:00
/* @flow */
import TrezorConnect from 'trezor-connect';
2018-02-20 09:30:36 +00:00
import BigNumber from 'bignumber.js';
import * as ACCOUNT from 'actions/constants/account';
2018-08-14 13:18:16 +00:00
import * as NOTIFICATION from 'actions/constants/notification';
import * as SEND from 'actions/constants/send';
2018-09-22 16:49:05 +00:00
import * as WEB3 from 'actions/constants/web3';
import * as ValidationActions from 'actions/SendFormValidationActions';
2017-12-13 11:01:37 +00:00
2018-08-14 13:18:16 +00:00
import { initialState } from 'reducers/SendFormReducer';
import { findToken } from 'reducers/TokensReducer';
2018-09-22 16:49:05 +00:00
import * as reducerUtils from 'reducers/utils';
2018-04-16 21:19:50 +00:00
2018-07-30 10:52:13 +00:00
import type {
2018-04-16 21:19:50 +00:00
Dispatch,
GetState,
2018-09-22 16:49:05 +00:00
State as ReducersState,
2018-04-16 21:19:50 +00:00
Action,
2018-05-02 09:01:08 +00:00
ThunkAction,
2018-04-16 21:19:50 +00:00
AsyncAction,
2018-07-30 10:52:13 +00:00
TrezorDevice,
2018-08-14 12:56:47 +00:00
} from 'flowtype';
2018-08-14 13:18:16 +00:00
import type { State, FeeLevel } from 'reducers/SendFormReducer';
import type { Account } from 'reducers/AccountsReducer';
2018-08-14 14:06:34 +00:00
import * as SessionStorageActions from './SessionStorageActions';
import { prepareEthereumTx, serializeEthereumTx } from './TxActions';
import * as BlockchainActions from './BlockchainActions';
2018-04-16 21:19:50 +00:00
export type SendTxAction = {
2018-04-16 21:19:50 +00:00
type: typeof SEND.TX_COMPLETE,
2018-05-09 15:47:34 +00:00
account: Account,
selectedCurrency: string,
2018-05-09 15:47:34 +00:00
amount: string,
2018-05-28 09:21:47 +00:00
total: string,
tx: any,
nonce: number,
2018-05-09 15:47:34 +00:00
txid: string,
txData: any,
};
2018-09-22 16:49:05 +00:00
export type SendFormAction = {
type: typeof SEND.INIT | typeof SEND.VALIDATION | typeof SEND.CHANGE,
state: State,
2018-04-16 21:19:50 +00:00
} | {
2018-09-22 16:49:05 +00:00
type: typeof SEND.TOGGLE_ADVANCED | typeof SEND.TX_SENDING | typeof SEND.TX_ERROR,
} | SendTxAction;
// list of all actions which has influence on "sendForm" reducer
// other actions will be ignored
const actions = [
ACCOUNT.UPDATE_SELECTED_ACCOUNT,
WEB3.GAS_PRICE_UPDATED,
...Object.values(SEND).filter(v => typeof v === 'string'),
];
2018-09-22 16:49:05 +00:00
/*
* Called from WalletService
2018-09-22 16:49:05 +00:00
*/
export const observe = (prevState: ReducersState, action: Action): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
// ignore not listed actions
if (actions.indexOf(action.type) < 0) return;
2018-09-22 16:49:05 +00:00
const currentState = getState();
// do not proceed if it's not "send" url
if (!currentState.router.location.state.send) return;
// if action type is SEND.VALIDATION which is called as result of this process
// save data to session storage
if (action.type === SEND.VALIDATION) {
dispatch(SessionStorageActions.saveDraftTransaction());
return;
}
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
// if send form was not initialized
if (currentState.sendForm.currency === '') {
dispatch(init());
return;
2017-12-13 11:01:37 +00:00
}
2018-09-22 16:49:05 +00:00
// handle gasPrice update from backend
// recalculate fee levels if needed
if (action.type === WEB3.GAS_PRICE_UPDATED) {
dispatch(ValidationActions.onGasPriceUpdated(action.network, action.gasPrice));
return;
2017-12-13 11:01:37 +00:00
}
2018-09-22 16:49:05 +00:00
let shouldUpdate: boolean = false;
// check if "selectedAccount" reducer changed
shouldUpdate = reducerUtils.observeChanges(prevState.selectedAccount, currentState.selectedAccount, {
account: ['balance', 'nonce'],
});
2018-09-22 16:49:05 +00:00
// check if "sendForm" reducer changed
if (!shouldUpdate) {
shouldUpdate = reducerUtils.observeChanges(prevState.sendForm, currentState.sendForm);
}
2018-04-11 13:21:43 +00:00
2018-09-22 16:49:05 +00:00
if (shouldUpdate) {
const validated = dispatch(ValidationActions.validation());
dispatch({
type: SEND.VALIDATION,
state: validated,
});
}
2018-07-30 10:52:13 +00:00
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from "observe" action
* Initialize "sendForm" reducer data
* Get data either from session storage or "selectedAccount" reducer
*/
export const init = (): AsyncAction => async (dispatch: Dispatch, getState: GetState): Promise<void> => {
2018-07-30 10:52:13 +00:00
const {
account,
network,
} = getState().selectedAccount;
2018-02-20 09:30:36 +00:00
if (!account || !network) return;
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
const stateFromStorage = dispatch(SessionStorageActions.loadDraftTransaction());
2018-07-30 10:52:13 +00:00
if (stateFromStorage) {
2018-09-22 16:49:05 +00:00
// TODO: consider if current gasPrice should be set here as "recommendedGasPrice"
2018-02-20 09:30:36 +00:00
dispatch({
type: SEND.INIT,
2018-07-30 10:52:13 +00:00
state: stateFromStorage,
2018-02-20 09:30:36 +00:00
});
2018-07-30 10:52:13 +00:00
return;
2018-02-20 09:30:36 +00:00
}
2018-09-20 07:37:17 +00:00
const gasPrice: BigNumber = await dispatch(BlockchainActions.getGasPrice(network.network, network.defaultGasPrice));
2018-09-22 16:49:05 +00:00
const gasLimit = network.defaultGasLimit.toString();
const feeLevels = ValidationActions.getFeeLevels(network.symbol, gasPrice, gasLimit);
const selectedFeeLevel = ValidationActions.getSelectedFeeLevel(feeLevels, initialState.selectedFeeLevel);
2018-07-30 10:52:13 +00:00
dispatch({
type: SEND.INIT,
state: {
2018-09-22 16:49:05 +00:00
...initialState,
networkName: network.network,
networkSymbol: network.symbol,
currency: network.symbol,
feeLevels,
selectedFeeLevel,
recommendedGasPrice: gasPrice.toString(),
gasLimit,
gasPrice: gasPrice.toString(),
2018-07-30 10:52:13 +00:00
},
});
};
2018-09-22 16:49:05 +00:00
/*
* Called from UI from "advanced" button
*/
export const toggleAdvanced = (): Action => ({
type: SEND.TOGGLE_ADVANCED,
});
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "address" field change
*/
2018-07-30 10:52:13 +00:00
export const onAddressChange = (address: string): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const state: State = getState().sendForm;
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
2018-07-30 10:52:13 +00:00
state: {
...state,
untouched: false,
2018-09-22 16:49:05 +00:00
touched: { ...state.touched, address: true },
2018-07-30 10:52:13 +00:00
address,
},
});
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "amount" field change
*/
2018-07-30 10:52:13 +00:00
export const onAmountChange = (amount: string): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const state = getState().sendForm;
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
2018-07-30 10:52:13 +00:00
state: {
...state,
untouched: false,
2018-09-22 16:49:05 +00:00
touched: { ...state.touched, amount: true },
2018-07-30 10:52:13 +00:00
setMax: false,
amount,
},
});
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "currency" selection change
*/
2018-07-30 10:52:13 +00:00
export const onCurrencyChange = (currency: { value: string, label: string }): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const {
account,
network,
} = getState().selectedAccount;
if (!account || !network) return;
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
const state = getState().sendForm;
const isToken = currency.value !== state.networkSymbol;
const gasLimit = isToken ? network.defaultGasLimitTokens.toString() : network.defaultGasLimit.toString();
const feeLevels = ValidationActions.getFeeLevels(network.symbol, state.recommendedGasPrice, gasLimit, state.selectedFeeLevel);
const selectedFeeLevel = ValidationActions.getSelectedFeeLevel(feeLevels, state.selectedFeeLevel);
2018-07-30 10:52:13 +00:00
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
state: {
...state,
currency: currency.value,
feeLevels,
selectedFeeLevel,
gasLimit,
},
2018-07-30 10:52:13 +00:00
});
};
2018-04-11 13:21:43 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI from "set max" button
*/
2018-07-30 10:52:13 +00:00
export const onSetMax = (): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const state = getState().sendForm;
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
2018-07-30 10:52:13 +00:00
state: {
...state,
2018-02-20 09:30:36 +00:00
untouched: false,
2018-09-22 16:49:05 +00:00
touched: { ...state.touched, amount: true },
2018-07-30 10:52:13 +00:00
setMax: !state.setMax,
},
});
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "fee" selection change
*/
2018-07-30 10:52:13 +00:00
export const onFeeLevelChange = (feeLevel: FeeLevel): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
2018-09-22 16:49:05 +00:00
const state = getState().sendForm;
2018-07-30 10:52:13 +00:00
2018-09-22 16:49:05 +00:00
const isCustom = feeLevel.value === 'Custom';
let newGasLimit = state.gasLimit;
let newGasPrice = state.gasPrice;
const advanced = isCustom ? true : state.advanced;
if (!isCustom) {
// if selected fee is not custom
// update gasLimit to default and gasPrice to selected value
const { network } = getState().selectedAccount;
if (!network) return;
const isToken = state.currency !== state.networkSymbol;
2018-07-30 10:52:13 +00:00
if (isToken) {
2018-09-22 16:49:05 +00:00
newGasLimit = network.defaultGasLimitTokens.toString();
2018-02-20 09:30:36 +00:00
} else {
2018-09-22 16:49:05 +00:00
// corner case: gas limit was changed by user OR by "estimateGasPrice" action
// leave gasLimit as it is
newGasLimit = state.touched.gasLimit ? state.gasLimit : network.defaultGasLimit.toString();
2018-02-20 09:30:36 +00:00
}
2018-09-22 16:49:05 +00:00
newGasPrice = feeLevel.gasPrice;
2018-02-20 09:30:36 +00:00
}
2018-07-30 10:52:13 +00:00
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
state: {
...state,
advanced,
selectedFeeLevel: feeLevel,
gasLimit: newGasLimit,
gasPrice: newGasPrice,
},
2018-07-30 10:52:13 +00:00
});
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI from "update recommended fees" button
*/
2018-07-30 10:52:13 +00:00
export const updateFeeLevels = (): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const {
account,
network,
} = getState().selectedAccount;
if (!account || !network) return;
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
const state: State = getState().sendForm;
const feeLevels = ValidationActions.getFeeLevels(network.symbol, state.recommendedGasPrice, state.gasLimit, state.selectedFeeLevel);
const selectedFeeLevel = ValidationActions.getSelectedFeeLevel(feeLevels, state.selectedFeeLevel);
2018-07-30 10:52:13 +00:00
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
state: {
...state,
feeLevels,
selectedFeeLevel,
gasPrice: selectedFeeLevel.gasPrice,
gasPriceNeedsUpdate: false,
},
2018-07-30 10:52:13 +00:00
});
};
2018-04-11 13:21:43 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "gas price" field change
*/
2018-07-30 10:52:13 +00:00
export const onGasPriceChange = (gasPrice: string): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
2018-09-22 16:49:05 +00:00
const state: State = getState().sendForm;
// switch to custom fee level
let newSelectedFeeLevel = state.selectedFeeLevel;
if (state.selectedFeeLevel.value !== 'Custom') newSelectedFeeLevel = state.feeLevels.find(f => f.value === 'Custom');
2018-02-20 09:30:36 +00:00
2018-07-30 10:52:13 +00:00
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
state: {
...state,
untouched: false,
touched: { ...state.touched, gasPrice: true },
gasPrice,
selectedFeeLevel: newSelectedFeeLevel,
},
2018-07-30 10:52:13 +00:00
});
};
2018-04-11 13:21:43 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "data" field change
* OR from "estimateGasPrice" action
*/
export const onGasLimitChange = (gasLimit: string): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const { network } = getState().selectedAccount;
if (!network) return;
const state: State = getState().sendForm;
// recalculate feeLevels with recommended gasPrice
const feeLevels = ValidationActions.getFeeLevels(network.symbol, state.recommendedGasPrice, gasLimit, state.selectedFeeLevel);
const selectedFeeLevel = ValidationActions.getSelectedFeeLevel(feeLevels, state.selectedFeeLevel);
2018-02-20 09:30:36 +00:00
2018-07-30 10:52:13 +00:00
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
state: {
...state,
calculatingGasLimit: false,
untouched: false,
touched: { ...state.touched, gasLimit: true },
gasLimit,
feeLevels,
selectedFeeLevel,
},
2018-07-30 10:52:13 +00:00
});
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "nonce" field change
*/
export const onNonceChange = (nonce: string): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const state: State = getState().sendForm;
dispatch({
type: SEND.CHANGE,
state: {
...state,
untouched: false,
touched: { ...state.touched, nonce: true },
nonce,
},
});
};
2018-07-30 10:52:13 +00:00
2018-09-22 16:49:05 +00:00
/*
* Called from UI on "data" field change
*/
export const onDataChange = (data: string): ThunkAction => (dispatch: Dispatch, getState: GetState): void => {
const state: State = getState().sendForm;
2018-07-30 10:52:13 +00:00
dispatch({
2018-09-22 16:49:05 +00:00
type: SEND.CHANGE,
state: {
...state,
calculatingGasLimit: true,
untouched: false,
touched: { ...state.touched, data: true },
data,
},
2018-07-30 10:52:13 +00:00
});
2018-09-22 16:49:05 +00:00
dispatch(estimateGasPrice());
2018-07-30 10:52:13 +00:00
};
2018-02-20 09:30:36 +00:00
2018-09-22 16:49:05 +00:00
/*
* Internal method
* Called from "onDataChange" action
* try to asynchronously download data from backend
*/
2018-07-30 10:52:13 +00:00
const estimateGasPrice = (): AsyncAction => async (dispatch: Dispatch, getState: GetState): Promise<void> => {
const state: State = getState().sendForm;
2018-09-22 16:49:05 +00:00
const { network } = getState().selectedAccount;
if (!network) {
// stop "calculatingGasLimit" process
dispatch(onGasLimitChange(state.gasLimit));
return;
}
2018-09-22 16:49:05 +00:00
const requestedData = state.data;
const re = /^[0-9A-Fa-f]+$/g; // TODO: allow "0x" prefix
2018-07-30 10:52:13 +00:00
if (!re.test(requestedData)) {
2018-09-22 16:49:05 +00:00
// stop "calculatingGasLimit" process
2018-07-30 10:52:13 +00:00
dispatch(onGasLimitChange(requestedData.length > 0 ? state.gasLimit : network.defaultGasLimit.toString()));
return;
}
2018-07-30 10:52:13 +00:00
if (state.data.length < 1) {
// set default
dispatch(onGasLimitChange(network.defaultGasLimit.toString()));
return;
2018-02-20 09:30:36 +00:00
}
2018-09-22 16:49:05 +00:00
const gasLimit = await dispatch(BlockchainActions.estimateGasLimit(network.network, state.data, state.amount, state.gasPrice));
2018-07-30 10:52:13 +00:00
2018-09-22 16:49:05 +00:00
// double check "data" field
// possible race condition when data changed before backend respond
2018-07-30 10:52:13 +00:00
if (getState().sendForm.data === requestedData) {
2018-09-22 16:49:05 +00:00
dispatch(onGasLimitChange(gasLimit));
2018-09-06 15:04:28 +00:00
}
};
2018-09-22 16:49:05 +00:00
/*
* Called from UI from "send" button
*/
2018-07-30 10:52:13 +00:00
export const onSend = (): AsyncAction => async (dispatch: Dispatch, getState: GetState): Promise<void> => {
const {
account,
network,
pending,
} = getState().selectedAccount;
if (!account || !network) return;
2018-07-30 10:52:13 +00:00
const currentState: State = getState().sendForm;
2018-07-30 10:52:13 +00:00
const isToken: boolean = currentState.currency !== currentState.networkSymbol;
2018-09-22 16:49:05 +00:00
const pendingNonce: number = reducerUtils.getPendingNonce(pending);
2018-07-30 10:52:13 +00:00
const nonce = pendingNonce > 0 && pendingNonce >= account.nonce ? pendingNonce : account.nonce;
2018-09-20 07:37:17 +00:00
const txData = await dispatch(prepareEthereumTx({
network: network.network,
token: isToken ? findToken(getState().tokens, account.address, currentState.currency, account.deviceState) : null,
from: account.address,
to: currentState.address,
amount: currentState.amount,
data: currentState.data,
gasLimit: currentState.gasLimit,
gasPrice: currentState.gasPrice,
2018-09-20 07:37:17 +00:00
nonce,
}));
2018-07-30 10:52:13 +00:00
const selected: ?TrezorDevice = getState().wallet.selectedDevice;
if (!selected) return;
const signedTransaction = await TrezorConnect.ethereumSignTransaction({
device: {
path: selected.path,
instance: selected.instance,
state: selected.state,
},
useEmptyPassphrase: !selected.instance,
2018-09-22 16:49:05 +00:00
path: account.addressPath,
2018-08-14 14:06:34 +00:00
transaction: txData,
2018-07-30 10:52:13 +00:00
});
if (!signedTransaction || !signedTransaction.success) {
dispatch({
type: NOTIFICATION.ADD,
payload: {
type: 'error',
title: 'Transaction error',
message: signedTransaction.payload.error,
cancelable: true,
actions: [],
},
});
return;
}
2018-02-20 09:30:36 +00:00
txData.r = signedTransaction.payload.r;
txData.s = signedTransaction.payload.s;
txData.v = signedTransaction.payload.v;
2017-12-13 11:01:37 +00:00
2018-07-30 10:52:13 +00:00
try {
2018-09-20 07:37:17 +00:00
const serializedTx: string = await dispatch(serializeEthereumTx(txData));
const push = await TrezorConnect.pushTransaction({
tx: serializedTx,
2018-09-20 07:37:17 +00:00
coin: network.network,
});
2018-09-20 07:37:17 +00:00
if (!push.success) {
2018-09-20 07:37:17 +00:00
throw new Error(push.payload.error);
}
2018-09-22 16:49:05 +00:00
const { txid } = push.payload;
2017-12-13 11:01:37 +00:00
2018-07-30 10:52:13 +00:00
dispatch({
type: SEND.TX_COMPLETE,
account,
selectedCurrency: currentState.currency,
amount: currentState.amount,
total: currentState.total,
tx: txData,
2018-07-30 10:52:13 +00:00
nonce,
txid,
txData,
2017-12-13 11:01:37 +00:00
});
2018-07-30 10:52:13 +00:00
// clear session storage
dispatch(SessionStorageActions.clear());
2018-02-20 09:30:36 +00:00
2018-07-30 10:52:13 +00:00
// reset form
dispatch(init());
2018-02-20 09:30:36 +00:00
2018-07-30 10:52:13 +00:00
dispatch({
type: NOTIFICATION.ADD,
payload: {
type: 'success',
title: 'Transaction success',
message: `<a href="${network.explorer.tx}${txid}" class="green" target="_blank" rel="noreferrer noopener">See transaction detail</a>`,
cancelable: true,
actions: [],
},
});
} catch (error) {
dispatch({
type: NOTIFICATION.ADD,
payload: {
type: 'error',
title: 'Transaction error',
message: error.message || error,
cancelable: true,
actions: [],
},
});
2017-12-13 11:01:37 +00:00
}
2018-07-30 10:52:13 +00:00
};
2018-04-16 21:19:50 +00:00
export default {
toggleAdvanced,
onAddressChange,
onAmountChange,
onCurrencyChange,
onSetMax,
onFeeLevelChange,
updateFeeLevels,
onGasPriceChange,
onGasLimitChange,
2018-05-11 13:20:11 +00:00
onNonceChange,
2018-04-16 21:19:50 +00:00
onDataChange,
onSend,
2018-07-30 10:52:13 +00:00
};