Rewrite yarn.lock (#2127)

This commit is contained in:
Jaco Greeff
2020-04-01 23:49:56 +02:00
committed by GitHub
parent 1f97c5e9e3
commit 58de0b8b9c
37 changed files with 172 additions and 154 deletions
@@ -109,13 +109,16 @@ export default class ContractRegistry extends MetaRegistry {
public createMessage (name: string, message: Partial<ContractABIMessage> & ContractABIMessageBase): ContractABIFn {
const args = message.args.map(({ name, type }): ContractABIFnArg => {
assert(isObject(type), `Invalid type at index ${type}`);
return {
name: stringCamelCase(name),
type
};
});
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}`);
@@ -136,6 +139,7 @@ export default class ContractRegistry extends MetaRegistry {
fn.args = args;
fn.isConstant = !(message.mutates || false);
fn.type = message.returnType || null;
return fn;
}
@@ -152,6 +156,7 @@ export default class ContractRegistry extends MetaRegistry {
public convertType ({ display_name: displayNameIndices, ty }: ContractABITypePre): TypeDef {
const displayName = this.stringsAt(displayNameIndices).join('::');
return this.typeDefAt(ty, { displayName });
}
@@ -240,6 +240,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
const type = displayType(this.typeDefFromMetaTypeAt(vecTypeIndex));
assert(type && type.length > 0, `MetaRegistry: Invalid builtin Vec type found at index ${typeIndex}`);
return {
@@ -256,6 +257,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
const type = displayType(this.typeDefFromMetaTypeAt(vecTypeIndex));
assert(type && type.length > 0, `MetaRegistry: Invalid vector type found at index ${typeIndex}`);
return {
@@ -272,8 +274,10 @@ export default class MetaRegistry extends MetadataRegistryLookup {
switch (name) {
case 'Option':
return this.typeDefForOption(id, typeIndex);
case 'Result':
return this.typeDefForResult(id, typeIndex);
default: {
const sub = def['enum.variants'].map((variant) => this.typeDefForEnumVariant(variant));
+1
View File
@@ -49,6 +49,7 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : nameOrIndex}`);
const fn = this.abi.messages[def.name] || this.abi.messages[stringCamelCase(def.name)];
return { def, fn, index };
}
}
+1
View File
@@ -77,6 +77,7 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
const methodName = _methodName as keyof typeof section;
// Not sure what to do here, casting as any. Though the final types are good
const method = (section[methodName] as any)(api);
// idem
(sectionAcc as any)[methodName] = method;
@@ -44,6 +44,7 @@ function parseActive (id: ParaId, active: Active): DeriveParachainActive | null
)
};
}
return null;
}
@@ -21,5 +21,6 @@ export function approvalFlagsToBools (flags: Vec<ApprovalFlag> | ApprovalFlag[])
// slice off trailing "false" values, as in substrate
const lastApproval: number = bools.lastIndexOf(true);
return lastApproval >= 0 ? bools.slice(0, lastApproval + 1) : [];
}
+5
View File
@@ -31,11 +31,13 @@ async function derive (api: ApiPromise): Promise<void> {
});
const fees = await api.derive.balances.fees();
console.log('fees', fees);
}
async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
const intentions = await api.query.staking.bonded();
console.log('intentions:', intentions);
// api.query.*.* is well-typed
@@ -47,6 +49,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
// It's hard to correctly type .multi. Expected: `Balance[]`, actual: Codec[].
// In the meantime, we can case with `<Balance>` (this is not available on recent chains)
const multi = await api.query.balances.freeBalance.multi<Balance>([keyring.alice.address, keyring.bob.address]);
console.log('query types:', bar, bal, bal2, override, oldBal, multi);
// check multi for unsub
@@ -71,6 +74,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
// at queries
const events = await api.query.system.events.at('0x12345');
console.log(`Received ${events.length} events:`);
// check entries()
@@ -82,6 +86,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
// check range types
const entries = await api.query.system.events.range(['0x12345', '0x7890']);
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`)}`);
}
+2
View File
@@ -56,7 +56,9 @@ describe('ApiPromise', (): void => {
const specVersion = 0;
const metadata: any = {};
const key = `${genesisHash}-${specVersion}`;
metadata[key] = rpcData;
const api = await ApiPromise.create({ metadata, provider, registry } as ApiOptions);
expect(api.genesisHash).toBeDefined();
+1
View File
@@ -37,6 +37,7 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Cod
// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once
function promiseTracker (resolve: (value: () => void) => void, reject: (value: Error) => void): Tracker {
let isCompleted = false;
const complete = (fn: Function, value: any): void => {
if (!isCompleted) {
isCompleted = true;
+1
View File
@@ -20,6 +20,7 @@ export default function filterEvents (extHash: H256, { block: { extrinsics, head
if (status.isInBlock) {
l.warn(`block ${header.hash}: Unable to find extrinsic ${myHash} inside ${allHashes}`);
}
return;
}
@@ -12,6 +12,7 @@ export default function createDescriptor (registry: Registry, section: string, s
const callIndex = new Uint8Array([sectionIndex, methodIndex]);
const expectedArgs = callMetadata.args;
const funcName = stringCamelCase(callMetadata.name.toString());
const extrinsicFn = (...args: any[]): Call => {
assert(
expectedArgs.length.valueOf() === args.length,
@@ -95,6 +95,7 @@ describe('createFunction', (): void => {
it('should return correct key', (): void => {
const result = storageFn(['5DXUeE5N5LtkW97F2PzqYPyqNkxqSWESdGSPTX6AvkUAhwKP', '5DXUeE5N5LtkW97F2PzqYPyqNkxqSWESdGSPTX6AvkUAhwKP']);
expect(u8aToHex(result)).toEqual('0xc000fa40e72d7173e69ee54b980345ea01cb81e64258502e0247af4303dee91ec0aec2ecd3a60ab080cff7b52a8f6d543b');
});
+5
View File
@@ -172,6 +172,7 @@ export default class Rpc implements RpcInterface {
private createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod {
const rpcName = `${section}_${method}`;
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
// Here, logically, it should be `of(this.formatInputs(method, values))`.
// However, formatInputs can throw, and when it does, the above way
@@ -226,10 +227,12 @@ export default class Rpc implements RpcInterface {
const subName = `${section}_${subMethod}`;
const unsubName = `${section}_${unsubMethod}`;
const subType = `${section}_${updateType}`;
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
return new Observable((observer: Observer<any>): VoidCallback => {
// Have at least an empty promise, as used in the unsubscribe
let subscriptionPromise: Promise<number | void> = Promise.resolve();
const errorHandler = (error: Error): void => {
logErrorMessage(method, def, error);
@@ -239,9 +242,11 @@ export default class Rpc implements RpcInterface {
try {
const params = this.formatInputs(def, values);
const paramsJson = params.map((param): AnyJson => param.toJSON());
const update = (error?: Error | null, result?: any): void => {
if (error) {
logErrorMessage(method, def, error);
return;
}
+1
View File
@@ -41,6 +41,7 @@ describe('replay', (): void => {
it('replay(1) works as expected', (done): void => {
const observable = rpc.system.chain();
let a: string | undefined;
observable.subscribe((value: any): void => { a = value; });
setTimeout((): void => {
+2
View File
@@ -9,6 +9,7 @@ import { drr } from './drr';
describe('drr', (): void => {
it('should not fire twice the same value', (done): void => {
let count = 0;
of(1, 1).pipe(drr()).subscribe((): void => { ++count; });
setTimeout((): void => {
@@ -19,6 +20,7 @@ describe('drr', (): void => {
it('should be a ReplaySubject(1)', (done): void => {
const obs = timer(0, 100).pipe(drr()); // Starts at 0, increments every 100ms
obs.subscribe(); // Fire the observable
// Subscribe another time after some time, i.e. after the observable has fired
+1
View File
@@ -86,6 +86,7 @@ export default class HttpProvider implements ProviderInterface {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void {
l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
return (): void => {
// noop
};
+1
View File
@@ -104,6 +104,7 @@ export default class Mock implements ProviderInterface {
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void {
this.emitter.on(type, sub);
return (): void => {
this.emitter.removeListener(type, sub);
};
@@ -18,6 +18,7 @@ describe('on', (): void => {
it('it emits both connected and disconnected events', (done): void => {
const events: Record<string, boolean> = { connected: false, disconnected: false };
const handler = (type: ProviderInterfaceEmitted): void => {
mock.on(type, (): void => {
events[type] = true;
+3
View File
@@ -182,6 +182,7 @@ export default class WsProvider implements WSProviderInterface {
try {
const json = this.#coder.encodeJson(method, params);
const id = this.#coder.getId();
const callback = (error?: Error | null, result?: any): void => {
error
? reject(error)
@@ -299,6 +300,7 @@ export default class WsProvider implements WSProviderInterface {
if (!handler) {
l.debug((): string => `Unable to find handler for id=${response.id}`);
return;
}
@@ -341,6 +343,7 @@ export default class WsProvider implements WSProviderInterface {
this.#waitingForId[subId] = response;
l.debug((): string => `Unable to find handler for subscription=${subId}`);
return;
}
+1
View File
@@ -87,6 +87,7 @@ export default function main (): void {
websocket.onclose = onSocketClose;
websocket.onerror = onSocketError;
websocket.onopen = onSocketOpen;
websocket.onmessage = (message: any): void => {
generate(JSON.parse(message.data).result, pkg, output, isStrict);
};
+1
View File
@@ -51,6 +51,7 @@ function documentationVecToMarkdown (docLines: Vec<Text>, indent = 0): string {
.replace(/^# <\/weight>$/g, '\n\n\\# \\</weight>')
.replace(/^#{1,3} /, '#### ')} `
, '');
// prefix each line with indentation
return md && md.split('\n\n').map((line) => `${' '.repeat(indent)}${line}`).join('\n\n');
}
+1
View File
@@ -80,6 +80,7 @@ export function getSimilarTypes (definitions: object, registry: Registry, _type:
if (type === 'Extrinsic') {
setImports(definitions, imports, ['IExtrinsic']);
return ['IExtrinsic'];
} else if (type === 'StorageKey') {
// TODO We can do better
+11
View File
@@ -173,19 +173,23 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatCompact(formatType(definitions, (typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Option: {
setImports(definitions, imports, ['Option']);
return formatOption(formatType(definitions, (typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Plain: {
return typeDef.type;
}
case TypeDefInfo.Vec: {
setImports(definitions, imports, ['Vec']);
return formatVec(formatType(definitions, (typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Tuple: {
setImports(definitions, imports, ['ITuple']);
@@ -195,6 +199,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
.map((sub): string => formatType(definitions, sub.type, imports)))
);
}
case TypeDefInfo.VecFixed: {
const type = (typeDef.sub as TypeDef).type;
@@ -208,6 +213,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatVec(formatType(definitions, type, imports));
}
case TypeDefInfo.BTreeMap: {
setImports(definitions, imports, ['BTreeMap']);
@@ -215,6 +221,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatBTreeMap(formatType(definitions, keyDef.type, imports), formatType(definitions, valDef.type, imports));
}
case TypeDefInfo.BTreeSet: {
setImports(definitions, imports, ['BTreeSet']);
@@ -222,6 +229,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatBTreeSet(formatType(definitions, valDef.type, imports));
}
case TypeDefInfo.HashMap: {
setImports(definitions, imports, ['HashMap']);
@@ -229,6 +237,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatHashMap(formatType(definitions, keyDef.type, imports), formatType(definitions, valDef.type, imports));
}
case TypeDefInfo.Linkage: {
const type = (typeDef.sub as TypeDef).type;
@@ -236,6 +245,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatLinkage(formatType(definitions, type, imports));
}
case TypeDefInfo.Result: {
setImports(definitions, imports, ['Result']);
@@ -243,6 +253,7 @@ export function formatType (definitions: object, type: string | TypeDef, imports
return formatResult(formatType(definitions, okDef.type, imports), formatType(definitions, errorDef.type, imports));
}
default: {
throw new Error(`Cannot format ${JSON.stringify(type)}`);
}
@@ -38,6 +38,7 @@ describe('BTreeMap', (): void => {
placeholder: U32,
value: 'BTreeMap<Text, U32>' as any
});
s.set('value', new (BTreeMap.with(Text, U32))(registry, mockU32TextMap));
expect(s.toString()).toBe('{"placeholder":0,"value":{"bazzing":69}}');
});
@@ -13,10 +13,12 @@ import BTreeSet from './BTreeSet';
const registry = new TypeRegistry();
const mockU32Set = new Set<U32>();
mockU32Set.add(new U32(registry, 2));
mockU32Set.add(new U32(registry, 24));
mockU32Set.add(new U32(registry, 30));
mockU32Set.add(new U32(registry, 80));
const mockU32SetString = '[2,24,30,80]';
const mockU32SetObject = [2, 24, 30, 80];
const mockU32SetHexString = '0x1002000000180000001e00000050000000';
@@ -44,6 +46,7 @@ describe('BTreeSet', (): void => {
const testEncode = (to: CodecTo, expected: any): void =>
it(`can encode ${to}`, (): void => {
const s = new BTreeSet(registry, U32, mockU32Set);
expect(s[to]()).toEqual(expected);
});
@@ -74,6 +77,7 @@ describe('BTreeSet', (): void => {
placeholder: U32,
value: BTreeSet.with(U32)
});
s.set('value', new BTreeSet(registry, U32, mockU32Set));
expect(s.toString()).toBe('{"placeholder":0,"value":[2,24,30,80]}');
});
+6
View File
@@ -11,17 +11,21 @@ import CodecMap from './Map';
const registry = new TypeRegistry();
const mockU32TextMap = new Map<Text, U32>();
mockU32TextMap.set(new Text(registry, 'bazzing'), new U32(registry, 69));
const mockU32TextMapString = '{"bazzing":69}';
const mockU32TextMapObject = { bazzing: 69 };
const mockU32TextMapHexString = '0x041c62617a7a696e6745000000';
const mockU32TextMapUint8Array = Uint8Array.from([4, 28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]);
const mockU32U32Map = new Map<U32, U32>();
mockU32U32Map.set(new U32(registry, 1), new U32(registry, 2));
mockU32U32Map.set(new U32(registry, 23), new U32(registry, 24));
mockU32U32Map.set(new U32(registry, 28), new U32(registry, 30));
mockU32U32Map.set(new U32(registry, 45), new U32(registry, 80));
const mockU32U32MapString = '{"1":2,"23":24,"28":30,"45":80}';
const mockU32U32MapObject = { 1: 2, 23: 24, 28: 30, 45: 80 };
const mockU32U32MapHexString = '0x10043102000000083233180000000832381e00000008343550000000';
@@ -49,6 +53,7 @@ describe('CodecMap', (): void => {
const testEncode = (to: CodecTo, expected: any): void =>
it(`can encode ${to}`, (): void => {
const s = new CodecMap(registry, 'BTreeMap', Text, U32, mockU32TextMap);
expect(s[to]()).toEqual(expected);
});
@@ -62,6 +67,7 @@ describe('CodecMap', (): void => {
const testEncode = (to: CodecTo, expected: any): void =>
it(`can encode ${to}`, (): void => {
const s = new CodecMap(registry, 'BTreeMap', Text, U32, mockU32U32Map);
expect(s[to]()).toEqual(expected);
});
+4
View File
@@ -22,6 +22,7 @@ describe('Struct', (): void => {
foo: Text,
bar: U32
}, input);
expect([...s.keys()]).toEqual(['foo', 'bar']);
expect(
[...s.values()].map((v): string =>
@@ -43,6 +44,7 @@ describe('Struct', (): void => {
foo: Text,
bar: U32
}, { foo: 'bazzing', bar: 69 });
expect(s[to]()).toEqual(expected);
});
@@ -81,6 +83,7 @@ describe('Struct', (): void => {
bar: Text
}))
}, { foo: [{ bar: 1 }, { bar: 2 }] });
expect(s.toString()).toBe('{"foo":[{"bar":"1"},{"bar":"2"}]}');
});
@@ -94,6 +97,7 @@ describe('Struct', (): void => {
foo: U32,
bar: U32
}, input);
expect(s.toString()).toEqual('{"txt":"fubar","foo":0,"bar":0}');
});
+1
View File
@@ -34,6 +34,7 @@ describe('Tuple', (): void => {
Text,
U32
], input);
expect(
t.toJSON()
).toEqual(['bazzing', 69]);
+1
View File
@@ -51,6 +51,7 @@ export default class Tuple extends AbstractArray<Codec> {
return Types.map((Type, index): Codec => {
try {
if (value?.[index] instanceof Type) return value[index] as any;
return new Type(registry, value?.[index]);
} catch (error) {
throw new Error(`Tuple: failed on ${index}:: ${error.message}`);
+1
View File
@@ -12,6 +12,7 @@ function isNotNested (...counters: number[]): boolean {
export function typeSplit (type: string): string[] {
let [cDepth, fDepth, sDepth, tDepth, start] = [0, 0, 0, 0, 0];
const result = [];
const extract = (index: number): void => {
if (isNotNested(cDepth, fDepth, sDepth, tDepth)) {
result.push(type.substr(start, index - start).trim());
@@ -76,7 +76,9 @@ export class MortalEra extends Tuple {
private static decodeMortalObject (registry: Registry, value: MortalMethod): MortalEraValue {
const { current, period } = value;
let calPeriod = Math.pow(2, Math.ceil(Math.log2(period)));
calPeriod = Math.min(Math.max(calPeriod, 4), 1 << 16);
const phase = current % calPeriod;
const quantizeFactor = Math.max(calPeriod >> 12, 1);
const quantizedPhase = phase / quantizeFactor * quantizeFactor;
@@ -30,6 +30,7 @@ describe('AccountId', (): void => {
const testDecode = (type: string, input: Uint8Array | string | AccountId, expected: string): void =>
it(`can decode from ${type}`, (): void => {
const a = registry.createType('AccountId', input);
expect(a.toString()).toBe(expected);
});
@@ -13,6 +13,7 @@ describe('Address', (): void => {
const testDecode = (type: string, input: Address | AccountId | AccountIndex | number[] | Uint8Array, expected: string): void =>
it(`can decode from ${type}`, (): void => {
const a = registry.createType('Address', input);
expect(a.toString()).toBe(expected);
});
@@ -98,6 +99,7 @@ describe('Address', (): void => {
const testEncode = (to: 'toHex' | 'toString' | 'toU8a', expected: string | Uint8Array): void =>
it(`can encode ${to}`, (): void => {
const a = registry.createType('Address', '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF');
expect(a[to]()).toEqual(expected);
});
+1
View File
@@ -32,6 +32,7 @@ function getArgsDef (registry: Registry, meta: FunctionMetadataLatest): ArgsDef
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return Call.filterOrigin(meta).reduce((result, { name, type }): ArgsDef => {
const Type = getTypeClass(registry, getTypeDef(type.toString()));
result[name.toString()] = Type;
return result;