Allow forks on explorer (no Babe), adjust EventsContext (#5161)

This commit is contained in:
Jaco 2021-04-29 10:45:03 +03:00 committed by GitHub
parent 9be4ded206
commit 00fd0e3b14
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 65 deletions

View File

@ -7,7 +7,6 @@ import React, { useContext, useRef } from 'react';
import { Route, Switch } from 'react-router';
import Tabs from '@polkadot/react-components/Tabs';
import { useApi } from '@polkadot/react-hooks';
import { BlockAuthorsContext, EventsContext } from '@polkadot/react-query';
import BlockInfo from './BlockInfo';
@ -22,11 +21,8 @@ interface Props {
newEvents?: KeyedEvent[];
}
const HIDDESN_NOBABE = ['forks'];
function ExplorerApp ({ basePath, className }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { lastHeaders } = useContext(BlockAuthorsContext);
const events = useContext(EventsContext);
@ -55,7 +51,6 @@ function ExplorerApp ({ basePath, className }: Props): React.ReactElement<Props>
<main className={className}>
<Tabs
basePath={basePath}
hidden={api.query.babe ? undefined : HIDDESN_NOBABE}
items={itemsRef.current}
/>
<Switch>

View File

@ -1,12 +1,15 @@
// Copyright 2017-2021 @polkadot/react-query authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiPromise } from '@polkadot/api';
import type { Vec } from '@polkadot/types';
import type { EventRecord } from '@polkadot/types/interfaces';
import type { IndexedEvent, KeyedEvent } from './types';
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { useApi } from '@polkadot/react-hooks';
import { stringToU8a } from '@polkadot/util';
import { useApi, useCall } from '@polkadot/react-hooks';
import { stringify, stringToU8a } from '@polkadot/util';
import { xxhashAsHex } from '@polkadot/util-crypto';
type Events = KeyedEvent[];
@ -15,71 +18,75 @@ interface Props {
children: React.ReactNode;
}
interface PrevHashes {
block: string | null;
event: string | null;
}
const MAX_EVENTS = 75;
const EventsContext: React.Context<Events> = React.createContext<Events>([]);
async function manageEvents (api: ApiPromise, prev: PrevHashes, records: Vec<EventRecord>, setState: React.Dispatch<React.SetStateAction<Events>>): Promise<void> {
const newEvents: IndexedEvent[] = records
.map((record, index) => ({ indexes: [index], record }))
.filter(({ record: { event: { method, section } } }) =>
section !== 'system' &&
(method !== 'Deposit' || !['balances', 'treasury'].includes(section)) &&
(section !== 'inclusion' || !['CandidateBacked', 'CandidateIncluded'].includes(method))
)
.reduce((combined: IndexedEvent[], e): IndexedEvent[] => {
const prev = combined.find(({ record: { event: { method, section } } }) =>
e.record.event.section === section &&
e.record.event.method === method
);
if (prev) {
prev.indexes.push(...e.indexes);
} else {
combined.push(e);
}
return combined;
}, [])
.reverse();
const newEventHash = xxhashAsHex(stringToU8a(stringify(newEvents)));
if (newEventHash !== prev.event && newEvents.length) {
prev.event = newEventHash;
// retrieve the last header, this will map to the current state
const header = await api.rpc.chain.getHeader(records.createdAtHash);
const blockNumber = header.number.unwrap();
const blockHash = header.hash.toHex();
if (blockHash !== prev.block) {
prev.block = blockHash;
setState((events) => [
...newEvents.map(({ indexes, record }): KeyedEvent => ({
blockHash,
blockNumber,
indexes,
key: `${blockNumber.toNumber()}-${blockHash}-${indexes.join('.')}`,
record
})),
// remove all events for the previous same-height blockNumber
...events.filter((p) => !p.blockNumber?.eq(blockNumber))
].slice(0, MAX_EVENTS));
}
}
}
function EventsBase ({ children }: Props): React.ReactElement<Props> {
const { api } = useApi();
const { api, isApiReady } = useApi();
const [state, setState] = useState<Events>([]);
const records = useCall<Vec<EventRecord>>(isApiReady && api.query.system.events);
const prevHashes = useRef({ block: null, event: null });
useEffect((): void => {
// No unsub, global context - destroyed on app close
api.isReady.then((): void => {
let prevBlockHash: string | null = null;
let prevEventHash: string | null = null;
api.query.system.events((records): void => {
const newEvents: IndexedEvent[] = records
.map((record, index) => ({ indexes: [index], record }))
.filter(({ record: { event: { method, section } } }) =>
section !== 'system' &&
(method !== 'Deposit' || !['balances', 'treasury'].includes(section)) &&
(section !== 'inclusion' || !['CandidateBacked', 'CandidateIncluded'].includes(method))
)
.reduce((combined: IndexedEvent[], e): IndexedEvent[] => {
const prev = combined.find(({ record: { event: { method, section } } }) => e.record.event.section === section && e.record.event.method === method);
if (prev) {
prev.indexes.push(...e.indexes);
} else {
combined.push(e);
}
return combined;
}, [])
.reverse();
const newEventHash = xxhashAsHex(stringToU8a(JSON.stringify(newEvents)));
if (newEventHash !== prevEventHash && newEvents.length) {
prevEventHash = newEventHash;
// retrieve the last header, this will map to the current state
api.rpc.chain.getHeader().then((header): void => {
const blockNumber = header.number.unwrap();
const blockHash = header.hash.toHex();
if (blockHash !== prevBlockHash) {
prevBlockHash = blockHash;
setState((events) => [
...newEvents.map(({ indexes, record }): KeyedEvent => ({
blockHash,
blockNumber,
indexes,
key: `${blockNumber.toNumber()}-${blockHash}-${indexes.join('.')}`,
record
})),
// remove all events for the previous same-height blockNumber
...events.filter((p) => !p.blockNumber?.eq(blockNumber))
].slice(0, MAX_EVENTS));
}
}).catch(console.error);
}
}).catch(console.error);
}).catch(console.error);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
records && manageEvents(api, prevHashes.current, records, setState).catch(console.error);
}, [api, prevHashes, records, setState]);
return (
<EventsContext.Provider value={state}>