Additional derive cleanups (#4299)
* Additional derive cleanups * map var * Apply suggestions from code review * Additional * Metadata cleanups * Adjust * Apply HexString to all Metadata init * typegen HexString * generator HexString * basepath
This commit is contained in:
@@ -40,15 +40,11 @@ function parseFlags (address: AccountId | Address | string | null | undefined, [
|
||||
*/
|
||||
export function flags (instanceId: string, api: ApiInterfaceRx): (address?: AccountId | Address | string | null) => Observable<DeriveAccountFlags> {
|
||||
return memo(instanceId, (address?: AccountId | Address | string | null): Observable<DeriveAccountFlags> => {
|
||||
const councilSection = api.query.phragmenElection
|
||||
? 'phragmenElection'
|
||||
: api.query.electionsPhragmen
|
||||
? 'electionsPhragmen'
|
||||
: 'elections';
|
||||
const elections = api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections;
|
||||
|
||||
return combineLatest([
|
||||
address && api.query[councilSection]?.members
|
||||
? api.query[councilSection].members<Vec<ITuple<[AccountId, Balance]>>>()
|
||||
address && elections?.members
|
||||
? elections.members<Vec<ITuple<[AccountId, Balance]>>>()
|
||||
: of(undefined),
|
||||
address && api.query.council?.members
|
||||
? api.query.council.members()
|
||||
@@ -63,7 +59,7 @@ export function flags (instanceId: string, api: ApiInterfaceRx): (address?: Acco
|
||||
? api.query.sudo.key()
|
||||
: of(undefined)
|
||||
]).pipe(
|
||||
map((result) => parseFlags(address, result))
|
||||
map((r) => parseFlags(address, r))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -165,9 +165,7 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId, balanceInstanc
|
||||
|
||||
return [
|
||||
vesting
|
||||
? Array.isArray(vesting)
|
||||
? vesting
|
||||
: [vesting]
|
||||
? Array.isArray(vesting) ? vesting : [vesting]
|
||||
: null,
|
||||
lockEmpty.map((e) => e ? api.registry.createType<Vec<PalletBalancesBalanceLock>>('Vec<BalanceLock>') : locks[++offset])
|
||||
];
|
||||
|
||||
@@ -42,14 +42,12 @@ export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observ
|
||||
? api.query.council.proposalCount<ProposalIndex>()
|
||||
: of(0)
|
||||
]).pipe(
|
||||
switchMap(() =>
|
||||
combineLatest([
|
||||
bountyBase.bounties.keys<[BountyIndex]>(),
|
||||
api.derive.council
|
||||
? api.derive.council.proposals()
|
||||
: of([])
|
||||
])
|
||||
),
|
||||
switchMap(() => combineLatest([
|
||||
bountyBase.bounties.keys<[BountyIndex]>(),
|
||||
api.derive.council
|
||||
? api.derive.council.proposals()
|
||||
: of([])
|
||||
])),
|
||||
switchMap(([keys, proposals]): Observable<Result> => {
|
||||
const ids = keys.map(({ args: [id] }) => id);
|
||||
|
||||
|
||||
@@ -61,10 +61,8 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], (Opt
|
||||
// however we have had cases on Darwinia where the indices have moved around after an
|
||||
// upgrade, which results in invalid on-chain data
|
||||
combineLatest(blockNumbers.map((blockNumber) =>
|
||||
api.query.scheduler.agenda(blockNumber).pipe(
|
||||
// this does create an issue since it discards all at that block
|
||||
catchError(() => of(null))
|
||||
)
|
||||
// this does create an issue since it discards all at that block
|
||||
api.query.scheduler.agenda(blockNumber).pipe(catchError(() => of(null)))
|
||||
))
|
||||
])
|
||||
: of<[BlockNumber[], null[]]>([[], []]);
|
||||
@@ -78,30 +76,23 @@ function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
|
||||
const result: SchedulerInfo[] = [];
|
||||
|
||||
blockNumbers.forEach((at, index): void => {
|
||||
(agendas[index] || [])
|
||||
.filter((opt) => opt.isSome)
|
||||
.forEach((optScheduled): void => {
|
||||
const scheduled = optScheduled.unwrap();
|
||||
(agendas[index] || []).filter((o) => o.isSome).forEach((o): void => {
|
||||
const scheduled = o.unwrap();
|
||||
|
||||
if (scheduled.maybeId.isSome) {
|
||||
const id = scheduled.maybeId.unwrap().toHex();
|
||||
if (scheduled.maybeId.isSome) {
|
||||
const id = scheduled.maybeId.unwrap().toHex();
|
||||
|
||||
if (id.startsWith(DEMOCRACY_ID)) {
|
||||
const [, index] = api.registry.createType('(u64, ReferendumIndex)', id);
|
||||
const imageHash = scheduled.call.args[0] as Hash;
|
||||
|
||||
result.push({ at, imageHash, index });
|
||||
}
|
||||
}
|
||||
});
|
||||
id.startsWith(DEMOCRACY_ID) && result.push({ at, imageHash: scheduled.call.args[0] as Hash, index: api.registry.createType('(u64, ReferendumIndex)', id)[1] });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return result.length
|
||||
? combineLatest([
|
||||
of(result),
|
||||
api.derive.democracy.preimages(result.map(({ imageHash }) => imageHash))
|
||||
])
|
||||
: of([[], []]);
|
||||
return combineLatest([
|
||||
of(result),
|
||||
result.length
|
||||
? api.derive.democracy.preimages(result.map(({ imageHash }) => imageHash))
|
||||
: of([])
|
||||
]);
|
||||
}),
|
||||
map(([infos, images]): DeriveDispatch[] =>
|
||||
infos.map((info, index) => ({ ...info, image: images[index] }))
|
||||
|
||||
@@ -42,6 +42,18 @@ function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [Accoun
|
||||
return balanceB.cmp(balanceA);
|
||||
}
|
||||
|
||||
function getConstants (api: ApiInterfaceRx, elections: string | null): Partial<DeriveElectionsInfo> {
|
||||
return 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
|
||||
}
|
||||
: {};
|
||||
}
|
||||
|
||||
function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
const elections = api.query.phragmenElection
|
||||
? 'phragmenElection'
|
||||
@@ -68,17 +80,7 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
])
|
||||
).pipe(
|
||||
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({
|
||||
...(
|
||||
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
|
||||
}
|
||||
: {}
|
||||
),
|
||||
...getConstants(api, elections),
|
||||
candidateCount: api.registry.createType('u32', candidates.length),
|
||||
candidates: candidates.map(getCandidate),
|
||||
members: members.length
|
||||
|
||||
@@ -29,8 +29,8 @@ function parseDetails (stashId: AccountId, controllerIdOpt: Option<AccountId> |
|
||||
|
||||
function getLedgers (api: ApiInterfaceRx, optIds: (Option<AccountId> | null)[], { withLedger = false }: StakingQueryFlags): Observable<Option<PalletStakingStakingLedger>[]> {
|
||||
const ids = optIds
|
||||
.filter((opt): opt is Option<AccountId> => withLedger && !!opt && opt.isSome)
|
||||
.map((opt) => opt.unwrap());
|
||||
.filter((o): o is Option<AccountId> => withLedger && !!o && o.isSome)
|
||||
.map((o) => o.unwrap());
|
||||
const emptyLed = api.registry.createType<Option<PalletStakingStakingLedger>>('Option<StakingLedger>');
|
||||
|
||||
return (
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types';
|
||||
import type { ChainProperties, Hash, RuntimeVersion, RuntimeVersionPartial } from '@polkadot/types/interfaces';
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ApiBase, ApiDecoration, ApiOptions, ApiTypes, DecorateMethod } from '../types';
|
||||
import type { VersionedRegistry } from './types';
|
||||
|
||||
@@ -172,7 +173,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
// nothing has been found, construct new
|
||||
const registry = new TypeRegistry(blockHash);
|
||||
const metadata = new Metadata(registry,
|
||||
await firstValueFrom(this._rpcCore.state.getMetadata.raw<string>(header.parentHash))
|
||||
await firstValueFrom(this._rpcCore.state.getMetadata.raw<HexString>(header.parentHash))
|
||||
);
|
||||
|
||||
this._initRegistry(registry, this._runtimeChain as Text, version, metadata);
|
||||
@@ -314,7 +315,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
private async _metaFromChain (optMetadata?: Record<string, string>): Promise<[Hash, Metadata]> {
|
||||
private async _metaFromChain (optMetadata?: Record<string, HexString>): Promise<[Hash, Metadata]> {
|
||||
const [genesisHash, runtimeVersion, chain, chainProps, rpcMethods, chainMetadata] = await Promise.all([
|
||||
firstValueFrom(this._rpcCore.chain.getBlockHash(0)),
|
||||
firstValueFrom(this._rpcCore.state.getRuntimeVersion()),
|
||||
|
||||
@@ -85,35 +85,6 @@ async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
|
||||
const multib = await api.query.system.account.multi([pairs.alice.address, pairs.bob.address]);
|
||||
|
||||
console.log('query types:', bar, bal, bal2, override, oldBal, multia, multib);
|
||||
|
||||
// check multi for unsub
|
||||
const multiUnsub = await api.queryMulti([
|
||||
[api.query.staking.validators],
|
||||
[api.query.system.events]
|
||||
], (values): void => {
|
||||
console.log('values', values);
|
||||
|
||||
multiUnsub();
|
||||
});
|
||||
|
||||
// check multi , Promise result
|
||||
const multiRes = await api.queryMulti([
|
||||
[api.query.system.account, pairs.eve.address],
|
||||
// older chains only
|
||||
[api.query.system.accountNonce, pairs.eve.address]
|
||||
]);
|
||||
|
||||
console.log(multiRes);
|
||||
|
||||
// check multi, via at
|
||||
const apiAt = await api.at('0x12345678');
|
||||
const multiResAt = await apiAt.queryMulti([
|
||||
api.query.timestamp.now,
|
||||
[apiAt.query.staking.validators],
|
||||
[apiAt.query.system.account, pairs.eve.address]
|
||||
]);
|
||||
|
||||
console.log(multiResAt);
|
||||
}
|
||||
|
||||
async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
|
||||
@@ -165,6 +136,37 @@ async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void
|
||||
}
|
||||
}
|
||||
|
||||
async function queryMulti (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
|
||||
// check multi for unsub
|
||||
const multiUnsub = await api.queryMulti([
|
||||
[api.query.staking.validators],
|
||||
[api.query.system.events]
|
||||
], (values): void => {
|
||||
console.log('values', values);
|
||||
|
||||
multiUnsub();
|
||||
});
|
||||
|
||||
// check multi , Promise result
|
||||
const multiRes = await api.queryMulti([
|
||||
[api.query.system.account, pairs.eve.address],
|
||||
// older chains only
|
||||
[api.query.system.accountNonce, pairs.eve.address]
|
||||
]);
|
||||
|
||||
console.log(multiRes);
|
||||
|
||||
// check multi, via at
|
||||
const apiAt = await api.at('0x12345678');
|
||||
const multiResAt = await apiAt.queryMulti([
|
||||
api.query.timestamp.now,
|
||||
[apiAt.query.staking.validators],
|
||||
[apiAt.query.system.account, pairs.eve.address]
|
||||
]);
|
||||
|
||||
console.log(multiResAt);
|
||||
}
|
||||
|
||||
async function rpc (api: ApiPromise): Promise<void> {
|
||||
// defaults
|
||||
await api.rpc.chain.subscribeNewHeads((header): void => {
|
||||
@@ -270,6 +272,7 @@ async function main (): Promise<void> {
|
||||
events(api),
|
||||
query(api, pairs),
|
||||
queryExtra(api, pairs),
|
||||
queryMulti(api, pairs),
|
||||
rpc(api),
|
||||
types(api),
|
||||
tx(api, pairs),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { SubmittableExtrinsic } from '../types';
|
||||
|
||||
import { jest } from '@jest/globals';
|
||||
@@ -56,7 +57,7 @@ describe('ApiPromise', (): void => {
|
||||
|
||||
describe('initialization', (): void => {
|
||||
it('Create API instance with metadata map and makes the runtime, rpc, state & extrinsics available', async (): Promise<void> => {
|
||||
const rpcData = await provider.send<string>('state_getMetadata', []);
|
||||
const rpcData = await provider.send<HexString>('state_getMetadata', []);
|
||||
const genesisHash = registry.createType('Hash', await provider.send('chain_getBlockHash', [])).toHex();
|
||||
const specVersion = 0;
|
||||
const api = await ApiPromise.create({ metadata: { [`${genesisHash}-${specVersion}`]: rpcData }, provider, registry, throwOnConnect: true });
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import type { Metadata } from '@polkadot/types/metadata';
|
||||
import type { CallFunction, DefinitionRpc, DefinitionRpcSub, RegisteredTypes, Registry, RegistryError, SignatureOptions, Signer } from '@polkadot/types/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ApiBase } from '../base';
|
||||
import type { DeriveAllSections } from '../util/decorate';
|
||||
import type { ApiTypes } from './base';
|
||||
@@ -54,7 +55,7 @@ export interface ApiOptions extends RegisteredTypes {
|
||||
* @description pre-bundles is a map of 'genesis hash and runtime spec version' as key to a metadata hex string
|
||||
* if genesis hash and runtime spec version matches, then use metadata, else fetch it from chain
|
||||
*/
|
||||
metadata?: Record<string, string>;
|
||||
metadata?: Record<string, HexString>;
|
||||
/**
|
||||
* @description Transport Provider from rpc-provider. If not specified, it will default to
|
||||
* connecting to a WsProvider connecting localhost with the default port, i.e. `ws://127.0.0.1:9944`
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/typegen authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import path from 'path';
|
||||
import yargs from 'yargs';
|
||||
|
||||
@@ -11,12 +13,13 @@ import { WebSocket } from '@polkadot/x-ws';
|
||||
import { generateDefaultConsts, generateDefaultErrors, generateDefaultEvents, generateDefaultQuery, generateDefaultRpc, generateDefaultTx } from './generate';
|
||||
import { HEADER, writeFile } from './util';
|
||||
|
||||
function generate (metaHex: string, pkg: string | undefined, output: string, isStrict?: boolean): void {
|
||||
function generate (metaHex: HexString, pkg: string | undefined, output: string, isStrict?: boolean): void {
|
||||
console.log(`Generating from metadata, ${formatNumber((metaHex.length - 2) / 2)} bytes`);
|
||||
|
||||
const base = path.join(process.cwd(), output);
|
||||
const extraTypes = pkg
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record<string, any> }
|
||||
? { [pkg]: require(path.join(base, 'definitions')) as Record<string, any> }
|
||||
: {};
|
||||
|
||||
let customLookupDefinitions;
|
||||
@@ -25,20 +28,20 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
|
||||
customLookupDefinitions = {
|
||||
rpc: {},
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires
|
||||
types: require(path.join(process.cwd(), output, 'lookup.ts')).default
|
||||
types: require(path.join(base, 'lookup.ts')).default
|
||||
} as Definitions;
|
||||
} catch (error) {
|
||||
console.log('No custom definitions found.');
|
||||
}
|
||||
|
||||
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultErrors(path.join(process.cwd(), output, 'augment-api-errors.ts'), metaHex, extraTypes, isStrict);
|
||||
generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultRpc(path.join(process.cwd(), output, 'augment-api-rpc.ts'), extraTypes);
|
||||
generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultConsts(path.join(base, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultErrors(path.join(base, 'augment-api-errors.ts'), metaHex, extraTypes, isStrict);
|
||||
generateDefaultEvents(path.join(base, 'augment-api-events.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultQuery(path.join(base, 'augment-api-query.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultRpc(path.join(base, 'augment-api-rpc.ts'), extraTypes);
|
||||
generateDefaultTx(path.join(base, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
|
||||
writeFile(path.join(process.cwd(), output, 'augment-api.ts'), (): string =>
|
||||
writeFile(path.join(base, 'augment-api.ts'), (): string =>
|
||||
[
|
||||
HEADER('chain'),
|
||||
...[
|
||||
@@ -95,13 +98,13 @@ export function main (): void {
|
||||
};
|
||||
|
||||
websocket.onmessage = (message: unknown): void => {
|
||||
generate((JSON.parse((message as Record<string, string>).data) as Record<string, string>).result, pkg, output, isStrict);
|
||||
generate((JSON.parse((message as Record<string, string>).data) as Record<string, HexString>).result, pkg, output, isStrict);
|
||||
};
|
||||
} catch (error) {
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
generate((require(path.join(process.cwd(), endpoint)) as Record<string, string>).result, pkg, output, isStrict);
|
||||
generate((require(path.join(process.cwd(), endpoint)) as Record<string, HexString>).result, pkg, output, isStrict);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/typegen authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import path from 'path';
|
||||
import yargs from 'yargs';
|
||||
|
||||
@@ -32,7 +34,7 @@ export function main (): void {
|
||||
|
||||
if (endpoint) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const metaHex = (require(path.join(process.cwd(), endpoint)) as Record<string, string>).result;
|
||||
const metaHex = (require(path.join(process.cwd(), endpoint)) as Record<string, HexString>).result;
|
||||
|
||||
generateDefaultLookup(path.join(process.cwd(), input), metaHex);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Metadata } from '@polkadot/types/metadata/Metadata';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -85,7 +86,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Metadata } from '@polkadot/types/metadata/Metadata';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -48,7 +49,7 @@ function generateForMeta (meta: Metadata, dest: string, isStrict: boolean): void
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
|
||||
export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false): void {
|
||||
const { metadata } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(metadata, dest, isStrict);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Metadata } from '@polkadot/types/metadata/Metadata';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -77,7 +78,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { PortableType, SiLookupTypeId, SiPath, SiTypeParameter } from '@polkadot/types/interfaces';
|
||||
import type { PortableRegistry } from '@polkadot/types/metadata';
|
||||
import type { TypeDef } from '@polkadot/types/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
import path from 'path';
|
||||
@@ -213,7 +214,7 @@ function generateLookupTypes (registry: Registry, filtered: [PortableType, TypeD
|
||||
writeFile(path.join(destDir, 'index.ts'), () => generateLookupIndexTmpl({ headerType: 'defs' }), true);
|
||||
}
|
||||
|
||||
function generateLookup (destDir: string, entries: [string | undefined, string][]): void {
|
||||
function generateLookup (destDir: string, entries: [string | undefined, HexString][]): void {
|
||||
entries.reduce<string[]>((exclude, [subPath, staticMeta]): string[] => {
|
||||
const { lookup, registry } = initMeta(staticMeta).metadata.asLatest;
|
||||
const filtered = getFilteredTypes(lookup, exclude);
|
||||
@@ -230,7 +231,7 @@ function generateLookup (destDir: string, entries: [string | undefined, string][
|
||||
}
|
||||
|
||||
// Generate `packages/types/src/lookup/*s`, the registry of all lookup types
|
||||
export function generateDefaultLookup (destDir = 'packages/types/src/augment/lookup', staticData?: string): void {
|
||||
export function generateDefaultLookup (destDir = 'packages/types/src/augment/lookup', staticData?: HexString): void {
|
||||
generateLookup(
|
||||
destDir,
|
||||
staticData
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { StorageEntryMetadataLatest } from '@polkadot/types/interfaces';
|
||||
import type { Metadata, PortableRegistry } from '@polkadot/types/metadata';
|
||||
import type { Definitions, Registry } from '@polkadot/types/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -134,7 +135,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata, registry } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import type { Metadata } from '@polkadot/types/metadata/Metadata';
|
||||
import type { Definitions, Registry } from '@polkadot/types/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -119,7 +120,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata, registry } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/typegen authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtraTypes } from '../generate/types';
|
||||
|
||||
import { Metadata, TypeRegistry } from '@polkadot/types';
|
||||
@@ -13,7 +14,7 @@ interface Result {
|
||||
registry: TypeRegistry;
|
||||
}
|
||||
|
||||
export function initMeta (staticMeta = staticSubstrate, extraTypes: ExtraTypes = {}): Result {
|
||||
export function initMeta (staticMeta: HexString = staticSubstrate, extraTypes: ExtraTypes = {}): Result {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
registerDefinitions(registry, extraTypes);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import kusama from '@polkadot/types-support/metadata/static-kusama';
|
||||
import polkadot from '@polkadot/types-support/metadata/static-polkadot';
|
||||
import substrate from '@polkadot/types-support/metadata/static-substrate';
|
||||
@@ -8,7 +10,7 @@ import substrate from '@polkadot/types-support/metadata/static-substrate';
|
||||
import { TypeRegistry } from '../create';
|
||||
import { Metadata } from './Metadata';
|
||||
|
||||
const allData: Record<string, string> = {
|
||||
const allData: Record<string, HexString> = {
|
||||
kusama,
|
||||
polkadot,
|
||||
substrate
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Registry } from '../types';
|
||||
|
||||
import { isHex, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
@@ -12,42 +13,30 @@ const VERSION_IDX = 4;
|
||||
|
||||
// magic + lowest supported version
|
||||
const EMPTY_METADATA = new Uint8Array([0x6d, 0x65, 0x74, 0x61, 9]);
|
||||
const EMPTY_U8A = new Uint8Array();
|
||||
|
||||
function toU8a (value: Uint8Array | string = EMPTY_U8A): Uint8Array {
|
||||
if (isHex(value)) {
|
||||
return toU8a(u8aToU8a(value));
|
||||
} else if (isU8a(value)) {
|
||||
return value.length === 0
|
||||
function toU8a (value: Uint8Array | HexString): Uint8Array {
|
||||
return isHex(value)
|
||||
? toU8a(u8aToU8a(value))
|
||||
: value.length === 0
|
||||
? EMPTY_METADATA
|
||||
: value;
|
||||
}
|
||||
|
||||
throw new Error('Invalid type passed to Metadata constructor');
|
||||
}
|
||||
|
||||
function decodeMetadata (registry: Registry, _value?: Uint8Array | string | Map<string, unknown> | Record<string, unknown>): MetadataVersioned {
|
||||
if (isU8a(_value) || !_value || isHex(_value)) {
|
||||
const value = toU8a(_value);
|
||||
const version = value[VERSION_IDX];
|
||||
function decodeU8a (registry: Registry, value: Uint8Array): MetadataVersioned {
|
||||
try {
|
||||
return new MetadataVersioned(registry, value);
|
||||
} catch (error) {
|
||||
// This is an f-ing hack as a follow-up to another ugly hack
|
||||
// https://github.com/polkadot-js/api/commit/a9211690be6b68ad6c6dad7852f1665cadcfa5b2
|
||||
// when we fail on V9, try to re-parse it as v10... yes... HACK
|
||||
if (value[VERSION_IDX] === 9) {
|
||||
value[VERSION_IDX] = 10;
|
||||
|
||||
try {
|
||||
return new MetadataVersioned(registry, value);
|
||||
} catch (error) {
|
||||
// This is an f-ing hack as a follow-up to another ugly hack
|
||||
// https://github.com/polkadot-js/api/commit/a9211690be6b68ad6c6dad7852f1665cadcfa5b2
|
||||
// when we fail on V9, try to re-parse it as v10... yes... HACK
|
||||
if (version === 9) {
|
||||
value[VERSION_IDX] = 10;
|
||||
|
||||
return decodeMetadata(registry, value);
|
||||
}
|
||||
|
||||
throw error;
|
||||
return decodeU8a(registry, value);
|
||||
}
|
||||
}
|
||||
|
||||
return new MetadataVersioned(registry, _value);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,7 +45,12 @@ function decodeMetadata (registry: Registry, _value?: Uint8Array | string | Map<
|
||||
* The versioned runtime metadata as a decoded structure
|
||||
*/
|
||||
export class Metadata extends MetadataVersioned {
|
||||
constructor (registry: Registry, value?: Uint8Array | string | Map<string, unknown> | Record<string, unknown>) {
|
||||
super(registry, decodeMetadata(registry, value));
|
||||
constructor (registry: Registry, value?: Uint8Array | HexString | Map<string, unknown> | Record<string, unknown>) {
|
||||
super(
|
||||
registry,
|
||||
isU8a(value) || isHex(value)
|
||||
? decodeU8a(registry, toU8a(value))
|
||||
: new MetadataVersioned(registry, value)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { BlockNumber } from '../../../interfaces';
|
||||
import type { Constants } from '../types';
|
||||
|
||||
@@ -11,7 +12,7 @@ import { TypeRegistry } from '../../../create';
|
||||
import { Metadata } from '../../Metadata';
|
||||
import { decorateConstants } from '..';
|
||||
|
||||
function init (meta: string): [Constants, TypeRegistry] {
|
||||
function init (meta: HexString): [Constants, TypeRegistry] {
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, meta);
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
export interface Check {
|
||||
compare: Record<string, unknown>;
|
||||
data: string;
|
||||
data: HexString;
|
||||
fails?: string[];
|
||||
types?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user