@polkadot/react-query
Version:
A collection of RxJs React components the Polkadot JS API
96 lines (79 loc) • 3.23 kB
JavaScript
;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BlockAuthors = BlockAuthors;
exports.ValidatorsContext = exports.BlockAuthorsContext = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactHooks = require("@polkadot/react-hooks");
var _util = require("@polkadot/util");
// Copyright 2017-2020 @polkadot/react-query authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const MAX_HEADERS = 25;
const byAuthor = {};
const BlockAuthorsContext = _react.default.createContext({
byAuthor,
lastHeaders: []
});
exports.BlockAuthorsContext = BlockAuthorsContext;
const ValidatorsContext = _react.default.createContext([]);
exports.ValidatorsContext = ValidatorsContext;
function BlockAuthors({
children
}) {
const {
api
} = (0, _reactHooks.useApi)();
const [state, setState] = (0, _react.useState)({
byAuthor,
lastHeaders: []
});
const [validators, setValidators] = (0, _react.useState)([]);
(0, _react.useEffect)(() => {
// TODO We should really unsub - but since this should just be used once,
// atm I'm rather typing this than doing it the way it is supposed to be
api.isReady.then(() => {
let lastHeaders = [];
let lastBlockAuthors = [];
let lastBlockNumber = ''; // subscribe to all validators
api.query.session && api.query.session.validators(validatorIds => {
setValidators(validatorIds.map(validatorId => validatorId.toString()));
}); // subscribe to new headers
api.derive.chain.subscribeNewHeads(lastHeader => {
if (lastHeader === null || lastHeader === void 0 ? void 0 : lastHeader.number) {
var _lastHeader$author;
const blockNumber = lastHeader.number.unwrap();
const thisBlockAuthor = (_lastHeader$author = lastHeader.author) === null || _lastHeader$author === void 0 ? void 0 : _lastHeader$author.toString();
const thisBlockNumber = (0, _util.formatNumber)(blockNumber);
if (thisBlockAuthor) {
byAuthor[thisBlockAuthor] = thisBlockNumber;
if (thisBlockNumber !== lastBlockNumber) {
lastBlockNumber = thisBlockNumber;
lastBlockAuthors = [thisBlockAuthor];
} else {
lastBlockAuthors.push(thisBlockAuthor);
}
}
lastHeaders = lastHeaders.filter((old, index) => index < MAX_HEADERS && old.number.unwrap().lt(blockNumber)).reduce((next, header) => {
next.push(header);
return next;
}, [lastHeader]).sort((a, b) => b.number.unwrap().cmp(a.number.unwrap()));
setState({
byAuthor,
lastBlockAuthors: lastBlockAuthors.slice(),
lastBlockNumber,
lastHeader,
lastHeaders
});
}
});
});
}, []);
return _react.default.createElement(ValidatorsContext.Provider, {
value: validators
}, _react.default.createElement(BlockAuthorsContext.Provider, {
value: state
}, children));
}