1
0
mirror of https://github.com/trezor/trezor-wallet synced 2024-11-27 10:48:22 +00:00

rewrite BlockchainActions.autoReconnect method

This commit is contained in:
Szymon Lesisz 2019-10-30 16:30:28 +01:00
parent 4c3d0d3b92
commit eb20aee923
2 changed files with 13 additions and 21 deletions

View File

@ -1,9 +1,9 @@
/* @flow */
import * as BLOCKCHAIN from 'actions/constants/blockchain';
import * as DiscoveryActions from 'actions/DiscoveryActions';
import * as EthereumBlockchainActions from 'actions/ethereum/BlockchainActions';
import * as RippleBlockchainActions from 'actions/ripple/BlockchainActions';
import { resolveAfter } from 'utils/promiseUtils';
import type { Dispatch, GetState, PromiseAction, BlockchainFeeLevel } from 'flowtype';
import type { BlockchainBlock, BlockchainNotification, BlockchainError } from 'trezor-connect';
@ -20,10 +20,6 @@ export type BlockchainAction =
| {
type: typeof BLOCKCHAIN.START_SUBSCRIBE,
shortcut: string,
}
| {
type: typeof BLOCKCHAIN.FAIL_SUBSCRIBE,
shortcut: string,
};
// Conditionally subscribe to blockchain backend
@ -153,23 +149,13 @@ const autoReconnect = (shortcut: string): PromiseAction<void> => async (
dispatch: Dispatch,
getState: GetState
): Promise<void> => {
const MAX_ATTEMPTS = 4;
let blockchain = getState().blockchain.find(b => b.shortcut === shortcut);
// try to automatically reconnect and wait after each attemp (5s * #attempt) untill max number of attemps is reached
for (let i = 0; i < MAX_ATTEMPTS; i++) {
const waitTime = 5000 * (i + 1); /// 5s * #attempt
if (!blockchain || blockchain.connected) {
break;
}
if (!blockchain || blockchain.reconnectionAttempts >= 5) return;
blockchain = getState().blockchain.find(b => b.shortcut === shortcut);
await resolveAfter(5000 * (blockchain.reconnectionAttempts + 1));
// reconnect with 7s timeout
// eslint-disable-next-line no-await-in-loop
await dispatch(DiscoveryActions.reconnect(shortcut, 7000));
blockchain = getState().blockchain.find(b => b.shortcut === shortcut);
if (!blockchain || blockchain.connected || blockchain.connecting) return;
// wait before next try
// eslint-disable-next-line no-await-in-loop
await new Promise(resolve => setTimeout(resolve, waitTime));
}
await dispatch(subscribe(shortcut));
};

View File

@ -1,5 +1,5 @@
/* @flow */
import { DEVICE } from 'trezor-connect';
import { DEVICE, BLOCKCHAIN } from 'trezor-connect';
import { LOCATION_CHANGE } from 'connected-react-router';
import * as WALLET from 'actions/constants/wallet';
import * as CONNECT from 'actions/constants/TrezorConnect';
@ -132,6 +132,12 @@ const WalletService: Middleware = (api: MiddlewareAPI) => (next: MiddlewareDispa
api.dispatch(DiscoveryActions.stop());
}
// try to restore discovery on BLOCKCHAIN.CONNECT event
// edge case when backend throws error during discovery
if (action.type === BLOCKCHAIN.CONNECT) {
api.dispatch(DiscoveryActions.restore());
}
return action;
};