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:
Jaco Greeff
2019-11-21 16:32:39 +01:00
committed by GitHub
co-authored by Amaury Martiny
parent 099992627b
commit 011e24bd49
269 changed files with 2495 additions and 2126 deletions
+10 -5
View File
@@ -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
+4 -8
View File
@@ -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();
+5 -5
View File
@@ -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);
}
/**
+9 -7
View File
@@ -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);
}
+9 -7
View File
@@ -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(
-259
View File
@@ -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);
})
);
}
}
+262
View File
@@ -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);
};
}
+6 -1
View File
@@ -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'>;
+10 -9
View File
@@ -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 -3
View File
@@ -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
+6 -4
View File
@@ -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,