Kit
Type aliases

Decoder

Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>

An object that can decode a byte array into a value of type TTo.

An Decoder can be either:

Type Parameters

Type ParameterDescription
TToThe type of the decoded value.

Examples

Getting the decoded value from a byte array.

const decoder: Decoder<string>;
const value = decoder.decode(bytes);

Reading the decoded value from a byte array at a specific offset and getting the offset of the next byte to read.

const decoder: Decoder<string>;
const [value, nextOffset] = decoder.read('hello', bytes, 20);

Remarks

You may create Decoders manually using the createDecoder function but it is more common to compose multiple Decoders together using the various helpers of the @solana/codecs package.

For instance, here's how you might create an Decoder for a Person object type that contains a name string and an age number:

import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs';
 
type Person = { name: string; age: number };
const getPersonDecoder = (): Decoder<Person> =>
    getStructDecoder([
        ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],
        ['age', getU32Decoder()],
    ]);

Note that composed Decoder types are clever enough to understand whether they are fixed-size or variable-size. In the example above, getU32Decoder() is a fixed-size decoder, while addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()) is a variable-size decoder. This makes the final Person decoder a variable-size decoder.

See

On this page