Add derive.chain.subscribeNewBlocks (#2765)

* Add derive.chain.subscribeNewBlocks

* Expand
This commit is contained in:
Jaco Greeff
2020-10-22 19:52:03 +02:00
committed by GitHub
parent 9f83f5cac3
commit fb82db382e
5 changed files with 47 additions and 1 deletions
+1
View File
@@ -5,4 +5,5 @@ export * from './bestNumber';
export * from './bestNumberFinalized';
export * from './bestNumberLag';
export * from './getHeader';
export * from './subscribeNewBlocks';
export * from './subscribeNewHeads';
@@ -0,0 +1,32 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { ApiInterfaceRx } from '@polkadot/api/types';
import { EventRecord, Hash, SignedBlock } from '@polkadot/types/interfaces';
import { FullNewBlock } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
/**
* @name subscribeNewBlocks
* @returns The latest block & events for that block
*/
export function subscribeNewBlocks (instanceId: string, api: ApiInterfaceRx): () => Observable<FullNewBlock> {
return memo(instanceId, (): Observable<FullNewBlock> =>
api.derive.chain.subscribeNewHeads().pipe(
switchMap((header): Observable<[Hash, EventRecord[], SignedBlock]> => {
const blockHash = header.hash;
return combineLatest(
of(blockHash),
api.query.system.events.at(blockHash),
api.rpc.chain.getBlock(header.hash)
);
}),
map(([blockHash, events, block]) => ({ block: block.block, blockHash, blockNumber: block.block.header.number.unwrap(), events, justification: block.justification }))
)
);
}
@@ -11,7 +11,7 @@ import { memo } from '../util';
/**
* @name subscribeNewHeads
* @returns An array containing the block header and the block author
* @returns A header with the current header (including extracted author)
* @description An observable of the current block header and it's author
* @example
* <BR>
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { Block, BlockNumber, EventRecord, Hash, Justification } from '@polkadot/types/interfaces';
export interface FullNewBlock {
block: Block;
blockHash: Hash;
blockNumber: BlockNumber;
events: EventRecord[];
justification: Justification;
}
+1
View File
@@ -7,6 +7,7 @@ import { AccountId, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidK
import { u32 } from '@polkadot/types';
export * from './accounts/types';
export * from './chain/types';
export * from './council/types';
export * from './democracy/types';
export * from './elections/types';