Drop V1 support in derive (#1718)

* Drop V1 support in derive

* Re-do staking with multi

* Re-bump deps

* Adjusts tests (no alice_session)

* CC
This commit is contained in:
Jaco Greeff
2020-01-14 15:55:25 +01:00
committed by GitHub
parent 88193b6a75
commit ffa60d1cfa
13 changed files with 90 additions and 243 deletions
+1 -1
View File
@@ -32,6 +32,6 @@
"@polkadot/types": "^1.0.0-beta.4"
},
"devDependencies": {
"@polkadot/keyring": "^2.0.0-beta.1"
"@polkadot/keyring": "^2.0.0-beta.2"
}
}
+1 -16
View File
@@ -13,7 +13,7 @@ import { memo } from '../util';
type Result = [Balance, Balance, Balance, Balance, Balance];
function queryV2 (api: ApiInterfaceRx): Observable<Result> {
function query (api: ApiInterfaceRx): Observable<Result> {
const paymentBase = api.consts.transactionPayment || api.consts.balances;
return of([
@@ -27,17 +27,6 @@ function queryV2 (api: ApiInterfaceRx): Observable<Result> {
]);
}
function queryV1 (api: ApiInterfaceRx): Observable<Result> {
return api.queryMulti<Result>([
// Support older versions and get values from storage
api.query.balances.creationFee,
api.query.balances.existentialDeposit,
api.query.balances.transferFee,
api.query.balances.transactionBaseFee,
api.query.balances.transactionByteFee
]);
}
/**
* @name fees
* @returns An object containing the combined results of the storage queries for
@@ -52,10 +41,6 @@ function queryV1 (api: ApiInterfaceRx): Observable<Result> {
* ```
*/
export function fees (api: ApiInterfaceRx): () => Observable<DerivedFees> {
const query = api.consts.balances
? queryV2
: queryV1;
return memo((): Observable<DerivedFees> =>
query(api).pipe(
map(([creationFee, existentialDeposit, transferFee, transactionBaseFee, transactionByteFee]): DerivedFees => ({
@@ -14,10 +14,9 @@ import { memo } from '../util';
export function referendums (api: ApiInterfaceRx): () => Observable<DerivedReferendum[]> {
return memo((): Observable<DerivedReferendum[]> =>
// V2 vs V1 (and early V2)
api.query.democracy?.lowestUnbaked || api.query.democracy?.nextTally
api.query.democracy?.lowestUnbaked
? api.queryMulti<[ReferendumIndex, ReferendumIndex]>([
api.query.democracy.lowestUnbaked || api.query.democracy.nextTally,
api.query.democracy.lowestUnbaked,
api.query.democracy.referendumCount
]).pipe(
switchMap(([earliest, referendumCount]): Observable<DerivedReferendum[]> =>
+5 -52
View File
@@ -2,50 +2,20 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BlockNumber, SessionIndex } from '@polkadot/types/interfaces';
import { SessionIndex } from '@polkadot/types/interfaces';
import { DerivedSessionInfo, DeriveSessionIndexes } from '../types';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, u64, createType } from '@polkadot/types';
import { u64, createType } from '@polkadot/types';
import { memo } from '../util';
type ResultV1Session = [Option<BlockNumber>, BlockNumber, BlockNumber, SessionIndex];
type ResultV1 = [BlockNumber, DeriveSessionIndexes, ResultV1Session];
type ResultSlots = [u64, u64, u64, SessionIndex];
type ResultType = [boolean, u64, SessionIndex];
type Result = [ResultType, DeriveSessionIndexes, ResultSlots];
// internal helper to just split the logic - take all inputs, do the calculations and combine
function createDerivedV1 (api: ApiInterfaceRx, [bestNumber, { currentIndex, validatorCount }, [_lastLengthChange, sessionLength, lastEraLengthChange, sessionsPerEra]]: ResultV1): DerivedSessionInfo {
const lastLengthChange = _lastLengthChange?.unwrapOr(null) || createType(api.registry, 'BlockNumber');
const sessionProgress = bestNumber
.sub(lastLengthChange)
.add(sessionLength)
.mod(sessionLength);
const currentEra = currentIndex
.sub(lastEraLengthChange)
.mod(sessionsPerEra);
const eraProgress = currentEra
.mul(sessionLength)
.add(sessionProgress);
return {
currentEra: createType(api.registry, 'EraIndex', currentEra),
currentIndex,
eraLength: createType(api.registry, 'BlockNumber', sessionLength.mul(sessionsPerEra)),
eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
isEpoch: false,
sessionLength,
sessionsPerEra,
sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
validatorCount
};
}
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
const sessionProgress = currentSlot.sub(epochStartSlot);
@@ -64,21 +34,6 @@ function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, ses
};
}
function infoV1 (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
return combineLatest([
api.derive.chain.bestNumber(),
api.derive.session.indexes(),
api.queryMulti<ResultV1Session>([
api.query.session.lastLengthChange,
api.query.session.sessionLength,
api.query.staking.lastEraLengthChange,
api.query.staking.sessionsPerEra
])
]).pipe(
map((result): DerivedSessionInfo => createDerivedV1(api, result))
);
}
function infoLatestAura (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
return api.derive.session.indexes().pipe(
map((indexes): DerivedSessionInfo =>
@@ -115,11 +70,9 @@ function infoLatestBabe (api: ApiInterfaceRx): Observable<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: ApiInterfaceRx): () => Observable<DerivedSessionInfo> {
const query = api.consts.timestamp || api.consts.babe || api.consts.aura
? api.consts.babe
? infoLatestBabe // 2.x with Babe
: infoLatestAura // 2.x with Aura (not all info there)
: infoV1;
const query = api.consts.babe
? infoLatestBabe // 2.x with Babe
: infoLatestAura; // 2.x with Aura (not all info there)
return memo((): Observable<DerivedSessionInfo> =>
query(api));
+1 -18
View File
@@ -13,10 +13,7 @@ import { Option, Vec } from '@polkadot/types';
import { memo } from '../util';
// NOTE Unused ATM, preparing for V2-only
type Result = [Option<AccountId>, [Vec<AccountId>], RewardDestination, Exposure, ValidatorPrefs, Option<Keys>?];
type ResultV1 = [Option<AccountId>, ITuple<[Vec<AccountId>]>, RewardDestination, Exposure, ValidatorPrefs];
type ResultV2 = [Option<AccountId>, ITuple<[Vec<AccountId>]>, RewardDestination, Exposure, ValidatorPrefs, Option<Keys>];
function parse (stashId: AccountId, [_controllerId, [nominators], rewardDestination, stakers, validatorPrefs, _nextKeys]: Result): DerivedStakingStash {
@@ -31,17 +28,7 @@ function parse (stashId: AccountId, [_controllerId, [nominators], rewardDestinat
};
}
function retrieveV1 (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
return api.queryMulti<ResultV1>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.stakers, stashId],
[api.query.staking.validators, stashId]
]);
}
function retrieveV2 (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
function query (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
return api.queryMulti<ResultV2>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
@@ -53,10 +40,6 @@ function retrieveV2 (api: ApiInterfaceRx, stashId: AccountId): Observable<Result
}
export function infoStash (api: ApiInterfaceRx): (stashId: AccountId) => Observable<DerivedStakingStash> {
const query = api.consts.session
? retrieveV2
: retrieveV1;
return memo((stashId: AccountId): Observable<DerivedStakingStash> =>
query(api, stashId).pipe(
map((result): DerivedStakingStash => parse(stashId, result))
+37 -118
View File
@@ -13,142 +13,61 @@ import { createType, Option, Vec } from '@polkadot/types';
import { memo } from '../util';
interface ParseInput {
accountId: AccountId;
controllerId: AccountId;
nominators: AccountId[];
rewardDestination: RewardDestination;
queuedKeys?: [AccountId, Keys][];
stakers: Exposure;
stakingLedger: Option<StakingLedger>;
stashId: AccountId;
validatorPrefs: ValidatorPrefs;
nextKeys?: Option<Keys>;
nextKeyFor?: Option<AccountId>;
}
type MultiResultV2 = [Option<AccountId>, Option<ITuple<[Nominations]>>, RewardDestination, Exposure, [ValidatorPrefs], Option<Keys>, Option<StakingLedger>];
function unwrapSessionIds (stashId: AccountId, queuedKeys: Option<AccountId> | [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
// for 2.x we have a Vec<(ValidatorId,Keys)> of the keys
if (Array.isArray(queuedKeys)) {
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
currentId.eq(stashId)
) || [undefined, [] as AccountId[]])[1];
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
return {
nextSessionIds,
sessionIds
};
}
// substrate 1.x
const nextSessionIds = queuedKeys.isSome
? [queuedKeys.unwrap()]
: [];
function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
currentId.eq(stashId)
) || [undefined, [] as AccountId[]])[1];
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
return {
nextSessionIds,
sessionIds: nextSessionIds
sessionIds
};
}
function parseResult (api: ApiInterfaceRx, { accountId, controllerId, stashId, nextKeyFor, queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys }: ParseInput): DerivedStakingQuery {
const _stakingLedger = stakingLedger.unwrapOr(undefined);
const _nextKeyFor = nextKeyFor || createType(api.registry, 'Option<AccountId>', null);
const _nextKeys = nextKeys || createType(api.registry, 'Option<Keys>', null);
return {
accountId,
controllerId,
nominators,
rewardDestination,
stakers,
stakingLedger: _stakingLedger,
stashId,
validatorPrefs,
...unwrapSessionIds(stashId, queuedKeys || _nextKeyFor, _nextKeys)
};
}
type MultiResultV1 = [Option<AccountId>, Option<StakingLedger>, [Vec<AccountId>], RewardDestination, Exposure, ITuple<[ValidatorPrefs]>];
function retrieveInfoV1 (api: ApiInterfaceRx, accountId: AccountId, stashId: AccountId, controllerId: AccountId): Observable<DerivedStakingQuery> {
return (
api.queryMulti([
[api.query.session.nextKeyFor, controllerId],
[api.query.staking.ledger, controllerId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.stakers, stashId],
[api.query.staking.validators, stashId]
]) as Observable<MultiResultV1>
).pipe(map(([nextKeyFor, stakingLedger, [nominators], rewardDestination, stakers, [validatorPrefs]]: MultiResultV1): DerivedStakingQuery =>
parseResult(api, {
accountId, controllerId, stashId, nextKeyFor, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs
})
));
}
type MultiResultV2 = [[Vec<AccountId>] | Option<ITuple<[Nominations]>>, RewardDestination, Exposure, [ValidatorPrefs], Option<Keys>, Option<StakingLedger>];
function retrieveInfoV2 (api: ApiInterfaceRx, accountId: AccountId, stashId: AccountId, controllerId: AccountId): Observable<DerivedStakingQuery> {
function retrieve (api: ApiInterfaceRx, stashId: AccountId): Observable<[Vec<ITuple<[AccountId, Keys]>>, MultiResultV2]> {
return combineLatest([
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>(),
api.queryMulti([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.stakers, stashId],
[api.query.staking.validators, stashId],
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]],
[api.query.staking.ledger, controllerId]
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]]
]) as Observable<MultiResultV2>
]).pipe(map(([queuedKeys, [_nominators, rewardDestination, stakers, [validatorPrefs], nextKeys, stakingLedger]]: [[AccountId, Keys][], MultiResultV2]): DerivedStakingQuery => {
// if we have staking.storageVersion it indicates the new structure, unwrap as needed
// FIXME We really want to be pulling all the new (valuable) info along
const nominators: AccountId[] = api.query.staking.storageVersion
? (_nominators as Option<ITuple<[Nominations]>>).isSome
? (_nominators as Option<ITuple<[Nominations]>>).unwrap()[0].targets
: []
: (_nominators as [Vec<AccountId>])[0];
return parseResult(api, {
accountId, controllerId, stashId, queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys
});
}));
}
function retrieveV1 (api: ApiInterfaceRx, accountId: AccountId): Observable<DerivedStakingQuery> {
// depending on where we come from, this may be a controller or stash
return combineLatest([
api.query.staking.bonded<Option<AccountId>>(accountId),
api.query.staking.ledger<Option<StakingLedger>>(accountId)
]).pipe(switchMap(([bonded, stakingLedger]): Observable<DerivedStakingQuery> =>
stakingLedger.isSome
? retrieveInfoV1(api, accountId, stakingLedger.unwrap().stash, accountId)
: bonded.isSome
? retrieveInfoV1(api, accountId, accountId, bonded.unwrap())
: of({ accountId: accountId, nextSessionIds: [], sessionIds: [] })
));
}
function retrieveV2 (api: ApiInterfaceRx, stashId: AccountId): Observable<DerivedStakingQuery> {
return api.query.staking
.bonded<Option<AccountId>>(stashId)
.pipe(switchMap((controllerId): Observable<DerivedStakingQuery> =>
controllerId.isSome
? retrieveInfoV2(api, stashId, stashId, controllerId.unwrap())
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] })
));
]);
}
/**
* @description From a stash, retrieve the controllerId and fill in all the relevant staking details
* @description From a stash, retrieve the controllerId and all relevant details
*/
export function query (api: ApiInterfaceRx): (_accountId: Uint8Array | string) => Observable<DerivedStakingQuery> {
const retrieve = api.consts.session
? retrieveV2
: retrieveV1;
export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DerivedStakingQuery> {
return memo((accountId: Uint8Array | string): Observable<DerivedStakingQuery> => {
const stashId = createType(api.registry, 'AccountId', accountId);
return memo((accountId: Uint8Array | string): Observable<DerivedStakingQuery> =>
retrieve(api, createType(api.registry, 'AccountId', accountId)));
return retrieve(api, stashId).pipe(
switchMap(([queuedKeys, [controllerIdOpt, nominatorsOpt, rewardDestination, stakers, [validatorPrefs], nextKeys]]): Observable<DerivedStakingQuery> => {
const controllerId = controllerIdOpt.unwrapOr(null);
return controllerId
? api.query.staking.ledger(controllerId).pipe(
map((stakingLedgerOpt): DerivedStakingQuery => ({
accountId: stashId,
controllerId,
nominators: nominatorsOpt.unwrapOr([{ targets: [] }])[0].targets,
rewardDestination,
stakers,
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
stashId,
validatorPrefs,
...unwrapSessionIds(stashId, queuedKeys, nextKeys)
}))
)
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
})
);
});
}