Skip to content
Permalink
Browse files

[DDW-589] Retrieve Epoch from cardanoexplorer

  • Loading branch information...
daniloprates committed Mar 15, 2019
1 parent 56ab719 commit 7aea28f53b3666a3708462b78c120e32a71fa609
@@ -6,4 +6,5 @@ import Action from './lib/Action';
export default class NetworkStatusActions {
isSyncedAndReady: Action<any> = new Action();
getEpochsData: Action<any> = new Action();
getCurrentEpochFallback: Action<any> = new Action();
}
@@ -938,10 +938,11 @@ export default class AdaApi {
this.config,
queryInfoParams
);
Logger.debug(`${loggerText} success`, { nodeInfo });

const nodeSettings: NodeSettingsResponse = await getNodeSettings(
this.config
);
Logger.debug(`${loggerText} success`, { nodeInfo });
Logger.debug('AdaApi::getNetworkStatusSettings success', {
nodeSettings,
});
@@ -981,10 +982,11 @@ export default class AdaApi {
getCurrentEpochFallback = async () => {
try {
const pages = await getCurrentEpoch();
console.info('pages', pages);
return pages;
} catch (err) {
console.info('err', err);
const currentEpoch = get(pages, 'Right[1][0].cbeEpoch');
return currentEpoch;
} catch (error) {
Logger.error('AdaApi::getCurrentEpoch error', { error });
throw new GenericApiError();
}
};

@@ -1,15 +1,12 @@
// @flow
// import type { RequestConfig } from '../../common/types';
import type { NodeSettingsResponse } from '../types';
import { request } from '../../utils/request';
import { externalRequest } from '../../utils/externalRequest';

export const getCurrentEpoch = (): // config: RequestConfig
Promise<NodeSettingsResponse> =>
request({
host: 'cardanoexplorer.com',
href: 'https://cardanoexplorer.com/api/blocks/pages',
origin: 'https://cardanoexplorer.com',
externalRequest({
hostname: 'cardanoexplorer.com',
path: '/api/blocks/pages',
protocol: 'https:',
method: 'GET',
});
@@ -56,4 +56,7 @@ export type GetNetworkStatusResponse = {
status: LocalTimeInformationStatus,
difference: ?number,
},
slotId: {
epoch: number,
},
};
@@ -0,0 +1,37 @@
// @flow
import { ALLOWED_EXTERNAL_HOSTNAMES } from '../../config/urlsConfig';

export type HttpOptions = {
hostname: string,
method: string,
path?: string,
port?: number,
headers?: {
'Content-Type': string,
'Content-Length': number,
},
};

export const externalRequest = (httpOptions: HttpOptions): Promise<any> => {
return new Promise((resolve, reject) => {
if (!ALLOWED_EXTERNAL_HOSTNAMES.includes(httpOptions.hostname)) {
return reject(new Error('Hostname not allowed'));
}

const httpsRequest = global.https.request(httpOptions);

httpsRequest.on('response', response => {
let body = '';
response.on('data', chunk => {
body += chunk;
});
response.on('error', error => reject(error));
response.on('end', () => {
const parsedBody = JSON.parse(body);
return resolve(parsedBody);
});
});
httpsRequest.on('error', error => reject(error));
return httpsRequest.end();
});
};
@@ -3,6 +3,7 @@ import BigNumber from 'bignumber.js';
import { get } from 'lodash';
import AdaApi from '../api';
import { getNodeInfo } from '../nodes/requests/getNodeInfo';
import { getNodeSettings } from '../nodes/requests/getNodeSettings';
import { GenericApiError } from '../common/errors';
import { Logger } from '../../utils/logging';
import { RedeemAdaError } from '../transactions/errors';
@@ -11,6 +12,7 @@ import type { RedeemPaperVendedAdaParams } from '../transactions/requests/redeem
import type { NodeInfoQueryParams } from '../nodes/requests/getNodeInfo';
import type {
NodeInfoResponse,
NodeSettingsResponse,
GetNetworkStatusResponse,
} from '../nodes/types';

@@ -81,18 +83,26 @@ export default (api: AdaApi) => {
): Promise<GetNetworkStatusResponse> => {
Logger.debug('AdaApi::getNetworkStatus (PATCHED) called');
try {
const status: NodeInfoResponse = await getNodeInfo(
const nodeInfo: NodeInfoResponse = await getNodeInfo(
api.config,
queryInfoParams
);
Logger.debug('AdaApi::getNetworkStatus (PATCHED) success', { status });
Logger.debug('AdaApi::getNetworkStatus (PATCHED) success', { nodeInfo });
const nodeSettings: NodeSettingsResponse = await getNodeSettings(
api.config
);
Logger.debug('AdaApi::getNetworkStatusSettings success', {
nodeSettings,
});

const {
blockchainHeight,
subscriptionStatus,
syncProgress,
localBlockchainHeight,
} = status;
} = nodeInfo;

const { slotId } = nodeSettings;

// extract relevant data before sending to NetworkStatusStore
return {
@@ -104,6 +114,7 @@ export default (api: AdaApi) => {
status: 'available',
difference: LOCAL_TIME_DIFFERENCE,
},
slotId,
};
} catch (error) {
Logger.error('AdaApi::getNetworkStatus (PATCHED) error', { error });
@@ -102,9 +102,7 @@ function typedRequest<Response>(

const parsedBody = JSON.parse(body);
const status = get(parsedBody, 'status', false);
if (options.host.indexOf('cardanoexplorer') > -1) {
resolve(parsedBody);
} else if (status) {
if (status) {
if (status === 'success') {
resolve(returnMeta ? parsedBody : parsedBody.data);
} else if (status === 'error' || status === 'fail') {
@@ -8,3 +8,5 @@ export const TESTNET_EXPLORER_URL =
export const DEVELOPMENT_EKG_URL = 'http://localhost:8083';
export const STAGING_EKG_URL = 'http://localhost:8082';
export const TESTNET_EKG_URL = 'http://localhost:8081';

export const ALLOWED_EXTERNAL_HOSTNAMES = ['cardanoexplorer.com'];
@@ -9,6 +9,7 @@ import { EPOCH_DATA_UPDATE_INTERVAL } from '../../config/timingConfig';
@observer
export default class BlockConsolidationStatusPage extends Component<InjectedProps> {
pollingInterval: ?IntervalID = null;
currentEpochFallbackRequested: boolean = false;

componentWillMount() {
this.pollingInterval = setInterval(
@@ -30,11 +31,33 @@ export default class BlockConsolidationStatusPage extends Component<InjectedProp
this.props.actions.app.toggleBlockConsolidationStatusScreen.trigger();
};

/**
*
* This method checks if the `currentEpoch` was returned by the API, which might fail sometimes
* In this case, it calls `getCurrentEpochFallback`, which retrieves it from CardanoExplorer
*
* The reason why this is not on `ComponentWillReceiveProps`,
* is that `ComponentWillReceiveProps` is not fired when reloading the app
*
*/
handleCurrentEpoch = () => {
if (this.currentEpochFallbackRequested) return false;
const {
epochsConsolidated,
syncProgress,
currentEpoch,
} = this.props.stores.networkStatus;
if ((epochsConsolidated || syncProgress) && !currentEpoch) {
this.currentEpochFallbackRequested = true;
this.props.actions.networkStatus.getCurrentEpochFallback.trigger();
}
};

render() {
const { app, networkStatus } = this.props.stores;
const { epochsConsolidated, syncProgress, currentEpoch } = networkStatus;
this.handleCurrentEpoch();
const { openExternalLink } = app;

return (
<BlockConsolidationStatus
currentEpoch={currentEpoch}
@@ -111,6 +111,7 @@ export default class NetworkStatusStore extends Store {
setup() {
const actions = this.actions.networkStatus;
actions.getEpochsData.listen(this._getEpochsData);
actions.getCurrentEpochFallback.listen(this._getCurrentEpochFallback);
// ========== IPC CHANNELS =========== //

// Request node state
@@ -428,7 +429,7 @@ export default class NetworkStatusStore extends Store {

// Update sync progress
runInAction('update currentEpoch', () => {
// this.currentEpoch = slotId.epoch;
this.currentEpoch = slotId.epoch;
});

runInAction('update block heights', () => {
@@ -557,8 +558,11 @@ export default class NetworkStatusStore extends Store {
};

@action _getCurrentEpochFallback = async () => {
const pages = await this.getCurrentEpochFallbackRequest.execute().promise;
console.log('pages store', pages);
const currentEpoch = await this.getCurrentEpochFallbackRequest.execute()
.promise;
runInAction(() => {
this.currentEpoch = currentEpoch;
});
};

@action _setDisconnected = (wasConnected: boolean) => {

0 comments on commit 7aea28f

Please sign in to comment.
You can’t perform that action at this time.