@polkadot-api/metadata-builders
Advanced tools
Comparing version 0.0.1-4720098dad2c69dafd379d4eb3a609154080c24d.1.0 to 0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0
import * as scale from '@polkadot-api/substrate-bindings'; | ||
import { StringRecord, V14, Codec, Decoder, HexString } from '@polkadot-api/substrate-bindings'; | ||
export { Decoder, HexString, StringRecord, V14 } from '@polkadot-api/substrate-bindings'; | ||
import { StringRecord, V15, Codec } from '@polkadot-api/substrate-bindings'; | ||
type VoidVar = { | ||
type MetadataPrimitives = "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256"; | ||
type PrimitiveVar = { | ||
type: "primitive"; | ||
value: "_void"; | ||
value: MetadataPrimitives; | ||
}; | ||
type MetadataPrimitives$1 = "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256"; | ||
type PrimitiveVar = { | ||
type: "primitive"; | ||
value: MetadataPrimitives$1; | ||
} | VoidVar; | ||
type VoidVar = { | ||
type: "void"; | ||
}; | ||
type CompactVar = { | ||
type: "compact"; | ||
isBig: boolean; | ||
isBig: boolean | null; | ||
}; | ||
@@ -21,3 +19,6 @@ type BitSequenceVar = { | ||
}; | ||
type TerminalVar = PrimitiveVar | CompactVar | BitSequenceVar; | ||
type AccountId32 = { | ||
type: "AccountId32"; | ||
}; | ||
type TerminalVar = PrimitiveVar | VoidVar | CompactVar | BitSequenceVar | AccountId32; | ||
type TupleVar = { | ||
@@ -35,3 +36,6 @@ type: "tuple"; | ||
type: "enum"; | ||
value: StringRecord<(TupleVar | StructVar | VoidVar) & { | ||
value: StringRecord<({ | ||
type: "lookupEntry"; | ||
value: LookupEntry; | ||
} | VoidVar | TupleVar | StructVar) & { | ||
idx: number; | ||
@@ -41,2 +45,13 @@ }>; | ||
}; | ||
type OptionVar = { | ||
type: "option"; | ||
value: LookupEntry; | ||
}; | ||
type ResultVar = { | ||
type: "result"; | ||
value: { | ||
ok: LookupEntry; | ||
ko: LookupEntry; | ||
}; | ||
}; | ||
type SequenceVar = { | ||
@@ -51,3 +66,3 @@ type: "sequence"; | ||
}; | ||
type ComposedVar = TupleVar | StructVar | SequenceVar | ArrayVar | EnumVar; | ||
type ComposedVar = TupleVar | StructVar | SequenceVar | ArrayVar | OptionVar | ResultVar | EnumVar; | ||
type Var = TerminalVar | ComposedVar; | ||
@@ -62,3 +77,3 @@ type LookupEntry = { | ||
name: string; | ||
type: number | void | undefined; | ||
type: number | undefined; | ||
}[]; | ||
@@ -68,5 +83,5 @@ def: { | ||
value: { | ||
name: string | void | undefined; | ||
name: string | undefined; | ||
type: number; | ||
typeName: string | void | undefined; | ||
typeName: string | undefined; | ||
docs: string[]; | ||
@@ -79,5 +94,5 @@ }[]; | ||
fields: { | ||
name: string | void | undefined; | ||
name: string | undefined; | ||
type: number; | ||
typeName: string | void | undefined; | ||
typeName: string | undefined; | ||
docs: string[]; | ||
@@ -157,5 +172,2 @@ }[]; | ||
}; | ||
} | { | ||
tag: "historicMetaCompat"; | ||
value: string; | ||
}; | ||
@@ -165,30 +177,3 @@ docs: string[]; | ||
type MetadataPrimitives = "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256"; | ||
declare const primitiveTypes: Record<MetadataPrimitives | "_void" | "compactNumber" | "compactBn" | "bitSequence" | "historicMetaCompat", string>; | ||
interface Variable { | ||
id: string; | ||
types: string; | ||
value: string; | ||
directDependencies: Set<string>; | ||
} | ||
interface CodeDeclarations { | ||
imports: Set<string>; | ||
typeImports: Set<string>; | ||
variables: Map<string, Variable>; | ||
} | ||
declare const getStaticBuilder: (metadata: V14) => { | ||
buildDefinition: (id: number) => string; | ||
buildStorage: (pallet: string, entry: string) => { | ||
key: string; | ||
val: string; | ||
}; | ||
buildEvent: (pallet: string, name: string) => string; | ||
buildError: (pallet: string, name: string) => string; | ||
buildCall: (pallet: string, callName: string) => string; | ||
buildConstant: (pallet: string, constantName: string) => string; | ||
getTypeFromVarName: (varName: string) => string; | ||
getCode: () => string; | ||
}; | ||
declare const getDynamicBuilder: (metadata: V14) => { | ||
declare const getDynamicBuilder: (metadata: V15) => { | ||
buildDefinition: (id: number) => Codec<any>; | ||
@@ -216,3 +201,8 @@ buildStorage: (pallet: string, entry: string) => { | ||
}; | ||
buildCall: (pallet: string, callName: string) => { | ||
buildRuntimeCall: (api: string, method: string) => { | ||
args: Codec<any[]>; | ||
value: Codec<any>; | ||
}; | ||
buildCall: (pallet: string, name: string) => { | ||
codec: Codec<any>; | ||
location: [ | ||
@@ -222,3 +212,2 @@ number, | ||
]; | ||
args: Codec<any>; | ||
}; | ||
@@ -229,143 +218,15 @@ buildConstant: (pallet: string, constantName: string) => Codec<any>; | ||
declare const getChecksumBuilder: (metadata: V14) => { | ||
declare const getChecksumBuilder: (metadata: V15) => { | ||
buildDefinition: (id: number) => string | null; | ||
buildRuntimeCall: (api: string, method: string) => string | null; | ||
buildStorage: (pallet: string, entry: string) => string | null; | ||
buildCall: (pallet: string, callName: string) => string | null; | ||
buildCall: (pallet: string, name: string) => string | null; | ||
buildEvent: (pallet: string, name: string) => string | null; | ||
buildError: (pallet: string, name: string) => string | null; | ||
buildConstant: (pallet: string, constantName: string) => string | null; | ||
buildComposite: (input: VoidVar | TupleVar | StructVar) => string | null; | ||
buildNamedTuple: (input: StructVar) => string | null; | ||
getAllGeneratedChecksums: () => string[]; | ||
}; | ||
type GetViewBuilder = (metadata: V14) => { | ||
buildDefinition: (idx: number) => { | ||
shape: Shape; | ||
decoder: Decoder<Decoded>; | ||
}; | ||
callDecoder: Decoder<DecodedCall>; | ||
}; | ||
interface DecodedCall { | ||
pallet: { | ||
value: { | ||
name: string; | ||
idx: number; | ||
}; | ||
input: HexString; | ||
}; | ||
call: { | ||
value: { | ||
name: string; | ||
idx: number; | ||
}; | ||
input: HexString; | ||
docs: string[]; | ||
}; | ||
args: { | ||
value: StructDecoded; | ||
shape: Shape; | ||
}; | ||
} | ||
type WithInputAndPath<T> = T & { | ||
input: HexString; | ||
path?: string[]; | ||
}; | ||
type VoidDecoded = WithInputAndPath<{ | ||
codec: "_void"; | ||
value: undefined; | ||
}>; | ||
type BoolDecoded = WithInputAndPath<{ | ||
codec: "bool"; | ||
value: boolean; | ||
}>; | ||
type StringDecoded = WithInputAndPath<{ | ||
codec: "str" | "char"; | ||
value: string; | ||
}>; | ||
type NumberDecoded = WithInputAndPath<{ | ||
codec: "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "compactNumber"; | ||
value: number; | ||
}>; | ||
type BigNumberDecoded = WithInputAndPath<{ | ||
codec: "u64" | "u128" | "u256" | "i64" | "i128" | "i256" | "compactBn"; | ||
value: bigint; | ||
}>; | ||
type BitSequenceDecoded = WithInputAndPath<{ | ||
codec: "bitSequence"; | ||
value: { | ||
bitsLen: number; | ||
bytes: Uint8Array; | ||
}; | ||
}>; | ||
type BytesSequenceDecoded = WithInputAndPath<{ | ||
codec: "Bytes"; | ||
value: HexString; | ||
}>; | ||
type BytesArrayDecoded = WithInputAndPath<{ | ||
codec: "BytesArray"; | ||
value: HexString; | ||
len: number; | ||
}>; | ||
type AccountIdDecoded = WithInputAndPath<{ | ||
codec: "AccountId"; | ||
value: { | ||
ss58Prefix: number; | ||
address: string; | ||
}; | ||
}>; | ||
type PrimitiveDecoded = VoidDecoded | BoolDecoded | StringDecoded | NumberDecoded | BigNumberDecoded | BitSequenceDecoded | BytesSequenceDecoded | BytesArrayDecoded | AccountIdDecoded; | ||
type SequenceDecoded = WithInputAndPath<{ | ||
codec: "Sequence"; | ||
value: Array<Decoded>; | ||
}>; | ||
type ArrayDecoded = WithInputAndPath<{ | ||
codec: "Array"; | ||
value: Array<Decoded>; | ||
}>; | ||
type TupleDecoded = WithInputAndPath<{ | ||
codec: "Tuple"; | ||
value: Array<Decoded>; | ||
innerDocs: Array<string[]>; | ||
}>; | ||
type StructDecoded = WithInputAndPath<{ | ||
codec: "Struct"; | ||
value: StringRecord<Decoded>; | ||
innerDocs: StringRecord<string[]>; | ||
}>; | ||
type EnumDecoded = WithInputAndPath<{ | ||
codec: "Enum"; | ||
value: { | ||
tag: string; | ||
value: Decoded; | ||
}; | ||
docs: string[]; | ||
}>; | ||
type ComplexDecoded = SequenceDecoded | ArrayDecoded | TupleDecoded | StructDecoded | EnumDecoded; | ||
type Decoded = PrimitiveDecoded | ComplexDecoded; | ||
interface SequenceShape { | ||
codec: "Sequence"; | ||
shape: Shape; | ||
} | ||
interface ArrayShape { | ||
codec: "Array"; | ||
len: number; | ||
shape: Shape; | ||
} | ||
interface TupleShape { | ||
codec: "Tuple"; | ||
shape: Array<Shape>; | ||
} | ||
interface StructShape { | ||
codec: "Struct"; | ||
shape: StringRecord<Shape>; | ||
} | ||
interface EnumShape { | ||
codec: "Enum"; | ||
shape: StringRecord<Shape>; | ||
} | ||
type ComplexShape = SequenceShape | ArrayShape | TupleShape | StructShape | EnumShape; | ||
type Shape = { | ||
codec: PrimitiveDecoded["codec"]; | ||
} | ComplexShape; | ||
declare const getViewBuilder: GetViewBuilder; | ||
export { type AccountIdDecoded, type ArrayDecoded, type ArrayShape, type ArrayVar, type BigNumberDecoded, type BitSequenceDecoded, type BitSequenceVar, type BoolDecoded, type BytesArrayDecoded, type BytesSequenceDecoded, type CodeDeclarations, type CompactVar, type ComplexDecoded, type ComplexShape, type ComposedVar, type Decoded, type DecodedCall, type EnumDecoded, type EnumShape, type EnumVar, type GetViewBuilder, type LookupEntry, type MetadataPrimitives$1 as MetadataPrimitives, type NumberDecoded, type PrimitiveDecoded, type PrimitiveVar, type SequenceDecoded, type SequenceShape, type SequenceVar, type Shape, type StringDecoded, type StructDecoded, type StructShape, type StructVar, type TerminalVar, type TupleDecoded, type TupleShape, type TupleVar, type Var, type Variable, type VoidDecoded, type VoidVar, getChecksumBuilder, getDynamicBuilder, getLookupFn, getStaticBuilder, getViewBuilder, primitiveTypes }; | ||
export { type AccountId32, type ArrayVar, type BitSequenceVar, type CompactVar, type ComposedVar, type EnumVar, type LookupEntry, type MetadataPrimitives, type OptionVar, type PrimitiveVar, type ResultVar, type SequenceVar, type StructVar, type TerminalVar, type TupleVar, type Var, type VoidVar, getChecksumBuilder, getDynamicBuilder, getLookupFn }; |
1158
dist/index.js
@@ -35,6 +35,3 @@ "use strict"; | ||
getDynamicBuilder: () => getDynamicBuilder, | ||
getLookupFn: () => getLookupFn, | ||
getStaticBuilder: () => getStaticBuilder, | ||
getViewBuilder: () => getViewBuilder, | ||
primitiveTypes: () => primitiveTypes | ||
getLookupFn: () => getLookupFn | ||
}); | ||
@@ -44,3 +41,2 @@ module.exports = __toCommonJS(src_exports); | ||
// src/lookups.ts | ||
var voidVar = { type: "primitive", value: "_void" }; | ||
var getLookupFn = (lookupData) => { | ||
@@ -77,9 +73,15 @@ const lookups = /* @__PURE__ */ new Map(); | ||
}; | ||
let isAccountId32SearchOn = true; | ||
const getLookupEntryDef = withCache2((id) => { | ||
const { def } = lookupData[id]; | ||
const { def, path, params } = lookupData[id]; | ||
if (def.tag === "composite") { | ||
if (def.value.length === 0) | ||
return voidVar; | ||
if (def.value.length === 1) | ||
return { type: "void" }; | ||
if (def.value.length === 1) { | ||
if (isAccountId32SearchOn && path.join(",") === "sp_core,crypto,AccountId32") { | ||
isAccountId32SearchOn = false; | ||
return { type: "AccountId32" }; | ||
} | ||
return getLookupEntryDef(def.value[0].type); | ||
} | ||
let allKey = true; | ||
@@ -105,4 +107,24 @@ const values = {}; | ||
if (def.tag === "variant") { | ||
if (path.length === 1 && path[0] === "Option" && params.length === 1 && params[0].name === "T") { | ||
const value = getLookupEntryDef(params[0].type); | ||
return value.type === "void" ? ( | ||
// Option<void> would return a Codec<undefined> which makes no sense | ||
// Therefore, we better treat it as a bool | ||
{ type: "primitive", value: "bool" } | ||
) : { | ||
type: "option", | ||
value | ||
}; | ||
} | ||
if (path.length === 1 && path[0] === "Result" && params.length === 2 && params[0].name === "T" && params[1].name === "E") { | ||
return { | ||
type: "result", | ||
value: { | ||
ok: getLookupEntryDef(params[0].type), | ||
ko: getLookupEntryDef(params[1].type) | ||
} | ||
}; | ||
} | ||
if (def.value.length === 0) | ||
return voidVar; | ||
return { type: "void" }; | ||
const enumValue = {}; | ||
@@ -114,5 +136,13 @@ const enumDocs = {}; | ||
if (x.fields.length === 0) { | ||
enumValue[key] = { ...voidVar, idx: x.index }; | ||
enumValue[key] = { type: "void", idx: x.index }; | ||
return; | ||
} | ||
if (x.fields.length === 1 && !x.fields[0].name) { | ||
enumValue[key] = { | ||
type: "lookupEntry", | ||
value: getLookupEntryDef(x.fields[0].type), | ||
idx: x.index | ||
}; | ||
return; | ||
} | ||
let allKey = true; | ||
@@ -146,13 +176,18 @@ const values = {}; | ||
if (def.tag === "sequence") { | ||
const value2 = getLookupEntryDef(def.value); | ||
const value = getLookupEntryDef(def.value); | ||
return { | ||
type: "sequence", | ||
value: value2 | ||
value | ||
}; | ||
} | ||
if (def.tag === "array") { | ||
const value2 = getLookupEntryDef(def.value.type); | ||
const { len } = def.value; | ||
const value = getLookupEntryDef(def.value.type); | ||
if (len === 0) | ||
return { type: "void" }; | ||
if (len === 1) | ||
return value; | ||
return { | ||
type: "array", | ||
value: value2, | ||
value, | ||
len: def.value.len | ||
@@ -163,10 +198,18 @@ }; | ||
if (def.value.length === 0) | ||
return voidVar; | ||
return { type: "void" }; | ||
if (def.value.length === 1) | ||
return getLookupEntryDef(def.value[0]); | ||
const value2 = def.value.map((x) => getLookupEntryDef(x)); | ||
const value = def.value.map((x) => getLookupEntryDef(x)); | ||
const innerDocs = def.value.map((x) => lookupData[x].docs); | ||
const areAllSame = value.every((v) => v.id === value[0].id); | ||
if (areAllSame && innerDocs.every((doc) => doc.length === 0)) { | ||
return { | ||
type: "array", | ||
value: value[0], | ||
len: value.length | ||
}; | ||
} | ||
return { | ||
type: "tuple", | ||
value: value2, | ||
value, | ||
innerDocs | ||
@@ -183,2 +226,4 @@ }; | ||
const translated = getLookupEntryDef(def.value); | ||
if (translated.type === "void") | ||
return { type: "compact", isBig: null }; | ||
const isBig = Number(translated.value.slice(1)) > 32; | ||
@@ -190,9 +235,4 @@ return { | ||
} | ||
if (def.tag === "bitSequence") { | ||
return { type: "bitSequence" }; | ||
} | ||
const value = def.value; | ||
return { | ||
type: "primitive", | ||
value | ||
type: def.tag | ||
}; | ||
@@ -203,2 +243,5 @@ }); | ||
// src/dynamic-builder.ts | ||
var scale = __toESM(require("@polkadot-api/substrate-bindings")); | ||
// src/with-cache.ts | ||
@@ -223,334 +266,12 @@ var withCache = (fn, onEnterCircular, onExitCircular) => (input, cache, stack, ...rest) => { | ||
// src/static-builder.ts | ||
var primitiveTypes = { | ||
_void: "undefined", | ||
bool: "boolean", | ||
char: "string", | ||
str: "string", | ||
u8: "number", | ||
u16: "number", | ||
u32: "number", | ||
u64: "bigint", | ||
u128: "bigint", | ||
u256: "bigint", | ||
i8: "number", | ||
i16: "number", | ||
i32: "number", | ||
i64: "bigint", | ||
i128: "bigint", | ||
i256: "bigint", | ||
compactNumber: "number", | ||
compactBn: "bigint", | ||
bitSequence: "{bitsLen: number, bytes: Uint8Array}", | ||
historicMetaCompat: "any" | ||
}; | ||
var toCamelCase = (...parts) => parts[0] + parts.slice(1).map((part) => part[0].toUpperCase() + part.slice(1)).join(""); | ||
var isBytes = (input) => input.type === "primitive" && input.value === "u8"; | ||
var getTypes = (varName) => primitiveTypes[varName] ?? `I${varName}`; | ||
var _buildSyntax = (input, cache, stack, declarations, getVarName) => { | ||
if (input.type === "primitive") { | ||
declarations.imports.add(input.value); | ||
return input.value; | ||
} | ||
if (input.type === "compact") { | ||
const importVal = input.isBig ? "compactBn" : "compactNumber"; | ||
declarations.imports.add(importVal); | ||
return importVal; | ||
} | ||
if (input.type === "bitSequence") { | ||
declarations.imports.add(input.type); | ||
return input.type; | ||
} | ||
if (input.type === "sequence" && input.value.type === "primitive" && input.value.value === "u8") { | ||
declarations.imports.add("Bin"); | ||
declarations.typeImports.add("HexString"); | ||
declarations.typeImports.add("Binary"); | ||
const variable = { | ||
id: "_bytesSeq", | ||
value: "Bin()", | ||
types: "Binary", | ||
directDependencies: /* @__PURE__ */ new Set() | ||
}; | ||
if (!declarations.variables.has(variable.id)) { | ||
declarations.variables.set(variable.id, variable); | ||
} | ||
return variable.id; | ||
} | ||
if (declarations.variables.has(getVarName(input.id, "circular"))) | ||
return getVarName(input.id, "circular"); | ||
if (declarations.variables.has(getVarName(input.id))) | ||
return getVarName(input.id); | ||
const buildNextSyntax = (nextInput) => buildSyntax(nextInput, cache, stack, declarations, getVarName); | ||
const buildVector = (id, inner, len) => { | ||
declarations.imports.add("Vector"); | ||
const dependsVar = buildNextSyntax(inner); | ||
const args = len ? [dependsVar, len] : [dependsVar]; | ||
const variable = { | ||
id, | ||
value: `Vector(${args.join(", ")})`, | ||
types: `Array<${getTypes(dependsVar)}>`, | ||
directDependencies: /* @__PURE__ */ new Set([dependsVar]) | ||
}; | ||
declarations.variables.set(id, variable); | ||
return id; | ||
}; | ||
const buildTuple = (id, value) => { | ||
declarations.imports.add("Tuple"); | ||
const deps = value.map(buildNextSyntax); | ||
const variable = { | ||
id, | ||
value: `Tuple(${deps.join(", ")})`, | ||
types: `[${deps.map(getTypes).join(", ")}]`, | ||
directDependencies: new Set(deps) | ||
}; | ||
declarations.variables.set(id, variable); | ||
return id; | ||
}; | ||
const buildStruct = (id, value) => { | ||
declarations.imports.add("Struct"); | ||
const deps = Object.values(value).map(buildNextSyntax); | ||
const variable = { | ||
id, | ||
value: `Struct({${Object.keys(value).map((key, idx) => `${key}: ${deps[idx]}`).join(", ")}})`, | ||
types: `{${Object.keys(value).map((key, idx) => `${key}: ${getTypes(deps[idx])}`).join(", ")}}`, | ||
directDependencies: new Set(deps) | ||
}; | ||
declarations.variables.set(id, variable); | ||
return id; | ||
}; | ||
const varId = getVarName(input.id); | ||
if (input.type === "array") { | ||
if (isBytes(input.value)) { | ||
if (input.len === 32 && (input.id === 0 || input.id === 1)) { | ||
declarations.imports.add("AccountId"); | ||
const id = "_accountId"; | ||
declarations.variables.set(id, { | ||
id, | ||
value: `AccountId()`, | ||
types: "SS58String", | ||
directDependencies: /* @__PURE__ */ new Set() | ||
}); | ||
declarations.typeImports.add("SS58String"); | ||
return id; | ||
} | ||
declarations.imports.add("Bin"); | ||
declarations.variables.set(varId, { | ||
id: varId, | ||
value: `Bin(${input.len})`, | ||
types: "Binary", | ||
directDependencies: /* @__PURE__ */ new Set() | ||
}); | ||
declarations.typeImports.add("HexString"); | ||
declarations.typeImports.add("Binary"); | ||
return varId; | ||
} | ||
return buildVector(varId, input.value, input.len); | ||
} | ||
if (input.type === "sequence") | ||
return buildVector(varId, input.value); | ||
if (input.type === "tuple") | ||
return buildTuple(varId, input.value); | ||
if (input.type === "struct") | ||
return buildStruct(varId, input.value); | ||
declarations.imports.add("Enum"); | ||
const dependencies = Object.entries(input.value).map(([key, value]) => { | ||
if (value.type === "primitive") { | ||
declarations.imports.add(value.value); | ||
return value.value; | ||
} | ||
const varName = toCamelCase(varId, key); | ||
if (value.type === "tuple") { | ||
if (value.value.length === 1) { | ||
let result = buildNextSyntax(value.value[0]); | ||
if (!declarations.variables.has(varName)) { | ||
declarations.variables.set(varName, { | ||
id: varName, | ||
value: result, | ||
types: getTypes(result), | ||
directDependencies: /* @__PURE__ */ new Set([result]) | ||
}); | ||
} | ||
return varName; | ||
} | ||
return buildTuple(varName, value.value); | ||
} else { | ||
buildStruct(varName, value.value); | ||
} | ||
return varName; | ||
}); | ||
const indexes = Object.values(input.value).map((x) => x.idx); | ||
const areIndexesSorted = indexes.every((idx, i) => idx === i); | ||
const innerEnum = `{${Object.keys(input.value).map( | ||
(key, idx) => `${key}: ${dependencies[idx]}` | ||
)}}${areIndexesSorted ? "" : `, [${indexes.join(", ")}]`}`; | ||
declarations.variables.set(varId, { | ||
id: varId, | ||
value: `Enum(${innerEnum})`, | ||
types: Object.keys(input.value).map( | ||
(key, idx) => `{tag: '${key}', value: ${getTypes(dependencies[idx])}}` | ||
).join(" | "), | ||
directDependencies: new Set(dependencies) | ||
}); | ||
return varId; | ||
}; | ||
var buildSyntax = withCache( | ||
_buildSyntax, | ||
(_getter, entry, declarations, getVarName) => { | ||
declarations.imports.add("Self"); | ||
const nonCircular = getVarName(entry.id); | ||
const variable = { | ||
id: getVarName(entry.id, "circular"), | ||
types: `I${nonCircular}`, | ||
value: `Self(() => ${nonCircular})`, | ||
directDependencies: /* @__PURE__ */ new Set([nonCircular]) | ||
}; | ||
declarations.variables.set(variable.id, variable); | ||
return variable.id; | ||
}, | ||
(x) => x | ||
); | ||
var getStaticBuilder = (metadata) => { | ||
const declarations = { | ||
imports: /* @__PURE__ */ new Set(), | ||
typeImports: /* @__PURE__ */ new Set(["Codec"]), | ||
variables: /* @__PURE__ */ new Map() | ||
}; | ||
const lookupData = metadata.lookup; | ||
const getLookupEntryDef = getLookupFn(lookupData); | ||
const getVarName = (idx, ...post) => { | ||
const { path } = lookupData[idx]; | ||
const parts = path.length === 0 ? ["cdc" + idx] : ["c", ...path]; | ||
parts.push(...post); | ||
return toCamelCase(...parts); | ||
}; | ||
const cache = /* @__PURE__ */ new Map(); | ||
const buildDefinition = (id) => buildSyntax( | ||
getLookupEntryDef(id), | ||
cache, | ||
/* @__PURE__ */ new Set(), | ||
declarations, | ||
getVarName | ||
); | ||
const buildNamedTuple = (params, varName) => { | ||
if (declarations.variables.has(varName)) | ||
return varName; | ||
const args = params.map((p) => p.type).map(buildDefinition); | ||
const names = params.map((p) => p.name); | ||
declarations.imports.add("Tuple"); | ||
const variable = { | ||
id: varName, | ||
types: `[${names.map( | ||
(name, pIdx) => `${name[0].toUpperCase() + name.slice(1)}: ${getTypes(args[pIdx])}` | ||
).join(", ")}]`, | ||
value: `Tuple(${args.join(", ")})`, | ||
directDependencies: new Set(args) | ||
}; | ||
declarations.variables.set(varName, variable); | ||
return varName; | ||
}; | ||
const EMPTY_TUPLE_VAR_NAME = "_emptyTuple"; | ||
const getEmptyTuple = () => { | ||
if (!declarations.variables.has(EMPTY_TUPLE_VAR_NAME)) { | ||
declarations.imports.add("Tuple"); | ||
declarations.variables.set(EMPTY_TUPLE_VAR_NAME, { | ||
id: EMPTY_TUPLE_VAR_NAME, | ||
types: `[]`, | ||
value: `Tuple()`, | ||
directDependencies: /* @__PURE__ */ new Set() | ||
}); | ||
} | ||
return EMPTY_TUPLE_VAR_NAME; | ||
}; | ||
const buildStorage = (pallet, entry) => { | ||
const storageEntry = metadata.pallets.find((x) => x.name === pallet).storage.items.find((s) => s.name === entry); | ||
if (storageEntry.type.tag === "plain") | ||
return { | ||
key: getEmptyTuple(), | ||
val: buildDefinition(storageEntry.type.value) | ||
}; | ||
const { key, value } = storageEntry.type.value; | ||
const val = buildDefinition(value); | ||
const returnKey = storageEntry.type.value.hashers.length === 1 ? buildNamedTuple( | ||
[{ name: "key", type: key }], | ||
getVarName(key, "Tupled") | ||
) : buildDefinition(key); | ||
return { key: returnKey, val }; | ||
}; | ||
const buildVariant = (type) => (pallet, name) => { | ||
const eventsLookup = getLookupEntryDef( | ||
metadata.pallets.find((x) => x.name === pallet)[type] | ||
); | ||
if (eventsLookup.type !== "enum") | ||
throw null; | ||
const returnVar = toCamelCase(buildDefinition(eventsLookup.id), name); | ||
if (!declarations.variables.has(returnVar) && eventsLookup.value[name].type === "primitive") { | ||
declarations.variables.set(returnVar, { | ||
id: returnVar, | ||
value: "_void", | ||
types: "undefined", | ||
directDependencies: /* @__PURE__ */ new Set() | ||
}); | ||
} | ||
return returnVar; | ||
}; | ||
const buildCall = (pallet, callName) => { | ||
const callsLookup = getLookupEntryDef( | ||
metadata.pallets.find((x) => x.name === pallet).calls | ||
); | ||
if (callsLookup.type !== "enum") | ||
throw null; | ||
const callEntry = callsLookup.value[callName]; | ||
if (callEntry.type === "primitive") | ||
return getEmptyTuple(); | ||
if (callEntry.type === "tuple") | ||
return toCamelCase(buildDefinition(callsLookup.id), callName); | ||
const params = Object.entries(callEntry.value).map(([name, val]) => ({ | ||
name, | ||
type: val.id | ||
})); | ||
return buildNamedTuple( | ||
params, | ||
getVarName(callsLookup.id, callName, "Tupled") | ||
); | ||
}; | ||
const buildConstant = (pallet, constantName) => { | ||
const storageEntry = metadata.pallets.find((x) => x.name === pallet).constants.find((s) => s.name === constantName); | ||
return buildDefinition(storageEntry.type); | ||
}; | ||
const getCode = () => { | ||
const typeImports = `import type {${[...declarations.typeImports].join( | ||
", " | ||
)}} from "@polkadot-api/substrate-bindings"; | ||
`; | ||
const varImports = `import {${[...declarations.imports].join( | ||
", " | ||
)}} from "@polkadot-api/substrate-bindings"; | ||
`; | ||
const code = [...declarations.variables.values()].map((variable) => { | ||
return `type I${variable.id} = ${variable.types}; | ||
const ${variable.id}: Codec<I${variable.id}> = ${variable.value};`; | ||
}).join("\n\n"); | ||
return `${typeImports}${varImports}${code}`; | ||
}; | ||
const getTypeFromVarName = (varName) => primitiveTypes[varName] ?? declarations.variables.get(varName)?.types ?? `I${varName}`; | ||
return { | ||
buildDefinition, | ||
buildStorage, | ||
buildEvent: buildVariant("events"), | ||
buildError: buildVariant("errors"), | ||
buildCall, | ||
buildConstant, | ||
getTypeFromVarName, | ||
getCode | ||
}; | ||
}; | ||
// src/dynamic-builder.ts | ||
var scale = __toESM(require("@polkadot-api/substrate-bindings")); | ||
var import_utils = require("@polkadot-api/utils"); | ||
var _bytes = scale.Bin(); | ||
var isBytes2 = (input) => input.type === "primitive" && input.value === "u8"; | ||
var _buildCodec = (input, cache, stack, _accountId) => { | ||
if (input.type === "primitive") | ||
return scale[input.value]; | ||
if (input.type === "void") | ||
return scale._void; | ||
if (input.type === "AccountId32") | ||
return _accountId; | ||
if (input.type === "compact") | ||
@@ -560,5 +281,2 @@ return scale.compact; | ||
return scale.bitSequence; | ||
if (input.type === "sequence" && input.value.type === "primitive" && input.value.value === "u8") { | ||
return _bytes; | ||
} | ||
const buildNextCodec = (nextInput) => buildCodec(nextInput, cache, stack, _accountId); | ||
@@ -576,6 +294,8 @@ const buildVector = (inner2, len) => { | ||
}; | ||
if (input.type === "sequence" && input.value.type === "primitive" && input.value.value === "u8") { | ||
return _bytes; | ||
} | ||
if (input.type === "array") { | ||
if (isBytes2(input.value)) { | ||
return input.len === 32 && (input.id === 0 || input.id === 1) ? _accountId : scale.Bin(input.len); | ||
} | ||
if (input.value.type === "primitive" && input.value.value === "u8") | ||
return scale.Bin(input.len); | ||
return buildVector(input.value, input.len); | ||
@@ -589,7 +309,14 @@ } | ||
return buildStruct(input.value); | ||
if (input.type === "option") | ||
return scale.Option(buildNextCodec(input.value)); | ||
if (input.type === "result") | ||
return scale.Result( | ||
buildNextCodec(input.value.ok), | ||
buildNextCodec(input.value.ko) | ||
); | ||
const dependencies = Object.values(input.value).map((v) => { | ||
if (v.type === "primitive") | ||
if (v.type === "void") | ||
return scale._void; | ||
if (v.type === "tuple" && v.value.length === 1) | ||
return buildNextCodec(v.value[0]); | ||
if (v.type === "lookupEntry") | ||
return buildNextCodec(v.value); | ||
return v.type === "tuple" ? buildTuple(v.value) : buildStruct(v.value); | ||
@@ -604,6 +331,5 @@ }); | ||
const areIndexesSorted = indexes.every((idx, i) => idx === i); | ||
return areIndexesSorted ? scale.Enum(inner) : scale.Enum(inner, indexes); | ||
return areIndexesSorted ? scale.Variant(inner) : scale.Variant(inner, indexes); | ||
}; | ||
var buildCodec = withCache(_buildCodec, scale.Self, (res) => res); | ||
var emptyTuple = scale.Tuple(); | ||
var getDynamicBuilder = (metadata) => { | ||
@@ -658,16 +384,12 @@ const lookupData = metadata.lookup; | ||
}; | ||
const buildCall = (pallet, callName) => { | ||
const palletEntry = metadata.pallets.find((x) => x.name === pallet); | ||
const callsLookup = getLookupEntryDef(palletEntry.calls); | ||
if (callsLookup.type !== "enum") | ||
throw null; | ||
const callEntry = callsLookup.value[callName]; | ||
return { | ||
location: [palletEntry.index, callEntry.idx], | ||
args: callEntry.type === "primitive" ? emptyTuple : scale.Tuple( | ||
...Object.values(callEntry.value).map( | ||
(l) => buildDefinition(l.id) | ||
) | ||
) | ||
}; | ||
const buildEnumEntry = (entry) => { | ||
if (entry.type === "void") | ||
return scale._void; | ||
if (entry.type === "lookupEntry") | ||
return buildDefinition(entry.value.id); | ||
return entry.type === "tuple" ? scale.Tuple( | ||
...Object.values(entry.value).map((l) => buildDefinition(l.id)) | ||
) : scale.Struct( | ||
(0, import_utils.mapObject)(entry.value, (x) => buildDefinition(x.id)) | ||
); | ||
}; | ||
@@ -683,8 +405,17 @@ const buildConstant = (pallet, constantName) => { | ||
throw null; | ||
const event = lookup.value[name]; | ||
const entry = lookup.value[name]; | ||
return { | ||
location: [palletEntry.index, event.idx], | ||
codec: event.type === "primitive" ? scale._void : buildDefinition(lookup.id) | ||
location: [palletEntry.index, entry.idx], | ||
codec: buildEnumEntry(lookup.value[name]) | ||
}; | ||
}; | ||
const buildRuntimeCall = (api, method) => { | ||
const entry = metadata.apis.find((x) => x.name === api)?.methods.find((x) => x.name === method); | ||
if (!entry) | ||
throw null; | ||
return { | ||
args: scale.Tuple(...entry.inputs.map((x) => buildDefinition(x.type))), | ||
value: buildDefinition(entry.output) | ||
}; | ||
}; | ||
return { | ||
@@ -695,3 +426,4 @@ buildDefinition, | ||
buildError: buildVariant("errors"), | ||
buildCall, | ||
buildRuntimeCall, | ||
buildCall: buildVariant("calls"), | ||
buildConstant, | ||
@@ -706,66 +438,147 @@ ss58Prefix | ||
var encodeText = textEncoder.encode.bind(textEncoder); | ||
var getChecksum = (values, shape) => { | ||
const hasShape = typeof shape === "string"; | ||
const res = new Uint8Array((values.length + (hasShape ? 1 : 0)) * 8); | ||
var getChecksum = (values) => { | ||
const res = new Uint8Array(values.length * 8); | ||
const dv = new DataView(res.buffer); | ||
let offset = 0; | ||
if (hasShape) { | ||
dv.setBigUint64(offset, (0, import_substrate_bindings.h64)(encodeText(shape))); | ||
offset += 8; | ||
} | ||
for (let i = 0; i < values.length; i++, offset += 8) | ||
dv.setBigUint64(offset, values[i]); | ||
for (let i = 0; i < values.length; i++) | ||
dv.setBigUint64(i * 8, values[i]); | ||
return (0, import_substrate_bindings.h64)(res); | ||
}; | ||
var primitiveChecksums = { | ||
_void: 0n, | ||
bool: 1n, | ||
char: 2n, | ||
str: 3n, | ||
u8: 4n, | ||
u16: 5n, | ||
u32: 6n, | ||
u64: 7n, | ||
u128: 8n, | ||
u256: 9n, | ||
i8: 5n, | ||
i16: 5n, | ||
i32: 6n, | ||
i64: 7n, | ||
i128: 8n, | ||
i256: 9n, | ||
compacts: 10n, | ||
compactb: 11n, | ||
bitSequence: 12n, | ||
historicMetaCompat: 13n | ||
var getStringChecksum = (values) => getChecksum(values.map((v) => (0, import_substrate_bindings.h64)(encodeText(v)))); | ||
var shapeIds = { | ||
primitive: 0n, | ||
vector: 1n, | ||
tuple: 2n, | ||
struct: 3n, | ||
option: 4n, | ||
result: 5n, | ||
enum: 6n, | ||
void: 7n | ||
}; | ||
var bytesChecksum = 14n; | ||
var _buildChecksum = (input, cache, stack) => { | ||
if (cache.has(input.id)) | ||
return cache.get(input.id); | ||
var runtimePrimitiveIds = { | ||
undefined: 0n, | ||
number: 1n, | ||
string: 2n, | ||
bigint: 3n, | ||
boolean: 4n, | ||
bitSequence: 5n, | ||
// {bitsLen: number, bytes: Uint8Array} | ||
byteSequence: 6n, | ||
// Binary | ||
accountId: 7n | ||
// SS58String | ||
}; | ||
var metadataPrimitiveIds = { | ||
bool: runtimePrimitiveIds.boolean, | ||
char: runtimePrimitiveIds.string, | ||
str: runtimePrimitiveIds.string, | ||
u8: runtimePrimitiveIds.number, | ||
u16: runtimePrimitiveIds.number, | ||
u32: runtimePrimitiveIds.number, | ||
u64: runtimePrimitiveIds.bigint, | ||
u128: runtimePrimitiveIds.bigint, | ||
u256: runtimePrimitiveIds.bigint, | ||
i8: runtimePrimitiveIds.number, | ||
i16: runtimePrimitiveIds.number, | ||
i32: runtimePrimitiveIds.number, | ||
i64: runtimePrimitiveIds.bigint, | ||
i128: runtimePrimitiveIds.bigint, | ||
i256: runtimePrimitiveIds.bigint | ||
}; | ||
var structLikeBuilder = (shapeId, input, innerChecksum) => { | ||
const sortedEntries = Object.entries(input).sort( | ||
([a], [b]) => a.localeCompare(b) | ||
); | ||
const keysChecksum = getStringChecksum(sortedEntries.map(([key]) => key)); | ||
const valuesChecksum = getChecksum( | ||
sortedEntries.map(([, entry]) => innerChecksum(entry)) | ||
); | ||
return getChecksum([shapeId, keysChecksum, valuesChecksum]); | ||
}; | ||
var buildGraph = (entry, result = /* @__PURE__ */ new Map()) => { | ||
if (result.has(entry.id)) | ||
return result; | ||
switch (entry.type) { | ||
case "array": | ||
case "option": | ||
case "sequence": | ||
result.set(entry.id, [entry, /* @__PURE__ */ new Set([entry.value.id])]); | ||
buildGraph(entry.value, result); | ||
break; | ||
case "enum": { | ||
const children = Object.values(entry.value).flatMap((value) => { | ||
if (value.type === "void") | ||
return []; | ||
if (value.type === "lookupEntry") | ||
return value.value; | ||
if (value.type === "struct") | ||
return Object.values(value.value); | ||
return value.value; | ||
}); | ||
result.set(entry.id, [entry, new Set(children.map((child) => child.id))]); | ||
children.forEach((child) => buildGraph(child, result)); | ||
break; | ||
} | ||
case "result": | ||
result.set(entry.id, [ | ||
entry, | ||
/* @__PURE__ */ new Set([entry.value.ok.id, entry.value.ko.id]) | ||
]); | ||
buildGraph(entry.value.ok, result); | ||
buildGraph(entry.value.ko, result); | ||
break; | ||
case "struct": { | ||
const children = Object.values(entry.value); | ||
result.set(entry.id, [entry, new Set(children.map((child) => child.id))]); | ||
children.forEach((child) => buildGraph(child, result)); | ||
break; | ||
} | ||
case "tuple": | ||
result.set(entry.id, [ | ||
entry, | ||
new Set(entry.value.map((child) => child.id)) | ||
]); | ||
entry.value.forEach((child) => buildGraph(child, result)); | ||
break; | ||
default: | ||
result.set(entry.id, [entry, /* @__PURE__ */ new Set()]); | ||
} | ||
return result; | ||
}; | ||
var _buildChecksum = (input, buildNextChecksum) => { | ||
if (input.type === "primitive") | ||
return primitiveChecksums[input.value]; | ||
return getChecksum([shapeIds.primitive, metadataPrimitiveIds[input.value]]); | ||
if (input.type === "void") | ||
return getChecksum([shapeIds.void]); | ||
if (input.type === "compact") | ||
return primitiveChecksums[input.isBig ? "compactb" : "compacts"]; | ||
return getChecksum([ | ||
shapeIds.primitive, | ||
runtimePrimitiveIds[input.isBig || input.isBig === null ? "bigint" : "number"] | ||
]); | ||
if (input.type === "bitSequence") | ||
return primitiveChecksums.bitSequence; | ||
if (input.type === "sequence" && input.value.type === "primitive" && input.value.value === "u8") { | ||
return bytesChecksum; | ||
return getChecksum([shapeIds.primitive, runtimePrimitiveIds.bitSequence]); | ||
if (input.type === "AccountId32") { | ||
return getChecksum([shapeIds.primitive, runtimePrimitiveIds.accountId]); | ||
} | ||
const buildNextChecksum = (nextInput) => buildChecksum(nextInput, cache, stack); | ||
const buildVector = (inner, len) => { | ||
const innerChecksum = buildNextChecksum(inner); | ||
return len ? getChecksum([innerChecksum, BigInt(len)], "Vector(,)") : getChecksum([innerChecksum], "Vector()"); | ||
}; | ||
const buildTuple = (value) => getChecksum(value.map(buildNextChecksum)); | ||
const buildStruct = (value) => { | ||
return getChecksum( | ||
Object.values(value).map(buildNextChecksum), | ||
JSON.stringify(Object.keys(value)) | ||
); | ||
}; | ||
if (input.type === "array") | ||
return buildVector(input.value, input.len); | ||
if (input.type === "sequence") | ||
return buildVector(input.value); | ||
if (input.type === "array") { | ||
const innerValue = input.value; | ||
if (innerValue.type === "primitive" && innerValue.value === "u8") { | ||
return getChecksum([ | ||
shapeIds.primitive, | ||
runtimePrimitiveIds.byteSequence, | ||
BigInt(input.len) | ||
]); | ||
} | ||
const innerChecksum = buildNextChecksum(innerValue); | ||
return getChecksum([shapeIds.vector, innerChecksum, BigInt(input.len)]); | ||
} | ||
if (input.type === "sequence") { | ||
const innerValue = input.value; | ||
if (innerValue.type === "primitive" && innerValue.value === "u8") { | ||
return getChecksum([shapeIds.primitive, runtimePrimitiveIds.byteSequence]); | ||
} | ||
const innerChecksum = buildNextChecksum(innerValue); | ||
return getChecksum([shapeIds.vector, innerChecksum]); | ||
} | ||
const buildTuple = (entries) => getChecksum([shapeIds.tuple, ...entries.map(buildNextChecksum)]); | ||
const buildStruct = (entries) => structLikeBuilder(shapeIds.struct, entries, buildNextChecksum); | ||
if (input.type === "tuple") | ||
@@ -775,16 +588,156 @@ return buildTuple(input.value); | ||
return buildStruct(input.value); | ||
const dependencies = Object.values(input.value).map((v) => { | ||
if (v.type === "primitive") | ||
return 0n; | ||
return v.type === "tuple" ? buildTuple(v.value) : buildStruct(v.value); | ||
if (input.type === "option") | ||
return getChecksum([shapeIds.option, buildNextChecksum(input.value)]); | ||
if (input.type === "result") | ||
return getChecksum([ | ||
shapeIds.result, | ||
buildNextChecksum(input.value.ok), | ||
buildNextChecksum(input.value.ko) | ||
]); | ||
return structLikeBuilder(shapeIds.enum, input.value, (entry) => { | ||
if (entry.type === "lookupEntry") | ||
return buildNextChecksum(entry.value); | ||
switch (entry.type) { | ||
case "void": | ||
return getChecksum([shapeIds.void]); | ||
case "tuple": | ||
return buildTuple(entry.value); | ||
case "struct": | ||
return buildStruct(entry.value); | ||
} | ||
}); | ||
const keys = Object.keys(input.value); | ||
keys.push("Enum"); | ||
return getChecksum(dependencies, JSON.stringify({ Enum: keys })); | ||
}; | ||
var buildChecksum = withCache( | ||
_buildChecksum, | ||
() => 0n, | ||
(result) => result | ||
); | ||
var getCycles = (graph) => { | ||
const tarjanState = /* @__PURE__ */ new Map(); | ||
let index = 0; | ||
const stack = []; | ||
const result = []; | ||
function strongConnect(v) { | ||
const state = { | ||
index, | ||
lowLink: index, | ||
onStack: true | ||
}; | ||
tarjanState.set(v, state); | ||
index++; | ||
stack.push(v); | ||
const edges = graph.get(v)[1]; | ||
for (let w of edges) { | ||
const edgeState = tarjanState.get(w); | ||
if (!edgeState) { | ||
strongConnect(w); | ||
state.lowLink = Math.min(state.lowLink, tarjanState.get(w).lowLink); | ||
} else if (edgeState.onStack) { | ||
state.lowLink = Math.min(state.lowLink, edgeState.index); | ||
} | ||
} | ||
if (state.lowLink === state.index) { | ||
const component = /* @__PURE__ */ new Set(); | ||
let poppedNode = -1; | ||
do { | ||
poppedNode = stack.pop(); | ||
tarjanState.get(poppedNode).onStack = false; | ||
component.add(poppedNode); | ||
} while (poppedNode !== v); | ||
if (component.size > 1) | ||
result.push(component); | ||
} | ||
} | ||
for (const node of graph.keys()) { | ||
if (!tarjanState.has(node)) { | ||
strongConnect(node); | ||
} | ||
} | ||
return result; | ||
}; | ||
var getCyclicGroups = (cycles) => { | ||
const ungroupedCycles = new Set(cycles.map((_, i) => i)); | ||
const edges = new Map(cycles.map((_, i) => [i, /* @__PURE__ */ new Set()])); | ||
cycles.forEach((cycle, i) => { | ||
cycles.slice(i + 1).forEach((otherCycle, _j) => { | ||
const j = _j + i + 1; | ||
const combined = /* @__PURE__ */ new Set([...cycle, ...otherCycle]); | ||
if (combined.size !== cycle.size + otherCycle.size) { | ||
edges.get(i).add(j); | ||
edges.get(j).add(i); | ||
} | ||
}); | ||
}); | ||
const groups = []; | ||
while (ungroupedCycles.size) { | ||
const group = /* @__PURE__ */ new Set(); | ||
const toVisit = [ungroupedCycles.values().next().value]; | ||
while (toVisit.length) { | ||
const idx = toVisit.pop(); | ||
if (!ungroupedCycles.has(idx)) | ||
continue; | ||
ungroupedCycles.delete(idx); | ||
const cycle = cycles[idx]; | ||
cycle.forEach((v) => group.add(Number(v))); | ||
edges.get(idx).forEach((n) => toVisit.push(n)); | ||
} | ||
groups.push(group); | ||
} | ||
return groups; | ||
}; | ||
var sortCyclicGroups = (groups, graph) => { | ||
const getReachableNodes = (group) => { | ||
const first = group.values().next().value; | ||
const entry = graph.get(first)[0]; | ||
return Array.from(buildGraph(entry).keys()); | ||
}; | ||
const result = new Array(); | ||
function dependentsFirst(group) { | ||
if (result.includes(group)) | ||
return; | ||
const dependents = groups.filter( | ||
(candidate) => candidate !== group && getReachableNodes(group).some((node) => candidate.has(node)) | ||
); | ||
dependents.forEach((group2) => dependentsFirst(group2)); | ||
if (result.includes(group)) | ||
return; | ||
result.push(group); | ||
} | ||
groups.forEach((group) => dependentsFirst(group)); | ||
return result; | ||
}; | ||
var buildChecksum = (entry, cache) => { | ||
if (cache.has(entry.id)) | ||
return cache.get(entry.id); | ||
const graph = buildGraph(entry); | ||
const cycles = getCycles(graph); | ||
const cyclicGroups = getCyclicGroups(cycles); | ||
const sortedCyclicGroups = sortCyclicGroups(cyclicGroups, graph); | ||
const recursiveBuildChecksum = (entry2, writeCache, skipCache = false) => { | ||
if (!skipCache && cache.has(entry2.id)) { | ||
return cache.get(entry2.id); | ||
} | ||
const result = _buildChecksum( | ||
entry2, | ||
(nextEntry) => recursiveBuildChecksum(nextEntry, writeCache) | ||
); | ||
writeCache(entry2.id, result); | ||
return result; | ||
}; | ||
sortedCyclicGroups.forEach((group) => { | ||
group.forEach((id) => cache.set(id, 0n)); | ||
for (let i = 0; i < group.size; i++) { | ||
const results = /* @__PURE__ */ new Map(); | ||
group.forEach( | ||
(id) => recursiveBuildChecksum( | ||
graph.get(id)[0], | ||
(id2, value) => { | ||
const writeCache = group.has(id2) ? results : cache; | ||
writeCache.set(id2, value); | ||
}, | ||
true | ||
) | ||
); | ||
Array.from(results.entries()).forEach( | ||
([id, checksum]) => cache.set(id, checksum) | ||
); | ||
} | ||
}); | ||
return recursiveBuildChecksum(entry, (id, value) => cache.set(id, value)); | ||
}; | ||
var getChecksumBuilder = (metadata) => { | ||
@@ -794,3 +747,3 @@ const lookupData = metadata.lookup; | ||
const cache = /* @__PURE__ */ new Map(); | ||
const buildDefinition = (id) => buildChecksum(getLookupEntryDef(id), cache, /* @__PURE__ */ new Set()); | ||
const buildDefinition = (id) => buildChecksum(getLookupEntryDef(id), cache); | ||
const buildStorage = (pallet, entry) => { | ||
@@ -800,6 +753,6 @@ try { | ||
if (storageEntry.type.tag === "plain") | ||
return getChecksum([buildDefinition(storageEntry.type.value)]); | ||
return buildDefinition(storageEntry.type.value); | ||
const { key, value } = storageEntry.type.value; | ||
const val = buildDefinition(value); | ||
const returnKey = storageEntry.type.value.hashers.length === 1 ? getChecksum([buildDefinition(key)]) : buildDefinition(key); | ||
const returnKey = buildDefinition(key); | ||
return getChecksum([val, returnKey]); | ||
@@ -810,15 +763,15 @@ } catch (_) { | ||
}; | ||
const buildEnumEntry = (entry) => { | ||
if (entry.type === "primitive") | ||
return 0n; | ||
const values = Object.values(entry.value).map((l) => buildDefinition(l.id)); | ||
return entry.type === "tuple" ? getChecksum(values) : getChecksum(values, JSON.stringify(Object.keys(entry.value))); | ||
}; | ||
const buildCall = (pallet, callName) => { | ||
const buildRuntimeCall = (api, method) => { | ||
try { | ||
const palletEntry = metadata.pallets.find((x) => x.name === pallet); | ||
const callsLookup = getLookupEntryDef(palletEntry.calls); | ||
if (callsLookup.type !== "enum") | ||
const entry = metadata.apis.find((x) => x.name === api)?.methods.find((x) => x.name === method); | ||
if (!entry) | ||
throw null; | ||
return buildEnumEntry(callsLookup.value[callName]); | ||
const argNamesChecksum = getStringChecksum( | ||
entry.inputs.map((x) => x.name) | ||
); | ||
const argValuesChecksum = getChecksum( | ||
entry.inputs.map((x) => buildDefinition(x.type)) | ||
); | ||
const outputChecksum = buildDefinition(entry.output); | ||
return getChecksum([argNamesChecksum, argValuesChecksum, outputChecksum]); | ||
} catch (_) { | ||
@@ -828,11 +781,35 @@ return null; | ||
}; | ||
const buildComposite = (input) => { | ||
if (input.type === "void") | ||
return getChecksum([0n]); | ||
if (input.type === "tuple") { | ||
const values = Object.values(input.value).map( | ||
(entry) => buildDefinition(entry.id) | ||
); | ||
return getChecksum([shapeIds.tuple, ...values]); | ||
} | ||
return structLikeBuilder( | ||
shapeIds.struct, | ||
input.value, | ||
(entry) => buildDefinition(entry.id) | ||
); | ||
}; | ||
const buildNamedTuple = (input) => { | ||
return structLikeBuilder( | ||
shapeIds.tuple, | ||
input.value, | ||
(entry) => buildDefinition(entry.id) | ||
); | ||
}; | ||
const buildVariant = (variantType) => (pallet, name) => { | ||
try { | ||
const palletEntry = metadata.pallets.find((x) => x.name === pallet); | ||
const callsLookup = getLookupEntryDef( | ||
const enumLookup = getLookupEntryDef( | ||
palletEntry[variantType] | ||
); | ||
if (callsLookup.type !== "enum") | ||
buildDefinition(enumLookup.id); | ||
if (enumLookup.type !== "enum") | ||
throw null; | ||
return buildEnumEntry(callsLookup.value[name]); | ||
const entry = enumLookup.value[name]; | ||
return entry.type === "lookupEntry" ? buildDefinition(entry.value.id) : buildComposite(entry); | ||
} catch (_) { | ||
@@ -853,254 +830,13 @@ return null; | ||
buildDefinition: toStringEnhancer(buildDefinition), | ||
buildRuntimeCall: toStringEnhancer(buildRuntimeCall), | ||
buildStorage: toStringEnhancer(buildStorage), | ||
buildCall: toStringEnhancer(buildCall), | ||
buildCall: toStringEnhancer(buildVariant("calls")), | ||
buildEvent: toStringEnhancer(buildVariant("events")), | ||
buildError: toStringEnhancer(buildVariant("errors")), | ||
buildConstant: toStringEnhancer(buildConstant) | ||
buildConstant: toStringEnhancer(buildConstant), | ||
buildComposite: toStringEnhancer(buildComposite), | ||
buildNamedTuple: toStringEnhancer(buildNamedTuple), | ||
getAllGeneratedChecksums: () => Array.from(cache.values()).map((v) => v.toString(32)) | ||
}; | ||
}; | ||
// src/view-builder/view-builder.ts | ||
var import_utils2 = require("@polkadot-api/utils"); | ||
var import_substrate_bindings2 = require("@polkadot-api/substrate-bindings"); | ||
// src/view-builder/shaped-decoders.ts | ||
var import_utils = require("@polkadot-api/utils"); | ||
var scale2 = __toESM(require("@polkadot-api/substrate-bindings")); | ||
var toHex = import_utils.toHex; | ||
var createInputValueDecoder = (dec, rest) => scale2.createDecoder((_bytes2) => { | ||
const bytes = _bytes2; | ||
const start = bytes.i; | ||
const value = dec(bytes); | ||
const input = toHex(new Uint8Array(bytes.buffer.slice(start, bytes.i))); | ||
return { ...rest, value, input }; | ||
}); | ||
var primitiveShapedDecoder = (codec, input, rest) => { | ||
const decoder = createInputValueDecoder(input, { codec, ...rest }); | ||
return Object.assign(decoder, { | ||
shape: { codec } | ||
}); | ||
}; | ||
var complexShapedDecoder = (shape, input, rest) => { | ||
const decoder = createInputValueDecoder(input, { codec: shape.codec, ...rest }); | ||
return Object.assign(decoder, { | ||
shape | ||
}); | ||
}; | ||
var AccountIdShaped = (ss58Prefix = 42) => { | ||
const enhanced = scale2.enhanceDecoder( | ||
scale2.AccountId(ss58Prefix).dec, | ||
(address) => ({ | ||
address, | ||
ss58Prefix | ||
}) | ||
); | ||
return primitiveShapedDecoder("AccountId", enhanced, {}); | ||
}; | ||
var BytesArray = (len) => primitiveShapedDecoder("BytesArray", scale2.Hex.dec(len), { len }); | ||
var _primitives = [ | ||
"_void", | ||
"bool", | ||
"char", | ||
"str", | ||
"u8", | ||
"u16", | ||
"u32", | ||
"i8", | ||
"i16", | ||
"i32", | ||
"u64", | ||
"u128", | ||
"u256", | ||
"i64", | ||
"i128", | ||
"i256", | ||
"compactNumber", | ||
"compactBn", | ||
"bitSequence" | ||
]; | ||
var corePrimitives = Object.fromEntries( | ||
_primitives.map((x) => [x, primitiveShapedDecoder(x, scale2[x].dec)]) | ||
); | ||
var primitives = { | ||
...corePrimitives, | ||
Bytes: primitiveShapedDecoder("Bytes", scale2.Hex.dec()), | ||
BytesArray, | ||
AccountId: AccountIdShaped() | ||
}; | ||
var Sequence = (input) => complexShapedDecoder( | ||
{ codec: "Sequence", shape: input.shape }, | ||
scale2.Vector.dec(input) | ||
); | ||
var ArrayDec = (input, len) => complexShapedDecoder( | ||
{ codec: "Array", shape: input.shape, len }, | ||
scale2.Vector.dec(input, len) | ||
); | ||
var TupleDec = (...input) => complexShapedDecoder( | ||
{ codec: "Tuple", shape: input.map((x) => x.shape) }, | ||
scale2.Tuple.dec(...input) | ||
); | ||
var StructDec = (input) => complexShapedDecoder( | ||
{ codec: "Struct", shape: (0, import_utils.mapStringRecord)(input, (x) => x.shape) }, | ||
scale2.Struct.dec(input) | ||
); | ||
var EnumDec = (input, args) => complexShapedDecoder( | ||
{ codec: "Enum", shape: (0, import_utils.mapStringRecord)(input, (x) => x.shape) }, | ||
scale2.Enum.dec(input, args) | ||
); | ||
var selfDecoder = (value) => { | ||
let cache = (x) => { | ||
const decoder = value(); | ||
const result2 = decoder; | ||
cache = decoder; | ||
return result2(x); | ||
}; | ||
const result = (x) => cache(x); | ||
result.shape = { codec: "_void" }; | ||
return result; | ||
}; | ||
var complex = { | ||
Sequence, | ||
Array: ArrayDec, | ||
Tuple: TupleDec, | ||
Struct: StructDec, | ||
Enum: EnumDec | ||
}; | ||
// src/view-builder/view-builder.ts | ||
var withProp = (input, propName, propValue) => { | ||
const decoder = (0, import_substrate_bindings2.enhanceDecoder)(input, (x) => ({ | ||
...x, | ||
[propName]: propValue | ||
})); | ||
decoder.shape = input.shape; | ||
return decoder; | ||
}; | ||
var addPath = (fn) => (input, cache, stack, lookupData, ...rest) => { | ||
const { path } = lookupData[input.id]; | ||
const base = fn(input, cache, stack, lookupData, ...rest); | ||
return path.length ? withProp(base, "path", path) : base; | ||
}; | ||
var _buildShapedDecoder = (input, cache, stack, lookupData, _accountId) => { | ||
if (input.type === "primitive") | ||
return primitives[input.value]; | ||
if (input.type === "compact") | ||
return input.isBig ? primitives.compactBn : primitives.compactNumber; | ||
if (input.type === "bitSequence") | ||
return primitives.bitSequence; | ||
if (input.type === "sequence" && input.value.type === "primitive" && input.value.value === "u8") { | ||
return primitives.Bytes; | ||
} | ||
const buildNext = (nextInput) => buildShapedDecoder(nextInput, cache, stack, lookupData, _accountId); | ||
const buildVector = (inner2, len) => { | ||
const _inner = buildNext(inner2); | ||
return len ? complex.Array(_inner, len) : complex.Sequence(_inner); | ||
}; | ||
const buildTuple = (value, innerDocs) => withProp(complex.Tuple(...value.map(buildNext)), "innerDocs", innerDocs); | ||
const buildStruct = (value, innerDocs) => withProp( | ||
complex.Struct((0, import_utils2.mapStringRecord)(value, buildNext)), | ||
"innerDocs", | ||
innerDocs | ||
); | ||
if (input.type === "array") { | ||
if (input.value.type === "primitive" && input.value.value === "u8") { | ||
return input.len === 32 && (input.id === 0 || input.id === 1) ? _accountId : primitives.BytesArray(input.len); | ||
} | ||
return buildVector(input.value, input.len); | ||
} | ||
if (input.type === "sequence") | ||
return buildVector(input.value); | ||
if (input.type === "tuple") | ||
return buildTuple(input.value, input.innerDocs); | ||
if (input.type === "struct") | ||
return buildStruct(input.value, input.innerDocs); | ||
const dependencies = Object.values(input.value).map((v) => { | ||
if (v.type === "primitive") | ||
return primitives._void; | ||
if (v.type === "tuple" && v.value.length === 1) { | ||
return buildNext(v.value[0]); | ||
} | ||
return v.type === "tuple" ? buildTuple(v.value, v.innerDocs) : buildStruct(v.value, v.innerDocs); | ||
}); | ||
const inner = Object.fromEntries( | ||
Object.keys(input.value).map((key, idx) => [key, dependencies[idx]]) | ||
); | ||
const indexes = Object.values(input.value).map((x) => x.idx); | ||
const areIndexesSorted = indexes.every((idx, i) => idx === i); | ||
const withoutDocs = areIndexesSorted ? complex.Enum(inner) : complex.Enum(inner, indexes); | ||
const withDocs = (0, import_substrate_bindings2.enhanceDecoder)(withoutDocs, (val) => { | ||
const docs = input.innerDocs[val.value.tag]; | ||
return { | ||
...val, | ||
docs | ||
}; | ||
}); | ||
withDocs.shape = withoutDocs.shape; | ||
return withDocs; | ||
}; | ||
var withPath = addPath(_buildShapedDecoder); | ||
var buildShapedDecoder = withCache(withPath, selfDecoder, (outter, inner) => { | ||
inner.shape = outter.shape; | ||
return outter; | ||
}); | ||
var hexStrFromByte = (input) => `0x${input.toString(16).padEnd(2, "0")}`; | ||
var getViewBuilder = (metadata) => { | ||
const lookupData = metadata.lookup; | ||
const cache = /* @__PURE__ */ new Map(); | ||
const getDecoder = (id) => buildShapedDecoder( | ||
getLookupEntryDef(id), | ||
cache, | ||
/* @__PURE__ */ new Set(), | ||
lookupData, | ||
_accountId | ||
); | ||
const getLookupEntryDef = getLookupFn(lookupData); | ||
let _accountId = primitives.AccountId; | ||
const prefix = metadata.pallets.find((x) => x.name === "System")?.constants.find((x) => x.name === "SS58Prefix"); | ||
if (prefix) { | ||
try { | ||
const prefixVal = getDecoder(prefix.type)(prefix.value).value; | ||
if (typeof prefixVal === "number") | ||
_accountId = AccountIdShaped(prefixVal); | ||
} catch (_) { | ||
} | ||
} | ||
const buildDefinition = (id) => { | ||
const shapedDecoder = getDecoder(id); | ||
return { | ||
shape: shapedDecoder.shape, | ||
decoder: shapedDecoder | ||
}; | ||
}; | ||
const callDecoder = (0, import_substrate_bindings2.createDecoder)((bytes) => { | ||
const palletIdx = import_substrate_bindings2.u8.dec(bytes); | ||
const palletEntry = metadata.pallets.find((x) => x.index === palletIdx); | ||
if (!palletEntry) | ||
throw new Error("Invalid Pallet"); | ||
const pallet = { | ||
value: { | ||
name: palletEntry.name, | ||
idx: palletIdx | ||
}, | ||
input: hexStrFromByte(bytes[0]) | ||
}; | ||
const callsDecoder = getDecoder(palletEntry.calls); | ||
const decoded = callsDecoder(bytes); | ||
if (decoded.codec !== "Enum") | ||
throw null; | ||
const call = { | ||
value: { | ||
name: decoded.value.tag, | ||
idx: bytes[1] | ||
}, | ||
input: hexStrFromByte(bytes[1]), | ||
docs: decoded.docs | ||
}; | ||
return { | ||
pallet, | ||
call, | ||
args: { value: decoded.value.value, shape: callsDecoder.shape } | ||
}; | ||
}); | ||
return { buildDefinition, callDecoder }; | ||
}; | ||
//# sourceMappingURL=index.js.map |
import * as scale from '@polkadot-api/substrate-bindings'; | ||
import { StringRecord, V14, Codec, Decoder, HexString } from '@polkadot-api/substrate-bindings'; | ||
export { Decoder, HexString, StringRecord, V14 } from '@polkadot-api/substrate-bindings'; | ||
import { StringRecord, V15, Codec } from '@polkadot-api/substrate-bindings'; | ||
type VoidVar = { | ||
type MetadataPrimitives = "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256"; | ||
type PrimitiveVar = { | ||
type: "primitive"; | ||
value: "_void"; | ||
value: MetadataPrimitives; | ||
}; | ||
type MetadataPrimitives$1 = "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256"; | ||
type PrimitiveVar = { | ||
type: "primitive"; | ||
value: MetadataPrimitives$1; | ||
} | VoidVar; | ||
type VoidVar = { | ||
type: "void"; | ||
}; | ||
type CompactVar = { | ||
type: "compact"; | ||
isBig: boolean; | ||
isBig: boolean | null; | ||
}; | ||
@@ -21,3 +19,6 @@ type BitSequenceVar = { | ||
}; | ||
type TerminalVar = PrimitiveVar | CompactVar | BitSequenceVar; | ||
type AccountId32 = { | ||
type: "AccountId32"; | ||
}; | ||
type TerminalVar = PrimitiveVar | VoidVar | CompactVar | BitSequenceVar | AccountId32; | ||
type TupleVar = { | ||
@@ -35,3 +36,6 @@ type: "tuple"; | ||
type: "enum"; | ||
value: StringRecord<(TupleVar | StructVar | VoidVar) & { | ||
value: StringRecord<({ | ||
type: "lookupEntry"; | ||
value: LookupEntry; | ||
} | VoidVar | TupleVar | StructVar) & { | ||
idx: number; | ||
@@ -41,2 +45,13 @@ }>; | ||
}; | ||
type OptionVar = { | ||
type: "option"; | ||
value: LookupEntry; | ||
}; | ||
type ResultVar = { | ||
type: "result"; | ||
value: { | ||
ok: LookupEntry; | ||
ko: LookupEntry; | ||
}; | ||
}; | ||
type SequenceVar = { | ||
@@ -51,3 +66,3 @@ type: "sequence"; | ||
}; | ||
type ComposedVar = TupleVar | StructVar | SequenceVar | ArrayVar | EnumVar; | ||
type ComposedVar = TupleVar | StructVar | SequenceVar | ArrayVar | OptionVar | ResultVar | EnumVar; | ||
type Var = TerminalVar | ComposedVar; | ||
@@ -62,3 +77,3 @@ type LookupEntry = { | ||
name: string; | ||
type: number | void | undefined; | ||
type: number | undefined; | ||
}[]; | ||
@@ -68,5 +83,5 @@ def: { | ||
value: { | ||
name: string | void | undefined; | ||
name: string | undefined; | ||
type: number; | ||
typeName: string | void | undefined; | ||
typeName: string | undefined; | ||
docs: string[]; | ||
@@ -79,5 +94,5 @@ }[]; | ||
fields: { | ||
name: string | void | undefined; | ||
name: string | undefined; | ||
type: number; | ||
typeName: string | void | undefined; | ||
typeName: string | undefined; | ||
docs: string[]; | ||
@@ -157,5 +172,2 @@ }[]; | ||
}; | ||
} | { | ||
tag: "historicMetaCompat"; | ||
value: string; | ||
}; | ||
@@ -165,30 +177,3 @@ docs: string[]; | ||
type MetadataPrimitives = "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256"; | ||
declare const primitiveTypes: Record<MetadataPrimitives | "_void" | "compactNumber" | "compactBn" | "bitSequence" | "historicMetaCompat", string>; | ||
interface Variable { | ||
id: string; | ||
types: string; | ||
value: string; | ||
directDependencies: Set<string>; | ||
} | ||
interface CodeDeclarations { | ||
imports: Set<string>; | ||
typeImports: Set<string>; | ||
variables: Map<string, Variable>; | ||
} | ||
declare const getStaticBuilder: (metadata: V14) => { | ||
buildDefinition: (id: number) => string; | ||
buildStorage: (pallet: string, entry: string) => { | ||
key: string; | ||
val: string; | ||
}; | ||
buildEvent: (pallet: string, name: string) => string; | ||
buildError: (pallet: string, name: string) => string; | ||
buildCall: (pallet: string, callName: string) => string; | ||
buildConstant: (pallet: string, constantName: string) => string; | ||
getTypeFromVarName: (varName: string) => string; | ||
getCode: () => string; | ||
}; | ||
declare const getDynamicBuilder: (metadata: V14) => { | ||
declare const getDynamicBuilder: (metadata: V15) => { | ||
buildDefinition: (id: number) => Codec<any>; | ||
@@ -216,3 +201,8 @@ buildStorage: (pallet: string, entry: string) => { | ||
}; | ||
buildCall: (pallet: string, callName: string) => { | ||
buildRuntimeCall: (api: string, method: string) => { | ||
args: Codec<any[]>; | ||
value: Codec<any>; | ||
}; | ||
buildCall: (pallet: string, name: string) => { | ||
codec: Codec<any>; | ||
location: [ | ||
@@ -222,3 +212,2 @@ number, | ||
]; | ||
args: Codec<any>; | ||
}; | ||
@@ -229,143 +218,15 @@ buildConstant: (pallet: string, constantName: string) => Codec<any>; | ||
declare const getChecksumBuilder: (metadata: V14) => { | ||
declare const getChecksumBuilder: (metadata: V15) => { | ||
buildDefinition: (id: number) => string | null; | ||
buildRuntimeCall: (api: string, method: string) => string | null; | ||
buildStorage: (pallet: string, entry: string) => string | null; | ||
buildCall: (pallet: string, callName: string) => string | null; | ||
buildCall: (pallet: string, name: string) => string | null; | ||
buildEvent: (pallet: string, name: string) => string | null; | ||
buildError: (pallet: string, name: string) => string | null; | ||
buildConstant: (pallet: string, constantName: string) => string | null; | ||
buildComposite: (input: VoidVar | TupleVar | StructVar) => string | null; | ||
buildNamedTuple: (input: StructVar) => string | null; | ||
getAllGeneratedChecksums: () => string[]; | ||
}; | ||
type GetViewBuilder = (metadata: V14) => { | ||
buildDefinition: (idx: number) => { | ||
shape: Shape; | ||
decoder: Decoder<Decoded>; | ||
}; | ||
callDecoder: Decoder<DecodedCall>; | ||
}; | ||
interface DecodedCall { | ||
pallet: { | ||
value: { | ||
name: string; | ||
idx: number; | ||
}; | ||
input: HexString; | ||
}; | ||
call: { | ||
value: { | ||
name: string; | ||
idx: number; | ||
}; | ||
input: HexString; | ||
docs: string[]; | ||
}; | ||
args: { | ||
value: StructDecoded; | ||
shape: Shape; | ||
}; | ||
} | ||
type WithInputAndPath<T> = T & { | ||
input: HexString; | ||
path?: string[]; | ||
}; | ||
type VoidDecoded = WithInputAndPath<{ | ||
codec: "_void"; | ||
value: undefined; | ||
}>; | ||
type BoolDecoded = WithInputAndPath<{ | ||
codec: "bool"; | ||
value: boolean; | ||
}>; | ||
type StringDecoded = WithInputAndPath<{ | ||
codec: "str" | "char"; | ||
value: string; | ||
}>; | ||
type NumberDecoded = WithInputAndPath<{ | ||
codec: "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "compactNumber"; | ||
value: number; | ||
}>; | ||
type BigNumberDecoded = WithInputAndPath<{ | ||
codec: "u64" | "u128" | "u256" | "i64" | "i128" | "i256" | "compactBn"; | ||
value: bigint; | ||
}>; | ||
type BitSequenceDecoded = WithInputAndPath<{ | ||
codec: "bitSequence"; | ||
value: { | ||
bitsLen: number; | ||
bytes: Uint8Array; | ||
}; | ||
}>; | ||
type BytesSequenceDecoded = WithInputAndPath<{ | ||
codec: "Bytes"; | ||
value: HexString; | ||
}>; | ||
type BytesArrayDecoded = WithInputAndPath<{ | ||
codec: "BytesArray"; | ||
value: HexString; | ||
len: number; | ||
}>; | ||
type AccountIdDecoded = WithInputAndPath<{ | ||
codec: "AccountId"; | ||
value: { | ||
ss58Prefix: number; | ||
address: string; | ||
}; | ||
}>; | ||
type PrimitiveDecoded = VoidDecoded | BoolDecoded | StringDecoded | NumberDecoded | BigNumberDecoded | BitSequenceDecoded | BytesSequenceDecoded | BytesArrayDecoded | AccountIdDecoded; | ||
type SequenceDecoded = WithInputAndPath<{ | ||
codec: "Sequence"; | ||
value: Array<Decoded>; | ||
}>; | ||
type ArrayDecoded = WithInputAndPath<{ | ||
codec: "Array"; | ||
value: Array<Decoded>; | ||
}>; | ||
type TupleDecoded = WithInputAndPath<{ | ||
codec: "Tuple"; | ||
value: Array<Decoded>; | ||
innerDocs: Array<string[]>; | ||
}>; | ||
type StructDecoded = WithInputAndPath<{ | ||
codec: "Struct"; | ||
value: StringRecord<Decoded>; | ||
innerDocs: StringRecord<string[]>; | ||
}>; | ||
type EnumDecoded = WithInputAndPath<{ | ||
codec: "Enum"; | ||
value: { | ||
tag: string; | ||
value: Decoded; | ||
}; | ||
docs: string[]; | ||
}>; | ||
type ComplexDecoded = SequenceDecoded | ArrayDecoded | TupleDecoded | StructDecoded | EnumDecoded; | ||
type Decoded = PrimitiveDecoded | ComplexDecoded; | ||
interface SequenceShape { | ||
codec: "Sequence"; | ||
shape: Shape; | ||
} | ||
interface ArrayShape { | ||
codec: "Array"; | ||
len: number; | ||
shape: Shape; | ||
} | ||
interface TupleShape { | ||
codec: "Tuple"; | ||
shape: Array<Shape>; | ||
} | ||
interface StructShape { | ||
codec: "Struct"; | ||
shape: StringRecord<Shape>; | ||
} | ||
interface EnumShape { | ||
codec: "Enum"; | ||
shape: StringRecord<Shape>; | ||
} | ||
type ComplexShape = SequenceShape | ArrayShape | TupleShape | StructShape | EnumShape; | ||
type Shape = { | ||
codec: PrimitiveDecoded["codec"]; | ||
} | ComplexShape; | ||
declare const getViewBuilder: GetViewBuilder; | ||
export { type AccountIdDecoded, type ArrayDecoded, type ArrayShape, type ArrayVar, type BigNumberDecoded, type BitSequenceDecoded, type BitSequenceVar, type BoolDecoded, type BytesArrayDecoded, type BytesSequenceDecoded, type CodeDeclarations, type CompactVar, type ComplexDecoded, type ComplexShape, type ComposedVar, type Decoded, type DecodedCall, type EnumDecoded, type EnumShape, type EnumVar, type GetViewBuilder, type LookupEntry, type MetadataPrimitives$1 as MetadataPrimitives, type NumberDecoded, type PrimitiveDecoded, type PrimitiveVar, type SequenceDecoded, type SequenceShape, type SequenceVar, type Shape, type StringDecoded, type StructDecoded, type StructShape, type StructVar, type TerminalVar, type TupleDecoded, type TupleShape, type TupleVar, type Var, type Variable, type VoidDecoded, type VoidVar, getChecksumBuilder, getDynamicBuilder, getLookupFn, getStaticBuilder, getViewBuilder, primitiveTypes }; | ||
export { type AccountId32, type ArrayVar, type BitSequenceVar, type CompactVar, type ComposedVar, type EnumVar, type LookupEntry, type MetadataPrimitives, type OptionVar, type PrimitiveVar, type ResultVar, type SequenceVar, type StructVar, type TerminalVar, type TupleVar, type Var, type VoidVar, getChecksumBuilder, getDynamicBuilder, getLookupFn }; |
@@ -1,8 +0,2 @@ | ||
"use strict";var ie=Object.create;var q=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty;var pe=(e,t)=>{for(var p in t)q(e,p,{get:t[p],enumerable:!0})},G=(e,t,p,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of se(t))!ue.call(e,s)&&s!==p&&q(e,s,{get:()=>t[s],enumerable:!(r=ae(t,s))||r.enumerable});return e};var J=(e,t,p)=>(p=e!=null?ie(ce(e)):{},G(t||!e||!e.__esModule?q(p,"default",{value:e,enumerable:!0}):p,e)),de=e=>G(q({},"__esModule",{value:!0}),e);var qe={};pe(qe,{getChecksumBuilder:()=>Ee,getDynamicBuilder:()=>Se,getLookupFn:()=>T,getStaticBuilder:()=>ye,getViewBuilder:()=>oe,primitiveTypes:()=>M});module.exports=de(qe);var I={type:"primitive",value:"_void"},T=e=>{let t=new Map,p=new Set,s=(d=>n=>{let h=t.get(n);if(h)return h;if(p.has(n)){let c={id:n};return t.set(n,c),c}p.add(n);let y=d(n);return h=t.get(n),h?Object.assign(h,y):(h={id:n,...y},t.set(n,h)),p.delete(n),h})(d=>{let{def:n}=e[d];if(n.tag==="composite"){if(n.value.length===0)return I;if(n.value.length===1)return s(n.value[0].type);let y=!0,c={},v={};return n.value.forEach((b,m)=>{y=y&&!!b.name;let u=b.name||m;c[u]=s(b.type),v[u]=b.docs}),y?{type:"struct",value:c,innerDocs:v}:{type:"tuple",value:Object.values(c),innerDocs:Object.values(v)}}if(n.tag==="variant"){if(n.value.length===0)return I;let y={},c={};return n.value.forEach(v=>{let b=v.name;if(c[b]=v.docs,v.fields.length===0){y[b]={...I,idx:v.index};return}let m=!0,u={},i={};v.fields.forEach((o,a)=>{m=m&&!!o.name;let l=o.name||a;u[l]=s(o.type),i[l]=o.docs}),y[b]=m?{type:"struct",value:u,innerDocs:i,idx:v.index}:{type:"tuple",value:Object.values(u),innerDocs:Object.values(i),idx:v.index}}),{type:"enum",value:y,innerDocs:c}}if(n.tag==="sequence")return{type:"sequence",value:s(n.value)};if(n.tag==="array")return{type:"array",value:s(n.value.type),len:n.value.len};if(n.tag==="tuple"){if(n.value.length===0)return I;if(n.value.length===1)return s(n.value[0]);let y=n.value.map(v=>s(v)),c=n.value.map(v=>e[v].docs);return{type:"tuple",value:y,innerDocs:c}}if(n.tag==="primitive")return{type:"primitive",value:n.value.tag};if(n.tag==="compact"){let y=s(n.value);return{type:"compact",isBig:Number(y.value.slice(1))>32}}return n.tag==="bitSequence"?{type:"bitSequence"}:{type:"primitive",value:n.value}});return s};var L=(e,t,p)=>(r,s,d,...n)=>{let{id:h}=r;if(s.has(h))return s.get(h);if(d.has(h)){let c=t(()=>s.get(h),r,...n);return s.set(h,c),c}d.add(h);let y=e(r,s,d,...n);return d.delete(h),s.has(h)&&(y=p(y,s.get(h),r,...n)),s.set(h,y),y};var M={_void:"undefined",bool:"boolean",char:"string",str:"string",u8:"number",u16:"number",u32:"number",u64:"bigint",u128:"bigint",u256:"bigint",i8:"number",i16:"number",i32:"number",i64:"bigint",i128:"bigint",i256:"bigint",compactNumber:"number",compactBn:"bigint",bitSequence:"{bitsLen: number, bytes: Uint8Array}",historicMetaCompat:"any"},W=(...e)=>e[0]+e.slice(1).map(t=>t[0].toUpperCase()+t.slice(1)).join(""),le=e=>e.type==="primitive"&&e.value==="u8",O=e=>M[e]??`I${e}`,me=(e,t,p,r,s)=>{if(e.type==="primitive")return r.imports.add(e.value),e.value;if(e.type==="compact"){let i=e.isBig?"compactBn":"compactNumber";return r.imports.add(i),i}if(e.type==="bitSequence")return r.imports.add(e.type),e.type;if(e.type==="sequence"&&e.value.type==="primitive"&&e.value.value==="u8"){r.imports.add("Bin"),r.typeImports.add("HexString"),r.typeImports.add("Binary");let i={id:"_bytesSeq",value:"Bin()",types:"Binary",directDependencies:new Set};return r.variables.has(i.id)||r.variables.set(i.id,i),i.id}if(r.variables.has(s(e.id,"circular")))return s(e.id,"circular");if(r.variables.has(s(e.id)))return s(e.id);let d=i=>Y(i,t,p,r,s),n=(i,o,a)=>{r.imports.add("Vector");let l=d(o),S={id:i,value:`Vector(${(a?[l,a]:[l]).join(", ")})`,types:`Array<${O(l)}>`,directDependencies:new Set([l])};return r.variables.set(i,S),i},h=(i,o)=>{r.imports.add("Tuple");let a=o.map(d),l={id:i,value:`Tuple(${a.join(", ")})`,types:`[${a.map(O).join(", ")}]`,directDependencies:new Set(a)};return r.variables.set(i,l),i},y=(i,o)=>{r.imports.add("Struct");let a=Object.values(o).map(d),l={id:i,value:`Struct({${Object.keys(o).map((g,S)=>`${g}: ${a[S]}`).join(", ")}})`,types:`{${Object.keys(o).map((g,S)=>`${g}: ${O(a[S])}`).join(", ")}}`,directDependencies:new Set(a)};return r.variables.set(i,l),i},c=s(e.id);if(e.type==="array"){if(le(e.value)){if(e.len===32&&(e.id===0||e.id===1)){r.imports.add("AccountId");let i="_accountId";return r.variables.set(i,{id:i,value:"AccountId()",types:"SS58String",directDependencies:new Set}),r.typeImports.add("SS58String"),i}return r.imports.add("Bin"),r.variables.set(c,{id:c,value:`Bin(${e.len})`,types:"Binary",directDependencies:new Set}),r.typeImports.add("HexString"),r.typeImports.add("Binary"),c}return n(c,e.value,e.len)}if(e.type==="sequence")return n(c,e.value);if(e.type==="tuple")return h(c,e.value);if(e.type==="struct")return y(c,e.value);r.imports.add("Enum");let v=Object.entries(e.value).map(([i,o])=>{if(o.type==="primitive")return r.imports.add(o.value),o.value;let a=W(c,i);if(o.type==="tuple"){if(o.value.length===1){let l=d(o.value[0]);return r.variables.has(a)||r.variables.set(a,{id:a,value:l,types:O(l),directDependencies:new Set([l])}),a}return h(a,o.value)}else y(a,o.value);return a}),b=Object.values(e.value).map(i=>i.idx),m=b.every((i,o)=>i===o),u=`{${Object.keys(e.value).map((i,o)=>`${i}: ${v[o]}`)}}${m?"":`, [${b.join(", ")}]`}`;return r.variables.set(c,{id:c,value:`Enum(${u})`,types:Object.keys(e.value).map((i,o)=>`{tag: '${i}', value: ${O(v[o])}}`).join(" | "),directDependencies:new Set(v)}),c},Y=L(me,(e,t,p,r)=>{p.imports.add("Self");let s=r(t.id),d={id:r(t.id,"circular"),types:`I${s}`,value:`Self(() => ${s})`,directDependencies:new Set([s])};return p.variables.set(d.id,d),d.id},e=>e),ye=e=>{let t={imports:new Set,typeImports:new Set(["Codec"]),variables:new Map},p=e.lookup,r=T(p),s=(a,...l)=>{let{path:g}=p[a],S=g.length===0?["cdc"+a]:["c",...g];return S.push(...l),W(...S)},d=new Map,n=a=>Y(r(a),d,new Set,t,s),h=(a,l)=>{if(t.variables.has(l))return l;let g=a.map(x=>x.type).map(n),S=a.map(x=>x.name);t.imports.add("Tuple");let E={id:l,types:`[${S.map((x,C)=>`${x[0].toUpperCase()+x.slice(1)}: ${O(g[C])}`).join(", ")}]`,value:`Tuple(${g.join(", ")})`,directDependencies:new Set(g)};return t.variables.set(l,E),l},y="_emptyTuple",c=()=>(t.variables.has(y)||(t.imports.add("Tuple"),t.variables.set(y,{id:y,types:"[]",value:"Tuple()",directDependencies:new Set})),y),v=(a,l)=>{let g=e.pallets.find(j=>j.name===a).storage.items.find(j=>j.name===l);if(g.type.tag==="plain")return{key:c(),val:n(g.type.value)};let{key:S,value:E}=g.type.value,x=n(E);return{key:g.type.value.hashers.length===1?h([{name:"key",type:S}],s(S,"Tupled")):n(S),val:x}},b=a=>(l,g)=>{let S=r(e.pallets.find(x=>x.name===l)[a]);if(S.type!=="enum")throw null;let E=W(n(S.id),g);return!t.variables.has(E)&&S.value[g].type==="primitive"&&t.variables.set(E,{id:E,value:"_void",types:"undefined",directDependencies:new Set}),E},m=(a,l)=>{let g=r(e.pallets.find(x=>x.name===a).calls);if(g.type!=="enum")throw null;let S=g.value[l];if(S.type==="primitive")return c();if(S.type==="tuple")return W(n(g.id),l);let E=Object.entries(S.value).map(([x,C])=>({name:x,type:C.id}));return h(E,s(g.id,l,"Tupled"))},u=(a,l)=>{let g=e.pallets.find(S=>S.name===a).constants.find(S=>S.name===l);return n(g.type)},i=()=>{let a=`import type {${[...t.typeImports].join(", ")}} from "@polkadot-api/substrate-bindings"; | ||
`,l=`import {${[...t.imports].join(", ")}} from "@polkadot-api/substrate-bindings"; | ||
`,g=[...t.variables.values()].map(S=>`type I${S.id} = ${S.types}; | ||
const ${S.id}: Codec<I${S.id}> = ${S.value};`).join(` | ||
`);return`${a}${l}${g}`},o=a=>M[a]??t.variables.get(a)?.types??`I${a}`;return{buildDefinition:n,buildStorage:v,buildEvent:b("events"),buildError:b("errors"),buildCall:m,buildConstant:u,getTypeFromVarName:o,getCode:i}};var f=J(require("@polkadot-api/substrate-bindings"));var ve=f.Bin(),he=e=>e.type==="primitive"&&e.value==="u8",be=(e,t,p,r)=>{if(e.type==="primitive")return f[e.value];if(e.type==="compact")return f.compact;if(e.type==="bitSequence")return f.bitSequence;if(e.type==="sequence"&&e.value.type==="primitive"&&e.value.value==="u8")return ve;let s=m=>z(m,t,p,r),d=(m,u)=>{let i=s(m);return u?f.Vector(i,u):f.Vector(i)},n=m=>f.Tuple(...m.map(s)),h=m=>{let u=Object.fromEntries(Object.entries(m).map(([i,o])=>[i,s(o)]));return f.Struct(u)};if(e.type==="array")return he(e.value)?e.len===32&&(e.id===0||e.id===1)?r:f.Bin(e.len):d(e.value,e.len);if(e.type==="sequence")return d(e.value);if(e.type==="tuple")return n(e.value);if(e.type==="struct")return h(e.value);let y=Object.values(e.value).map(m=>m.type==="primitive"?f._void:m.type==="tuple"&&m.value.length===1?s(m.value[0]):m.type==="tuple"?n(m.value):h(m.value)),c=Object.fromEntries(Object.keys(e.value).map((m,u)=>[m,y[u]])),v=Object.values(e.value).map(m=>m.idx);return v.every((m,u)=>m===u)?f.Enum(c):f.Enum(c,v)},z=L(be,f.Self,e=>e),ge=f.Tuple(),Se=e=>{let t=e.lookup,p=T(t),r=f.AccountId(),s=new Map,d=u=>z(p(u),s,new Set,r),n=e.pallets.find(u=>u.name==="System")?.constants.find(u=>u.name==="SS58Prefix"),h;if(n)try{let u=d(n.type).dec(n.value);typeof u=="number"&&(h=u,r=f.AccountId(u))}catch{}let y=new Map,c=(u,i)=>{let o=y.get(u);o||y.set(u,o=f.Storage(u));let a=e.pallets.find(V=>V.name===u).storage.items.find(V=>V.name===i),l=(V,..._)=>{let K=o(..._);return{...K,len:V,fallback:a.modifier===1?K.dec(a.fallback):void 0}};if(a.type.tag==="plain")return l(0,i,d(a.type.value).dec);let{key:g,value:S,hashers:E}=a.type.value,x=d(S),C=E.map(V=>f[V.tag]),j=C.length===1?[[d(g),C[0]]]:p(g).value.map((V,_)=>[d(V.id),C[_]]);return l(C.length,i,x.dec,...j)},v=(u,i)=>{let o=e.pallets.find(g=>g.name===u),a=p(o.calls);if(a.type!=="enum")throw null;let l=a.value[i];return{location:[o.index,l.idx],args:l.type==="primitive"?ge:f.Tuple(...Object.values(l.value).map(g=>d(g.id)))}},b=(u,i)=>{let o=e.pallets.find(a=>a.name===u).constants.find(a=>a.name===i);return d(o.type)},m=u=>(i,o)=>{let a=e.pallets.find(S=>S.name===i),l=p(a[u]);if(l.type!=="enum")throw null;let g=l.value[o];return{location:[a.index,g.idx],codec:g.type==="primitive"?f._void:d(l.id)}};return{buildDefinition:d,buildStorage:c,buildEvent:m("events"),buildError:m("errors"),buildCall:v,buildConstant:b,ss58Prefix:h}};var F=require("@polkadot-api/substrate-bindings");var Q=new TextEncoder,fe=Q.encode.bind(Q),k=(e,t)=>{let p=typeof t=="string",r=new Uint8Array((e.length+(p?1:0))*8),s=new DataView(r.buffer),d=0;p&&(s.setBigUint64(d,(0,F.h64)(fe(t))),d+=8);for(let n=0;n<e.length;n++,d+=8)s.setBigUint64(d,e[n]);return(0,F.h64)(r)},H={_void:0n,bool:1n,char:2n,str:3n,u8:4n,u16:5n,u32:6n,u64:7n,u128:8n,u256:9n,i8:5n,i16:5n,i32:6n,i64:7n,i128:8n,i256:9n,compacts:10n,compactb:11n,bitSequence:12n,historicMetaCompat:13n},De=14n,xe=(e,t,p)=>{if(t.has(e.id))return t.get(e.id);if(e.type==="primitive")return H[e.value];if(e.type==="compact")return H[e.isBig?"compactb":"compacts"];if(e.type==="bitSequence")return H.bitSequence;if(e.type==="sequence"&&e.value.type==="primitive"&&e.value.value==="u8")return De;let r=c=>X(c,t,p),s=(c,v)=>{let b=r(c);return v?k([b,BigInt(v)],"Vector(,)"):k([b],"Vector()")},d=c=>k(c.map(r)),n=c=>k(Object.values(c).map(r),JSON.stringify(Object.keys(c)));if(e.type==="array")return s(e.value,e.len);if(e.type==="sequence")return s(e.value);if(e.type==="tuple")return d(e.value);if(e.type==="struct")return n(e.value);let h=Object.values(e.value).map(c=>c.type==="primitive"?0n:c.type==="tuple"?d(c.value):n(c.value)),y=Object.keys(e.value);return y.push("Enum"),k(h,JSON.stringify({Enum:y}))},X=L(xe,()=>0n,e=>e),Ee=e=>{let t=e.lookup,p=T(t),r=new Map,s=b=>X(p(b),r,new Set),d=(b,m)=>{try{let u=e.pallets.find(g=>g.name===b).storage.items.find(g=>g.name===m);if(u.type.tag==="plain")return k([s(u.type.value)]);let{key:i,value:o}=u.type.value,a=s(o),l=u.type.value.hashers.length===1?k([s(i)]):s(i);return k([a,l])}catch{return null}},n=b=>{if(b.type==="primitive")return 0n;let m=Object.values(b.value).map(u=>s(u.id));return b.type==="tuple"?k(m):k(m,JSON.stringify(Object.keys(b.value)))},h=(b,m)=>{try{let u=e.pallets.find(o=>o.name===b),i=p(u.calls);if(i.type!=="enum")throw null;return n(i.value[m])}catch{return null}},y=b=>(m,u)=>{try{let i=e.pallets.find(a=>a.name===m),o=p(i[b]);if(o.type!=="enum")throw null;return n(o.value[u])}catch{return null}},c=(b,m)=>{try{let u=e.pallets.find(i=>i.name===b).constants.find(i=>i.name===m);return s(u.type)}catch{return null}},v=b=>(...m)=>b(...m)?.toString(32)??null;return{buildDefinition:v(s),buildStorage:v(d),buildCall:v(h),buildEvent:v(y("events")),buildError:v(y("errors")),buildConstant:v(c)}};var re=require("@polkadot-api/utils"),A=require("@polkadot-api/substrate-bindings");var B=require("@polkadot-api/utils"),D=J(require("@polkadot-api/substrate-bindings")),ke=B.toHex,Z=(e,t)=>D.createDecoder(p=>{let r=p,s=r.i,d=e(r),n=ke(new Uint8Array(r.buffer.slice(s,r.i)));return{...t,value:d,input:n}}),$=(e,t,p)=>{let r=Z(t,{codec:e,...p});return Object.assign(r,{shape:{codec:e}})},R=(e,t,p)=>{let r=Z(t,{codec:e.codec,...p});return Object.assign(r,{shape:e})},U=(e=42)=>{let t=D.enhanceDecoder(D.AccountId(e).dec,p=>({address:p,ss58Prefix:e}));return $("AccountId",t,{})},Ce=e=>$("BytesArray",D.Hex.dec(e),{len:e}),Ve=["_void","bool","char","str","u8","u16","u32","i8","i16","i32","u64","u128","u256","i64","i128","i256","compactNumber","compactBn","bitSequence"],Te=Object.fromEntries(Ve.map(e=>[e,$(e,D[e].dec)])),P={...Te,Bytes:$("Bytes",D.Hex.dec()),BytesArray:Ce,AccountId:U()},Pe=e=>R({codec:"Sequence",shape:e.shape},D.Vector.dec(e)),Le=(e,t)=>R({codec:"Array",shape:e.shape,len:t},D.Vector.dec(e,t)),we=(...e)=>R({codec:"Tuple",shape:e.map(t=>t.shape)},D.Tuple.dec(...e)),Ae=e=>R({codec:"Struct",shape:(0,B.mapStringRecord)(e,t=>t.shape)},D.Struct.dec(e)),Oe=(e,t)=>R({codec:"Enum",shape:(0,B.mapStringRecord)(e,p=>p.shape)},D.Enum.dec(e,t)),ee=e=>{let t=r=>{let s=e(),d=s;return t=s,d(r)},p=r=>t(r);return p.shape={codec:"_void"},p},w={Sequence:Pe,Array:Le,Tuple:we,Struct:Ae,Enum:Oe};var N=(e,t,p)=>{let r=(0,A.enhanceDecoder)(e,s=>({...s,[t]:p}));return r.shape=e.shape,r},je=e=>(t,p,r,s,...d)=>{let{path:n}=s[t.id],h=e(t,p,r,s,...d);return n.length?N(h,"path",n):h},Be=(e,t,p,r,s)=>{if(e.type==="primitive")return P[e.value];if(e.type==="compact")return e.isBig?P.compactBn:P.compactNumber;if(e.type==="bitSequence")return P.bitSequence;if(e.type==="sequence"&&e.value.type==="primitive"&&e.value.value==="u8")return P.Bytes;let d=o=>ne(o,t,p,r,s),n=(o,a)=>{let l=d(o);return a?w.Array(l,a):w.Sequence(l)},h=(o,a)=>N(w.Tuple(...o.map(d)),"innerDocs",a),y=(o,a)=>N(w.Struct((0,re.mapStringRecord)(o,d)),"innerDocs",a);if(e.type==="array")return e.value.type==="primitive"&&e.value.value==="u8"?e.len===32&&(e.id===0||e.id===1)?s:P.BytesArray(e.len):n(e.value,e.len);if(e.type==="sequence")return n(e.value);if(e.type==="tuple")return h(e.value,e.innerDocs);if(e.type==="struct")return y(e.value,e.innerDocs);let c=Object.values(e.value).map(o=>o.type==="primitive"?P._void:o.type==="tuple"&&o.value.length===1?d(o.value[0]):o.type==="tuple"?h(o.value,o.innerDocs):y(o.value,o.innerDocs)),v=Object.fromEntries(Object.keys(e.value).map((o,a)=>[o,c[a]])),b=Object.values(e.value).map(o=>o.idx),u=b.every((o,a)=>o===a)?w.Enum(v):w.Enum(v,b),i=(0,A.enhanceDecoder)(u,o=>{let a=e.innerDocs[o.value.tag];return{...o,docs:a}});return i.shape=u.shape,i},Re=je(Be),ne=L(Re,ee,(e,t)=>(t.shape=e.shape,e)),te=e=>`0x${e.toString(16).padEnd(2,"0")}`,oe=e=>{let t=e.lookup,p=new Map,r=c=>ne(s(c),p,new Set,t,d),s=T(t),d=P.AccountId,n=e.pallets.find(c=>c.name==="System")?.constants.find(c=>c.name==="SS58Prefix");if(n)try{let c=r(n.type)(n.value).value;typeof c=="number"&&(d=U(c))}catch{}let h=c=>{let v=r(c);return{shape:v.shape,decoder:v}},y=(0,A.createDecoder)(c=>{let v=A.u8.dec(c),b=e.pallets.find(a=>a.index===v);if(!b)throw new Error("Invalid Pallet");let m={value:{name:b.name,idx:v},input:te(c[0])},u=r(b.calls),i=u(c);if(i.codec!=="Enum")throw null;let o={value:{name:i.value.tag,idx:c[1]},input:te(c[1]),docs:i.docs};return{pallet:m,call:o,args:{value:i.value.value,shape:u.shape}}});return{buildDefinition:h,callDecoder:y}}; | ||
"use strict";var W=Object.create;var A=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var J=(e,r)=>{for(var s in r)A(e,s,{get:r[s],enumerable:!0})},D=(e,r,s,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of H(r))!N.call(e,n)&&n!==s&&A(e,n,{get:()=>r[n],enumerable:!(a=K(r,n))||a.enumerable});return e};var Q=(e,r,s)=>(s=e!=null?W(U(e)):{},D(r||!e||!e.__esModule?A(s,"default",{value:e,enumerable:!0}):s,e)),X=e=>D(A({},"__esModule",{value:!0}),e);var se={};J(se,{getChecksumBuilder:()=>ue,getDynamicBuilder:()=>$,getLookupFn:()=>C});module.exports=X(se);var C=e=>{let r=new Map,s=new Set,a=p=>t=>{let c=r.get(t);if(c)return c;if(s.has(t)){let l={id:t};return r.set(t,l),l}s.add(t);let m=p(t);return c=r.get(t),c?Object.assign(c,m):(c={id:t,...m},r.set(t,c)),s.delete(t),c},n=!0,o=a(p=>{let{def:t,path:c,params:m}=e[p];if(t.tag==="composite"){if(t.value.length===0)return{type:"void"};if(t.value.length===1)return n&&c.join(",")==="sp_core,crypto,AccountId32"?(n=!1,{type:"AccountId32"}):o(t.value[0].type);let l=!0,v={},i={};return t.value.forEach((d,u)=>{l=l&&!!d.name;let g=d.name||u;v[g]=o(d.type),i[g]=d.docs}),l?{type:"struct",value:v,innerDocs:i}:{type:"tuple",value:Object.values(v),innerDocs:Object.values(i)}}if(t.tag==="variant"){if(c.length===1&&c[0]==="Option"&&m.length===1&&m[0].name==="T"){let i=o(m[0].type);return i.type==="void"?{type:"primitive",value:"bool"}:{type:"option",value:i}}if(c.length===1&&c[0]==="Result"&&m.length===2&&m[0].name==="T"&&m[1].name==="E")return{type:"result",value:{ok:o(m[0].type),ko:o(m[1].type)}};if(t.value.length===0)return{type:"void"};let l={},v={};return t.value.forEach(i=>{let d=i.name;if(v[d]=i.docs,i.fields.length===0){l[d]={type:"void",idx:i.index};return}if(i.fields.length===1&&!i.fields[0].name){l[d]={type:"lookupEntry",value:o(i.fields[0].type),idx:i.index};return}let u=!0,g={},b={};i.fields.forEach((f,h)=>{u=u&&!!f.name;let V=f.name||h;g[V]=o(f.type),b[V]=f.docs}),l[d]=u?{type:"struct",value:g,innerDocs:b,idx:i.index}:{type:"tuple",value:Object.values(g),innerDocs:Object.values(b),idx:i.index}}),{type:"enum",value:l,innerDocs:v}}if(t.tag==="sequence")return{type:"sequence",value:o(t.value)};if(t.tag==="array"){let{len:l}=t.value,v=o(t.value.type);return l===0?{type:"void"}:l===1?v:{type:"array",value:v,len:t.value.len}}if(t.tag==="tuple"){if(t.value.length===0)return{type:"void"};if(t.value.length===1)return o(t.value[0]);let l=t.value.map(d=>o(d)),v=t.value.map(d=>e[d].docs);return l.every(d=>d.id===l[0].id)&&v.every(d=>d.length===0)?{type:"array",value:l[0],len:l.length}:{type:"tuple",value:l,innerDocs:v}}if(t.tag==="primitive")return{type:"primitive",value:t.value.tag};if(t.tag==="compact"){let l=o(t.value);return l.type==="void"?{type:"compact",isBig:null}:{type:"compact",isBig:Number(l.value.slice(1))>32}}return{type:t.tag}});return o};var y=Q(require("@polkadot-api/substrate-bindings"));var I=(e,r,s)=>(a,n,o,...p)=>{let{id:t}=a;if(n.has(t))return n.get(t);if(o.has(t)){let m=r(()=>n.get(t),a,...p);return n.set(t,m),m}o.add(t);let c=e(a,n,o,...p);return o.delete(t),n.has(t)&&(c=s(c,n.get(t),a,...p)),n.set(t,c),c};var M=require("@polkadot-api/utils"),Y=y.Bin(),Z=(e,r,s,a)=>{if(e.type==="primitive")return y[e.value];if(e.type==="void")return y._void;if(e.type==="AccountId32")return a;if(e.type==="compact")return y.compact;if(e.type==="bitSequence")return y.bitSequence;let n=i=>B(i,r,s,a),o=(i,d)=>{let u=n(i);return d?y.Vector(u,d):y.Vector(u)},p=i=>y.Tuple(...i.map(n)),t=i=>{let d=Object.fromEntries(Object.entries(i).map(([u,g])=>[u,n(g)]));return y.Struct(d)};if(e.type==="sequence"&&e.value.type==="primitive"&&e.value.value==="u8")return Y;if(e.type==="array")return e.value.type==="primitive"&&e.value.value==="u8"?y.Bin(e.len):o(e.value,e.len);if(e.type==="sequence")return o(e.value);if(e.type==="tuple")return p(e.value);if(e.type==="struct")return t(e.value);if(e.type==="option")return y.Option(n(e.value));if(e.type==="result")return y.Result(n(e.value.ok),n(e.value.ko));let c=Object.values(e.value).map(i=>i.type==="void"?y._void:i.type==="lookupEntry"?n(i.value):i.type==="tuple"?p(i.value):t(i.value)),m=Object.fromEntries(Object.keys(e.value).map((i,d)=>[i,c[d]])),l=Object.values(e.value).map(i=>i.idx);return l.every((i,d)=>i===d)?y.Variant(m):y.Variant(m,l)},B=I(Z,y.Self,e=>e),$=e=>{let r=e.lookup,s=C(r),a=y.AccountId(),n=new Map,o=u=>B(s(u),n,new Set,a),p=e.pallets.find(u=>u.name==="System")?.constants.find(u=>u.name==="SS58Prefix"),t;if(p)try{let u=o(p.type).dec(p.value);typeof u=="number"&&(t=u,a=y.AccountId(u))}catch{}let c=new Map,m=(u,g)=>{let b=c.get(u);b||c.set(u,b=y.Storage(u));let f=e.pallets.find(L=>L.name===u).storage.items.find(L=>L.name===g),h=(L,...O)=>{let j=b(...O);return{...j,len:L,fallback:f.modifier===1?j.dec(f.fallback):void 0}};if(f.type.tag==="plain")return h(0,g,o(f.type.value).dec);let{key:V,value:x,hashers:G}=f.type.value,F=o(x),R=G.map(L=>y[L.tag]),z=R.length===1?[[o(V),R[0]]]:s(V).value.map((L,O)=>[o(L.id),R[O]]);return h(R.length,g,F.dec,...z)},l=u=>u.type==="void"?y._void:u.type==="lookupEntry"?o(u.value.id):u.type==="tuple"?y.Tuple(...Object.values(u.value).map(g=>o(g.id))):y.Struct((0,M.mapObject)(u.value,g=>o(g.id))),v=(u,g)=>{let b=e.pallets.find(f=>f.name===u).constants.find(f=>f.name===g);return o(b.type)},i=u=>(g,b)=>{let f=e.pallets.find(x=>x.name===g),h=s(f[u]);if(h.type!=="enum")throw null;let V=h.value[b];return{location:[f.index,V.idx],codec:l(h.value[b])}},d=(u,g)=>{let b=e.apis.find(f=>f.name===u)?.methods.find(f=>f.name===g);if(!b)throw null;return{args:y.Tuple(...b.inputs.map(f=>o(f.type))),value:o(b.output)}};return{buildDefinition:o,buildStorage:m,buildEvent:i("events"),buildError:i("errors"),buildRuntimeCall:d,buildCall:i("calls"),buildConstant:v,ss58Prefix:t}};var q=require("@polkadot-api/substrate-bindings");var P=new TextEncoder,ee=P.encode.bind(P),k=e=>{let r=new Uint8Array(e.length*8),s=new DataView(r.buffer);for(let a=0;a<e.length;a++)s.setBigUint64(a*8,e[a]);return(0,q.h64)(r)},_=e=>k(e.map(r=>(0,q.h64)(ee(r)))),E={primitive:0n,vector:1n,tuple:2n,struct:3n,option:4n,result:5n,enum:6n,void:7n},S={undefined:0n,number:1n,string:2n,bigint:3n,boolean:4n,bitSequence:5n,byteSequence:6n,accountId:7n},te={bool:S.boolean,char:S.string,str:S.string,u8:S.number,u16:S.number,u32:S.number,u64:S.bigint,u128:S.bigint,u256:S.bigint,i8:S.number,i16:S.number,i32:S.number,i64:S.bigint,i128:S.bigint,i256:S.bigint},T=(e,r,s)=>{let a=Object.entries(r).sort(([p],[t])=>p.localeCompare(t)),n=_(a.map(([p])=>p)),o=k(a.map(([,p])=>s(p)));return k([e,n,o])},w=(e,r=new Map)=>{if(r.has(e.id))return r;switch(e.type){case"array":case"option":case"sequence":r.set(e.id,[e,new Set([e.value.id])]),w(e.value,r);break;case"enum":{let s=Object.values(e.value).flatMap(a=>a.type==="void"?[]:a.type==="lookupEntry"?a.value:a.type==="struct"?Object.values(a.value):a.value);r.set(e.id,[e,new Set(s.map(a=>a.id))]),s.forEach(a=>w(a,r));break}case"result":r.set(e.id,[e,new Set([e.value.ok.id,e.value.ko.id])]),w(e.value.ok,r),w(e.value.ko,r);break;case"struct":{let s=Object.values(e.value);r.set(e.id,[e,new Set(s.map(a=>a.id))]),s.forEach(a=>w(a,r));break}case"tuple":r.set(e.id,[e,new Set(e.value.map(s=>s.id))]),e.value.forEach(s=>w(s,r));break;default:r.set(e.id,[e,new Set])}return r},re=(e,r)=>{if(e.type==="primitive")return k([E.primitive,te[e.value]]);if(e.type==="void")return k([E.void]);if(e.type==="compact")return k([E.primitive,S[e.isBig||e.isBig===null?"bigint":"number"]]);if(e.type==="bitSequence")return k([E.primitive,S.bitSequence]);if(e.type==="AccountId32")return k([E.primitive,S.accountId]);if(e.type==="array"){let n=e.value;if(n.type==="primitive"&&n.value==="u8")return k([E.primitive,S.byteSequence,BigInt(e.len)]);let o=r(n);return k([E.vector,o,BigInt(e.len)])}if(e.type==="sequence"){let n=e.value;if(n.type==="primitive"&&n.value==="u8")return k([E.primitive,S.byteSequence]);let o=r(n);return k([E.vector,o])}let s=n=>k([E.tuple,...n.map(r)]),a=n=>T(E.struct,n,r);return e.type==="tuple"?s(e.value):e.type==="struct"?a(e.value):e.type==="option"?k([E.option,r(e.value)]):e.type==="result"?k([E.result,r(e.value.ok),r(e.value.ko)]):T(E.enum,e.value,n=>{if(n.type==="lookupEntry")return r(n.value);switch(n.type){case"void":return k([E.void]);case"tuple":return s(n.value);case"struct":return a(n.value)}})},ne=e=>{let r=new Map,s=0,a=[],n=[];function o(p){let t={index:s,lowLink:s,onStack:!0};r.set(p,t),s++,a.push(p);let c=e.get(p)[1];for(let m of c){let l=r.get(m);l?l.onStack&&(t.lowLink=Math.min(t.lowLink,l.index)):(o(m),t.lowLink=Math.min(t.lowLink,r.get(m).lowLink))}if(t.lowLink===t.index){let m=new Set,l=-1;do l=a.pop(),r.get(l).onStack=!1,m.add(l);while(l!==p);m.size>1&&n.push(m)}}for(let p of e.keys())r.has(p)||o(p);return n},oe=e=>{let r=new Set(e.map((n,o)=>o)),s=new Map(e.map((n,o)=>[o,new Set]));e.forEach((n,o)=>{e.slice(o+1).forEach((p,t)=>{let c=t+o+1;new Set([...n,...p]).size!==n.size+p.size&&(s.get(o).add(c),s.get(c).add(o))})});let a=[];for(;r.size;){let n=new Set,o=[r.values().next().value];for(;o.length;){let p=o.pop();if(!r.has(p))continue;r.delete(p),e[p].forEach(c=>n.add(Number(c))),s.get(p).forEach(c=>o.push(c))}a.push(n)}return a},ie=(e,r)=>{let s=o=>{let p=o.values().next().value,t=r.get(p)[0];return Array.from(w(t).keys())},a=new Array;function n(o){a.includes(o)||(e.filter(t=>t!==o&&s(o).some(c=>t.has(c))).forEach(t=>n(t)),a.includes(o))||a.push(o)}return e.forEach(o=>n(o)),a},ae=(e,r)=>{if(r.has(e.id))return r.get(e.id);let s=w(e),a=ne(s),n=oe(a),o=ie(n,s),p=(t,c,m=!1)=>{if(!m&&r.has(t.id))return r.get(t.id);let l=re(t,v=>p(v,c));return c(t.id,l),l};return o.forEach(t=>{t.forEach(c=>r.set(c,0n));for(let c=0;c<t.size;c++){let m=new Map;t.forEach(l=>p(s.get(l)[0],(v,i)=>{(t.has(v)?m:r).set(v,i)},!0)),Array.from(m.entries()).forEach(([l,v])=>r.set(l,v))}}),p(e,(t,c)=>r.set(t,c))},ue=e=>{let r=e.lookup,s=C(r),a=new Map,n=i=>ae(s(i),a),o=(i,d)=>{try{let u=e.pallets.find(V=>V.name===i).storage.items.find(V=>V.name===d);if(u.type.tag==="plain")return n(u.type.value);let{key:g,value:b}=u.type.value,f=n(b),h=n(g);return k([f,h])}catch{return null}},p=(i,d)=>{try{let u=e.apis.find(h=>h.name===i)?.methods.find(h=>h.name===d);if(!u)throw null;let g=_(u.inputs.map(h=>h.name)),b=k(u.inputs.map(h=>n(h.type))),f=n(u.output);return k([g,b,f])}catch{return null}},t=i=>{if(i.type==="void")return k([0n]);if(i.type==="tuple"){let d=Object.values(i.value).map(u=>n(u.id));return k([E.tuple,...d])}return T(E.struct,i.value,d=>n(d.id))},c=i=>T(E.tuple,i.value,d=>n(d.id)),m=i=>(d,u)=>{try{let g=e.pallets.find(h=>h.name===d),b=s(g[i]);if(n(b.id),b.type!=="enum")throw null;let f=b.value[u];return f.type==="lookupEntry"?n(f.value.id):t(f)}catch{return null}},l=(i,d)=>{try{let u=e.pallets.find(g=>g.name===i).constants.find(g=>g.name===d);return n(u.type)}catch{return null}},v=i=>(...d)=>i(...d)?.toString(32)??null;return{buildDefinition:v(n),buildRuntimeCall:v(p),buildStorage:v(o),buildCall:v(m("calls")),buildEvent:v(m("events")),buildError:v(m("errors")),buildConstant:v(l),buildComposite:v(t),buildNamedTuple:v(c),getAllGeneratedChecksums:()=>Array.from(a.values()).map(i=>i.toString(32))}}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@polkadot-api/metadata-builders", | ||
"version": "0.0.1-4720098dad2c69dafd379d4eb3a609154080c24d.1.0", | ||
"version": "0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0", | ||
"author": "Josep M Sobrepere (https://github.com/josepot)", | ||
@@ -43,5 +43,8 @@ "repository": { | ||
"dependencies": { | ||
"@polkadot-api/substrate-bindings": "0.0.1-4720098dad2c69dafd379d4eb3a609154080c24d.1.0", | ||
"@polkadot-api/utils": "0.0.1-4720098dad2c69dafd379d4eb3a609154080c24d.1.0" | ||
"@polkadot-api/substrate-bindings": "0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0", | ||
"@polkadot-api/utils": "0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0" | ||
}, | ||
"devDependencies": { | ||
"@polkadot-api/metadata-fixtures": "0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0" | ||
}, | ||
"scripts": { | ||
@@ -48,0 +51,0 @@ "build": "tsc --noEmit && tsup-node src/index.ts --clean --sourcemap --platform neutral --target=es2020 --format esm,cjs --dts && tsup-node src/index.ts --clean --sourcemap --platform neutral --target=es2020 --format cjs --dts --minify --out-dir dist/min", |
117
README.md
# @polkadot-api/metadata-builders | ||
This package has multiple functions that read a metadata object, denormalizes it, and builds other structures needed for different processes | ||
## getLookupFn | ||
```ts | ||
function getLookupFn( | ||
lookupData: Metadata["lookup"], | ||
): (id: number) => LookupEntry | ||
``` | ||
Given the lookup property of a metadata, returns a function that will give the `LookupEntry` for an id. | ||
The `LookupEntry` is a denormalized data structure for one entry in the metadata. It also "shortcuts" type references when those are pointers (composites or tuples of length 1). Essentially, it's a union of each of the different types that can be found in the lookup, mostly equivalent to something like: | ||
```ts | ||
type TerminalVar = | ||
| PrimitiveVar // u8, str, char, i128, etc. | ||
| CompactVar | ||
| BitSequenceVar | ||
| AccountId32 | ||
type ComposedVar = | ||
| TupleVar | ||
| StructVar | ||
| SequenceVar | ||
| ArrayVar | ||
| OptionVar | ||
| ResultVar | ||
| EnumVar | ||
type LookupEntry = TerminalVar | ComposedVar | ||
``` | ||
Where, for instance, a StructVar is of the shape | ||
```ts | ||
type StructVar = { | ||
type: "struct" | ||
value: Record<string, LookupEntry> | ||
} | ||
``` | ||
It's useful to get types referenced by storage calls, etc. | ||
## getDynamicBuilder | ||
```ts | ||
function getDynamicBuilder(lookupData: Metadata): { | ||
buildDefinition: (id: number) => Codec | ||
buildConstant: (pallet: string, name: string) => Codec | ||
buildEvent: (pallet: string, name: string) => VariantEntry | ||
buildError: (pallet: string, name: string) => VariantEntry | ||
buildCall: (pallet: string, name: string) => VariantEntry | ||
buildStorage: (pallet: string, entry: string) => StorageEntry | ||
buildRuntimeCall: (api: string, method: string) => RuntimeEntry | ||
} | ||
``` | ||
Generates all the codecs needed to SCALE encode or decode the data for any interaction with the chain. | ||
`buildDefinition` returns the codec for the type identified by the parameter `id` | ||
`buildConstant` returns the codec for the requested constant (equivalent as calling `buildDefinition` with the type id of that constant) | ||
`buildEvent`, `buildError` and `buildCall` return an object with the codec, and the indices of the pallet and entry within the metadata: | ||
```ts | ||
interface VariantEntry { | ||
location: [number, number] // [palletIdx, entryIdx], | ||
codec: Codec | ||
} | ||
``` | ||
`buildStorage` creates all the encoders/decoders needed to encode a storage call and decode its result: | ||
```ts | ||
interface StorageEntry { | ||
// Encodes the arguments of the storage call. | ||
enc: (...args: any[]) => string | ||
// Decodes the result from the storage call. | ||
dec: (value: string) => any | ||
// Decodes the arguments of the storage call | ||
keyDecoder: (value: string) => any[] | ||
// Expected number of arguments | ||
len: number | ||
// Decoded fallback value as defined in the metadata entry | ||
fallback: unknown | ||
} | ||
``` | ||
Similarly, `buildRuntimeCall` returns the codecs for both encoding the arguments of the runtime call, and the codec for decoding the result | ||
```ts | ||
interface RuntimeEntry { | ||
args: Codec<any[]> | ||
value: Codec<any> | ||
} | ||
``` | ||
## getChecksumBuilder | ||
```ts | ||
function getChecksumBuilder(metadata: Metadata): { | ||
buildDefinition: (id: number) => string | null | ||
buildRuntimeCall: (api: string, method: string) => string | null | ||
buildStorage: (pallet: string, entry: string) => string | null | ||
buildCall: (pallet: string, name: string) => string | null | ||
buildEvent: (pallet: string, name: string) => string | null | ||
buildError: (pallet: string, name: string) => string | null | ||
buildConstant: (pallet: string, constantName: string) => string | null | ||
} | ||
``` | ||
Generates the checksums for the different components defined in the metadata. | ||
`buildDefinition` builds the checksum of one of the types in the lookup. The rest of the methods build the checksum for each of the interfaces of the chain. |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
119
246847
1
2067
+ Added@polkadot-api/substrate-bindings@0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0(transitive)
+ Added@polkadot-api/utils@0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0(transitive)
- Removed@polkadot-api/substrate-bindings@0.0.1-4720098dad2c69dafd379d4eb3a609154080c24d.1.0(transitive)
- Removed@polkadot-api/utils@0.0.1-4720098dad2c69dafd379d4eb3a609154080c24d.1.0(transitive)
Updated@polkadot-api/substrate-bindings@0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0
Updated@polkadot-api/utils@0.0.1-477e108b3b2a58cdd1a50b7e8d127fdf50aeed20.1.0