Add palletVersion to queries (#4088)

* Add palletVersion to queries

* Re-use raw key creator

* types

* Re-adjust test
This commit is contained in:
Jaco
2021-10-21 14:36:54 +03:00
committed by GitHub
parent f508668c46
commit a8da5707f2
8 changed files with 131 additions and 83 deletions
+2 -1
View File
@@ -43,7 +43,7 @@ import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/ty
import type { AccountStatus, AccountValidity } from '@polkadot/types/interfaces/purchase';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, AccountId20, AccountId32, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, BlockNumberFor, BlockNumberOf, Call, CallHash, CallHashOf, ChangesTrieConfiguration, ChangesTrieSignal, CodecHash, Consensus, ConsensusEngineId, Digest, DigestItem, EncodedJustification, ExtrinsicsWeight, Fixed128, Fixed64, FixedI128, FixedI64, FixedU128, FixedU64, H1024, H128, H160, H2048, H256, H32, H512, H64, Hash, Header, HeaderPartial, I32F32, Index, IndicesLookupSource, Justification, Justifications, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, MultiAddress, MultiSigner, OpaqueCall, Origin, OriginCaller, PalletId, PalletVersion, PalletsOrigin, Pays, PerU16, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Releases, RuntimeDbWeight, Seal, SealV0, SignedBlock, SignedBlockWithJustification, SignedBlockWithJustifications, Slot, StorageData, StorageProof, TransactionInfo, TransactionPriority, TransactionStorageProof, U32F32, ValidatorId, ValidatorIdOf, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';
import type { AccountId, AccountId20, AccountId32, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, BlockNumberFor, BlockNumberOf, Call, CallHash, CallHashOf, ChangesTrieConfiguration, ChangesTrieSignal, CodecHash, Consensus, ConsensusEngineId, CrateVersion, Digest, DigestItem, EncodedJustification, ExtrinsicsWeight, Fixed128, Fixed64, FixedI128, FixedI64, FixedU128, FixedU64, H1024, H128, H160, H2048, H256, H32, H512, H64, Hash, Header, HeaderPartial, I32F32, Index, IndicesLookupSource, Justification, Justifications, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, MultiAddress, MultiSigner, OpaqueCall, Origin, OriginCaller, PalletId, PalletVersion, PalletsOrigin, Pays, PerU16, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Releases, RuntimeDbWeight, Seal, SealV0, SignedBlock, SignedBlockWithJustification, SignedBlockWithJustifications, Slot, StorageData, StorageProof, TransactionInfo, TransactionPriority, TransactionStorageProof, U32F32, ValidatorId, ValidatorIdOf, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';
import type { Si0Field, Si0LookupTypeId, Si0Path, Si0Type, Si0TypeDef, Si0TypeDefArray, Si0TypeDefBitSequence, Si0TypeDefCompact, Si0TypeDefComposite, Si0TypeDefPhantom, Si0TypeDefPrimitive, Si0TypeDefSequence, Si0TypeDefTuple, Si0TypeDefVariant, Si0TypeParameter, Si0Variant, Si1Field, Si1LookupTypeId, Si1Path, Si1Type, Si1TypeDef, Si1TypeDefArray, Si1TypeDefBitSequence, Si1TypeDefCompact, Si1TypeDefComposite, Si1TypeDefPrimitive, Si1TypeDefSequence, Si1TypeDefTuple, Si1TypeDefVariant, Si1TypeParameter, Si1Variant, SiField, SiLookupTypeId, SiPath, SiType, SiTypeDef, SiTypeDefArray, SiTypeDefBitSequence, SiTypeDefCompact, SiTypeDefComposite, SiTypeDefPrimitive, SiTypeDefSequence, SiTypeDefTuple, SiTypeDefVariant, SiTypeParameter, SiVariant } from '@polkadot/types/interfaces/scaleInfo';
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';
@@ -259,6 +259,7 @@ declare module '@polkadot/types/types/registry' {
CoreAssignment: CoreAssignment;
CoreIndex: CoreIndex;
CoreOccupied: CoreOccupied;
CrateVersion: CrateVersion;
CreatedBlock: CreatedBlock;
Data: Data;
DeferredOffenceOf: DeferredOffenceOf;
@@ -53,6 +53,11 @@ export default {
},
ConsensusEngineId: 'GenericConsensusEngineId',
CodecHash: 'Hash',
CrateVersion: {
major: 'u16',
minor: 'u8',
patch: 'u8'
},
Digest: {
logs: 'Vec<DigestItem>'
},
@@ -76,6 +76,13 @@ export interface Consensus extends ITuple<[ConsensusEngineId, Bytes]> {}
/** @name ConsensusEngineId */
export interface ConsensusEngineId extends GenericConsensusEngineId {}
/** @name CrateVersion */
export interface CrateVersion extends Struct {
readonly major: u16;
readonly minor: u8;
readonly patch: u8;
}
/** @name Digest */
export interface Digest extends Struct {
readonly logs: Vec<DigestItem>;
@@ -14,14 +14,17 @@ import { StorageKey } from '../../../primitive';
import { getHasher } from './getHasher';
export interface CreateItemOptions {
key?: string;
key?: Uint8Array | string;
skipHashing?: boolean;
}
export interface CreateItemFn {
meta: StorageEntryMetadataLatest;
export interface CreateItemBase {
method: string;
prefix: string;
}
export interface CreateItemFn extends CreateItemBase {
meta: StorageEntryMetadataLatest;
section: string;
}
@@ -31,7 +34,7 @@ interface IterFn {
}
/** @internal */
function createKeyRaw (registry: Registry, itemFn: CreateItemFn, keys: SiLookupTypeId[], hashers: StorageHasher[], args: unknown[]): Uint8Array {
export function createKeyRaw (registry: Registry, itemFn: CreateItemBase, keys: SiLookupTypeId[], hashers: StorageHasher[], args: unknown[]): Uint8Array {
return u8aConcat(
xxhashAsU8a(itemFn.prefix, 128),
xxhashAsU8a(itemFn.method, 128),
@@ -4,6 +4,7 @@
import { createTestPairs } from '@polkadot/keyring/testingPairs';
import rpcMetadata from '@polkadot/types-support/metadata/static-substrate';
import { u8aToHex } from '@polkadot/util';
import { xxhashAsHex } from '@polkadot/util-crypto';
import { TypeRegistry } from '../../../create';
import { Metadata } from '../../';
@@ -37,11 +38,24 @@ describe('decorateStorage', (): void => {
it('should return the correct length-prefixed storage key', (): void => {
expect(
u8aToHex(
query.system.account(keyring.alice.address)
)
u8aToHex(query.system.account(keyring.alice.address))
).toEqual(
'0x410126aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d'
'0x' +
'4101' + // length
'26aa394eea5630e07c48ae0c9558cef7' + // System
'b99d880ec681799c0cf30e8886371da9' + // account
'de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d'
);
});
it('should decorate the palletVersion entry', (): void => {
expect(
u8aToHex(query.system.palletVersion())
).toEqual(
'0x' +
'80' + // length
'26aa394eea5630e07c48ae0c9558cef7' + // System
xxhashAsHex(':__STORAGE_VERSION__:', 128).substr(2)
);
});
});
@@ -7,8 +7,9 @@ import type { ModuleStorage, Storage } from '../types';
import { stringCamelCase, stringLowerFirst } from '@polkadot/util';
import { createFunction } from './createFunction';
import { createFunction, createKeyRaw } from './createFunction';
import { getStorage } from './getStorage';
import { createRuntimeFunction } from './util';
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -35,7 +36,17 @@ export function decorateStorage (registry: Registry, { pallets }: MetadataLatest
}, {});
return newModule;
}, {} as ModuleStorage);
}, {
palletVersion: createRuntimeFunction(
name.toString(),
'palletVersion',
createKeyRaw(registry, { method: ':__STORAGE_VERSION__:', prefix: name.toString() }, [], [], []),
{
docs: 'Returns the current pallet version from storage',
type: 'u16'
}
)(registry)
} as ModuleStorage);
return result;
}, { ...getStorage(registry) });
@@ -1,97 +1,31 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { PortableType } from '../../../interfaces';
import type { StorageEntry } from '../../../primitive/types';
import type { Registry } from '../../../types';
import { createFunction } from './createFunction';
interface SubstrateMetadata {
docs: string;
type: string;
}
import { createRuntimeFunction } from './util';
type Creator = (registry: Registry) => StorageEntry;
function findSiPrimitive (registry: Registry, _prim: string): PortableType | undefined {
const prim = _prim.toLowerCase();
const portable = registry.lookup.types.find((t) =>
(
t.type.def.isPrimitive &&
t.type.def.asPrimitive.toString().toLowerCase() === prim
) || (
t.type.def.isHistoricMetaCompat &&
t.type.def.asHistoricMetaCompat.toString().toLowerCase() === prim
)
);
return portable;
}
function findSiType (registry: Registry, orig: string): PortableType | undefined {
let portable = findSiPrimitive(registry, orig);
if (!portable && orig === 'Bytes') {
const u8 = findSiPrimitive(registry, 'u8');
if (u8) {
portable = registry.lookup.types.find((t) =>
(
t.type.def.isSequence &&
t.type.def.asSequence.type.eq(u8.id)
) || (
t.type.def.isHistoricMetaCompat &&
t.type.def.asHistoricMetaCompat.eq(orig)
)
);
}
}
if (!portable) {
console.warn(`Unable to map ${orig} to a lookup index`);
}
return portable;
}
// Small helper function to factorize code on this page.
/** @internal */
function createRuntimeFunction (method: string, key: string, { docs, type }: SubstrateMetadata): (registry: Registry) => StorageEntry {
return (registry: Registry): StorageEntry =>
createFunction(registry, {
meta: registry.createType('StorageEntryMetadataLatest', {
docs: registry.createType('Vec<Text>', [docs]),
modifier: registry.createType('StorageEntryModifierLatest', 'Required'),
name: registry.createType('Text', method),
toJSON: (): any => key,
type: registry.createType('StorageEntryTypeLatest', { Plain: findSiType(registry, type)?.id || 0 })
}),
method,
prefix: 'Substrate',
section: 'substrate'
}, { key, skipHashing: true });
}
export const substrate: Record<string, Creator> = {
changesTrieConfig: createRuntimeFunction('changesTrieConfig', ':changes_trie', {
changesTrieConfig: createRuntimeFunction('Substrate', 'changesTrieConfig', ':changes_trie', {
docs: ' Changes trie configuration is stored under this key.',
type: 'u32'
}),
childStorageKeyPrefix: createRuntimeFunction('childStorageKeyPrefix', ':child_storage:', {
childStorageKeyPrefix: createRuntimeFunction('Substrate', 'childStorageKeyPrefix', ':child_storage:', {
docs: ' Prefix of child storage keys.',
type: 'u32'
}),
code: createRuntimeFunction('code', ':code', {
code: createRuntimeFunction('Substrate', 'code', ':code', {
docs: ' Wasm code of the runtime.',
type: 'Bytes'
}),
extrinsicIndex: createRuntimeFunction('extrinsicIndex', ':extrinsic_index', {
extrinsicIndex: createRuntimeFunction('Substrate', 'extrinsicIndex', ':extrinsic_index', {
docs: ' Current extrinsic index (u32) is stored under this key.',
type: 'u32'
}),
heapPages: createRuntimeFunction('heapPages', ':heappages', {
heapPages: createRuntimeFunction('Substrate', 'heapPages', ':heappages', {
docs: ' Number of wasm linear memory pages required for execution of the runtime.',
type: 'u64'
})
@@ -0,0 +1,73 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { PortableType } from '../../../interfaces';
import type { StorageEntry } from '../../../primitive/types';
import type { Registry } from '../../../types';
import { createFunction } from './createFunction';
interface ManualMetadata {
docs: string;
type: string;
}
function findSiPrimitive (registry: Registry, _prim: string): PortableType | undefined {
const prim = _prim.toLowerCase();
const portable = registry.lookup.types.find((t) =>
(
t.type.def.isPrimitive &&
t.type.def.asPrimitive.toString().toLowerCase() === prim
) || (
t.type.def.isHistoricMetaCompat &&
t.type.def.asHistoricMetaCompat.toString().toLowerCase() === prim
)
);
return portable;
}
function findSiType (registry: Registry, orig: string): PortableType | undefined {
let portable = findSiPrimitive(registry, orig);
if (!portable && orig === 'Bytes') {
const u8 = findSiPrimitive(registry, 'u8');
if (u8) {
portable = registry.lookup.types.find((t) =>
(
t.type.def.isSequence &&
t.type.def.asSequence.type.eq(u8.id)
) || (
t.type.def.isHistoricMetaCompat &&
t.type.def.asHistoricMetaCompat.eq(orig)
)
);
}
}
if (!portable) {
console.warn(`Unable to map ${orig} to a lookup index`);
}
return portable;
}
// Small helper function to factorize code on this page.
/** @internal */
export function createRuntimeFunction (prefix: string, method: string, key: Uint8Array | string, { docs, type }: ManualMetadata): (registry: Registry) => StorageEntry {
return (registry: Registry): StorageEntry =>
createFunction(registry, {
meta: registry.createType('StorageEntryMetadataLatest', {
docs: registry.createType('Vec<Text>', [docs]),
modifier: registry.createType('StorageEntryModifierLatest', 'Required'),
name: registry.createType('Text', method),
toJSON: (): any => key,
type: registry.createType('StorageEntryTypeLatest', { Plain: findSiType(registry, type)?.id || 0 })
}),
method,
prefix,
section: prefix.toLowerCase()
}, { key, skipHashing: true });
}