Kit
Type aliases

Codec

Codec<TFrom, TTo> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>

An object that can encode and decode a value to and from a byte array.

A Codec can be either:

Type Parameters

Type ParameterDefault type
TFrom-
TTo extends TFromTFrom

Example

const codec: Codec<string>;
const bytes = codec.encode('hello');
const value = codec.decode(bytes); // 'hello'

Remarks

For convenience, codecs can encode looser types than they decode. That is, type TFrom can be a superset of type TTo. For instance, a Codec<bigint | number, bigint> can encode both bigint and number values, but will always decode to a bigint.

const codec: Codec<bigint | number, bigint>;
const bytes = codec.encode(42);
const value = codec.decode(bytes); // 42n

It is worth noting that codecs are the union of encoders and decoders. This means that a Codec<TFrom, TTo> can be combined from an Encoder<TFrom> and a Decoder<TTo> using the combineCodec function. This is particularly useful for library authors who want to expose all three types of objects to their users.

const encoder: Encoder<bigint | number>;
const decoder: Decoder<bigint>;
const codec: Codec<bigint | number, bigint> = combineCodec(encoder, decoder);

Aside from combining encoders and decoders, codecs can also be created from scratch using the createCodec function but it is more common to compose multiple codecs together using the various helpers of the @solana/codecs package.

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

import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs';
 
type Person = { name: string; age: number };
const getPersonCodec = (): Codec<Person> =>
    getStructCodec([
        ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],
        ['age', getU32Codec()],
    ]);

Note that composed Codec types are clever enough to understand whether they are fixed-size or variable-size. In the example above, getU32Codec() is a fixed-size codec, while addCodecSizePrefix(getUtf8Codec(), getU32Codec()) is a variable-size codec. This makes the final Person codec a variable-size codec.

See

On this page