import type { AccountsCoder } from "@coral-xyz/anchor"; import { BorshAccountsCoder } from "@coral-xyz/anchor"; import type { IdlTypeDef } from "@coral-xyz/anchor/dist/esm/idl.js"; import type { ProgramAccountParser, PublicKey } from "@saberhq/solana-contrib"; import camelCase from "lodash.camelcase"; /** * Account information. */ export interface AnchorAccount extends ProgramAccountParser { /** * {@link IdlTypeDef}. */ idl: IdlTypeDef; /** * Size of the account in bytes */ size: number; /** * The discriminator. */ discriminator: Buffer; /** * Encodes the value. */ encode: (value: T) => Promise; } /** * {@link ProgramAccountParser}s associated with an IDL. */ export type AnchorAccountMap = { [K in keyof M]: AnchorAccount; }; /** * Generates the metadata of accounts. * * This is intended to be called once at initialization. */ export const generateAnchorAccounts = ( programID: PublicKey, accounts: IdlTypeDef[], coder: AccountsCoder, ): AnchorAccountMap => { const parsers: Partial> = {}; accounts.forEach((account) => { parsers[camelCase(account.name) as keyof M] = { programID, name: account.name, encode: (value) => coder.encode(account.name, value), parse: (data: Buffer) => coder.decode(account.name, data), idl: account, size: coder.size(account), discriminator: BorshAccountsCoder.accountDiscriminator(account.name), }; }); return parsers as AnchorAccountMap; };