Pass registry to all codec types (#1592)
* Pass registry to all codec types
* Pass through registry inside API (where the rubber meets the road)
* Small additions
* Derive w/ registry
* Types are more-or-less covered
* Some test adjustments (guided by linting)
* Rid the world of some ../injector
* Additional cleanups, merge injector into registry
* Cleanup extrinsics (always passing registry)
* Remove injector imports (not all replaced)
* Typ spec cleanups
* Phase 1 - types seem lint-free
* rpc-{core,provider} lint free
* Start working through metadata
* Small metadata additions
* Some e2e tests (out-of-order)
* Down to a handful
* Fixup tests for packages/types/src/codec/*.spec.ts
* packages/types/src/codec passes all tests
* packages/types ok (Convert storage with registry fn)
* progress (sort out injection, dreaded find-before msg)
* Down to 1 lint issue...
* Linting done... along with on-demand import
* Exposed ordering
* Remove global injects
* Cleanup comments
* Add CHANGELOG & UPGRADING
* Apply suggestions from code review
Co-Authored-By: Amaury Martiny <amaury.martiny@protonmail.com>
* Update Metadata description
This commit is contained in:
co-authored by
Amaury Martiny
parent
099992627b
commit
011e24bd49
@@ -2,16 +2,19 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import incrementerAbi from '../test/contracts/incrementer.json';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import incrementerAbi from '../test/contracts/incrementer.json';
|
||||
import { Abi } from '.';
|
||||
|
||||
describe('Abi', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
describe('incrementer', (): void => {
|
||||
let abi: Abi;
|
||||
|
||||
beforeEach((): void => {
|
||||
abi = new Abi(incrementerAbi);
|
||||
abi = new Abi(registry, incrementerAbi);
|
||||
});
|
||||
|
||||
it('has the attached methods', (): void => {
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { AbiConstructors, AbiMessages, ContractABI, ContractABIPre, ContractABIFn, InterfaceAbi } from './types';
|
||||
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import ContractRegistry from './ContractRegistry';
|
||||
@@ -14,8 +16,8 @@ export default class ContractAbi extends ContractRegistry implements InterfaceAb
|
||||
|
||||
public readonly messages: AbiMessages;
|
||||
|
||||
constructor (abi: ContractABIPre) {
|
||||
super(abi);
|
||||
constructor (registry: Registry, abi: ContractABIPre) {
|
||||
super(registry, abi);
|
||||
[this.abi, this.constructors, this.messages] = this.decodeAbi(abi);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,28 +2,28 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { CodecArg, Constructor, TypeDef } from '@polkadot/types/types';
|
||||
import { CodecArg, Constructor, Registry, TypeDef } from '@polkadot/types/types';
|
||||
import { ContractABIArgBasePre, ContractABIContract, ContractABIContractPre, ContractABIEvent, ContractABIEventPre, ContractABIFn, ContractABIFnArg, ContractABIMessage, ContractABIMessageBase, ContractABIMessagePre, ContractABI, ContractABIMessageCommon, ContractABIPre, ContractABIRange, ContractABIRangePre, ContractABIStorage, ContractABIStorageLayout, ContractABIStorageLayoutPre, ContractABIStoragePre, ContractABIStorageStruct, ContractABIStorageStructPre, ContractABITypePre } from './types';
|
||||
import { Compact, u32, createClass, createType, encodeType } from '@polkadot/types';
|
||||
|
||||
import { Compact, u32, createClass, createType, encodeType } from '@polkadot/types';
|
||||
import { assert, hexToU8a, isNumber, isString, isNull, isObject, isUndefined, stringCamelCase, isHex, hexToNumber } from '@polkadot/util';
|
||||
|
||||
import MetaRegistry from './MetaRegistry';
|
||||
|
||||
// parse a selector, this can be a number (older) or of [<hex>, <hex>, ...]. However,
|
||||
// just catch everything (since this is now non-standard for u32 anyway)
|
||||
function parseSelector (fnname: string, input: ContractABIMessageCommon['selector']): u32 {
|
||||
function parseSelector (registry: Registry, fnname: string, input: ContractABIMessageCommon['selector']): u32 {
|
||||
if (isNumber(input)) {
|
||||
return createType('u32', input);
|
||||
return createType(registry, 'u32', input);
|
||||
} else if (isHex(input)) {
|
||||
return createType('u32', hexToU8a(input));
|
||||
return createType(registry, 'u32', hexToU8a(input));
|
||||
} else if (typeof input === 'string') {
|
||||
try {
|
||||
const array = JSON.parse(input);
|
||||
|
||||
assert(array.length === 4, `${fnname}: Invalid selector length`);
|
||||
|
||||
return createType('u32', Uint8Array.from(
|
||||
return createType(registry, 'u32', Uint8Array.from(
|
||||
// the as number[] is here to pacify TS, it doesn't quite know how to handle the cb
|
||||
(array as number[]).map((value: string | number): number =>
|
||||
isHex(value)
|
||||
@@ -39,8 +39,9 @@ function parseSelector (fnname: string, input: ContractABIMessageCommon['selecto
|
||||
throw new Error(`${fnname}: Unable to parse selector`);
|
||||
}
|
||||
|
||||
function createArgClass (args: ContractABIFnArg[], baseDef: Record<string, string>): Constructor {
|
||||
function createArgClass (registry: Registry, args: ContractABIFnArg[], baseDef: Record<string, string>): Constructor {
|
||||
return createClass(
|
||||
registry,
|
||||
JSON.stringify(
|
||||
args.reduce((base: Record<string, any>, { name, type }): Record<string, any> => {
|
||||
base[name] = type.displayName || encodeType(type);
|
||||
@@ -87,7 +88,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
assert(isNumber(name) && isString(this.stringAt(name)), `Expected name for ${fnname}`);
|
||||
assert(isNull(returnType) || (isNumber(returnType.ty) && isObject(this.typeDefAt(returnType.ty))), `Expected return_type for ${fnname}`);
|
||||
|
||||
parseSelector(fnname, selector);
|
||||
parseSelector(this.registry, fnname, selector);
|
||||
this.validateArgs(fnname, message.args);
|
||||
});
|
||||
}
|
||||
@@ -113,12 +114,13 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
type
|
||||
};
|
||||
});
|
||||
const Clazz = createArgClass(args, isUndefined(message.selector) ? {} : { __selector: 'u32' });
|
||||
const baseStruct: { [index: string]: any } = { __selector: isUndefined(message.selector) ? undefined : parseSelector(name, message.selector) };
|
||||
const Clazz = createArgClass(this.registry, args, isUndefined(message.selector) ? {} : { __selector: 'u32' });
|
||||
const baseStruct: { [index: string]: any } = { __selector: isUndefined(message.selector) ? undefined : parseSelector(this.registry, name, message.selector) };
|
||||
const encoder = (...params: CodecArg[]): Uint8Array => {
|
||||
assert(params.length === args.length, `Expected ${args.length} arguments to contract ${name}, found ${params.length}`);
|
||||
|
||||
const u8a = new Clazz(
|
||||
this.registry,
|
||||
args.reduce((mapped, { name }, index): Record<string, CodecArg> => {
|
||||
mapped[name] = params[index];
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import MetaRegistry from './MetaRegistry';
|
||||
|
||||
@@ -11,9 +12,11 @@ import erc20Abi from '../test/contracts/Erc20.json';
|
||||
import sharedVecAbi from '../test/contracts/SharedVecV2.json';
|
||||
|
||||
describe('MetaRegistry', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
describe('construction', (): void => {
|
||||
it('initializes from a contract ABI (ERC20)', (): void => {
|
||||
const metaRegistry = new MetaRegistry(erc20Abi);
|
||||
const metaRegistry = new MetaRegistry(registry, erc20Abi);
|
||||
fs.writeFile(path.join(__dirname, '../test/compare/erc20.test.json'), JSON.stringify(metaRegistry.typeDefs, null, 2), function (err): void {
|
||||
if (err) throw err;
|
||||
});
|
||||
@@ -22,7 +25,7 @@ describe('MetaRegistry', (): void => {
|
||||
});
|
||||
|
||||
it('initializes from a contract ABI (SharedVec)', (): void => {
|
||||
const metaRegistry = new MetaRegistry(sharedVecAbi);
|
||||
const metaRegistry = new MetaRegistry(registry, sharedVecAbi);
|
||||
fs.writeFile(path.join(__dirname, '../test/compare/shared-vec.test.json'), JSON.stringify(metaRegistry.typeDefs, null, 2), function (err): void {
|
||||
if (err) throw err;
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, MetaTypeDefEnum, MetaTypeDefEnumVariant, MetaTypeDefEnumVariantStruct, MetaTypeDefEnumVariantTupleStruct, MetaTypeDefEnumVariantUnit, MetaTypeDefStruct, MetaTypeDefStructField, MetaTypeDefTupleStruct, MetaTypeDefUnion, MetaTypeIdCustom, MetaTypeIdVec, MetaTypeIdVecFixed, MetaTypeInfo, StringIndex, TypeDef, TypeDefInfo, TypeIndex } from '@polkadot/types/types';
|
||||
import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, MetaTypeDefEnum, MetaTypeDefEnumVariant, MetaTypeDefEnumVariantStruct, MetaTypeDefEnumVariantTupleStruct, MetaTypeDefEnumVariantUnit, MetaTypeDefStruct, MetaTypeDefStructField, MetaTypeDefTupleStruct, MetaTypeDefUnion, MetaTypeIdCustom, MetaTypeIdVec, MetaTypeIdVecFixed, MetaTypeInfo, Registry, StringIndex, TypeDef, TypeDefInfo, TypeIndex } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
import { displayType, withTypeString } from '@polkadot/types';
|
||||
@@ -34,13 +34,16 @@ function detectedType ({ def, id }: MetaType): MetaTypeInfo {
|
||||
}
|
||||
|
||||
class MetadataRegistryLookup {
|
||||
public readonly registry: Registry;
|
||||
|
||||
protected _strings: string[] = [];
|
||||
|
||||
protected _types: MetaType[] = [];
|
||||
|
||||
public typeDefs: TypeDef[] = [];
|
||||
|
||||
constructor ({ registry: { strings, types } }: MetaRegistryJson) {
|
||||
constructor (registry: Registry, { registry: { strings, types } }: MetaRegistryJson) {
|
||||
this.registry = registry;
|
||||
this._strings = strings;
|
||||
this._types = types;
|
||||
}
|
||||
@@ -102,8 +105,8 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
|
||||
export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
constructor (json: MetaRegistryJson) {
|
||||
super(json);
|
||||
constructor (registry: Registry, json: MetaRegistryJson) {
|
||||
super(registry, json);
|
||||
|
||||
// Generate TypeDefs for each provided registry type
|
||||
this._types.forEach((_, index: number): void => this.setTypeDefAtIndex(index + 1));
|
||||
|
||||
@@ -41,7 +41,7 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
|
||||
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, codeHash: string | Hash) {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
this.codeHash = createType('Hash', codeHash);
|
||||
this.codeHash = createType(this.registry, 'Hash', codeHash);
|
||||
}
|
||||
|
||||
public deployContract (constructorIndex = 0, endowment: number | BN, maxGas: number | BN, ...params: any[]): BlueprintCreate<ApiType> {
|
||||
|
||||
@@ -44,7 +44,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
as === 'rpc'
|
||||
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> => {
|
||||
return this.rpcContractsCall(
|
||||
createType('ContractCallRequest', {
|
||||
createType(this.registry, 'ContractCallRequest', {
|
||||
origin: account,
|
||||
dest: this.address.toString(),
|
||||
value,
|
||||
@@ -54,7 +54,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
)
|
||||
.pipe(
|
||||
map((result: ContractExecResult): ContractCallOutcome =>
|
||||
this.createOutcome(result, createType('AccountId', account), def, params)
|
||||
this.createOutcome(result, createType(this.registry, 'AccountId', account), def, params)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -74,8 +74,8 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
const { data } = result.asSuccess;
|
||||
|
||||
output = message.returnType
|
||||
? formatData(data, message.returnType)
|
||||
: createType('Data', data);
|
||||
? formatData(this.registry, data, message.returnType)
|
||||
: createType(this.registry, 'Data', data);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -92,6 +92,6 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, address: string | AccountId | Address) {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
this.address = createType('Address', address);
|
||||
this.address = createType(this.registry, 'Address', address);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { ApiTypes, DecorateMethod, DecoratedRpc, SubmittableModuleExtrinsics } from '@polkadot/api/types';
|
||||
import { ApiObject, ContractABIMessage, ContractABIPre, ContractBase, ContractMessage } from '../types';
|
||||
import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert, stringCamelCase } from '@polkadot/util';
|
||||
import Abi from '../Abi';
|
||||
@@ -16,10 +17,13 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
|
||||
|
||||
public readonly decorateMethod: DecorateMethod<ApiType>;
|
||||
|
||||
public readonly registry: Registry;
|
||||
|
||||
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>) {
|
||||
this.abi = abi instanceof Abi
|
||||
? abi
|
||||
: new Abi(abi);
|
||||
: new Abi(api.registry, abi);
|
||||
this.registry = api.registry;
|
||||
this.api = api;
|
||||
this.decorateMethod = decorateMethod;
|
||||
}
|
||||
|
||||
@@ -2,20 +2,21 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Codec, TypeDefInfo, TypeDef } from '@polkadot/types/types';
|
||||
import { Codec, Registry, TypeDefInfo, TypeDef } from '@polkadot/types/types';
|
||||
|
||||
import { Data, Option, createClass } from '@polkadot/types';
|
||||
import { createTypeUnsafe } from '@polkadot/types/codec';
|
||||
|
||||
export function formatData (data: Data, { info, type }: TypeDef): Codec {
|
||||
export function formatData (registry: Registry, data: Data, { info, type }: TypeDef): Codec {
|
||||
const u8a = data.toU8a();
|
||||
|
||||
if (info === TypeDefInfo.Option) {
|
||||
return new Option(
|
||||
createClass(type),
|
||||
createTypeUnsafe(type, [u8a], true)
|
||||
registry,
|
||||
createClass(registry, type),
|
||||
createTypeUnsafe(registry, type, [u8a], true)
|
||||
);
|
||||
}
|
||||
|
||||
return createTypeUnsafe(type, [u8a], true);
|
||||
return createTypeUnsafe(registry, type, [u8a], true);
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@ import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { createType } from '@polkadot/types';
|
||||
import { isU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -23,14 +23,14 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
|
||||
: decodeAddress((address || '').toString());
|
||||
|
||||
if (decoded.length === 32) {
|
||||
const accountId = createType('AccountId', decoded);
|
||||
const accountId = createType(api.registry, 'AccountId', decoded);
|
||||
|
||||
return api.derive.accounts.idToIndex(accountId).pipe(
|
||||
map((accountIndex): AccountIdAndIndex => [accountId, accountIndex] as AccountIdAndIndex)
|
||||
);
|
||||
}
|
||||
|
||||
const accountIndex = createType('AccountIndex', decoded);
|
||||
const accountIndex = createType(api.registry, 'AccountIndex', decoded);
|
||||
|
||||
return api.derive.accounts.indexToId(accountIndex).pipe(
|
||||
map((accountId): AccountIdAndIndex => [accountId, accountIndex] as AccountIdAndIndex)
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Observable } from 'rxjs';
|
||||
import { map, startWith } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/primitive/Generic/AccountIndex';
|
||||
import { createType, ClassOf, Vec } from '@polkadot/types';
|
||||
import { ClassOf, Vec, createType } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -29,9 +29,9 @@ export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | s
|
||||
const querySection = api.query.indices || api.query.balances;
|
||||
|
||||
return memo((_accountIndex: AccountIndex | string): Observable<AccountId | undefined> => {
|
||||
const accountIndex = _accountIndex instanceof ClassOf('AccountIndex')
|
||||
const accountIndex = _accountIndex instanceof ClassOf(api.registry, 'AccountIndex')
|
||||
? _accountIndex
|
||||
: createType('AccountIndex', _accountIndex);
|
||||
: createType(api.registry, 'AccountIndex', _accountIndex);
|
||||
|
||||
return querySection.enumSet<Vec<AccountId>>(accountIndex.div(ENUMSET_SIZE)).pipe(
|
||||
startWith([]),
|
||||
|
||||
@@ -9,7 +9,7 @@ import { AccountIndexes } from '../types';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/primitive/Generic/AccountIndex';
|
||||
import { createType, Vec } from '@polkadot/types';
|
||||
import { Vec, createType } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -47,7 +47,7 @@ export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes>
|
||||
// 64 (0..63 in first) is [1][0] (the first index value in set 2)
|
||||
const index = (outerIndex * enumsetSize) + innerIndex;
|
||||
|
||||
result[accountId.toString()] = createType('AccountIndex', index);
|
||||
result[accountId.toString()] = createType(api.registry, 'AccountIndex', index);
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
@@ -17,8 +17,8 @@ import { memo } from '../util';
|
||||
type ResultBalance = [Balance, Balance, BalanceLock[], Option<VestingSchedule>];
|
||||
type Result = [AccountId, BlockNumber, ResultBalance, Index];
|
||||
|
||||
function calcBalances ([accountId, bestNumber, [freeBalance, reservedBalance, locks, vesting], accountNonce]: Result): DerivedBalances {
|
||||
let lockedBalance = createType('Balance');
|
||||
function calcBalances (api: ApiInterfaceRx, [accountId, bestNumber, [freeBalance, reservedBalance, locks, vesting], accountNonce]: Result): DerivedBalances {
|
||||
let lockedBalance = createType(api.registry, 'Balance');
|
||||
let lockedBreakdown: BalanceLock[] = [];
|
||||
|
||||
if (Array.isArray(locks)) {
|
||||
@@ -27,15 +27,15 @@ function calcBalances ([accountId, bestNumber, [freeBalance, reservedBalance, lo
|
||||
|
||||
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
|
||||
if (lockedBreakdown.length) {
|
||||
lockedBalance = createType('Balance', bnMax(...lockedBreakdown.map(({ amount }): Balance => amount)));
|
||||
lockedBalance = createType(api.registry, 'Balance', bnMax(...lockedBreakdown.map(({ amount }): Balance => amount)));
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the vesting balances,
|
||||
// - offset = balance locked at genesis,
|
||||
// - perBlock is the unlock amount
|
||||
const { offset: vestingTotal, perBlock } = vesting.unwrapOr(createType('VestingSchedule'));
|
||||
const vestedBalance = createType('Balance', perBlock.mul(bestNumber));
|
||||
const { offset: vestingTotal, perBlock } = vesting.unwrapOr(createType(api.registry, 'VestingSchedule'));
|
||||
const vestedBalance = createType(api.registry, 'Balance', perBlock.mul(bestNumber));
|
||||
const isVesting = vestedBalance.lt(vestingTotal);
|
||||
|
||||
// The available balance & vested has an interplay here
|
||||
@@ -46,7 +46,7 @@ function calcBalances ([accountId, bestNumber, [freeBalance, reservedBalance, lo
|
||||
// i.e. (balance >= 200 && balance >= 300) == (balance >= 300)
|
||||
// ""
|
||||
const floating = freeBalance.sub(lockedBalance);
|
||||
const availableBalance = createType('Balance', bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance : floating));
|
||||
const availableBalance = createType(api.registry, 'Balance', bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance : floating));
|
||||
|
||||
return {
|
||||
accountId,
|
||||
@@ -59,7 +59,7 @@ function calcBalances ([accountId, bestNumber, [freeBalance, reservedBalance, lo
|
||||
reservedBalance,
|
||||
vestedBalance,
|
||||
vestingTotal,
|
||||
votingBalance: createType('Balance', freeBalance.add(reservedBalance))
|
||||
votingBalance: createType(api.registry, 'Balance', freeBalance.add(reservedBalance))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -103,9 +103,9 @@ export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId |
|
||||
// : api.query.system.accountNonce<Index>(accountId)
|
||||
api.query.system.accountNonce<Index>(accountId)
|
||||
])
|
||||
: of([createType('AccountId'), createType('BlockNumber'), [createType('Balance'), createType('Balance'), createType('Vec<BalanceLock>'), createType('Option<VestingSchedule>', null)], createType('Index')])
|
||||
: of([createType(api.registry, 'AccountId'), createType(api.registry, 'BlockNumber'), [createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Vec<BalanceLock>'), createType(api.registry, 'Option<VestingSchedule>', null)], createType(api.registry, 'Index')])
|
||||
)
|
||||
),
|
||||
map(calcBalances)
|
||||
map((result): DerivedBalances => calcBalances(api, result))
|
||||
));
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export function bestNumberLag (api: ApiInterfaceRx): () => Observable<BlockNumbe
|
||||
api.derive.chain.bestNumberFinalized()
|
||||
]).pipe(
|
||||
map(([bestNumber, bestNumberFinalized]): BlockNumber =>
|
||||
createType('BlockNumber', bestNumber.sub(bestNumberFinalized))
|
||||
createType(api.registry, 'BlockNumber', bestNumber.sub(bestNumberFinalized))
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) =>
|
||||
: of([])
|
||||
]).pipe(
|
||||
map(([header, validators]): HeaderExtended =>
|
||||
new HeaderExtended(header, validators)
|
||||
new HeaderExtended(api.registry, header, validators)
|
||||
),
|
||||
catchError((): Observable<undefined> =>
|
||||
// where rpc.chain.getHeader throws, we will land here - it can happen that
|
||||
|
||||
@@ -30,7 +30,7 @@ export function subscribeNewHeads (api: ApiInterfaceRx): () => Observable<Header
|
||||
api.derive.staking.validators()
|
||||
]).pipe(
|
||||
map(([header, { validators }]): HeaderExtended =>
|
||||
new HeaderExtended(header, validators)
|
||||
new HeaderExtended(api.registry, header, validators)
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -14,16 +14,17 @@ import { isNull } from '@polkadot/util';
|
||||
import { ReferendumInfoExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
export function constructInfo (index: BN | number, optionInfo?: Option<ReferendumInfo>): Option<ReferendumInfoExtended> {
|
||||
export function constructInfo (api: ApiInterfaceRx, index: BN | number, optionInfo?: Option<ReferendumInfo>): Option<ReferendumInfoExtended> {
|
||||
const info = optionInfo
|
||||
? optionInfo.unwrapOr(null)
|
||||
: null;
|
||||
|
||||
return new Option<ReferendumInfoExtended>(
|
||||
api.registry,
|
||||
ReferendumInfoExtended,
|
||||
isNull(info)
|
||||
? null
|
||||
: new ReferendumInfoExtended(info, index)
|
||||
: new ReferendumInfoExtended(api.registry, info, index)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,7 +32,7 @@ export function referendumInfo (api: ApiInterfaceRx): (index: BN | number) => Ob
|
||||
return memo((index: BN | number): Observable<Option<ReferendumInfoExtended>> =>
|
||||
api.query.democracy.referendumInfoOf<Option<ReferendumInfo>>(index).pipe(
|
||||
map((optionInfo): Option<ReferendumInfoExtended> =>
|
||||
constructInfo(index, optionInfo)
|
||||
constructInfo(api, index, optionInfo)
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export function referendumInfos (api: ApiInterfaceRx): (ids?: (BN | number)[]) =
|
||||
).pipe(
|
||||
map((infos): Option<ReferendumInfoExtended>[] =>
|
||||
ids.map((id, index): Option<ReferendumInfoExtended> =>
|
||||
constructInfo(id, infos[index])
|
||||
constructInfo(api, id, infos[index])
|
||||
)
|
||||
)
|
||||
));
|
||||
|
||||
@@ -26,8 +26,8 @@ export function referendumVotesFor (api: ApiInterfaceRx): (referendumId: BN | nu
|
||||
map(([votersFor, votes, balances]): DerivedReferendumVote[] =>
|
||||
votersFor.map((accountId, index): DerivedReferendumVote => ({
|
||||
accountId,
|
||||
balance: balances[index].votingBalance || createType('Balance'),
|
||||
vote: votes[index] || createType('Vote')
|
||||
balance: balances[index].votingBalance || createType(api.registry, 'Balance'),
|
||||
vote: votes[index] || createType(api.registry, 'Vote')
|
||||
} as unknown as DerivedReferendumVote))
|
||||
)
|
||||
));
|
||||
|
||||
@@ -16,13 +16,13 @@ import { memo } from '../util';
|
||||
type ResultElectionsInner = [u32, u32, Vec<ITuple<[AccountId, BlockNumber]>>, SetIndex, BlockNumber, VoteIndex, SetIndex];
|
||||
type ResultElections = [Vec<AccountId>, ResultElectionsInner];
|
||||
|
||||
function deriveElections ([candidates, [candidateCount, desiredSeats, members, nextVoterSet, termDuration, voteCount, voterCount]]: ResultElections): DerivedElectionsInfo {
|
||||
function deriveElections (api: ApiInterfaceRx, [candidates, [candidateCount, desiredSeats, members, nextVoterSet, termDuration, voteCount, voterCount]]: ResultElections): DerivedElectionsInfo {
|
||||
return {
|
||||
candidates,
|
||||
candidateCount,
|
||||
desiredSeats,
|
||||
nextVoterSet,
|
||||
members: members.map(([accountId]): [AccountId, Balance] => [accountId, createType('Balance')]),
|
||||
members: members.map(([accountId]): [AccountId, Balance] => [accountId, createType(api.registry, 'Balance')]),
|
||||
runnersUp: [],
|
||||
termDuration,
|
||||
voteCount,
|
||||
@@ -43,13 +43,13 @@ function queryElections (api: ApiInterfaceRx): Observable<DerivedElectionsInfo>
|
||||
api.query.elections.voteCount,
|
||||
api.query.elections.voterCount
|
||||
])
|
||||
]).pipe(map(deriveElections));
|
||||
]).pipe(map((result): DerivedElectionsInfo => deriveElections(api, result)));
|
||||
}
|
||||
|
||||
function derivePhragmen (candidates: AccountId[], members: [AccountId, Balance][], runnersUp: [AccountId, Balance][], candidacyBond: Balance, desiredSeats: u32, termDuration: BlockNumber, votingBond: Balance): DerivedElectionsInfo {
|
||||
function derivePhragmen (api: ApiInterfaceRx, candidates: AccountId[], members: [AccountId, Balance][], runnersUp: [AccountId, Balance][], candidacyBond: Balance, desiredSeats: u32, termDuration: BlockNumber, votingBond: Balance): DerivedElectionsInfo {
|
||||
return {
|
||||
candidates,
|
||||
candidateCount: createType('u32', candidates.length),
|
||||
candidateCount: createType(api.registry, 'u32', candidates.length),
|
||||
candidacyBond,
|
||||
desiredSeats,
|
||||
members,
|
||||
@@ -69,6 +69,7 @@ function queryPhragmen (api: ApiInterfaceRx): Observable<DerivedElectionsInfo> {
|
||||
api.query.electionsPhragmen.runnersUp<Vec<ITuple<[AccountId, Balance]>>>()
|
||||
]).pipe(
|
||||
map(([candidates, members, runnersUp]): DerivedElectionsInfo => derivePhragmen(
|
||||
api,
|
||||
candidates,
|
||||
members,
|
||||
runnersUp,
|
||||
|
||||
@@ -29,7 +29,7 @@ function queryElections (api: ApiInterfaceRx): Observable<DerivedVoterPositions>
|
||||
result[accountId.toString()] = {
|
||||
globalIndex: (api.consts.elections.voterSetSize as u32).muln(setIndex).addn(index),
|
||||
index: new BN(index),
|
||||
setIndex: createType('SetIndex', setIndex)
|
||||
setIndex: createType(api.registry, 'SetIndex', setIndex)
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -16,10 +16,11 @@ function queryElections (api: ApiInterfaceRx): Observable<AccountId[]> {
|
||||
return api.derive.elections.voterPositions().pipe(
|
||||
map((voterPositions: DerivedVoterPositions): Vec<AccountId> =>
|
||||
createType(
|
||||
api.registry,
|
||||
'Vec<AccountId>',
|
||||
Object.entries(voterPositions)
|
||||
.sort((a, b): number => a[1].globalIndex.cmp(b[1].globalIndex))
|
||||
.map(([accountId]): AccountId => createType('AccountId', accountId))
|
||||
.map(([accountId]): AccountId => createType(api.registry, 'AccountId', accountId))
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { Observable, from } from 'rxjs';
|
||||
import ApiRx from '@polkadot/api/rx/Api';
|
||||
import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { ExactDerive } from '.';
|
||||
|
||||
@@ -26,8 +27,10 @@ const testFunction = (api: ApiRx): any => {
|
||||
};
|
||||
|
||||
describe('derive', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
describe('builtin', (): void => {
|
||||
const api = new ApiRx({ provider: new MockProvider() });
|
||||
const api = new ApiRx({ provider: new MockProvider(registry), registry });
|
||||
|
||||
beforeAll((done): void => {
|
||||
api.isReady.subscribe((): void => done());
|
||||
@@ -77,7 +80,8 @@ describe('derive', (): void => {
|
||||
test: (): any => (): Observable<any> => from([1, 2, 3])
|
||||
}
|
||||
},
|
||||
provider: new MockProvider()
|
||||
provider: new MockProvider(registry),
|
||||
registry
|
||||
});
|
||||
|
||||
beforeAll((done): void => {
|
||||
|
||||
@@ -22,7 +22,7 @@ export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionInd
|
||||
api.query.staking.currentEra,
|
||||
api.query.staking.validatorCount
|
||||
])
|
||||
: of([createType('SessionIndex', 1), createType('EraIndex', 1), new U32()])
|
||||
: of([createType(api.registry, 'SessionIndex', 1), createType(api.registry, 'EraIndex', 1), createType(api.registry, 'u32')])
|
||||
).pipe(
|
||||
map(([currentIndex, currentEra, validatorCount]): DeriveSessionIndexes => ({
|
||||
currentIndex, currentEra, validatorCount
|
||||
|
||||
@@ -20,8 +20,8 @@ type ResultType = [boolean, u64, SessionIndex];
|
||||
type Result = [ResultType, DeriveSessionIndexes, ResultSlots];
|
||||
|
||||
// internal helper to just split the logic - take all inputs, do the calculations and combine
|
||||
function createDerivedV1 ([bestNumber, { currentIndex, validatorCount }, [_lastLengthChange, sessionLength, lastEraLengthChange, sessionsPerEra]]: ResultV1): DerivedSessionInfo {
|
||||
const lastLengthChange = _lastLengthChange?.unwrapOr(null) || createType('BlockNumber');
|
||||
function createDerivedV1 (api: ApiInterfaceRx, [bestNumber, { currentIndex, validatorCount }, [_lastLengthChange, sessionLength, lastEraLengthChange, sessionsPerEra]]: ResultV1): DerivedSessionInfo {
|
||||
const lastLengthChange = _lastLengthChange?.unwrapOr(null) || createType(api.registry, 'BlockNumber');
|
||||
const sessionProgress = bestNumber
|
||||
.sub(lastLengthChange)
|
||||
.add(sessionLength)
|
||||
@@ -34,21 +34,21 @@ function createDerivedV1 ([bestNumber, { currentIndex, validatorCount }, [_lastL
|
||||
.add(sessionProgress);
|
||||
|
||||
return {
|
||||
currentEra: createType('EraIndex', currentEra),
|
||||
currentEra: createType(api.registry, 'EraIndex', currentEra),
|
||||
currentIndex,
|
||||
eraLength: createType('BlockNumber', sessionLength.mul(sessionsPerEra)),
|
||||
eraProgress: createType('BlockNumber', eraProgress),
|
||||
eraLength: createType(api.registry, 'BlockNumber', sessionLength.mul(sessionsPerEra)),
|
||||
eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
|
||||
isEpoch: false,
|
||||
lastEraLengthChange,
|
||||
lastLengthChange,
|
||||
sessionLength,
|
||||
sessionsPerEra,
|
||||
sessionProgress: createType('BlockNumber', sessionProgress),
|
||||
sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
|
||||
validatorCount
|
||||
};
|
||||
}
|
||||
|
||||
function createDerivedLatest ([[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
|
||||
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
|
||||
const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
|
||||
const sessionProgress = currentSlot.sub(epochStartSlot);
|
||||
const eraProgress = currentIndex.sub(currentEraStartSessionIndex).mul(epochDuration).add(sessionProgress);
|
||||
@@ -56,14 +56,14 @@ function createDerivedLatest ([[hasBabe, epochDuration, sessionsPerEra], { curre
|
||||
return {
|
||||
currentEra,
|
||||
currentIndex,
|
||||
eraLength: createType('BlockNumber', sessionsPerEra.mul(epochDuration)),
|
||||
eraProgress: createType('BlockNumber', eraProgress),
|
||||
eraLength: createType(api.registry, 'BlockNumber', sessionsPerEra.mul(epochDuration)),
|
||||
eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
|
||||
isEpoch: hasBabe,
|
||||
lastEraLengthChange: createType('BlockNumber'),
|
||||
lastLengthChange: createType('BlockNumber', epochStartSlot),
|
||||
lastEraLengthChange: createType(api.registry, 'BlockNumber'),
|
||||
lastLengthChange: createType(api.registry, 'BlockNumber', epochStartSlot),
|
||||
sessionLength: epochDuration,
|
||||
sessionsPerEra,
|
||||
sessionProgress: createType('BlockNumber', sessionProgress),
|
||||
sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
|
||||
validatorCount
|
||||
};
|
||||
}
|
||||
@@ -79,17 +79,17 @@ function infoV1 (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
|
||||
api.query.staking.sessionsPerEra
|
||||
])
|
||||
]).pipe(
|
||||
map(createDerivedV1)
|
||||
map((result): DerivedSessionInfo => createDerivedV1(api, result))
|
||||
);
|
||||
}
|
||||
|
||||
function infoLatestAura (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
|
||||
return api.derive.session.indexes().pipe(
|
||||
map((indexes): DerivedSessionInfo =>
|
||||
createDerivedLatest([
|
||||
[false, createType('u64', 1), api.consts.staking.sessionsPerEra],
|
||||
createDerivedLatest(api, [
|
||||
[false, createType(api.registry, 'u64', 1), api.consts.staking.sessionsPerEra],
|
||||
indexes,
|
||||
[createType('u64', 1), createType('u64', 1), createType('u64', 1), createType('SessionIndex', 1)]
|
||||
[createType(api.registry, 'u64', 1), createType(api.registry, 'u64', 1), createType(api.registry, 'u64', 1), createType(api.registry, 'SessionIndex', 1)]
|
||||
])
|
||||
)
|
||||
);
|
||||
@@ -106,7 +106,7 @@ function infoLatestBabe (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
|
||||
])
|
||||
]).pipe(
|
||||
map(([indexes, slots]: [DeriveSessionIndexes, ResultSlots]): DerivedSessionInfo =>
|
||||
createDerivedLatest([
|
||||
createDerivedLatest(api, [
|
||||
[true, api.consts.babe.epochDuration, api.consts.staking.sessionsPerEra],
|
||||
indexes,
|
||||
slots
|
||||
|
||||
@@ -46,11 +46,11 @@ function groupByEra (list: UnlockChunk[]): Record<string, BN> {
|
||||
}
|
||||
|
||||
// calculate the remaining blocks in a specific unlock era
|
||||
function remainingBlocks (era: BN, sessionInfo: DerivedSessionInfo): BlockNumber {
|
||||
function remainingBlocks (api: ApiInterfaceRx, era: BN, sessionInfo: DerivedSessionInfo): BlockNumber {
|
||||
const remaining = era.sub(sessionInfo.currentEra);
|
||||
|
||||
// on the Rust side the current-era >= era-for-unlock (removal done on >)
|
||||
return createType('BlockNumber', remaining.gtn(0)
|
||||
return createType(api.registry, 'BlockNumber', remaining.gtn(0)
|
||||
? remaining
|
||||
.subn(1)
|
||||
.mul(sessionInfo.eraLength)
|
||||
@@ -59,13 +59,13 @@ function remainingBlocks (era: BN, sessionInfo: DerivedSessionInfo): BlockNumber
|
||||
);
|
||||
}
|
||||
|
||||
function calculateUnlocking (stakingLedger: StakingLedger | undefined, sessionInfo: DerivedSessionInfo): DerivedUnlocking[] | undefined {
|
||||
function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DerivedSessionInfo): DerivedUnlocking[] | undefined {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const unlockingChunks = stakingLedger.unlocking.filter(({ era }): boolean =>
|
||||
remainingBlocks(era.unwrap(), sessionInfo).gtn(0)
|
||||
remainingBlocks(api, era.unwrap(), sessionInfo).gtn(0)
|
||||
);
|
||||
|
||||
if (!unlockingChunks.length) {
|
||||
@@ -75,20 +75,20 @@ function calculateUnlocking (stakingLedger: StakingLedger | undefined, sessionIn
|
||||
// group the unlock chunks that have the same era and sum their values
|
||||
const groupedResult = groupByEra(unlockingChunks);
|
||||
const results = Object.entries(groupedResult).map(([eraString, value]): DerivedUnlocking => ({
|
||||
value: createType('Balance', value),
|
||||
remainingBlocks: remainingBlocks(new BN(eraString), sessionInfo)
|
||||
value: createType(api.registry, 'Balance', value),
|
||||
remainingBlocks: remainingBlocks(api, new BN(eraString), sessionInfo)
|
||||
}));
|
||||
|
||||
return results.length ? results : undefined;
|
||||
}
|
||||
|
||||
function redeemableSum (stakingLedger: StakingLedger | undefined, sessionInfo: DerivedSessionInfo): Balance {
|
||||
function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DerivedSessionInfo): Balance {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return createType('Balance');
|
||||
return createType(api.registry, 'Balance');
|
||||
}
|
||||
|
||||
return createType('Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
|
||||
return remainingBlocks(era.unwrap(), sessionInfo).eqn(0)
|
||||
return createType(api.registry, 'Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
|
||||
return remainingBlocks(api, era.unwrap(), sessionInfo).eqn(0)
|
||||
? total.add(value.unwrap())
|
||||
: total;
|
||||
}, new BN(0)));
|
||||
@@ -119,22 +119,24 @@ function unwrapSessionIds (stashId: AccountId, queuedKeys: Option<AccountId> | [
|
||||
};
|
||||
}
|
||||
|
||||
function parseResult ({ accountId, controllerId, stashId, sessionInfo, recentlyOffline = {}, nextKeyFor = createType('Option<AccountId>', null), queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys = createType('Option<Keys>', null) }: ParseInput): DerivedStaking {
|
||||
function parseResult (api: ApiInterfaceRx, { accountId, controllerId, stashId, sessionInfo, recentlyOffline = {}, nextKeyFor, queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys }: ParseInput): DerivedStaking {
|
||||
const _stakingLedger = stakingLedger.unwrapOr(undefined);
|
||||
const _nextKeyFor = nextKeyFor || createType(api.registry, 'Option<AccountId>', null);
|
||||
const _nextKeys = nextKeys || createType(api.registry, 'Option<Keys>', null);
|
||||
|
||||
return {
|
||||
accountId,
|
||||
controllerId,
|
||||
nominators,
|
||||
offline: recentlyOffline[stashId.toString()],
|
||||
redeemable: redeemableSum(_stakingLedger, sessionInfo),
|
||||
redeemable: redeemableSum(api, _stakingLedger, sessionInfo),
|
||||
rewardDestination,
|
||||
stakers,
|
||||
stakingLedger: _stakingLedger,
|
||||
stashId,
|
||||
unlocking: calculateUnlocking(_stakingLedger, sessionInfo),
|
||||
unlocking: calculateUnlocking(api, _stakingLedger, sessionInfo),
|
||||
validatorPrefs,
|
||||
...unwrapSessionIds(stashId, queuedKeys || nextKeyFor, nextKeys)
|
||||
...unwrapSessionIds(stashId, queuedKeys || _nextKeyFor, _nextKeys)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -153,7 +155,7 @@ function retrieveInfoV1 (api: ApiInterfaceRx, accountId: AccountId, stashId: Acc
|
||||
[api.query.staking.validators, stashId]
|
||||
]) as Observable<MultiResultV1>
|
||||
]).pipe(map(([sessionInfo, recentlyOffline, [nextKeyFor, stakingLedger, [nominators], rewardDestination, stakers, [validatorPrefs]]]: [DerivedSessionInfo, DerivedRecentlyOffline, MultiResultV1]): DerivedStaking =>
|
||||
parseResult({
|
||||
parseResult(api, {
|
||||
accountId, controllerId, stashId, sessionInfo, recentlyOffline, nextKeyFor, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs
|
||||
})
|
||||
));
|
||||
@@ -182,7 +184,7 @@ function retrieveInfoV2 (api: ApiInterfaceRx, accountId: AccountId, stashId: Acc
|
||||
: []
|
||||
: (_nominators as [Vec<AccountId>])[0];
|
||||
|
||||
return parseResult({
|
||||
return parseResult(api, {
|
||||
accountId, controllerId, stashId, sessionInfo, queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys
|
||||
});
|
||||
}));
|
||||
@@ -221,5 +223,5 @@ export function info (api: ApiInterfaceRx): (_accountId: Uint8Array | string) =>
|
||||
: retrieveV1;
|
||||
|
||||
return memo((accountId: Uint8Array | string): Observable<DerivedStaking> =>
|
||||
query(api, createType('AccountId', accountId)));
|
||||
query(api, createType(api.registry, 'AccountId', accountId)));
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export function overview (api: ApiInterfaceRx): () => Observable<DerivedStakingO
|
||||
// this will change on a per block basis, keep it innermost (and it needs eraIndex)
|
||||
api.query.staking?.currentEraPointsEarned
|
||||
? api.query.staking.currentEraPointsEarned<EraPoints>(currentEra)
|
||||
: of(createType('EraPoints'))
|
||||
: of(createType(api.registry, 'EraPoints'))
|
||||
])
|
||||
),
|
||||
map(([{ currentElected, currentEra, currentIndex, validators, validatorCount }, eraPoints]): DerivedStakingOverview => ({
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Header } from '@polkadot/types/interfaces';
|
||||
import { AnyJsonObject, Constructor } from '@polkadot/types/types';
|
||||
import { AnyJsonObject, Constructor, Registry } from '@polkadot/types/types';
|
||||
|
||||
import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
|
||||
import { Struct } from '@polkadot/types';
|
||||
@@ -19,8 +19,8 @@ const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header as an
|
||||
export default class HeaderExtended extends _Header {
|
||||
private _author?: AccountId;
|
||||
|
||||
constructor (header?: Header, sessionValidators?: AccountId[]) {
|
||||
super(header);
|
||||
constructor (registry: Registry, header?: Header, sessionValidators?: AccountId[]) {
|
||||
super(registry, header);
|
||||
|
||||
this._author = this.extractAuthor(sessionValidators);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ReferendumIndex, ReferendumInfo } from '@polkadot/types/interfaces/democracy';
|
||||
import { AnyJsonObject, Constructor } from '@polkadot/types/types';
|
||||
import { AnyJsonObject, Constructor, Registry } from '@polkadot/types/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import democracyTypes from '@polkadot/types/interfaces/democracy/definitions';
|
||||
@@ -20,12 +20,12 @@ const _ReferendumInfo: Constructor<ReferendumInfo> = Struct.with(democracyTypes.
|
||||
export default class ReferendumInfoExtended extends _ReferendumInfo {
|
||||
private _index: ReferendumIndex;
|
||||
|
||||
constructor (value: ReferendumInfo | ReferendumInfoExtended, index?: BN | number) {
|
||||
super(value);
|
||||
constructor (registry: Registry, value: ReferendumInfo | ReferendumInfoExtended, index?: BN | number) {
|
||||
super(registry, value);
|
||||
|
||||
this._index = value instanceof ReferendumInfoExtended
|
||||
? value.index
|
||||
: createType('ReferendumIndex', index);
|
||||
: createType(registry, 'ReferendumIndex', index);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
|
||||
import { ApprovalFlag } from '@polkadot/types/interfaces';
|
||||
|
||||
import { createType } from '@polkadot/types';
|
||||
import { createType, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { approvalFlagsToBools } from './approvalFlagsToBools';
|
||||
|
||||
describe('approvalFlagsToBools', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('translates and empty array to empty', (): void => {
|
||||
expect(
|
||||
approvalFlagsToBools([] as ApprovalFlag[])
|
||||
@@ -18,7 +20,7 @@ describe('approvalFlagsToBools', (): void => {
|
||||
it('translates a single input', (): void => {
|
||||
expect(
|
||||
approvalFlagsToBools([
|
||||
createType('ApprovalFlag', 0b1010)
|
||||
createType(registry, 'ApprovalFlag', 0b1010)
|
||||
])
|
||||
).toEqual([false, true, false, true]);
|
||||
});
|
||||
@@ -26,8 +28,8 @@ describe('approvalFlagsToBools', (): void => {
|
||||
it('translates multiple inputs', (): void => {
|
||||
expect(
|
||||
approvalFlagsToBools([
|
||||
createType('ApprovalFlag', 0b0000),
|
||||
createType('ApprovalFlag', 0b1100)
|
||||
createType(registry, 'ApprovalFlag', 0b0000),
|
||||
createType(registry, 'ApprovalFlag', 0b1100)
|
||||
])
|
||||
).toEqual([false, false, false, true, true]);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { Constants, Storage } from '@polkadot/metadata/Decorated/types';
|
||||
import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
|
||||
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ModulesWithCalls } from '@polkadot/types/types';
|
||||
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ModulesWithCalls, Registry } from '@polkadot/types/types';
|
||||
import { SubmittableExtrinsic } from '../submittable/types';
|
||||
import {
|
||||
ApiInterfaceRx, ApiOptions, ApiTypes,
|
||||
@@ -20,7 +20,7 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
|
||||
import RpcCore from '@polkadot/rpc-core';
|
||||
import { WsProvider } from '@polkadot/rpc-provider';
|
||||
import { Metadata, Null, u64 } from '@polkadot/types';
|
||||
import { Metadata, Null, u64, TypeRegistry } from '@polkadot/types';
|
||||
import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage';
|
||||
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/primitive/Extrinsic/constants';
|
||||
import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
|
||||
@@ -39,6 +39,8 @@ interface MetaDecoration {
|
||||
}
|
||||
|
||||
export default abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
public readonly registry: Registry;
|
||||
|
||||
// HACK Use BN import so decorateDerive works... yes, wtf.
|
||||
protected __phantom = new BN(0);
|
||||
|
||||
@@ -113,6 +115,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
|
||||
super();
|
||||
|
||||
this.registry = options.registry || new TypeRegistry();
|
||||
|
||||
const thisProvider = options.source
|
||||
? options.source._rpcCore.provider.clone()
|
||||
: (options.provider || new WsProvider());
|
||||
@@ -120,9 +124,10 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
this.decorateMethod = decorateMethod;
|
||||
this._options = options;
|
||||
this._type = type;
|
||||
this._rpcCore = new RpcCore(thisProvider, this._options.rpc);
|
||||
this._rpcCore = new RpcCore(this.registry, thisProvider, this._options.rpc);
|
||||
this._isConnected = new BehaviorSubject(this._rpcCore.provider.isConnected());
|
||||
this._rx.hasSubscriptions = this._rpcCore.provider.hasSubscriptions;
|
||||
this._rx.registry = this.registry;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -328,8 +333,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
}
|
||||
|
||||
const nextResult = vals.length
|
||||
? new LinkageResult([keys[0].constructor as any, keys], [vals[0].constructor as any, vals])
|
||||
: new LinkageResult([Null, []], [Null, []]);
|
||||
? new LinkageResult(this.registry, [keys[0].constructor as any, keys], [vals[0].constructor as any, vals])
|
||||
: new LinkageResult(this.registry, [Null, []], [Null, []]);
|
||||
|
||||
// we set our result into a subject so we have a single observable for
|
||||
// which the value changes over time. Initially create, follow-up next
|
||||
|
||||
@@ -7,7 +7,7 @@ import { RegistryTypes } from '@polkadot/types/types';
|
||||
import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
|
||||
|
||||
import DecoratedMeta from '@polkadot/metadata';
|
||||
import { GenericCall, GenericEvent, Metadata, u32 as U32 } from '@polkadot/types';
|
||||
import { Metadata, u32 as U32 } from '@polkadot/types';
|
||||
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/primitive/Extrinsic/Extrinsic';
|
||||
import { logger } from '@polkadot/util';
|
||||
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
|
||||
@@ -16,7 +16,6 @@ import addressDefaults from '@polkadot/util-crypto/address/defaults';
|
||||
import Decorate from './Decorate';
|
||||
|
||||
const KEEPALIVE_INTERVAL = 15000;
|
||||
const DEFAULT_SS58 = new U32(addressDefaults.prefix);
|
||||
|
||||
// these are override types for polkadot chains
|
||||
// NOTE The SessionKeys definition for Polkadot and Substrate (OpaqueKeys
|
||||
@@ -141,7 +140,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
// retrieve metadata, either from chain or as pass-in via options
|
||||
const metadataKey = `${genesisHash}-${runtimeVersion.specVersion}`;
|
||||
const metadata = metadataKey in optMetadata
|
||||
? new Metadata(optMetadata[metadataKey])
|
||||
? new Metadata(this.registry, optMetadata[metadataKey])
|
||||
: await this._rpcCore.state.getMetadata().toPromise();
|
||||
|
||||
// set our chain version & genesisHash as returned
|
||||
@@ -149,7 +148,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this._runtimeVersion = runtimeVersion;
|
||||
|
||||
// set the global ss58Format as detected by the chain
|
||||
setSS58Format(chainProps.ss58Format.unwrapOr(DEFAULT_SS58).toNumber());
|
||||
setSS58Format(chainProps.ss58Format.unwrapOr(new U32(this.registry, addressDefaults.prefix)).toNumber());
|
||||
|
||||
// get unique types & validate
|
||||
metadata.getUniqTypes(false);
|
||||
@@ -165,13 +164,10 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this.registerTypes(TYPES_SUBSTRATE_1);
|
||||
}
|
||||
|
||||
const decoratedMeta = new DecoratedMeta(metadata);
|
||||
const decoratedMeta = new DecoratedMeta(this.registry, metadata);
|
||||
|
||||
// only inject if we are not a clone (global init)
|
||||
if (!this._options.source) {
|
||||
GenericEvent.injectMetadata(metadata);
|
||||
GenericCall.injectMetadata(metadata);
|
||||
|
||||
// detect the extrinsic version in-use based on the last block
|
||||
const { block: { extrinsics: [firstTx] } }: SignedBlock = await this._rpcCore.chain.getBlock().toPromise();
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { InterfaceRegistry } from '@polkadot/types/interfaceRegistry';
|
||||
import { CallFunction, InterfaceTypes, RegistryTypes, SignerPayloadRawBase } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecoratedRpc, DecorateMethod, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics, Signer } from '../types';
|
||||
|
||||
import { GenericCall, Metadata, createType, getTypeRegistry } from '@polkadot/types';
|
||||
import { Metadata, createType } from '@polkadot/types';
|
||||
import { assert, isString, isUndefined, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import Init from './Init';
|
||||
@@ -227,8 +227,8 @@ export default abstract class ApiBase<ApiType extends ApiTypes> extends Init<Api
|
||||
/**
|
||||
* @description Creates an instance of a type as registered
|
||||
*/
|
||||
public createType<K extends InterfaceTypes> (type: K, ...params: any[]): InterfaceRegistry[K] {
|
||||
return createType(type, ...params);
|
||||
public createType = <K extends InterfaceTypes> (type: K, ...params: any[]): InterfaceRegistry[K] => {
|
||||
return createType(this.registry, type, ...params);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -242,14 +242,14 @@ export default abstract class ApiBase<ApiType extends ApiTypes> extends Init<Api
|
||||
* @description Finds the definition for a specific [[Call]] based on the index supplied
|
||||
*/
|
||||
public findCall (callIndex: Uint8Array | string): CallFunction {
|
||||
return GenericCall.findFunction(u8aToU8a(callIndex));
|
||||
return this.registry.findMetaCall(u8aToU8a(callIndex));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Register additional user-defined of chain-specific types in the type registry
|
||||
*/
|
||||
public registerTypes (types?: RegistryTypes): void {
|
||||
types && getTypeRegistry().register(types);
|
||||
types && this.registry.register(types);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,10 +10,12 @@ import { IExtrinsic, IMethod } from '@polkadot/types/types';
|
||||
import { ApiPromise } from '@polkadot/api';
|
||||
import { HeaderExtended } from '@polkadot/api-derive';
|
||||
import testKeyring, { TestKeyringMap } from '@polkadot/keyring/testingPairs';
|
||||
import { createType, createTypeUnsafe } from '@polkadot/types/codec';
|
||||
import { createType, createTypeUnsafe, TypeRegistry } from '@polkadot/types/codec';
|
||||
|
||||
import { SubmittableResult } from './';
|
||||
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
function consts (api: ApiPromise): void {
|
||||
// constants has actual value & metadata
|
||||
console.log(
|
||||
@@ -70,13 +72,13 @@ async function rpc (api: ApiPromise): Promise<void> {
|
||||
|
||||
function types (): void {
|
||||
// check correct types with `createType`
|
||||
const balance = createType('Balance', 2);
|
||||
const gas = createType('Gas', 2);
|
||||
const compact = createType('Compact<u32>', 2);
|
||||
// const random = createType('RandomType', 2); // This one should deliberately show a TS error
|
||||
const balance = createType(registry, 'Balance', 2);
|
||||
const gas = createType(registry, 'Gas', 2);
|
||||
const compact = createType(registry, 'Compact<u32>', 2);
|
||||
// const random = createType(registry, 'RandomType', 2); // This one should deliberately show a TS error
|
||||
|
||||
const gasUnsafe = createTypeUnsafe('Gas', [2]);
|
||||
const overriddenUnsafe = createTypeUnsafe<Header>('Gas', [2]);
|
||||
const gasUnsafe = createTypeUnsafe(registry, 'Gas', [2]);
|
||||
const overriddenUnsafe = createTypeUnsafe<Header>(registry, 'Gas', [2]);
|
||||
|
||||
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
|
||||
}
|
||||
|
||||
@@ -4,30 +4,31 @@
|
||||
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import Mock from '@polkadot/rpc-provider/mock/index';
|
||||
import { createType } from '@polkadot/types';
|
||||
import { createType, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { ApiPromise } from '..';
|
||||
import { SingleAccountSigner } from '../../test/util';
|
||||
import { ApiOptions } from '../types';
|
||||
|
||||
describe('ApiPromise', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const keyring = testingPairs({ type: 'ed25519' });
|
||||
let provider: Mock;
|
||||
|
||||
beforeEach((): void => {
|
||||
jest.setTimeout(3000000);
|
||||
provider = new Mock();
|
||||
provider = new Mock(registry);
|
||||
});
|
||||
|
||||
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('state_getMetadata', []);
|
||||
const genesisHash = createType('Hash', await provider.send('chain_getBlockHash', [])).toHex();
|
||||
const genesisHash = createType(registry, 'Hash', await provider.send('chain_getBlockHash', [])).toHex();
|
||||
const specVersion = 0;
|
||||
const metadata: any = {};
|
||||
const key = `${genesisHash}-${specVersion}`;
|
||||
metadata[key] = rpcData;
|
||||
const api = await ApiPromise.create({ provider, metadata } as unknown as ApiOptions);
|
||||
const api = await ApiPromise.create({ provider, metadata, registry } as unknown as ApiOptions);
|
||||
|
||||
expect(api.genesisHash).toBeDefined();
|
||||
expect(api.runtimeMetadata).toBeDefined();
|
||||
@@ -40,7 +41,7 @@ describe('ApiPromise', (): void => {
|
||||
|
||||
it('Create API instance without metadata and makes the runtime, rpc, state & extrinsics available', async (): Promise<void> => {
|
||||
const metadata = {};
|
||||
const api = await ApiPromise.create({ provider, metadata });
|
||||
const api = await ApiPromise.create({ provider, metadata, registry });
|
||||
|
||||
expect(api.genesisHash).toBeDefined();
|
||||
expect(api.runtimeMetadata).toBeDefined();
|
||||
@@ -58,7 +59,7 @@ describe('ApiPromise', (): void => {
|
||||
const SIG = '0x659effefbbe5ab4d7136ebb5084b959eb424e32b862307371be4721ac2c46334245af4f1476c36c5e5aff04396c2fdd2ce561ec90382821d4aa071b559b1db0f';
|
||||
|
||||
it('signs data using a specified keyring', async (): Promise<void> => {
|
||||
const api = new ApiPromise({ provider });
|
||||
const api = new ApiPromise({ provider, registry });
|
||||
|
||||
expect(
|
||||
await api.sign(keyring.alice_session, TEST)
|
||||
@@ -68,7 +69,8 @@ describe('ApiPromise', (): void => {
|
||||
it('signs data using an external signer', async (): Promise<void> => {
|
||||
const api = new ApiPromise({
|
||||
provider,
|
||||
signer: new SingleAccountSigner(keyring.alice_session)
|
||||
registry,
|
||||
signer: new SingleAccountSigner(registry, keyring.alice_session)
|
||||
});
|
||||
|
||||
expect(
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
/* eslint-disable no-dupe-class-members */
|
||||
// Copyright 2017-2019 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Address, Call, Extrinsic, ExtrinsicEra, ExtrinsicStatus, Hash, Header, Index } from '@polkadot/types/interfaces';
|
||||
import { Callback, Codec, Constructor, IKeyringPair, SignatureOptions } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx, ApiTypes, SignerResult } from '../types';
|
||||
import { SignerOptions, SubmittableExtrinsic, SubmittableResultImpl, SubmittableResultResult, SubmittableResultSubscription } from './types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { first, map, mergeMap, switchMap, tap } from 'rxjs/operators';
|
||||
import { createType, ClassOf } from '@polkadot/types';
|
||||
import { isBn, isFunction, isNumber, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { filterEvents, isKeyringPair } from '../util';
|
||||
import ApiBase from '../base';
|
||||
import SubmittableResult from './Result';
|
||||
|
||||
interface SubmittableOptions<ApiType extends ApiTypes> {
|
||||
api: ApiInterfaceRx;
|
||||
decorateMethod: ApiBase<ApiType>['decorateMethod'];
|
||||
type: ApiTypes;
|
||||
}
|
||||
|
||||
// The default for 6s allowing for 5min eras. When translating this to faster blocks -
|
||||
// - 4s = (10 / 15) * 5 = 3.33m
|
||||
// - 2s = (10 / 30) * 5 = 1.66m
|
||||
const BLOCKTIME = 6;
|
||||
const ONE_MINUTE = 60 / BLOCKTIME;
|
||||
const DEFAULT_MORTAL_LENGTH = 5 * ONE_MINUTE;
|
||||
|
||||
const _Extrinsic: Constructor<Extrinsic> = ClassOf('Extrinsic');
|
||||
|
||||
export default class Submittable<ApiType extends ApiTypes> extends _Extrinsic implements SubmittableExtrinsic<ApiType> {
|
||||
private readonly _api: ApiInterfaceRx;
|
||||
|
||||
private readonly _decorateMethod: ApiBase<ApiType>['decorateMethod'];
|
||||
|
||||
private readonly _ignoreStatusCb: boolean;
|
||||
|
||||
constructor (extrinsic: Call | Uint8Array | string, { api, decorateMethod, type }: SubmittableOptions<ApiType>) {
|
||||
super(extrinsic, { version: api.extrinsicType });
|
||||
|
||||
this._api = api;
|
||||
this._decorateMethod = decorateMethod;
|
||||
this._ignoreStatusCb = type === 'rxjs';
|
||||
}
|
||||
|
||||
// sign a transaction, returning the this to allow cianing, i.e. .sign(...).send()
|
||||
public sign (account: IKeyringPair, optionsOrNonce: Partial<SignerOptions>): this {
|
||||
// NOTE here we actually override nonce if it was specified (backwards compat for
|
||||
// the previous signature - don't let userspace break, but allow then time to upgrade)
|
||||
const options: Partial<SignerOptions> = isBn(optionsOrNonce) || isNumber(optionsOrNonce)
|
||||
? { nonce: optionsOrNonce }
|
||||
: optionsOrNonce;
|
||||
|
||||
super.sign(account, this._makeSignOptions(options, {}));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// signAndSend with an immediate Hash result
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
|
||||
|
||||
// signAndSend with a subscription, i.e. callback provided
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, statusCb: Callback<SubmittableResultImpl>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
// signAndSend with options and a callback
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, options: Partial<SignerOptions>, statusCb?: Callback<SubmittableResultImpl>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
// signAndSend implementation for all 3 cases above
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, optionsOrStatus?: Partial<SignerOptions> | Callback<SubmittableResultImpl>, optionalStatusCb?: Callback<SubmittableResultImpl>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
|
||||
const [options, statusCb] = this._makeSignAndSendOptions(optionsOrStatus, optionalStatusCb);
|
||||
const isSubscription = this._api.hasSubscriptions && (this._ignoreStatusCb || !!statusCb);
|
||||
const address = isKeyringPair(account) ? account.address : account.toString();
|
||||
let updateId: number | undefined;
|
||||
|
||||
return this._decorateMethod(
|
||||
(): Observable<Codec> => (
|
||||
this._getPrelimState(address, options).pipe(
|
||||
first(),
|
||||
mergeMap(async ([nonce, header]): Promise<void> => {
|
||||
const eraOptions = this._makeEraOptions(options, { header, nonce });
|
||||
|
||||
if (isKeyringPair(account)) {
|
||||
this.sign(account, eraOptions);
|
||||
} else {
|
||||
updateId = await this._signViaSigner(address, eraOptions, header);
|
||||
}
|
||||
}),
|
||||
switchMap((): Observable<SubmittableResultImpl> | Observable<Hash> => {
|
||||
return isSubscription
|
||||
? this._subscribeObservable(updateId)
|
||||
: this._sendObservable(updateId);
|
||||
})
|
||||
) as Observable<Codec>) // FIXME This is wrong, SubmittableResult is _not_ a codec
|
||||
)(statusCb) as SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType>;
|
||||
}
|
||||
|
||||
// send with an immediate Hash result
|
||||
public send (): SubmittableResultResult<ApiType>;
|
||||
|
||||
// send with a status callback
|
||||
public send (statusCb: Callback<SubmittableResultImpl>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
// send implementation for both immediate Hash and statusCb variants
|
||||
public send (statusCb?: Callback<SubmittableResultImpl>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
|
||||
const isSubscription = this._api.hasSubscriptions && (this._ignoreStatusCb || !!statusCb);
|
||||
|
||||
return this._decorateMethod(
|
||||
isSubscription
|
||||
? this._subscribeObservable
|
||||
: this._sendObservable
|
||||
)(statusCb);
|
||||
}
|
||||
|
||||
private _makeSignAndSendOptions (optionsOrStatus?: Partial<SignerOptions> | Callback<SubmittableResultImpl>, statusCb?: Callback<SubmittableResultImpl>): [Partial<SignerOptions>, Callback<SubmittableResultImpl>?] {
|
||||
let options: Partial<SignerOptions> = {};
|
||||
|
||||
if (isFunction(optionsOrStatus)) {
|
||||
statusCb = optionsOrStatus;
|
||||
} else {
|
||||
options = { ...optionsOrStatus };
|
||||
}
|
||||
|
||||
return [options, statusCb];
|
||||
}
|
||||
|
||||
private async _signViaSigner (address: string, optionsWithEra: SignatureOptions, header: Header | null): Promise<number> {
|
||||
if (!this._api.signer) {
|
||||
throw new Error('no signer attached');
|
||||
}
|
||||
|
||||
const payload = createType('SignerPayload', {
|
||||
...optionsWithEra,
|
||||
address,
|
||||
method: this.method,
|
||||
blockNumber: header ? header.number : 0
|
||||
});
|
||||
let result: SignerResult;
|
||||
|
||||
if (this._api.signer.signPayload) {
|
||||
result = await this._api.signer.signPayload(payload.toPayload());
|
||||
} else if (this._api.signer.signRaw) {
|
||||
result = await this._api.signer.signRaw(payload.toRaw());
|
||||
} else {
|
||||
throw new Error('Invalid signer interface, it should implement either signPayload or signRaw (or both)');
|
||||
}
|
||||
|
||||
// Here we explicitly call `toPayload()` again instead of working with an object
|
||||
// (reference) as passed to the signer. This means that we are sure that the
|
||||
// payload data is not modified from our inputs, but the signer
|
||||
super.addSignature(address, result.signature, payload.toPayload());
|
||||
|
||||
return result.id;
|
||||
}
|
||||
|
||||
private _makeSignOptions (options: Partial<SignerOptions>, extras: { blockHash?: Hash; era?: ExtrinsicEra; nonce?: Index }): SignatureOptions {
|
||||
return {
|
||||
blockHash: this._api.genesisHash,
|
||||
...options,
|
||||
...extras,
|
||||
genesisHash: this._api.genesisHash,
|
||||
runtimeVersion: this._api.runtimeVersion,
|
||||
version: this._api.extrinsicType
|
||||
} as unknown as SignatureOptions;
|
||||
}
|
||||
|
||||
private _makeEraOptions (options: Partial<SignerOptions>, { header, nonce }: { header: Header | null; nonce: Index }): SignatureOptions {
|
||||
if (!header) {
|
||||
if (isNumber(options.era)) {
|
||||
// since we have no header, it is immortal, remove any option overrides
|
||||
// so we only supply the genesisHash and no era to the construction
|
||||
delete options.era;
|
||||
delete options.blockHash;
|
||||
}
|
||||
|
||||
return this._makeSignOptions(options, { nonce });
|
||||
}
|
||||
|
||||
return this._makeSignOptions(options, {
|
||||
blockHash: header.hash,
|
||||
era: createType('ExtrinsicEra', {
|
||||
current: header.number,
|
||||
period: options.era || DEFAULT_MORTAL_LENGTH
|
||||
}),
|
||||
nonce
|
||||
});
|
||||
}
|
||||
|
||||
private _getPrelimState (address: string, options: Partial<SignerOptions>): Observable<[Index, Header | null]> {
|
||||
return combineLatest([
|
||||
// if we have a nonce already, don't retrieve the latest, use what is there
|
||||
isUndefined(options.nonce)
|
||||
// FIXME This apparently is having issues on latest Kusama for nonce retrieval,
|
||||
// hence we are using the accountNonce only
|
||||
// ? this._api.rpc.account.nextIndex
|
||||
// ? this._api.rpc.account.nextIndex(address)
|
||||
// : this._api.query.system.accountNonce(address)
|
||||
? this._api.query.system.accountNonce(address)
|
||||
: of(createType('Index', options.nonce)),
|
||||
// if we have an era provided already or eraLength is <= 0 (immortal)
|
||||
// don't get the latest block, just pass null, handle in mergeMap
|
||||
(isUndefined(options.era) || (isNumber(options.era) && options.era > 0))
|
||||
? this._api.rpc.chain.getHeader()
|
||||
: of(null)
|
||||
]);
|
||||
}
|
||||
|
||||
private _updateSigner (updateId: number, status: Hash | SubmittableResultImpl): void {
|
||||
if ((updateId !== -1) && this._api.signer && this._api.signer.update) {
|
||||
this._api.signer.update(updateId, status);
|
||||
}
|
||||
}
|
||||
|
||||
private _statusObservable (status: ExtrinsicStatus): Observable<SubmittableResultImpl> {
|
||||
if (!status.isFinalized) {
|
||||
return of(new SubmittableResult({ status }));
|
||||
}
|
||||
|
||||
const blockHash = status.asFinalized;
|
||||
|
||||
return combineLatest([
|
||||
this._api.rpc.chain.getBlock(blockHash),
|
||||
this._api.query.system.events.at(blockHash)
|
||||
]).pipe(
|
||||
map(([signedBlock, allEvents]): SubmittableResultImpl =>
|
||||
new SubmittableResult({
|
||||
events: filterEvents(this.hash, signedBlock, allEvents),
|
||||
status
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private _sendObservable = (updateId = -1): Observable<Hash> => {
|
||||
return this._api.rpc.author
|
||||
.submitExtrinsic(this)
|
||||
.pipe(
|
||||
tap((hash): void => {
|
||||
this._updateSigner(updateId, hash);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private _subscribeObservable = (updateId = -1): Observable<SubmittableResultImpl> => {
|
||||
return this._api.rpc.author
|
||||
.submitAndWatchExtrinsic(this)
|
||||
.pipe(
|
||||
switchMap((status): Observable<SubmittableResultImpl> =>
|
||||
this._statusObservable(status)
|
||||
),
|
||||
tap((status): void => {
|
||||
this._updateSigner(updateId, status);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/* eslint-disable no-dupe-class-members */
|
||||
// Copyright 2017-2019 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Address, Call, ExtrinsicEra, ExtrinsicStatus, Hash, Header, Index } from '@polkadot/types/interfaces';
|
||||
import { Callback, Codec, Constructor, IKeyringPair, Registry, SignatureOptions } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx, ApiTypes, SignerResult } from '../types';
|
||||
import { SignerOptions, SubmittableExtrinsic, SubmittableResultImpl, SubmittableResultResult, SubmittableResultSubscription } from './types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { first, map, mergeMap, switchMap, tap } from 'rxjs/operators';
|
||||
import { createType, ClassOf } from '@polkadot/types';
|
||||
import { isBn, isFunction, isNumber, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { filterEvents, isKeyringPair } from '../util';
|
||||
import ApiBase from '../base';
|
||||
import SubmittableResult from './Result';
|
||||
|
||||
interface SubmittableOptions<ApiType extends ApiTypes> {
|
||||
api: ApiInterfaceRx;
|
||||
apiType: ApiTypes;
|
||||
decorateMethod: ApiBase<ApiType>['decorateMethod'];
|
||||
}
|
||||
|
||||
// The default for 6s allowing for 5min eras. When translating this to faster blocks -
|
||||
// - 4s = (10 / 15) * 5 = 3.33m
|
||||
// - 2s = (10 / 30) * 5 = 1.66m
|
||||
const BLOCKTIME = 6;
|
||||
const ONE_MINUTE = 60 / BLOCKTIME;
|
||||
const DEFAULT_MORTAL_LENGTH = 5 * ONE_MINUTE;
|
||||
|
||||
export default function createClass <ApiType extends ApiTypes> ({ api, apiType, decorateMethod }: SubmittableOptions<ApiType>): Constructor<SubmittableExtrinsic<ApiType>> {
|
||||
// an instance of the base extrinsic for us to extend
|
||||
const Extrinsic = ClassOf(api.registry, 'Extrinsic');
|
||||
|
||||
return class Submittable extends Extrinsic implements SubmittableExtrinsic<ApiType> {
|
||||
private readonly _api: ApiInterfaceRx;
|
||||
|
||||
private readonly _decorateMethod: ApiBase<ApiType>['decorateMethod'];
|
||||
|
||||
private readonly _ignoreStatusCb: boolean;
|
||||
|
||||
constructor (registry: Registry, extrinsic: Call | Uint8Array | string) {
|
||||
super(registry, extrinsic, { version: api.extrinsicType });
|
||||
|
||||
this._api = api;
|
||||
this._decorateMethod = decorateMethod;
|
||||
this._ignoreStatusCb = apiType === 'rxjs';
|
||||
}
|
||||
|
||||
// sign a transaction, returning the this to allow cianing, i.e. .sign(...).send()
|
||||
public sign (account: IKeyringPair, optionsOrNonce: Partial<SignerOptions>): this {
|
||||
// NOTE here we actually override nonce if it was specified (backwards compat for
|
||||
// the previous signature - don't let userspace break, but allow then time to upgrade)
|
||||
const options: Partial<SignerOptions> = isBn(optionsOrNonce) || isNumber(optionsOrNonce)
|
||||
? { nonce: optionsOrNonce }
|
||||
: optionsOrNonce;
|
||||
|
||||
super.sign(account, this._makeSignOptions(options, {}));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// signAndSend with an immediate Hash result
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
|
||||
|
||||
// signAndSend with a subscription, i.e. callback provided
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, statusCb: Callback<SubmittableResultImpl>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
// signAndSend with options and a callback
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, options: Partial<SignerOptions>, statusCb?: Callback<SubmittableResultImpl>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
// signAndSend implementation for all 3 cases above
|
||||
public signAndSend (account: IKeyringPair | string | AccountId | Address, optionsOrStatus?: Partial<SignerOptions> | Callback<SubmittableResultImpl>, optionalStatusCb?: Callback<SubmittableResultImpl>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
|
||||
const [options, statusCb] = this._makeSignAndSendOptions(optionsOrStatus, optionalStatusCb);
|
||||
const isSubscription = this._api.hasSubscriptions && (this._ignoreStatusCb || !!statusCb);
|
||||
const address = isKeyringPair(account) ? account.address : account.toString();
|
||||
let updateId: number | undefined;
|
||||
|
||||
return this._decorateMethod(
|
||||
(): Observable<Codec> => (
|
||||
this._getPrelimState(address, options).pipe(
|
||||
first(),
|
||||
mergeMap(async ([nonce, header]): Promise<void> => {
|
||||
const eraOptions = this._makeEraOptions(options, { header, nonce });
|
||||
|
||||
if (isKeyringPair(account)) {
|
||||
this.sign(account, eraOptions);
|
||||
} else {
|
||||
updateId = await this._signViaSigner(address, eraOptions, header);
|
||||
}
|
||||
}),
|
||||
switchMap((): Observable<SubmittableResultImpl> | Observable<Hash> => {
|
||||
return isSubscription
|
||||
? this._subscribeObservable(updateId)
|
||||
: this._sendObservable(updateId);
|
||||
})
|
||||
) as Observable<Codec>) // FIXME This is wrong, SubmittableResult is _not_ a codec
|
||||
)(statusCb) as SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType>;
|
||||
}
|
||||
|
||||
// send with an immediate Hash result
|
||||
public send (): SubmittableResultResult<ApiType>;
|
||||
|
||||
// send with a status callback
|
||||
public send (statusCb: Callback<SubmittableResultImpl>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
// send implementation for both immediate Hash and statusCb variants
|
||||
public send (statusCb?: Callback<SubmittableResultImpl>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
|
||||
const isSubscription = this._api.hasSubscriptions && (this._ignoreStatusCb || !!statusCb);
|
||||
|
||||
return this._decorateMethod(
|
||||
isSubscription
|
||||
? this._subscribeObservable
|
||||
: this._sendObservable
|
||||
)(statusCb);
|
||||
}
|
||||
|
||||
private _makeSignAndSendOptions (optionsOrStatus?: Partial<SignerOptions> | Callback<SubmittableResultImpl>, statusCb?: Callback<SubmittableResultImpl>): [Partial<SignerOptions>, Callback<SubmittableResultImpl>?] {
|
||||
let options: Partial<SignerOptions> = {};
|
||||
|
||||
if (isFunction(optionsOrStatus)) {
|
||||
statusCb = optionsOrStatus;
|
||||
} else {
|
||||
options = { ...optionsOrStatus };
|
||||
}
|
||||
|
||||
return [options, statusCb];
|
||||
}
|
||||
|
||||
private async _signViaSigner (address: string, optionsWithEra: SignatureOptions, header: Header | null): Promise<number> {
|
||||
if (!this._api.signer) {
|
||||
throw new Error('no signer attached');
|
||||
}
|
||||
|
||||
const payload = createType(this.registry, 'SignerPayload', {
|
||||
...optionsWithEra,
|
||||
address,
|
||||
method: this.method,
|
||||
blockNumber: header ? header.number : 0
|
||||
});
|
||||
let result: SignerResult;
|
||||
|
||||
if (this._api.signer.signPayload) {
|
||||
result = await this._api.signer.signPayload(payload.toPayload());
|
||||
} else if (this._api.signer.signRaw) {
|
||||
result = await this._api.signer.signRaw(payload.toRaw());
|
||||
} else {
|
||||
throw new Error('Invalid signer interface, it should implement either signPayload or signRaw (or both)');
|
||||
}
|
||||
|
||||
// Here we explicitly call `toPayload()` again instead of working with an object
|
||||
// (reference) as passed to the signer. This means that we are sure that the
|
||||
// payload data is not modified from our inputs, but the signer
|
||||
super.addSignature(address, result.signature, payload.toPayload());
|
||||
|
||||
return result.id;
|
||||
}
|
||||
|
||||
private _makeSignOptions (options: Partial<SignerOptions>, extras: { blockHash?: Hash; era?: ExtrinsicEra; nonce?: Index }): SignatureOptions {
|
||||
return {
|
||||
blockHash: this._api.genesisHash,
|
||||
...options,
|
||||
...extras,
|
||||
genesisHash: this._api.genesisHash,
|
||||
runtimeVersion: this._api.runtimeVersion,
|
||||
version: this._api.extrinsicType
|
||||
} as unknown as SignatureOptions;
|
||||
}
|
||||
|
||||
private _makeEraOptions (options: Partial<SignerOptions>, { header, nonce }: { header: Header | null; nonce: Index }): SignatureOptions {
|
||||
if (!header) {
|
||||
if (isNumber(options.era)) {
|
||||
// since we have no header, it is immortal, remove any option overrides
|
||||
// so we only supply the genesisHash and no era to the construction
|
||||
delete options.era;
|
||||
delete options.blockHash;
|
||||
}
|
||||
|
||||
return this._makeSignOptions(options, { nonce });
|
||||
}
|
||||
|
||||
return this._makeSignOptions(options, {
|
||||
blockHash: header.hash,
|
||||
era: createType(this.registry, 'ExtrinsicEra', {
|
||||
current: header.number,
|
||||
period: options.era || DEFAULT_MORTAL_LENGTH
|
||||
}),
|
||||
nonce
|
||||
});
|
||||
}
|
||||
|
||||
private _getPrelimState (address: string, options: Partial<SignerOptions>): Observable<[Index, Header | null]> {
|
||||
return combineLatest([
|
||||
// if we have a nonce already, don't retrieve the latest, use what is there
|
||||
isUndefined(options.nonce)
|
||||
// FIXME This apparently is having issues on latest Kusama for nonce retrieval,
|
||||
// hence we are using the accountNonce only
|
||||
// ? this._api.rpc.account.nextIndex
|
||||
// ? this._api.rpc.account.nextIndex(address)
|
||||
// : this._api.query.system.accountNonce(address)
|
||||
? this._api.query.system.accountNonce(address)
|
||||
: of(createType(this.registry, 'Index', options.nonce)),
|
||||
// if we have an era provided already or eraLength is <= 0 (immortal)
|
||||
// don't get the latest block, just pass null, handle in mergeMap
|
||||
(isUndefined(options.era) || (isNumber(options.era) && options.era > 0))
|
||||
? this._api.rpc.chain.getHeader()
|
||||
: of(null)
|
||||
]);
|
||||
}
|
||||
|
||||
private _updateSigner (updateId: number, status: Hash | SubmittableResultImpl): void {
|
||||
if ((updateId !== -1) && this._api.signer && this._api.signer.update) {
|
||||
this._api.signer.update(updateId, status);
|
||||
}
|
||||
}
|
||||
|
||||
private _statusObservable (status: ExtrinsicStatus): Observable<SubmittableResultImpl> {
|
||||
if (!status.isFinalized) {
|
||||
return of(new SubmittableResult({ status }));
|
||||
}
|
||||
|
||||
const blockHash = status.asFinalized;
|
||||
|
||||
return combineLatest([
|
||||
this._api.rpc.chain.getBlock(blockHash),
|
||||
this._api.query.system.events.at(blockHash)
|
||||
]).pipe(
|
||||
map(([signedBlock, allEvents]): SubmittableResultImpl =>
|
||||
new SubmittableResult({
|
||||
events: filterEvents(this.hash, signedBlock, allEvents),
|
||||
status
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private _sendObservable = (updateId = -1): Observable<Hash> => {
|
||||
return this._api.rpc.author
|
||||
.submitExtrinsic(this)
|
||||
.pipe(
|
||||
tap((hash): void => {
|
||||
this._updateSigner(updateId, hash);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private _subscribeObservable = (updateId = -1): Observable<SubmittableResultImpl> => {
|
||||
return this._api.rpc.author
|
||||
.submitAndWatchExtrinsic(this)
|
||||
.pipe(
|
||||
switchMap((status): Observable<SubmittableResultImpl> =>
|
||||
this._statusObservable(status)
|
||||
),
|
||||
tap((status): void => {
|
||||
this._updateSigner(updateId, status);
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -8,19 +8,20 @@ import { ApiInterfaceRx, ApiTypes } from '../types';
|
||||
import { SubmittableExtrinsic } from './types';
|
||||
|
||||
import ApiBase from '../base';
|
||||
import createClass from './createClass';
|
||||
|
||||
type Creator<ApiType extends ApiTypes> = (extrinsic: Call | Uint8Array | string) => SubmittableExtrinsic<ApiType>;
|
||||
|
||||
let Submittable: Constructor<SubmittableExtrinsic<any>>;
|
||||
|
||||
export default function createSubmittable<ApiType extends ApiTypes> (type: ApiTypes, api: ApiInterfaceRx, decorateMethod: ApiBase<ApiType>['decorateMethod']): Creator<ApiType> {
|
||||
export default function createSubmittable<ApiType extends ApiTypes> (apiType: ApiTypes, api: ApiInterfaceRx, decorateMethod: ApiBase<ApiType>['decorateMethod']): Creator<ApiType> {
|
||||
return (extrinsic: Call | Uint8Array | string): SubmittableExtrinsic<ApiType> => {
|
||||
// HACK This is not great, but basically what we do here is to lazily only require the class
|
||||
// right at the point it is actually needed - delaying initialization
|
||||
// This is not great, but basically what we do here is to only require the
|
||||
// class right at the point it is actually needed - delaying initialization
|
||||
if (!Submittable) {
|
||||
Submittable = require('./Submittable').default;
|
||||
Submittable = createClass<ApiType>({ api, apiType, decorateMethod });
|
||||
}
|
||||
|
||||
return new Submittable(extrinsic, { api, decorateMethod, type });
|
||||
return new Submittable(api.registry, extrinsic);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import './query.types';
|
||||
import { Constants } from '@polkadot/metadata/Decorated/types';
|
||||
import { UserRpc } from '@polkadot/rpc-core/types';
|
||||
import { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { AnyFunction, Callback, CallFunction, Codec, CodecArg, RegistryTypes, SignatureOptions, SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
|
||||
import { AnyFunction, Callback, CallFunction, Codec, CodecArg, RegistryTypes, SignatureOptions, SignerPayloadJSON, SignerPayloadRaw, Registry } from '@polkadot/types/types';
|
||||
import { SubmittableResultImpl, SubmittableExtrinsic } from './submittable/types';
|
||||
import { DeriveAllSections } from './util/decorate';
|
||||
|
||||
@@ -192,6 +192,10 @@ export interface ApiOptions {
|
||||
* connecting to a WsProvider connecting localhost with the default port, i.e. `ws://127.0.0.1:9944`
|
||||
*/
|
||||
provider?: ProviderInterface;
|
||||
/**
|
||||
* @description A type registry to use along with this instance
|
||||
*/
|
||||
registry?: Registry;
|
||||
/**
|
||||
* @description User-defined RPC methods
|
||||
*/
|
||||
@@ -227,6 +231,7 @@ export interface ApiInterfaceRx {
|
||||
extrinsicType: number;
|
||||
genesisHash: Hash;
|
||||
hasSubscriptions: boolean;
|
||||
registry: Registry;
|
||||
runtimeMetadata: Metadata;
|
||||
runtimeVersion: RuntimeVersion;
|
||||
query: QueryableStorage<'rxjs'>;
|
||||
|
||||
@@ -9,7 +9,7 @@ import BN from 'bn.js';
|
||||
import ApiRx from '@polkadot/api/rx/Api';
|
||||
import { HeaderExtended } from '@polkadot/api-derive';
|
||||
import { DerivedBalances, DerivedContractFees, DerivedElectionsInfo, DerivedFees, DerivedSessionInfo } from '@polkadot/api-derive/types';
|
||||
import { createType, ClassOf } from '@polkadot/types';
|
||||
import { createType, ClassOf, TypeRegistry } from '@polkadot/types';
|
||||
import { WsProvider } from '@polkadot/rpc-provider';
|
||||
|
||||
import { describeE2E } from '../../util';
|
||||
@@ -24,6 +24,7 @@ describeE2E({
|
||||
'remote-substrate-1.0'
|
||||
]
|
||||
})('Api-RX derive e2e', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
let api: ApiRx;
|
||||
|
||||
beforeAll((): void => {
|
||||
@@ -76,7 +77,7 @@ describeE2E({
|
||||
api.derive.accounts.indexToId(IX).subscribe((accountId): void => {
|
||||
// The first emitted value for accountId is undefined when passing the IX
|
||||
if (accountId) {
|
||||
expect(accountId instanceof ClassOf('AccountId')).toBe(true);
|
||||
expect(accountId instanceof ClassOf(registry, 'AccountId')).toBe(true);
|
||||
expect(accountId.toString()).toEqual(ID);
|
||||
} else {
|
||||
expect(accountId).toEqual(undefined);
|
||||
@@ -91,7 +92,7 @@ describeE2E({
|
||||
api.derive.accounts.idToIndex(ID).subscribe((accountIndex): void => {
|
||||
// The first emitted value for AccountIndex is undefined when passing the ID
|
||||
if (accountIndex) {
|
||||
expect(accountIndex instanceof ClassOf('AccountIndex')).toBe(true);
|
||||
expect(accountIndex instanceof ClassOf(registry, 'AccountIndex')).toBe(true);
|
||||
expect(accountIndex.toString()).toEqual(IX);
|
||||
} else {
|
||||
expect(accountIndex).toEqual(undefined);
|
||||
@@ -107,7 +108,7 @@ describeE2E({
|
||||
// A local dev chain should have the AccountIndex of Alice
|
||||
expect(accountIndexes).toHaveProperty(
|
||||
ID,
|
||||
createType('AccountIndex', IX)
|
||||
createType(registry, 'AccountIndex', IX)
|
||||
);
|
||||
done();
|
||||
});
|
||||
@@ -122,8 +123,8 @@ describeE2E({
|
||||
it('It returns an object with all relevant balance information of an account', (done): void => {
|
||||
api.derive.balances.all(ID).subscribe((balances: DerivedBalances): void => {
|
||||
expect(balances).toEqual(expect.objectContaining({
|
||||
accountId: expect.any(ClassOf('AccountId')),
|
||||
accountNonce: expect.any(ClassOf('Index')),
|
||||
accountId: expect.any(ClassOf(registry, 'AccountId')),
|
||||
accountNonce: expect.any(ClassOf(registry, 'Index')),
|
||||
availableBalance: expect.any(BN),
|
||||
freeBalance: expect.any(BN),
|
||||
lockedBalance: expect.any(BN),
|
||||
@@ -156,7 +157,7 @@ describeE2E({
|
||||
describe('bestNumber', (): void => {
|
||||
it('Get the latest block number', (done): void => {
|
||||
api.derive.chain.bestNumber().subscribe((blockNumber: BlockNumber): void => {
|
||||
expect(blockNumber instanceof ClassOf('BlockNumber')).toBe(true);
|
||||
expect(blockNumber instanceof ClassOf(registry, 'BlockNumber')).toBe(true);
|
||||
expect(blockNumber.gten(0)).toBe(true);
|
||||
done();
|
||||
});
|
||||
@@ -166,7 +167,7 @@ describeE2E({
|
||||
describe('bestNumberFinalized', (): void => {
|
||||
it('Get the latest finalised block number', (done): void => {
|
||||
api.derive.chain.bestNumberFinalized().subscribe((blockNumber: BlockNumber): void => {
|
||||
expect(blockNumber instanceof ClassOf('BlockNumber')).toBe(true);
|
||||
expect(blockNumber instanceof ClassOf(registry, 'BlockNumber')).toBe(true);
|
||||
expect(blockNumber.gten(0)).toBe(true);
|
||||
done();
|
||||
});
|
||||
@@ -176,7 +177,7 @@ describeE2E({
|
||||
describe('bestNumberLag', (): void => {
|
||||
it('lag between finalised head and best head', (done): void => {
|
||||
api.derive.chain.bestNumberLag().subscribe((numberLag: BlockNumber): void => {
|
||||
expect(numberLag instanceof ClassOf('BlockNumber')).toBe(true);
|
||||
expect(numberLag instanceof ClassOf(registry, 'BlockNumber')).toBe(true);
|
||||
expect(numberLag.gten(0)).toBe(true);
|
||||
done();
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { AccountId, EventRecord } from '@polkadot/types/interfaces';
|
||||
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { ClassOf, Option, Vec } from '@polkadot/types';
|
||||
import { ClassOf, Option, TypeRegistry, Vec } from '@polkadot/types';
|
||||
|
||||
import ApiPromise from '../../../src/promise';
|
||||
import { describeE2E } from '../../util';
|
||||
@@ -13,6 +13,7 @@ import { describeE2E } from '../../util';
|
||||
describeE2E({
|
||||
only: ['docker-polkadot-alexander', 'remote-polkadot-alexander']
|
||||
})('Promise e2e alex queries', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
let api: ApiPromise;
|
||||
|
||||
beforeEach(async (done): Promise<void> => {
|
||||
@@ -46,7 +47,7 @@ describeE2E({
|
||||
it('Gets the hash of the last finalized header', async (done): Promise<() => void> => {
|
||||
return (
|
||||
api.rpc.chain.getFinalizedHead((head): void => {
|
||||
expect(head instanceof ClassOf('Hash')).toBe(true);
|
||||
expect(head instanceof ClassOf(registry, 'Hash')).toBe(true);
|
||||
done();
|
||||
})
|
||||
);
|
||||
@@ -55,7 +56,7 @@ describeE2E({
|
||||
it('Subscribes to the best finalized header on ALEX', async (done): Promise<() => void> => {
|
||||
return (
|
||||
api.rpc.chain.subscribeFinalizedHeads((head): void => {
|
||||
expect(head instanceof ClassOf('Header')).toBe(true);
|
||||
expect(head instanceof ClassOf(registry, 'Header')).toBe(true);
|
||||
done();
|
||||
})
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { ClassOf } from '@polkadot/types';
|
||||
import { ClassOf, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import ApiPromise from '../../../src/promise';
|
||||
import { describeE2E } from '../../util';
|
||||
@@ -16,6 +16,7 @@ describeE2E({
|
||||
'docker-substrate-2.0'
|
||||
]
|
||||
})('Promise e2e consts', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
let api: ApiPromise;
|
||||
|
||||
beforeEach(async (done): Promise<void> => {
|
||||
@@ -25,7 +26,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('democracy.cooloffPeriod parameter type', (): void => {
|
||||
expect(api.consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf('BlockNumber'));
|
||||
expect(api.consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf(registry, 'BlockNumber'));
|
||||
expect(
|
||||
api.consts.democracy.cooloffPeriod.eq(432000) || // Substrate
|
||||
api.consts.democracy.cooloffPeriod.eq(259200) // Polkadot
|
||||
|
||||
@@ -48,7 +48,7 @@ describeE2E({
|
||||
let abi: Abi;
|
||||
|
||||
beforeEach((): void => {
|
||||
abi = new Abi(incrementerAbi);
|
||||
abi = new Abi(api.registry, incrementerAbi);
|
||||
});
|
||||
|
||||
it('allows putCode', (done): Promise<() => void> => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import BN from 'bn.js';
|
||||
import { DerivedBalances } from '@polkadot/api-derive/types';
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { Option, u32, createType } from '@polkadot/types';
|
||||
import { Option, u32, createType, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import ApiPromise from '../../../src/promise';
|
||||
import { describeE2E } from '../../util';
|
||||
@@ -23,6 +23,7 @@ describeE2E({
|
||||
'remote-substrate-1.0'
|
||||
]
|
||||
})('Promise e2e development queries', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
let api: ApiPromise;
|
||||
|
||||
beforeEach(async (done): Promise<void> => {
|
||||
@@ -159,7 +160,7 @@ describeE2E({
|
||||
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
|
||||
const key = api.query.balances.freeBalance.key(keyring.alice_stash.address);
|
||||
const balanceData = await api.rpc.state.getStorage(key) as Option<any>;
|
||||
const balanceRPC = createType('Balance', balanceData.unwrapOr(undefined));
|
||||
const balanceRPC = createType(registry, 'Balance', balanceData.unwrapOr(undefined));
|
||||
|
||||
const balance = await api.query.balances.freeBalance(keyring.alice_stash.address);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { EventRecord, Hash, Header, SessionIndex } from '@polkadot/types/interfa
|
||||
import { HeaderExtended } from '@polkadot/api-derive';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { LinkageResult } from '@polkadot/types/codec/Linkage';
|
||||
import { Option, createType } from '@polkadot/types';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import ApiPromise from '../../../src/promise';
|
||||
import { describeE2E } from '../../util';
|
||||
@@ -128,7 +128,7 @@ describeE2E()('Promise e2e queries', (wsUrl: string): void => {
|
||||
it('gets correct key', async (): Promise<void> => {
|
||||
const key = api.query.session.currentIndex.key();
|
||||
const sessionIndexData = await api.rpc.state.getStorage<Option<any>>(key);
|
||||
const sessionIndexRPC = createType('SessionIndex', sessionIndexData.unwrapOr(undefined));
|
||||
const sessionIndexRPC = api.createType('SessionIndex', sessionIndexData.unwrapOr(undefined));
|
||||
|
||||
expect(sessionIndexRPC.toNumber()).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { Header } from '@polkadot/types/interfaces';
|
||||
import { createType } from '@polkadot/types';
|
||||
import { createType, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import ApiPromise from '../../../src/promise';
|
||||
import { Signer } from '../../../src/types';
|
||||
@@ -19,6 +19,7 @@ describeE2E({
|
||||
'docker-substrate-1.0'
|
||||
]
|
||||
})('Promise e2e transactions with specified eras', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const keyring = testingPairs({ type: 'ed25519' });
|
||||
let api: ApiPromise;
|
||||
|
||||
@@ -32,7 +33,7 @@ describeE2E({
|
||||
it('makes a transfer (specified era)', async (done): Promise<void> => {
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const exERA = createType(registry, 'ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
|
||||
|
||||
await ex.signAndSend(keyring.charlie, {
|
||||
@@ -44,7 +45,7 @@ describeE2E({
|
||||
it('makes a transfer (specified era, previous block)', async (done): Promise<void> => {
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number.toBn().subn(1);
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 10 });
|
||||
const exERA = createType(registry, 'ExtrinsicEra', { current: currentHeight, period: 10 });
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
|
||||
|
||||
await ex.signAndSend(keyring.charlie, {
|
||||
@@ -57,7 +58,7 @@ describeE2E({
|
||||
const nonce = await api.query.system.accountNonce(keyring.alice.address);
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const exERA = createType(registry, 'ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const eraDeath = exERA.asMortalEra.death(currentHeight.toNumber());
|
||||
const blockHash = signedBlock.block.header.hash;
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
|
||||
@@ -79,14 +80,14 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('fails on a transfer with invalid time (via Signer)', async (done): Promise<void> => {
|
||||
const signer: Signer = new SingleAccountSigner(keyring.alice);
|
||||
const signer: Signer = new SingleAccountSigner(registry, keyring.alice);
|
||||
|
||||
api.setSigner(signer);
|
||||
|
||||
const nonce = await api.query.system.accountNonce(keyring.bob_stash.address);
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const exERA = createType(registry, 'ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const eraDeath = exERA.asMortalEra.death(currentHeight.toNumber());
|
||||
const blockHash = signedBlock.block.header.hash;
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12121);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import ApiPromise from '../../../src/promise';
|
||||
import { Signer } from '../../../src/types';
|
||||
@@ -12,6 +13,7 @@ import { describeE2E, logEvents, SingleAccountSigner } from '../../util';
|
||||
describeE2E({
|
||||
except: ['remote-polkadot-alexander', 'remote-substrate-1.0']
|
||||
})('Promise e2e transactions with Signer injection', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const keyring = testingPairs({ type: 'ed25519' });
|
||||
let api: ApiPromise;
|
||||
|
||||
@@ -23,7 +25,7 @@ describeE2E({
|
||||
|
||||
describe('Signer injection', (): void => {
|
||||
it('makes a transfer (signAndSend via Signer)', async (done): Promise<void> => {
|
||||
const signer = new SingleAccountSigner(keyring.bob_stash);
|
||||
const signer = new SingleAccountSigner(registry, keyring.bob_stash);
|
||||
|
||||
api.setSigner(signer);
|
||||
|
||||
@@ -34,7 +36,7 @@ describeE2E({
|
||||
|
||||
it('succeeds when waiting some blocks before submission', async (done): Promise<void> => {
|
||||
// 10 second delay
|
||||
const signer = new SingleAccountSigner(keyring.bob_stash, 10000);
|
||||
const signer = new SingleAccountSigner(registry, keyring.bob_stash, 10000);
|
||||
|
||||
api.setSigner(signer);
|
||||
|
||||
@@ -54,7 +56,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('fails (signAndSend via Signer) with the wrong keyring pair', async (): Promise<void> => {
|
||||
const signer: Signer = new SingleAccountSigner(keyring.dave);
|
||||
const signer: Signer = new SingleAccountSigner(registry, keyring.dave);
|
||||
|
||||
api.setSigner(signer);
|
||||
|
||||
|
||||
@@ -2,7 +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 '@polkadot/types/injector';
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { randomAsHex } from '@polkadot/util-crypto';
|
||||
|
||||
@@ -7,14 +7,13 @@ import { BlockNumber, Index, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import Metadata from '@polkadot/metadata';
|
||||
import rpcMetadata from '@polkadot/metadata/Metadata/static';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { ClassOf } from '@polkadot/types';
|
||||
import { ClassOf, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import Rpc from '@polkadot/rpc-core';
|
||||
|
||||
import { describeE2E } from '../../util';
|
||||
|
||||
const randomAccount = '5HTqyWJHAVUieZnpb1V8gK4T1E4mnhkrUVSSzWBQd6kYgsVJ';
|
||||
const metadata = new Metadata(rpcMetadata);
|
||||
|
||||
describeE2E({
|
||||
only: [
|
||||
@@ -22,10 +21,12 @@ describeE2E({
|
||||
'docker-polkadot-alexander'
|
||||
]
|
||||
})('e2e Alexander - Polkadot', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, rpcMetadata);
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach((): void => {
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
rpc = new Rpc(registry, new WsProvider(wsUrl));
|
||||
});
|
||||
|
||||
it('subscribes to storage', (done): void => {
|
||||
@@ -38,8 +39,8 @@ describeE2E({
|
||||
expect(data).toHaveLength(2);
|
||||
expect(data).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.any(ClassOf('Index')),
|
||||
expect.any(ClassOf('Index'))
|
||||
expect.any(ClassOf(registry, 'Index')),
|
||||
expect.any(ClassOf(registry, 'Index'))
|
||||
])
|
||||
);
|
||||
|
||||
@@ -52,7 +53,7 @@ describeE2E({
|
||||
.getBlock('0x627847bffdf5f3e01ac440d057dec6a37a12a6f329db7ef8367665574b76b5df')
|
||||
.subscribe((block: SignedBlock): void => {
|
||||
expect(block).toBeDefined();
|
||||
expect(block).toBeInstanceOf(ClassOf('SignedBlock'));
|
||||
expect(block).toBeInstanceOf(ClassOf(registry, 'SignedBlock'));
|
||||
done();
|
||||
});
|
||||
});
|
||||
@@ -62,7 +63,7 @@ describeE2E({
|
||||
.getBlock('0x53416d53a4b1dfcae9165a89d193608e4aa770414f02267f5b2c4015a2e66091')
|
||||
.subscribe((block: SignedBlock): void => {
|
||||
expect(block).toBeDefined();
|
||||
expect(block).toBeInstanceOf(ClassOf('SignedBlock'));
|
||||
expect(block).toBeInstanceOf(ClassOf(registry, 'SignedBlock'));
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { ChainProperties, Extrinsic } from '@polkadot/types/interfaces';
|
||||
|
||||
import { ClassOf, Vec } from '@polkadot/types';
|
||||
import { ClassOf, TypeRegistry, Vec } from '@polkadot/types';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import Rpc from '@polkadot/rpc-core';
|
||||
|
||||
@@ -16,11 +16,12 @@ describeE2E({
|
||||
'remote-substrate-1.0'
|
||||
]
|
||||
})('RPC-core e2e basics', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach((): void => {
|
||||
jest.setTimeout(30000);
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
rpc = new Rpc(registry, new WsProvider(wsUrl));
|
||||
});
|
||||
|
||||
it('retrieves the pending extrinsics', (done): void => {
|
||||
@@ -36,7 +37,7 @@ describeE2E({
|
||||
rpc.system
|
||||
.properties()
|
||||
.subscribe((properties: ChainProperties): void => {
|
||||
expect(properties).toBeInstanceOf(ClassOf('ChainProperties'));
|
||||
expect(properties).toBeInstanceOf(ClassOf(registry, 'ChainProperties'));
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { Header } from '@polkadot/types/interfaces';
|
||||
|
||||
import { ClassOf } from '@polkadot/types';
|
||||
import { ClassOf, TypeRegistry } from '@polkadot/types';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import Rpc from '@polkadot/rpc-core';
|
||||
|
||||
@@ -16,11 +16,12 @@ describeE2E({
|
||||
'remote-substrate-1.0'
|
||||
]
|
||||
})('RPC-core e2e chain', (wsUrl: string): void => {
|
||||
const registry = new TypeRegistry();
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach((): void => {
|
||||
jest.setTimeout(30000);
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
rpc = new Rpc(registry, new WsProvider(wsUrl));
|
||||
});
|
||||
|
||||
it('subscribes via subscribeNewHeads', (done): void => {
|
||||
@@ -29,7 +30,7 @@ describeE2E({
|
||||
rpc.chain
|
||||
.subscribeNewHeads()
|
||||
.subscribe((header: Header): void => {
|
||||
expect(header).toBeInstanceOf(ClassOf('Header'));
|
||||
expect(header).toBeInstanceOf(ClassOf(registry, 'Header'));
|
||||
|
||||
if (++count === 3) {
|
||||
done();
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Hash } from '@polkadot/types/interfaces';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { Hash } from '@polkadot/types/interfaces';
|
||||
import { H256, StorageData, StorageKey } from '@polkadot/types';
|
||||
|
||||
import { ApiPromise, SubmittableResult } from '@polkadot/api';
|
||||
import { Abi } from '@polkadot/api-contract';
|
||||
@@ -14,6 +14,7 @@ import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import { KeyringPair } from '@polkadot/keyring/types';
|
||||
import Rpc from '@polkadot/rpc-core';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { H256, StorageData, StorageKey, TypeRegistry } from '@polkadot/types';
|
||||
import { hexToBn, isInstanceOf } from '@polkadot/util';
|
||||
|
||||
import { describeE2E } from '../../util';
|
||||
@@ -37,6 +38,7 @@ describeE2E({
|
||||
]
|
||||
})('RPC-core e2e child-storage', (wsUrl: string): void => {
|
||||
const MAX_GAS = 50000;
|
||||
const registry = new TypeRegistry();
|
||||
const keyring: Record<string, KeyringPair> = testingPairs({ type: 'sr25519' });
|
||||
const randomStart = Math.floor(Date.now() / 1000);
|
||||
let abi: Abi;
|
||||
@@ -45,7 +47,7 @@ describeE2E({
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeAll(async (done): Promise<() => void> => {
|
||||
abi = new Abi(incrementerAbi);
|
||||
abi = new Abi(registry, incrementerAbi);
|
||||
api = await ApiPromise.create({ provider: new WsProvider(wsUrl) });
|
||||
|
||||
return (
|
||||
@@ -64,7 +66,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
beforeEach((done): void => {
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
rpc = new Rpc(registry, new WsProvider(wsUrl));
|
||||
done();
|
||||
});
|
||||
|
||||
@@ -73,7 +75,7 @@ describeE2E({
|
||||
// @TODO Add tests for Polkadot once child storage is being used there.
|
||||
describe('e2e state child methods', (): void => {
|
||||
beforeAll(async (done): Promise<() => void> => {
|
||||
abi = new Abi(incrementerAbi);
|
||||
abi = new Abi(registry, incrementerAbi);
|
||||
api = await ApiPromise.create({ provider: new WsProvider(wsUrl) });
|
||||
// An instance of a contract can only be deployed once by one specific account.
|
||||
// That's why we need a random starting point for our incrementer contract to be
|
||||
|
||||
@@ -8,13 +8,15 @@ import DecorateMeta from '@polkadot/metadata';
|
||||
import rpcMetadata from '@polkadot/metadata/Metadata/static';
|
||||
import Rpc from '@polkadot/rpc-core';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { Bytes, ClassOf, Metadata, StorageKey } from '@polkadot/types';
|
||||
import { Bytes, ClassOf, Metadata, StorageKey, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { describeE2E } from '../../util';
|
||||
|
||||
const BOB_STASH = '5HpG9w8EBLe5XCrbczpwq5TSXvedjrBGCwqxK1iQ7qUsSWFc';
|
||||
const CODE = '0x3a636f6465'; // :code
|
||||
const metadata = new DecorateMeta(rpcMetadata);
|
||||
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new DecorateMeta(registry, rpcMetadata);
|
||||
|
||||
describeE2E({
|
||||
except: [
|
||||
@@ -26,7 +28,7 @@ describeE2E({
|
||||
|
||||
beforeEach((): void => {
|
||||
jest.setTimeout(30000);
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
rpc = new Rpc(registry, new WsProvider(wsUrl));
|
||||
});
|
||||
|
||||
it('getMetadata(): retrieves the wasm metadata', (done): void => {
|
||||
@@ -52,7 +54,7 @@ describeE2E({
|
||||
rpc.state
|
||||
.getRuntimeVersion()
|
||||
.subscribe((version: RuntimeVersion): void => {
|
||||
expect(version).toBeInstanceOf(ClassOf('RuntimeVersion'));
|
||||
expect(version).toBeInstanceOf(ClassOf(registry, 'RuntimeVersion'));
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,11 +8,12 @@ import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import Rpc from '@polkadot/rpc-core';
|
||||
import { Index, Moment, SessionIndex } from '@polkadot/types/interfaces';
|
||||
import { ClassOf } from '@polkadot/types';
|
||||
import { ClassOf, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { describeE2E } from '../../util';
|
||||
|
||||
const metadata = new Metadata(rpcMetadata);
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, rpcMetadata);
|
||||
|
||||
describeE2E({
|
||||
except: [
|
||||
@@ -25,7 +26,7 @@ describeE2E({
|
||||
|
||||
beforeEach((): void => {
|
||||
jest.setTimeout(30000);
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
rpc = new Rpc(registry, new WsProvider(wsUrl));
|
||||
});
|
||||
|
||||
it('subscribes to storage', (done): void => {
|
||||
@@ -38,8 +39,8 @@ describeE2E({
|
||||
expect(data).toHaveLength(2);
|
||||
expect(data).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.any(ClassOf('Index')),
|
||||
expect.any(ClassOf('Index'))
|
||||
expect.any(ClassOf(registry, 'Index')),
|
||||
expect.any(ClassOf(registry, 'Index'))
|
||||
])
|
||||
);
|
||||
|
||||
|
||||
@@ -4,20 +4,23 @@
|
||||
|
||||
import { Signer, SignerResult } from '@polkadot/api/types';
|
||||
import { KeyringPair } from '@polkadot/keyring/types';
|
||||
import { Registry, SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
|
||||
|
||||
import { createType } from '@polkadot/types';
|
||||
import { hexToU8a, u8aToHex } from '@polkadot/util';
|
||||
import { SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
|
||||
|
||||
let id = 0;
|
||||
|
||||
export class SingleAccountSigner implements Signer {
|
||||
private keyringPair: KeyringPair;
|
||||
|
||||
private registry: Registry;
|
||||
|
||||
private signDelay: number;
|
||||
|
||||
constructor (keyringPair: KeyringPair, signDelay = 0) {
|
||||
constructor (registry: Registry, keyringPair: KeyringPair, signDelay = 0) {
|
||||
this.keyringPair = keyringPair;
|
||||
this.registry = registry;
|
||||
this.signDelay = signDelay;
|
||||
}
|
||||
|
||||
@@ -28,7 +31,7 @@ export class SingleAccountSigner implements Signer {
|
||||
|
||||
return new Promise((resolve): void => {
|
||||
setTimeout((): void => {
|
||||
const signed = createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.keyringPair);
|
||||
const signed = createType(this.registry, 'ExtrinsicPayload', payload, { version: payload.version }).sign(this.keyringPair);
|
||||
|
||||
resolve({
|
||||
id: ++id,
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
|
||||
import { ClassOf, createType } from '@polkadot/types/codec/create';
|
||||
import { ClassOf, createType, TypeRegistry } from '@polkadot/types/codec/create';
|
||||
|
||||
import Decorated from './Decorated';
|
||||
import json from '../Metadata/static';
|
||||
|
||||
const decorated = new Decorated(json);
|
||||
const registry = new TypeRegistry();
|
||||
const decorated = new Decorated(registry, json);
|
||||
|
||||
describe('Decorated', () => {
|
||||
it('should correctly get Alice\'s freeBalance storage key (u8a)', (): void => {
|
||||
@@ -27,7 +26,7 @@ describe('Decorated', () => {
|
||||
|
||||
it('should return properly-encoded transactions', (): void => {
|
||||
expect(
|
||||
createType('Extrinsic', decorated.tx.timestamp.set([10101])).toU8a()
|
||||
createType(registry, 'Extrinsic', decorated.tx.timestamp.set([10101])).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([
|
||||
// length (encoded)
|
||||
@@ -43,7 +42,7 @@ describe('Decorated', () => {
|
||||
});
|
||||
|
||||
it('should return constants with the correct type and value', (): void => {
|
||||
expect(decorated.consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf('BlockNumber'));
|
||||
expect(decorated.consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf(registry, 'BlockNumber'));
|
||||
expect(decorated.consts.democracy.cooloffPeriod.toHex()).toEqual('0x000c4e00');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ModulesWithCalls } from '@polkadot/types/types';
|
||||
import { ModulesWithCalls, Registry } from '@polkadot/types/types';
|
||||
import { Constants, Storage } from './types';
|
||||
|
||||
import Metadata from '../Metadata';
|
||||
@@ -20,14 +20,19 @@ export default class Decorated {
|
||||
|
||||
public readonly metadata: Metadata;
|
||||
|
||||
public readonly registry: Registry;
|
||||
|
||||
public readonly query: Storage;
|
||||
|
||||
public readonly tx: ModulesWithCalls;
|
||||
|
||||
constructor (value?: Uint8Array | string | Metadata) {
|
||||
this.metadata = value instanceof Metadata ? value : new Metadata(value);
|
||||
this.tx = extrinsicsFromMeta(this.metadata);
|
||||
this.query = storageFromMeta(this.metadata);
|
||||
this.consts = constantsFromMeta(this.metadata);
|
||||
constructor (registry: Registry, value?: Uint8Array | string | Metadata) {
|
||||
this.registry = registry;
|
||||
this.metadata = value instanceof Metadata ? value : new Metadata(registry, value);
|
||||
|
||||
// decoration
|
||||
this.tx = extrinsicsFromMeta(registry, this.metadata);
|
||||
this.query = storageFromMeta(registry, this.metadata);
|
||||
this.consts = constantsFromMeta(registry, this.metadata);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,20 +2,19 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
|
||||
import { ClassOf, Metadata } from '@polkadot/types';
|
||||
import { ClassOf, Metadata, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import rpcMetadata from '../../../Metadata/static';
|
||||
import fromMetadata from '../fromMetadata';
|
||||
|
||||
// Use the pre-generated metadata
|
||||
const metadata = new Metadata(rpcMetadata);
|
||||
const consts = fromMetadata(metadata);
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, rpcMetadata);
|
||||
const consts = fromMetadata(registry, metadata);
|
||||
|
||||
describe('fromMetadata', (): void => {
|
||||
it('should return constants with the correct type and value', (): void => {
|
||||
expect(consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf('BlockNumber'));
|
||||
expect(consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf(registry, 'BlockNumber'));
|
||||
expect(consts.democracy.cooloffPeriod.toHex()).toEqual('0x000c4e00');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { Constants, ConstantCodec, ModuleConstants } from '../../types';
|
||||
|
||||
import { createTypeUnsafe } from '@polkadot/types/codec';
|
||||
@@ -14,7 +15,7 @@ import Metadata from '../../../Metadata';
|
||||
*
|
||||
* @param metadata - The metadata
|
||||
*/
|
||||
export default function fromMetadata (metadata: Metadata): Constants {
|
||||
export default function fromMetadata (registry: Registry, metadata: Metadata): Constants {
|
||||
return metadata.asLatest.modules.reduce((result: Constants, moduleMetadata): Constants => {
|
||||
if (moduleMetadata.constants.isEmpty) {
|
||||
return result;
|
||||
@@ -24,7 +25,7 @@ export default function fromMetadata (metadata: Metadata): Constants {
|
||||
|
||||
// For access, we change the index names, i.e. Democracy.EnactmentPeriod -> democracy.enactmentPeriod
|
||||
result[stringCamelCase(name.toString())] = moduleMetadata.constants.reduce((newModule: ModuleConstants, meta): ModuleConstants => {
|
||||
const codec = createTypeUnsafe(meta.type.toString(), [meta.value]);
|
||||
const codec = createTypeUnsafe(registry, meta.type.toString(), [meta.value]);
|
||||
|
||||
// This is not a perfect idea, however as it stands with number-only constants on the metadata
|
||||
// does not have any effect. However, this could become problematic in cases where items are
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Call, FunctionMetadataLatest } from '@polkadot/types/interfaces';
|
||||
import { CallFunction } from '@polkadot/types/types';
|
||||
import { Call } from '@polkadot/types/interfaces';
|
||||
import { AnyJsonObject, CallFunction, Registry, RegistryMetadataCall } from '@polkadot/types/types';
|
||||
|
||||
import { createType } from '@polkadot/types/codec';
|
||||
// we do a direct import here to remove all circular dependencies (importing from
|
||||
// /types, /types/codec or /types/codec/create makes all hell break loose)
|
||||
import { createType } from '@polkadot/types/codec/create/createType';
|
||||
import { assert, stringCamelCase } from '@polkadot/util';
|
||||
|
||||
/**
|
||||
@@ -17,12 +19,7 @@ import { assert, stringCamelCase } from '@polkadot/util';
|
||||
* @param methodIndex - Index of the method inside the section.
|
||||
* @param callMetadata - Metadata of the call function.
|
||||
*/
|
||||
export default function createDescriptor (
|
||||
section: string,
|
||||
sectionIndex: number,
|
||||
methodIndex: number,
|
||||
callMetadata: FunctionMetadataLatest
|
||||
): CallFunction {
|
||||
export default function createDescriptor (registry: Registry, section: string, sectionIndex: number, methodIndex: number, callMetadata: RegistryMetadataCall): CallFunction {
|
||||
const callIndex = new Uint8Array([sectionIndex, methodIndex]);
|
||||
const expectedArgs = callMetadata.args;
|
||||
const funcName = stringCamelCase(callMetadata.name.toString());
|
||||
@@ -32,7 +29,7 @@ export default function createDescriptor (
|
||||
`Extrinsic ${section}.${funcName} expects ${expectedArgs.length.valueOf()} arguments, got ${args.length}.`
|
||||
);
|
||||
|
||||
return createType('Call', {
|
||||
return createType(registry, 'Call', {
|
||||
args,
|
||||
callIndex
|
||||
}, callMetadata);
|
||||
@@ -42,7 +39,7 @@ export default function createDescriptor (
|
||||
extrinsicFn.meta = callMetadata;
|
||||
extrinsicFn.method = funcName;
|
||||
extrinsicFn.section = section;
|
||||
extrinsicFn.toJSON = (): any =>
|
||||
extrinsicFn.toJSON = (): string | AnyJsonObject =>
|
||||
callMetadata.toJSON();
|
||||
|
||||
return extrinsicFn as CallFunction;
|
||||
|
||||
@@ -2,16 +2,15 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
|
||||
import { createType, Metadata } from '@polkadot/types';
|
||||
import { createType, Metadata, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import json from '../../../Metadata/static';
|
||||
import fromMetadata from '.';
|
||||
|
||||
// Use the pre-generated metadata
|
||||
const metadata = new Metadata(json);
|
||||
const newExtrinsics = fromMetadata(metadata);
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, json);
|
||||
const newExtrinsics = fromMetadata(registry, metadata);
|
||||
|
||||
describe('fromMetadata', (): void => {
|
||||
it('should throw if an incorrect number of args is supplied', (): void => {
|
||||
@@ -24,7 +23,7 @@ describe('fromMetadata', (): void => {
|
||||
|
||||
it('should return properly-encoded transactions', (): void => {
|
||||
expect(
|
||||
createType('Extrinsic', newExtrinsics.timestamp.set([10101])).toU8a()
|
||||
createType(registry, 'Extrinsic', newExtrinsics.timestamp.set([10101])).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([
|
||||
// length (encoded)
|
||||
|
||||
@@ -2,12 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Calls, ModulesWithCalls } from '@polkadot/types/types';
|
||||
import { Calls, ModulesWithCalls, Registry, RegistryMetadata, RegistryMetadataModule } from '@polkadot/types/types';
|
||||
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import { ModuleMetadataV8 } from '../../../Metadata/v8/Metadata';
|
||||
import Metadata from '../../../Metadata';
|
||||
import extrinsics from '../';
|
||||
import createUnchecked from './createUnchecked';
|
||||
|
||||
@@ -16,16 +14,16 @@ import createUnchecked from './createUnchecked';
|
||||
*
|
||||
* @param metadata - The metadata
|
||||
*/
|
||||
export default function fromMetadata (metadata: Metadata): ModulesWithCalls {
|
||||
export default function fromMetadata (registry: Registry, metadata: RegistryMetadata): ModulesWithCalls {
|
||||
return metadata.asLatest.modules
|
||||
.filter(({ calls }): boolean => calls.isSome)
|
||||
.reduce((result, { calls, name }: ModuleMetadataV8, sectionIndex): ModulesWithCalls => {
|
||||
.reduce((result, { calls, name }: RegistryMetadataModule, sectionIndex): ModulesWithCalls => {
|
||||
const section = stringCamelCase(name.toString());
|
||||
|
||||
result[section] = calls.unwrap().reduce((newModule: Calls, callMetadata, methodIndex): Calls => {
|
||||
const method = stringCamelCase(callMetadata.name.toString());
|
||||
|
||||
newModule[method] = createUnchecked(section, sectionIndex, methodIndex, callMetadata);
|
||||
newModule[method] = createUnchecked(registry, section, sectionIndex, methodIndex, callMetadata);
|
||||
|
||||
return newModule;
|
||||
}, {});
|
||||
|
||||
@@ -2,29 +2,22 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ModulesWithCalls } from '@polkadot/types/types';
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import { createType, Metadata } from '@polkadot/types';
|
||||
import { createType, Metadata, TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import metadataStatic from '../../Metadata/static';
|
||||
import fromMetadata from './fromMetadata';
|
||||
|
||||
const keyring = testingPairs({ type: 'ed25519' }, false);
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, metadataStatic);
|
||||
const extrinsics = fromMetadata(registry, metadata);
|
||||
|
||||
describe('extrinsics', (): void => {
|
||||
let extrinsics: ModulesWithCalls;
|
||||
|
||||
beforeEach((): void => {
|
||||
extrinsics = fromMetadata(new Metadata(metadataStatic));
|
||||
});
|
||||
|
||||
it('encodes an actual transfer (actual data)', (): void => {
|
||||
expect(
|
||||
createType('Extrinsic',
|
||||
createType(registry, 'Extrinsic',
|
||||
extrinsics.balances.transfer(keyring.bob.publicKey, 6969)
|
||||
).sign(keyring.alice, {
|
||||
blockHash: '0xec7afaf1cca720ce88c1d1b689d81f0583cc15a97d621cf046dd9abf605ef22f',
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { StorageHasher, Text } from '@polkadot/types';
|
||||
import { StorageHasher, Text, TypeRegistry } from '@polkadot/types';
|
||||
import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
|
||||
import { stringToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import createFunction from './createFunction';
|
||||
|
||||
describe('createFunction', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('should create timestamp.now correctly', (): void => {
|
||||
expect(
|
||||
createFunction({
|
||||
createFunction(registry, {
|
||||
prefix: 'Timestamp',
|
||||
section: 'timestamp',
|
||||
method: 'Now',
|
||||
@@ -25,6 +27,7 @@ describe('createFunction', (): void => {
|
||||
it('allows overrides on key (keeping name)', (): void => {
|
||||
expect(
|
||||
createFunction(
|
||||
registry,
|
||||
{
|
||||
prefix: 'Substrate',
|
||||
section: 'substrate',
|
||||
@@ -44,6 +47,7 @@ describe('createFunction', (): void => {
|
||||
|
||||
expect(
|
||||
createFunction(
|
||||
registry,
|
||||
{
|
||||
prefix: 'Substrate',
|
||||
section: 'substrate',
|
||||
@@ -67,7 +71,7 @@ describe('createFunction', (): void => {
|
||||
let storageFn: StorageEntry;
|
||||
|
||||
beforeAll((): void => {
|
||||
storageFn = createFunction({
|
||||
storageFn = createFunction(registry, {
|
||||
prefix: 'GenericAsset',
|
||||
section: 'genericAsset',
|
||||
method: 'FreeBalance',
|
||||
@@ -76,11 +80,11 @@ describe('createFunction', (): void => {
|
||||
type: {
|
||||
isDoubleMap: true,
|
||||
asDoubleMap: {
|
||||
hasher: new StorageHasher('Blake2_256'),
|
||||
key1: new Text('AccountId'),
|
||||
key2: new Text('AccountId'),
|
||||
value: new Text('Balance'),
|
||||
key2Hasher: new Text('twox_128')
|
||||
hasher: new StorageHasher(registry, 'Blake2_256'),
|
||||
key1: new Text(registry, 'AccountId'),
|
||||
key2: new Text(registry, 'AccountId'),
|
||||
value: new Text(registry, 'Balance'),
|
||||
key2Hasher: new Text(registry, 'twox_128')
|
||||
}
|
||||
}
|
||||
} as any
|
||||
@@ -100,7 +104,7 @@ describe('createFunction', (): void => {
|
||||
});
|
||||
|
||||
it('allows creates double map function with a Null type key', (): void => {
|
||||
const storageFn = createFunction({
|
||||
const storageFn = createFunction(registry, {
|
||||
prefix: 'System',
|
||||
section: 'system',
|
||||
method: 'EventTopics',
|
||||
@@ -108,11 +112,11 @@ describe('createFunction', (): void => {
|
||||
type: {
|
||||
isDoubleMap: true,
|
||||
asDoubleMap: {
|
||||
hasher: new StorageHasher('Blake2_256'),
|
||||
key1: new Text('Null'),
|
||||
key2: new Text('Hash'),
|
||||
value: new Text('Vec<(BlockNumber,EventIndex)>'),
|
||||
key2Hasher: new Text('blake2_256')
|
||||
hasher: new StorageHasher(registry, 'Blake2_256'),
|
||||
key1: new Text(registry, 'Null'),
|
||||
key2: new Text(registry, 'Hash'),
|
||||
value: new Text(registry, 'Vec<(BlockNumber,EventIndex)>'),
|
||||
key2Hasher: new Text(registry, 'blake2_256')
|
||||
}
|
||||
}
|
||||
} as any
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Codec, Registry } from '@polkadot/types/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Compact, U8a, createType, createTypeUnsafe } from '@polkadot/types/codec';
|
||||
@@ -56,7 +56,7 @@ function getHashers ({ meta: { type } }: CreateItemFn): [HasherFunction, HasherF
|
||||
}
|
||||
|
||||
// create a key for a DoubleMap type
|
||||
function createKeyDoubleMap ({ meta: { name, type } }: CreateItemFn, rawKey: Uint8Array, args: [CreateArgType, CreateArgType], [hasher, key2Hasher]: [HasherFunction, HasherFunction?]): Uint8Array {
|
||||
function createKeyDoubleMap (registry: Registry, { meta: { name, type } }: CreateItemFn, rawKey: Uint8Array, args: [CreateArgType, CreateArgType], [hasher, key2Hasher]: [HasherFunction, HasherFunction?]): Uint8Array {
|
||||
// since we are passing an almost-unknown through, trust, but verify
|
||||
assert(
|
||||
Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]),
|
||||
@@ -66,25 +66,25 @@ function createKeyDoubleMap ({ meta: { name, type } }: CreateItemFn, rawKey: Uin
|
||||
const [key1, key2] = args;
|
||||
const type1 = type.asDoubleMap.key1.toString();
|
||||
const type2 = type.asDoubleMap.key2.toString();
|
||||
const param1Encoded = u8aConcat(rawKey, createTypeUnsafe(type1, [key1]).toU8a(true));
|
||||
const param1Encoded = u8aConcat(rawKey, createTypeUnsafe(registry, type1, [key1]).toU8a(true));
|
||||
const param1Hashed = hasher(param1Encoded);
|
||||
|
||||
// If this fails it means the getHashers function failed - and we have much bigger issues
|
||||
const param2Hashed = (key2Hasher as HasherFunction)(createTypeUnsafe(type2, [key2]).toU8a(true));
|
||||
const param2Hashed = (key2Hasher as HasherFunction)(createTypeUnsafe(registry, type2, [key2]).toU8a(true));
|
||||
|
||||
// as per createKey, always add the length prefix (underlying it is Bytes)
|
||||
return Compact.addLengthPrefix(u8aConcat(param1Hashed, param2Hashed));
|
||||
}
|
||||
|
||||
// create a key for either a map or a plain value
|
||||
function createKey ({ meta: { name, type } }: CreateItemFn, rawKey: Uint8Array, arg: CreateArgType, hasher: (value: Uint8Array) => Uint8Array): Uint8Array {
|
||||
function createKey (registry: Registry, { meta: { name, type } }: CreateItemFn, rawKey: Uint8Array, arg: CreateArgType, hasher: (value: Uint8Array) => Uint8Array): Uint8Array {
|
||||
let key = rawKey;
|
||||
|
||||
if (type.isMap) {
|
||||
assert(!isUndefined(arg) && !isNull(arg), `${name} is a Map and requires one argument`);
|
||||
|
||||
const mapType = type.asMap.key.toString();
|
||||
const param = createTypeUnsafe(mapType, [arg]).toU8a();
|
||||
const param = createTypeUnsafe(registry, mapType, [arg]).toU8a();
|
||||
|
||||
key = u8aConcat(key, param);
|
||||
}
|
||||
@@ -111,24 +111,24 @@ function expandWithMeta ({ meta, method, prefix, section }: CreateItemFn, storag
|
||||
}
|
||||
|
||||
// attch the head key hashing for linked maps
|
||||
function extendLinkedMap ({ meta: { documentation, name, type } }: CreateItemFn, storageFn: StorageEntry, stringKey: string, hasher: HasherFunction): StorageEntry {
|
||||
const headHash = new U8a(hasher(`head of ${stringKey}`));
|
||||
function extendLinkedMap (registry: Registry, { meta: { documentation, name, type } }: CreateItemFn, storageFn: StorageEntry, stringKey: string, hasher: HasherFunction): StorageEntry {
|
||||
const headHash = new U8a(registry, hasher(`head of ${stringKey}`));
|
||||
const headFn: any = (): U8a =>
|
||||
headHash;
|
||||
|
||||
// metadata with a fallback value using the type of the key, the normal
|
||||
// meta fallback only applies to actual entry values, create one for head
|
||||
headFn.meta = new StorageEntryMetadata({
|
||||
headFn.meta = new StorageEntryMetadata(registry, {
|
||||
name,
|
||||
modifier: createType('StorageEntryModifierLatest', 1), // required
|
||||
type: new StorageEntryType(createType('PlainTypeLatest', type.asMap.key), 0),
|
||||
fallback: createType('Bytes', createTypeUnsafe(type.asMap.key.toString()).toHex()),
|
||||
modifier: createType(registry, 'StorageEntryModifierLatest', 1), // required
|
||||
type: new StorageEntryType(registry, createType(registry, 'PlainTypeLatest', type.asMap.key), 0),
|
||||
fallback: createType(registry, 'Bytes', createTypeUnsafe(registry, type.asMap.key.toString()).toHex()),
|
||||
documentation
|
||||
});
|
||||
|
||||
// here we pass the section/method through as well - these are not on
|
||||
// the function itself, so specify these explicitly to the constructor
|
||||
storageFn.headKey = createType('StorageKey', headFn, {
|
||||
storageFn.headKey = createType(registry, 'StorageKey', headFn, {
|
||||
method: storageFn.method,
|
||||
section: `head of ${storageFn.section}`
|
||||
});
|
||||
@@ -146,7 +146,7 @@ function extendLinkedMap ({ meta: { documentation, name, type } }: CreateItemFn,
|
||||
* are not known at runtime (from state_getMetadata), they need to be supplied
|
||||
* by us manually at compile time.
|
||||
*/
|
||||
export default function createFunction (item: CreateItemFn, options: CreateItemOptions = {}): StorageEntry {
|
||||
export default function createFunction (registry: Registry, item: CreateItemFn, options: CreateItemOptions = {}): StorageEntry {
|
||||
const { meta: { type } } = item;
|
||||
const [stringKey, rawKey] = createKeys(item, options);
|
||||
const [hasher, key2Hasher] = getHashers(item);
|
||||
@@ -157,13 +157,13 @@ export default function createFunction (item: CreateItemFn, options: CreateItemO
|
||||
// For doublemap queries the params is passed in as an tuple, [key1, key2]
|
||||
const _storageFn = (arg?: CreateArgType | [CreateArgType?, CreateArgType?]): Uint8Array =>
|
||||
type.isDoubleMap
|
||||
? createKeyDoubleMap(item, rawKey, arg as [CreateArgType, CreateArgType], [hasher, key2Hasher])
|
||||
: createKey(item, rawKey, arg as CreateArgType, options.skipHashing ? NULL_HASHER : hasher);
|
||||
? createKeyDoubleMap(registry, item, rawKey, arg as [CreateArgType, CreateArgType], [hasher, key2Hasher])
|
||||
: createKey(registry, item, rawKey, arg as CreateArgType, options.skipHashing ? NULL_HASHER : hasher);
|
||||
|
||||
const storageFn = expandWithMeta(item, _storageFn as StorageEntry);
|
||||
|
||||
if (type.isMap && type.asMap.linked.isTrue) {
|
||||
extendLinkedMap(item, storageFn, stringKey, hasher);
|
||||
extendLinkedMap(registry, item, storageFn, stringKey, hasher);
|
||||
}
|
||||
|
||||
return storageFn;
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
import { u8aToHex } from '@polkadot/util';
|
||||
|
||||
import rpcMetadata from '../../../Metadata/static';
|
||||
import Decorated from '../../Decorated';
|
||||
|
||||
const registry = new TypeRegistry();
|
||||
const keyring = testingPairs({ type: 'ed25519' });
|
||||
const decorated = new Decorated(rpcMetadata);
|
||||
const decorated = new Decorated(registry, rpcMetadata);
|
||||
|
||||
describe('fromMetadata', (): void => {
|
||||
it('should throw if the storage function expects an argument', (): void => {
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { StorageHasher } from '@polkadot/types';
|
||||
import { StorageHasher, TypeRegistry } from '@polkadot/types';
|
||||
import { stringToU8a } from '@polkadot/util';
|
||||
import { xxhashAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import getHasher from './getHasher';
|
||||
|
||||
describe('getHasher', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
describe('Twox64Concat', (): void => {
|
||||
it('matches the foo test from Rust', (): void => {
|
||||
const hasher = getHasher(new StorageHasher('Twox64Concat'));
|
||||
const hasher = getHasher(new StorageHasher(registry, 'Twox64Concat'));
|
||||
const hash = hasher('foo');
|
||||
const xxhash = xxhashAsU8a('foo', 128);
|
||||
|
||||
|
||||
@@ -2,20 +2,21 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { ModuleStorage, Storage } from '../../types';
|
||||
|
||||
import { stringCamelCase, stringLowerFirst } from '@polkadot/util';
|
||||
|
||||
import Metadata from '../../../Metadata';
|
||||
import createFunction from './createFunction';
|
||||
import { storage } from './storage';
|
||||
import getStorage from './storage';
|
||||
|
||||
/**
|
||||
* Return an object with the modules and the functions to access their storage.
|
||||
*
|
||||
* @param metadata - The metadata
|
||||
*/
|
||||
export default function fromMetadata (metadata: Metadata): Storage {
|
||||
export default function fromMetadata (registry: Registry, metadata: Metadata): Storage {
|
||||
return metadata.asLatest.modules.reduce((result, moduleMetadata): Storage => {
|
||||
if (moduleMetadata.storage.isNone) {
|
||||
return result;
|
||||
@@ -30,7 +31,7 @@ export default function fromMetadata (metadata: Metadata): Storage {
|
||||
result[section] = unwrapped.items.reduce((newModule, meta): ModuleStorage => {
|
||||
const method = meta.name.toString();
|
||||
|
||||
newModule[stringLowerFirst(method)] = createFunction({
|
||||
newModule[stringLowerFirst(method)] = createFunction(metadata.registry, {
|
||||
meta,
|
||||
method,
|
||||
prefix,
|
||||
@@ -41,5 +42,5 @@ export default function fromMetadata (metadata: Metadata): Storage {
|
||||
}, {} as unknown as ModuleStorage);
|
||||
|
||||
return result;
|
||||
}, { ...storage });
|
||||
}, { ...getStorage(registry) });
|
||||
}
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { storage } from './storage';
|
||||
import getStorage from './storage';
|
||||
|
||||
describe('storage', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const storage = getStorage(registry);
|
||||
|
||||
it('should return well known keys', (): void => {
|
||||
expect(typeof storage.substrate).toBe('object');
|
||||
|
||||
|
||||
@@ -2,9 +2,20 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { Storage } from '../../types';
|
||||
|
||||
import * as substrate from './substrate';
|
||||
|
||||
export const storage: Storage = {
|
||||
substrate // Prefill storage with well known keys, as not returned by state_getMetadata
|
||||
};
|
||||
export default function getStorage (registry: Registry): Storage {
|
||||
return {
|
||||
substrate: Object
|
||||
.entries(substrate)
|
||||
.reduce((storage: Record<string, StorageEntry>, [key, fn]): Record<string, StorageEntry> => {
|
||||
(storage as any)[key] = fn(registry);
|
||||
|
||||
return storage;
|
||||
}, {})
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,40 +2,42 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import { authorityCount, authorityPrefix, changesTrieConfig, childStorageKeyPrefix, code, extrinsicIndex, heapPages } from './substrate';
|
||||
|
||||
describe('substrate', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
// @deprecated: The ':auth:' (authorityPrefix) and ':auth:len' (authorityCount) storage keys
|
||||
// have been removed in https://github.com/paritytech/substrate/pull/2802
|
||||
it('authorityCount should return the correct storage key', (): void => {
|
||||
expect(authorityCount()).toEqual(Uint8Array.from([36, 58, 97, 117, 116, 104, 58, 108, 101, 110])); // Length-prefixed
|
||||
expect(authorityCount(registry)()).toEqual(Uint8Array.from([36, 58, 97, 117, 116, 104, 58, 108, 101, 110])); // Length-prefixed
|
||||
});
|
||||
|
||||
it('authorityPrefix should return the correct storage key', (): void => {
|
||||
expect(authorityPrefix()).toEqual(Uint8Array.from([24, 58, 97, 117, 116, 104, 58])); // Length-prefixed
|
||||
expect(authorityPrefix(registry)()).toEqual(Uint8Array.from([24, 58, 97, 117, 116, 104, 58])); // Length-prefixed
|
||||
});
|
||||
|
||||
it('changesTrieConfig should return the correct storage key', (): void => {
|
||||
expect(changesTrieConfig()).toEqual(Uint8Array.from([52, 58, 99, 104, 97, 110, 103, 101, 115, 95, 116, 114, 105, 101])); // Length-prefixed
|
||||
expect(changesTrieConfig(registry)()).toEqual(Uint8Array.from([52, 58, 99, 104, 97, 110, 103, 101, 115, 95, 116, 114, 105, 101])); // Length-prefixed
|
||||
});
|
||||
|
||||
it('childStorageKeyPrefix should return the correct storage key', (): void => {
|
||||
expect(childStorageKeyPrefix()).toEqual(Uint8Array.from([60, 58, 99, 104, 105, 108, 100, 95, 115, 116, 111, 114, 97, 103, 101, 58])); // Length-prefixed
|
||||
expect(childStorageKeyPrefix(registry)()).toEqual(Uint8Array.from([60, 58, 99, 104, 105, 108, 100, 95, 115, 116, 111, 114, 97, 103, 101, 58])); // Length-prefixed
|
||||
});
|
||||
|
||||
it('code should return the correct storage key', (): void => {
|
||||
expect(code()).toEqual(Uint8Array.from([20, 58, 99, 111, 100, 101])); // Length-prefixed
|
||||
expect(code(registry)()).toEqual(Uint8Array.from([20, 58, 99, 111, 100, 101])); // Length-prefixed
|
||||
});
|
||||
|
||||
it('extrinsicIndex should return the correct storage key', (): void => {
|
||||
expect(extrinsicIndex()).toEqual(
|
||||
expect(extrinsicIndex(registry)()).toEqual(
|
||||
Uint8Array.from([64, 58, 101, 120, 116, 114, 105, 110, 115, 105, 99, 95, 105, 110, 100, 101, 120]) // Length-prefixed
|
||||
);
|
||||
});
|
||||
|
||||
it('heapPages should return the correct storage key', (): void => {
|
||||
expect(heapPages()).toEqual(Uint8Array.from([40, 58, 104, 101, 97, 112, 112, 97, 103, 101, 115])); // Length-prefixed
|
||||
expect(heapPages(registry)()).toEqual(Uint8Array.from([40, 58, 104, 101, 97, 112, 112, 97, 103, 101, 115])); // Length-prefixed
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
|
||||
import { createType } from '@polkadot/types/codec';
|
||||
import { StorageEntryMetadata, StorageEntryType } from '../../../Metadata/v8/Storage';
|
||||
@@ -14,24 +16,20 @@ interface SubstrateMetadata {
|
||||
}
|
||||
|
||||
// Small helper function to factorize code on this page.
|
||||
const createRuntimeFunction = (method: string, key: string, { documentation, type }: SubstrateMetadata): StorageEntry =>
|
||||
createFunction(
|
||||
{
|
||||
function createRuntimeFunction (method: string, key: string, { documentation, type }: SubstrateMetadata): (registry: Registry) => StorageEntry {
|
||||
return (registry: Registry): StorageEntry =>
|
||||
createFunction(registry, {
|
||||
meta: {
|
||||
documentation: createType('Vec<Text>', [documentation]),
|
||||
modifier: createType('StorageEntryModifierLatest', 1), // required
|
||||
type: new StorageEntryType(type, 0),
|
||||
documentation: createType(registry, 'Vec<Text>', [documentation]),
|
||||
modifier: createType(registry, 'StorageEntryModifierLatest', 1), // required
|
||||
type: new StorageEntryType(registry, type, 0),
|
||||
toJSON: (): any => key
|
||||
} as unknown as StorageEntryMetadata,
|
||||
method,
|
||||
prefix: 'Substrate',
|
||||
section: 'substrate'
|
||||
},
|
||||
{
|
||||
key,
|
||||
skipHashing: true
|
||||
}
|
||||
);
|
||||
}, { key, skipHashing: true });
|
||||
}
|
||||
|
||||
// @deprecated: The ':auth:' (authorityPrefix) and ':auth:len' (authorityCount) storage keys
|
||||
// have been removed in https://github.com/paritytech/substrate/pull/2802
|
||||
|
||||
@@ -2,6 +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 { storage } from './fromMetadata/storage';
|
||||
import getStorage from './fromMetadata/storage';
|
||||
|
||||
export default storage;
|
||||
export default getStorage;
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import MagicNumber, { MAGIC_NUMBER } from './MagicNumber';
|
||||
|
||||
describe('MagicNumber', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('succeeds when the magic number matches', (): void => {
|
||||
expect((): MagicNumber => new MagicNumber(MAGIC_NUMBER)).not.toThrow();
|
||||
expect((): MagicNumber => new MagicNumber(registry, MAGIC_NUMBER)).not.toThrow();
|
||||
});
|
||||
|
||||
it('fails when the magic number missmatches', (): void => {
|
||||
expect((): MagicNumber => new MagicNumber(0x12345)).toThrow(/MagicNumber/);
|
||||
it('fails when the magic number mismatches', (): void => {
|
||||
expect((): MagicNumber => new MagicNumber(registry, 0x12345)).toThrow(/MagicNumber/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,16 +2,20 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import U32 from '@polkadot/types/primitive/U32';
|
||||
|
||||
export const MAGIC_NUMBER = new U32(0x6174656d); // `meta`, reversed for Little Endian encoding
|
||||
export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding
|
||||
|
||||
export default class MagicNumber extends U32 {
|
||||
constructor (value?: any) {
|
||||
super(value);
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, value);
|
||||
|
||||
assert(this.eq(MAGIC_NUMBER), `MagicNumber mismatch: expected ${MAGIC_NUMBER.toHex()}, found ${this.toHex()}`);
|
||||
const magic = new U32(registry, MAGIC_NUMBER);
|
||||
|
||||
assert(this.eq(magic), `MagicNumber mismatch: expected ${magic.toHex()}, found ${this.toHex()}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { isHex, hexToU8a, u8aConcat } from '@polkadot/util';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { bnToU8a, isHex, hexToU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import { MAGIC_NUMBER } from './MagicNumber';
|
||||
import MetadataVersioned from './MetadataVersioned';
|
||||
@@ -13,20 +15,20 @@ import MetadataVersioned from './MetadataVersioned';
|
||||
* The versioned runtime metadata as a decoded structure
|
||||
*/
|
||||
export default class Metadata extends MetadataVersioned {
|
||||
constructor (value?: Uint8Array | string) {
|
||||
super(Metadata.decodeMetadata(value));
|
||||
constructor (registry: Registry, value?: Uint8Array | string) {
|
||||
super(registry, Metadata.decodeMetadata(registry, value));
|
||||
}
|
||||
|
||||
// first we try and parse using the versioned structure, if this does fail,
|
||||
// we adjust with the magic number and a manual version and re-try. As soon as
|
||||
// we remove support for V0, we will just do a new here
|
||||
private static decodeMetadata (_value: Uint8Array | string = new Uint8Array()): MetadataVersioned {
|
||||
private static decodeMetadata (registry: Registry, _value: Uint8Array | string = new Uint8Array()): MetadataVersioned {
|
||||
const value = isHex(_value)
|
||||
? hexToU8a(_value)
|
||||
: _value;
|
||||
|
||||
try {
|
||||
return new MetadataVersioned(value);
|
||||
return new MetadataVersioned(registry, value);
|
||||
} catch (error) {
|
||||
if (error.message.indexOf('MagicNumber mismatch') === -1) {
|
||||
throw error;
|
||||
@@ -34,8 +36,9 @@ export default class Metadata extends MetadataVersioned {
|
||||
}
|
||||
|
||||
return new MetadataVersioned(
|
||||
registry,
|
||||
u8aConcat(
|
||||
MAGIC_NUMBER.toU8a(), // manually add the magic number
|
||||
bnToU8a(MAGIC_NUMBER), // manually add the magic number
|
||||
Uint8Array.from([0]), // add the version for the original
|
||||
value // the actual data as retrieved
|
||||
)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { MetadataV0, MetadataV1 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
@@ -32,8 +33,8 @@ type MetaVersions = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
||||
type MetaAsX = 'asV0' | 'asV1' | 'asV2' | 'asV3' | 'asV4' | 'asV5' | 'asV6' | 'asV7';
|
||||
|
||||
class MetadataEnum extends Enum {
|
||||
constructor (value?: any, index?: number) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any, index?: number) {
|
||||
super(registry, {
|
||||
V0: 'MetadataV0', // once rolled-out, can replace this with MetadataDeprecated
|
||||
V1: 'MetadataV1', // once rolled-out, can replace this with MetadataDeprecated
|
||||
V2: MetadataV2, // once rolled-out, can replace this with MetadataDeprecated
|
||||
@@ -206,11 +207,13 @@ class MetadataEnum extends Enum {
|
||||
export default class MetadataVersioned extends Struct {
|
||||
private _converted: Map<number, MetaMapped> = new Map();
|
||||
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
magicNumber: MagicNumber,
|
||||
metadata: MetadataEnum
|
||||
}, value);
|
||||
|
||||
registry.setMetadata(this);
|
||||
}
|
||||
|
||||
private assertVersion (version: number): boolean {
|
||||
@@ -219,7 +222,7 @@ export default class MetadataVersioned extends Struct {
|
||||
return this.version === version;
|
||||
}
|
||||
|
||||
private getVersion<T extends MetaMapped, F extends MetaMapped> (version: MetaVersions, fromPrev: (input: F) => T): T {
|
||||
private getVersion<T extends MetaMapped, F extends MetaMapped> (version: MetaVersions, fromPrev: (registry: Registry, input: F) => T): T {
|
||||
const asCurr: MetaAsX = `asV${version}` as any;
|
||||
const asPrev: MetaAsX = `asV${version - 1}` as any;
|
||||
|
||||
@@ -228,7 +231,7 @@ export default class MetadataVersioned extends Struct {
|
||||
}
|
||||
|
||||
if (!this._converted.has(version)) {
|
||||
this._converted.set(version, fromPrev(this[asPrev] as F));
|
||||
this._converted.set(version, fromPrev(this.registry, this[asPrev] as F));
|
||||
}
|
||||
|
||||
return this._converted.get(version) as T;
|
||||
@@ -238,9 +241,9 @@ export default class MetadataVersioned extends Struct {
|
||||
* @description Returns the wrapped metadata as a limited calls-only (latest) version
|
||||
*/
|
||||
public get asCallsOnly (): MetadataVersioned {
|
||||
return new MetadataVersioned({
|
||||
return new MetadataVersioned(this.registry, {
|
||||
magicNumber: this.magicNumber,
|
||||
metadata: new MetadataEnum(toCallsOnly(this.asLatest), this.version)
|
||||
metadata: new MetadataEnum(this.registry, toCallsOnly(this.registry, this.asLatest), this.version)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -338,6 +341,6 @@ export default class MetadataVersioned extends Struct {
|
||||
}
|
||||
|
||||
public getUniqTypes (throwError: boolean): string[] {
|
||||
return getUniqTypes(this.asLatest, throwError);
|
||||
return getUniqTypes(this.registry, this.asLatest, throwError);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Codec, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { Option, Vec } from '@polkadot/types/codec';
|
||||
import { Text, Type } from '@polkadot/types/primitive';
|
||||
@@ -159,7 +159,7 @@ function getStorageNames ({ modules }: ExtractionMetadata): string[][][] {
|
||||
);
|
||||
}
|
||||
|
||||
export default function getUniqTypes (meta: ExtractionMetadata, throwError: boolean): string[] {
|
||||
export default function getUniqTypes (registry: Registry, meta: ExtractionMetadata, throwError: boolean): string[] {
|
||||
const types = flattenUniq([
|
||||
getCallNames(meta),
|
||||
getConstantNames(meta),
|
||||
@@ -167,7 +167,7 @@ export default function getUniqTypes (meta: ExtractionMetadata, throwError: bool
|
||||
getStorageNames(meta)
|
||||
]);
|
||||
|
||||
validateTypes(types, throwError);
|
||||
validateTypes(registry, types, throwError);
|
||||
|
||||
return types;
|
||||
}
|
||||
|
||||
@@ -2,13 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Codec, Registry } from '@polkadot/types/types';
|
||||
import { MetadataInterface } from '../types';
|
||||
|
||||
import { createTypeUnsafe } from '@polkadot/types/codec/create';
|
||||
import Call from '@polkadot/types/primitive/Generic/Call';
|
||||
|
||||
import getUniqTypes from './getUniqTypes';
|
||||
import Metadata from '../Metadata';
|
||||
@@ -17,13 +14,9 @@ import Metadata from '../Metadata';
|
||||
* Given the static `rpcData` and the `staticSubstrate` JSON file, Metadata
|
||||
* should decode `rpcData` and output `staticSubstrate`.
|
||||
*/
|
||||
export function decodeLatestSubstrate<Modules extends Codec> (
|
||||
version: number,
|
||||
rpcData: string,
|
||||
staticSubstrate: object
|
||||
): void {
|
||||
export function decodeLatestSubstrate<Modules extends Codec> (registry: Registry, version: number, rpcData: string, staticSubstrate: object): void {
|
||||
it('decodes latest substrate properly', (): void => {
|
||||
const metadata = new Metadata(rpcData);
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
|
||||
console.error(JSON.stringify(metadata.toJSON()));
|
||||
|
||||
@@ -37,15 +30,15 @@ export function decodeLatestSubstrate<Modules extends Codec> (
|
||||
* Given a `version`, MetadataLatest and MetadataV{version} should output the same
|
||||
* unique types.
|
||||
*/
|
||||
export function toLatest<Modules extends Codec> (version: number, rpcData: string): void {
|
||||
export function toLatest<Modules extends Codec> (registry: Registry, version: number, rpcData: string): void {
|
||||
it(`converts v${version} to v8`, (): void => {
|
||||
const metadata = new Metadata(rpcData)[`asV${version}` as keyof Metadata];
|
||||
const metadataV8 = new Metadata(rpcData).asLatest;
|
||||
const metadata = new Metadata(registry, rpcData)[`asV${version}` as keyof Metadata];
|
||||
const metadataV8 = new Metadata(registry, rpcData).asLatest;
|
||||
|
||||
expect(
|
||||
getUniqTypes(metadata as unknown as MetadataInterface<Modules>, true)
|
||||
getUniqTypes(registry, metadata as unknown as MetadataInterface<Modules>, true)
|
||||
).toEqual(
|
||||
getUniqTypes(metadataV8, true)
|
||||
getUniqTypes(registry, metadataV8, true)
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -53,11 +46,9 @@ export function toLatest<Modules extends Codec> (version: number, rpcData: strin
|
||||
/**
|
||||
* Given a Metadata, no type should throw when given its fallback value.
|
||||
*/
|
||||
export function defaultValues (rpcData: string): void {
|
||||
export function defaultValues (registry: Registry, rpcData: string): void {
|
||||
describe('storage with default values', (): void => {
|
||||
const metadata = new Metadata(rpcData);
|
||||
|
||||
Call.injectMetadata(metadata);
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
|
||||
metadata.asLatest.modules
|
||||
.filter(({ storage }): boolean => storage.isSome)
|
||||
@@ -65,7 +56,7 @@ export function defaultValues (rpcData: string): void {
|
||||
mod.storage.unwrap().items.forEach(({ fallback, name, type }): void => {
|
||||
it(`creates default types for ${mod.name}.${name}, type ${type}`, (): void => {
|
||||
expect(
|
||||
(): Codec => createTypeUnsafe(type.toString(), [fallback])
|
||||
(): Codec => createTypeUnsafe(registry, type.toString(), [fallback])
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import '@polkadot/types/injector';
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import staticData from '../static';
|
||||
import Metadata from '..';
|
||||
|
||||
describe('toCallsOnly', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('creates a calls-only version of the metadata', (): void => {
|
||||
const stripped = new Metadata(staticData).asCallsOnly;
|
||||
const stripped = new Metadata(registry, staticData).asCallsOnly;
|
||||
|
||||
console.error(JSON.stringify(stripped));
|
||||
|
||||
@@ -17,8 +19,8 @@ describe('toCallsOnly', (): void => {
|
||||
});
|
||||
|
||||
it('can serialize from the input', (): void => {
|
||||
const s1 = new Metadata(staticData).asCallsOnly.toU8a();
|
||||
const s2 = new Metadata(s1).asCallsOnly.toU8a();
|
||||
const s1 = new Metadata(registry, staticData).asCallsOnly.toU8a();
|
||||
const s2 = new Metadata(registry, s1).asCallsOnly.toU8a();
|
||||
|
||||
expect(s1).toEqual(s2);
|
||||
});
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AnyJsonObject, Registry } from '@polkadot/types/types';
|
||||
|
||||
import MetadataV8 from '../v8';
|
||||
|
||||
/**
|
||||
* @description Convert from MetadataV8 to a stripped representation of MetadataV8
|
||||
*/
|
||||
export default function toCallsOnly ({ modules }: MetadataV8): any {
|
||||
return new MetadataV8({
|
||||
export default function toCallsOnly (registry: Registry, { modules }: MetadataV8): AnyJsonObject | string {
|
||||
return new MetadataV8(registry, {
|
||||
// FIXME, this needs typing, not any
|
||||
modules: modules.map(({ calls, name }): any => ({
|
||||
name,
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { TypeDef, TypeDefInfo, TypeDefExtVecFixed } from '@polkadot/types/codec/types';
|
||||
|
||||
import { getTypeDef, getTypeRegistry } from '@polkadot/types/codec/create';
|
||||
import { getTypeDef } from '@polkadot/types/codec/create';
|
||||
|
||||
import flattenUniq from './flattenUniq';
|
||||
|
||||
@@ -36,10 +37,9 @@ function extractTypes (types: string[]): any[] {
|
||||
});
|
||||
}
|
||||
|
||||
export default function validateTypes (types: string[], throwError: boolean): void {
|
||||
const typeRegistry = getTypeRegistry();
|
||||
export default function validateTypes (registry: Registry, types: string[], throwError: boolean): void {
|
||||
const missing = flattenUniq(extractTypes(types)).filter((type): boolean =>
|
||||
!typeRegistry.hasType(type)
|
||||
!registry.hasType(type)
|
||||
);
|
||||
|
||||
if (missing.length !== 0) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { createType } from '@polkadot/types/codec';
|
||||
import { createType, TypeRegistry } from '@polkadot/types/codec';
|
||||
|
||||
import Metadata from '../';
|
||||
import latestSubstrateV0 from './static-substrate.json';
|
||||
@@ -10,15 +10,17 @@ import rpcData from './static';
|
||||
import { defaultValues, toLatest } from '../util/testUtil';
|
||||
|
||||
describe('Metadata', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('works with fallback', (): void => {
|
||||
const metadata = new Metadata(rpcData);
|
||||
const metadataV0 = createType('MetadataV0', rpcData);
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
const metadataV0 = createType(registry, 'MetadataV0', rpcData);
|
||||
|
||||
expect(metadata.asV0.toString()).toEqual(metadataV0.toString());
|
||||
});
|
||||
|
||||
it('decodes latest substrate properly', (): void => {
|
||||
const metadata = new Metadata(rpcData);
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
const json = metadata.asV0.toJSON();
|
||||
|
||||
console.error(JSON.stringify(json));
|
||||
@@ -28,7 +30,7 @@ describe('Metadata', (): void => {
|
||||
expect(json).toEqual(latestSubstrateV0);
|
||||
});
|
||||
|
||||
toLatest(0, rpcData);
|
||||
toLatest(registry, 0, rpcData);
|
||||
|
||||
defaultValues(rpcData);
|
||||
defaultValues(registry, rpcData);
|
||||
});
|
||||
|
||||
@@ -4,49 +4,50 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EventMetadataV1, FunctionMetadataV1, MetadataV0, MetadataV1, ModuleMetadataV1, RuntimeModuleMetadataV0, StorageFunctionMetadataV1 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { stringUpperFirst } from '@polkadot/util';
|
||||
|
||||
import { createType, Option, Vec } from '@polkadot/types/codec';
|
||||
import { Text } from '@polkadot/types/primitive';
|
||||
|
||||
function toV1Calls ({ module: { call: { functions } } }: RuntimeModuleMetadataV0): Option<FunctionMetadataV1> {
|
||||
function toV1Calls (registry: Registry, { module: { call: { functions } } }: RuntimeModuleMetadataV0): Option<FunctionMetadataV1> {
|
||||
return functions.length
|
||||
? new Option(Vec.with('FunctionMetadataV1'), functions)
|
||||
: new Option(Vec.with('FunctionMetadataV1'));
|
||||
? new Option(registry, Vec.with('FunctionMetadataV1'), functions)
|
||||
: new Option(registry, Vec.with('FunctionMetadataV1'));
|
||||
}
|
||||
|
||||
function toV1Events (metadataV0: MetadataV0, prefix: Text): Option<EventMetadataV1> {
|
||||
function toV1Events (registry: Registry, metadataV0: MetadataV0, prefix: Text): Option<EventMetadataV1> {
|
||||
const events = metadataV0.outerEvent.events.find((event): boolean => event[0].eq(prefix));
|
||||
|
||||
return events
|
||||
? new Option(Vec.with('EventMetadataV1'), events[1])
|
||||
: new Option(Vec.with('EventMetadataV1'));
|
||||
? new Option(registry, Vec.with('EventMetadataV1'), events[1])
|
||||
: new Option(registry, Vec.with('EventMetadataV1'));
|
||||
}
|
||||
|
||||
function toV1Storage ({ storage }: RuntimeModuleMetadataV0): Option<StorageFunctionMetadataV1> {
|
||||
function toV1Storage (registry: Registry, { storage }: RuntimeModuleMetadataV0): Option<StorageFunctionMetadataV1> {
|
||||
return storage.isSome
|
||||
? new Option('Vec<StorageFunctionMetadataV1>', storage.unwrap().functions)
|
||||
: new Option('Vec<StorageFunctionMetadataV1>');
|
||||
? new Option(registry, 'Vec<StorageFunctionMetadataV1>', storage.unwrap().functions)
|
||||
: new Option(registry, 'Vec<StorageFunctionMetadataV1>');
|
||||
}
|
||||
|
||||
/**
|
||||
* Function that converts MetadataV0 to MetadataV1
|
||||
*/
|
||||
export default function toV1 (metadataV0: MetadataV0): MetadataV1 {
|
||||
return createType('MetadataV1', {
|
||||
export default function toV1 (registry: Registry, metadataV0: MetadataV0): MetadataV1 {
|
||||
return createType(registry, 'MetadataV1', {
|
||||
modules: metadataV0.modules.map((mod): ModuleMetadataV1 => {
|
||||
// The prefix of this module (capitalized)
|
||||
const prefix = mod.storage.isSome
|
||||
? mod.storage.unwrap().prefix.toString()
|
||||
: stringUpperFirst(mod.prefix.toString()); // If this module doesn't have storage, we just assume the prefix is the name capitalized
|
||||
|
||||
return createType('ModuleMetadataV1', {
|
||||
return createType(registry, 'ModuleMetadataV1', {
|
||||
name: mod.prefix, // Not capitalized
|
||||
prefix, // Capitalized
|
||||
storage: toV1Storage(mod),
|
||||
calls: toV1Calls(mod),
|
||||
events: toV1Events(metadataV0, mod.prefix)
|
||||
storage: toV1Storage(registry, mod),
|
||||
calls: toV1Calls(registry, mod),
|
||||
events: toV1Events(registry, metadataV0, mod.prefix)
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import staticSubstrate from './static-substrate.json';
|
||||
import rpcData from './static';
|
||||
import { decodeLatestSubstrate, defaultValues, toLatest } from '../util/testUtil';
|
||||
|
||||
describe('MetadataV1', (): void => {
|
||||
decodeLatestSubstrate(1, rpcData, staticSubstrate);
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
toLatest(1, rpcData);
|
||||
decodeLatestSubstrate(registry, 1, rpcData, staticSubstrate);
|
||||
|
||||
defaultValues(rpcData);
|
||||
toLatest(registry, 1, rpcData);
|
||||
|
||||
defaultValues(registry, rpcData);
|
||||
});
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { MetadataV1 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import MetadataV2 from '../v2';
|
||||
|
||||
export default function toV2 (metadataV1: MetadataV1): MetadataV2 {
|
||||
return new MetadataV2(metadataV1);
|
||||
export default function toV2 (registry: Registry, metadataV1: MetadataV1): MetadataV2 {
|
||||
return new MetadataV2(registry, metadataV1);
|
||||
}
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import staticSubstrate from './static-substrate.json';
|
||||
import rpcData from './static';
|
||||
import { decodeLatestSubstrate, defaultValues, toLatest } from '../util/testUtil';
|
||||
|
||||
describe('MetadataV2', (): void => {
|
||||
decodeLatestSubstrate(2, rpcData, staticSubstrate);
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
toLatest(2, rpcData);
|
||||
decodeLatestSubstrate(registry, 2, rpcData, staticSubstrate);
|
||||
|
||||
defaultValues(rpcData);
|
||||
toLatest(registry, 2, rpcData);
|
||||
|
||||
defaultValues(registry, rpcData);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EventMetadataV2, FunctionMetadataV2 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { MetadataInterface } from '../types';
|
||||
|
||||
import Option from '@polkadot/types/codec/Option';
|
||||
@@ -18,8 +19,8 @@ import { StorageFunctionMetadata } from './Storage';
|
||||
* The definition of a module in the system
|
||||
*/
|
||||
export class ModuleMetadataV2 extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
prefix: 'Text',
|
||||
storage: Option.with(Vec.with(StorageFunctionMetadata)),
|
||||
@@ -70,8 +71,8 @@ export class ModuleMetadataV2 extends Struct {
|
||||
* The runtime metadata as a decoded structure
|
||||
*/
|
||||
export default class MetadataV2 extends Struct implements MetadataInterface<ModuleMetadataV2> {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
modules: Vec.with(ModuleMetadataV2)
|
||||
}, value);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { MapTypeV2, PlainTypeV2, StorageFunctionModifierV2 } from '@polkadot/types/interfaces/metadata';
|
||||
import { AnyNumber } from '@polkadot/types/types';
|
||||
import { AnyNumber, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
@@ -14,8 +14,8 @@ import Bytes from '@polkadot/types/primitive/Bytes';
|
||||
import Text from '@polkadot/types/primitive/Text';
|
||||
|
||||
export class StorageFunctionType extends Enum {
|
||||
constructor (value?: any, index?: number) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any, index?: number) {
|
||||
super(registry, {
|
||||
Type: 'PlainTypeV2',
|
||||
Map: 'MapTypeV2'
|
||||
}, value, index);
|
||||
@@ -83,8 +83,8 @@ export interface StorageFunctionMetadataValue {
|
||||
* The definition of a storage function
|
||||
*/
|
||||
export class StorageFunctionMetadata extends Struct {
|
||||
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: StorageFunctionMetadataValue | Uint8Array) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
modifier: 'StorageFunctionModifierV2',
|
||||
type: StorageFunctionType,
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import MetadataV2 from './Metadata';
|
||||
import MetadataV3 from '../v3';
|
||||
|
||||
export default function toV3 (metadataV2: MetadataV2): MetadataV3 {
|
||||
return new MetadataV3(metadataV2);
|
||||
export default function toV3 (registry: Registry, metadataV2: MetadataV2): MetadataV3 {
|
||||
return new MetadataV3(registry, metadataV2);
|
||||
}
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import staticSubstrate from './static-substrate.json';
|
||||
import rpcData from './static';
|
||||
import { decodeLatestSubstrate, defaultValues, toLatest } from '../util/testUtil';
|
||||
|
||||
describe('MetadataV3', (): void => {
|
||||
decodeLatestSubstrate(3, rpcData, staticSubstrate);
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
toLatest(3, rpcData);
|
||||
decodeLatestSubstrate(registry, 3, rpcData, staticSubstrate);
|
||||
|
||||
defaultValues(rpcData);
|
||||
toLatest(registry, 3, rpcData);
|
||||
|
||||
defaultValues(registry, rpcData);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EventMetadataV3, FunctionMetadataV3 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { MetadataInterface } from '../types';
|
||||
|
||||
import Option from '@polkadot/types/codec/Option';
|
||||
@@ -18,8 +19,8 @@ import { StorageFunctionMetadata } from './Storage';
|
||||
* The definition of a module in the system
|
||||
*/
|
||||
export class ModuleMetadataV3 extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
prefix: 'Text',
|
||||
storage: Option.with(Vec.with(StorageFunctionMetadata)),
|
||||
@@ -70,8 +71,8 @@ export class ModuleMetadataV3 extends Struct {
|
||||
* The runtime metadata as a decoded structure
|
||||
*/
|
||||
export default class MetadataV3 extends Struct implements MetadataInterface<ModuleMetadataV3> {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
modules: Vec.with(ModuleMetadataV3)
|
||||
}, value);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { DoubleMapTypeV3, MapTypeV3, PlainTypeV3, StorageFunctionModifierV3 } from '@polkadot/types/interfaces/metadata';
|
||||
import { AnyNumber } from '@polkadot/types/types';
|
||||
import { AnyNumber, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
@@ -14,8 +14,8 @@ import Bytes from '@polkadot/types/primitive/Bytes';
|
||||
import Text from '@polkadot/types/primitive/Text';
|
||||
|
||||
export class StorageFunctionType extends Enum {
|
||||
constructor (value?: any, index?: number) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any, index?: number) {
|
||||
super(registry, {
|
||||
Type: 'PlainTypeV3',
|
||||
Map: 'MapTypeV3',
|
||||
DoubleMap: 'DoubleMapTypeV3'
|
||||
@@ -104,8 +104,8 @@ export interface StorageFunctionMetadataValue {
|
||||
* The definition of a storage function
|
||||
*/
|
||||
export class StorageFunctionMetadata extends Struct {
|
||||
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: StorageFunctionMetadataValue | Uint8Array) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
modifier: 'StorageFunctionModifierV3',
|
||||
type: StorageFunctionType,
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import StorageHasher from '@polkadot/types/primitive/StorageHasher';
|
||||
import { createType, Option, Vec } from '@polkadot/types/codec';
|
||||
|
||||
@@ -14,7 +16,7 @@ import { StorageFunctionMetadata as StorageFunctionMetadataV3 } from './Storage'
|
||||
/**
|
||||
* Convert V3 StorageFunction to V4 StorageFunction
|
||||
*/
|
||||
function toV4StorageFunction (storageFn: StorageFunctionMetadataV3): StorageFunctionMetadata {
|
||||
function toV4StorageFunction (registry: Registry, storageFn: StorageFunctionMetadataV3): StorageFunctionMetadata {
|
||||
const { documentation, fallback, modifier, name, type } = storageFn;
|
||||
|
||||
// Convert the old type to the new type: there is one new field
|
||||
@@ -23,26 +25,26 @@ function toV4StorageFunction (storageFn: StorageFunctionMetadataV3): StorageFunc
|
||||
const [newType, index] = type.isPlainType
|
||||
? [type, 0]
|
||||
: type.isMap
|
||||
? [createType('MapTypeV4', {
|
||||
hasher: new StorageHasher('Twox128'),
|
||||
? [createType(registry, 'MapTypeV4', {
|
||||
hasher: new StorageHasher(registry, 'Twox128'),
|
||||
key: type.asMap.key,
|
||||
value: type.asMap.value,
|
||||
linked: type.asMap.linked
|
||||
}), 1]
|
||||
: [createType('DoubleMapTypeV4', {
|
||||
hasher: new StorageHasher('Twox128'),
|
||||
: [createType(registry, 'DoubleMapTypeV4', {
|
||||
hasher: new StorageHasher(registry, 'Twox128'),
|
||||
key1: type.asDoubleMap.key1,
|
||||
key2: type.asDoubleMap.key2,
|
||||
value: type.asDoubleMap.value,
|
||||
key2Hasher: type.asDoubleMap.key2Hasher
|
||||
}), 2];
|
||||
|
||||
return new StorageFunctionMetadata({
|
||||
return new StorageFunctionMetadata(registry, {
|
||||
documentation,
|
||||
fallback,
|
||||
name,
|
||||
modifier,
|
||||
type: new StorageFunctionType(newType, index)
|
||||
type: new StorageFunctionType(registry, newType, index)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,16 +52,20 @@ function toV4StorageFunction (storageFn: StorageFunctionMetadataV3): StorageFunc
|
||||
* Convert from MetadataV3 to MetadataV4
|
||||
* See https://github.com/paritytech/substrate/pull/2268 for details
|
||||
*/
|
||||
export default function toV4 ({ modules }: MetadataV3): MetadataV4 {
|
||||
return new MetadataV4({
|
||||
export default function toV4 (registry: Registry, { modules }: MetadataV3): MetadataV4 {
|
||||
return new MetadataV4(registry, {
|
||||
modules: modules.map(({ calls, events, name, prefix, storage }): ModuleMetadataV4 =>
|
||||
new ModuleMetadataV4({
|
||||
new ModuleMetadataV4(registry, {
|
||||
calls,
|
||||
events,
|
||||
name,
|
||||
prefix,
|
||||
storage: storage.isSome
|
||||
? new Option(Vec.with(StorageFunctionMetadata), storage.unwrap().map(toV4StorageFunction))
|
||||
? new Option(
|
||||
registry,
|
||||
Vec.with(StorageFunctionMetadata),
|
||||
storage.unwrap().map((v): StorageFunctionMetadata => toV4StorageFunction(registry, v))
|
||||
)
|
||||
: undefined
|
||||
})
|
||||
)
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import staticSubstrate from './static-substrate.json';
|
||||
import rpcData from './static';
|
||||
import { decodeLatestSubstrate, defaultValues, toLatest } from '../util/testUtil';
|
||||
|
||||
describe('MetadataV4', (): void => {
|
||||
decodeLatestSubstrate(4, rpcData, staticSubstrate);
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
toLatest(4, rpcData);
|
||||
decodeLatestSubstrate(registry, 4, rpcData, staticSubstrate);
|
||||
|
||||
defaultValues(rpcData);
|
||||
toLatest(registry, 4, rpcData);
|
||||
|
||||
defaultValues(registry, rpcData);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EventMetadataV4, FunctionMetadataV4 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { MetadataInterface } from '../types';
|
||||
|
||||
import Option from '@polkadot/types/codec/Option';
|
||||
@@ -17,8 +18,8 @@ import { StorageFunctionMetadata } from './Storage';
|
||||
* The definition of a module in the system
|
||||
*/
|
||||
export class ModuleMetadataV4 extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
prefix: 'Text',
|
||||
storage: Option.with(Vec.with(StorageFunctionMetadata)),
|
||||
@@ -69,8 +70,8 @@ export class ModuleMetadataV4 extends Struct {
|
||||
* The runtime metadata as a decoded structure
|
||||
*/
|
||||
export default class MetadataV4 extends Struct implements MetadataInterface<ModuleMetadataV4> {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
modules: Vec.with(ModuleMetadataV4)
|
||||
}, value);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { DoubleMapTypeV4, MapTypeV4, PlainTypeV4, StorageFunctionModifierV4 } from '@polkadot/types/interfaces/metadata';
|
||||
import { AnyNumber } from '@polkadot/types/types';
|
||||
import { AnyNumber, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
@@ -14,8 +14,8 @@ import Bytes from '@polkadot/types/primitive/Bytes';
|
||||
import Text from '@polkadot/types/primitive/Text';
|
||||
|
||||
export class StorageFunctionType extends Enum {
|
||||
constructor (value?: any, index?: number) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any, index?: number) {
|
||||
super(registry, {
|
||||
Type: 'PlainTypeV4',
|
||||
Map: 'MapTypeV4',
|
||||
DoubleMap: 'DoubleMapTypeV4'
|
||||
@@ -104,8 +104,8 @@ export interface StorageFunctionMetadataValue {
|
||||
* The definition of a storage function
|
||||
*/
|
||||
export class StorageFunctionMetadata extends Struct {
|
||||
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: StorageFunctionMetadataValue | Uint8Array) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
modifier: 'StorageFunctionModifierV4',
|
||||
type: StorageFunctionType,
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { createType, Option, Vec } from '@polkadot/types/codec';
|
||||
@@ -21,37 +23,37 @@ const hasherMap: Map<string, string> = new Map([
|
||||
['twox_64_concat', 'Twox64Concat']
|
||||
]);
|
||||
|
||||
function toStorageHasher (text: Text): StorageHasher {
|
||||
function toStorageHasher (registry: Registry, text: Text): StorageHasher {
|
||||
const mapped = hasherMap.get(text.toString());
|
||||
|
||||
assert(mapped, `Invalid Storage hasher: ${text.toString()}`);
|
||||
|
||||
return new StorageHasher(mapped);
|
||||
return new StorageHasher(registry, mapped);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert V4 StorageFunction to V5 StorageFunction
|
||||
*/
|
||||
function toV5StorageFunction (storageFn: StorageFunctionMetadataV4): StorageFunctionMetadata {
|
||||
function toV5StorageFunction (registry: Registry, storageFn: StorageFunctionMetadataV4): StorageFunctionMetadata {
|
||||
const { documentation, fallback, modifier, name, type } = storageFn;
|
||||
const [newType, index] = type.isPlainType
|
||||
? [type, 0]
|
||||
: type.isMap
|
||||
? [type.asMap, 1]
|
||||
: [createType('DoubleMapTypeV5', {
|
||||
: [createType(registry, 'DoubleMapTypeV5', {
|
||||
hasher: type.asDoubleMap.hasher,
|
||||
key1: type.asDoubleMap.key1,
|
||||
key2: type.asDoubleMap.key2,
|
||||
value: type.asDoubleMap.value,
|
||||
key2Hasher: toStorageHasher(type.asDoubleMap.key2Hasher)
|
||||
key2Hasher: toStorageHasher(registry, type.asDoubleMap.key2Hasher)
|
||||
}), 2];
|
||||
|
||||
return new StorageFunctionMetadata({
|
||||
return new StorageFunctionMetadata(registry, {
|
||||
documentation,
|
||||
fallback,
|
||||
name,
|
||||
modifier,
|
||||
type: new StorageFunctionType(newType, index)
|
||||
type: new StorageFunctionType(registry, newType, index)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -59,14 +61,18 @@ function toV5StorageFunction (storageFn: StorageFunctionMetadataV4): StorageFunc
|
||||
* Convert from MetadataV4 to MetadataV5
|
||||
* See https://github.com/paritytech/substrate/pull/2836/files for details
|
||||
*/
|
||||
export default function toV5 ({ modules }: MetadataV4): MetadataV5 {
|
||||
return new MetadataV5({
|
||||
export default function toV5 (registry: Registry, { modules }: MetadataV4): MetadataV5 {
|
||||
return new MetadataV5(registry, {
|
||||
modules: modules.map(({ calls, events, name, prefix, storage }): ModuleMetadataV5 =>
|
||||
new ModuleMetadataV5({
|
||||
new ModuleMetadataV5(registry, {
|
||||
name,
|
||||
prefix,
|
||||
storage: storage.isSome
|
||||
? new Option(Vec.with(StorageFunctionMetadata), storage.unwrap().map(toV5StorageFunction))
|
||||
? new Option(
|
||||
registry,
|
||||
Vec.with(StorageFunctionMetadata),
|
||||
storage.unwrap().map((v): StorageFunctionMetadata => toV5StorageFunction(registry, v))
|
||||
)
|
||||
: undefined,
|
||||
calls,
|
||||
events
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import polkadotJson from './static-polkadot.json';
|
||||
import substrateJson from './static-substrate.json';
|
||||
import polkadotData from './static.polkadot';
|
||||
@@ -9,17 +11,21 @@ import substrateData from './static';
|
||||
import { decodeLatestSubstrate, defaultValues, toLatest } from '../util/testUtil';
|
||||
|
||||
describe('MetadataV5 (substrate)', (): void => {
|
||||
decodeLatestSubstrate(5, substrateData, substrateJson);
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
toLatest(5, substrateData);
|
||||
decodeLatestSubstrate(registry, 5, substrateData, substrateJson);
|
||||
|
||||
defaultValues(substrateData);
|
||||
toLatest(registry, 5, substrateData);
|
||||
|
||||
defaultValues(registry, substrateData);
|
||||
});
|
||||
|
||||
describe('MetadataV5 (polkadot)', (): void => {
|
||||
decodeLatestSubstrate(5, polkadotData, polkadotJson);
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
toLatest(5, polkadotData);
|
||||
decodeLatestSubstrate(registry, 5, polkadotData, polkadotJson);
|
||||
|
||||
defaultValues(polkadotData);
|
||||
toLatest(registry, 5, polkadotData);
|
||||
|
||||
defaultValues(registry, polkadotData);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EventMetadataV5, FunctionMetadataV5 } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { MetadataInterface } from '../types';
|
||||
|
||||
import Option from '@polkadot/types/codec/Option';
|
||||
@@ -17,8 +18,8 @@ import { StorageFunctionMetadata } from './Storage';
|
||||
* The definition of a module in the system
|
||||
*/
|
||||
export class ModuleMetadataV5 extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
name: 'Text',
|
||||
prefix: 'Text',
|
||||
storage: Option.with(Vec.with(StorageFunctionMetadata)),
|
||||
@@ -69,8 +70,8 @@ export class ModuleMetadataV5 extends Struct {
|
||||
* The runtime metadata as a decoded structure
|
||||
*/
|
||||
export default class MetadataV5 extends Struct implements MetadataInterface<ModuleMetadataV5> {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
constructor (registry: Registry, value?: any) {
|
||||
super(registry, {
|
||||
modules: Vec.with(ModuleMetadataV5)
|
||||
}, value);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user