addSelfFetchFunctions

function addSelfFetchFunctions<TCodec>(
    client,
    codec,
): SelfFetchFunctions<InferTFrom<TCodec>, InferTTo<TCodec>> & TCodec;

Adds self-fetching methods to a codec for retrieving and decoding accounts.

This function augments the provided codec with methods that allow it to fetch accounts from the network and decode them in one step. It enables a fluent API where you can call methods like .fetch() directly on the codec.

Type Parameters

Type ParameterDescription
TCodec extends AnyObjectCodecThe codec type being augmented.

Parameters

ParameterTypeDescription
clientClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>A client that provides RPC access for fetching accounts.
codecTCodecThe codec to augment with self-fetch methods.

Returns

SelfFetchFunctions<InferTFrom<TCodec>, InferTTo<TCodec>> & TCodec

The codec augmented with SelfFetchFunctions methods.

Examples

Adding self-fetch functions to an account codec.

import { addSelfFetchFunctions } from '@solana/program-client-core';
 
const myAccountCodec = addSelfFetchFunctions(client, getMyAccountCodec());
 
// Fetch and decode an account in one step.
const account = await myAccountCodec.fetch(accountAddress);

Handling accounts that may not exist.

const myAccountCodec = addSelfFetchFunctions(client, getMyAccountCodec());
 
const maybeAccount = await myAccountCodec.fetchMaybe(accountAddress);
if (maybeAccount.exists) {
    console.log('Account data:', maybeAccount.data);
} else {
    console.log(`Account ${maybeAccount.address} does not exist`);
}

Fetching multiple accounts at once.

const myAccountCodec = addSelfFetchFunctions(client, getMyAccountCodec());
 
// Throws if any account does not exist.
const accounts = await myAccountCodec.fetchAll([addressA, addressB, addressC]);
 
// Returns MaybeAccount for each, allowing some to not exist.
const maybeAccounts = await myAccountCodec.fetchAllMaybe([addressA, addressB]);

See

SelfFetchFunctions

On this page