@polkadot/types-create
Advanced tools
Comparing version 9.14.2 to 10.0.1
@@ -1,7 +0,4 @@ | ||
// Copyright 2017-2023 @polkadot/types-codec authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
export { packageInfo } from "./packageInfo.js"; | ||
export { TypeDefInfo } from "./types/index.js"; | ||
export * from "./create/index.js"; | ||
export * from "./util/index.js"; | ||
export { packageInfo } from './packageInfo.js'; | ||
export { TypeDefInfo } from './types/index.js'; | ||
export * from './create/index.js'; | ||
export * from './util/index.js'; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
var _exportNames = { | ||
packageInfo: true, | ||
TypeDefInfo: true | ||
}; | ||
Object.defineProperty(exports, "TypeDefInfo", { | ||
enumerable: true, | ||
get: function () { | ||
return _types.TypeDefInfo; | ||
} | ||
}); | ||
Object.defineProperty(exports, "packageInfo", { | ||
enumerable: true, | ||
get: function () { | ||
return _packageInfo.packageInfo; | ||
} | ||
}); | ||
var _packageInfo = require("./packageInfo"); | ||
var _types = require("./types"); | ||
var _create = require("./create"); | ||
Object.keys(_create).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; | ||
if (key in exports && exports[key] === _create[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _create[key]; | ||
} | ||
}); | ||
}); | ||
var _util = require("./util"); | ||
Object.keys(_util).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; | ||
if (key in exports && exports[key] === _util[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _util[key]; | ||
} | ||
}); | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.TypeDefInfo = exports.packageInfo = void 0; | ||
const tslib_1 = require("tslib"); | ||
var packageInfo_1 = require("./packageInfo"); | ||
Object.defineProperty(exports, "packageInfo", { enumerable: true, get: function () { return packageInfo_1.packageInfo; } }); | ||
var types_1 = require("./types"); | ||
Object.defineProperty(exports, "TypeDefInfo", { enumerable: true, get: function () { return types_1.TypeDefInfo; } }); | ||
tslib_1.__exportStar(require("./create"), exports); | ||
tslib_1.__exportStar(require("./util"), exports); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.constructTypeClass = constructTypeClass; | ||
exports.createClassUnsafe = createClassUnsafe; | ||
exports.getTypeClass = getTypeClass; | ||
var _typesCodec = require("@polkadot/types-codec"); | ||
var _util = require("@polkadot/util"); | ||
var _types = require("../types"); | ||
var _getTypeDef = require("../util/getTypeDef"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
function getTypeDefType(_ref) { | ||
let { | ||
lookupName, | ||
type | ||
} = _ref; | ||
return lookupName || type; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.createClassUnsafe = exports.getTypeClass = exports.constructTypeClass = void 0; | ||
const types_codec_1 = require("@polkadot/types-codec"); | ||
const util_1 = require("@polkadot/util"); | ||
const types_1 = require("../types"); | ||
const getTypeDef_1 = require("../util/getTypeDef"); | ||
function getTypeDefType({ lookupName, type }) { | ||
return lookupName || type; | ||
} | ||
function getSubDefArray(value) { | ||
if (!Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef[] in ${(0, _util.stringify)(value)}`); | ||
} | ||
return value.sub; | ||
if (!Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef[] in ${(0, util_1.stringify)(value)}`); | ||
} | ||
return value.sub; | ||
} | ||
function getSubDef(value) { | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef in ${(0, _util.stringify)(value)}`); | ||
} | ||
return value.sub; | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef in ${(0, util_1.stringify)(value)}`); | ||
} | ||
return value.sub; | ||
} | ||
function getSubType(value) { | ||
return getTypeDefType(getSubDef(value)); | ||
return getTypeDefType(getSubDef(value)); | ||
} | ||
// create a maps of type string CodecClasss from the input | ||
function getTypeClassMap(value) { | ||
const subs = getSubDefArray(value); | ||
const map = {}; | ||
for (let i = 0; i < subs.length; i++) { | ||
map[subs[i].name] = getTypeDefType(subs[i]); | ||
} | ||
return map; | ||
const subs = getSubDefArray(value); | ||
const map = {}; | ||
for (let i = 0; i < subs.length; i++) { | ||
map[subs[i].name] = getTypeDefType(subs[i]); | ||
} | ||
return map; | ||
} | ||
// create an array of type string CodecClasss from the input | ||
function getTypeClassArray(value) { | ||
return getSubDefArray(value).map(getTypeDefType); | ||
return getSubDefArray(value).map(getTypeDefType); | ||
} | ||
function createInt(Clazz, _ref2) { | ||
let { | ||
displayName, | ||
length | ||
} = _ref2; | ||
if (!(0, _util.isNumber)(length)) { | ||
throw new Error(`Expected bitLength information for ${displayName || Clazz.constructor.name}<bitLength>`); | ||
} | ||
return Clazz.with(length, displayName); | ||
function createInt(Clazz, { displayName, length }) { | ||
if (!(0, util_1.isNumber)(length)) { | ||
throw new Error(`Expected bitLength information for ${displayName || Clazz.constructor.name}<bitLength>`); | ||
} | ||
return Clazz.with(length, displayName); | ||
} | ||
function createHashMap(Clazz, value) { | ||
const [keyType, valueType] = getTypeClassArray(value); | ||
return Clazz.with(keyType, valueType); | ||
const [keyType, valueType] = getTypeClassArray(value); | ||
return Clazz.with(keyType, valueType); | ||
} | ||
function createWithSub(Clazz, value) { | ||
return Clazz.with(getSubType(value)); | ||
return Clazz.with(getSubType(value)); | ||
} | ||
const infoMapping = { | ||
[_types.TypeDefInfo.BTreeMap]: (registry, value) => createHashMap(_typesCodec.BTreeMap, value), | ||
[_types.TypeDefInfo.BTreeSet]: (registry, value) => createWithSub(_typesCodec.BTreeSet, value), | ||
[_types.TypeDefInfo.Compact]: (registry, value) => createWithSub(_typesCodec.Compact, value), | ||
[_types.TypeDefInfo.DoNotConstruct]: (registry, value) => _typesCodec.DoNotConstruct.with(value.displayName || value.type), | ||
[_types.TypeDefInfo.Enum]: (registry, value) => { | ||
const subs = getSubDefArray(value); | ||
return _typesCodec.Enum.with(subs.every(_ref3 => { | ||
let { | ||
type | ||
} = _ref3; | ||
return type === 'Null'; | ||
}) ? subs.reduce((out, _ref4, count) => { | ||
let { | ||
index, | ||
name | ||
} = _ref4; | ||
out[name] = index || count; | ||
return out; | ||
}, {}) : getTypeClassMap(value)); | ||
}, | ||
[_types.TypeDefInfo.HashMap]: (registry, value) => createHashMap(_typesCodec.HashMap, value), | ||
[_types.TypeDefInfo.Int]: (registry, value) => createInt(_typesCodec.Int, value), | ||
// We have circular deps between Linkage & Struct | ||
[_types.TypeDefInfo.Linkage]: (registry, value) => { | ||
const type = `Option<${getSubType(value)}>`; | ||
// eslint-disable-next-line sort-keys | ||
const Clazz = _typesCodec.Struct.with({ | ||
previous: type, | ||
next: type | ||
}); | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
Clazz.prototype.toRawType = function () { | ||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call | ||
return `Linkage<${this.next.toRawType(true)}>`; | ||
}; | ||
return Clazz; | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[_types.TypeDefInfo.Null]: (registry, _) => _typesCodec.Null, | ||
[_types.TypeDefInfo.Option]: (registry, value) => { | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error('Expected type information for Option'); | ||
} | ||
// NOTE This is opt-in (unhandled), not by default | ||
// if (value.sub.type === 'bool') { | ||
// return OptionBool; | ||
// } | ||
return createWithSub(_typesCodec.Option, value); | ||
}, | ||
[_types.TypeDefInfo.Plain]: (registry, value) => registry.getOrUnknown(value.type), | ||
[_types.TypeDefInfo.Range]: (registry, value) => createWithSub(_typesCodec.Range, value), | ||
[_types.TypeDefInfo.RangeInclusive]: (registry, value) => createWithSub(_typesCodec.RangeInclusive, value), | ||
[_types.TypeDefInfo.Result]: (registry, value) => { | ||
const [Ok, Err] = getTypeClassArray(value); | ||
// eslint-disable-next-line @typescript-eslint/no-use-before-define | ||
return _typesCodec.Result.with({ | ||
Err, | ||
Ok | ||
}); | ||
}, | ||
[_types.TypeDefInfo.Set]: (registry, value) => _typesCodec.CodecSet.with(getSubDefArray(value).reduce((result, _ref5) => { | ||
let { | ||
index, | ||
name | ||
} = _ref5; | ||
result[name] = index; | ||
return result; | ||
}, {}), value.length), | ||
[_types.TypeDefInfo.Si]: (registry, value) => getTypeClass(registry, registry.lookup.getTypeDef(value.type)), | ||
[_types.TypeDefInfo.Struct]: (registry, value) => _typesCodec.Struct.with(getTypeClassMap(value), value.alias), | ||
[_types.TypeDefInfo.Tuple]: (registry, value) => _typesCodec.Tuple.with(getTypeClassArray(value)), | ||
[_types.TypeDefInfo.UInt]: (registry, value) => createInt(_typesCodec.UInt, value), | ||
[_types.TypeDefInfo.Vec]: (registry, _ref6) => { | ||
let { | ||
sub | ||
} = _ref6; | ||
if (!sub || Array.isArray(sub)) { | ||
throw new Error('Expected type information for vector'); | ||
} | ||
return sub.type === 'u8' ? _typesCodec.Bytes : _typesCodec.Vec.with(getTypeDefType(sub)); | ||
}, | ||
[_types.TypeDefInfo.VecFixed]: (registry, _ref7) => { | ||
let { | ||
displayName, | ||
length, | ||
sub | ||
} = _ref7; | ||
if (!(0, _util.isNumber)(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Expected length & type information for fixed vector'); | ||
} | ||
return sub.type === 'u8' ? _typesCodec.U8aFixed.with(length * 8, displayName) : _typesCodec.VecFixed.with(getTypeDefType(sub), length); | ||
}, | ||
[_types.TypeDefInfo.WrapperKeepOpaque]: (registry, value) => createWithSub(_typesCodec.WrapperKeepOpaque, value), | ||
[_types.TypeDefInfo.WrapperOpaque]: (registry, value) => createWithSub(_typesCodec.WrapperOpaque, value) | ||
[types_1.TypeDefInfo.BTreeMap]: (registry, value) => createHashMap(types_codec_1.BTreeMap, value), | ||
[types_1.TypeDefInfo.BTreeSet]: (registry, value) => createWithSub(types_codec_1.BTreeSet, value), | ||
[types_1.TypeDefInfo.Compact]: (registry, value) => createWithSub(types_codec_1.Compact, value), | ||
[types_1.TypeDefInfo.DoNotConstruct]: (registry, value) => types_codec_1.DoNotConstruct.with(value.displayName || value.type), | ||
[types_1.TypeDefInfo.Enum]: (registry, value) => { | ||
const subs = getSubDefArray(value); | ||
return types_codec_1.Enum.with(subs.every(({ type }) => type === 'Null') | ||
? subs.reduce((out, { index, name }, count) => { | ||
out[name] = index || count; | ||
return out; | ||
}, {}) | ||
: getTypeClassMap(value)); | ||
}, | ||
[types_1.TypeDefInfo.HashMap]: (registry, value) => createHashMap(types_codec_1.HashMap, value), | ||
[types_1.TypeDefInfo.Int]: (registry, value) => createInt(types_codec_1.Int, value), | ||
// We have circular deps between Linkage & Struct | ||
[types_1.TypeDefInfo.Linkage]: (registry, value) => { | ||
const type = `Option<${getSubType(value)}>`; | ||
// eslint-disable-next-line sort-keys | ||
const Clazz = types_codec_1.Struct.with({ previous: type, next: type }); | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
Clazz.prototype.toRawType = function () { | ||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call | ||
return `Linkage<${this.next.toRawType(true)}>`; | ||
}; | ||
return Clazz; | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[types_1.TypeDefInfo.Null]: (registry, _) => types_codec_1.Null, | ||
[types_1.TypeDefInfo.Option]: (registry, value) => { | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error('Expected type information for Option'); | ||
} | ||
// NOTE This is opt-in (unhandled), not by default | ||
// if (value.sub.type === 'bool') { | ||
// return OptionBool; | ||
// } | ||
return createWithSub(types_codec_1.Option, value); | ||
}, | ||
[types_1.TypeDefInfo.Plain]: (registry, value) => registry.getOrUnknown(value.type), | ||
[types_1.TypeDefInfo.Range]: (registry, value) => createWithSub(types_codec_1.Range, value), | ||
[types_1.TypeDefInfo.RangeInclusive]: (registry, value) => createWithSub(types_codec_1.RangeInclusive, value), | ||
[types_1.TypeDefInfo.Result]: (registry, value) => { | ||
const [Ok, Err] = getTypeClassArray(value); | ||
// eslint-disable-next-line @typescript-eslint/no-use-before-define | ||
return types_codec_1.Result.with({ Err, Ok }); | ||
}, | ||
[types_1.TypeDefInfo.Set]: (registry, value) => types_codec_1.CodecSet.with(getSubDefArray(value).reduce((result, { index, name }) => { | ||
result[name] = index; | ||
return result; | ||
}, {}), value.length), | ||
[types_1.TypeDefInfo.Si]: (registry, value) => getTypeClass(registry, registry.lookup.getTypeDef(value.type)), | ||
[types_1.TypeDefInfo.Struct]: (registry, value) => types_codec_1.Struct.with(getTypeClassMap(value), value.alias), | ||
[types_1.TypeDefInfo.Tuple]: (registry, value) => types_codec_1.Tuple.with(getTypeClassArray(value)), | ||
[types_1.TypeDefInfo.UInt]: (registry, value) => createInt(types_codec_1.UInt, value), | ||
[types_1.TypeDefInfo.Vec]: (registry, { sub }) => { | ||
if (!sub || Array.isArray(sub)) { | ||
throw new Error('Expected type information for vector'); | ||
} | ||
return (sub.type === 'u8' | ||
? types_codec_1.Bytes | ||
: types_codec_1.Vec.with(getTypeDefType(sub))); | ||
}, | ||
[types_1.TypeDefInfo.VecFixed]: (registry, { displayName, length, sub }) => { | ||
if (!(0, util_1.isNumber)(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Expected length & type information for fixed vector'); | ||
} | ||
return (sub.type === 'u8' | ||
? types_codec_1.U8aFixed.with((length * 8), displayName) | ||
: types_codec_1.VecFixed.with(getTypeDefType(sub), length)); | ||
}, | ||
[types_1.TypeDefInfo.WrapperKeepOpaque]: (registry, value) => createWithSub(types_codec_1.WrapperKeepOpaque, value), | ||
[types_1.TypeDefInfo.WrapperOpaque]: (registry, value) => createWithSub(types_codec_1.WrapperOpaque, value) | ||
}; | ||
function constructTypeClass(registry, typeDef) { | ||
try { | ||
const Type = infoMapping[typeDef.info](registry, typeDef); | ||
if (!Type) { | ||
throw new Error('No class created'); | ||
try { | ||
const Type = infoMapping[typeDef.info](registry, typeDef); | ||
if (!Type) { | ||
throw new Error('No class created'); | ||
} | ||
// don't clobber any existing | ||
if (!Type.__fallbackType && typeDef.fallbackType) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-ignore ...this is the only place we we actually assign this... | ||
Type.__fallbackType = typeDef.fallbackType; | ||
} | ||
return Type; | ||
} | ||
// don't clobber any existing | ||
if (!Type.__fallbackType && typeDef.fallbackType) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-ignore ...this is the only place we we actually assign this... | ||
Type.__fallbackType = typeDef.fallbackType; | ||
catch (error) { | ||
throw new Error(`Unable to construct class from ${(0, util_1.stringify)(typeDef)}: ${error.message}`); | ||
} | ||
return Type; | ||
} catch (error) { | ||
throw new Error(`Unable to construct class from ${(0, _util.stringify)(typeDef)}: ${error.message}`); | ||
} | ||
} | ||
// Returns the type Class for construction | ||
exports.constructTypeClass = constructTypeClass; | ||
function getTypeClass(registry, typeDef) { | ||
return registry.getUnsafe(typeDef.type, false, typeDef); | ||
return registry.getUnsafe(typeDef.type, false, typeDef); | ||
} | ||
exports.getTypeClass = getTypeClass; | ||
function createClassUnsafe(registry, type) { | ||
return ( | ||
return ( | ||
// just retrieve via name, no creation via typeDef | ||
registry.getUnsafe(type) || | ||
// we don't have an existing type, create the class via typeDef | ||
getTypeClass(registry, registry.isLookupType(type) ? registry.lookup.getTypeDef(type) : (0, _getTypeDef.getTypeDef)(type)) | ||
); | ||
} | ||
// we don't have an existing type, create the class via typeDef | ||
getTypeClass(registry, registry.isLookupType(type) | ||
? registry.lookup.getTypeDef(type) | ||
: (0, getTypeDef_1.getTypeDef)(type))); | ||
} | ||
exports.createClassUnsafe = createClassUnsafe; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
var _class = require("./class"); | ||
Object.keys(_class).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _class[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _class[key]; | ||
} | ||
}); | ||
}); | ||
var _type = require("./type"); | ||
Object.keys(_type).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _type[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _type[key]; | ||
} | ||
}); | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
tslib_1.__exportStar(require("./class"), exports); | ||
tslib_1.__exportStar(require("./type"), exports); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.createTypeUnsafe = createTypeUnsafe; | ||
var _typesCodec = require("@polkadot/types-codec"); | ||
var _util = require("@polkadot/util"); | ||
var _class = require("./class"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// With isPedantic, actually check that the encoding matches that supplied. This | ||
// is much slower, but verifies that we have the correct types defined | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.createTypeUnsafe = void 0; | ||
const types_codec_1 = require("@polkadot/types-codec"); | ||
const util_1 = require("@polkadot/util"); | ||
const class_1 = require("./class"); | ||
function checkInstance(created, matcher) { | ||
const u8a = created.toU8a(); | ||
const rawType = created.toRawType(); | ||
const isOk = | ||
// full match, all ok | ||
(0, _util.u8aEq)(u8a, matcher) || | ||
// on a length-prefixed type, just check the actual length | ||
['Bytes', 'Text', 'Type'].includes(rawType) && matcher.length === created.length || | ||
// when the created is empty and matcher is also empty, let it slide... | ||
created.isEmpty && matcher.every(v => !v); | ||
if (!isOk) { | ||
throw new Error(`${rawType}:: Decoded input doesn't match input, received ${(0, _util.u8aToHex)(matcher, 512)} (${matcher.length} bytes), created ${(0, _util.u8aToHex)(u8a, 512)} (${u8a.length} bytes)`); | ||
} | ||
const u8a = created.toU8a(); | ||
const rawType = created.toRawType(); | ||
const isOk = ( | ||
// full match, all ok | ||
(0, util_1.u8aEq)(u8a, matcher) || | ||
( | ||
// on a length-prefixed type, just check the actual length | ||
['Bytes', 'Text', 'Type'].includes(rawType) && | ||
matcher.length === created.length) || | ||
( | ||
// when the created is empty and matcher is also empty, let it slide... | ||
created.isEmpty && | ||
matcher.every((v) => !v))); | ||
if (!isOk) { | ||
throw new Error(`${rawType}:: Decoded input doesn't match input, received ${(0, util_1.u8aToHex)(matcher, 512)} (${matcher.length} bytes), created ${(0, util_1.u8aToHex)(u8a, 512)} (${u8a.length} bytes)`); | ||
} | ||
} | ||
function checkPedantic(created, _ref) { | ||
let [value] = _ref; | ||
if ((0, _util.isU8a)(value)) { | ||
checkInstance(created, value); | ||
} else if ((0, _util.isHex)(value)) { | ||
checkInstance(created, (0, _util.u8aToU8a)(value)); | ||
} | ||
function checkPedantic(created, [value]) { | ||
if ((0, util_1.isU8a)(value)) { | ||
checkInstance(created, value); | ||
} | ||
else if ((0, util_1.isHex)(value)) { | ||
checkInstance(created, (0, util_1.u8aToU8a)(value)); | ||
} | ||
} | ||
// Initializes a type with a value. This also checks for fallbacks and in the cases | ||
// where isPedantic is specified (storage decoding), also check the format/structure | ||
function initType(registry, Type) { | ||
let params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
let { | ||
blockHash, | ||
isFallback, | ||
isOptional, | ||
isPedantic | ||
} = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; | ||
const created = new (isOptional ? _typesCodec.Option.with(Type) : Type)(registry, ...params); | ||
isPedantic && checkPedantic(created, params); | ||
if (blockHash) { | ||
created.createdAtHash = createTypeUnsafe(registry, 'BlockHash', [blockHash]); | ||
} | ||
if (isFallback) { | ||
created.isStorageFallback = true; | ||
} | ||
return created; | ||
function initType(registry, Type, params = [], { blockHash, isFallback, isOptional, isPedantic } = {}) { | ||
const created = new (isOptional | ||
? types_codec_1.Option.with(Type) | ||
: Type)(registry, ...params); | ||
isPedantic && checkPedantic(created, params); | ||
if (blockHash) { | ||
created.createdAtHash = createTypeUnsafe(registry, 'BlockHash', [blockHash]); | ||
} | ||
if (isFallback) { | ||
created.isStorageFallback = true; | ||
} | ||
return created; | ||
} | ||
// An unsafe version of the `createType` below. It's unsafe because the `type` | ||
// argument here can be any string, which, when it cannot parse, will yield a | ||
// runtime error. | ||
function createTypeUnsafe(registry, type) { | ||
let params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; | ||
let Clazz = null; | ||
let firstError = null; | ||
try { | ||
Clazz = (0, _class.createClassUnsafe)(registry, type); | ||
return initType(registry, Clazz, params, options); | ||
} catch (error) { | ||
firstError = new Error(`createType(${type}):: ${error.message}`); | ||
} | ||
if (Clazz && Clazz.__fallbackType) { | ||
function createTypeUnsafe(registry, type, params = [], options = {}) { | ||
let Clazz = null; | ||
let firstError = null; | ||
try { | ||
Clazz = (0, _class.createClassUnsafe)(registry, Clazz.__fallbackType); | ||
return initType(registry, Clazz, params, options); | ||
} catch { | ||
// swallow, we will throw the first error again | ||
Clazz = (0, class_1.createClassUnsafe)(registry, type); | ||
return initType(registry, Clazz, params, options); | ||
} | ||
} | ||
throw firstError; | ||
} | ||
catch (error) { | ||
firstError = new Error(`createType(${type}):: ${error.message}`); | ||
} | ||
if (Clazz && Clazz.__fallbackType) { | ||
try { | ||
Clazz = (0, class_1.createClassUnsafe)(registry, Clazz.__fallbackType); | ||
return initType(registry, Clazz, params, options); | ||
} | ||
catch { | ||
// swallow, we will throw the first error again | ||
} | ||
} | ||
throw firstError; | ||
} | ||
exports.createTypeUnsafe = createTypeUnsafe; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = void 0; | ||
var _packageInfo = require("@polkadot/types-codec/cjs/packageInfo"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
var _default = [_packageInfo.packageInfo]; | ||
exports.default = _default; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const packageInfo_1 = require("@polkadot/types-codec/cjs/packageInfo"); | ||
exports.default = [packageInfo_1.packageInfo]; |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
var _util = require("@polkadot/util"); | ||
var _detectOther = _interopRequireDefault(require("./detectOther")); | ||
var _packageInfo = require("./packageInfo"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// Do not edit, auto-generated by @polkadot/dev | ||
(0, _util.detectPackage)(_packageInfo.packageInfo, null, _detectOther.default); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
const util_1 = require("@polkadot/util"); | ||
const detectOther_1 = tslib_1.__importDefault(require("./detectOther")); | ||
const packageInfo_1 = require("./packageInfo"); | ||
(0, util_1.detectPackage)(packageInfo_1.packageInfo, null, detectOther_1.default); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
require("./detectPackage"); | ||
var _bundle = require("./bundle"); | ||
Object.keys(_bundle).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _bundle[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _bundle[key]; | ||
} | ||
}); | ||
}); | ||
tslib_1.__exportStar(require("./bundle"), exports); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.packageInfo = void 0; | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// Do not edit, auto-generated by @polkadot/dev | ||
const packageInfo = { | ||
name: '@polkadot/types-create', | ||
path: typeof __dirname === 'string' ? __dirname : 'auto', | ||
type: 'cjs', | ||
version: '9.14.2' | ||
}; | ||
exports.packageInfo = packageInfo; | ||
exports.packageInfo = { name: '@polkadot/types-create', path: typeof __dirname === 'string' ? __dirname : 'auto', type: 'cjs', version: '10.0.1' }; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
require("@polkadot/types-codec/types/registry"); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
require("./augmentRegistry"); | ||
var _lookup = require("./lookup"); | ||
Object.keys(_lookup).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _lookup[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _lookup[key]; | ||
} | ||
}); | ||
}); | ||
var _types = require("./types"); | ||
Object.keys(_types).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _types[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _types[key]; | ||
} | ||
}); | ||
}); | ||
tslib_1.__exportStar(require("./lookup"), exports); | ||
tslib_1.__exportStar(require("./types"), exports); |
@@ -1,1 +0,2 @@ | ||
"use strict"; | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.TypeDefInfo = void 0; | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
let TypeDefInfo; | ||
exports.TypeDefInfo = TypeDefInfo; | ||
var TypeDefInfo; | ||
(function (TypeDefInfo) { | ||
TypeDefInfo[TypeDefInfo["BTreeMap"] = 0] = "BTreeMap"; | ||
TypeDefInfo[TypeDefInfo["BTreeSet"] = 1] = "BTreeSet"; | ||
TypeDefInfo[TypeDefInfo["Compact"] = 2] = "Compact"; | ||
TypeDefInfo[TypeDefInfo["DoNotConstruct"] = 3] = "DoNotConstruct"; | ||
TypeDefInfo[TypeDefInfo["Enum"] = 4] = "Enum"; | ||
TypeDefInfo[TypeDefInfo["HashMap"] = 5] = "HashMap"; | ||
TypeDefInfo[TypeDefInfo["Int"] = 6] = "Int"; | ||
TypeDefInfo[TypeDefInfo["Linkage"] = 7] = "Linkage"; | ||
TypeDefInfo[TypeDefInfo["Null"] = 8] = "Null"; | ||
TypeDefInfo[TypeDefInfo["Option"] = 9] = "Option"; | ||
TypeDefInfo[TypeDefInfo["Plain"] = 10] = "Plain"; | ||
TypeDefInfo[TypeDefInfo["Range"] = 11] = "Range"; | ||
TypeDefInfo[TypeDefInfo["RangeInclusive"] = 12] = "RangeInclusive"; | ||
TypeDefInfo[TypeDefInfo["Result"] = 13] = "Result"; | ||
TypeDefInfo[TypeDefInfo["Set"] = 14] = "Set"; | ||
TypeDefInfo[TypeDefInfo["Si"] = 15] = "Si"; | ||
TypeDefInfo[TypeDefInfo["Struct"] = 16] = "Struct"; | ||
TypeDefInfo[TypeDefInfo["Tuple"] = 17] = "Tuple"; | ||
TypeDefInfo[TypeDefInfo["UInt"] = 18] = "UInt"; | ||
TypeDefInfo[TypeDefInfo["Vec"] = 19] = "Vec"; | ||
TypeDefInfo[TypeDefInfo["VecFixed"] = 20] = "VecFixed"; | ||
TypeDefInfo[TypeDefInfo["WrapperKeepOpaque"] = 21] = "WrapperKeepOpaque"; | ||
TypeDefInfo[TypeDefInfo["WrapperOpaque"] = 22] = "WrapperOpaque"; | ||
})(TypeDefInfo || (exports.TypeDefInfo = TypeDefInfo = {})); | ||
TypeDefInfo[TypeDefInfo["BTreeMap"] = 0] = "BTreeMap"; | ||
TypeDefInfo[TypeDefInfo["BTreeSet"] = 1] = "BTreeSet"; | ||
TypeDefInfo[TypeDefInfo["Compact"] = 2] = "Compact"; | ||
TypeDefInfo[TypeDefInfo["DoNotConstruct"] = 3] = "DoNotConstruct"; | ||
TypeDefInfo[TypeDefInfo["Enum"] = 4] = "Enum"; | ||
TypeDefInfo[TypeDefInfo["HashMap"] = 5] = "HashMap"; | ||
TypeDefInfo[TypeDefInfo["Int"] = 6] = "Int"; | ||
TypeDefInfo[TypeDefInfo["Linkage"] = 7] = "Linkage"; | ||
TypeDefInfo[TypeDefInfo["Null"] = 8] = "Null"; | ||
TypeDefInfo[TypeDefInfo["Option"] = 9] = "Option"; | ||
TypeDefInfo[TypeDefInfo["Plain"] = 10] = "Plain"; | ||
TypeDefInfo[TypeDefInfo["Range"] = 11] = "Range"; | ||
TypeDefInfo[TypeDefInfo["RangeInclusive"] = 12] = "RangeInclusive"; | ||
TypeDefInfo[TypeDefInfo["Result"] = 13] = "Result"; | ||
TypeDefInfo[TypeDefInfo["Set"] = 14] = "Set"; | ||
TypeDefInfo[TypeDefInfo["Si"] = 15] = "Si"; | ||
TypeDefInfo[TypeDefInfo["Struct"] = 16] = "Struct"; | ||
TypeDefInfo[TypeDefInfo["Tuple"] = 17] = "Tuple"; | ||
TypeDefInfo[TypeDefInfo["UInt"] = 18] = "UInt"; | ||
TypeDefInfo[TypeDefInfo["Vec"] = 19] = "Vec"; | ||
TypeDefInfo[TypeDefInfo["VecFixed"] = 20] = "VecFixed"; | ||
TypeDefInfo[TypeDefInfo["WrapperKeepOpaque"] = 21] = "WrapperKeepOpaque"; | ||
TypeDefInfo[TypeDefInfo["WrapperOpaque"] = 22] = "WrapperOpaque"; | ||
})(TypeDefInfo = exports.TypeDefInfo || (exports.TypeDefInfo = {})); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.encodeTypeDef = encodeTypeDef; | ||
exports.paramsNotation = paramsNotation; | ||
exports.withTypeString = withTypeString; | ||
var _util = require("@polkadot/util"); | ||
var _types = require("../types"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
const stringIdentity = value => value.toString(); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.withTypeString = exports.encodeTypeDef = exports.paramsNotation = void 0; | ||
const util_1 = require("@polkadot/util"); | ||
const types_1 = require("../types"); | ||
const stringIdentity = (value) => value.toString(); | ||
const INFO_WRAP = ['BTreeMap', 'BTreeSet', 'Compact', 'HashMap', 'Option', 'Result', 'Vec']; | ||
function paramsNotation(outer, inner) { | ||
let transform = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringIdentity; | ||
return `${outer}${inner ? `<${(Array.isArray(inner) ? inner : [inner]).map(transform).join(', ')}>` : ''}`; | ||
function paramsNotation(outer, inner, transform = stringIdentity) { | ||
return `${outer}${inner | ||
? `<${(Array.isArray(inner) ? inner : [inner]).map(transform).join(', ')}>` | ||
: ''}`; | ||
} | ||
exports.paramsNotation = paramsNotation; | ||
function encodeWithParams(registry, typeDef, outer) { | ||
const { | ||
info, | ||
sub | ||
} = typeDef; | ||
switch (info) { | ||
case _types.TypeDefInfo.BTreeMap: | ||
case _types.TypeDefInfo.BTreeSet: | ||
case _types.TypeDefInfo.Compact: | ||
case _types.TypeDefInfo.HashMap: | ||
case _types.TypeDefInfo.Linkage: | ||
case _types.TypeDefInfo.Option: | ||
case _types.TypeDefInfo.Range: | ||
case _types.TypeDefInfo.RangeInclusive: | ||
case _types.TypeDefInfo.Result: | ||
case _types.TypeDefInfo.Vec: | ||
case _types.TypeDefInfo.WrapperKeepOpaque: | ||
case _types.TypeDefInfo.WrapperOpaque: | ||
return paramsNotation(outer, sub, p => encodeTypeDef(registry, p)); | ||
} | ||
throw new Error(`Unable to encode ${(0, _util.stringify)(typeDef)} with params`); | ||
const { info, sub } = typeDef; | ||
switch (info) { | ||
case types_1.TypeDefInfo.BTreeMap: | ||
case types_1.TypeDefInfo.BTreeSet: | ||
case types_1.TypeDefInfo.Compact: | ||
case types_1.TypeDefInfo.HashMap: | ||
case types_1.TypeDefInfo.Linkage: | ||
case types_1.TypeDefInfo.Option: | ||
case types_1.TypeDefInfo.Range: | ||
case types_1.TypeDefInfo.RangeInclusive: | ||
case types_1.TypeDefInfo.Result: | ||
case types_1.TypeDefInfo.Vec: | ||
case types_1.TypeDefInfo.WrapperKeepOpaque: | ||
case types_1.TypeDefInfo.WrapperOpaque: | ||
return paramsNotation(outer, sub, (p) => encodeTypeDef(registry, p)); | ||
} | ||
throw new Error(`Unable to encode ${(0, util_1.stringify)(typeDef)} with params`); | ||
} | ||
function encodeSubTypes(registry, sub, asEnum, extra) { | ||
const names = sub.map(_ref => { | ||
let { | ||
name | ||
} = _ref; | ||
return name; | ||
}); | ||
if (!names.every(n => !!n)) { | ||
throw new Error(`Subtypes does not have consistent names, ${names.join(', ')}`); | ||
} | ||
const inner = (0, _util.objectSpread)({}, extra); | ||
for (let i = 0; i < sub.length; i++) { | ||
const def = sub[i]; | ||
inner[def.name] = encodeTypeDef(registry, def); | ||
} | ||
return (0, _util.stringify)(asEnum ? { | ||
_enum: inner | ||
} : inner); | ||
const names = sub.map(({ name }) => name); | ||
if (!names.every((n) => !!n)) { | ||
throw new Error(`Subtypes does not have consistent names, ${names.join(', ')}`); | ||
} | ||
const inner = (0, util_1.objectSpread)({}, extra); | ||
for (let i = 0; i < sub.length; i++) { | ||
const def = sub[i]; | ||
inner[def.name] = encodeTypeDef(registry, def); | ||
} | ||
return (0, util_1.stringify)(asEnum | ||
? { _enum: inner } | ||
: inner); | ||
} | ||
// We setup a record here to ensure we have comprehensive coverage (any item not covered will result | ||
// in a compile-time error with the missing index) | ||
const encoders = { | ||
[_types.TypeDefInfo.BTreeMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeMap'), | ||
[_types.TypeDefInfo.BTreeSet]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeSet'), | ||
[_types.TypeDefInfo.Compact]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Compact'), | ||
[_types.TypeDefInfo.DoNotConstruct]: (registry, _ref2) => { | ||
let { | ||
displayName, | ||
lookupIndex, | ||
lookupName | ||
} = _ref2; | ||
return `DoNotConstruct<${lookupName || displayName || ((0, _util.isUndefined)(lookupIndex) ? 'Unknown' : registry.createLookupType(lookupIndex))}>`; | ||
}, | ||
[_types.TypeDefInfo.Enum]: (registry, _ref3) => { | ||
let { | ||
sub | ||
} = _ref3; | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Enum type'); | ||
} | ||
// c-like enums have all Null entries | ||
// TODO We need to take the disciminant into account and auto-add empty entries | ||
return sub.every(_ref4 => { | ||
let { | ||
type | ||
} = _ref4; | ||
return type === 'Null'; | ||
}) ? (0, _util.stringify)({ | ||
_enum: sub.map((_ref5, index) => { | ||
let { | ||
name | ||
} = _ref5; | ||
return `${name || `Empty${index}`}`; | ||
}) | ||
}) : encodeSubTypes(registry, sub, true); | ||
}, | ||
[_types.TypeDefInfo.HashMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'HashMap'), | ||
[_types.TypeDefInfo.Int]: (registry, _ref6) => { | ||
let { | ||
length = 32 | ||
} = _ref6; | ||
return `Int<${length}>`; | ||
}, | ||
[_types.TypeDefInfo.Linkage]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Linkage'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[_types.TypeDefInfo.Null]: (registry, typeDef) => 'Null', | ||
[_types.TypeDefInfo.Option]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Option'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[_types.TypeDefInfo.Plain]: (registry, _ref7) => { | ||
let { | ||
displayName, | ||
type | ||
} = _ref7; | ||
return displayName || type; | ||
}, | ||
[_types.TypeDefInfo.Range]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Range'), | ||
[_types.TypeDefInfo.RangeInclusive]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'RangeInclusive'), | ||
[_types.TypeDefInfo.Result]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Result'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[_types.TypeDefInfo.Set]: (registry, _ref8) => { | ||
let { | ||
length = 8, | ||
sub | ||
} = _ref8; | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Set type'); | ||
} | ||
return (0, _util.stringify)({ | ||
_set: sub.reduce((all, _ref9, count) => { | ||
let { | ||
index, | ||
name | ||
} = _ref9; | ||
return (0, _util.objectSpread)(all, { | ||
[`${name || `Unknown${index || count}`}`]: index || count | ||
[types_1.TypeDefInfo.BTreeMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeMap'), | ||
[types_1.TypeDefInfo.BTreeSet]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeSet'), | ||
[types_1.TypeDefInfo.Compact]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Compact'), | ||
[types_1.TypeDefInfo.DoNotConstruct]: (registry, { displayName, lookupIndex, lookupName }) => `DoNotConstruct<${lookupName || displayName || ((0, util_1.isUndefined)(lookupIndex) ? 'Unknown' : registry.createLookupType(lookupIndex))}>`, | ||
[types_1.TypeDefInfo.Enum]: (registry, { sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Enum type'); | ||
} | ||
// c-like enums have all Null entries | ||
// TODO We need to take the disciminant into account and auto-add empty entries | ||
return sub.every(({ type }) => type === 'Null') | ||
? (0, util_1.stringify)({ _enum: sub.map(({ name }, index) => `${name || `Empty${index}`}`) }) | ||
: encodeSubTypes(registry, sub, true); | ||
}, | ||
[types_1.TypeDefInfo.HashMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'HashMap'), | ||
[types_1.TypeDefInfo.Int]: (registry, { length = 32 }) => `Int<${length}>`, | ||
[types_1.TypeDefInfo.Linkage]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Linkage'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[types_1.TypeDefInfo.Null]: (registry, typeDef) => 'Null', | ||
[types_1.TypeDefInfo.Option]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Option'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[types_1.TypeDefInfo.Plain]: (registry, { displayName, type }) => displayName || type, | ||
[types_1.TypeDefInfo.Range]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Range'), | ||
[types_1.TypeDefInfo.RangeInclusive]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'RangeInclusive'), | ||
[types_1.TypeDefInfo.Result]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Result'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[types_1.TypeDefInfo.Set]: (registry, { length = 8, sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Set type'); | ||
} | ||
return (0, util_1.stringify)({ | ||
_set: sub.reduce((all, { index, name }, count) => (0, util_1.objectSpread)(all, { [`${name || `Unknown${index || count}`}`]: index || count }), { _bitLength: length || 8 }) | ||
}); | ||
}, { | ||
_bitLength: length || 8 | ||
}) | ||
}); | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[_types.TypeDefInfo.Si]: (registry, _ref10) => { | ||
let { | ||
lookupName, | ||
type | ||
} = _ref10; | ||
return lookupName || type; | ||
}, | ||
[_types.TypeDefInfo.Struct]: (registry, _ref11) => { | ||
let { | ||
alias, | ||
sub | ||
} = _ref11; | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Struct type'); | ||
} | ||
return encodeSubTypes(registry, sub, false, alias ? { | ||
_alias: [...alias.entries()].reduce((all, _ref12) => { | ||
let [k, v] = _ref12; | ||
return (0, _util.objectSpread)(all, { | ||
[k]: v | ||
}); | ||
}, {}) | ||
} : {}); | ||
}, | ||
[_types.TypeDefInfo.Tuple]: (registry, _ref13) => { | ||
let { | ||
sub | ||
} = _ref13; | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Tuple type'); | ||
} | ||
return `(${sub.map(type => encodeTypeDef(registry, type)).join(',')})`; | ||
}, | ||
[_types.TypeDefInfo.UInt]: (registry, _ref14) => { | ||
let { | ||
length = 32 | ||
} = _ref14; | ||
return `UInt<${length}>`; | ||
}, | ||
[_types.TypeDefInfo.Vec]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Vec'), | ||
[_types.TypeDefInfo.VecFixed]: (registry, _ref15) => { | ||
let { | ||
length, | ||
sub | ||
} = _ref15; | ||
if (!(0, _util.isNumber)(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Unable to encode VecFixed type'); | ||
} | ||
return `[${sub.type};${length}]`; | ||
}, | ||
[_types.TypeDefInfo.WrapperKeepOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperKeepOpaque'), | ||
[_types.TypeDefInfo.WrapperOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperOpaque') | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[types_1.TypeDefInfo.Si]: (registry, { lookupName, type }) => lookupName || type, | ||
[types_1.TypeDefInfo.Struct]: (registry, { alias, sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Struct type'); | ||
} | ||
return encodeSubTypes(registry, sub, false, alias | ||
? { | ||
_alias: [...alias.entries()].reduce((all, [k, v]) => (0, util_1.objectSpread)(all, { [k]: v }), {}) | ||
} | ||
: {}); | ||
}, | ||
[types_1.TypeDefInfo.Tuple]: (registry, { sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Tuple type'); | ||
} | ||
return `(${sub.map((type) => encodeTypeDef(registry, type)).join(',')})`; | ||
}, | ||
[types_1.TypeDefInfo.UInt]: (registry, { length = 32 }) => `UInt<${length}>`, | ||
[types_1.TypeDefInfo.Vec]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Vec'), | ||
[types_1.TypeDefInfo.VecFixed]: (registry, { length, sub }) => { | ||
if (!(0, util_1.isNumber)(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Unable to encode VecFixed type'); | ||
} | ||
return `[${sub.type};${length}]`; | ||
}, | ||
[types_1.TypeDefInfo.WrapperKeepOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperKeepOpaque'), | ||
[types_1.TypeDefInfo.WrapperOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperOpaque') | ||
}; | ||
function encodeType(registry, typeDef) { | ||
let withLookup = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; | ||
return withLookup && typeDef.lookupName ? typeDef.lookupName : encoders[typeDef.info](registry, typeDef); | ||
function encodeType(registry, typeDef, withLookup = true) { | ||
return withLookup && typeDef.lookupName | ||
? typeDef.lookupName | ||
: encoders[typeDef.info](registry, typeDef); | ||
} | ||
function encodeTypeDef(registry, typeDef) { | ||
// In the case of contracts we do have the unfortunate situation where the displayName would | ||
// refer to "Option" when it is an option. For these, string it out, only using when actually | ||
// not a top-level element to be used | ||
return typeDef.displayName && !INFO_WRAP.some(i => typeDef.displayName === i) ? typeDef.displayName : encodeType(registry, typeDef); | ||
// In the case of contracts we do have the unfortunate situation where the displayName would | ||
// refer to "Option" when it is an option. For these, string it out, only using when actually | ||
// not a top-level element to be used | ||
return (typeDef.displayName && !INFO_WRAP.some((i) => typeDef.displayName === i)) | ||
? typeDef.displayName | ||
: encodeType(registry, typeDef); | ||
} | ||
exports.encodeTypeDef = encodeTypeDef; | ||
function withTypeString(registry, typeDef) { | ||
return (0, _util.objectSpread)({}, typeDef, { | ||
type: encodeType(registry, typeDef, false) | ||
}); | ||
} | ||
return (0, util_1.objectSpread)({}, typeDef, { | ||
type: encodeType(registry, typeDef, false) | ||
}); | ||
} | ||
exports.withTypeString = withTypeString; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.getTypeDef = getTypeDef; | ||
var _typesCodec = require("@polkadot/types-codec"); | ||
var _util = require("@polkadot/util"); | ||
var _types = require("../types"); | ||
var _typeSplit = require("./typeSplit"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getTypeDef = void 0; | ||
const types_codec_1 = require("@polkadot/types-codec"); | ||
const util_1 = require("@polkadot/util"); | ||
const types_1 = require("../types"); | ||
const typeSplit_1 = require("./typeSplit"); | ||
const KNOWN_INTERNALS = ['_alias', '_fallback']; | ||
function getTypeString(typeOrObj) { | ||
return (0, _util.isString)(typeOrObj) ? typeOrObj.toString() : JSON.stringify(typeOrObj); | ||
return (0, util_1.isString)(typeOrObj) | ||
? typeOrObj.toString() | ||
: JSON.stringify(typeOrObj); | ||
} | ||
function isRustEnum(details) { | ||
const values = Object.values(details); | ||
if (values.some(v => (0, _util.isNumber)(v))) { | ||
if (!values.every(v => (0, _util.isNumber)(v) && v >= 0 && v <= 255)) { | ||
throw new Error('Invalid number-indexed enum definition'); | ||
const values = Object.values(details); | ||
if (values.some((v) => (0, util_1.isNumber)(v))) { | ||
if (!values.every((v) => (0, util_1.isNumber)(v) && v >= 0 && v <= 255)) { | ||
throw new Error('Invalid number-indexed enum definition'); | ||
} | ||
return false; | ||
} | ||
return false; | ||
} | ||
return true; | ||
return true; | ||
} | ||
// decode an enum of either of the following forms | ||
// { _enum: ['A', 'B', 'C'] } | ||
// { _enum: { A: AccountId, B: Balance, C: u32 } } | ||
// { _enum: { A: 1, B: 2 } } | ||
function _decodeEnum(value, details, count, fallbackType) { | ||
value.info = _types.TypeDefInfo.Enum; | ||
value.fallbackType = fallbackType; | ||
// not as pretty, but remain compatible with oo7 for both struct and Array types | ||
if (Array.isArray(details)) { | ||
value.sub = details.map((name, index) => ({ | ||
index, | ||
info: _types.TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} else if (isRustEnum(details)) { | ||
value.sub = Object.entries(details).map((_ref, index) => { | ||
let [name, typeOrObj] = _ref; | ||
return (0, _util.objectSpread)({}, getTypeDef(getTypeString(typeOrObj || 'Null'), { | ||
name | ||
}, count), { | ||
index | ||
}); | ||
}); | ||
} else { | ||
value.sub = Object.entries(details).map(_ref2 => { | ||
let [name, index] = _ref2; | ||
return { | ||
value.info = types_1.TypeDefInfo.Enum; | ||
value.fallbackType = fallbackType; | ||
// not as pretty, but remain compatible with oo7 for both struct and Array types | ||
if (Array.isArray(details)) { | ||
value.sub = details.map((name, index) => ({ | ||
index, | ||
info: types_1.TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} | ||
else if (isRustEnum(details)) { | ||
value.sub = Object.entries(details).map(([name, typeOrObj], index) => (0, util_1.objectSpread)({}, getTypeDef(getTypeString(typeOrObj || 'Null'), { name }, count), { index })); | ||
} | ||
else { | ||
value.sub = Object.entries(details).map(([name, index]) => ({ | ||
index, | ||
info: types_1.TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} | ||
return value; | ||
} | ||
function _decodeSet(value, details, fallbackType) { | ||
value.info = types_1.TypeDefInfo.Set; | ||
value.fallbackType = fallbackType; | ||
value.length = details._bitLength; | ||
value.sub = Object | ||
.entries(details) | ||
.filter(([name]) => !name.startsWith('_')) | ||
.map(([name, index]) => ({ | ||
index, | ||
info: _types.TypeDefInfo.Plain, | ||
info: types_1.TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
}; | ||
}); | ||
} | ||
return value; | ||
})); | ||
return value; | ||
} | ||
// decode a set of the form | ||
// { _set: { A: 0b0001, B: 0b0010, C: 0b0100 } } | ||
function _decodeSet(value, details, fallbackType) { | ||
value.info = _types.TypeDefInfo.Set; | ||
value.fallbackType = fallbackType; | ||
value.length = details._bitLength; | ||
value.sub = Object.entries(details).filter(_ref3 => { | ||
let [name] = _ref3; | ||
return !name.startsWith('_'); | ||
}).map(_ref4 => { | ||
let [name, index] = _ref4; | ||
return { | ||
index, | ||
info: _types.TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
}; | ||
}); | ||
return value; | ||
} | ||
// decode a struct, set or enum | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeStruct(value, type, _, count) { | ||
const parsed = JSON.parse(type); | ||
const keys = Object.keys(parsed); | ||
if (keys.includes('_enum')) { | ||
return _decodeEnum(value, parsed._enum, count, parsed._fallback); | ||
} else if (keys.includes('_set')) { | ||
return _decodeSet(value, parsed._set, parsed._fallback); | ||
} | ||
value.alias = parsed._alias ? new Map(Object.entries(parsed._alias)) : undefined; | ||
value.fallbackType = parsed._fallback; | ||
value.sub = keys.filter(name => !KNOWN_INTERNALS.includes(name)).map(name => getTypeDef(getTypeString(parsed[name]), { | ||
name | ||
}, count)); | ||
return value; | ||
const parsed = JSON.parse(type); | ||
const keys = Object.keys(parsed); | ||
if (keys.includes('_enum')) { | ||
return _decodeEnum(value, parsed._enum, count, parsed._fallback); | ||
} | ||
else if (keys.includes('_set')) { | ||
return _decodeSet(value, parsed._set, parsed._fallback); | ||
} | ||
value.alias = parsed._alias | ||
? new Map(Object.entries(parsed._alias)) | ||
: undefined; | ||
value.fallbackType = parsed._fallback; | ||
value.sub = keys | ||
.filter((name) => !KNOWN_INTERNALS.includes(name)) | ||
.map((name) => getTypeDef(getTypeString(parsed[name]), { name }, count)); | ||
return value; | ||
} | ||
// decode a fixed vector, e.g. [u8;32] | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeFixedVec(value, type, _, count) { | ||
const max = type.length - 1; | ||
let index = -1; | ||
let inner = 0; | ||
for (let i = 1; i < max && index === -1; i++) { | ||
switch (type[i]) { | ||
case ';': | ||
{ | ||
if (inner === 0) { | ||
index = i; | ||
} | ||
break; | ||
const max = type.length - 1; | ||
let index = -1; | ||
let inner = 0; | ||
for (let i = 1; (i < max) && (index === -1); i++) { | ||
switch (type[i]) { | ||
case ';': { | ||
if (inner === 0) { | ||
index = i; | ||
} | ||
break; | ||
} | ||
case '[': | ||
case '(': | ||
case '<': | ||
inner++; | ||
break; | ||
case ']': | ||
case ')': | ||
case '>': | ||
inner--; | ||
break; | ||
} | ||
case '[': | ||
case '(': | ||
case '<': | ||
inner++; | ||
break; | ||
case ']': | ||
case ')': | ||
case '>': | ||
inner--; | ||
break; | ||
} | ||
} | ||
if (index === -1) { | ||
throw new Error(`${type}: Unable to extract location of ';'`); | ||
} | ||
const vecType = type.substring(1, index); | ||
const [strLength, displayName] = type.substring(index + 1, max).split(';'); | ||
const length = parseInt(strLength.trim(), 10); | ||
if (length > 2048) { | ||
throw new Error(`${type}: Only support for [Type; <length>], where length <= 2048`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
value.sub = getTypeDef(vecType, {}, count); | ||
return value; | ||
if (index === -1) { | ||
throw new Error(`${type}: Unable to extract location of ';'`); | ||
} | ||
const vecType = type.substring(1, index); | ||
const [strLength, displayName] = type.substring(index + 1, max).split(';'); | ||
const length = parseInt(strLength.trim(), 10); | ||
if (length > 2048) { | ||
throw new Error(`${type}: Only support for [Type; <length>], where length <= 2048`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
value.sub = getTypeDef(vecType, {}, count); | ||
return value; | ||
} | ||
// decode a tuple | ||
function _decodeTuple(value, _, subType, count) { | ||
value.sub = subType.length === 0 ? [] : (0, _typeSplit.typeSplit)(subType).map(inner => getTypeDef(inner, {}, count)); | ||
return value; | ||
value.sub = subType.length === 0 | ||
? [] | ||
: (0, typeSplit_1.typeSplit)(subType).map((inner) => getTypeDef(inner, {}, count)); | ||
return value; | ||
} | ||
// decode a Int/UInt<bitLength[, name]> | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeAnyInt(value, type, _, clazz) { | ||
const [strLength, displayName] = type.substring(clazz.length + 1, type.length - 1).split(','); | ||
const length = parseInt(strLength.trim(), 10); | ||
if (length > 8192 || length % 8) { | ||
throw new Error(`${type}: Only support for ${clazz}<bitLength>, where length <= 8192 and a power of 8, found ${length}`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
return value; | ||
const [strLength, displayName] = type.substring(clazz.length + 1, type.length - 1).split(','); | ||
const length = parseInt(strLength.trim(), 10); | ||
if ((length > 8192) || (length % 8)) { | ||
throw new Error(`${type}: Only support for ${clazz}<bitLength>, where length <= 8192 and a power of 8, found ${length}`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
return value; | ||
} | ||
function _decodeInt(value, type, subType) { | ||
return _decodeAnyInt(value, type, subType, 'Int'); | ||
return _decodeAnyInt(value, type, subType, 'Int'); | ||
} | ||
function _decodeUInt(value, type, subType) { | ||
return _decodeAnyInt(value, type, subType, 'UInt'); | ||
return _decodeAnyInt(value, type, subType, 'UInt'); | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeDoNotConstruct(value, type, _) { | ||
const NAME_LENGTH = 'DoNotConstruct'.length; | ||
value.displayName = type.substring(NAME_LENGTH + 1, type.length - 1); | ||
return value; | ||
const NAME_LENGTH = 'DoNotConstruct'.length; | ||
value.displayName = type.substring(NAME_LENGTH + 1, type.length - 1); | ||
return value; | ||
} | ||
function hasWrapper(type, _ref5) { | ||
let [start, end] = _ref5; | ||
return type.substring(0, start.length) === start && type.slice(-1 * end.length) === end; | ||
function hasWrapper(type, [start, end]) { | ||
return (type.substring(0, start.length) === start) && (type.slice(-1 * end.length) === end); | ||
} | ||
const nestedExtraction = [['[', ']', _types.TypeDefInfo.VecFixed, _decodeFixedVec], ['{', '}', _types.TypeDefInfo.Struct, _decodeStruct], ['(', ')', _types.TypeDefInfo.Tuple, _decodeTuple], | ||
// the inner for these are the same as tuple, multiple values | ||
['BTreeMap<', '>', _types.TypeDefInfo.BTreeMap, _decodeTuple], ['HashMap<', '>', _types.TypeDefInfo.HashMap, _decodeTuple], ['Int<', '>', _types.TypeDefInfo.Int, _decodeInt], ['Result<', '>', _types.TypeDefInfo.Result, _decodeTuple], ['UInt<', '>', _types.TypeDefInfo.UInt, _decodeUInt], ['DoNotConstruct<', '>', _types.TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct]]; | ||
const wrappedExtraction = [['BTreeSet<', '>', _types.TypeDefInfo.BTreeSet], ['Compact<', '>', _types.TypeDefInfo.Compact], ['Linkage<', '>', _types.TypeDefInfo.Linkage], ['Opaque<', '>', _types.TypeDefInfo.WrapperOpaque], ['Option<', '>', _types.TypeDefInfo.Option], ['Range<', '>', _types.TypeDefInfo.Range], ['RangeInclusive<', '>', _types.TypeDefInfo.RangeInclusive], ['Vec<', '>', _types.TypeDefInfo.Vec], ['WrapperKeepOpaque<', '>', _types.TypeDefInfo.WrapperKeepOpaque], ['WrapperOpaque<', '>', _types.TypeDefInfo.WrapperOpaque]]; | ||
function extractSubType(type, _ref6) { | ||
let [start, end] = _ref6; | ||
return type.substring(start.length, type.length - end.length); | ||
const nestedExtraction = [ | ||
['[', ']', types_1.TypeDefInfo.VecFixed, _decodeFixedVec], | ||
['{', '}', types_1.TypeDefInfo.Struct, _decodeStruct], | ||
['(', ')', types_1.TypeDefInfo.Tuple, _decodeTuple], | ||
// the inner for these are the same as tuple, multiple values | ||
['BTreeMap<', '>', types_1.TypeDefInfo.BTreeMap, _decodeTuple], | ||
['HashMap<', '>', types_1.TypeDefInfo.HashMap, _decodeTuple], | ||
['Int<', '>', types_1.TypeDefInfo.Int, _decodeInt], | ||
['Result<', '>', types_1.TypeDefInfo.Result, _decodeTuple], | ||
['UInt<', '>', types_1.TypeDefInfo.UInt, _decodeUInt], | ||
['DoNotConstruct<', '>', types_1.TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct] | ||
]; | ||
const wrappedExtraction = [ | ||
['BTreeSet<', '>', types_1.TypeDefInfo.BTreeSet], | ||
['Compact<', '>', types_1.TypeDefInfo.Compact], | ||
['Linkage<', '>', types_1.TypeDefInfo.Linkage], | ||
['Opaque<', '>', types_1.TypeDefInfo.WrapperOpaque], | ||
['Option<', '>', types_1.TypeDefInfo.Option], | ||
['Range<', '>', types_1.TypeDefInfo.Range], | ||
['RangeInclusive<', '>', types_1.TypeDefInfo.RangeInclusive], | ||
['Vec<', '>', types_1.TypeDefInfo.Vec], | ||
['WrapperKeepOpaque<', '>', types_1.TypeDefInfo.WrapperKeepOpaque], | ||
['WrapperOpaque<', '>', types_1.TypeDefInfo.WrapperOpaque] | ||
]; | ||
function extractSubType(type, [start, end]) { | ||
return type.substring(start.length, type.length - end.length); | ||
} | ||
function getTypeDef(_type) { | ||
let { | ||
displayName, | ||
name | ||
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
let count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; | ||
// create the type via Type, allowing types to be sanitized | ||
const type = (0, _typesCodec.sanitize)(_type); | ||
const value = { | ||
displayName, | ||
info: _types.TypeDefInfo.Plain, | ||
name, | ||
type | ||
}; | ||
if (++count > 64) { | ||
throw new Error('getTypeDef: Maximum nested limit reached'); | ||
} | ||
const nested = nestedExtraction.find(nested => hasWrapper(type, nested)); | ||
if (nested) { | ||
value.info = nested[2]; | ||
return nested[3](value, type, extractSubType(type, nested), count); | ||
} | ||
const wrapped = wrappedExtraction.find(wrapped => hasWrapper(type, wrapped)); | ||
if (wrapped) { | ||
value.info = wrapped[2]; | ||
value.sub = getTypeDef(extractSubType(type, wrapped), {}, count); | ||
} | ||
return value; | ||
} | ||
function getTypeDef(_type, { displayName, name } = {}, count = 0) { | ||
// create the type via Type, allowing types to be sanitized | ||
const type = (0, types_codec_1.sanitize)(_type); | ||
const value = { displayName, info: types_1.TypeDefInfo.Plain, name, type }; | ||
if (++count > 64) { | ||
throw new Error('getTypeDef: Maximum nested limit reached'); | ||
} | ||
const nested = nestedExtraction.find((nested) => hasWrapper(type, nested)); | ||
if (nested) { | ||
value.info = nested[2]; | ||
return nested[3](value, type, extractSubType(type, nested), count); | ||
} | ||
const wrapped = wrappedExtraction.find((wrapped) => hasWrapper(type, wrapped)); | ||
if (wrapped) { | ||
value.info = wrapped[2]; | ||
value.sub = getTypeDef(extractSubType(type, wrapped), {}, count); | ||
} | ||
return value; | ||
} | ||
exports.getTypeDef = getTypeDef; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
var _encodeTypes = require("./encodeTypes"); | ||
Object.keys(_encodeTypes).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _encodeTypes[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _encodeTypes[key]; | ||
} | ||
}); | ||
}); | ||
var _getTypeDef = require("./getTypeDef"); | ||
Object.keys(_getTypeDef).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _getTypeDef[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _getTypeDef[key]; | ||
} | ||
}); | ||
}); | ||
var _typeSplit = require("./typeSplit"); | ||
Object.keys(_typeSplit).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _typeSplit[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _typeSplit[key]; | ||
} | ||
}); | ||
}); | ||
var _xcm = require("./xcm"); | ||
Object.keys(_xcm).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (key in exports && exports[key] === _xcm[key]) return; | ||
Object.defineProperty(exports, key, { | ||
enumerable: true, | ||
get: function () { | ||
return _xcm[key]; | ||
} | ||
}); | ||
}); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
tslib_1.__exportStar(require("./encodeTypes"), exports); | ||
tslib_1.__exportStar(require("./getTypeDef"), exports); | ||
tslib_1.__exportStar(require("./typeSplit"), exports); | ||
tslib_1.__exportStar(require("./xcm"), exports); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.typeSplit = typeSplit; | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// safely split a string on ', ' while taking care of any nested occurences | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.typeSplit = void 0; | ||
function typeSplit(type) { | ||
const result = []; | ||
// these are the depths of the various tokens: <, [, {, ( | ||
let c = 0; | ||
let f = 0; | ||
let s = 0; | ||
let t = 0; | ||
// current start position | ||
let start = 0; | ||
for (let i = 0; i < type.length; i++) { | ||
switch (type[i]) { | ||
// if we are not nested, add the type | ||
case ',': | ||
{ | ||
if (!(c || f || s || t)) { | ||
result.push(type.substring(start, i).trim()); | ||
start = i + 1; | ||
} | ||
break; | ||
const result = []; | ||
// these are the depths of the various tokens: <, [, {, ( | ||
let c = 0; | ||
let f = 0; | ||
let s = 0; | ||
let t = 0; | ||
// current start position | ||
let start = 0; | ||
for (let i = 0; i < type.length; i++) { | ||
switch (type[i]) { | ||
// if we are not nested, add the type | ||
case ',': { | ||
if (!(c || f || s || t)) { | ||
result.push(type.substring(start, i).trim()); | ||
start = i + 1; | ||
} | ||
break; | ||
} | ||
// adjust compact/vec (and friends) depth | ||
case '<': | ||
c++; | ||
break; | ||
case '>': | ||
c--; | ||
break; | ||
// adjust fixed vec depths | ||
case '[': | ||
f++; | ||
break; | ||
case ']': | ||
f--; | ||
break; | ||
// adjust struct depth | ||
case '{': | ||
s++; | ||
break; | ||
case '}': | ||
s--; | ||
break; | ||
// adjust tuple depth | ||
case '(': | ||
t++; | ||
break; | ||
case ')': | ||
t--; | ||
break; | ||
} | ||
// adjust compact/vec (and friends) depth | ||
case '<': | ||
c++; | ||
break; | ||
case '>': | ||
c--; | ||
break; | ||
// adjust fixed vec depths | ||
case '[': | ||
f++; | ||
break; | ||
case ']': | ||
f--; | ||
break; | ||
// adjust struct depth | ||
case '{': | ||
s++; | ||
break; | ||
case '}': | ||
s--; | ||
break; | ||
// adjust tuple depth | ||
case '(': | ||
t++; | ||
break; | ||
case ')': | ||
t--; | ||
break; | ||
} | ||
} | ||
// ensure we have all the terminators taken care of | ||
if (c || f || s || t) { | ||
throw new Error(`Invalid definition (missing terminators) found in ${type}`); | ||
} | ||
// the final leg of the journey | ||
result.push(type.substring(start, type.length).trim()); | ||
return result; | ||
} | ||
// ensure we have all the terminators taken care of | ||
if (c || f || s || t) { | ||
throw new Error(`Invalid definition (missing terminators) found in ${type}`); | ||
} | ||
// the final leg of the journey | ||
result.push(type.substring(start, type.length).trim()); | ||
return result; | ||
} | ||
exports.typeSplit = typeSplit; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.XCM_MAPPINGS = void 0; | ||
exports.mapXcmTypes = mapXcmTypes; | ||
var _util = require("@polkadot/util"); | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
const XCM_MAPPINGS = ['AssetInstance', 'Fungibility', 'Junction', 'Junctions', 'MultiAsset', 'MultiAssetFilter', 'MultiLocation', 'Response', 'WildFungibility', 'WildMultiAsset', 'Xcm', 'XcmError', 'XcmOrder']; | ||
exports.XCM_MAPPINGS = XCM_MAPPINGS; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.mapXcmTypes = exports.XCM_MAPPINGS = void 0; | ||
const util_1 = require("@polkadot/util"); | ||
exports.XCM_MAPPINGS = ['AssetInstance', 'Fungibility', 'Junction', 'Junctions', 'MultiAsset', 'MultiAssetFilter', 'MultiLocation', 'Response', 'WildFungibility', 'WildMultiAsset', 'Xcm', 'XcmError', 'XcmOrder']; | ||
function mapXcmTypes(version) { | ||
return XCM_MAPPINGS.reduce((all, key) => (0, _util.objectSpread)(all, { | ||
[key]: `${key}${version}` | ||
}), {}); | ||
} | ||
return exports.XCM_MAPPINGS.reduce((all, key) => (0, util_1.objectSpread)(all, { [key]: `${key}${version}` }), {}); | ||
} | ||
exports.mapXcmTypes = mapXcmTypes; |
@@ -1,183 +0,151 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { BTreeMap, BTreeSet, Bytes, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Null, Option, Range, RangeInclusive, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed, WrapperKeepOpaque, WrapperOpaque } from '@polkadot/types-codec'; | ||
import { isNumber, stringify } from '@polkadot/util'; | ||
import { TypeDefInfo } from "../types/index.js"; | ||
import { getTypeDef } from "../util/getTypeDef.js"; | ||
function getTypeDefType({ | ||
lookupName, | ||
type | ||
}) { | ||
return lookupName || type; | ||
import { TypeDefInfo } from '../types/index.js'; | ||
import { getTypeDef } from '../util/getTypeDef.js'; | ||
function getTypeDefType({ lookupName, type }) { | ||
return lookupName || type; | ||
} | ||
function getSubDefArray(value) { | ||
if (!Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef[] in ${stringify(value)}`); | ||
} | ||
return value.sub; | ||
if (!Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef[] in ${stringify(value)}`); | ||
} | ||
return value.sub; | ||
} | ||
function getSubDef(value) { | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef in ${stringify(value)}`); | ||
} | ||
return value.sub; | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error(`Expected subtype as TypeDef in ${stringify(value)}`); | ||
} | ||
return value.sub; | ||
} | ||
function getSubType(value) { | ||
return getTypeDefType(getSubDef(value)); | ||
return getTypeDefType(getSubDef(value)); | ||
} | ||
// create a maps of type string CodecClasss from the input | ||
function getTypeClassMap(value) { | ||
const subs = getSubDefArray(value); | ||
const map = {}; | ||
for (let i = 0; i < subs.length; i++) { | ||
map[subs[i].name] = getTypeDefType(subs[i]); | ||
} | ||
return map; | ||
const subs = getSubDefArray(value); | ||
const map = {}; | ||
for (let i = 0; i < subs.length; i++) { | ||
map[subs[i].name] = getTypeDefType(subs[i]); | ||
} | ||
return map; | ||
} | ||
// create an array of type string CodecClasss from the input | ||
function getTypeClassArray(value) { | ||
return getSubDefArray(value).map(getTypeDefType); | ||
return getSubDefArray(value).map(getTypeDefType); | ||
} | ||
function createInt(Clazz, { | ||
displayName, | ||
length | ||
}) { | ||
if (!isNumber(length)) { | ||
throw new Error(`Expected bitLength information for ${displayName || Clazz.constructor.name}<bitLength>`); | ||
} | ||
return Clazz.with(length, displayName); | ||
function createInt(Clazz, { displayName, length }) { | ||
if (!isNumber(length)) { | ||
throw new Error(`Expected bitLength information for ${displayName || Clazz.constructor.name}<bitLength>`); | ||
} | ||
return Clazz.with(length, displayName); | ||
} | ||
function createHashMap(Clazz, value) { | ||
const [keyType, valueType] = getTypeClassArray(value); | ||
return Clazz.with(keyType, valueType); | ||
const [keyType, valueType] = getTypeClassArray(value); | ||
return Clazz.with(keyType, valueType); | ||
} | ||
function createWithSub(Clazz, value) { | ||
return Clazz.with(getSubType(value)); | ||
return Clazz.with(getSubType(value)); | ||
} | ||
const infoMapping = { | ||
[TypeDefInfo.BTreeMap]: (registry, value) => createHashMap(BTreeMap, value), | ||
[TypeDefInfo.BTreeSet]: (registry, value) => createWithSub(BTreeSet, value), | ||
[TypeDefInfo.Compact]: (registry, value) => createWithSub(Compact, value), | ||
[TypeDefInfo.DoNotConstruct]: (registry, value) => DoNotConstruct.with(value.displayName || value.type), | ||
[TypeDefInfo.Enum]: (registry, value) => { | ||
const subs = getSubDefArray(value); | ||
return Enum.with(subs.every(({ | ||
type | ||
}) => type === 'Null') ? subs.reduce((out, { | ||
index, | ||
name | ||
}, count) => { | ||
out[name] = index || count; | ||
return out; | ||
}, {}) : getTypeClassMap(value)); | ||
}, | ||
[TypeDefInfo.HashMap]: (registry, value) => createHashMap(HashMap, value), | ||
[TypeDefInfo.Int]: (registry, value) => createInt(Int, value), | ||
// We have circular deps between Linkage & Struct | ||
[TypeDefInfo.Linkage]: (registry, value) => { | ||
const type = `Option<${getSubType(value)}>`; | ||
// eslint-disable-next-line sort-keys | ||
const Clazz = Struct.with({ | ||
previous: type, | ||
next: type | ||
}); | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
Clazz.prototype.toRawType = function () { | ||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call | ||
return `Linkage<${this.next.toRawType(true)}>`; | ||
}; | ||
return Clazz; | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Null]: (registry, _) => Null, | ||
[TypeDefInfo.Option]: (registry, value) => { | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error('Expected type information for Option'); | ||
} | ||
// NOTE This is opt-in (unhandled), not by default | ||
// if (value.sub.type === 'bool') { | ||
// return OptionBool; | ||
// } | ||
return createWithSub(Option, value); | ||
}, | ||
[TypeDefInfo.Plain]: (registry, value) => registry.getOrUnknown(value.type), | ||
[TypeDefInfo.Range]: (registry, value) => createWithSub(Range, value), | ||
[TypeDefInfo.RangeInclusive]: (registry, value) => createWithSub(RangeInclusive, value), | ||
[TypeDefInfo.Result]: (registry, value) => { | ||
const [Ok, Err] = getTypeClassArray(value); | ||
// eslint-disable-next-line @typescript-eslint/no-use-before-define | ||
return Result.with({ | ||
Err, | ||
Ok | ||
}); | ||
}, | ||
[TypeDefInfo.Set]: (registry, value) => CodecSet.with(getSubDefArray(value).reduce((result, { | ||
index, | ||
name | ||
}) => { | ||
result[name] = index; | ||
return result; | ||
}, {}), value.length), | ||
[TypeDefInfo.Si]: (registry, value) => getTypeClass(registry, registry.lookup.getTypeDef(value.type)), | ||
[TypeDefInfo.Struct]: (registry, value) => Struct.with(getTypeClassMap(value), value.alias), | ||
[TypeDefInfo.Tuple]: (registry, value) => Tuple.with(getTypeClassArray(value)), | ||
[TypeDefInfo.UInt]: (registry, value) => createInt(UInt, value), | ||
[TypeDefInfo.Vec]: (registry, { | ||
sub | ||
}) => { | ||
if (!sub || Array.isArray(sub)) { | ||
throw new Error('Expected type information for vector'); | ||
} | ||
return sub.type === 'u8' ? Bytes : Vec.with(getTypeDefType(sub)); | ||
}, | ||
[TypeDefInfo.VecFixed]: (registry, { | ||
displayName, | ||
length, | ||
sub | ||
}) => { | ||
if (!isNumber(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Expected length & type information for fixed vector'); | ||
} | ||
return sub.type === 'u8' ? U8aFixed.with(length * 8, displayName) : VecFixed.with(getTypeDefType(sub), length); | ||
}, | ||
[TypeDefInfo.WrapperKeepOpaque]: (registry, value) => createWithSub(WrapperKeepOpaque, value), | ||
[TypeDefInfo.WrapperOpaque]: (registry, value) => createWithSub(WrapperOpaque, value) | ||
[TypeDefInfo.BTreeMap]: (registry, value) => createHashMap(BTreeMap, value), | ||
[TypeDefInfo.BTreeSet]: (registry, value) => createWithSub(BTreeSet, value), | ||
[TypeDefInfo.Compact]: (registry, value) => createWithSub(Compact, value), | ||
[TypeDefInfo.DoNotConstruct]: (registry, value) => DoNotConstruct.with(value.displayName || value.type), | ||
[TypeDefInfo.Enum]: (registry, value) => { | ||
const subs = getSubDefArray(value); | ||
return Enum.with(subs.every(({ type }) => type === 'Null') | ||
? subs.reduce((out, { index, name }, count) => { | ||
out[name] = index || count; | ||
return out; | ||
}, {}) | ||
: getTypeClassMap(value)); | ||
}, | ||
[TypeDefInfo.HashMap]: (registry, value) => createHashMap(HashMap, value), | ||
[TypeDefInfo.Int]: (registry, value) => createInt(Int, value), | ||
// We have circular deps between Linkage & Struct | ||
[TypeDefInfo.Linkage]: (registry, value) => { | ||
const type = `Option<${getSubType(value)}>`; | ||
// eslint-disable-next-line sort-keys | ||
const Clazz = Struct.with({ previous: type, next: type }); | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
Clazz.prototype.toRawType = function () { | ||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call | ||
return `Linkage<${this.next.toRawType(true)}>`; | ||
}; | ||
return Clazz; | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Null]: (registry, _) => Null, | ||
[TypeDefInfo.Option]: (registry, value) => { | ||
if (!value.sub || Array.isArray(value.sub)) { | ||
throw new Error('Expected type information for Option'); | ||
} | ||
// NOTE This is opt-in (unhandled), not by default | ||
// if (value.sub.type === 'bool') { | ||
// return OptionBool; | ||
// } | ||
return createWithSub(Option, value); | ||
}, | ||
[TypeDefInfo.Plain]: (registry, value) => registry.getOrUnknown(value.type), | ||
[TypeDefInfo.Range]: (registry, value) => createWithSub(Range, value), | ||
[TypeDefInfo.RangeInclusive]: (registry, value) => createWithSub(RangeInclusive, value), | ||
[TypeDefInfo.Result]: (registry, value) => { | ||
const [Ok, Err] = getTypeClassArray(value); | ||
// eslint-disable-next-line @typescript-eslint/no-use-before-define | ||
return Result.with({ Err, Ok }); | ||
}, | ||
[TypeDefInfo.Set]: (registry, value) => CodecSet.with(getSubDefArray(value).reduce((result, { index, name }) => { | ||
result[name] = index; | ||
return result; | ||
}, {}), value.length), | ||
[TypeDefInfo.Si]: (registry, value) => getTypeClass(registry, registry.lookup.getTypeDef(value.type)), | ||
[TypeDefInfo.Struct]: (registry, value) => Struct.with(getTypeClassMap(value), value.alias), | ||
[TypeDefInfo.Tuple]: (registry, value) => Tuple.with(getTypeClassArray(value)), | ||
[TypeDefInfo.UInt]: (registry, value) => createInt(UInt, value), | ||
[TypeDefInfo.Vec]: (registry, { sub }) => { | ||
if (!sub || Array.isArray(sub)) { | ||
throw new Error('Expected type information for vector'); | ||
} | ||
return (sub.type === 'u8' | ||
? Bytes | ||
: Vec.with(getTypeDefType(sub))); | ||
}, | ||
[TypeDefInfo.VecFixed]: (registry, { displayName, length, sub }) => { | ||
if (!isNumber(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Expected length & type information for fixed vector'); | ||
} | ||
return (sub.type === 'u8' | ||
? U8aFixed.with((length * 8), displayName) | ||
: VecFixed.with(getTypeDefType(sub), length)); | ||
}, | ||
[TypeDefInfo.WrapperKeepOpaque]: (registry, value) => createWithSub(WrapperKeepOpaque, value), | ||
[TypeDefInfo.WrapperOpaque]: (registry, value) => createWithSub(WrapperOpaque, value) | ||
}; | ||
export function constructTypeClass(registry, typeDef) { | ||
try { | ||
const Type = infoMapping[typeDef.info](registry, typeDef); | ||
if (!Type) { | ||
throw new Error('No class created'); | ||
try { | ||
const Type = infoMapping[typeDef.info](registry, typeDef); | ||
if (!Type) { | ||
throw new Error('No class created'); | ||
} | ||
// don't clobber any existing | ||
if (!Type.__fallbackType && typeDef.fallbackType) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-ignore ...this is the only place we we actually assign this... | ||
Type.__fallbackType = typeDef.fallbackType; | ||
} | ||
return Type; | ||
} | ||
// don't clobber any existing | ||
if (!Type.__fallbackType && typeDef.fallbackType) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-ignore ...this is the only place we we actually assign this... | ||
Type.__fallbackType = typeDef.fallbackType; | ||
catch (error) { | ||
throw new Error(`Unable to construct class from ${stringify(typeDef)}: ${error.message}`); | ||
} | ||
return Type; | ||
} catch (error) { | ||
throw new Error(`Unable to construct class from ${stringify(typeDef)}: ${error.message}`); | ||
} | ||
} | ||
// Returns the type Class for construction | ||
export function getTypeClass(registry, typeDef) { | ||
return registry.getUnsafe(typeDef.type, false, typeDef); | ||
return registry.getUnsafe(typeDef.type, false, typeDef); | ||
} | ||
export function createClassUnsafe(registry, type) { | ||
return ( | ||
return ( | ||
// just retrieve via name, no creation via typeDef | ||
registry.getUnsafe(type) || | ||
// we don't have an existing type, create the class via typeDef | ||
getTypeClass(registry, registry.isLookupType(type) ? registry.lookup.getTypeDef(type) : getTypeDef(type)) | ||
); | ||
// we don't have an existing type, create the class via typeDef | ||
getTypeClass(registry, registry.isLookupType(type) | ||
? registry.lookup.getTypeDef(type) | ||
: getTypeDef(type))); | ||
} |
@@ -1,5 +0,2 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
export * from "./class.js"; | ||
export * from "./type.js"; | ||
export * from './class.js'; | ||
export * from './type.js'; |
@@ -1,72 +0,63 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { Option } from '@polkadot/types-codec'; | ||
import { isHex, isU8a, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util'; | ||
import { createClassUnsafe } from "./class.js"; | ||
// With isPedantic, actually check that the encoding matches that supplied. This | ||
// is much slower, but verifies that we have the correct types defined | ||
import { createClassUnsafe } from './class.js'; | ||
function checkInstance(created, matcher) { | ||
const u8a = created.toU8a(); | ||
const rawType = created.toRawType(); | ||
const isOk = | ||
// full match, all ok | ||
u8aEq(u8a, matcher) || | ||
// on a length-prefixed type, just check the actual length | ||
['Bytes', 'Text', 'Type'].includes(rawType) && matcher.length === created.length || | ||
// when the created is empty and matcher is also empty, let it slide... | ||
created.isEmpty && matcher.every(v => !v); | ||
if (!isOk) { | ||
throw new Error(`${rawType}:: Decoded input doesn't match input, received ${u8aToHex(matcher, 512)} (${matcher.length} bytes), created ${u8aToHex(u8a, 512)} (${u8a.length} bytes)`); | ||
} | ||
const u8a = created.toU8a(); | ||
const rawType = created.toRawType(); | ||
const isOk = ( | ||
// full match, all ok | ||
u8aEq(u8a, matcher) || | ||
( | ||
// on a length-prefixed type, just check the actual length | ||
['Bytes', 'Text', 'Type'].includes(rawType) && | ||
matcher.length === created.length) || | ||
( | ||
// when the created is empty and matcher is also empty, let it slide... | ||
created.isEmpty && | ||
matcher.every((v) => !v))); | ||
if (!isOk) { | ||
throw new Error(`${rawType}:: Decoded input doesn't match input, received ${u8aToHex(matcher, 512)} (${matcher.length} bytes), created ${u8aToHex(u8a, 512)} (${u8a.length} bytes)`); | ||
} | ||
} | ||
function checkPedantic(created, [value]) { | ||
if (isU8a(value)) { | ||
checkInstance(created, value); | ||
} else if (isHex(value)) { | ||
checkInstance(created, u8aToU8a(value)); | ||
} | ||
if (isU8a(value)) { | ||
checkInstance(created, value); | ||
} | ||
else if (isHex(value)) { | ||
checkInstance(created, u8aToU8a(value)); | ||
} | ||
} | ||
// Initializes a type with a value. This also checks for fallbacks and in the cases | ||
// where isPedantic is specified (storage decoding), also check the format/structure | ||
function initType(registry, Type, params = [], { | ||
blockHash, | ||
isFallback, | ||
isOptional, | ||
isPedantic | ||
} = {}) { | ||
const created = new (isOptional ? Option.with(Type) : Type)(registry, ...params); | ||
isPedantic && checkPedantic(created, params); | ||
if (blockHash) { | ||
created.createdAtHash = createTypeUnsafe(registry, 'BlockHash', [blockHash]); | ||
} | ||
if (isFallback) { | ||
created.isStorageFallback = true; | ||
} | ||
return created; | ||
function initType(registry, Type, params = [], { blockHash, isFallback, isOptional, isPedantic } = {}) { | ||
const created = new (isOptional | ||
? Option.with(Type) | ||
: Type)(registry, ...params); | ||
isPedantic && checkPedantic(created, params); | ||
if (blockHash) { | ||
created.createdAtHash = createTypeUnsafe(registry, 'BlockHash', [blockHash]); | ||
} | ||
if (isFallback) { | ||
created.isStorageFallback = true; | ||
} | ||
return created; | ||
} | ||
// An unsafe version of the `createType` below. It's unsafe because the `type` | ||
// argument here can be any string, which, when it cannot parse, will yield a | ||
// runtime error. | ||
export function createTypeUnsafe(registry, type, params = [], options = {}) { | ||
let Clazz = null; | ||
let firstError = null; | ||
try { | ||
Clazz = createClassUnsafe(registry, type); | ||
return initType(registry, Clazz, params, options); | ||
} catch (error) { | ||
firstError = new Error(`createType(${type}):: ${error.message}`); | ||
} | ||
if (Clazz && Clazz.__fallbackType) { | ||
let Clazz = null; | ||
let firstError = null; | ||
try { | ||
Clazz = createClassUnsafe(registry, Clazz.__fallbackType); | ||
return initType(registry, Clazz, params, options); | ||
} catch { | ||
// swallow, we will throw the first error again | ||
Clazz = createClassUnsafe(registry, type); | ||
return initType(registry, Clazz, params, options); | ||
} | ||
} | ||
throw firstError; | ||
catch (error) { | ||
firstError = new Error(`createType(${type}):: ${error.message}`); | ||
} | ||
if (Clazz && Clazz.__fallbackType) { | ||
try { | ||
Clazz = createClassUnsafe(registry, Clazz.__fallbackType); | ||
return initType(registry, Clazz, params, options); | ||
} | ||
catch { | ||
// swallow, we will throw the first error again | ||
} | ||
} | ||
throw firstError; | ||
} |
@@ -1,5 +0,2 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { packageInfo as codecInfo } from '@polkadot/types-codec/packageInfo'; | ||
export default [codecInfo]; |
@@ -1,9 +0,4 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// Do not edit, auto-generated by @polkadot/dev | ||
import { detectPackage } from '@polkadot/util'; | ||
import others from "./detectOther.js"; | ||
import { packageInfo } from "./packageInfo.js"; | ||
import others from './detectOther.js'; | ||
import { packageInfo } from './packageInfo.js'; | ||
detectPackage(packageInfo, null, others); |
@@ -1,5 +0,2 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import "./detectPackage.js"; | ||
export * from "./bundle.js"; | ||
import './detectPackage.js'; | ||
export * from './bundle.js'; |
@@ -23,3 +23,3 @@ { | ||
"type": "module", | ||
"version": "9.14.2", | ||
"version": "10.0.1", | ||
"main": "./cjs/index.js", | ||
@@ -66,3 +66,6 @@ "module": "./index.js", | ||
}, | ||
"./package.json": "./package.json", | ||
"./package.json": { | ||
"require": "./cjs/package.json", | ||
"default": "./package.json" | ||
}, | ||
"./packageInfo.js": { | ||
@@ -125,6 +128,6 @@ "types": "./packageInfo.d.ts", | ||
"dependencies": { | ||
"@babel/runtime": "^7.20.13", | ||
"@polkadot/types-codec": "9.14.2", | ||
"@polkadot/util": "^10.4.2" | ||
"@polkadot/types-codec": "10.0.1", | ||
"@polkadot/util": "^11.0.1", | ||
"tslib": "^2.5.0" | ||
} | ||
} |
@@ -1,11 +0,1 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// Do not edit, auto-generated by @polkadot/dev | ||
export const packageInfo = { | ||
name: '@polkadot/types-create', | ||
path: (import.meta && import.meta.url) ? new URL(import.meta.url).pathname.substring(0, new URL(import.meta.url).pathname.lastIndexOf('/') + 1) : 'auto', | ||
type: 'esm', | ||
version: '9.14.2' | ||
}; | ||
export const packageInfo = { name: '@polkadot/types-create', path: (import.meta && import.meta.url) ? new URL(import.meta.url).pathname.substring(0, new URL(import.meta.url).pathname.lastIndexOf('/') + 1) : 'auto', type: 'esm', version: '10.0.1' }; |
@@ -1,6 +0,1 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// import type lookup before we augment - in some environments | ||
// this is required to allow for ambient/previous definitions | ||
import '@polkadot/types-codec/types/registry'; |
@@ -1,6 +0,3 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import "./augmentRegistry.js"; | ||
export * from "./lookup.js"; | ||
export * from "./types.js"; | ||
import './augmentRegistry.js'; | ||
export * from './lookup.js'; | ||
export * from './types.js'; |
@@ -1,29 +0,26 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
export let TypeDefInfo; | ||
export var TypeDefInfo; | ||
(function (TypeDefInfo) { | ||
TypeDefInfo[TypeDefInfo["BTreeMap"] = 0] = "BTreeMap"; | ||
TypeDefInfo[TypeDefInfo["BTreeSet"] = 1] = "BTreeSet"; | ||
TypeDefInfo[TypeDefInfo["Compact"] = 2] = "Compact"; | ||
TypeDefInfo[TypeDefInfo["DoNotConstruct"] = 3] = "DoNotConstruct"; | ||
TypeDefInfo[TypeDefInfo["Enum"] = 4] = "Enum"; | ||
TypeDefInfo[TypeDefInfo["HashMap"] = 5] = "HashMap"; | ||
TypeDefInfo[TypeDefInfo["Int"] = 6] = "Int"; | ||
TypeDefInfo[TypeDefInfo["Linkage"] = 7] = "Linkage"; | ||
TypeDefInfo[TypeDefInfo["Null"] = 8] = "Null"; | ||
TypeDefInfo[TypeDefInfo["Option"] = 9] = "Option"; | ||
TypeDefInfo[TypeDefInfo["Plain"] = 10] = "Plain"; | ||
TypeDefInfo[TypeDefInfo["Range"] = 11] = "Range"; | ||
TypeDefInfo[TypeDefInfo["RangeInclusive"] = 12] = "RangeInclusive"; | ||
TypeDefInfo[TypeDefInfo["Result"] = 13] = "Result"; | ||
TypeDefInfo[TypeDefInfo["Set"] = 14] = "Set"; | ||
TypeDefInfo[TypeDefInfo["Si"] = 15] = "Si"; | ||
TypeDefInfo[TypeDefInfo["Struct"] = 16] = "Struct"; | ||
TypeDefInfo[TypeDefInfo["Tuple"] = 17] = "Tuple"; | ||
TypeDefInfo[TypeDefInfo["UInt"] = 18] = "UInt"; | ||
TypeDefInfo[TypeDefInfo["Vec"] = 19] = "Vec"; | ||
TypeDefInfo[TypeDefInfo["VecFixed"] = 20] = "VecFixed"; | ||
TypeDefInfo[TypeDefInfo["WrapperKeepOpaque"] = 21] = "WrapperKeepOpaque"; | ||
TypeDefInfo[TypeDefInfo["WrapperOpaque"] = 22] = "WrapperOpaque"; | ||
TypeDefInfo[TypeDefInfo["BTreeMap"] = 0] = "BTreeMap"; | ||
TypeDefInfo[TypeDefInfo["BTreeSet"] = 1] = "BTreeSet"; | ||
TypeDefInfo[TypeDefInfo["Compact"] = 2] = "Compact"; | ||
TypeDefInfo[TypeDefInfo["DoNotConstruct"] = 3] = "DoNotConstruct"; | ||
TypeDefInfo[TypeDefInfo["Enum"] = 4] = "Enum"; | ||
TypeDefInfo[TypeDefInfo["HashMap"] = 5] = "HashMap"; | ||
TypeDefInfo[TypeDefInfo["Int"] = 6] = "Int"; | ||
TypeDefInfo[TypeDefInfo["Linkage"] = 7] = "Linkage"; | ||
TypeDefInfo[TypeDefInfo["Null"] = 8] = "Null"; | ||
TypeDefInfo[TypeDefInfo["Option"] = 9] = "Option"; | ||
TypeDefInfo[TypeDefInfo["Plain"] = 10] = "Plain"; | ||
TypeDefInfo[TypeDefInfo["Range"] = 11] = "Range"; | ||
TypeDefInfo[TypeDefInfo["RangeInclusive"] = 12] = "RangeInclusive"; | ||
TypeDefInfo[TypeDefInfo["Result"] = 13] = "Result"; | ||
TypeDefInfo[TypeDefInfo["Set"] = 14] = "Set"; | ||
TypeDefInfo[TypeDefInfo["Si"] = 15] = "Si"; | ||
TypeDefInfo[TypeDefInfo["Struct"] = 16] = "Struct"; | ||
TypeDefInfo[TypeDefInfo["Tuple"] = 17] = "Tuple"; | ||
TypeDefInfo[TypeDefInfo["UInt"] = 18] = "UInt"; | ||
TypeDefInfo[TypeDefInfo["Vec"] = 19] = "Vec"; | ||
TypeDefInfo[TypeDefInfo["VecFixed"] = 20] = "VecFixed"; | ||
TypeDefInfo[TypeDefInfo["WrapperKeepOpaque"] = 21] = "WrapperKeepOpaque"; | ||
TypeDefInfo[TypeDefInfo["WrapperOpaque"] = 22] = "WrapperOpaque"; | ||
})(TypeDefInfo || (TypeDefInfo = {})); |
@@ -1,168 +0,124 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { isNumber, isUndefined, objectSpread, stringify } from '@polkadot/util'; | ||
import { TypeDefInfo } from "../types/index.js"; | ||
const stringIdentity = value => value.toString(); | ||
import { TypeDefInfo } from '../types/index.js'; | ||
const stringIdentity = (value) => value.toString(); | ||
const INFO_WRAP = ['BTreeMap', 'BTreeSet', 'Compact', 'HashMap', 'Option', 'Result', 'Vec']; | ||
export function paramsNotation(outer, inner, transform = stringIdentity) { | ||
return `${outer}${inner ? `<${(Array.isArray(inner) ? inner : [inner]).map(transform).join(', ')}>` : ''}`; | ||
return `${outer}${inner | ||
? `<${(Array.isArray(inner) ? inner : [inner]).map(transform).join(', ')}>` | ||
: ''}`; | ||
} | ||
function encodeWithParams(registry, typeDef, outer) { | ||
const { | ||
info, | ||
sub | ||
} = typeDef; | ||
switch (info) { | ||
case TypeDefInfo.BTreeMap: | ||
case TypeDefInfo.BTreeSet: | ||
case TypeDefInfo.Compact: | ||
case TypeDefInfo.HashMap: | ||
case TypeDefInfo.Linkage: | ||
case TypeDefInfo.Option: | ||
case TypeDefInfo.Range: | ||
case TypeDefInfo.RangeInclusive: | ||
case TypeDefInfo.Result: | ||
case TypeDefInfo.Vec: | ||
case TypeDefInfo.WrapperKeepOpaque: | ||
case TypeDefInfo.WrapperOpaque: | ||
return paramsNotation(outer, sub, p => encodeTypeDef(registry, p)); | ||
} | ||
throw new Error(`Unable to encode ${stringify(typeDef)} with params`); | ||
const { info, sub } = typeDef; | ||
switch (info) { | ||
case TypeDefInfo.BTreeMap: | ||
case TypeDefInfo.BTreeSet: | ||
case TypeDefInfo.Compact: | ||
case TypeDefInfo.HashMap: | ||
case TypeDefInfo.Linkage: | ||
case TypeDefInfo.Option: | ||
case TypeDefInfo.Range: | ||
case TypeDefInfo.RangeInclusive: | ||
case TypeDefInfo.Result: | ||
case TypeDefInfo.Vec: | ||
case TypeDefInfo.WrapperKeepOpaque: | ||
case TypeDefInfo.WrapperOpaque: | ||
return paramsNotation(outer, sub, (p) => encodeTypeDef(registry, p)); | ||
} | ||
throw new Error(`Unable to encode ${stringify(typeDef)} with params`); | ||
} | ||
function encodeSubTypes(registry, sub, asEnum, extra) { | ||
const names = sub.map(({ | ||
name | ||
}) => name); | ||
if (!names.every(n => !!n)) { | ||
throw new Error(`Subtypes does not have consistent names, ${names.join(', ')}`); | ||
} | ||
const inner = objectSpread({}, extra); | ||
for (let i = 0; i < sub.length; i++) { | ||
const def = sub[i]; | ||
inner[def.name] = encodeTypeDef(registry, def); | ||
} | ||
return stringify(asEnum ? { | ||
_enum: inner | ||
} : inner); | ||
const names = sub.map(({ name }) => name); | ||
if (!names.every((n) => !!n)) { | ||
throw new Error(`Subtypes does not have consistent names, ${names.join(', ')}`); | ||
} | ||
const inner = objectSpread({}, extra); | ||
for (let i = 0; i < sub.length; i++) { | ||
const def = sub[i]; | ||
inner[def.name] = encodeTypeDef(registry, def); | ||
} | ||
return stringify(asEnum | ||
? { _enum: inner } | ||
: inner); | ||
} | ||
// We setup a record here to ensure we have comprehensive coverage (any item not covered will result | ||
// in a compile-time error with the missing index) | ||
const encoders = { | ||
[TypeDefInfo.BTreeMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeMap'), | ||
[TypeDefInfo.BTreeSet]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeSet'), | ||
[TypeDefInfo.Compact]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Compact'), | ||
[TypeDefInfo.DoNotConstruct]: (registry, { | ||
displayName, | ||
lookupIndex, | ||
lookupName | ||
}) => `DoNotConstruct<${lookupName || displayName || (isUndefined(lookupIndex) ? 'Unknown' : registry.createLookupType(lookupIndex))}>`, | ||
[TypeDefInfo.Enum]: (registry, { | ||
sub | ||
}) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Enum type'); | ||
} | ||
// c-like enums have all Null entries | ||
// TODO We need to take the disciminant into account and auto-add empty entries | ||
return sub.every(({ | ||
type | ||
}) => type === 'Null') ? stringify({ | ||
_enum: sub.map(({ | ||
name | ||
}, index) => `${name || `Empty${index}`}`) | ||
}) : encodeSubTypes(registry, sub, true); | ||
}, | ||
[TypeDefInfo.HashMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'HashMap'), | ||
[TypeDefInfo.Int]: (registry, { | ||
length = 32 | ||
}) => `Int<${length}>`, | ||
[TypeDefInfo.Linkage]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Linkage'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Null]: (registry, typeDef) => 'Null', | ||
[TypeDefInfo.Option]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Option'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Plain]: (registry, { | ||
displayName, | ||
type | ||
}) => displayName || type, | ||
[TypeDefInfo.Range]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Range'), | ||
[TypeDefInfo.RangeInclusive]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'RangeInclusive'), | ||
[TypeDefInfo.Result]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Result'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Set]: (registry, { | ||
length = 8, | ||
sub | ||
}) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Set type'); | ||
} | ||
return stringify({ | ||
_set: sub.reduce((all, { | ||
index, | ||
name | ||
}, count) => objectSpread(all, { | ||
[`${name || `Unknown${index || count}`}`]: index || count | ||
}), { | ||
_bitLength: length || 8 | ||
}) | ||
}); | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Si]: (registry, { | ||
lookupName, | ||
type | ||
}) => lookupName || type, | ||
[TypeDefInfo.Struct]: (registry, { | ||
alias, | ||
sub | ||
}) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Struct type'); | ||
} | ||
return encodeSubTypes(registry, sub, false, alias ? { | ||
_alias: [...alias.entries()].reduce((all, [k, v]) => objectSpread(all, { | ||
[k]: v | ||
}), {}) | ||
} : {}); | ||
}, | ||
[TypeDefInfo.Tuple]: (registry, { | ||
sub | ||
}) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Tuple type'); | ||
} | ||
return `(${sub.map(type => encodeTypeDef(registry, type)).join(',')})`; | ||
}, | ||
[TypeDefInfo.UInt]: (registry, { | ||
length = 32 | ||
}) => `UInt<${length}>`, | ||
[TypeDefInfo.Vec]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Vec'), | ||
[TypeDefInfo.VecFixed]: (registry, { | ||
length, | ||
sub | ||
}) => { | ||
if (!isNumber(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Unable to encode VecFixed type'); | ||
} | ||
return `[${sub.type};${length}]`; | ||
}, | ||
[TypeDefInfo.WrapperKeepOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperKeepOpaque'), | ||
[TypeDefInfo.WrapperOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperOpaque') | ||
[TypeDefInfo.BTreeMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeMap'), | ||
[TypeDefInfo.BTreeSet]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'BTreeSet'), | ||
[TypeDefInfo.Compact]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Compact'), | ||
[TypeDefInfo.DoNotConstruct]: (registry, { displayName, lookupIndex, lookupName }) => `DoNotConstruct<${lookupName || displayName || (isUndefined(lookupIndex) ? 'Unknown' : registry.createLookupType(lookupIndex))}>`, | ||
[TypeDefInfo.Enum]: (registry, { sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Enum type'); | ||
} | ||
// c-like enums have all Null entries | ||
// TODO We need to take the disciminant into account and auto-add empty entries | ||
return sub.every(({ type }) => type === 'Null') | ||
? stringify({ _enum: sub.map(({ name }, index) => `${name || `Empty${index}`}`) }) | ||
: encodeSubTypes(registry, sub, true); | ||
}, | ||
[TypeDefInfo.HashMap]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'HashMap'), | ||
[TypeDefInfo.Int]: (registry, { length = 32 }) => `Int<${length}>`, | ||
[TypeDefInfo.Linkage]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Linkage'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Null]: (registry, typeDef) => 'Null', | ||
[TypeDefInfo.Option]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Option'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Plain]: (registry, { displayName, type }) => displayName || type, | ||
[TypeDefInfo.Range]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Range'), | ||
[TypeDefInfo.RangeInclusive]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'RangeInclusive'), | ||
[TypeDefInfo.Result]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Result'), | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Set]: (registry, { length = 8, sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Set type'); | ||
} | ||
return stringify({ | ||
_set: sub.reduce((all, { index, name }, count) => objectSpread(all, { [`${name || `Unknown${index || count}`}`]: index || count }), { _bitLength: length || 8 }) | ||
}); | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
[TypeDefInfo.Si]: (registry, { lookupName, type }) => lookupName || type, | ||
[TypeDefInfo.Struct]: (registry, { alias, sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Struct type'); | ||
} | ||
return encodeSubTypes(registry, sub, false, alias | ||
? { | ||
_alias: [...alias.entries()].reduce((all, [k, v]) => objectSpread(all, { [k]: v }), {}) | ||
} | ||
: {}); | ||
}, | ||
[TypeDefInfo.Tuple]: (registry, { sub }) => { | ||
if (!Array.isArray(sub)) { | ||
throw new Error('Unable to encode Tuple type'); | ||
} | ||
return `(${sub.map((type) => encodeTypeDef(registry, type)).join(',')})`; | ||
}, | ||
[TypeDefInfo.UInt]: (registry, { length = 32 }) => `UInt<${length}>`, | ||
[TypeDefInfo.Vec]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'Vec'), | ||
[TypeDefInfo.VecFixed]: (registry, { length, sub }) => { | ||
if (!isNumber(length) || !sub || Array.isArray(sub)) { | ||
throw new Error('Unable to encode VecFixed type'); | ||
} | ||
return `[${sub.type};${length}]`; | ||
}, | ||
[TypeDefInfo.WrapperKeepOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperKeepOpaque'), | ||
[TypeDefInfo.WrapperOpaque]: (registry, typeDef) => encodeWithParams(registry, typeDef, 'WrapperOpaque') | ||
}; | ||
function encodeType(registry, typeDef, withLookup = true) { | ||
return withLookup && typeDef.lookupName ? typeDef.lookupName : encoders[typeDef.info](registry, typeDef); | ||
return withLookup && typeDef.lookupName | ||
? typeDef.lookupName | ||
: encoders[typeDef.info](registry, typeDef); | ||
} | ||
export function encodeTypeDef(registry, typeDef) { | ||
// In the case of contracts we do have the unfortunate situation where the displayName would | ||
// refer to "Option" when it is an option. For these, string it out, only using when actually | ||
// not a top-level element to be used | ||
return typeDef.displayName && !INFO_WRAP.some(i => typeDef.displayName === i) ? typeDef.displayName : encodeType(registry, typeDef); | ||
// In the case of contracts we do have the unfortunate situation where the displayName would | ||
// refer to "Option" when it is an option. For these, string it out, only using when actually | ||
// not a top-level element to be used | ||
return (typeDef.displayName && !INFO_WRAP.some((i) => typeDef.displayName === i)) | ||
? typeDef.displayName | ||
: encodeType(registry, typeDef); | ||
} | ||
export function withTypeString(registry, typeDef) { | ||
return objectSpread({}, typeDef, { | ||
type: encodeType(registry, typeDef, false) | ||
}); | ||
return objectSpread({}, typeDef, { | ||
type: encodeType(registry, typeDef, false) | ||
}); | ||
} |
@@ -1,198 +0,192 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { sanitize } from '@polkadot/types-codec'; | ||
import { isNumber, isString, objectSpread } from '@polkadot/util'; | ||
import { TypeDefInfo } from "../types/index.js"; | ||
import { typeSplit } from "./typeSplit.js"; | ||
import { TypeDefInfo } from '../types/index.js'; | ||
import { typeSplit } from './typeSplit.js'; | ||
const KNOWN_INTERNALS = ['_alias', '_fallback']; | ||
function getTypeString(typeOrObj) { | ||
return isString(typeOrObj) ? typeOrObj.toString() : JSON.stringify(typeOrObj); | ||
return isString(typeOrObj) | ||
? typeOrObj.toString() | ||
: JSON.stringify(typeOrObj); | ||
} | ||
function isRustEnum(details) { | ||
const values = Object.values(details); | ||
if (values.some(v => isNumber(v))) { | ||
if (!values.every(v => isNumber(v) && v >= 0 && v <= 255)) { | ||
throw new Error('Invalid number-indexed enum definition'); | ||
const values = Object.values(details); | ||
if (values.some((v) => isNumber(v))) { | ||
if (!values.every((v) => isNumber(v) && v >= 0 && v <= 255)) { | ||
throw new Error('Invalid number-indexed enum definition'); | ||
} | ||
return false; | ||
} | ||
return false; | ||
} | ||
return true; | ||
return true; | ||
} | ||
// decode an enum of either of the following forms | ||
// { _enum: ['A', 'B', 'C'] } | ||
// { _enum: { A: AccountId, B: Balance, C: u32 } } | ||
// { _enum: { A: 1, B: 2 } } | ||
function _decodeEnum(value, details, count, fallbackType) { | ||
value.info = TypeDefInfo.Enum; | ||
value.fallbackType = fallbackType; | ||
// not as pretty, but remain compatible with oo7 for both struct and Array types | ||
if (Array.isArray(details)) { | ||
value.sub = details.map((name, index) => ({ | ||
index, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} else if (isRustEnum(details)) { | ||
value.sub = Object.entries(details).map(([name, typeOrObj], index) => objectSpread({}, getTypeDef(getTypeString(typeOrObj || 'Null'), { | ||
name | ||
}, count), { | ||
index | ||
})); | ||
} else { | ||
value.sub = Object.entries(details).map(([name, index]) => ({ | ||
index, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} | ||
return value; | ||
value.info = TypeDefInfo.Enum; | ||
value.fallbackType = fallbackType; | ||
// not as pretty, but remain compatible with oo7 for both struct and Array types | ||
if (Array.isArray(details)) { | ||
value.sub = details.map((name, index) => ({ | ||
index, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} | ||
else if (isRustEnum(details)) { | ||
value.sub = Object.entries(details).map(([name, typeOrObj], index) => objectSpread({}, getTypeDef(getTypeString(typeOrObj || 'Null'), { name }, count), { index })); | ||
} | ||
else { | ||
value.sub = Object.entries(details).map(([name, index]) => ({ | ||
index, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
} | ||
return value; | ||
} | ||
// decode a set of the form | ||
// { _set: { A: 0b0001, B: 0b0010, C: 0b0100 } } | ||
function _decodeSet(value, details, fallbackType) { | ||
value.info = TypeDefInfo.Set; | ||
value.fallbackType = fallbackType; | ||
value.length = details._bitLength; | ||
value.sub = Object.entries(details).filter(([name]) => !name.startsWith('_')).map(([name, index]) => ({ | ||
index, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
return value; | ||
value.info = TypeDefInfo.Set; | ||
value.fallbackType = fallbackType; | ||
value.length = details._bitLength; | ||
value.sub = Object | ||
.entries(details) | ||
.filter(([name]) => !name.startsWith('_')) | ||
.map(([name, index]) => ({ | ||
index, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type: 'Null' | ||
})); | ||
return value; | ||
} | ||
// decode a struct, set or enum | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeStruct(value, type, _, count) { | ||
const parsed = JSON.parse(type); | ||
const keys = Object.keys(parsed); | ||
if (keys.includes('_enum')) { | ||
return _decodeEnum(value, parsed._enum, count, parsed._fallback); | ||
} else if (keys.includes('_set')) { | ||
return _decodeSet(value, parsed._set, parsed._fallback); | ||
} | ||
value.alias = parsed._alias ? new Map(Object.entries(parsed._alias)) : undefined; | ||
value.fallbackType = parsed._fallback; | ||
value.sub = keys.filter(name => !KNOWN_INTERNALS.includes(name)).map(name => getTypeDef(getTypeString(parsed[name]), { | ||
name | ||
}, count)); | ||
return value; | ||
const parsed = JSON.parse(type); | ||
const keys = Object.keys(parsed); | ||
if (keys.includes('_enum')) { | ||
return _decodeEnum(value, parsed._enum, count, parsed._fallback); | ||
} | ||
else if (keys.includes('_set')) { | ||
return _decodeSet(value, parsed._set, parsed._fallback); | ||
} | ||
value.alias = parsed._alias | ||
? new Map(Object.entries(parsed._alias)) | ||
: undefined; | ||
value.fallbackType = parsed._fallback; | ||
value.sub = keys | ||
.filter((name) => !KNOWN_INTERNALS.includes(name)) | ||
.map((name) => getTypeDef(getTypeString(parsed[name]), { name }, count)); | ||
return value; | ||
} | ||
// decode a fixed vector, e.g. [u8;32] | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeFixedVec(value, type, _, count) { | ||
const max = type.length - 1; | ||
let index = -1; | ||
let inner = 0; | ||
for (let i = 1; i < max && index === -1; i++) { | ||
switch (type[i]) { | ||
case ';': | ||
{ | ||
if (inner === 0) { | ||
index = i; | ||
} | ||
break; | ||
const max = type.length - 1; | ||
let index = -1; | ||
let inner = 0; | ||
for (let i = 1; (i < max) && (index === -1); i++) { | ||
switch (type[i]) { | ||
case ';': { | ||
if (inner === 0) { | ||
index = i; | ||
} | ||
break; | ||
} | ||
case '[': | ||
case '(': | ||
case '<': | ||
inner++; | ||
break; | ||
case ']': | ||
case ')': | ||
case '>': | ||
inner--; | ||
break; | ||
} | ||
case '[': | ||
case '(': | ||
case '<': | ||
inner++; | ||
break; | ||
case ']': | ||
case ')': | ||
case '>': | ||
inner--; | ||
break; | ||
} | ||
} | ||
if (index === -1) { | ||
throw new Error(`${type}: Unable to extract location of ';'`); | ||
} | ||
const vecType = type.substring(1, index); | ||
const [strLength, displayName] = type.substring(index + 1, max).split(';'); | ||
const length = parseInt(strLength.trim(), 10); | ||
if (length > 2048) { | ||
throw new Error(`${type}: Only support for [Type; <length>], where length <= 2048`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
value.sub = getTypeDef(vecType, {}, count); | ||
return value; | ||
if (index === -1) { | ||
throw new Error(`${type}: Unable to extract location of ';'`); | ||
} | ||
const vecType = type.substring(1, index); | ||
const [strLength, displayName] = type.substring(index + 1, max).split(';'); | ||
const length = parseInt(strLength.trim(), 10); | ||
if (length > 2048) { | ||
throw new Error(`${type}: Only support for [Type; <length>], where length <= 2048`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
value.sub = getTypeDef(vecType, {}, count); | ||
return value; | ||
} | ||
// decode a tuple | ||
function _decodeTuple(value, _, subType, count) { | ||
value.sub = subType.length === 0 ? [] : typeSplit(subType).map(inner => getTypeDef(inner, {}, count)); | ||
return value; | ||
value.sub = subType.length === 0 | ||
? [] | ||
: typeSplit(subType).map((inner) => getTypeDef(inner, {}, count)); | ||
return value; | ||
} | ||
// decode a Int/UInt<bitLength[, name]> | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeAnyInt(value, type, _, clazz) { | ||
const [strLength, displayName] = type.substring(clazz.length + 1, type.length - 1).split(','); | ||
const length = parseInt(strLength.trim(), 10); | ||
if (length > 8192 || length % 8) { | ||
throw new Error(`${type}: Only support for ${clazz}<bitLength>, where length <= 8192 and a power of 8, found ${length}`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
return value; | ||
const [strLength, displayName] = type.substring(clazz.length + 1, type.length - 1).split(','); | ||
const length = parseInt(strLength.trim(), 10); | ||
if ((length > 8192) || (length % 8)) { | ||
throw new Error(`${type}: Only support for ${clazz}<bitLength>, where length <= 8192 and a power of 8, found ${length}`); | ||
} | ||
value.displayName = displayName; | ||
value.length = length; | ||
return value; | ||
} | ||
function _decodeInt(value, type, subType) { | ||
return _decodeAnyInt(value, type, subType, 'Int'); | ||
return _decodeAnyInt(value, type, subType, 'Int'); | ||
} | ||
function _decodeUInt(value, type, subType) { | ||
return _decodeAnyInt(value, type, subType, 'UInt'); | ||
return _decodeAnyInt(value, type, subType, 'UInt'); | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
function _decodeDoNotConstruct(value, type, _) { | ||
const NAME_LENGTH = 'DoNotConstruct'.length; | ||
value.displayName = type.substring(NAME_LENGTH + 1, type.length - 1); | ||
return value; | ||
const NAME_LENGTH = 'DoNotConstruct'.length; | ||
value.displayName = type.substring(NAME_LENGTH + 1, type.length - 1); | ||
return value; | ||
} | ||
function hasWrapper(type, [start, end]) { | ||
return type.substring(0, start.length) === start && type.slice(-1 * end.length) === end; | ||
return (type.substring(0, start.length) === start) && (type.slice(-1 * end.length) === end); | ||
} | ||
const nestedExtraction = [['[', ']', TypeDefInfo.VecFixed, _decodeFixedVec], ['{', '}', TypeDefInfo.Struct, _decodeStruct], ['(', ')', TypeDefInfo.Tuple, _decodeTuple], | ||
// the inner for these are the same as tuple, multiple values | ||
['BTreeMap<', '>', TypeDefInfo.BTreeMap, _decodeTuple], ['HashMap<', '>', TypeDefInfo.HashMap, _decodeTuple], ['Int<', '>', TypeDefInfo.Int, _decodeInt], ['Result<', '>', TypeDefInfo.Result, _decodeTuple], ['UInt<', '>', TypeDefInfo.UInt, _decodeUInt], ['DoNotConstruct<', '>', TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct]]; | ||
const wrappedExtraction = [['BTreeSet<', '>', TypeDefInfo.BTreeSet], ['Compact<', '>', TypeDefInfo.Compact], ['Linkage<', '>', TypeDefInfo.Linkage], ['Opaque<', '>', TypeDefInfo.WrapperOpaque], ['Option<', '>', TypeDefInfo.Option], ['Range<', '>', TypeDefInfo.Range], ['RangeInclusive<', '>', TypeDefInfo.RangeInclusive], ['Vec<', '>', TypeDefInfo.Vec], ['WrapperKeepOpaque<', '>', TypeDefInfo.WrapperKeepOpaque], ['WrapperOpaque<', '>', TypeDefInfo.WrapperOpaque]]; | ||
const nestedExtraction = [ | ||
['[', ']', TypeDefInfo.VecFixed, _decodeFixedVec], | ||
['{', '}', TypeDefInfo.Struct, _decodeStruct], | ||
['(', ')', TypeDefInfo.Tuple, _decodeTuple], | ||
// the inner for these are the same as tuple, multiple values | ||
['BTreeMap<', '>', TypeDefInfo.BTreeMap, _decodeTuple], | ||
['HashMap<', '>', TypeDefInfo.HashMap, _decodeTuple], | ||
['Int<', '>', TypeDefInfo.Int, _decodeInt], | ||
['Result<', '>', TypeDefInfo.Result, _decodeTuple], | ||
['UInt<', '>', TypeDefInfo.UInt, _decodeUInt], | ||
['DoNotConstruct<', '>', TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct] | ||
]; | ||
const wrappedExtraction = [ | ||
['BTreeSet<', '>', TypeDefInfo.BTreeSet], | ||
['Compact<', '>', TypeDefInfo.Compact], | ||
['Linkage<', '>', TypeDefInfo.Linkage], | ||
['Opaque<', '>', TypeDefInfo.WrapperOpaque], | ||
['Option<', '>', TypeDefInfo.Option], | ||
['Range<', '>', TypeDefInfo.Range], | ||
['RangeInclusive<', '>', TypeDefInfo.RangeInclusive], | ||
['Vec<', '>', TypeDefInfo.Vec], | ||
['WrapperKeepOpaque<', '>', TypeDefInfo.WrapperKeepOpaque], | ||
['WrapperOpaque<', '>', TypeDefInfo.WrapperOpaque] | ||
]; | ||
function extractSubType(type, [start, end]) { | ||
return type.substring(start.length, type.length - end.length); | ||
return type.substring(start.length, type.length - end.length); | ||
} | ||
export function getTypeDef(_type, { | ||
displayName, | ||
name | ||
} = {}, count = 0) { | ||
// create the type via Type, allowing types to be sanitized | ||
const type = sanitize(_type); | ||
const value = { | ||
displayName, | ||
info: TypeDefInfo.Plain, | ||
name, | ||
type | ||
}; | ||
if (++count > 64) { | ||
throw new Error('getTypeDef: Maximum nested limit reached'); | ||
} | ||
const nested = nestedExtraction.find(nested => hasWrapper(type, nested)); | ||
if (nested) { | ||
value.info = nested[2]; | ||
return nested[3](value, type, extractSubType(type, nested), count); | ||
} | ||
const wrapped = wrappedExtraction.find(wrapped => hasWrapper(type, wrapped)); | ||
if (wrapped) { | ||
value.info = wrapped[2]; | ||
value.sub = getTypeDef(extractSubType(type, wrapped), {}, count); | ||
} | ||
return value; | ||
export function getTypeDef(_type, { displayName, name } = {}, count = 0) { | ||
// create the type via Type, allowing types to be sanitized | ||
const type = sanitize(_type); | ||
const value = { displayName, info: TypeDefInfo.Plain, name, type }; | ||
if (++count > 64) { | ||
throw new Error('getTypeDef: Maximum nested limit reached'); | ||
} | ||
const nested = nestedExtraction.find((nested) => hasWrapper(type, nested)); | ||
if (nested) { | ||
value.info = nested[2]; | ||
return nested[3](value, type, extractSubType(type, nested), count); | ||
} | ||
const wrapped = wrappedExtraction.find((wrapped) => hasWrapper(type, wrapped)); | ||
if (wrapped) { | ||
value.info = wrapped[2]; | ||
value.sub = getTypeDef(extractSubType(type, wrapped), {}, count); | ||
} | ||
return value; | ||
} |
@@ -1,7 +0,4 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
export * from "./encodeTypes.js"; | ||
export * from "./getTypeDef.js"; | ||
export * from "./typeSplit.js"; | ||
export * from "./xcm.js"; | ||
export * from './encodeTypes.js'; | ||
export * from './getTypeDef.js'; | ||
export * from './typeSplit.js'; | ||
export * from './xcm.js'; |
@@ -1,70 +0,57 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// safely split a string on ', ' while taking care of any nested occurences | ||
export function typeSplit(type) { | ||
const result = []; | ||
// these are the depths of the various tokens: <, [, {, ( | ||
let c = 0; | ||
let f = 0; | ||
let s = 0; | ||
let t = 0; | ||
// current start position | ||
let start = 0; | ||
for (let i = 0; i < type.length; i++) { | ||
switch (type[i]) { | ||
// if we are not nested, add the type | ||
case ',': | ||
{ | ||
if (!(c || f || s || t)) { | ||
result.push(type.substring(start, i).trim()); | ||
start = i + 1; | ||
} | ||
break; | ||
const result = []; | ||
// these are the depths of the various tokens: <, [, {, ( | ||
let c = 0; | ||
let f = 0; | ||
let s = 0; | ||
let t = 0; | ||
// current start position | ||
let start = 0; | ||
for (let i = 0; i < type.length; i++) { | ||
switch (type[i]) { | ||
// if we are not nested, add the type | ||
case ',': { | ||
if (!(c || f || s || t)) { | ||
result.push(type.substring(start, i).trim()); | ||
start = i + 1; | ||
} | ||
break; | ||
} | ||
// adjust compact/vec (and friends) depth | ||
case '<': | ||
c++; | ||
break; | ||
case '>': | ||
c--; | ||
break; | ||
// adjust fixed vec depths | ||
case '[': | ||
f++; | ||
break; | ||
case ']': | ||
f--; | ||
break; | ||
// adjust struct depth | ||
case '{': | ||
s++; | ||
break; | ||
case '}': | ||
s--; | ||
break; | ||
// adjust tuple depth | ||
case '(': | ||
t++; | ||
break; | ||
case ')': | ||
t--; | ||
break; | ||
} | ||
// adjust compact/vec (and friends) depth | ||
case '<': | ||
c++; | ||
break; | ||
case '>': | ||
c--; | ||
break; | ||
// adjust fixed vec depths | ||
case '[': | ||
f++; | ||
break; | ||
case ']': | ||
f--; | ||
break; | ||
// adjust struct depth | ||
case '{': | ||
s++; | ||
break; | ||
case '}': | ||
s--; | ||
break; | ||
// adjust tuple depth | ||
case '(': | ||
t++; | ||
break; | ||
case ')': | ||
t--; | ||
break; | ||
} | ||
} | ||
// ensure we have all the terminators taken care of | ||
if (c || f || s || t) { | ||
throw new Error(`Invalid definition (missing terminators) found in ${type}`); | ||
} | ||
// the final leg of the journey | ||
result.push(type.substring(start, type.length).trim()); | ||
return result; | ||
// ensure we have all the terminators taken care of | ||
if (c || f || s || t) { | ||
throw new Error(`Invalid definition (missing terminators) found in ${type}`); | ||
} | ||
// the final leg of the journey | ||
result.push(type.substring(start, type.length).trim()); | ||
return result; | ||
} |
@@ -1,10 +0,5 @@ | ||
// Copyright 2017-2023 @polkadot/types-create authors & contributors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { objectSpread } from '@polkadot/util'; | ||
export const XCM_MAPPINGS = ['AssetInstance', 'Fungibility', 'Junction', 'Junctions', 'MultiAsset', 'MultiAssetFilter', 'MultiLocation', 'Response', 'WildFungibility', 'WildMultiAsset', 'Xcm', 'XcmError', 'XcmOrder']; | ||
export function mapXcmTypes(version) { | ||
return XCM_MAPPINGS.reduce((all, key) => objectSpread(all, { | ||
[key]: `${key}${version}` | ||
}), {}); | ||
return XCM_MAPPINGS.reduce((all, key) => objectSpread(all, { [key]: `${key}${version}` }), {}); | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
76356
1438
+ Addedtslib@^2.5.0
+ Added@polkadot/types-codec@10.0.1(transitive)
+ Added@polkadot/util@11.1.3(transitive)
+ Added@polkadot/x-bigint@11.1.3(transitive)
+ Added@polkadot/x-global@11.1.3(transitive)
+ Added@polkadot/x-textdecoder@11.1.3(transitive)
+ Added@polkadot/x-textencoder@11.1.3(transitive)
+ Addedtslib@2.8.1(transitive)
- Removed@babel/runtime@^7.20.13
- Removed@babel/runtime@7.26.0(transitive)
- Removed@polkadot/types-codec@9.14.2(transitive)
- Removed@polkadot/util@10.4.2(transitive)
- Removed@polkadot/x-bigint@10.4.2(transitive)
- Removed@polkadot/x-global@10.4.2(transitive)
- Removed@polkadot/x-textdecoder@10.4.2(transitive)
- Removed@polkadot/x-textencoder@10.4.2(transitive)
- Removedregenerator-runtime@0.14.1(transitive)
Updated@polkadot/types-codec@10.0.1
Updated@polkadot/util@^11.0.1