Make chain properties available on registry (#1868)

* Make chain properties available on registry

* Use registry chainSS58 to format address

* CHANGELOG

* CHANGELOG typo

* Fix tests vis setChainProperties

* Cleanup tests via chain property set

* Remove global ss58 format set
This commit is contained in:
Jaco Greeff
2020-02-16 11:09:48 +01:00
committed by GitHub
parent 5c962cf093
commit 1e975c68ee
7 changed files with 60 additions and 15 deletions
+5 -1
View File
@@ -1,3 +1,7 @@
# 1.3.0-beta.x
- Expose chain properies on registry (and use for API type formatting)
# 1.2.1 Feb 16, 2020
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
@@ -11,7 +15,7 @@
- Applied the latest types for Polkadot parachains
- `registry.findMetaError` now can take in a `DispatchErrorModule` object for error lookups (from `asModule` in `DispatchError`)
- Metadata now correctly serializes to the original input data via `toHex()` & `toU8a()`
- Metadata dcocumentation generation rework, including the output of errors from metadata
- Metadata documentation generation rework, including the output of errors from metadata
- Update all examples and comments to use latest `system.account` queries (instead of `system.accountNonce` and `balances.freeBalance`/`balances.reservedBalance`)
- Cleanup `codec/Date` tests to make it run properly on all timezones
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
+4 -6
View File
@@ -6,12 +6,11 @@ import { SignedBlock } from '@polkadot/types/interfaces';
import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
import DecoratedMeta from '@polkadot/metadata/Decorated';
import { Metadata, u32 as U32 } from '@polkadot/types';
import { Metadata } from '@polkadot/types';
import { getChainTypes, getMetadataTypes } from '@polkadot/types/known';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/primitive/Extrinsic/Extrinsic';
import { logger } from '@polkadot/util';
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
import addressDefaults from '@polkadot/util-crypto/address/defaults';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import Decorate from './Decorate';
@@ -73,6 +72,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
this._extrinsicType = source.extrinsicVersion;
this._runtimeVersion = source.runtimeVersion;
this._genesisHash = source.genesisHash;
this.registry.setChainProperties(source.registry.getChainProperties());
const methods: string[] = [];
@@ -100,6 +100,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// based on the node spec & chain, inject specific type overrides
this.registerTypes(getChainTypes(chain, runtimeVersion, typesChain, typesSpec));
this.registry.setChainProperties(chainProps);
// filter the RPC methods (this does an rpc-methods call)
await this.filterRpc();
@@ -114,9 +115,6 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
this._genesisHash = genesisHash;
this._runtimeVersion = runtimeVersion;
// set the global ss58Format as detected by the chain
setSS58Format(chainProps.ss58Format.unwrapOr(new U32(this.registry, addressDefaults.prefix)).toNumber());
// get unique types & validate
metadata.getUniqTypes(false);
+34 -1
View File
@@ -3,7 +3,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DispatchErrorModule } from '../../interfaces/types';
import { ChainProperties, DispatchErrorModule } from '../../interfaces/types';
import { CallFunction, Codec, Constructor, InterfaceTypes, RegistryError, RegistryTypes, Registry, RegistryMetadata, TypeDef } from '../../types';
import extrinsicsFromMeta from '@polkadot/metadata/Decorated/extrinsics/fromMetadata';
@@ -77,6 +77,8 @@ function decorateExtrinsics (registry: Registry, metadata: RegistryMetadata, met
}
export class TypeRegistry implements Registry {
private _chainProperties?: ChainProperties;
private _classes: Map<string, Constructor> = new Map();
private _definitions: Map<string, string> = new Map();
@@ -105,6 +107,25 @@ export class TypeRegistry implements Registry {
);
}
public get chainDecimals (): number {
return this._chainProperties?.tokenDecimals.isSome
? this._chainProperties.tokenDecimals.unwrap().toNumber()
: 12;
}
public get chainSS58 (): number | undefined {
return this._chainProperties?.ss58Format.isSome
? this._chainProperties.ss58Format.unwrap().toNumber()
: undefined;
}
public get chainToken (): string {
return this._chainProperties?.tokenSymbol.isSome
? this._chainProperties.tokenSymbol.unwrap().toString()
: 'DEV';
}
// find a specific call
public findMetaCall (callIndex: Uint8Array): CallFunction {
const hexIndex = u8aToHex(callIndex);
const fn = this._metadataCalls[hexIndex];
@@ -114,6 +135,7 @@ export class TypeRegistry implements Registry {
return fn;
}
// finds an error
public findMetaError (errorIndex: Uint8Array | DispatchErrorModule): RegistryError {
const hexIndex = u8aToHex(
isU8a(errorIndex)
@@ -159,6 +181,10 @@ export class TypeRegistry implements Registry {
return Type as Constructor<T>;
}
public getChainProperties (): ChainProperties | undefined {
return this._chainProperties;
}
public getDefinition (name: string): string | undefined {
return this._definitions.get(name);
}
@@ -232,6 +258,13 @@ export class TypeRegistry implements Registry {
});
}
// sets the chain properties
public setChainProperties (properties?: ChainProperties): void {
if (properties) {
this._chainProperties = properties;
}
}
// sets the metadata
public setMetadata (metadata: RegistryMetadata): void {
decorateExtrinsics(this, metadata, this._metadataCalls);
@@ -2,8 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { setSS58Format } from '@polkadot/util-crypto';
import { createType, TypeRegistry } from '../../codec/create';
import Raw from '../../codec/Raw';
import jsonVec from '../../json/AccountIdVec.001.json';
@@ -84,7 +82,11 @@ describe('AccountId', (): void => {
describe('storage decoding', (): void => {
it('has the correct entries', (): void => {
setSS58Format(68);
registry.setChainProperties(
createType(registry, 'ChainProperties', {
ss58Format: 68
})
);
const data = createType(registry, 'StorageData', jsonVec.params.result.changes[0][1]);
const list = createType(registry, 'Vec<AccountId>', data).map((accountId): string => accountId.toString());
@@ -34,8 +34,8 @@ export default class AccountId extends U8aFixed {
super(registry, decodeAccountId(value), 256);
}
public static encode (value: Uint8Array): string {
return encodeAddress(value);
public static encode (value: Uint8Array, ss58Format?: number): string {
return encodeAddress(value, ss58Format);
}
/**
@@ -56,7 +56,7 @@ export default class AccountId extends U8aFixed {
* @description Returns the string representation of the value
*/
public toString (): string {
return AccountId.encode(this);
return AccountId.encode(this, this.registry.chainSS58);
}
/**
@@ -108,7 +108,7 @@ export default class AccountIndex extends U32 {
public toString (): string {
const length = AccountIndex.calcLength(this);
return encodeAddress(this.toU8a().subarray(0, length));
return encodeAddress(this.toU8a().subarray(0, length), this.registry.chainSS58);
}
/**
+8
View File
@@ -4,6 +4,7 @@
import { SignOptions } from '@polkadot/keyring/types';
import { FunctionMetadataLatest } from './interfaces/metadata';
import { ChainProperties } from './interfaces/rpc';
import { Address, Balance, Call, EcdsaSignature, Ed25519Signature, Index, Sr25519Signature } from './interfaces/runtime';
import BN from 'bn.js';
@@ -403,6 +404,10 @@ export interface RegistryMetadata {
}
export interface Registry {
readonly chainDecimals: number;
readonly chainSS58: number | undefined;
readonly chainToken: string;
findMetaCall (callIndex: Uint8Array): CallFunction;
findMetaError (errorIndex: Uint8Array): any;
// due to same circular imports where types don't really want to import from EventData,
@@ -410,6 +415,8 @@ export interface Registry {
findMetaEvent (eventIndex: Uint8Array): Constructor<any>;
get <T extends Codec = Codec> (name: string): Constructor<T> | undefined;
getChainProperties (): ChainProperties | undefined;
getDefinition (name: string): string | undefined;
getOrThrow <T extends Codec = Codec> (name: string, msg?: string): Constructor<T>;
getSignedExtensionExtra (): Record<string, InterfaceTypes>;
getSignedExtensionTypes (): Record<string, InterfaceTypes>;
@@ -419,5 +426,6 @@ export interface Registry {
register (type: Constructor | RegistryTypes): void;
register (name: string, type: Constructor): void;
register (arg1: string | Constructor | RegistryTypes, arg2?: Constructor): void;
setChainProperties (properties?: ChainProperties): void;
setMetadata (metadata: RegistryMetadata): void;
}