Kit
Type aliases

Encoder

Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>

An object that can encode a value of type TFrom into a ReadonlyUint8Array.

An Encoder can be either:

Type Parameters

Type ParameterDescription
TFromThe type of the value to encode.

Examples

Encoding a value into a new byte array.

const encoder: Encoder<string>;
const bytes = encoder.encode('hello');

Writing the encoded value into an existing byte array.

const encoder: Encoder<string>;
const bytes = new Uint8Array(100);
const nextOffset = encoder.write('hello', bytes, 20);

Remarks

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

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

import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs';
 
type Person = { name: string; age: number };
const getPersonEncoder = (): Encoder<Person> =>
    getStructEncoder([
        ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],
        ['age', getU32Encoder()],
    ]);

Note that composed Encoder types are clever enough to understand whether they are fixed-size or variable-size. In the example above, getU32Encoder() is a fixed-size encoder, while addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()) is a variable-size encoder. This makes the final Person encoder a variable-size encoder.

See

On this page