eslint rules (#1099)
* Off to the races - 3760 problems (1794 errors, 1966 warnings)
* Convert Array<T> -> T[] (not all correct, eg. extends)
* () => { -> (): void => {
* get is/as -> public get is/as
* public for getters, constructors & base Codec
* Some cleanups from previous overzealous search & replace
* Under 2k, 1874 problems (649 errors, 1225 warnings)
* ^^^ check that commit for details ;)
* Minor.
* rm config header
* Minor cleanups
* Default to tslint, eslint as option
* Trigger
* Update jsonrpc
* 1494 problems (433 errors, 1061 warnings)
* 1103 problems (135 errors, 968 warnings)
* 899 problems (9 errors, 890 warnings)
* 483 problems (9 errors, 474 warnings) (ignore any... for now)
* 366 problems (9 errors, 357 warnings)
* 336 problems (9 errors, 327 warnings)
* 148 problems (9 errors, 139 warnings)
* 31 problems (8 errors, 23 warnings)
* 0, 0
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, startWith } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, AccountIndex, Address } from '@polkadot/types';
|
||||
import { isU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
@@ -28,7 +28,7 @@ export type AccountIdAndIndex = [AccountId?, AccountIndex?];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function idAndIndex (api: ApiInterface$Rx) {
|
||||
export function idAndIndex (api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountIdAndIndex> {
|
||||
return (address?: Address | AccountId | AccountIndex | string | null): Observable<AccountIdAndIndex> => {
|
||||
try {
|
||||
// yes, this can fail, don't care too much, catch will catch it
|
||||
@@ -41,7 +41,7 @@ export function idAndIndex (api: ApiInterface$Rx) {
|
||||
|
||||
return idToIndex(api)(accountId).pipe(
|
||||
startWith(undefined),
|
||||
map((accountIndex) => [accountId, accountIndex] as AccountIdAndIndex),
|
||||
map((accountIndex): AccountIdAndIndex => [accountId, accountIndex] as AccountIdAndIndex),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ export function idAndIndex (api: ApiInterface$Rx) {
|
||||
|
||||
return indexToId(api)(accountIndex).pipe(
|
||||
startWith(undefined),
|
||||
map((accountId) => [accountId, accountIndex] as AccountIdAndIndex),
|
||||
map((accountId): AccountIdAndIndex => [accountId, accountIndex] as AccountIdAndIndex),
|
||||
drr()
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, startWith } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, AccountIndex } from '@polkadot/types';
|
||||
|
||||
import { indexes, AccountIndexes } from './indexes';
|
||||
@@ -24,12 +24,14 @@ import { drr } from '../util/drr';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function idToIndex (api: ApiInterface$Rx) {
|
||||
export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
|
||||
return (accountId: AccountId | string): Observable<AccountIndex | undefined> =>
|
||||
indexes(api)()
|
||||
.pipe(
|
||||
startWith({}),
|
||||
map((indexes: AccountIndexes) => (indexes || {})[accountId.toString()]),
|
||||
map((indexes: AccountIndexes): AccountIndex | undefined =>
|
||||
(indexes || {})[accountId.toString()]
|
||||
),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, startWith } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/primitive/AccountIndex';
|
||||
import { AccountId, AccountIndex, Vector } from '@polkadot/types';
|
||||
|
||||
@@ -23,8 +23,8 @@ import { drr } from '../util/drr';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function indexToId (api: ApiInterface$Rx) {
|
||||
return (_accountIndex: AccountIndex | string): Observable<AccountId> => {
|
||||
export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
|
||||
return (_accountIndex: AccountIndex | string): Observable<AccountId | undefined> => {
|
||||
const querySection = api.query.indices || api.query.balances;
|
||||
const accountIndex = _accountIndex instanceof AccountIndex
|
||||
? _accountIndex
|
||||
@@ -33,11 +33,10 @@ export function indexToId (api: ApiInterface$Rx) {
|
||||
return (querySection.enumSet<Vector<AccountId>>(accountIndex.div(ENUMSET_SIZE)))
|
||||
.pipe(
|
||||
startWith([]),
|
||||
map((accounts) =>
|
||||
map((accounts): AccountId | undefined =>
|
||||
(accounts || [])[accountIndex.mod(ENUMSET_SIZE).toNumber()]
|
||||
),
|
||||
drr()
|
||||
);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/primitive/AccountIndex';
|
||||
import { AccountId, AccountIndex } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
|
||||
export type AccountIndexes = { [index: string]: AccountIndex };
|
||||
export type AccountIndexes = Record<string, AccountIndex>;
|
||||
|
||||
const enumsetSize = ENUMSET_SIZE.toNumber();
|
||||
|
||||
@@ -29,7 +29,7 @@ const enumsetSize = ENUMSET_SIZE.toNumber();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function indexes (api: ApiInterface$Rx) {
|
||||
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
|
||||
return (): Observable<AccountIndexes> => {
|
||||
return (api.query.indices.nextEnumSet<AccountIndex>())
|
||||
.pipe(
|
||||
@@ -37,12 +37,12 @@ export function indexes (api: ApiInterface$Rx) {
|
||||
// a range of values to query [0, 1, 2, ...]. Retrieve the full enum set for the
|
||||
// specific index - each query can return up to ENUMSET_SIZE (64) records, each
|
||||
// containing an AccountId
|
||||
switchMap((next: AccountIndex) =>
|
||||
switchMap((next: AccountIndex): Observable<any> =>
|
||||
api.query.indices.enumSet.multi([...Array(next.toNumber() + 1).keys()]) as Observable<any>
|
||||
),
|
||||
map((all: Array<Array<AccountId> | undefined>) =>
|
||||
(all || []).reduce((result, list, outerIndex) => {
|
||||
(list || []).forEach((accountId, innerIndex) => {
|
||||
map((all: (AccountId[] | undefined)[]): AccountIndexes =>
|
||||
(all || []).reduce((result, list, outerIndex): AccountIndexes => {
|
||||
(list || []).forEach((accountId, innerIndex): void => {
|
||||
// re-create the index based on position 0 is [0][0] and likewise
|
||||
// 64 (0..63 in first) is [1][0] (the first index value in set 2)
|
||||
const index = (outerIndex * enumsetSize) + innerIndex;
|
||||
@@ -51,7 +51,7 @@ export function indexes (api: ApiInterface$Rx) {
|
||||
});
|
||||
|
||||
return result;
|
||||
}, {} as AccountIndexes)),
|
||||
}, {} as unknown as AccountIndexes)),
|
||||
drr()
|
||||
);
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import BN from 'bn.js';
|
||||
import { combineLatest, of, Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, AccountIndex, Address, Balance, BalanceLock, BlockNumber, Index, Option, VestingSchedule } from '@polkadot/types';
|
||||
import { bnMax } from '@polkadot/util';
|
||||
|
||||
@@ -14,7 +14,7 @@ import { bestNumber } from '../chain/bestNumber';
|
||||
import { DerivedBalances } from '../types';
|
||||
import { drr } from '../util/drr';
|
||||
|
||||
type Result = [AccountId | undefined, BlockNumber | undefined, [Balance?, Balance?, Array<BalanceLock>?, Option<VestingSchedule>?, Index?]];
|
||||
type Result = [AccountId | undefined, BlockNumber | undefined, [Balance?, Balance?, BalanceLock[]?, Option<VestingSchedule>?, Index?]];
|
||||
|
||||
const EMPTY_ACCOUNT = new AccountId();
|
||||
const ZERO = new Balance(0);
|
||||
@@ -24,10 +24,10 @@ function calcBalances ([accountId = EMPTY_ACCOUNT, bestNumber = ZERO, [freeBalan
|
||||
|
||||
if (Array.isArray(locks)) {
|
||||
// only get the locks that are valid until passed the current block
|
||||
const totals = locks.filter((value) => bestNumber && value.until.gt(bestNumber));
|
||||
const totals = locks.filter((value): boolean => bestNumber && value.until.gt(bestNumber));
|
||||
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
|
||||
lockedBalance = totals[0]
|
||||
? bnMax(...totals.map(({ amount }) => amount)) as Balance
|
||||
? bnMax(...totals.map(({ amount }): Balance => amount)) as Balance
|
||||
: ZERO;
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ function calcBalances ([accountId = EMPTY_ACCOUNT, bestNumber = ZERO, [freeBalan
|
||||
reservedBalance,
|
||||
vestedBalance,
|
||||
votingBalance: freeBalance.add(reservedBalance)
|
||||
} as DerivedBalances;
|
||||
} as unknown as DerivedBalances;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,10 +73,10 @@ function calcBalances ([accountId = EMPTY_ACCOUNT, bestNumber = ZERO, [freeBalan
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function all (api: ApiInterface$Rx) {
|
||||
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DerivedBalances> {
|
||||
return (address: AccountIndex | AccountId | Address | string): Observable<DerivedBalances> => {
|
||||
return idAndIndex(api)(address).pipe(
|
||||
switchMap(([accountId]) =>
|
||||
switchMap(([accountId]): Observable<Result> =>
|
||||
(accountId
|
||||
? combineLatest([
|
||||
of(accountId),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DerivedFees } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
@@ -24,7 +24,7 @@ import { drr } from '../util/drr';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function fees (api: ApiInterface$Rx) {
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DerivedFees> {
|
||||
return (): Observable<DerivedFees> => {
|
||||
return (
|
||||
api.consts.balances
|
||||
@@ -45,13 +45,14 @@ export function fees (api: ApiInterface$Rx) {
|
||||
api.query.balances.transactionByteFee,
|
||||
api.query.balances.transferFee
|
||||
]) as any as Observable<[BN, BN, BN, BN, BN]>
|
||||
).pipe(map(([creationFee, existentialDeposit, transactionBaseFee, transactionByteFee, transferFee]) => ({
|
||||
).pipe(
|
||||
map(([creationFee, existentialDeposit, transactionBaseFee, transactionByteFee, transferFee]): DerivedFees => ({
|
||||
creationFee,
|
||||
existentialDeposit,
|
||||
transactionBaseFee,
|
||||
transactionByteFee,
|
||||
transferFee
|
||||
} as DerivedFees)),
|
||||
} as unknown as DerivedFees)),
|
||||
drr()
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,18 +3,18 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { combineLatest, Observable, of } from 'rxjs';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, AccountIndex, Address } from '@polkadot/types';
|
||||
|
||||
import { DerivedBalances } from '../types';
|
||||
import { drr } from '../util/drr';
|
||||
import { all } from './all';
|
||||
|
||||
export function votingBalances (api: ApiInterface$Rx) {
|
||||
return (addresses?: Array<AccountId | AccountIndex | Address | string>): Observable<Array<DerivedBalances>> => {
|
||||
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DerivedBalances[]> {
|
||||
return (addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DerivedBalances[]> => {
|
||||
return (
|
||||
!addresses || !addresses.length
|
||||
? of([] as Array<DerivedBalances>)
|
||||
? of([] as DerivedBalances[])
|
||||
: combineLatest(addresses.map(all(api)))
|
||||
).pipe(
|
||||
drr()
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, AccountIndex, Address, Vector } from '@polkadot/types';
|
||||
|
||||
import { idAndIndex } from '../accounts/idAndIndex';
|
||||
@@ -12,13 +12,13 @@ import { DerivedBalances } from '../types';
|
||||
import { drr } from '../util/drr';
|
||||
import { votingBalances } from './votingBalances';
|
||||
|
||||
export function votingBalancesNominatorsFor (api: ApiInterface$Rx) {
|
||||
return (address: AccountId | AccountIndex | Address | string): Observable<Array<DerivedBalances>> => {
|
||||
export function votingBalancesNominatorsFor (api: ApiInterfaceRx): (address: AccountId | AccountIndex | Address | string) => Observable<DerivedBalances[]> {
|
||||
return (address: AccountId | AccountIndex | Address | string): Observable<DerivedBalances[]> => {
|
||||
return idAndIndex(api)(address).pipe(
|
||||
switchMap(([accountId]) =>
|
||||
switchMap(([accountId]): Observable<AccountId[]> =>
|
||||
accountId
|
||||
? (api.query.staking.nominatorsFor<Vector<AccountId>>(accountId))
|
||||
: of([] as Array<AccountId>)
|
||||
: of([] as AccountId[])
|
||||
),
|
||||
switchMap(votingBalances(api)),
|
||||
drr()
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BlockNumber, Header } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
@@ -21,12 +21,12 @@ import { drr } from '../util/drr';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function bestNumber (api: ApiInterface$Rx) {
|
||||
export function bestNumber (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return (): Observable<BlockNumber> =>
|
||||
(api.rpc.chain.subscribeNewHead() as Observable<Header>)
|
||||
.pipe(
|
||||
filter((header: Header) => header && !!header.blockNumber),
|
||||
map(({ blockNumber }: Header) => blockNumber),
|
||||
filter((header: Header): boolean => !!header && !!header.blockNumber),
|
||||
map(({ blockNumber }: Header): BlockNumber => blockNumber),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BlockNumber, Header } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
@@ -22,12 +22,12 @@ import { drr } from '../util/drr';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function bestNumberFinalized (api: ApiInterface$Rx) {
|
||||
export function bestNumberFinalized (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return (): Observable<BlockNumber> =>
|
||||
(api.rpc.chain.subscribeFinalizedHeads() as Observable<Header>)
|
||||
.pipe(
|
||||
filter((header: Header) => header && !!header.blockNumber),
|
||||
map(({ blockNumber }: Header) => blockNumber),
|
||||
filter((header: Header): boolean => !!header && !!header.blockNumber),
|
||||
map(({ blockNumber }: Header): BlockNumber => blockNumber),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable, combineLatest } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BlockNumber } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
@@ -24,13 +24,13 @@ import { bestNumberFinalized } from './bestNumberFinalized';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function bestNumberLag (api: ApiInterface$Rx) {
|
||||
export function bestNumberLag (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return (): Observable<BlockNumber> =>
|
||||
combineLatest([
|
||||
bestNumber(api)(),
|
||||
bestNumberFinalized(api)()
|
||||
]).pipe(
|
||||
map(([bestNumber, bestNumberFinalized]) =>
|
||||
map(([bestNumber, bestNumberFinalized]): BlockNumber =>
|
||||
new BlockNumber(bestNumber.sub(bestNumberFinalized))
|
||||
),
|
||||
drr()
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { catchError, map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Header } from '@polkadot/types';
|
||||
|
||||
import { HeaderExtended } from '../type';
|
||||
@@ -25,7 +25,7 @@ import { HeaderAndValidators } from './subscribeNewHead';
|
||||
* console.log(`block #${blockNumber} was authored by ${author}`);
|
||||
* ```
|
||||
*/
|
||||
export function getHeader (api: ApiInterface$Rx) {
|
||||
export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
|
||||
return (hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
|
||||
// tslint:disable-next-line
|
||||
(combineLatest([
|
||||
@@ -34,10 +34,10 @@ export function getHeader (api: ApiInterface$Rx) {
|
||||
? api.query.session.validators.at(hash)
|
||||
: of([])
|
||||
]) as Observable<HeaderAndValidators>).pipe(
|
||||
map(([header, validators]) =>
|
||||
map(([header, validators]): HeaderExtended =>
|
||||
new HeaderExtended(header, validators)
|
||||
),
|
||||
catchError(() =>
|
||||
catchError((): Observable<undefined> =>
|
||||
// where rpc.chain.getHeader throws, we will land here - it can happen that
|
||||
// we supplied an invalid hash. (Due to defaults, storeage will have an
|
||||
// empty value, so only the RPC is affected). So return undefined
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { filter, map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Header } from '@polkadot/types';
|
||||
|
||||
import { HeaderExtended } from '../type';
|
||||
import { drr } from '../util/drr';
|
||||
|
||||
export type HeaderAndValidators = [Header, Array<AccountId>];
|
||||
export type HeaderAndValidators = [Header, AccountId[]];
|
||||
|
||||
/**
|
||||
* @name subscribeNewHead
|
||||
@@ -25,13 +25,11 @@ export type HeaderAndValidators = [Header, Array<AccountId>];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function subscribeNewHead (api: ApiInterface$Rx) {
|
||||
export function subscribeNewHead (api: ApiInterfaceRx): () => Observable<HeaderExtended> {
|
||||
return (): Observable<HeaderExtended> =>
|
||||
(api.rpc.chain.subscribeNewHead() as Observable<Header>)
|
||||
.pipe(
|
||||
filter((header: Header) =>
|
||||
header && !!header.blockNumber
|
||||
),
|
||||
filter((header: Header): boolean => !!header && !!header.blockNumber),
|
||||
switchMap((header: Header): Observable<HeaderAndValidators> =>
|
||||
(combineLatest([
|
||||
of(header),
|
||||
@@ -43,7 +41,7 @@ export function subscribeNewHead (api: ApiInterface$Rx) {
|
||||
: of([])
|
||||
]) as Observable<HeaderAndValidators>)
|
||||
),
|
||||
map(([header, validators]) =>
|
||||
map(([header, validators]): HeaderExtended =>
|
||||
new HeaderExtended(header, validators)
|
||||
),
|
||||
drr()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DerivedContractFees } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
@@ -26,7 +26,7 @@ const ZERO = new BN(0);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function fees (api: ApiInterface$Rx) {
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DerivedContractFees> {
|
||||
return (): Observable<DerivedContractFees> => {
|
||||
const queryBase = api.query.contracts || api.query.contract;
|
||||
|
||||
@@ -44,11 +44,11 @@ export function fees (api: ApiInterface$Rx) {
|
||||
queryBase.transactionByteFee,
|
||||
queryBase.transferFee
|
||||
])
|
||||
]) as any as Observable<Array<Array<BN>>>).pipe(
|
||||
]) as unknown as Observable<BN[][]>).pipe(
|
||||
map(([
|
||||
[rentByteFee, rentDepositOffset, tombstoneDeposit],
|
||||
[callBaseFee, contractFee, createBaseFee, creationFee, transactionBaseFee, transactionByteFee, transferFee]
|
||||
]) => ({
|
||||
]): DerivedContractFees => ({
|
||||
callBaseFee,
|
||||
contractFee,
|
||||
createBaseFee,
|
||||
@@ -59,7 +59,7 @@ export function fees (api: ApiInterface$Rx) {
|
||||
transactionBaseFee,
|
||||
transactionByteFee,
|
||||
transferFee
|
||||
} as DerivedContractFees)),
|
||||
} as unknown as DerivedContractFees)),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
@@ -79,7 +79,7 @@ export function fees (api: ApiInterface$Rx) {
|
||||
api.consts.contracts.transactionBaseFee,
|
||||
api.consts.contracts.transactionByteFee,
|
||||
api.consts.contracts.transferFee
|
||||
]) as any as Observable<Array<BN>>
|
||||
]) as unknown as Observable<BN[]>
|
||||
// Support versions pre spec_version 101 and get values from storage
|
||||
: api.queryMulti([
|
||||
queryBase.callBaseFee,
|
||||
@@ -92,9 +92,10 @@ export function fees (api: ApiInterface$Rx) {
|
||||
queryBase.transactionBaseFee,
|
||||
queryBase.transactionByteFee,
|
||||
queryBase.transferFee
|
||||
]) as any as Observable<Array<BN>>
|
||||
).pipe(map(
|
||||
([callBaseFee, contractFee, createBaseFee, creationFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee, transferFee]) => ({
|
||||
]) as unknown as Observable<BN[]>
|
||||
).pipe(
|
||||
map(
|
||||
([callBaseFee, contractFee, createBaseFee, creationFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee, transferFee]): DerivedContractFees => ({
|
||||
callBaseFee,
|
||||
contractFee,
|
||||
createBaseFee,
|
||||
@@ -105,7 +106,7 @@ export function fees (api: ApiInterface$Rx) {
|
||||
transactionBaseFee,
|
||||
transactionByteFee,
|
||||
transferFee
|
||||
} as DerivedContractFees)
|
||||
} as unknown as DerivedContractFees)
|
||||
),
|
||||
drr()
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import BN from 'bn.js';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, ReferendumInfo } from '@polkadot/types';
|
||||
import { isNull } from '@polkadot/util';
|
||||
|
||||
@@ -25,15 +25,14 @@ export function constructInfo (index: BN | number, optionInfo?: Option<Referendu
|
||||
);
|
||||
}
|
||||
|
||||
export function referendumInfo (api: ApiInterface$Rx) {
|
||||
export function referendumInfo (api: ApiInterfaceRx): (index: BN | number) => Observable<Option<ReferendumInfoExtended>> {
|
||||
return (index: BN | number): Observable<Option<ReferendumInfoExtended>> => {
|
||||
return (api.query.democracy.referendumInfoOf<Option<ReferendumInfo>>(index))
|
||||
.pipe(
|
||||
map((optionInfo) =>
|
||||
map((optionInfo): Option<ReferendumInfoExtended> =>
|
||||
constructInfo(index, optionInfo)
|
||||
),
|
||||
drr()
|
||||
);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -5,27 +5,26 @@
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, ReferendumInfo, Vector } from '@polkadot/types';
|
||||
|
||||
import { ReferendumInfoExtended } from '../type';
|
||||
import { drr } from '../util/drr';
|
||||
import { constructInfo } from './referendumInfo';
|
||||
|
||||
export function referendumInfos (api: ApiInterface$Rx) {
|
||||
return (ids: Array<BN | number> = []): Observable<Array<Option<ReferendumInfoExtended>>> => {
|
||||
export function referendumInfos (api: ApiInterfaceRx): (ids?: (BN | number)[]) => Observable<Option<ReferendumInfoExtended>[]> {
|
||||
return (ids: (BN | number)[] = []): Observable<Option<ReferendumInfoExtended>[]> => {
|
||||
return (
|
||||
!ids || !ids.length
|
||||
? of([] as Array<Option<ReferendumInfo>>)
|
||||
? of([] as Option<ReferendumInfo>[])
|
||||
: api.query.democracy.referendumInfoOf.multi(ids) as Observable<Vector<Option<ReferendumInfo>>>
|
||||
).pipe(
|
||||
map((infos) =>
|
||||
ids.map((id, index) =>
|
||||
constructInfo(id, infos[index])
|
||||
)
|
||||
),
|
||||
drr()
|
||||
);
|
||||
map((infos): Option<ReferendumInfoExtended>[] =>
|
||||
ids.map((id, index): Option<ReferendumInfoExtended> =>
|
||||
constructInfo(id, infos[index])
|
||||
)
|
||||
),
|
||||
drr()
|
||||
);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -5,30 +5,30 @@
|
||||
import BN from 'bn.js';
|
||||
import { combineLatest, Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Balance, Vector, Vote } from '@polkadot/types';
|
||||
|
||||
import { DerivedReferendumVote } from '../types';
|
||||
import { DerivedBalances, DerivedReferendumVote } from '../types';
|
||||
import { drr } from '../util/drr';
|
||||
import { votes } from './votes';
|
||||
import { votingBalances } from '../balances/votingBalances';
|
||||
|
||||
export function referendumVotesFor (api: ApiInterface$Rx) {
|
||||
return (referendumId: BN | number): Observable<Array<DerivedReferendumVote>> =>
|
||||
export function referendumVotesFor (api: ApiInterfaceRx): (referendumId: BN | number) => Observable<DerivedReferendumVote[]> {
|
||||
return (referendumId: BN | number): Observable<DerivedReferendumVote[]> =>
|
||||
(api.query.democracy.votersFor<Vector<AccountId>>(referendumId)).pipe(
|
||||
switchMap((votersFor) =>
|
||||
switchMap((votersFor): Observable<[Vector<AccountId>, Vote[], DerivedBalances[]]> =>
|
||||
combineLatest([
|
||||
of(votersFor),
|
||||
votes(api)(referendumId as BN, votersFor),
|
||||
votingBalances(api)(votersFor)
|
||||
])
|
||||
),
|
||||
map(([votersFor, votes, balances]) =>
|
||||
map(([votersFor, votes, balances]): DerivedReferendumVote[] =>
|
||||
votersFor.map((accountId, index): DerivedReferendumVote => ({
|
||||
accountId,
|
||||
balance: balances[index].votingBalance || new Balance(0),
|
||||
vote: votes[index] || new Vote(0)
|
||||
} as DerivedReferendumVote))
|
||||
} as unknown as DerivedReferendumVote))
|
||||
),
|
||||
drr()
|
||||
);
|
||||
|
||||
@@ -2,25 +2,26 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, ReferendumIndex } from '@polkadot/types';
|
||||
|
||||
import { ReferendumInfoExtended } from '../type';
|
||||
import { drr } from '../util/drr';
|
||||
import { referendumInfos } from './referendumInfos';
|
||||
|
||||
export function referendums (api: ApiInterface$Rx) {
|
||||
return (): Observable<Array<Option<ReferendumInfoExtended>>> =>
|
||||
export function referendums (api: ApiInterfaceRx): () => Observable<Option<ReferendumInfoExtended>[]> {
|
||||
return (): Observable<Option<ReferendumInfoExtended>[]> =>
|
||||
(api.queryMulti([
|
||||
api.query.democracy.nextTally,
|
||||
api.query.democracy.referendumCount
|
||||
]) as any as Observable<[ReferendumIndex?, ReferendumIndex?]>).pipe(
|
||||
switchMap(([nextTally, referendumCount]) =>
|
||||
switchMap(([nextTally, referendumCount]): Observable<Option<ReferendumInfoExtended>[]> =>
|
||||
referendumCount && nextTally && referendumCount.gt(nextTally) && referendumCount.gtn(0)
|
||||
? referendumInfos(api)(
|
||||
[...Array(referendumCount.sub(nextTally).toNumber())].map((_, i) =>
|
||||
[...Array(referendumCount.sub(nextTally).toNumber())].map((_, i): BN =>
|
||||
nextTally.addn(i)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -4,19 +4,21 @@
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Vector, Vote } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
|
||||
export function votes (api: ApiInterface$Rx) {
|
||||
return (referendumId: BN, accountIds: Array<AccountId> = []): Observable<Array<Vote>> => {
|
||||
export function votes (api: ApiInterfaceRx): (referendumId: BN, accountIds?: AccountId[]) => Observable<Vote[]> {
|
||||
return (referendumId: BN, accountIds: AccountId[] = []): Observable<Vote[]> => {
|
||||
return ((
|
||||
!accountIds || !accountIds.length
|
||||
? of([])
|
||||
: api.query.democracy.voteOf.multi(
|
||||
accountIds.map((accountId) => [referendumId, accountId])
|
||||
accountIds.map((accountId): [BN, AccountId] =>
|
||||
[referendumId, accountId]
|
||||
)
|
||||
) as Observable<Vector<Vote>>).pipe(drr());
|
||||
)
|
||||
) as Observable<Vector<Vote>>).pipe(drr());
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,17 +8,17 @@ import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
|
||||
import { Derive } from '.';
|
||||
|
||||
const testFunction = (api: ApiRx) => {
|
||||
const testFunction = (api: ApiRx): any => {
|
||||
return <
|
||||
Section extends keyof Derive,
|
||||
Method extends keyof (typeof api.derive[Section])
|
||||
>(section: Section, method: Method, inputs: any[]) => {
|
||||
describe(`derive.${section}.${method}`, () => {
|
||||
it('should be a function', () => {
|
||||
>(section: Section, method: Method, inputs: any[]): void => {
|
||||
describe(`derive.${section}.${method}`, (): void => {
|
||||
it('should be a function', (): void => {
|
||||
expect(typeof api.derive[section][method]).toBe('function');
|
||||
});
|
||||
|
||||
it('should return an Observable', () => {
|
||||
it('should return an Observable', (): void => {
|
||||
expect((api.derive[section][method] as any)(...inputs)).toBeInstanceOf(Observable);
|
||||
});
|
||||
});
|
||||
@@ -27,12 +27,12 @@ const testFunction = (api: ApiRx) => {
|
||||
|
||||
// https://github.com/polkadot-js/api/pull/1066#issuecomment-509142048
|
||||
// https://github.com/polkadot-js/api/issues/1064
|
||||
describe.skip('derive', () => {
|
||||
describe('builtin', () => {
|
||||
describe.skip('derive', (): void => {
|
||||
describe('builtin', (): void => {
|
||||
const api = new ApiRx(new MockProvider());
|
||||
|
||||
beforeAll((done) => {
|
||||
api.isReady.subscribe(() => done());
|
||||
beforeAll((done): void => {
|
||||
api.isReady.subscribe((): void => done());
|
||||
});
|
||||
|
||||
testFunction(api)('accounts', 'idAndIndex', []);
|
||||
@@ -59,21 +59,21 @@ describe.skip('derive', () => {
|
||||
testFunction(api)('session', 'sessionProgress', []);
|
||||
});
|
||||
|
||||
describe('custom', () => {
|
||||
describe('custom', (): void => {
|
||||
const api = new ApiRx({
|
||||
derives: {
|
||||
balances: {
|
||||
fees: () => () => from(['a', 'b'])
|
||||
fees: (): any => (): Observable<any> => from(['a', 'b'])
|
||||
},
|
||||
custom: {
|
||||
test: () => () => from([1, 2, 3])
|
||||
test: (): any => (): Observable<any> => from([1, 2, 3])
|
||||
}
|
||||
},
|
||||
provider: new MockProvider()
|
||||
});
|
||||
|
||||
beforeAll((done) => {
|
||||
api.isReady.subscribe(() => done());
|
||||
beforeAll((done): void => {
|
||||
api.isReady.subscribe((): void => done());
|
||||
});
|
||||
|
||||
// override
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AnyFunction } from '@polkadot/types/types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
@@ -19,33 +19,29 @@ export * from './type';
|
||||
|
||||
export type ReturnTypes<Section> = {
|
||||
[Method in keyof Section]: Section[Method] extends AnyFunction
|
||||
? ReturnType<Section[Method]> // ReturnType<Section[Method]> will be the inner function, i.e. without (api) argument
|
||||
: never;
|
||||
? ReturnType<Section[Method]> // ReturnType<Section[Method]> will be the inner function, i.e. without (api) argument
|
||||
: never;
|
||||
};
|
||||
|
||||
export type DeriveSections<AllSections> = {
|
||||
[Section in keyof AllSections]: ReturnTypes<AllSections[Section]>
|
||||
};
|
||||
|
||||
export interface DeriveCustom {
|
||||
[index: string]: {
|
||||
[index: string]: (api: ApiInterface$Rx) => (...args: Array<any>) => Observable<any>
|
||||
};
|
||||
}
|
||||
export type DeriveCustom = Record<string, Record<string, (api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
|
||||
|
||||
/**
|
||||
* Returns an object that will inject `api` into all the functions inside
|
||||
* `allSections`, and keep the object architecture of `allSections`.
|
||||
*/
|
||||
function injectFunctions<AllSections> (api: ApiInterface$Rx, allSections: AllSections) {
|
||||
function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSections): DeriveSections<AllSections> {
|
||||
return Object
|
||||
.keys(allSections)
|
||||
.reduce((deriveAcc, sectionName) => {
|
||||
.reduce((deriveAcc, sectionName): DeriveSections<AllSections> => {
|
||||
const section = allSections[sectionName as keyof AllSections];
|
||||
|
||||
deriveAcc[sectionName as keyof AllSections] = Object
|
||||
.keys(section)
|
||||
.reduce((sectionAcc, _methodName) => {
|
||||
.reduce((sectionAcc, _methodName): ReturnTypes<typeof section> => {
|
||||
const methodName = _methodName as keyof typeof section;
|
||||
// Not sure what to do here, casting as any. Though the final types are good
|
||||
const method = (section[methodName] as any)(api);
|
||||
@@ -53,16 +49,18 @@ function injectFunctions<AllSections> (api: ApiInterface$Rx, allSections: AllSec
|
||||
(sectionAcc as any)[methodName] = method;
|
||||
|
||||
return sectionAcc;
|
||||
}, {} as ReturnTypes<typeof section>);
|
||||
}, {} as unknown as ReturnTypes<typeof section>);
|
||||
|
||||
return deriveAcc;
|
||||
}, {} as DeriveSections<AllSections>);
|
||||
}, {} as unknown as DeriveSections<AllSections>);
|
||||
}
|
||||
|
||||
export const derive = { accounts, balances, chain, contracts, democracy, session, staking };
|
||||
export type Derive = typeof derive;
|
||||
|
||||
export default function decorateDerive (api: ApiInterface$Rx, custom: DeriveCustom = {}) {
|
||||
// FIXME I have no idea how to get this done
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
||||
export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}) {
|
||||
return {
|
||||
...injectFunctions(api, derive),
|
||||
...injectFunctions(api, custom)
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
import BN from 'bn.js';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
import { info } from './info';
|
||||
|
||||
export function eraLength (api: ApiInterface$Rx) {
|
||||
export function eraLength (api: ApiInterfaceRx): () => Observable<BN> {
|
||||
return (): Observable<BN> =>
|
||||
info(api)().pipe(
|
||||
map(({ eraLength }) => eraLength),
|
||||
map(({ eraLength }): BN => eraLength),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
import BN from 'bn.js';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
import { info } from './info';
|
||||
|
||||
export function eraProgress (api: ApiInterface$Rx) {
|
||||
export function eraProgress (api: ApiInterfaceRx): () => Observable<BN> {
|
||||
return (): Observable<BN> =>
|
||||
info(api)().pipe(
|
||||
map(({ eraProgress }) => eraProgress),
|
||||
map(({ eraProgress }): BN => eraProgress),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@ import { DerivedSessionInfo } from '../types';
|
||||
import BN from 'bn.js';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BlockNumber, Option } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
import { bestNumber } from '../chain';
|
||||
|
||||
type Result_0_94 = [BN, [BN, Option<BlockNumber>, BN, BN, BN]];
|
||||
type Result0to94 = [BN, [BN, Option<BlockNumber>, BN, BN, BN]];
|
||||
type Result = [BN, [BN, BN]];
|
||||
|
||||
const ZERO = new BN(0);
|
||||
|
||||
// internal helper to just split the logic - take all inputs, do the calculations and combine
|
||||
function createDerived_0_94 ([bestNumber, [currentIndex, _lastLengthChange, sessionLength, lastEraLengthChange, sessionsPerEra]]: Result_0_94): DerivedSessionInfo {
|
||||
function createDerived0to94 ([bestNumber, [currentIndex, _lastLengthChange, sessionLength, lastEraLengthChange, sessionsPerEra]]: Result0to94): DerivedSessionInfo {
|
||||
const eraLength = sessionLength.mul(sessionsPerEra);
|
||||
const lastLengthChange = _lastLengthChange
|
||||
? _lastLengthChange.unwrapOr(ZERO)
|
||||
@@ -45,7 +45,7 @@ function createDerived_0_94 ([bestNumber, [currentIndex, _lastLengthChange, sess
|
||||
sessionLength,
|
||||
sessionsPerEra,
|
||||
sessionProgress
|
||||
} as DerivedSessionInfo;
|
||||
} as unknown as DerivedSessionInfo;
|
||||
}
|
||||
|
||||
function createDerived ([sessionsPerEra, [currentIndex, currentEra]]: Result): DerivedSessionInfo {
|
||||
@@ -61,43 +61,47 @@ function createDerived ([sessionsPerEra, [currentIndex, currentEra]]: Result): D
|
||||
sessionLength: ZERO,
|
||||
sessionsPerEra,
|
||||
sessionProgress: ZERO
|
||||
} as DerivedSessionInfo;
|
||||
} as unknown as DerivedSessionInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Retrieves all the session and era info and calculates specific values on it as the length of the session and eras
|
||||
*/
|
||||
export function info (api: ApiInterface$Rx) {
|
||||
export function info (api: ApiInterfaceRx): () => Observable<DerivedSessionInfo> {
|
||||
return (): Observable<DerivedSessionInfo> => {
|
||||
// With substrate `spec_version 94`, the era and session has been explicitly exposed as `parameter_types`.
|
||||
// pre-94 we had more info and needed to calculate (handle old/Alex first)
|
||||
// https://github.com/paritytech/substrate/commit/dbf322620948935d2bbae214504e6c668c3073ed#diff-c29f42d6b931fa93ba038dbbbfec3055
|
||||
return api.query.session.lastLengthChange
|
||||
? (combineLatest([
|
||||
bestNumber(api)(),
|
||||
api.queryMulti([
|
||||
api.query.session.currentIndex,
|
||||
api.query.session.lastLengthChange,
|
||||
api.query.session.sessionLength,
|
||||
api.query.staking.lastEraLengthChange,
|
||||
api.query.staking.sessionsPerEra
|
||||
])
|
||||
]) as any as Observable<Result_0_94>).pipe(
|
||||
map(createDerived_0_94),
|
||||
? (
|
||||
combineLatest([
|
||||
bestNumber(api)(),
|
||||
api.queryMulti([
|
||||
api.query.session.currentIndex,
|
||||
api.query.session.lastLengthChange,
|
||||
api.query.session.sessionLength,
|
||||
api.query.staking.lastEraLengthChange,
|
||||
api.query.staking.sessionsPerEra
|
||||
])
|
||||
]) as any as Observable<Result0to94>
|
||||
).pipe(
|
||||
map(createDerived0to94),
|
||||
drr()
|
||||
)
|
||||
: (combineLatest([
|
||||
// sessionsPerEra:
|
||||
// substrate spec_version >= 94 : get from parameter_types exposed as api.consts
|
||||
// https://github.com/paritytech/substrate/pull/2802/files#diff-5e5e1c3aec9ddfde0a9054d062ab3db9R156
|
||||
of(api.consts.staking.sessionsPerEra),
|
||||
api.queryMulti([
|
||||
api.query.session.currentIndex,
|
||||
api.query.staking.currentEra
|
||||
])
|
||||
]) as any as Observable<Result>).pipe(
|
||||
map(createDerived),
|
||||
drr()
|
||||
);
|
||||
: (
|
||||
combineLatest([
|
||||
// sessionsPerEra:
|
||||
// substrate spec_version >= 94 : get from parameter_types exposed as api.consts
|
||||
// https://github.com/paritytech/substrate/pull/2802/files#diff-5e5e1c3aec9ddfde0a9054d062ab3db9R156
|
||||
of(api.consts.staking.sessionsPerEra),
|
||||
api.queryMulti([
|
||||
api.query.session.currentIndex,
|
||||
api.query.staking.currentEra
|
||||
])
|
||||
]) as unknown as Observable<Result>
|
||||
).pipe(
|
||||
map(createDerived),
|
||||
drr()
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
import BN from 'bn.js';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
import { info } from './info';
|
||||
|
||||
export function sessionProgress (api: ApiInterface$Rx) {
|
||||
export function sessionProgress (api: ApiInterfaceRx): () => Observable<BN> {
|
||||
return (): Observable<BN> =>
|
||||
info(api)().pipe(
|
||||
map(({ sessionProgress }) => sessionProgress),
|
||||
map(({ sessionProgress }): BN => sessionProgress),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Option } from '@polkadot/types';
|
||||
|
||||
import { drr } from '../util/drr';
|
||||
@@ -12,14 +12,14 @@ import { drr } from '../util/drr';
|
||||
/**
|
||||
* @description From the list of stash accounts, retrieve the list of controllers
|
||||
*/
|
||||
export function controllers (api: ApiInterface$Rx) {
|
||||
return (): Observable<[Array<AccountId>, Array<Option<AccountId>>]> =>
|
||||
(api.query.staking.validators() as any as Observable<[Array<AccountId>, any]>)
|
||||
export function controllers (api: ApiInterfaceRx): () => Observable<[AccountId[], Option<AccountId>[]]> {
|
||||
return (): Observable<[AccountId[], Option<AccountId>[]]> =>
|
||||
(api.query.staking.validators() as any as Observable<[AccountId[], any]>)
|
||||
.pipe(
|
||||
switchMap(([stashIds]) =>
|
||||
switchMap(([stashIds]): Observable<[AccountId[], Option<AccountId>[]]> =>
|
||||
combineLatest([
|
||||
of(stashIds),
|
||||
api.query.staking.bonded.multi(stashIds) as any as Observable<Array<Option<AccountId>>>
|
||||
api.query.staking.bonded.multi(stashIds) as any as Observable<Option<AccountId>[]>
|
||||
])
|
||||
),
|
||||
drr()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterface$Rx } from '@polkadot/api/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DerivedStaking, DerivedUnlocking } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
@@ -16,30 +16,8 @@ import { bestNumber } from '../chain/bestNumber';
|
||||
import { eraLength } from '../session/eraLength';
|
||||
import { drr } from '../util/drr';
|
||||
|
||||
function calculateUnlocking (stakingLedger: StakingLedger | undefined, eraLength: BN, bestNumber: BlockNumber): DerivedUnlocking | undefined {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// select the Unlockchunks that can't be redeemed yet.
|
||||
const unlockingChunks = stakingLedger.unlocking.filter((chunk) => remainingBlocks(chunk.era, eraLength, bestNumber).gtn(0));
|
||||
|
||||
if (!unlockingChunks.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// group the Unlockchunks that have the same era and sum their values
|
||||
const groupedResult = groupByEra(unlockingChunks);
|
||||
const results = Object.entries(groupedResult).map(([eraString, value]) => ({
|
||||
value,
|
||||
remainingBlocks: remainingBlocks(new BlockNumber(eraString), eraLength, bestNumber)
|
||||
}));
|
||||
|
||||
return results.length ? results : undefined;
|
||||
}
|
||||
|
||||
function groupByEra (list: UnlockChunk[]) {
|
||||
return list.reduce((map, { era, value }) => {
|
||||
function groupByEra (list: UnlockChunk[]): Record<string, BN> {
|
||||
return list.reduce((map, { era, value }): Record<string, BN> => {
|
||||
const key = era.toString();
|
||||
|
||||
if (!map[key]) {
|
||||
@@ -49,27 +27,51 @@ function groupByEra (list: UnlockChunk[]) {
|
||||
}
|
||||
|
||||
return map;
|
||||
}, {} as { [index: string]: BN });
|
||||
}, {} as unknown as Record<string, BN>);
|
||||
}
|
||||
|
||||
function redeemableSum (stakingLedger: StakingLedger | undefined, eraLength: BN, bestNumber: BlockNumber) {
|
||||
function remainingBlocks (era: BN, eraLength: BN, bestNumber: BlockNumber): BN {
|
||||
const remaining = eraLength.mul(era).sub(bestNumber);
|
||||
|
||||
return remaining.lten(0) ? new BN(0) : remaining;
|
||||
}
|
||||
|
||||
function calculateUnlocking (stakingLedger: StakingLedger | undefined, eraLength: BN, bestNumber: BlockNumber): DerivedUnlocking | undefined {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// select the Unlockchunks that can't be redeemed yet.
|
||||
const unlockingChunks = stakingLedger.unlocking.filter((chunk): boolean =>
|
||||
remainingBlocks(chunk.era, eraLength, bestNumber).gtn(0)
|
||||
);
|
||||
|
||||
if (!unlockingChunks.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// group the Unlockchunks that have the same era and sum their values
|
||||
const groupedResult = groupByEra(unlockingChunks);
|
||||
const results = Object.entries(groupedResult).map(([eraString, value]): { value: BN; remainingBlocks: BN } => ({
|
||||
value,
|
||||
remainingBlocks: remainingBlocks(new BlockNumber(eraString), eraLength, bestNumber)
|
||||
}));
|
||||
|
||||
return results.length ? results : undefined;
|
||||
}
|
||||
|
||||
function redeemableSum (stakingLedger: StakingLedger | undefined, eraLength: BN, bestNumber: BlockNumber): BN {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return new BN(0);
|
||||
}
|
||||
|
||||
return stakingLedger.unlocking
|
||||
.filter((chunk) => remainingBlocks(chunk.era, eraLength, bestNumber).eqn(0))
|
||||
.reduce((curr, prev) => {
|
||||
.filter((chunk): boolean => remainingBlocks(chunk.era, eraLength, bestNumber).eqn(0))
|
||||
.reduce((curr, prev): BN => {
|
||||
return curr.add(prev.value);
|
||||
}, new BN(0));
|
||||
}
|
||||
|
||||
function remainingBlocks (era: BN, eraLength: BN, bestNumber: BlockNumber) {
|
||||
const remaining = eraLength.mul(era).sub(bestNumber);
|
||||
|
||||
return remaining.lten(0) ? new BN(0) : remaining;
|
||||
}
|
||||
|
||||
function nextSessionId (_nextKeyFor: Option<Keys | SessionKey>): AccountId | undefined {
|
||||
const nextKeyFor: SessionKeys | SessionKey | null = _nextKeyFor.unwrapOr(null);
|
||||
|
||||
@@ -79,7 +81,7 @@ function nextSessionId (_nextKeyFor: Option<Keys | SessionKey>): AccountId | und
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function withStashController (api: ApiInterface$Rx, accountId: AccountId, controllerId: AccountId): Observable<DerivedStaking> {
|
||||
function withStashController (api: ApiInterfaceRx, accountId: AccountId, controllerId: AccountId): Observable<DerivedStaking> {
|
||||
const stashId = accountId;
|
||||
|
||||
return (
|
||||
@@ -94,9 +96,9 @@ function withStashController (api: ApiInterface$Rx, accountId: AccountId, contro
|
||||
[api.query.staking.stakers, stashId],
|
||||
[api.query.staking.validators, stashId]
|
||||
])
|
||||
]) as any as Observable<[BN, BlockNumber, [Option<Keys | SessionKey>, Option<StakingLedger>, [Array<AccountId>], RewardDestination, Exposure, [ValidatorPrefs]]]>
|
||||
]) as any as Observable<[BN, BlockNumber, [Option<Keys | SessionKey>, Option<StakingLedger>, [AccountId[]], RewardDestination, Exposure, [ValidatorPrefs]]]>
|
||||
).pipe(
|
||||
map(([eraLength, bestNumber, [nextKeyFor, _stakingLedger, [nominators], rewardDestination, stakers, [validatorPrefs]]]) => {
|
||||
map(([eraLength, bestNumber, [nextKeyFor, _stakingLedger, [nominators], rewardDestination, stakers, [validatorPrefs]]]): DerivedStaking => {
|
||||
const stakingLedger = _stakingLedger.unwrapOr(null) || undefined;
|
||||
|
||||
return {
|
||||
@@ -111,13 +113,13 @@ function withStashController (api: ApiInterface$Rx, accountId: AccountId, contro
|
||||
stashId,
|
||||
unlocking: calculateUnlocking(stakingLedger, eraLength, bestNumber),
|
||||
validatorPrefs
|
||||
} as DerivedStaking;
|
||||
} as unknown as DerivedStaking;
|
||||
}),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
|
||||
function withControllerLedger (api: ApiInterface$Rx, accountId: AccountId, stakingLedger: StakingLedger): Observable<DerivedStaking> {
|
||||
function withControllerLedger (api: ApiInterfaceRx, accountId: AccountId, stakingLedger: StakingLedger): Observable<DerivedStaking> {
|
||||
const controllerId = accountId;
|
||||
const stashId = stakingLedger.stash;
|
||||
|
||||
@@ -128,9 +130,9 @@ function withControllerLedger (api: ApiInterface$Rx, accountId: AccountId, staki
|
||||
[api.query.staking.payee, stashId],
|
||||
[api.query.staking.stakers, stashId],
|
||||
[api.query.staking.validators, stashId]
|
||||
]) as any as Observable<[Option<Keys | SessionKey>, [Array<AccountId>], RewardDestination, Exposure, [ValidatorPrefs]]>
|
||||
]) as any as Observable<[Option<Keys | SessionKey>, [AccountId[]], RewardDestination, Exposure, [ValidatorPrefs]]>
|
||||
).pipe(
|
||||
map(([nextKeyFor, [nominators], rewardDestination, stakers, [validatorPrefs]]) => ({
|
||||
map(([nextKeyFor, [nominators], rewardDestination, stakers, [validatorPrefs]]): DerivedStaking => ({
|
||||
accountId,
|
||||
controllerId,
|
||||
nextSessionId: nextSessionId(nextKeyFor),
|
||||
@@ -140,7 +142,7 @@ function withControllerLedger (api: ApiInterface$Rx, accountId: AccountId, staki
|
||||
stakingLedger,
|
||||
stashId,
|
||||
validatorPrefs
|
||||
} as DerivedStaking)),
|
||||
} as unknown as DerivedStaking)),
|
||||
drr()
|
||||
);
|
||||
}
|
||||
@@ -148,7 +150,7 @@ function withControllerLedger (api: ApiInterface$Rx, accountId: AccountId, staki
|
||||
/**
|
||||
* @description From either a stash or controller id, retrieve the controllerId, stashId, nextSessionId, stakingLedger and preferences
|
||||
*/
|
||||
export function info (api: ApiInterface$Rx) {
|
||||
export function info (api: ApiInterfaceRx): (_accountId: Uint8Array | string) => Observable<DerivedStaking> {
|
||||
return (_accountId: Uint8Array | string): Observable<DerivedStaking> => {
|
||||
const accountId = new AccountId(_accountId);
|
||||
|
||||
@@ -158,7 +160,7 @@ export function info (api: ApiInterface$Rx) {
|
||||
[api.query.staking.ledger, accountId] // try to map to stash
|
||||
]) as any as Observable<[Option<AccountId>, Option<StakingLedger>]>
|
||||
).pipe(
|
||||
switchMap(([controllerId, stakingLedger]) =>
|
||||
switchMap(([controllerId, stakingLedger]): Observable<DerivedStaking> =>
|
||||
controllerId.isSome
|
||||
// we have a controller, so input was a stash, great
|
||||
? withStashController(api, accountId, controllerId.unwrap())
|
||||
@@ -166,7 +168,7 @@ export function info (api: ApiInterface$Rx) {
|
||||
stakingLedger.isSome
|
||||
? withControllerLedger(api, accountId, stakingLedger.unwrap())
|
||||
// dangit, this is something else, ok, we are done
|
||||
: of({ accountId } as DerivedStaking)
|
||||
: of({ accountId } as unknown as DerivedStaking)
|
||||
)
|
||||
),
|
||||
drr()
|
||||
|
||||
@@ -13,7 +13,7 @@ import { AnyJsonObject } from '@polkadot/types/types';
|
||||
export default class HeaderExtended extends Header {
|
||||
private _author?: AccountId;
|
||||
|
||||
constructor (header: Header | null = null, sessionValidators: Array<AccountId> = []) {
|
||||
public constructor (header: Header | null = null, sessionValidators: AccountId[] = []) {
|
||||
super(header);
|
||||
|
||||
if (!header || !header.digest || !sessionValidators.length) {
|
||||
@@ -59,14 +59,14 @@ export default class HeaderExtended extends Header {
|
||||
/**
|
||||
* @description Convenience method, returns the author for the block
|
||||
*/
|
||||
get author (): AccountId | undefined {
|
||||
public get author (): AccountId | undefined {
|
||||
return this._author;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates the JSON representation
|
||||
*/
|
||||
toJSON (): AnyJsonObject {
|
||||
public toJSON (): AnyJsonObject {
|
||||
return {
|
||||
...super.toJSON() as AnyJsonObject,
|
||||
author: this.author
|
||||
|
||||
@@ -14,7 +14,7 @@ import { AnyJsonObject } from '@polkadot/types/types';
|
||||
export default class ReferendumInfoExtended extends ReferendumInfo {
|
||||
private _index: ReferendumIndex;
|
||||
|
||||
constructor (value: ReferendumInfo | ReferendumInfoExtended, index?: BN | number) {
|
||||
public constructor (value: ReferendumInfo | ReferendumInfoExtended, index?: BN | number) {
|
||||
super(value);
|
||||
|
||||
this._index = value instanceof ReferendumInfoExtended
|
||||
@@ -25,14 +25,14 @@ export default class ReferendumInfoExtended extends ReferendumInfo {
|
||||
/**
|
||||
* @description Convenience getter, returns the referendumIndex
|
||||
*/
|
||||
get index (): ReferendumIndex {
|
||||
public get index (): ReferendumIndex {
|
||||
return this._index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates the JSON representation
|
||||
*/
|
||||
toJSON (): AnyJsonObject {
|
||||
public toJSON (): AnyJsonObject {
|
||||
return {
|
||||
...super.toJSON() as AnyJsonObject,
|
||||
index: this.index.toJSON()
|
||||
|
||||
@@ -16,9 +16,7 @@ export interface DerivedBalances {
|
||||
vestedBalance: BN;
|
||||
}
|
||||
|
||||
export type DerivedBalancesMap = {
|
||||
[index: string]: DerivedBalances
|
||||
};
|
||||
export type DerivedBalancesMap = Record<string, DerivedBalances>;
|
||||
|
||||
export interface DerivedContractFees {
|
||||
callBaseFee: BN;
|
||||
@@ -63,7 +61,7 @@ export interface DerivedStaking {
|
||||
accountId: AccountId;
|
||||
controllerId?: AccountId;
|
||||
nextSessionId?: AccountId;
|
||||
nominators?: Array<AccountId>;
|
||||
nominators?: AccountId[];
|
||||
redeemable?: BN;
|
||||
rewardDestination?: RewardDestination;
|
||||
stakers?: Exposure;
|
||||
@@ -73,4 +71,4 @@ export interface DerivedStaking {
|
||||
validatorPrefs?: ValidatorPrefs;
|
||||
}
|
||||
|
||||
export type DerivedUnlocking = Array<{remainingBlocks: BN, value: BN}>;
|
||||
export type DerivedUnlocking = { remainingBlocks: BN; value: BN }[];
|
||||
|
||||
@@ -6,24 +6,24 @@ import { of, timer } from 'rxjs';
|
||||
|
||||
import { drr } from './drr';
|
||||
|
||||
describe('drr', () => {
|
||||
it('should not fire twice the same value', (done) => {
|
||||
describe('drr', (): void => {
|
||||
it('should not fire twice the same value', (done): void => {
|
||||
let count = 0;
|
||||
of(1, 1).pipe(drr()).subscribe(() => { ++count; });
|
||||
of(1, 1).pipe(drr()).subscribe((): void => { ++count; });
|
||||
|
||||
setTimeout(() => {
|
||||
setTimeout((): void => {
|
||||
expect(count).toBe(1);
|
||||
done();
|
||||
}, 50);
|
||||
});
|
||||
|
||||
it('should be a ReplaySubject(1)', (done) => {
|
||||
it('should be a ReplaySubject(1)', (done): void => {
|
||||
const obs = timer(0, 100).pipe(drr()); // Starts at 0, increments every 100ms
|
||||
obs.subscribe(); // Fire the observable
|
||||
|
||||
// Subscribe another time after some time, i.e. after the observable has fired
|
||||
setTimeout(() => {
|
||||
obs.subscribe((value) => {
|
||||
setTimeout((): void => {
|
||||
obs.subscribe((value): void => {
|
||||
expect(value > 1).toBe(true);
|
||||
done();
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ import { catchError, distinctUntilChanged, publishReplay, refCount } from 'rxjs/
|
||||
import { Observable } from 'rxjs';
|
||||
import { logger } from '@polkadot/util';
|
||||
|
||||
type DrrResult = <T> (source$: Observable<T>) => Observable<T>;
|
||||
|
||||
const l = logger('drr');
|
||||
|
||||
/**
|
||||
@@ -13,12 +15,12 @@ const l = logger('drr');
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
export const drr = () => <T>(source$: Observable<T>): Observable<T> =>
|
||||
export const drr = (): DrrResult => <T> (source$: Observable<T>): Observable<T> =>
|
||||
source$.pipe(
|
||||
catchError(err => {
|
||||
l.error(err);
|
||||
catchError((error): Observable<never> => {
|
||||
l.error(error);
|
||||
|
||||
throw err;
|
||||
throw error;
|
||||
}),
|
||||
distinctUntilChanged(),
|
||||
publishReplay(1),
|
||||
|
||||
Reference in New Issue
Block a user