96 lines
2.5 KiB
TypeScript
96 lines
2.5 KiB
TypeScript
import {
|
|
getDynamicBuilder,
|
|
MetadataLookup,
|
|
} from "@polkadot-api/metadata-builders"
|
|
import {
|
|
_void,
|
|
AccountId,
|
|
Bytes,
|
|
compact,
|
|
enhanceDecoder,
|
|
Enum,
|
|
SS58String,
|
|
Struct,
|
|
u8,
|
|
Variant,
|
|
} from "@polkadot-api/substrate-bindings"
|
|
import { Codec } from "polkadot-api"
|
|
|
|
export const createExtrinsicCodec = (lookup: MetadataLookup) => {
|
|
const dynamicBuilder = getDynamicBuilder(lookup)
|
|
|
|
// https://spec.polkadot.network/id-extrinsics#id-extrinsics-body
|
|
const extrinsicHeader = enhanceDecoder(u8.dec, (value) => ({
|
|
signed: (value & 0x80) > 0,
|
|
version: value & 0x7f,
|
|
}))
|
|
const sender =
|
|
"address" in lookup.metadata.extrinsic
|
|
? (dynamicBuilder.buildDefinition(
|
|
lookup.metadata.extrinsic.address,
|
|
) as Codec<
|
|
// TODO Assume MultiAddress, but can be anything really :/
|
|
Enum<{
|
|
Id: SS58String
|
|
}>
|
|
>)
|
|
: AccountId()
|
|
const v14Signature = Variant({
|
|
Ed25519: Bytes(64),
|
|
Sr25519: Bytes(64),
|
|
Ecdsa: Bytes(65),
|
|
})
|
|
const signature =
|
|
"signature" in lookup.metadata.extrinsic
|
|
? (dynamicBuilder.buildDefinition(
|
|
lookup.metadata.extrinsic.signature,
|
|
) as typeof v14Signature)
|
|
: v14Signature
|
|
const extra =
|
|
"extra" in lookup.metadata.extrinsic
|
|
? (dynamicBuilder.buildDefinition(
|
|
lookup.metadata.extrinsic.extra,
|
|
) as Codec<unknown[]>)
|
|
: Struct({
|
|
mortality: Variant({
|
|
Immortal: _void,
|
|
...Object.fromEntries(
|
|
new Array(255).fill(0).map((_, i) => [`Mortal${i}`, u8]),
|
|
),
|
|
}),
|
|
nonce: compact,
|
|
tip: compact,
|
|
})
|
|
const call = dynamicBuilder.buildDefinition(
|
|
"call" in lookup.metadata.extrinsic
|
|
? lookup.metadata.extrinsic.call
|
|
: lookup.metadata.extrinsic.type,
|
|
) as Codec<{ type: string; value: { type: string; value: unknown } }>
|
|
const signedExtrinsicV4 = Struct({
|
|
sender,
|
|
signature,
|
|
extra,
|
|
call,
|
|
})
|
|
|
|
// Externally, it's an opaque
|
|
return enhanceDecoder(Bytes().dec, (bytes: Uint8Array) => {
|
|
const header = extrinsicHeader(bytes)
|
|
|
|
return header.signed
|
|
? {
|
|
version: header.version,
|
|
signed: true as const,
|
|
...signedExtrinsicV4.dec(bytes.slice(1)),
|
|
}
|
|
: {
|
|
version: header.version,
|
|
signed: false as const,
|
|
call: call.dec(bytes.slice(1)),
|
|
}
|
|
})
|
|
}
|
|
export type DecodedExtrinsic = ReturnType<
|
|
ReturnType<typeof createExtrinsicCodec>
|
|
>
|