This commit is contained in:
ian.he
2019-04-11 13:42:06 +12:00
commit 4e30fab9d6
688 changed files with 51707 additions and 0 deletions
@@ -0,0 +1,47 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, of } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { decodeAddress } from '@plugnet/keyring';
import { AccountId, AccountIndex, Address } from '@plugnet/types';
import { isU8a } from '@plugnet/util';
import { idToIndex } from './idToIndex';
import { indexToId } from './indexToId';
import { drr } from '../util/drr';
export type AccountIdAndIndex = [AccountId?, AccountIndex?];
export function idAndIndex (api: ApiInterface$Rx) {
return (address?: Address | AccountId | AccountIndex | string | null): Observable<AccountIdAndIndex> => {
try {
// yes, this can fail, don't care too much, catch will catch it
const decoded = isU8a(address)
? address
: decodeAddress((address || '').toString());
if (decoded.length === 32) {
const accountId = new AccountId(decoded);
return idToIndex(api)(accountId).pipe(
startWith(undefined),
map((accountIndex) => [accountId, accountIndex] as AccountIdAndIndex),
drr()
);
}
const accountIndex = new AccountIndex(decoded);
return indexToId(api)(accountIndex).pipe(
startWith(undefined),
map((accountId) => [accountId, accountIndex] as AccountIdAndIndex),
drr()
);
} catch (error) {
return of([undefined, undefined] as AccountIdAndIndex).pipe(drr());
}
};
}
@@ -0,0 +1,21 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, AccountIndex } from '@plugnet/types';
import { indexes, AccountIndexes } from './indexes';
import { drr } from '../util/drr';
export function idToIndex (api: ApiInterface$Rx) {
return (accountId: AccountId | string): Observable<AccountIndex | undefined> =>
indexes(api)()
.pipe(
startWith({}),
map((indexes: AccountIndexes) => (indexes || {})[accountId.toString()]),
drr()
);
}
@@ -0,0 +1,8 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './idAndIndex';
export * from './idToIndex';
export * from './indexToId';
export * from './indexes';
@@ -0,0 +1,28 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { ENUMSET_SIZE } from '@plugnet/types/type/AccountIndex';
import { AccountId, AccountIndex, Vector } from '@plugnet/types';
import { drr } from '../util/drr';
export function indexToId (api: ApiInterface$Rx) {
return (_accountIndex: AccountIndex | string): Observable<AccountId> => {
const querySection = api.query.indices || api.query.balances;
const accountIndex = _accountIndex instanceof AccountIndex
? _accountIndex
: new AccountIndex(_accountIndex);
return (querySection.enumSet(accountIndex.div(ENUMSET_SIZE)) as Observable<Vector<AccountId>>)
.pipe(
startWith([]),
map((accounts) => (accounts || [])[accountIndex.mod(ENUMSET_SIZE).toNumber()]),
drr()
);
};
}
@@ -0,0 +1,42 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { combineLatest, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { ENUMSET_SIZE } from '@plugnet/types/type/AccountIndex';
import { AccountId, AccountIndex } from '@plugnet/types';
import { drr } from '../util/drr';
export type AccountIndexes = { [index: string]: AccountIndex };
export function indexes (api: ApiInterface$Rx) {
return (): Observable<AccountIndexes> => {
const querySection = api.query.indices || api.query.balances;
return (querySection.nextEnumSet() as Observable<AccountIndex>)
.pipe(
map((next: AccountIndex) => {
const enumRange = [...Array(next.div(ENUMSET_SIZE).toNumber() + 1).keys()];
return enumRange;
}),
switchMap((enumRange) => combineLatest(
enumRange.map((index) => (querySection.enumSet(index) as Observable<any>))
)),
map((all: Array<Array<AccountId> | undefined>) =>
(all || []).reduce((result, list, outerIndex) => {
(list || []).forEach((accountId, innerIndex) => {
const index = (outerIndex * ENUMSET_SIZE.toNumber()) + innerIndex;
result[accountId.toString()] = new AccountIndex(index);
});
return result;
}, {} as AccountIndexes)),
drr()
);
};
}
+36
View File
@@ -0,0 +1,36 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import BN from 'bn.js';
import { DerivedFees } from '../types';
import { drr } from '../util/drr';
export function fees (api: ApiInterface$Rx) {
return (): Observable<DerivedFees> => {
return (combineLatest(
api.query.balances.creationFee(),
api.query.balances.existentialDeposit(),
api.query.fees
? api.query.fees.transactionBaseFee()
: api.query.balances.transactionBaseFee(),
api.query.fees
? api.query.fees.transactionByteFee()
: api.query.balances.transactionByteFee(),
api.query.balances.transferFee()
) as any as Observable<[BN, BN, BN, BN, BN]>).pipe(
map(([creationFee, existentialDeposit, transactionBaseFee, transactionByteFee, transferFee]) => ({
creationFee,
existentialDeposit,
transactionBaseFee,
transactionByteFee,
transferFee
})),
drr()
) ;
};
}
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './fees';
export * from './validatingBalance';
export * from './validatingBalances';
export * from './votingBalance';
export * from './votingBalances';
export * from './votingBalancesNominatorsFor';
@@ -0,0 +1,41 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, AccountIndex, Address, Balance } from '@plugnet/types';
import { DerivedBalances } from '../types';
import { drr } from '../util/drr';
import { votingBalance } from './votingBalance';
import { votingBalancesNominatorsFor } from './votingBalancesNominatorsFor';
export function validatingBalance (api: ApiInterface$Rx) {
return (address: AccountId | AccountIndex | Address | string): Observable<DerivedBalances> => {
return combineLatest(
votingBalance(api)(address),
votingBalancesNominatorsFor(api)(address)
).pipe(
map(([balance, nominators]) => {
const nominatedBalance = nominators.reduce(
(total: BN, nominatorBalance: DerivedBalances) =>
total.add(nominatorBalance.votingBalance),
new BN(0)
);
return {
...balance,
nominators,
nominatedBalance: new Balance(nominatedBalance),
stakingBalance: new Balance(
nominatedBalance.add(balance.votingBalance)
)
};
}),
drr()
);
};
}
@@ -0,0 +1,31 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { combineLatest, Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, Address } from '@plugnet/types';
import { DerivedBalancesMap } from '../types';
import { drr } from '../util/drr';
import { validatingBalance } from './validatingBalance';
export function validatingBalances (api: ApiInterface$Rx) {
return (accountIds: Array<AccountId | Address | string>): Observable<DerivedBalancesMap> => {
return !accountIds || !accountIds.length
? of({}).pipe(drr())
: combineLatest(
accountIds.map(validatingBalance(api))
).pipe(
map((result) => {
return result.reduce((balances, balance) => {
balances[balance.accountId.toString()] = balance;
return balances;
}, {} as DerivedBalancesMap);
}),
drr()
);
};
}
@@ -0,0 +1,44 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { combineLatest, of, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, AccountIndex, Address, Balance } from '@plugnet/types';
import { idAndIndex } from '../accounts/idAndIndex';
import { DerivedBalances } from '../types';
import { drr } from '../util/drr';
const EMPTY_ACCOUNT = new AccountId(new Uint8Array(32));
export function votingBalance (api: ApiInterface$Rx) {
return (address: AccountIndex | AccountId | Address | string): Observable<DerivedBalances> => {
return idAndIndex(api)(address).pipe(
switchMap(([accountId]) =>
(accountId
? combineLatest(
of(accountId),
api.query.balances.freeBalance(accountId),
api.query.balances.reservedBalance(accountId)
)
: of([undefined, undefined, undefined])
) as Observable<[AccountId?, Balance?, Balance?]>
),
map(([accountId = EMPTY_ACCOUNT, freeBalance = new Balance(0), reservedBalance = new Balance(0)]) => {
return {
accountId,
freeBalance,
nominatedBalance: new Balance(0),
reservedBalance,
stakingBalance: new Balance(0),
votingBalance: new Balance(
freeBalance.add(reservedBalance)
)
};
}),
drr()
);
};
}
@@ -0,0 +1,19 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { combineLatest, Observable, of } from 'rxjs';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, AccountIndex, Address } from '@plugnet/types';
import { DerivedBalances } from '../types';
import { drr } from '../util/drr';
import { votingBalance } from './votingBalance';
export function votingBalances (api: ApiInterface$Rx) {
return (addresses?: Array<AccountId | AccountIndex | Address | string>): Observable<Array<DerivedBalances>> => {
return !addresses || !addresses.length
? of([]).pipe(drr())
: combineLatest(...addresses.map(votingBalance(api))).pipe(drr());
};
}
@@ -0,0 +1,27 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, AccountIndex, Address, Vector } from '@plugnet/types';
import { idAndIndex } from '../accounts/idAndIndex';
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>> => {
return idAndIndex(api)(address).pipe(
switchMap(([accountId]) =>
accountId
? (api.query.staking.nominatorsFor(accountId) as Observable<Vector<AccountId>>)
: of([] as Array<AccountId>)
),
switchMap(votingBalances(api)),
drr()
);
};
}
@@ -0,0 +1,31 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { BlockNumber, Header } from '@plugnet/types';
import { drr } from '../util/drr';
/**
* @description Get the latest block number.
* @example
* <BR>
*
* ```javascript
* api.derive.chain.bestNumber((blockNumber) => {
* console.log(`the current best block is #${blockNumber}`);
* });
* ```
*/
export function bestNumber (api: ApiInterface$Rx) {
return (): Observable<BlockNumber> =>
(api.rpc.chain.subscribeNewHead() as Observable<Header>)
.pipe(
filter((header: Header) => header && !!header.blockNumber),
map(({ blockNumber }: Header) => blockNumber),
drr()
);
}
@@ -0,0 +1,31 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { BlockNumber, Header } from '@plugnet/types';
import { drr } from '../util/drr';
/**
* @description Get the latest finalised block number.
* example
* <BR>
*
* ```javascript
* api.derive.chain.bestNumberFinalized((blockNumber) => {
* console.log(`the current finalised block is #${blockNumber}`);
* });
* ```
*/
export function bestNumberFinalized (api: ApiInterface$Rx) {
return (): Observable<BlockNumber> =>
(api.rpc.chain.subscribeFinalizedHeads() as Observable<Header>)
.pipe(
filter((header: Header) => header && !!header.blockNumber),
map(({ blockNumber }: Header) => blockNumber),
drr()
);
}
@@ -0,0 +1,36 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { BlockNumber } from '@plugnet/types';
import { drr } from '../util/drr';
import { bestNumber } from './bestNumber';
import { bestNumberFinalized } from './bestNumberFinalized';
/**
* @description Calculates the lag between finalised head and best head
* @example
* <BR>
*
* ```javascript
* api.derive.chain.bestNumberLag((lag) => {
* console.log(`finalised is ${lag} blocks behind head`);
* });
* ```
*/
export function bestNumberLag (api: ApiInterface$Rx) {
return (): Observable<BlockNumber> =>
combineLatest(
bestNumber(api)(),
bestNumberFinalized(api)()
).pipe(
map(([bestNumber, bestNumberFinalized]) =>
new BlockNumber(bestNumber.sub(bestNumberFinalized))
),
drr()
);
}
@@ -0,0 +1,46 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, combineLatest, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { Header, HeaderExtended } from '@plugnet/types';
import { drr } from '../util/drr';
import { HeaderAndValidators } from './subscribeNewHead';
/**
* @description Get the a specific block header and extend it with the author
* @param hash: Uint8Array | string
* @example
* <BR>
*
* ```javascript
* const { author, blockNumber } = await api.derive.chain.getHeader('0x123...456');
*
* console.log(`block #${blockNumber} was authored by ${author}`);
* ```
*/
export function getHeader (api: ApiInterface$Rx) {
return (hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
// tslint:disable-next-line
(combineLatest(
api.rpc.chain.getHeader(hash) as Observable<Header>,
api.query.session
? api.query.session.validators.at(hash)
: of([])
) as Observable<HeaderAndValidators>).pipe(
map(([header, validators]) =>
new HeaderExtended(header, validators)
),
catchError(() =>
// 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
// tslint:disable-next-line
of() as Observable<undefined>
),
drr()
);
}
+9
View File
@@ -0,0 +1,9 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './bestNumber';
export * from './bestNumberFinalized';
export * from './bestNumberLag';
export * from './getHeader';
export * from './subscribeNewHead';
@@ -0,0 +1,48 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, combineLatest, of } from 'rxjs';
import { filter, map, switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, Header, HeaderExtended } from '@plugnet/types';
import { drr } from '../util/drr';
export type HeaderAndValidators = [Header, Array<AccountId>];
/**
* @description Subscribe to block headers and extend it with the author
* @example
* <BR>
*
* ```javascript
* api.derive.chain.subscribeNewHead(({ author, blockNumber }) => {
* console.log(`block #${blockNumber} was authored by ${author}`);
* });
* ```
*/
export function subscribeNewHead (api: ApiInterface$Rx) {
return (): Observable<HeaderExtended> =>
(api.rpc.chain.subscribeNewHead() as Observable<Header>)
.pipe(
filter((header: Header) =>
header && !!header.blockNumber
),
switchMap((header: Header): Observable<HeaderAndValidators> =>
(combineLatest(
of(header),
// theoretically we could combine at the first call with session.validators(), however
// we make 100% sure we actually get the validators at a specific block so when these
// change at an era boundary, we have the previous values to ensure our indexes are correct
api.query.session
? api.query.session.validators.at(header.hash)
: of([])
) as Observable<HeaderAndValidators>)
),
map(([header, validators]) =>
new HeaderExtended(header, validators)
),
drr()
);
}
@@ -0,0 +1,8 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './referendumInfos';
export * from './referendums';
export * from './referendumVotesFor';
export * from './votes';
@@ -0,0 +1,66 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { Option, ReferendumInfo, ReferendumIndex } from '@plugnet/types';
import { isNull } from '@plugnet/util';
import { drr } from '../util/drr';
/**
* @name ReferendumInfoExtended
* @description
* A [[ReferendumInfo]] with an additional `index` field
*/
export class ReferendumInfoExtended extends ReferendumInfo {
private _index: ReferendumIndex;
constructor (value: ReferendumInfo | ReferendumInfoExtended, index?: BN | number) {
super(value);
this._index = value instanceof ReferendumInfoExtended
? value.index
: new ReferendumIndex(index);
}
/**
* @description Convenience getter, returns the referendumIndex
*/
get index (): ReferendumIndex {
return this._index;
}
/**
* @description Creates the JSON representation
*/
toJSON (): any {
return {
...super.toJSON(),
index: this.index.toJSON()
};
}
}
export function referendumInfo (api: ApiInterface$Rx) {
return (index: BN | number): Observable<Option<ReferendumInfoExtended>> => {
return (api.query.democracy.referendumInfoOf(index) as Observable<Option<ReferendumInfo>>)
.pipe(
map((optionInfo) => {
const info = optionInfo.unwrapOr(null);
return new Option<ReferendumInfoExtended>(
ReferendumInfoExtended,
isNull(info)
? null
: new ReferendumInfoExtended(info, index)
);
}),
drr()
);
};
}
@@ -0,0 +1,26 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable, of } from 'rxjs';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { Option } from '@plugnet/types';
import { drr } from '../util/drr';
import { referendumInfo, ReferendumInfoExtended } from './referendumInfo';
export function referendumInfos (api: ApiInterface$Rx) {
const referendumInfoOf = referendumInfo(api);
return (ids: Array<BN | number> = []): Observable<Array<Option<ReferendumInfoExtended>>> => {
return !ids || !ids.length
? of([]).pipe(drr())
: combineLatest(
ids.map((id) => referendumInfoOf(id))
).pipe(
drr()
);
};
}
@@ -0,0 +1,36 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, Balance, Vector, Vote } from '@plugnet/types';
import { 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>> =>
(api.query.democracy.votersFor(referendumId) as Observable<Vector<AccountId>>).pipe(
switchMap((votersFor) =>
combineLatest(
of(votersFor),
votes(api)(referendumId as BN, votersFor),
votingBalances(api)(votersFor)
)
),
map(([votersFor, votes, balances]) =>
votersFor.map((accountId, index): DerivedReferendumVote => ({
accountId,
balance: balances[index].votingBalance || new Balance(0),
vote: votes[index] || new Vote(0)
}))
),
drr()
);
}
@@ -0,0 +1,31 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { combineLatest, Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { Option, ReferendumIndex } from '@plugnet/types';
import { drr } from '../util/drr';
import { ReferendumInfoExtended } from './referendumInfo';
import { referendumInfos } from './referendumInfos';
export function referendums (api: ApiInterface$Rx) {
return (): Observable<Array<Option<ReferendumInfoExtended>>> =>
(combineLatest(
api.query.democracy.nextTally(),
api.query.democracy.referendumCount()
) as Observable<[ReferendumIndex?, ReferendumIndex?]>).pipe(
switchMap(([nextTally, referendumCount]) =>
referendumCount && nextTally && referendumCount.gt(nextTally) && referendumCount.gtn(0)
? referendumInfos(api)(
[...Array(referendumCount.sub(nextTally).toNumber())].map((_, i) =>
nextTally.addn(i)
)
)
: of([])
),
drr()
);
}
@@ -0,0 +1,24 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable, of } from 'rxjs';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, Vote } from '@plugnet/types';
import { drr } from '../util/drr';
export function votes (api: ApiInterface$Rx) {
return (referendumId: BN, accountIds: Array<AccountId> = []): Observable<Array<Vote>> => {
return !accountIds || !accountIds.length
? of([]).pipe(drr())
: combineLatest(
accountIds.map(
(accountId) => api.query.democracy.voteOf([referendumId, accountId]) as Observable<Vote>
)
).pipe(
drr()
);
};
}
+88
View File
@@ -0,0 +1,88 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, from } from 'rxjs';
import ApiRx from '@plugnet/api/rx/Api';
import { ApiInterface$Rx } from '@plugnet/api/types';
import MockProvider from '@plugnet/rpc-provider/mock';
import { Derive } from '.';
const testFunction = (api: ApiInterface$Rx) => {
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', () => {
expect(typeof api.derive[section][method]).toBe('function');
});
it('should return an Observable', () => {
expect((api.derive[section][method] as any)(...inputs)).toBeInstanceOf(Observable);
});
});
};
};
describe('derive', () => {
describe('builtin', () => {
const api = new ApiRx(new MockProvider());
beforeAll((done) => {
api.isReady.subscribe(() => done());
});
testFunction(api)('accounts', 'idAndIndex', []);
testFunction(api)('accounts', 'idToIndex', []);
testFunction(api)('accounts', 'indexes', []);
testFunction(api)('accounts', 'indexToId', []);
testFunction(api)('balances', 'fees', []);
testFunction(api)('balances', 'validatingBalance', []);
testFunction(api)('balances', 'validatingBalances', []);
testFunction(api)('balances', 'votingBalance', []);
testFunction(api)('balances', 'votingBalances', []);
testFunction(api)('balances', 'votingBalancesNominatorsFor', []);
testFunction(api)('chain', 'bestNumber', []);
testFunction(api)('chain', 'bestNumberFinalized', []);
testFunction(api)('democracy', 'referendumInfos', []);
testFunction(api)('democracy', 'referendums', []);
testFunction(api)('democracy', 'referendumVotesFor', []);
testFunction(api)('democracy', 'votes', []);
testFunction(api)('session', 'eraLength', []);
testFunction(api)('session', 'eraProgress', []);
testFunction(api)('session', 'sessionProgress', []);
});
describe('custom', () => {
const api = new ApiRx({
derives: {
balances: {
fees: () => () => from(['a', 'b'])
},
custom: {
test: () => () => from([1, 2, 3])
}
},
provider: new MockProvider()
});
beforeAll((done) => {
api.isReady.subscribe(() => done());
});
// override
testFunction(api)('balances', 'fees', ['a', 'b']);
// new
testFunction(api)('custom' as any, 'test', [1, 2, 3]);
// existing
testFunction(api)('chain', 'bestNumber', []);
});
});
+66
View File
@@ -0,0 +1,66 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { ApiInterface$Rx } from '@plugnet/api/types';
import * as accounts from './accounts';
import * as balances from './balances';
import * as chain from './chain';
import * as democracy from './democracy';
import * as session from './session';
import * as staking from './staking';
// Put all derived functions in an object, for easier Object.keys()-ing.
const functions = { accounts, balances, chain, democracy, session, staking };
/**
* T represents the section here (chain, balances...), and P represents
* the function name (bestNumber, sessionProgress...).
*/
type ReturnTypes<T extends Record<keyof T, (...args: any[]) => any>> = {
[P in keyof T]: ReturnType<T[P]>
};
export interface DeriveCustomMethod {
(api: ApiInterface$Rx): (...args: Array<any>) => Observable<any>;
}
export interface DeriveCustom {
[index: string]: {
[index: string]: DeriveCustomMethod
};
}
export interface Derive {
accounts: ReturnTypes<typeof accounts>;
balances: ReturnTypes<typeof balances>;
chain: ReturnTypes<typeof chain>;
democracy: ReturnTypes<typeof democracy>;
session: ReturnTypes<typeof session>;
staking: ReturnTypes<typeof staking>;
}
function injectFunctions (api: ApiInterface$Rx, derive: Derive, functions: DeriveCustom): Derive {
Object.keys(functions).forEach((sectionName: string) => {
const section = functions[sectionName as keyof Derive];
const result = derive[sectionName as keyof Derive] = derive[sectionName as keyof Derive] || {};
Object.keys(section).forEach((methodName) => {
// @ts-ignore No idea how to make this work...
result[methodName as keyof section] = section[methodName as keyof section](api);
});
});
return derive;
}
export default function decorateDerive (api: ApiInterface$Rx, custom: DeriveCustom = {}): Derive {
const derive = {} as Derive;
injectFunctions(api, derive, functions);
injectFunctions(api, derive, custom);
return derive;
}
@@ -0,0 +1,25 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { BlockNumber } from '@plugnet/types';
import { drr } from '../util/drr';
export function eraLength (api: ApiInterface$Rx) {
return (): Observable<BN> =>
(combineLatest(
api.query.session.sessionLength(),
api.query.staking.sessionsPerEra()
) as Observable<[BlockNumber?, BlockNumber?]>).pipe(
map(
([sessionLength, sessionsPerEra]) =>
(sessionLength || new BN(1)).mul(sessionsPerEra || new BN(1))
),
drr()
);
}
@@ -0,0 +1,35 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { BlockNumber } from '@plugnet/types';
import { sessionProgress } from './sessionProgress';
import { drr } from '../util/drr';
export function eraProgress (api: ApiInterface$Rx) {
return (): Observable<BN> =>
(combineLatest(
sessionProgress(api)(),
api.query.session.currentIndex(),
api.query.session.sessionLength(),
api.query.staking.lastEraLengthChange(),
api.query.staking.sessionsPerEra()
) as Observable<[BN, BlockNumber?, BlockNumber?, BlockNumber?, BlockNumber?]>).pipe(
map(
([sessionProgress, currentIndex, sessionLength, lastEraLengthChange, sessionsPerEra]) =>
(currentIndex || new BN(0))
.sub(lastEraLengthChange || new BN(0))
.mod(sessionsPerEra || new BN(1))
.mul(sessionLength || new BN(1))
.add(sessionProgress || new BN(0)
)
),
drr()
);
}
+7
View File
@@ -0,0 +1,7 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './eraLength';
export * from './eraProgress';
export * from './sessionProgress';
@@ -0,0 +1,30 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { BlockNumber, Option } from '@plugnet/types';
import { bestNumber } from '../chain';
import { drr } from '../util/drr';
export function sessionProgress (api: ApiInterface$Rx) {
return (): Observable<BN> =>
combineLatest(
bestNumber(api)(),
api.query.session.sessionLength(),
api.query.session.lastLengthChange()
).pipe(
map(
([bestNumber, sessionLength, lastLengthChange]) =>
(bestNumber || new BN(0))
.sub((lastLengthChange as Option<BlockNumber>).unwrapOr(new BN(0)))
.add(sessionLength as BlockNumber || new BN(1))
.mod(sessionLength as BlockNumber || new BN(1))
),
drr()
);
}
@@ -0,0 +1,35 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable, combineLatest, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, Option } from '@plugnet/types';
import { drr } from '../util/drr';
function allBonds (api: ApiInterface$Rx, stashIds: Array<AccountId>) {
return combineLatest(
stashIds.map((id) =>
(api.query.staking.bonded(id) as Observable<Option<AccountId>>)
)
);
}
/**
* @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]>)
.pipe(
switchMap(([stashIds]) =>
combineLatest(
of(stashIds),
allBonds(api, stashIds)
)
),
drr()
);
}
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './controllers';
export * from './intentionsBalances';
@@ -0,0 +1,25 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ApiInterface$Rx } from '@plugnet/api/types';
import { AccountId, Vector } from '@plugnet/types';
import { DerivedBalancesMap } from '../types';
import { validatingBalances } from '../balances';
import { drr } from '../util/drr';
/**
* Get the balances for all intentions and their nominators
*/
export function intentionsBalances (api: ApiInterface$Rx) {
return (): Observable<DerivedBalancesMap> =>
// tslint:disable-next-line
(api.query.staking.intentions() as Observable<Vector<AccountId>>)
.pipe(
switchMap(validatingBalances(api)),
drr()
) as Observable<DerivedBalancesMap>;
}
+34
View File
@@ -0,0 +1,34 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// 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 { AccountId, Balance, Vote } from '@plugnet/types';
export type DerivedBalances = {
accountId: AccountId,
freeBalance: Balance,
nominatedBalance: Balance,
reservedBalance: Balance,
votingBalance: Balance,
stakingBalance: Balance,
nominators?: Array<DerivedBalances>
};
export type DerivedFees = {
creationFee: BN,
existentialDeposit: BN,
transactionBaseFee: BN,
transactionByteFee: BN,
transferFee: BN
};
export type DerivedBalancesMap = {
[index: string]: DerivedBalances
};
export type DerivedReferendumVote = {
accountId: AccountId,
balance: Balance,
vote: Vote
};
+32
View File
@@ -0,0 +1,32 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { of, timer } from 'rxjs';
import { drr } from './drr';
describe('drr', () => {
it('should not fire twice the same value', (done) => {
let count = 0;
of(1, 1).pipe(drr()).subscribe(() => { ++count; });
setTimeout(() => {
expect(count).toBe(1);
done();
}, 50);
});
it('should be a ReplaySubject(1)', (done) => {
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) => {
expect(value > 1).toBe(true);
done();
});
}, 500);
});
});
+18
View File
@@ -0,0 +1,18 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { distinctUntilChanged, publishReplay, refCount } from 'rxjs/operators';
import { Observable } from 'rxjs';
/**
* Shorthand for distinctUntilChanged(), publishReplay(1) and refCount().
*
* @ignore
*/
export const drr = () => <T>(source$: Observable<T>): Observable<T> =>
source$.pipe(
distinctUntilChanged(),
publishReplay(1),
refCount()
);