Compare commits

..
18 Commits
Author SHA1 Message Date
Github Actions cbe2dfbd82 [CI Skip] release/stable 4.17.1
skip-checks: true
2021-07-05 08:02:45 +00:00
Jaco 5442a2e5fe 4.17 (#3724) 2021-07-05 09:53:56 +02:00
Github Actions 58b4d8c84f [CI Skip] release/beta 4.16.3-5
skip-checks: true
2021-07-05 06:42:55 +00:00
Jaco f5c6c8a072 Attach constructed registry to metadata (#3723)
* Attach constructed registry to metadata

* Remove return

* CHANGELOG
2021-07-05 08:31:06 +02:00
Github Actions 9d5ab4a2d6 [CI Skip] release/beta 4.16.3-4
skip-checks: true
2021-07-02 07:42:19 +00:00
Jaco 32f704459f api.at(blockHash).{consts, errors, events, query} (#3710)
* api.at(blockHash).{consts, errors, events, query}

* Manual tests for apiAt

* Adjust helpers... not perfect, but best for now

* Expand decorated return

* Re-add compable injectMetadata

* CHANGELOG

* Bump jest global timeout
2021-07-02 09:30:25 +02:00
Jaco e4795182ca Align static metadata with latest Substrate (#3717) 2021-07-02 09:30:01 +02:00
Github Actions 3297dbdaab [CI Skip] release/beta 4.16.3-3
skip-checks: true
2021-07-02 07:23:16 +00:00
Jaco a65a5985e6 Bump TS (#3718) 2021-07-02 09:14:50 +02:00
Github Actions 77eac494ad [CI Skip] release/beta 4.16.3-2
skip-checks: true
2021-07-02 04:58:49 +00:00
Jaco 4498f59607 Detect on elections (#3716) 2021-07-02 06:47:43 +02:00
Jaco 6322913310 Allow for fallback types (struct-only as a start) (#3714)
* Allow for fallback types (struct-only as a start)

* Filter fallback & alias from structs

* Don't clobber existing fallbackType
2021-07-01 12:54:02 +02:00
Github Actions be2f34a045 [CI Skip] release/beta 4.16.3-1
skip-checks: true
2021-07-01 08:26:48 +00:00
Jaco cce0c89168 Adjust collective with instances (#3712)
* Adjust collective with instances

* Update CHANGELOG

* Add prime & proposalaHashes to all

* Export members collective

* prime

* Optional constants

* Move constant expansion

* proposalCount derive

* candidateCount is non-optional
2021-07-01 10:17:48 +02:00
Github Actions 58cc197c89 [CI Skip] release/beta 4.16.3-0
skip-checks: true
2021-06-28 12:12:50 +00:00
Arjan Zijderveld bbb6d0eda9 Added Emergency to ElectionPhase (#3707)
Link to new field:

https://github.com/paritytech/substrate/blob/6242d37f43ec5aa9b6131a8e61b8d4e71b063907/frame/election-provider-multi-phase/src/lib.rs#L337
2021-06-28 14:03:57 +02:00
Github Actions c03068f0ec [CI Skip] release/stable 4.16.2
skip-checks: true
2021-06-27 04:03:48 +00:00
Jaco e8f352930d Correct CompactAssignments & RawSolution types for Polkadot (#3705)
* Correct `CompactAssignments` & `RawSolution` types for Polkadot

* Default to Solution 16
2021-06-27 05:55:11 +02:00
73 changed files with 1709 additions and 824 deletions
+2
View File
@@ -23,3 +23,5 @@
4.7.2
4.9.2
4.11.2
4.16.2
+26
View File
@@ -1,5 +1,31 @@
# CHANGELOG
## 4.17.1 Jul 5, 2021
Upgrade priority: Low. Allows cleaner access to multiple `.at` queries via new API.
Contributed:
- Added `Emergency` to `ElectionPhase` (Thanks to https://github.com/arjanz)
Changes:
- Added `await api.at(<blockHash>)` to retrieve API instances at a point
- Added `fallbackType` for type classes (only struct, as defined)
- Allow `instances` API config to drive derive collective locations
- Ensure correct registry is attached to historic metadata
- Align static metadata with latest Substrate
## 4.16.2 Jun 27, 2021
Upgrade priority: Low. Recommended for Polkadot with runtime >= 9050.
Changes:
- Correct `CompactAssignments` & `RawSolution` types for Polkadot
## 4.16.1 Jun 26, 2021
Upgrade priority: Low. Recommended for full from-genesis queries on Kusama.
+1 -1
View File
@@ -27,6 +27,6 @@ module.exports = {
'<rootDir>/packages/types/build',
'<rootDir>/packages/types-known/build'
],
testTimeout: 10000,
testTimeout: 30000,
transformIgnorePatterns: ['/node_modules/(?!@polkadot|@babel/runtime/helpers/esm/)']
};
+4 -4
View File
@@ -8,7 +8,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^4.3.4"
"typescript": "^4.3.5"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts",
@@ -28,11 +28,11 @@
"@babel/core": "^7.14.6",
"@babel/register": "^7.14.5",
"@babel/runtime": "^7.14.6",
"@polkadot/dev": "^0.62.43",
"@polkadot/ts": "^0.4.1",
"@polkadot/dev": "^0.62.44",
"@polkadot/ts": "^0.4.2",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.23",
"copyfiles": "^2.4.1"
},
"version": "4.16.1"
"version": "4.17.1"
}
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
@@ -20,9 +20,9 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/api": "4.16.1",
"@polkadot/types": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/x-rxjs": "^6.10.1"
"@polkadot/api": "4.17.1",
"@polkadot/types": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/x-rxjs": "^6.11.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-contract', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/api-contract', version: '4.17.1' };
+9 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
@@ -20,15 +20,15 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/api": "4.16.1",
"@polkadot/rpc-core": "4.16.1",
"@polkadot/types": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/util-crypto": "^6.10.1",
"@polkadot/x-rxjs": "^6.10.1"
"@polkadot/api": "4.17.1",
"@polkadot/rpc-core": "4.17.1",
"@polkadot/types": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/util-crypto": "^6.11.1",
"@polkadot/x-rxjs": "^6.11.1"
},
"devDependencies": {
"@polkadot/keyring": "^6.10.1",
"@polkadot/rpc-provider": "4.16.1"
"@polkadot/keyring": "^6.11.1",
"@polkadot/rpc-provider": "4.17.1"
}
}
@@ -0,0 +1,12 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
export function getInstance (api: ApiInterfaceRx, section: string): string {
const instances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), section);
return instances && instances.length
? instances[0]
: section;
}
@@ -1,4 +1,6 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './members';
export * from './prime';
export * from './proposals';
@@ -0,0 +1,23 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { Collective } from './types';
import { isFunction } from '@polkadot/util';
import { of } from '@polkadot/x-rxjs';
import { memo } from '../util';
import { getInstance } from './getInstance';
export function members (instanceId: string, api: ApiInterfaceRx, _section: Collective): () => Observable<AccountId[]> {
const section = getInstance(api, _section);
return memo(instanceId, (): Observable<AccountId[]> =>
isFunction(api.query[section]?.members)
? api.query[section as 'council'].members()
: of([])
);
}
@@ -0,0 +1,28 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Option } from '@polkadot/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { isFunction } from '@polkadot/util';
import { of } from '@polkadot/x-rxjs';
import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
import { getInstance } from './getInstance';
export function prime (instanceId: string, api: ApiInterfaceRx, _section: string): () => Observable<AccountId | null> {
const section = getInstance(api, _section);
return memo(instanceId, (): Observable<AccountId | null> =>
isFunction(api.query[section as 'council']?.prime)
? api.query[section as 'council'].prime<Option<AccountId>>().pipe(
map((optPrime): AccountId | null =>
optPrime.unwrapOr(null)
)
)
: of(null)
);
}
+42 -13
View File
@@ -2,18 +2,18 @@
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Option } from '@polkadot/types';
import type { Option, u32 } from '@polkadot/types';
import type { Hash, Proposal, Votes } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCollectiveProposal } from '../types';
import type { Collective } from './types';
import { isFunction } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs';
import { catchError, map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
type Collective = 'council' | 'membership' | 'technicalCommittee';
import { getInstance } from './getInstance';
type Result = [(Hash | Uint8Array | string)[], (Option<Proposal> | null)[], Option<Votes>[]];
@@ -31,7 +31,7 @@ function parse (api: ApiInterfaceRx, [hashes, proposals, votes]: Result): Derive
.filter((proposal): proposal is DeriveCollectiveProposal => !!proposal);
}
function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: Collective): (hashes: (Hash | Uint8Array | string)[]) => Observable<DeriveCollectiveProposal[]> {
function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: string): (hashes: (Hash | Uint8Array | string)[]) => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, (hashes: (Hash | Uint8Array | string)[]): Observable<DeriveCollectiveProposal[]> =>
(isFunction(api.query[section]?.proposals) && hashes.length
? combineLatest<Result>([
@@ -51,19 +51,48 @@ function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: Colle
);
}
export function proposals (instanceId: string, api: ApiInterfaceRx, section: Collective): () => Observable<DeriveCollectiveProposal[]> {
const proposalsFrom = _proposalsFrom(instanceId, api, section);
export function hasProposals (instanceId: string, api: ApiInterfaceRx, _section: Collective): () => Observable<boolean> {
const section = getInstance(api, _section);
return memo(instanceId, (): Observable<DeriveCollectiveProposal[]> =>
isFunction(api.query[section]?.proposals)
? api.query[section as 'council'].proposals().pipe(
switchMap(proposalsFrom)
)
: of([] as DeriveCollectiveProposal[])
return memo(instanceId, (): Observable<boolean> =>
of(isFunction(api.query[section]?.proposals))
);
}
export function proposal (instanceId: string, api: ApiInterfaceRx, section: Collective): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
export function proposalCount (instanceId: string, api: ApiInterfaceRx, _section: Collective): () => Observable<u32 | null> {
const section = getInstance(api, _section);
return memo(instanceId, (): Observable<u32 | null> =>
isFunction(api.query[section].proposalCount)
? api.query[section as 'council'].proposalCount()
: of(null)
);
}
export function proposalHashes (instanceId: string, api: ApiInterfaceRx, _section: Collective): () => Observable<Hash[]> {
const section = getInstance(api, _section);
return memo(instanceId, (): Observable<Hash[]> =>
isFunction(api.query[section]?.proposals)
? api.query[section as 'council'].proposals()
: of([])
);
}
export function proposals (instanceId: string, api: ApiInterfaceRx, _section: Collective): () => Observable<DeriveCollectiveProposal[]> {
const section = getInstance(api, _section);
const proposalsFrom = _proposalsFrom(instanceId, api, section);
const getHashes = proposalHashes(instanceId, api, _section);
return memo(instanceId, (): Observable<DeriveCollectiveProposal[]> =>
getHashes().pipe(
switchMap(proposalsFrom)
)
);
}
export function proposal (instanceId: string, api: ApiInterfaceRx, _section: Collective): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
const section = getInstance(api, _section);
const proposalsFrom = _proposalsFrom(instanceId, api, section);
return memo(instanceId, (hash: Hash | Uint8Array | string): Observable<DeriveCollectiveProposal | null> =>
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export type Collective = 'council' | 'membership' | 'technicalCommittee';
+2
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './members';
export * from './prime';
export * from './proposals';
export * from './votes';
export * from './votesOf';
@@ -0,0 +1,13 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { members as collectiveMembers } from '../collective';
import { memo } from '../util';
export function members (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, collectiveMembers(instanceId, api, 'council'));
}
+13
View File
@@ -0,0 +1,13 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { prime as collectivePrime } from '../collective';
import { memo } from '../util';
export function prime (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId | null> {
return memo(instanceId, collectivePrime(instanceId, api, 'council'));
}
+14 -1
View File
@@ -2,17 +2,30 @@
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { u32 } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCollectiveProposal } from '../types';
import { proposal as collectiveProposal, proposals as collectiveProposals } from '../collective';
import { hasProposals as collectiveHasProposals, proposal as collectiveProposal, proposalCount as collectiveProposalCount, proposalHashes as collectiveProposalHashes, proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function hasProposals (instanceId: string, api: ApiInterfaceRx): () => Observable<boolean> {
return memo(instanceId, collectiveHasProposals(instanceId, api, 'council'));
}
export function proposal (instanceId: string, api: ApiInterfaceRx): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
return memo(instanceId, collectiveProposal(instanceId, api, 'council'));
}
export function proposalCount (instanceId: string, api: ApiInterfaceRx): () => Observable<u32 | null> {
return memo(instanceId, collectiveProposalCount(instanceId, api, 'council'));
}
export function proposalHashes (instanceId: string, api: ApiInterfaceRx): () => Observable<Hash[]> {
return memo(instanceId, collectiveProposalHashes(instanceId, api, 'council'));
}
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, collectiveProposals(instanceId, api, 'council'));
}
+19 -14
View File
@@ -1,14 +1,14 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { ApiInterfaceRx, QueryableModuleStorage } from '@polkadot/api/types';
import type { Vec } from '@polkadot/types';
import type { AccountId, Balance, Voter } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types';
import { combineLatest } from '@polkadot/x-rxjs';
import { combineLatest, of } from '@polkadot/x-rxjs';
import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
@@ -20,24 +20,27 @@ function isVoter (value: VoteEntry): value is Voter {
return !Array.isArray(value);
}
function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> {
return (api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance, [AccountId]>().pipe(
function retrieveStakeOf (elections: QueryableModuleStorage<'rxjs'>): Observable<[AccountId, Balance][]> {
return elections.stakeOf.entries<Balance, [AccountId]>().pipe(
map((entries) =>
entries.map(([{ args: [accountId] }, stake]) => [accountId, stake])
)
);
}
function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> {
return (api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
function retrieveVoteOf (elections: QueryableModuleStorage<'rxjs'>): Observable<[AccountId, AccountId[]][]> {
return elections.votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
map((entries) =>
entries.map(([{ args: [accountId] }, votes]) => [accountId, votes])
)
);
}
function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
return combineLatest([retrieveStakeOf(api), retrieveVoteOf(api)]).pipe(
function retrievePrev (api: ApiInterfaceRx, elections: QueryableModuleStorage<'rxjs'>): Observable<DeriveCouncilVotes> {
return combineLatest([
retrieveStakeOf(elections),
retrieveVoteOf(elections)
]).pipe(
map(([stakes, votes]): DeriveCouncilVotes => {
const result: DeriveCouncilVotes = [];
@@ -60,9 +63,7 @@ function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
);
}
function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
const elections = (api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections);
function retrieveCurrent (elections: QueryableModuleStorage<'rxjs'>): Observable<DeriveCouncilVotes> {
return elections.voting.entries<VoteEntry, [AccountId]>().pipe(
map((entries): DeriveCouncilVotes =>
entries.map(([{ args: [accountId] }, value]): [AccountId, DeriveCouncilVote] => [
@@ -76,9 +77,13 @@ function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
}
export function votes (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCouncilVotes> {
const elections = api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections;
return memo(instanceId, (): Observable<DeriveCouncilVotes> =>
(api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections).stakeOf
? retrievePrev(api)
: retrieveCurrent(api)
elections
? elections.stakeOf
? retrievePrev(api, elections)
: retrieveCurrent(elections)
: of([])
);
}
+33 -14
View File
@@ -8,6 +8,7 @@ import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveElectionsInfo } from './types';
import { combineLatest, of } from '@polkadot/x-rxjs';
import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
@@ -42,30 +43,48 @@ function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [Accoun
}
function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
const section = api.query.phragmenElection
const elections = api.query.phragmenElection
? 'phragmenElection'
: api.query.electionsPhragmen
? 'electionsPhragmen'
: 'elections';
: api.query.elections
? 'elections'
: null;
const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'council') || ['council'];
return api.queryMulti<[Vec<AccountId>, Vec<Candidate>, Vec<Member>, Vec<Member>]>([
api.query.council.members,
api.query[section].candidates,
api.query[section].members,
api.query[section].runnersUp
]).pipe(
return (
elections
? api.queryMulti<[Vec<AccountId>, Vec<Candidate>, Vec<Member>, Vec<Member>]>([
api.query[council].members,
api.query[elections].candidates,
api.query[elections].members,
api.query[elections].runnersUp
])
: combineLatest<[Vec<AccountId>, Candidate[], Member[], Member[]]>([
api.query[council].members(),
of([]),
of([]),
of([])
])
).pipe(
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({
candidacyBond: api.consts[section].candidacyBond as Balance,
...(
elections
? {
candidacyBond: api.consts[elections].candidacyBond as Balance,
desiredRunnersUp: api.consts[elections].desiredRunnersUp as u32,
desiredSeats: api.consts[elections].desiredMembers as u32,
termDuration: api.consts[elections].termDuration as BlockNumber,
votingBond: api.consts[elections].votingBond as Balance
}
: {}
),
candidateCount: api.registry.createType('u32', candidates.length),
candidates: candidates.map(getCandidate),
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
desiredSeats: api.consts[section].desiredMembers as u32,
members: members.length
? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]),
runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts),
termDuration: api.consts[section].termDuration as BlockNumber,
votingBond: api.consts[section].votingBond as Balance
runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts)
}))
);
}
+3 -3
View File
@@ -8,12 +8,12 @@ export interface DeriveElectionsInfo {
candidates: AccountId[];
candidateCount: u32;
candidacyBond?: Balance;
desiredRunnersUp: u32;
desiredSeats: u32;
desiredRunnersUp?: u32;
desiredSeats?: u32;
members: [AccountId, Balance][];
nextVoterSet?: SetIndex;
runnersUp: [AccountId, Balance][];
termDuration: BlockNumber;
termDuration?: BlockNumber;
voteCount?: VoteIndex;
voterCount?: SetIndex;
votingBond?: Balance;
+28 -15
View File
@@ -28,6 +28,11 @@ import * as tx from './tx';
export { packageInfo } from './packageInfo';
export * from './type';
interface Avail {
instances: string[];
withDetect?: boolean;
}
export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx };
type DeriveSection<Section> = {
@@ -44,19 +49,19 @@ export type DeriveCustom = Record<string, Record<string, (instanceId: string, ap
export type ExactDerive = DeriveAllSections<typeof derive>;
// Enable derive only if some of these modules are available
const deriveAvail: Record<string, string[]> = {
contracts: ['contracts'],
council: ['council'],
democracy: ['democracy'],
elections: ['phragmenElection', 'electionsPhragmen', 'elections'],
imOnline: ['imOnline'],
membership: ['membership'],
parachains: ['parachains', 'registrar'],
session: ['session'],
society: ['society'],
staking: ['staking'],
technicalCommittee: ['technicalCommittee'],
treasury: ['treasury']
const deriveAvail: Record<string, Avail> = {
contracts: { instances: ['contracts'] },
council: { instances: ['council'], withDetect: true },
democracy: { instances: ['democracy'] },
elections: { instances: ['phragmenElection', 'electionsPhragmen', 'elections', 'council'], withDetect: true },
imOnline: { instances: ['imOnline'] },
membership: { instances: ['membership'] },
parachains: { instances: ['parachains', 'registrar'] },
session: { instances: ['session'] },
society: { instances: ['society'] },
staking: { instances: ['staking'] },
technicalCommittee: { instances: ['technicalCommittee'], withDetect: true },
treasury: { instances: ['treasury'] }
};
/**
@@ -66,11 +71,19 @@ const deriveAvail: Record<string, string[]> = {
/** @internal */
function injectFunctions<AllSections> (instanceId: string, api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
const queryKeys = Object.keys(api.query);
const specName = api.runtimeVersion.specName.toString();
return Object
.keys(allSections)
.filter((sectionName): boolean =>
!deriveAvail[sectionName] || deriveAvail[sectionName].some((query): boolean => queryKeys.includes(query))
.filter((sectionName) =>
!deriveAvail[sectionName] ||
deriveAvail[sectionName].instances.some((q) => queryKeys.includes(q)) ||
(
deriveAvail[sectionName].withDetect &&
deriveAvail[sectionName].instances.some((q) =>
(api.registry.getModuleInstances(specName, q) || []).some((q) => queryKeys.includes(q))
)
)
)
.reduce((deriveAcc, sectionName): DeriveAllSections<AllSections> => {
const section = allSections[sectionName as keyof AllSections];
@@ -1,4 +1,6 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './members';
export * from './prime';
export * from './proposals';
@@ -0,0 +1,13 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { members as collectiveMembers } from '../collective';
import { memo } from '../util';
export function members (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, collectiveMembers(instanceId, api, 'membership'));
}
@@ -0,0 +1,13 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { prime as collectivePrime } from '../collective';
import { memo } from '../util';
export function prime (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId | null> {
return memo(instanceId, collectivePrime(instanceId, api, 'membership'));
}
@@ -2,12 +2,30 @@
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { u32 } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCollectiveProposal } from '../types';
import { proposals as collectiveProposals } from '../collective';
import { hasProposals as collectiveHasProposals, proposal as collectiveProposal, proposalCount as collectiveProposalCount, proposalHashes as collectiveProposalHashes, proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function hasProposals (instanceId: string, api: ApiInterfaceRx): () => Observable<boolean> {
return memo(instanceId, collectiveHasProposals(instanceId, api, 'membership'));
}
export function proposal (instanceId: string, api: ApiInterfaceRx): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
return memo(instanceId, collectiveProposal(instanceId, api, 'membership'));
}
export function proposalCount (instanceId: string, api: ApiInterfaceRx): () => Observable<u32 | null> {
return memo(instanceId, collectiveProposalCount(instanceId, api, 'membership'));
}
export function proposalHashes (instanceId: string, api: ApiInterfaceRx): () => Observable<Hash[]> {
return memo(instanceId, collectiveProposalHashes(instanceId, api, 'membership'));
}
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, collectiveProposals(instanceId, api, 'membership'));
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-derive', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/api-derive', version: '4.17.1' };
@@ -1,4 +1,6 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './members';
export * from './prime';
export * from './proposals';
@@ -0,0 +1,13 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { members as collectiveMembers } from '../collective';
import { memo } from '../util';
export function members (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, collectiveMembers(instanceId, api, 'technicalCommittee'));
}
@@ -0,0 +1,13 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import { prime as collectivePrime } from '../collective';
import { memo } from '../util';
export function prime (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId | null> {
return memo(instanceId, collectivePrime(instanceId, api, 'technicalCommittee'));
}
@@ -2,12 +2,30 @@
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { u32 } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCollectiveProposal } from '../types';
import { proposals as collectiveProposals } from '../collective';
import { hasProposals as collectiveHasProposals, proposal as collectiveProposal, proposalCount as collectiveProposalCount, proposalHashes as collectiveProposalHashes, proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function hasProposals (instanceId: string, api: ApiInterfaceRx): () => Observable<boolean> {
return memo(instanceId, collectiveHasProposals(instanceId, api, 'technicalCommittee'));
}
export function proposal (instanceId: string, api: ApiInterfaceRx): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
return memo(instanceId, collectiveProposal(instanceId, api, 'technicalCommittee'));
}
export function proposalCount (instanceId: string, api: ApiInterfaceRx): () => Observable<u32 | null> {
return memo(instanceId, collectiveProposalCount(instanceId, api, 'technicalCommittee'));
}
export function proposalHashes (instanceId: string, api: ApiInterfaceRx): () => Observable<Hash[]> {
return memo(instanceId, collectiveProposalHashes(instanceId, api, 'technicalCommittee'));
}
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, collectiveProposals(instanceId, api, 'technicalCommittee'));
}
+1 -1
View File
@@ -14,7 +14,7 @@ export function createApiWithAugmentations (): ApiPromise {
const api = new ApiPromise({ provider: new WsProvider('ws://', false), registry });
api.injectMetadata(metadata, true);
api.injectMetadata(metadata, true, registry);
return api;
}
+11 -11
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
@@ -20,16 +20,16 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/api-derive": "4.16.1",
"@polkadot/keyring": "^6.10.1",
"@polkadot/metadata": "4.16.1",
"@polkadot/rpc-core": "4.16.1",
"@polkadot/rpc-provider": "4.16.1",
"@polkadot/types": "4.16.1",
"@polkadot/types-known": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/util-crypto": "^6.10.1",
"@polkadot/x-rxjs": "^6.10.1",
"@polkadot/api-derive": "4.17.1",
"@polkadot/keyring": "^6.11.1",
"@polkadot/metadata": "4.17.1",
"@polkadot/rpc-core": "4.17.1",
"@polkadot/rpc-provider": "4.17.1",
"@polkadot/types": "4.17.1",
"@polkadot/types-known": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/util-crypto": "^6.11.1",
"@polkadot/x-rxjs": "^6.11.1",
"eventemitter3": "^4.0.7"
}
}
+32
View File
@@ -199,10 +199,42 @@ declare module '@polkadot/api/types/consts' {
* to submit the worker's solution.
**/
offchainRepeat: BlockNumber & AugmentedConst<ApiType>;
/**
* Base deposit for a signed solution.
**/
signedDepositBase: BalanceOf & AugmentedConst<ApiType>;
/**
* Per-byte deposit for a signed solution.
**/
signedDepositByte: BalanceOf & AugmentedConst<ApiType>;
/**
* Per-weight deposit for a signed solution.
**/
signedDepositWeight: BalanceOf & AugmentedConst<ApiType>;
/**
* Maximum number of signed submissions that can be queued.
*
* It is best to avoid adjusting this during an election, as it impacts downstream data
* structures. In particular, `SignedSubmissionIndices<T>` is bounded on this value. If you
* update this value during an election, you _must_ ensure that
* `SignedSubmissionIndices.len()` is less than or equal to the new value. Otherwise,
* attempts to submit new solutions may cause a runtime panic.
**/
signedMaxSubmissions: u32 & AugmentedConst<ApiType>;
/**
* Maximum weight of a signed solution.
*
* This should probably be similar to [`Config::MinerMaxWeight`].
**/
signedMaxWeight: Weight & AugmentedConst<ApiType>;
/**
* Duration of the signed phase.
**/
signedPhase: BlockNumber & AugmentedConst<ApiType>;
/**
* Base reward for a signed solution
**/
signedRewardBase: BalanceOf & AugmentedConst<ApiType>;
/**
* The minimum amount of improvement to the solution score that defines a solution as
* "better" (in any phase).
+24
View File
@@ -555,6 +555,14 @@ declare module '@polkadot/api/types/errors' {
* The call is not allowed at this point.
**/
CallNotAllowed: AugmentedError<ApiType>;
/**
* `Self::insert_submission` returned an invalid index.
**/
InvalidSubmissionIndex: AugmentedError<ApiType>;
/**
* Snapshot metadata should exist but didn't.
**/
MissingSnapshotMetadata: AugmentedError<ApiType>;
/**
* OCW submitted solution for wrong round
**/
@@ -571,6 +579,22 @@ declare module '@polkadot/api/types/errors' {
* Wrong number of winners presented.
**/
PreDispatchWrongWinnerCount: AugmentedError<ApiType>;
/**
* The origin failed to pay the deposit.
**/
SignedCannotPayDeposit: AugmentedError<ApiType>;
/**
* Witness data to dispatchable is invalid.
**/
SignedInvalidWitness: AugmentedError<ApiType>;
/**
* The queue was full, and the solution was not better than any of the existing ones.
**/
SignedQueueFull: AugmentedError<ApiType>;
/**
* The signed submission consumes too much weight
**/
SignedTooMuchWeight: AugmentedError<ApiType>;
/**
* Generic error
**/
+5 -3
View File
@@ -391,7 +391,7 @@ declare module '@polkadot/api/types/events' {
/**
* An account has been rewarded for their signed submission being finalized.
**/
Rewarded: AugmentedEvent<ApiType, [AccountId]>;
Rewarded: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* The signed phase of the given round has started.
**/
@@ -399,14 +399,16 @@ declare module '@polkadot/api/types/events' {
/**
* An account has been slashed for submitting an invalid signed submission.
**/
Slashed: AugmentedEvent<ApiType, [AccountId]>;
Slashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A solution was stored with the given compute.
*
* If the solution is signed, this means that it hasn't yet been processed. If the
* solution is unsigned, this means that it has also been processed.
*
* The `bool` is `true` when a previous solution was ejected to make room for this one.
**/
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute]>;
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute, bool]>;
/**
* The unsigned phase of the given round has started.
**/
+39 -2
View File
@@ -20,11 +20,11 @@ import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lotter
import type { Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, Slot, TransactionInfo, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Percent, Releases, Slot, TransactionInfo, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, ElectionPhase, ElectionScore, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, ReadySolution, RewardDestination, RoundSnapshot, SeatHolder, SlashingSpans, SolutionOrSnapshotSize, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking';
import type { ActiveEraInfo, ElectionPhase, ElectionScore, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, ReadySolution, RewardDestination, RoundSnapshot, SeatHolder, SignedSubmissionOf, SlashingSpans, SolutionOrSnapshotSize, SpanIndex, SpanRecord, StakingLedger, SubmissionIndicesOf, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking';
import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
@@ -403,6 +403,37 @@ declare module '@polkadot/api/types/storage' {
* This is merely incremented once per every time that an upstream `elect` is called.
**/
round: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* A sorted, bounded set of `(score, index)`, where each `index` points to a value in
* `SignedSubmissions`.
*
* We never need to process more than a single signed submission at a time. Signed submissions
* can be quite large, so we're willing to pay the cost of multiple database accesses to access
* them one at a time instead of reading and decoding all of them at once.
**/
signedSubmissionIndices: AugmentedQuery<ApiType, () => Observable<SubmissionIndicesOf>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The next index to be assigned to an incoming signed submission.
*
* Every accepted submission is assigned a unique index; that index is bound to that particular
* submission for the duration of the election. On election finalization, the next index is
* reset to 0.
*
* We can't just use `SignedSubmissionIndices.len()`, because that's a bounded set; past its
* capacity, it will simply saturate. We can't just iterate over `SignedSubmissionsMap`,
* because iteration is slow. Instead, we store the value here.
**/
signedSubmissionNextIndex: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Unchecked, signed solutions.
*
* Together with `SubmissionIndices`, this stores a bounded set of `SignedSubmissions` while
* allowing us to keep only a single one in memory at a time.
*
* Twox note: the key of the map is an auto-incrementing index which users cannot inspect or
* affect; we shouldn't need a cryptographically secure hasher.
**/
signedSubmissionsMap: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<SignedSubmissionOf>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
* Snapshot data of the round.
*
@@ -883,6 +914,12 @@ declare module '@polkadot/api/types/storage' {
* canceled by extraordinary circumstances (e.g. governance).
**/
canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The threshold for when users can start calling `chill_other` for other validators / nominators.
* The threshold is compared to the actual number of validators / nominators (`CountFor*`) in
* the system compared to the configured max (`Max*Count`).
**/
chillThreshold: AugmentedQuery<ApiType, () => Observable<Option<Percent>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* A tracker to keep count of the number of items in the `Nominators` map.
**/
+46 -21
View File
@@ -1265,6 +1265,22 @@ declare module '@polkadot/api/types/submittable' {
* This check can be turned off by setting the value to `None`.
**/
setMinimumUntrustedScore: AugmentedSubmittable<(maybeNextScore: Option<ElectionScore> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Option<ElectionScore>]>;
/**
* Submit a solution for the signed phase.
*
* The dispatch origin fo this call must be __signed__.
*
* The solution is potentially queued, based on the claimed score and processed at the end
* of the signed phase.
*
* A deposit is reserved and recorded for the solution. Based on the outcome, the solution
* might be rewarded, slashed, or get all or a part of the deposit back.
*
* # <weight>
* Queue size must be provided as witness data.
* # </weight>
**/
submit: AugmentedSubmittable<(solution: RawSolution | { compact?: any; score?: any; round?: any } | string | Uint8Array, numSignedSubmissions: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [RawSolution, u32]>;
/**
* Submit a solution for the unsigned phase.
*
@@ -2997,15 +3013,24 @@ declare module '@polkadot/api/types/submittable' {
**/
chill: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
/**
* Declare a `controller` as having no desire to either validator or nominate.
* Declare a `controller` to stop participating as either a validator or nominator.
*
* Effects will be felt at the beginning of the next era.
*
* The dispatch origin for this call must be _Signed_, but can be called by anyone.
*
* If the caller is the same as the controller being targeted, then no further checks
* are enforced. However, this call can also be made by an third party user who witnesses
* that this controller does not satisfy the minimum bond requirements to be in their role.
* If the caller is the same as the controller being targeted, then no further checks are
* enforced, and this function behaves just like `chill`.
*
* If the caller is different than the controller being targeted, the following conditions
* must be met:
* * A `ChillThreshold` must be set and checked which defines how close to the max
* nominators or validators we must reach before users can start chilling one-another.
* * A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine
* how close we are to the threshold.
* * A `MinNominatorBond` and `MinValidatorBond` must be set and checked, which determines
* if this is a person that should be chilled because they have not met the threshold
* bond required.
*
* This can be helpful if bond requirements are updated, and we need to remove old users
* who do not satisfy these requirements.
@@ -3276,6 +3301,22 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
setPayee: AugmentedSubmittable<(payee: RewardDestination | { Staked: any } | { Stash: any } | { Controller: any } | { Account: any } | { None: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [RewardDestination]>;
/**
* Update the various staking limits this pallet.
*
* * `min_nominator_bond`: The minimum active bond needed to be a nominator.
* * `min_validator_bond`: The minimum active bond needed to be a validator.
* * `max_nominator_count`: The max number of users who can be a nominator at once.
* When set to `None`, no limit is enforced.
* * `max_validator_count`: The max number of users who can be a validator at once.
* When set to `None`, no limit is enforced.
*
* Origin must be Root to call this function.
*
* NOTE: Existing nominators and validators will not be affected by this update.
* to kick people under the new limits, `chill_other` should be called.
**/
setStakingLimits: AugmentedSubmittable<(minNominatorBond: BalanceOf | AnyNumber | Uint8Array, minValidatorBond: BalanceOf | AnyNumber | Uint8Array, maxNominatorCount: Option<u32> | null | object | string | Uint8Array, maxValidatorCount: Option<u32> | null | object | string | Uint8Array, threshold: Option<Percent> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf, BalanceOf, Option<u32>, Option<u32>, Option<Percent>]>;
/**
* Sets the ideal number of validators.
*
@@ -3325,22 +3366,6 @@ declare module '@polkadot/api/types/submittable' {
* </weight>
**/
unbond: AugmentedSubmittable<(value: Compact<BalanceOf> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>]>;
/**
* Update the various staking limits this pallet.
*
* * `min_nominator_bond`: The minimum active bond needed to be a nominator.
* * `min_validator_bond`: The minimum active bond needed to be a validator.
* * `max_nominator_count`: The max number of users who can be a nominator at once.
* When set to `None`, no limit is enforced.
* * `max_validator_count`: The max number of users who can be a validator at once.
* When set to `None`, no limit is enforced.
*
* Origin must be Root to call this function.
*
* NOTE: Existing nominators and validators will not be affected by this update.
* to kick people under the new limits, `chill_other` should be called.
**/
updateStakingLimits: AugmentedSubmittable<(minNominatorBond: BalanceOf | AnyNumber | Uint8Array, minValidatorBond: BalanceOf | AnyNumber | Uint8Array, maxNominatorCount: Option<u32> | null | object | string | Uint8Array, maxValidatorCount: Option<u32> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf, BalanceOf, Option<u32>, Option<u32>]>;
/**
* Declare the desire to validate for the origin controller.
*
@@ -4138,7 +4163,7 @@ declare module '@polkadot/api/types/submittable' {
*
* Weight: `O(n + m)` where:
* - `n = witness.instances`
* - `m = witness.instance_metdadatas`
* - `m = witness.instance_metadatas`
* - `a = witness.attributes`
**/
destroy: AugmentedSubmittable<(clazz: Compact<ClassId> | AnyNumber | Uint8Array, witness: DestroyWitness | { instances?: any; instanceMetadatas?: any; attributes?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<ClassId>, DestroyWitness]>;
+120 -11
View File
@@ -8,7 +8,8 @@ import type { Call, Hash, RpcMethods, RuntimeVersion } from '@polkadot/types/int
import type { StorageEntry } from '@polkadot/types/primitive/types';
import type { AnyFunction, AnyTuple, CallFunction, Codec, CodecArg as Arg, DefinitionRpc, DefinitionRpcSub, IMethod, InterfaceTypes, IStorageKey, Registry, RegistryTypes } from '@polkadot/types/types';
import type { SubmittableExtrinsic } from '../submittable/types';
import type { ApiInterfaceRx, ApiOptions, ApiTypes, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecoratedRpcSection, DecorateMethod, PaginationOptions, QueryableConsts, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import type { ApiDecoration, ApiInterfaceRx, ApiOptions, ApiTypes, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecoratedRpcSection, DecorateMethod, PaginationOptions, QueryableConsts, QueryableModuleStorage, QueryableModuleStorageAt, QueryableStorage, QueryableStorageAt, QueryableStorageEntry, QueryableStorageEntryAt, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import type { VersionedRegistry } from './types';
import { decorateDerive, ExactDerive } from '@polkadot/api-derive';
import { memo } from '@polkadot/api-derive/util';
@@ -18,7 +19,7 @@ import { WsProvider } from '@polkadot/rpc-provider';
import { TypeRegistry } from '@polkadot/types/create';
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants';
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { arrayChunk, arrayFlatten, assert, BN, compactStripLength, logger, u8aToHex } from '@polkadot/util';
import { arrayChunk, arrayFlatten, assert, BN, BN_ZERO, compactStripLength, logger, u8aToHex } from '@polkadot/util';
import { BehaviorSubject, combineLatest, Observable, of } from '@polkadot/x-rxjs';
import { map, switchMap, tap, toArray } from '@polkadot/x-rxjs/operators';
@@ -36,6 +37,11 @@ interface MetaDecoration {
toJSON: () => any;
}
interface FullDecoration<ApiType extends ApiTypes> {
decoratedApi: ApiDecoration<ApiType>;
decoratedMeta: DecoratedMeta;
}
// the max amount of keys/values that we will retrieve at once
const PAGE_SIZE_K = 1000; // limit aligned with the 1k on the node (trie lookups are heavy)
const PAGE_SIZE_V = 250; // limited since the data may be very large (e.g. misfiring elections)
@@ -186,8 +192,43 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return this._rpcCore.provider.hasSubscriptions || !!this._rpcCore.state.queryStorageAt;
}
public injectMetadata (metadata: Metadata, fromEmpty?: boolean, registry?: Registry): void {
const decoratedMeta = expandMetadata(registry || this.#registry, metadata);
protected _injectDecorated (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean, blockHash?: Uint8Array): FullDecoration<ApiType> {
const decoratedMeta = expandMetadata(registry.registry, registry.metadata);
// clear the decoration, we are redoing it here
if (fromEmpty || !registry.decoration) {
registry.decoration = {
consts: {},
errors: {},
events: {},
query: {}
} as ApiDecoration<ApiType>;
}
// adjust the versioned registry
augmentObject('consts', decoratedMeta.consts, registry.decoration.consts, fromEmpty);
augmentObject('errors', decoratedMeta.errors, registry.decoration.errors, fromEmpty);
augmentObject('events', decoratedMeta.events, registry.decoration.events, fromEmpty);
const storage = blockHash
? this._decorateStorageAt(decoratedMeta, this._decorateMethod, blockHash)
: this._decorateStorage(decoratedMeta, this._decorateMethod);
augmentObject('query', storage, registry.decoration.query, fromEmpty);
return {
decoratedApi: registry.decoration,
decoratedMeta
};
}
protected _injectMetadata (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean): void {
const { decoratedApi, decoratedMeta } = this._injectDecorated(registry, fromEmpty);
this._consts = decoratedApi.consts;
this._errors = decoratedApi.errors;
this._events = decoratedApi.events;
this._query = decoratedApi.query;
if (fromEmpty || !this._extrinsics) {
this._extrinsics = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
@@ -197,17 +238,19 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
augmentObject(null, this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod), this._rx.tx, false);
}
// this API
augmentObject('query', this._decorateStorage(decoratedMeta, this._decorateMethod), this._query, fromEmpty);
augmentObject('consts', decoratedMeta.consts, this._consts, fromEmpty);
augmentObject('errors', decoratedMeta.errors, this._errors, fromEmpty);
augmentObject('events', decoratedMeta.events, this._events, fromEmpty);
// rx
augmentObject(null, this._decorateStorage(decoratedMeta, this._rxDecorateMethod), this._rx.query, fromEmpty);
augmentObject(null, decoratedMeta.consts, this._rx.consts, fromEmpty);
}
/**
* @deprecated
* backwards compatible endpoint for metadata injection, may be removed in the future (However, it is still useful for testing injection)
*/
public injectMetadata (metadata: Metadata, fromEmpty?: boolean, registry?: Registry): void {
this._injectMetadata({ metadata, registry: registry || this.#registry, specVersion: BN_ZERO }, fromEmpty);
}
private _decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
output.meta = input.meta;
output.method = input.method;
@@ -353,6 +396,18 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
}, {} as QueryableStorage<ApiType>);
}
protected _decorateStorageAt<ApiType extends ApiTypes> ({ query }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array): QueryableStorageAt<ApiType> {
return Object.entries(query).reduce((out, [name, section]): QueryableStorageAt<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): QueryableModuleStorageAt<ApiType> => {
out[name] = this._decorateStorageEntryAt(method, decorateMethod, blockHash);
return out;
}, {} as QueryableModuleStorageAt<ApiType>);
return out;
}, {} as QueryableStorageAt<ApiType>);
}
private _decorateStorageEntry<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(creator, args);
@@ -371,7 +426,8 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this._rpcCore.state.getStorageHash(getArgs(args)));
decorated.is = <A extends AnyTuple> (key: IStorageKey<AnyTuple>): key is IStorageKey<A> =>
key.section === creator.section && key.method === creator.method;
key.section === creator.section &&
key.method === creator.method;
decorated.key = (...args: Arg[]): string =>
u8aToHex(compactStripLength(creator(
@@ -435,6 +491,59 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
private _decorateStorageEntryAt<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array): QueryableStorageEntryAt<ApiType> {
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(creator, args);
// Disable this where it occurs for each field we are decorating
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
const decorated = decorateMethod((...args: Arg[]): Observable<Codec> =>
this._rpcCore.state.getStorage(getArgs(args), blockHash));
decorated.creator = creator;
decorated.hash = decorateMethod((...args: Arg[]): Observable<Hash> =>
this._rpcCore.state.getStorageHash(getArgs(args), blockHash));
decorated.is = <A extends AnyTuple> (key: IStorageKey<AnyTuple>): key is IStorageKey<A> =>
key.section === creator.section &&
key.method === creator.method;
decorated.key = (...args: Arg[]): string =>
u8aToHex(compactStripLength(creator(
creator.meta.type.isPlain
? undefined
: creator.meta.type.isMap
? args[0]
: creator.meta.type.isDoubleMap
? [args[0], args[1]]
: args
))[1]);
decorated.keyPrefix = (...keys: Arg[]): string =>
u8aToHex(creator.keyPrefix(...keys));
decorated.size = decorateMethod((...args: Arg[]): Observable<u64> =>
this._rpcCore.state.getStorageSize(getArgs(args), blockHash));
// FIXME NMap support
// .keys() & .entries() only available on map types
if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) {
decorated.entries = decorateMethod(
memo(this.#instanceId, (...args: Arg[]): Observable<[StorageKey, Codec][]> =>
this._retrieveMapEntries(creator, blockHash, args)));
decorated.keys = decorateMethod(
memo(this.#instanceId, (...args: Arg[]): Observable<StorageKey[]> =>
this._retrieveMapKeys(creator, blockHash, args)));
}
/* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
// Decorate the base storage call. In the case or rxjs or promise-without-callback (await)
// we make a subscription, alternatively we push this through a single-shot query
private _decorateStorageCall<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
+2 -2
View File
@@ -5,7 +5,7 @@ import type { Metadata } from '@polkadot/metadata';
import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Text } from '@polkadot/types';
import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { ApiInterfaceRx, ApiTypes, DecoratedErrors, DecoratedEvents, DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '../types';
import type { ApiDecoration, ApiInterfaceRx, ApiTypes, DecoratedErrors, DecoratedEvents, DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '../types';
import { assertReturn } from '@polkadot/util';
@@ -21,7 +21,7 @@ function assertResult<T> (value: T | undefined): T {
return assertReturn(value, 'Api needs to be initialized before using, listen on \'ready\'');
}
export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> {
export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> implements ApiDecoration<ApiType> {
/**
* @description Contains the parameter types (constants) of all modules.
*
+37 -16
View File
@@ -7,7 +7,7 @@ import type { ChainProperties, Hash, RuntimeVersion } from '@polkadot/types/inte
import type { Registry } from '@polkadot/types/types';
import type { BN } from '@polkadot/util';
import type { Observable, Subscription } from '@polkadot/x-rxjs';
import type { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
import type { ApiBase, ApiDecoration, ApiOptions, ApiTypes, DecorateMethod } from '../types';
import type { VersionedRegistry } from './types';
import { Metadata } from '@polkadot/metadata';
@@ -28,7 +28,7 @@ const l = logger('api/init');
export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
#healthTimer: NodeJS.Timeout | null = null;
#registries: VersionedRegistry[] = [];
#registries: VersionedRegistry<ApiType>[] = [];
#updateSub?: Subscription | null = null;
@@ -44,7 +44,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
if (!options.source) {
this.registerTypes(options.types);
} else {
this.#registries = options.source.#registries;
this.#registries = options.source.#registries as VersionedRegistry<ApiType>[];
}
this._rpc = this._decorateRpc(this._rpcCore, this._decorateMethod);
@@ -79,7 +79,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
/**
* @description Decorates a registry based on the runtime version
*/
private _initRegistry (registry: Registry, chain: Text, version: { specName: Text, specVersion: BN }, metadata: Metadata, chainProps?: ChainProperties): Registry {
private _initRegistry (registry: Registry, chain: Text, version: { specName: Text, specVersion: BN }, metadata: Metadata, chainProps?: ChainProperties): void {
registry.setChainProperties(chainProps || this.registry.getChainProperties());
registry.setKnownTypes(this._options);
registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion));
@@ -94,14 +94,36 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
...getSpecExtensions(registry, chain, version.specName),
...(this._options.signedExtensions || {})
});
}
return registry;
/**
* @description Returns the default versioned registry
*/
private _getDefaultRegistry (): VersionedRegistry<ApiType> {
// get the default registry version
const thisRegistry = this.#registries.find(({ isDefault }) => isDefault);
assert(thisRegistry, 'Initialization error, cannot find the default registry');
return thisRegistry;
}
/**
* @description Returns a decorated API instance at a specific point in time
*/
public async at (blockHash: Uint8Array | string): Promise<ApiDecoration<ApiType>> {
const u8aHash = u8aToU8a(blockHash);
const registry = await this.getBlockRegistry(u8aHash);
return registry.decoration
? registry.decoration
: this._injectDecorated(registry, true, u8aHash).decoratedApi;
}
/**
* @description Sets up a registry based on the block hash defined
*/
public async getBlockRegistry (blockHash: Uint8Array): Promise<VersionedRegistry> {
public async getBlockRegistry (blockHash: Uint8Array): Promise<VersionedRegistry<ApiType>> {
const existingViaHash = this.#registries.find(({ lastBlockHash }) =>
lastBlockHash && u8aEq(lastBlockHash, blockHash)
);
@@ -141,13 +163,15 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
}
// nothing has been found, construct new
const metadata = new Metadata(this.registry,
const registry = new TypeRegistry(blockHash);
const metadata = new Metadata(registry,
await (this._rpcCore.state.getMetadata as RpcInterfaceMethod).raw(header.parentHash).toPromise()
);
const registry = this._initRegistry(new TypeRegistry(blockHash), this._runtimeChain as Text, version, metadata);
this._initRegistry(registry, this._runtimeChain as Text, version, metadata);
// add our new registry
const result = { isDefault: false, lastBlockHash: blockHash, metadata, metadataConsts: null, registry, specVersion: version.specVersion };
const result = { lastBlockHash: blockHash, metadata, registry, specVersion: version.specVersion };
this.#registries.push(result);
@@ -230,18 +254,15 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this._rx.runtimeVersion = version;
// update the default registry version
const thisRegistry = this.#registries.find(({ isDefault }) => isDefault);
assert(thisRegistry, 'Initialization error, cannot find the default registry');
const thisRegistry = this._getDefaultRegistry();
// setup the data as per the current versions
thisRegistry.metadata = metadata;
thisRegistry.metadataConsts = null;
thisRegistry.specVersion = version.specVersion;
// clear the registry types to ensure that we override correctly
this._initRegistry(thisRegistry.registry.init(), this._runtimeChain as Text, version, metadata);
this.injectMetadata(metadata, false, thisRegistry.registry);
this._injectMetadata(thisRegistry, false);
return this._detectCapabilities(thisRegistry.registry);
})
@@ -282,7 +303,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// setup the initial registry, when we have none
if (!this.#registries.length) {
this.#registries.push({ isDefault: true, lastBlockHash: null, metadata, metadataConsts: null, registry: this.registry, specVersion: runtimeVersion.specVersion });
this.#registries.push({ isDefault: true, metadata, registry: this.registry, specVersion: runtimeVersion.specVersion });
}
// get unique types & validate
@@ -298,7 +319,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here
// inject metadata and adjust the types as detected
this.injectMetadata(metadata, true);
this._injectMetadata(this._getDefaultRegistry(), true);
// derive is last, since it uses the decorated rx
this._rx.derive = this._decorateDeriveRx(this._rxDecorateMethod);
+5 -5
View File
@@ -2,15 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/metadata';
import type { Constants } from '@polkadot/metadata/decorate/types';
import type { Registry } from '@polkadot/types/types';
import type { BN } from '@polkadot/util';
import type { ApiDecoration, ApiTypes } from '../types';
export interface VersionedRegistry {
isDefault: boolean;
lastBlockHash: Uint8Array | null;
export interface VersionedRegistry<ApiType extends ApiTypes> {
decoration?: ApiDecoration<ApiType> | null;
isDefault?: boolean;
lastBlockHash?: Uint8Array | null;
metadata: Metadata;
metadataConsts: Constants | null;
registry: Registry;
specVersion: BN;
}
+12 -1
View File
@@ -239,6 +239,16 @@ async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
}
}
async function at (api: ApiPromise): Promise<void> {
const apiAt = await api.at('0x1234');
// get old balances
console.log(await apiAt.query.balances.freeBalance('0x1234'));
// get some constants
console.log(apiAt.consts.balances.existentialDeposit);
}
async function main (): Promise<void> {
const api = await ApiPromise.create();
const pairs = createTestPairs();
@@ -253,7 +263,8 @@ async function main (): Promise<void> {
queryExtra(api, pairs),
rpc(api),
types(api),
tx(api, pairs)
tx(api, pairs),
at(api)
]);
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/api', version: '4.17.1' };
+10
View File
@@ -14,7 +14,10 @@ import type { DefinitionRpc, DefinitionRpcSub, RegisteredTypes, Registry, Signat
import type { BN } from '@polkadot/util';
import type { ApiBase } from '../base';
import type { DeriveAllSections } from '../util/decorate';
import type { ApiTypes } from './base';
import type { QueryableConsts } from './consts';
import type { DecoratedErrors } from './errors';
import type { DecoratedEvents } from './events';
import type { DecoratedRpc } from './rpc';
import type { QueryableStorage, QueryableStorageMulti } from './storage';
import type { SubmittableExtrinsics } from './submittable';
@@ -103,3 +106,10 @@ export interface SignerOptions extends SignatureOptions {
blockNumber: BN;
genesisHash: Hash;
}
export interface ApiDecoration<ApiType extends ApiTypes> {
consts: QueryableConsts<ApiType>;
errors: DecoratedErrors<ApiType>;
events: DecoratedEvents<ApiType>;
query: QueryableStorage<ApiType>;
}
+32
View File
@@ -26,6 +26,11 @@ export interface StorageEntryPromiseOverloads {
<T extends Codec>(arg1: CodecArg, arg2: CodecArg, arg3: CodecArg, callback: Callback<T>): UnsubscribePromise;
}
export interface StorageEntryPromiseOverloadsAt {
(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Promise<Codec>;
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Promise<T>;
}
// This is the most generic typings we can have for a storage entry function
type GenericStorageEntryFunction = (...args: CodecArg[]) => Observable<Codec>
@@ -36,6 +41,17 @@ export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple =
// eslint-disable-next-line no-use-before-define
: AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads;
export type QueryableStorageEntryAt<ApiType extends ApiTypes, A extends AnyTuple = AnyTuple> =
ApiType extends 'rxjs'
// eslint-disable-next-line no-use-before-define
? AugmentedQueryAt<'rxjs', GenericStorageEntryFunction, A>
// eslint-disable-next-line no-use-before-define
: AugmentedQueryAt<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloadsAt;
export interface QueryableStorageAt<ApiType extends ApiTypes> extends AugmentedQueries<ApiType> {
[key: string]: QueryableModuleStorageAt<ApiType>;
}
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> {
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
creator: StorageEntry;
@@ -56,10 +72,24 @@ export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunctio
multi: ApiType extends 'rxjs' ? StorageEntryObservableMulti : StorageEntryPromiseMulti;
}
export interface StorageEntryBaseAt<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> {
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(...args: DropLast<Parameters<F>>) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
key: (...args: Parameters<F>) => string;
keyPrefix: (...args: DropLast<Parameters<F>>) => string;
keys: <K extends AnyTuple = A> (...args: DropLast<Parameters<F>>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>;
}
export interface QueryableModuleStorage<ApiType extends ApiTypes> {
[index: string]: QueryableStorageEntry<ApiType, AnyTuple>;
}
export interface QueryableModuleStorageAt<ApiType extends ApiTypes> {
[index: string]: QueryableStorageEntryAt<ApiType, AnyTuple>;
}
export type QueryableStorageMultiArg<ApiType extends ApiTypes> =
QueryableStorageEntry<ApiType> |
[QueryableStorageEntry<ApiType>, ...CodecArg[]];
@@ -83,5 +113,7 @@ export interface AugmentedQueries<ApiType extends ApiTypes> { }
export type AugmentedQuery<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = MethodResult<ApiType, F> & StorageEntryBase<ApiType, F, A>;
export type AugmentedQueryAt<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = MethodResult<ApiType, F> & StorageEntryBaseAt<ApiType, F, A>;
// backwards compatibility-only
export type AugmentedQueryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = AugmentedQuery<ApiType, F, A>;
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/metadata",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Helpers to extract information from runtime metadata",
"main": "index.js",
@@ -20,12 +20,12 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/types": "4.16.1",
"@polkadot/types-known": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/util-crypto": "^6.10.1"
"@polkadot/types": "4.17.1",
"@polkadot/types-known": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/util-crypto": "^6.11.1"
},
"devDependencies": {
"@polkadot/keyring": "^6.10.1"
"@polkadot/keyring": "^6.11.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/metadata', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/metadata', version: '4.17.1' };
+221 -13
View File
@@ -499,7 +499,7 @@
{
"name": "Version",
"type": "RuntimeVersion",
"value": "0x106e6f6465387375627374726174652d6e6f64650a0000000b0100000000000034df6acb689907609b0300000037e397fc7c91f5e40100000040fe3ad401f8959a05000000d2bc9897eed08f1502000000f78b278be53f454c02000000ed99c5acb25eedf502000000cbca25e39f14238702000000687ad44ad37f03c201000000bc9d89904f5b923f0100000068b66ba122c93fa70100000037c8bb1350a9a2a80100000091d5df18b0d2cf5801000000ab3c0572291feb8b0100000002000000",
"value": "0x106e6f6465387375627374726174652d6e6f64650a0000000b0100000000000034df6acb689907609b0300000037e397fc7c91f5e40100000040fe3ad401f8959a05000000d2bc9897eed08f1503000000f78b278be53f454c02000000ed99c5acb25eedf502000000cbca25e39f14238702000000687ad44ad37f03c201000000bc9d89904f5b923f0100000068b66ba122c93fa70100000037c8bb1350a9a2a80100000091d5df18b0d2cf5801000000ab3c0572291feb8b0100000002000000",
"documentation": [
" Get the chain's current version."
]
@@ -1954,6 +1954,63 @@
" Only exists when [`Snapshot`] is present."
]
},
{
"name": "SignedSubmissionNextIndex",
"modifier": "Default",
"type": {
"plain": "u32"
},
"fallback": "0x00000000",
"documentation": [
" The next index to be assigned to an incoming signed submission.",
"",
" Every accepted submission is assigned a unique index; that index is bound to that particular",
" submission for the duration of the election. On election finalization, the next index is",
" reset to 0.",
"",
" We can't just use `SignedSubmissionIndices.len()`, because that's a bounded set; past its",
" capacity, it will simply saturate. We can't just iterate over `SignedSubmissionsMap`,",
" because iteration is slow. Instead, we store the value here."
]
},
{
"name": "SignedSubmissionIndices",
"modifier": "Default",
"type": {
"plain": "SubmissionIndicesOf"
},
"fallback": "0x00",
"documentation": [
" A sorted, bounded set of `(score, index)`, where each `index` points to a value in",
" `SignedSubmissions`.",
"",
" We never need to process more than a single signed submission at a time. Signed submissions",
" can be quite large, so we're willing to pay the cost of multiple database accesses to access",
" them one at a time instead of reading and decoding all of them at once."
]
},
{
"name": "SignedSubmissionsMap",
"modifier": "Default",
"type": {
"map": {
"hasher": "Twox64Concat",
"key": "u32",
"value": "SignedSubmissionOf",
"linked": false
}
},
"fallback": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000",
"documentation": [
" Unchecked, signed solutions.",
"",
" Together with `SubmissionIndices`, this stores a bounded set of `SignedSubmissions` while",
" allowing us to keep only a single one in memory at a time.",
"",
" Twox note: the key of the map is an auto-incrementing index which users cannot inspect or",
" affect; we shouldn't need a cryptographically secure hasher."
]
},
{
"name": "MinimumUntrustedScore",
"modifier": "Optional",
@@ -2034,19 +2091,50 @@
" feasibility check itself can in principle cause the election process to fail (due to",
" memory/weight constrains)."
]
},
{
"name": "submit",
"args": [
{
"name": "solution",
"type": "RawSolution"
},
{
"name": "num_signed_submissions",
"type": "u32"
}
],
"documentation": [
" Submit a solution for the signed phase.",
"",
" The dispatch origin fo this call must be __signed__.",
"",
" The solution is potentially queued, based on the claimed score and processed at the end",
" of the signed phase.",
"",
" A deposit is reserved and recorded for the solution. Based on the outcome, the solution",
" might be rewarded, slashed, or get all or a part of the deposit back.",
"",
" # <weight>",
" Queue size must be provided as witness data.",
" # </weight>"
]
}
],
"events": [
{
"name": "SolutionStored",
"args": [
"ElectionCompute"
"ElectionCompute",
"bool"
],
"documentation": [
" A solution was stored with the given compute.",
"",
" If the solution is signed, this means that it hasn't yet been processed. If the",
" solution is unsigned, this means that it has also been processed."
" solution is unsigned, this means that it has also been processed.",
"",
" The `bool` is `true` when a previous solution was ejected to make room for this one."
]
},
{
@@ -2062,7 +2150,8 @@
{
"name": "Rewarded",
"args": [
"AccountId"
"AccountId",
"Balance"
],
"documentation": [
" An account has been rewarded for their signed submission being finalized."
@@ -2071,7 +2160,8 @@
{
"name": "Slashed",
"args": [
"AccountId"
"AccountId",
"Balance"
],
"documentation": [
" An account has been slashed for submitting an invalid signed submission."
@@ -2132,6 +2222,62 @@
" For example, if it is 5, that means that at least 5 blocks will elapse between attempts",
" to submit the worker's solution."
]
},
{
"name": "SignedMaxSubmissions",
"type": "u32",
"value": "0x0a000000",
"documentation": [
" Maximum number of signed submissions that can be queued.",
"",
" It is best to avoid adjusting this during an election, as it impacts downstream data",
" structures. In particular, `SignedSubmissionIndices<T>` is bounded on this value. If you",
" update this value during an election, you _must_ ensure that",
" `SignedSubmissionIndices.len()` is less than or equal to the new value. Otherwise,",
" attempts to submit new solutions may cause a runtime panic."
]
},
{
"name": "SignedMaxWeight",
"type": "Weight",
"value": "0xc07c907c2d010000",
"documentation": [
" Maximum weight of a signed solution.",
"",
" This should probably be similar to [`Config::MinerMaxWeight`]."
]
},
{
"name": "SignedRewardBase",
"type": "BalanceOf",
"value": "0x00407a10f35a00000000000000000000",
"documentation": [
" Base reward for a signed solution"
]
},
{
"name": "SignedDepositBase",
"type": "BalanceOf",
"value": "0x00407a10f35a00000000000000000000",
"documentation": [
" Base deposit for a signed solution."
]
},
{
"name": "SignedDepositByte",
"type": "BalanceOf",
"value": "0x0010a5d4e80000000000000000000000",
"documentation": [
" Per-byte deposit for a signed solution."
]
},
{
"name": "SignedDepositWeight",
"type": "BalanceOf",
"value": "0x00000000000000000000000000000000",
"documentation": [
" Per-weight deposit for a signed solution."
]
}
],
"errors": [
@@ -2153,12 +2299,48 @@
" Submission was too weak, score-wise."
]
},
{
"name": "SignedQueueFull",
"documentation": [
" The queue was full, and the solution was not better than any of the existing ones."
]
},
{
"name": "SignedCannotPayDeposit",
"documentation": [
" The origin failed to pay the deposit."
]
},
{
"name": "SignedInvalidWitness",
"documentation": [
" Witness data to dispatchable is invalid."
]
},
{
"name": "SignedTooMuchWeight",
"documentation": [
" The signed submission consumes too much weight"
]
},
{
"name": "OcwCallWrongEra",
"documentation": [
" OCW submitted solution for wrong round"
]
},
{
"name": "MissingSnapshotMetadata",
"documentation": [
" Snapshot metadata should exist but didn't."
]
},
{
"name": "InvalidSubmissionIndex",
"documentation": [
" `Self::insert_submission` returned an invalid index."
]
},
{
"name": "CallNotAllowed",
"documentation": [
@@ -2719,6 +2901,19 @@
"",
" This is set to v6.0.0 for new networks."
]
},
{
"name": "ChillThreshold",
"modifier": "Optional",
"type": {
"plain": "Percent"
},
"fallback": "0x00",
"documentation": [
" The threshold for when users can start calling `chill_other` for other validators / nominators.",
" The threshold is compared to the actual number of validators / nominators (`CountFor*`) in",
" the system compared to the configured max (`Max*Count`)."
]
}
]
},
@@ -3368,7 +3563,7 @@
]
},
{
"name": "update_staking_limits",
"name": "set_staking_limits",
"args": [
{
"name": "min_nominator_bond",
@@ -3385,6 +3580,10 @@
{
"name": "max_validator_count",
"type": "Option<u32>"
},
{
"name": "threshold",
"type": "Option<Percent>"
}
],
"documentation": [
@@ -3412,15 +3611,24 @@
}
],
"documentation": [
" Declare a `controller` as having no desire to either validator or nominate.",
" Declare a `controller` to stop participating as either a validator or nominator.",
"",
" Effects will be felt at the beginning of the next era.",
"",
" The dispatch origin for this call must be _Signed_, but can be called by anyone.",
"",
" If the caller is the same as the controller being targeted, then no further checks",
" are enforced. However, this call can also be made by an third party user who witnesses",
" that this controller does not satisfy the minimum bond requirements to be in their role.",
" If the caller is the same as the controller being targeted, then no further checks are",
" enforced, and this function behaves just like `chill`.",
"",
" If the caller is different than the controller being targeted, the following conditions",
" must be met:",
" * A `ChillThreshold` must be set and checked which defines how close to the max",
" nominators or validators we must reach before users can start chilling one-another.",
" * A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine",
" how close we are to the threshold.",
" * A `MinNominatorBond` and `MinValidatorBond` must be set and checked, which determines",
" if this is a person that should be chilled because they have not met the threshold",
" bond required.",
"",
" This can be helpful if bond requirements are updated, and we need to remove old users",
" who do not satisfy these requirements.",
@@ -7554,7 +7762,7 @@
{
"name": "Schedule",
"type": "Schedule",
"value": "0x0400000000020000000100008000000010000000001000000001000020000000200000000040000000000200020000008e060000e2fc0100cd0f030009170000861d0000030c00001f1800005629000082000000b059010055810200c00b000029070000590800003b060000b8160000a61a0000600700000de8b607b10600007d060000e6090000dc070000d5050000d70500005b06000043090000390900001c0900004d0900001d09000030090000180900004109000038090000680900007d080000f80800008e08000003220000371e0000fd210000e71d0000a6080000ab080000d5080000db090000d8090000190a00001e0b00000c09000052f72400000000006ee52400000000009c212400000000003039500000000000702a240000000000644f240000000000ce3a240000000000dc54240000000000f0182400000000001e31240000000000b0c14700000000009a12120000000000c0406d0000000000f4000000000000007854420000000000e302000000000000f03a7d2000000000672000000000000040a9e729000000002c1e000000000000650f000000000000ac13aa09000000006c835b0000000000c229870000000000dad6c907000000009409000000000000c0681300000000007c0b1900000000000210b20900000000b502000000000000fee1300800000000c274080200000000db050000000000006c548a0a00000000aab1da0f00000000f50e000000000000608b390800000000500200000000000002030000000000008e63f022000000007e2100000000000067020000000000002c030000000000002909000000000000a41f230000000000c3120000000000007ca6230000000000020d00000000000000bd1f00000000001506000000000000a6a81f0000000000fc05000000000000",
"value": "0x0400000000020000000100008000000010000000001000000001000020000000200000000040000000000200020000008e0f0000b04602009a8c0300a9720000767600005e380000ea5e00000753000097000000579e030088130500b60000007a170000c11100005721000099370000483a0000d0110000d8d12c08bc4300005c430000bb2e0000a942000000260000b72300009c370000ad540000de540000ca5400000354000018550000e553000011550000c053000007540000da540000a0530000e85300008d5400004a690000bd680000a56a000096670000b053000013540000055400006a5500009255000060550000f455000033550000cae32900000000007a332a00000000004041290000000000a6fb5d000000000060c02a0000000000e6d6290000000000065329000000000062002a0000000000d425290000000000b0522a00000000005cb3540000000000b41c1600000000008057640000000000000100000000000008f6380000000000710200000000000078d68a210000000098d6de2a000000007c75640900000000466d6f000000000070baac0000000000ec73de07000000007406000000000000922c190000000000fc9f1d00000000008618ee0900000000450200000000000082dc6108000000003e573102000000002704000000000000cc94430b000000009406e1100000000096fa930800000000dc010000000000009c020000000000001843c12400000000f001000000000000b80200000000000094070000000000008a9b2a0000000000561200000000000046432b0000000000ab0c000000000000c08c260000000000b005000000000000acd2260000000000b005000000000000",
"documentation": [
" Cost schedule and limits."
]
@@ -7640,7 +7848,7 @@
{
"name": "DeletionQueueDepth",
"type": "u32",
"value": "0x85040000",
"value": "0x1a040000",
"documentation": [
" The maximum number of tries that can be queued for deletion."
]
@@ -14875,7 +15083,7 @@
"",
" Weight: `O(n + m)` where:",
" - `n = witness.instances`",
" - `m = witness.instance_metdadatas`",
" - `m = witness.instance_metadatas`",
" - `a = witness.attributes`"
]
},
File diff suppressed because one or more lines are too long
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-core",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
@@ -20,13 +20,13 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/metadata": "4.16.1",
"@polkadot/rpc-provider": "4.16.1",
"@polkadot/types": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/x-rxjs": "^6.10.1"
"@polkadot/metadata": "4.17.1",
"@polkadot/rpc-provider": "4.17.1",
"@polkadot/types": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/x-rxjs": "^6.11.1"
},
"devDependencies": {
"@polkadot/keyring": "^6.10.1"
"@polkadot/keyring": "^6.11.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-core', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/rpc-core', version: '4.17.1' };
+9 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-provider",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Transport providers for the API",
"main": "index.js",
@@ -20,17 +20,17 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/types": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/util-crypto": "^6.10.1",
"@polkadot/x-fetch": "^6.10.1",
"@polkadot/x-global": "^6.10.1",
"@polkadot/x-ws": "^6.10.1",
"@polkadot/types": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/util-crypto": "^6.11.1",
"@polkadot/x-fetch": "^6.11.1",
"@polkadot/x-global": "^6.11.1",
"@polkadot/x-ws": "^6.11.1",
"eventemitter3": "^4.0.7"
},
"devDependencies": {
"@polkadot/keyring": "^6.10.1",
"@polkadot/metadata": "4.16.1",
"@polkadot/keyring": "^6.11.1",
"@polkadot/metadata": "4.17.1",
"mock-socket": "^9.0.3",
"nock": "^13.1.0"
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-provider', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/rpc-provider', version: '4.17.1' };
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/typegen",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Type generation scripts",
"main": "index.js",
@@ -29,11 +29,11 @@
"@babel/core": "^7.14.6",
"@babel/register": "^7.14.5",
"@babel/runtime": "^7.14.6",
"@polkadot/api": "4.16.1",
"@polkadot/metadata": "4.16.1",
"@polkadot/rpc-provider": "4.16.1",
"@polkadot/types": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/api": "4.17.1",
"@polkadot/metadata": "4.17.1",
"@polkadot/rpc-provider": "4.17.1",
"@polkadot/types": "4.17.1",
"@polkadot/util": "^6.11.1",
"handlebars": "^4.7.7",
"websocket": "^1.0.34",
"yargs": "^17.0.1"
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/typegen', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/typegen', version: '4.17.1' };
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types-known",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
@@ -20,8 +20,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/networks": "^6.10.1",
"@polkadot/types": "4.16.1",
"@polkadot/util": "^6.10.1"
"@polkadot/networks": "^6.11.1",
"@polkadot/types": "4.17.1",
"@polkadot/util": "^6.11.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/types-known', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/types-known', version: '4.17.1' };
+4 -2
View File
@@ -6,6 +6,8 @@
import type { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = {
CompactAssignments: 'CompactAssignmentsWith24',
RawSolution: 'RawSolutionWith24',
Keys: 'SessionKeys6',
ProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy']
@@ -16,9 +18,9 @@ const addrIndicesTypes = {
AccountInfo: 'AccountInfoWithRefCount',
Address: 'LookupSource',
CompactAssignments: 'CompactAssignmentsWith16',
RawSolution: 'RawSolutionWith16',
Keys: 'SessionKeys5',
LookupSource: 'IndicesLookupSource',
RawSolution: 'RawSolutionWith16',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
};
@@ -26,9 +28,9 @@ const addrAccountIdTypes = {
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
CompactAssignments: 'CompactAssignmentsWith16',
RawSolution: 'RawSolutionWith16',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
RawSolution: 'RawSolutionWith16',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
};
+3 -13
View File
@@ -6,6 +6,8 @@
import type { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = {
CompactAssignments: 'CompactAssignmentsWith16',
RawSolution: 'RawSolutionWith16',
Keys: 'SessionKeys6',
ProxyType: {
_enum: {
@@ -23,10 +25,8 @@ const sharedTypes = {
const addrAccountIdTypes = {
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
CompactAssignments: 'CompactAssignmentsWith16',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
RawSolution: 'RawSolutionWith16',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
};
@@ -70,21 +70,11 @@ const versioned: OverrideVersionedType[] = [
minmax: [28, 29],
types: {
...sharedTypes,
CompactAssignments: 'CompactAssignmentsWith16',
RawSolution: 'RawSolutionWith16',
AccountInfo: 'AccountInfoWithDualRefCount'
}
},
{
minmax: [30, 9000],
types: {
...sharedTypes,
CompactAssignments: 'CompactAssignmentsWith16',
RawSolution: 'RawSolutionWith16'
}
},
{
minmax: [9010, undefined],
minmax: [30, undefined],
types: {
...sharedTypes
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types",
"version": "4.16.1",
"version": "4.17.1",
"type": "module",
"description": "Implementation of the Parity codec",
"main": "index.js",
@@ -20,13 +20,13 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/metadata": "4.16.1",
"@polkadot/util": "^6.10.1",
"@polkadot/util-crypto": "^6.10.1",
"@polkadot/x-rxjs": "^6.10.1"
"@polkadot/metadata": "4.17.1",
"@polkadot/util": "^6.11.1",
"@polkadot/util-crypto": "^6.11.1",
"@polkadot/x-rxjs": "^6.11.1"
},
"devDependencies": {
"@polkadot/keyring": "^6.10.1",
"@polkadot/keyring": "^6.11.1",
"@types/bn.js": "^4.11.6",
"bn.js": "^4.11.9"
}
+14 -2
View File
@@ -48,10 +48,10 @@ import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDef, SiTypeDefArray
import type { Period, Priority, SchedulePeriod, SchedulePriority, Scheduled, ScheduledTo254, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { BeefyKey, FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys10, SessionKeys10B, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, SessionKeys6B, SessionKeys7, SessionKeys7B, SessionKeys8, SessionKeys8B, SessionKeys9, SessionKeys9B, ValidatorCount } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactAssignmentsTo265, CompactAssignmentsWith16, CompactAssignmentsWith24, CompactScore, CompactScoreCompact, ElectionCompute, ElectionPhase, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, ExtendedBalance, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RawSolution, RawSolutionTo265, RawSolutionWith16, RawSolutionWith24, ReadySolution, RewardDestination, RewardPoint, RoundSnapshot, SeatHolder, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SolutionOrSnapshotSize, SolutionSupport, SolutionSupports, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196, ValidatorPrefsWithBlocked, ValidatorPrefsWithCommission, VoteWeight, Voter } from '@polkadot/types/interfaces/staking';
import type { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactAssignmentsTo265, CompactAssignmentsWith16, CompactAssignmentsWith24, CompactScore, CompactScoreCompact, ElectionCompute, ElectionPhase, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, ExtendedBalance, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RawSolution, RawSolutionTo265, RawSolutionWith16, RawSolutionWith24, ReadySolution, RewardDestination, RewardPoint, RoundSnapshot, SeatHolder, SignedSubmission, SignedSubmissionOf, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SolutionOrSnapshotSize, SolutionSupport, SolutionSupports, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, SubmissionIndicesOf, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196, ValidatorPrefsWithBlocked, ValidatorPrefsWithCommission, VoteWeight, Voter } from '@polkadot/types/interfaces/staking';
import type { ApiId, BlockTrace, BlockTraceEvent, BlockTraceEventData, BlockTraceSpan, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, RuntimeVersionPartial, StorageChangeSet, TraceBlockResponse, TraceError } from '@polkadot/types/interfaces/state';
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import type { AccountInfo, AccountInfoWithDualRefCount, AccountInfoWithProviders, AccountInfoWithRefCount, AccountInfoWithTripleRefCount, ApplyExtrinsicResult, ArithmeticError, BlockLength, BlockWeights, ChainProperties, ChainType, ConsumedWeight, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, PerDispatchClassU32, PerDispatchClassWeight, PerDispatchClassWeightsPerClass, Phase, RawOrigin, RefCount, RefCountTo259, SyncState, SystemOrigin, TokenError, TransactionValidityError, UnknownTransaction, WeightPerClass } from '@polkadot/types/interfaces/system';
import type { AccountInfo, AccountInfoWithDualRefCount, AccountInfoWithProviders, AccountInfoWithRefCount, AccountInfoWithRefCountU8, AccountInfoWithTripleRefCount, ApplyExtrinsicResult, ArithmeticError, BlockLength, BlockWeights, ChainProperties, ChainType, ConsumedWeight, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, PerDispatchClassU32, PerDispatchClassWeight, PerDispatchClassWeightsPerClass, Phase, RawOrigin, RefCount, RefCountTo259, SyncState, SystemOrigin, TokenError, TransactionValidityError, UnknownTransaction, WeightPerClass } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, BountyStatus, BountyStatusActive, BountyStatusCuratorProposed, BountyStatusPendingPayout, OpenTip, OpenTipFinderTo225, OpenTipTip, OpenTipTo225, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
import type { ClassDetails, ClassId, ClassMetadata, DepositBalance, DepositBalanceOf, DestroyWitness, InstanceDetails, InstanceId, InstanceMetadata } from '@polkadot/types/interfaces/uniques';
@@ -168,6 +168,7 @@ declare module '@polkadot/types/types/registry' {
'Option<AccountInfoWithDualRefCount>': Option<AccountInfoWithDualRefCount>;
'Option<AccountInfoWithProviders>': Option<AccountInfoWithProviders>;
'Option<AccountInfoWithRefCount>': Option<AccountInfoWithRefCount>;
'Option<AccountInfoWithRefCountU8>': Option<AccountInfoWithRefCountU8>;
'Option<AccountInfoWithTripleRefCount>': Option<AccountInfoWithTripleRefCount>;
'Option<AccountKey20Junction>': Option<AccountKey20Junction>;
'Option<AccountStatus>': Option<AccountStatus>;
@@ -841,6 +842,8 @@ declare module '@polkadot/types/types/registry' {
'Option<SignedBlock>': Option<SignedBlock>;
'Option<SignedBlockWithJustification>': Option<SignedBlockWithJustification>;
'Option<SignedBlockWithJustifications>': Option<SignedBlockWithJustifications>;
'Option<SignedSubmission>': Option<SignedSubmission>;
'Option<SignedSubmissionOf>': Option<SignedSubmissionOf>;
'Option<SignerPayload>': Option<SignerPayload>;
'Option<SigningContext>': Option<SigningContext>;
'Option<SiLookupTypeId>': Option<SiLookupTypeId>;
@@ -912,6 +915,7 @@ declare module '@polkadot/types/types/registry' {
'Option<StoredState>': Option<StoredState>;
'Option<StrikeCount>': Option<StrikeCount>;
'Option<SubId>': Option<SubId>;
'Option<SubmissionIndicesOf>': Option<SubmissionIndicesOf>;
'Option<SyncState>': Option<SyncState>;
'Option<SystemInherentData>': Option<SystemInherentData>;
'Option<SystemOrigin>': Option<SystemOrigin>;
@@ -1044,6 +1048,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<AccountInfoWithDualRefCount>': Vec<AccountInfoWithDualRefCount>;
'Vec<AccountInfoWithProviders>': Vec<AccountInfoWithProviders>;
'Vec<AccountInfoWithRefCount>': Vec<AccountInfoWithRefCount>;
'Vec<AccountInfoWithRefCountU8>': Vec<AccountInfoWithRefCountU8>;
'Vec<AccountInfoWithTripleRefCount>': Vec<AccountInfoWithTripleRefCount>;
'Vec<AccountKey20Junction>': Vec<AccountKey20Junction>;
'Vec<AccountStatus>': Vec<AccountStatus>;
@@ -1717,6 +1722,8 @@ declare module '@polkadot/types/types/registry' {
'Vec<SignedBlock>': Vec<SignedBlock>;
'Vec<SignedBlockWithJustification>': Vec<SignedBlockWithJustification>;
'Vec<SignedBlockWithJustifications>': Vec<SignedBlockWithJustifications>;
'Vec<SignedSubmission>': Vec<SignedSubmission>;
'Vec<SignedSubmissionOf>': Vec<SignedSubmissionOf>;
'Vec<SignerPayload>': Vec<SignerPayload>;
'Vec<SigningContext>': Vec<SigningContext>;
'Vec<SiLookupTypeId>': Vec<SiLookupTypeId>;
@@ -1788,6 +1795,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<StoredState>': Vec<StoredState>;
'Vec<StrikeCount>': Vec<StrikeCount>;
'Vec<SubId>': Vec<SubId>;
'Vec<SubmissionIndicesOf>': Vec<SubmissionIndicesOf>;
'Vec<SyncState>': Vec<SyncState>;
'Vec<SystemInherentData>': Vec<SystemInherentData>;
'Vec<SystemOrigin>': Vec<SystemOrigin>;
@@ -1920,6 +1928,7 @@ declare module '@polkadot/types/types/registry' {
AccountInfoWithDualRefCount: AccountInfoWithDualRefCount;
AccountInfoWithProviders: AccountInfoWithProviders;
AccountInfoWithRefCount: AccountInfoWithRefCount;
AccountInfoWithRefCountU8: AccountInfoWithRefCountU8;
AccountInfoWithTripleRefCount: AccountInfoWithTripleRefCount;
AccountKey20Junction: AccountKey20Junction;
AccountStatus: AccountStatus;
@@ -2593,6 +2602,8 @@ declare module '@polkadot/types/types/registry' {
SignedBlock: SignedBlock;
SignedBlockWithJustification: SignedBlockWithJustification;
SignedBlockWithJustifications: SignedBlockWithJustifications;
SignedSubmission: SignedSubmission;
SignedSubmissionOf: SignedSubmissionOf;
SignerPayload: SignerPayload;
SigningContext: SigningContext;
SiLookupTypeId: SiLookupTypeId;
@@ -2664,6 +2675,7 @@ declare module '@polkadot/types/types/registry' {
StoredState: StoredState;
StrikeCount: StrikeCount;
SubId: SubId;
SubmissionIndicesOf: SubmissionIndicesOf;
SyncState: SyncState;
SystemInherentData: SystemInherentData;
SystemOrigin: SystemOrigin;
+11 -2
View File
@@ -175,7 +175,7 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
// Returns the type Class for construction
export function getTypeClass<T extends Codec = Codec> (registry: Registry, value: TypeDef): Constructor<T> {
const Type = registry.get<T>(value.type);
let Type = registry.get<T>(value.type);
if (Type) {
return Type;
@@ -185,5 +185,14 @@ export function getTypeClass<T extends Codec = Codec> (registry: Registry, value
assert(getFn, () => `Unable to construct class from ${stringify(value)}`);
return getFn(registry, value) as Constructor<T>;
Type = getFn(registry, value) as Constructor<T>;
// don't clobber any existing
if (!Type.__fallbackType && value.fallbackType) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore ...this is the only place we we actually assign this...
Type.__fallbackType = value.fallbackType;
}
return Type;
}
+19 -2
View File
@@ -55,11 +55,28 @@ function initType<T extends Codec = Codec, K extends string = string> (registry:
// argument here can be any string, which, when it cannot parse, will yield a
// runtime error.
export function createTypeUnsafe<T extends Codec = Codec, K extends string = string> (registry: Registry, type: K, params: unknown[] = [], options: CreateOptions = {}): T {
let Clazz: Constructor<FromReg<T, K>> | null = null;
let firstError: Error | null = null;
try {
return initType(registry, createClass<T, K>(registry, type), params, options);
Clazz = createClass<T, K>(registry, type);
return initType(registry, Clazz, params, options);
} catch (error) {
throw new Error(`createType(${type}):: ${(error as Error).message}`);
firstError = new Error(`createType(${type}):: ${(error as Error).message}`);
}
if (Clazz && Clazz.__fallbackType) {
try {
Clazz = createClass<T, K>(registry, Clazz.__fallbackType as unknown as K);
return initType(registry, Clazz, params, options);
} catch {
// swallow, we will throw the first error again
}
}
throw firstError;
}
/**
+3 -1
View File
@@ -15,6 +15,7 @@ interface TypeDefOptions {
}
const MAX_NESTED = 64;
const KNOWN_INTERNALS = ['_alias', '_fallback'];
function getTypeString (typeOrObj: any): string {
return isString(typeOrObj)
@@ -100,7 +101,8 @@ function _decodeStruct (value: TypeDef, type: string, _: string, count: number):
value.alias = parsed._alias
? new Map(Object.entries(parsed._alias))
: undefined;
value.sub = keys.filter((name) => !['_alias'].includes(name)).map((name): TypeDef =>
value.fallbackType = parsed._fallback as string | undefined;
value.sub = keys.filter((name) => !KNOWN_INTERNALS.includes(name)).map((name): TypeDef =>
getTypeDef(getTypeString(parsed[name]), { name }, count)
);
+2 -1
View File
@@ -32,9 +32,10 @@ export enum TypeDefInfo {
export interface TypeDef {
alias?: Map<string, string>;
displayName?: string;
fallbackType?: string;
info: TypeDefInfo;
index?: number;
displayName?: string;
length?: number;
name?: string;
namespace?: string;
@@ -15,7 +15,7 @@ const deprecated = {
};
const phragmen = {
CompactAssignments: 'CompactAssignmentsWith24',
CompactAssignments: 'CompactAssignmentsWith16',
CompactAssignmentsWith16: {
votes1: 'Vec<(NominatorIndexCompact, ValidatorIndexCompact)>',
votes2: 'Vec<(NominatorIndexCompact, CompactScoreCompact, ValidatorIndexCompact)>',
@@ -90,7 +90,8 @@ const phragmen = {
_enum: {
Off: null,
Signed: null,
Unsigned: '(bool, BlockNumber)'
Unsigned: '(bool, BlockNumber)',
Emergency: null
}
},
ElectionResult: {
@@ -111,7 +112,7 @@ const phragmen = {
}
},
ExtendedBalance: 'u128',
RawSolution: 'RawSolutionWith24',
RawSolution: 'RawSolutionWith16',
RawSolutionWith16: {
compact: 'CompactAssignmentsWith16',
score: 'ElectionScore',
@@ -137,6 +138,12 @@ const phragmen = {
stake: 'Balance',
deposit: 'Balance'
},
SignedSubmission: {
who: 'AccountId',
deposit: 'Balance',
solution: 'RawSolution'
},
SignedSubmissionOf: 'SignedSubmission',
SolutionOrSnapshotSize: {
voters: 'Compact<u32>',
targets: 'Compact<u32>'
@@ -146,6 +153,7 @@ const phragmen = {
voters: 'Vec<(AccountId, ExtendedBalance)>'
},
SolutionSupports: 'Vec<(AccountId, SolutionSupport)>',
SubmissionIndicesOf: 'BTreeMap<ElectionScore, u32>',
Voter: {
votes: 'Vec<AccountId>',
stake: 'Balance',
+16 -2
View File
@@ -12,7 +12,7 @@ export interface ActiveEraInfo extends Struct {
}
/** @name CompactAssignments */
export interface CompactAssignments extends CompactAssignmentsWith24 {}
export interface CompactAssignments extends CompactAssignmentsWith16 {}
/** @name CompactAssignmentsTo257 */
export interface CompactAssignmentsTo257 extends Struct {
@@ -104,6 +104,7 @@ export interface ElectionPhase extends Enum {
readonly isSigned: boolean;
readonly isUnsigned: boolean;
readonly asUnsigned: ITuple<[bool, BlockNumber]>;
readonly isEmergency: boolean;
}
/** @name ElectionResult */
@@ -207,7 +208,7 @@ export interface PhragmenScore extends Vec<u128> {}
export interface Points extends u32 {}
/** @name RawSolution */
export interface RawSolution extends RawSolutionWith24 {}
export interface RawSolution extends RawSolutionWith16 {}
/** @name RawSolutionTo265 */
export interface RawSolutionTo265 extends RawSolutionWith16 {}
@@ -259,6 +260,16 @@ export interface SeatHolder extends Struct {
readonly deposit: Balance;
}
/** @name SignedSubmission */
export interface SignedSubmission extends Struct {
readonly who: AccountId;
readonly deposit: Balance;
readonly solution: RawSolution;
}
/** @name SignedSubmissionOf */
export interface SignedSubmissionOf extends SignedSubmission {}
/** @name SlashingSpans */
export interface SlashingSpans extends Struct {
readonly spanIndex: SpanIndex;
@@ -331,6 +342,9 @@ export interface StakingLedgerTo240 extends Struct {
readonly lastReward: Option<EraIndex>;
}
/** @name SubmissionIndicesOf */
export interface SubmissionIndicesOf extends BTreeMap<ElectionScore, u32> {}
/** @name UnappliedSlash */
export interface UnappliedSlash extends Struct {
readonly validator: AccountId;
@@ -140,12 +140,19 @@ export default {
},
types: {
AccountInfo: 'AccountInfoWithTripleRefCount',
AccountInfoWithRefCountU8: {
nonce: 'Index',
refcount: 'u8',
data: 'AccountData'
},
AccountInfoWithRefCount: {
_fallback: 'AccountInfoWithRefCountU8',
nonce: 'Index',
refcount: 'RefCount',
data: 'AccountData'
},
AccountInfoWithDualRefCount: {
_fallback: 'AccountInfoWithRefCount',
nonce: 'Index',
consumers: 'RefCount',
providers: 'RefCount',
@@ -154,6 +161,7 @@ export default {
// original naming
AccountInfoWithProviders: 'AccountInfoWithDualRefCount',
AccountInfoWithTripleRefCount: {
_fallback: 'AccountInfoWithDualRefCount',
nonce: 'Index',
consumers: 'RefCount',
providers: 'RefCount',
@@ -27,6 +27,13 @@ export interface AccountInfoWithRefCount extends Struct {
readonly data: AccountData;
}
/** @name AccountInfoWithRefCountU8 */
export interface AccountInfoWithRefCountU8 extends Struct {
readonly nonce: Index;
readonly refcount: u8;
readonly data: AccountData;
}
/** @name AccountInfoWithTripleRefCount */
export interface AccountInfoWithTripleRefCount extends Struct {
readonly nonce: Index;
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/types', version: '4.16.1' };
export const packageInfo = { name: '@polkadot/types', version: '4.17.1' };
+5
View File
@@ -108,6 +108,11 @@ export type CodecArg = Codec | BigInt | BN | boolean | string | Uint8Array | boo
interface CodecArgArray extends Array<CodecArg> {}
export interface Constructor<T = Codec> {
/**
* @description An internal fallback type (previous generation) if encoding fails
*/
readonly __fallbackType?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new(registry: Registry, ...value: any[]): T;
}
+6 -1
View File
@@ -7,7 +7,12 @@ export type DefinitionTypeEnum = { _enum: DefinitionTypeType[] } | { _enum: Reco
export type DefinitionTypeSet = { _set: Record<string, number> };
export type DefinitionTypeStruct = Record<string, DefinitionTypeType> | { _alias?: Record<string, DefinitionTypeType> } & Record<string, unknown>;
type DefinitionTypeStructExtra = {
_alias?: Record<string, DefinitionTypeType>;
_fallback?: DefinitionTypeType;
} & Record<string, unknown>;
export type DefinitionTypeStruct = Record<string, DefinitionTypeType> | DefinitionTypeStructExtra;
export type DefinitionType = string | DefinitionTypeEnum | DefinitionTypeSet | DefinitionTypeStruct;
+578 -580
View File
File diff suppressed because it is too large Load Diff