Return additional error information from decodeU8a (#3540)

This commit is contained in:
Jaco
2021-05-18 12:57:48 +02:00
committed by GitHub
parent 83650b8f28
commit 4e81bbc43c
3 changed files with 24 additions and 10 deletions
+7
View File
@@ -1,5 +1,12 @@
# CHANGELOG
## master
Changes:
- Return additional error information from internal u8a decoding failures
## 4.10.1 May 17, 2021
Upgrade priority: Medium. Recommended for uses of Polkadot/Kusama 9010 runtimes.
+4 -3
View File
@@ -99,12 +99,13 @@ function decodeStructFromObject <T> (registry: Registry, Types: ConstructorDef,
*/
function decodeStruct <T> (registry: Registry, Types: ConstructorDef, value: unknown, jsonMap: Map<any, string>): T {
if (isHex(value)) {
return decodeStruct(registry, Types, hexToU8a(value as string), jsonMap);
return decodeStruct(registry, Types, hexToU8a(value.toString()), jsonMap);
} else if (isU8a(value)) {
const values = decodeU8a(registry, value, Object.values(Types));
const keys = Object.keys(Types);
const values = decodeU8a(registry, value, Object.values(Types), keys);
// Transform array of values to {key: value} mapping
return Object.keys(Types).reduce((raw, key, index): T => {
return keys.reduce((raw, key, index): T => {
// TS2322: Type 'Codec' is not assignable to type 'T[keyof S]'.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(raw as any)[key] = values[index];
+13 -7
View File
@@ -10,18 +10,24 @@ import type { Codec, Constructor, Registry } from '../../types';
* @param u8a - The u8a to decode.
* @param types - The array of Constructor to decode the U8a against.
*/
export function decodeU8a (registry: Registry, u8a: Uint8Array, _types: Constructor[] | { [index: string]: Constructor }): Codec[] {
const types = Array.isArray(_types)
? _types
: Object.values(_types);
export function decodeU8a (registry: Registry, u8a: Uint8Array, _types: Constructor[] | { [index: string]: Constructor }, _keys?: string[]): Codec[] {
const [types, keys]: [Constructor<Codec>[], string[]] = Array.isArray(_types)
? [_types, _keys || []]
: [Object.values(_types), Object.keys(_types)];
const result: Codec[] = [];
let offset = 0;
for (let i = 0; i < types.length; i++) {
const value = new types[i](registry, u8a.subarray(offset));
const Type = types[i];
result.push(value);
offset += value.encodedLength;
try {
const value = new Type(registry, u8a.subarray(offset));
result.push(value);
offset += value.encodedLength;
} catch (error) {
throw new Error(`decodeU8a: failed on ${keys[i] ? `${keys[i]}: ` : ''}${new Type(registry).toRawType()}:: ${(error as Error).message}`);
}
}
return result;