import type { AccountsCoder, Idl } from "@coral-xyz/anchor"; import { BorshAccountsCoder } from "@coral-xyz/anchor"; import camelCase from "lodash.camelcase"; /** * Parsers associated with an IDL. */ export type AccountParsers = { [K in keyof M]: (data: Buffer) => M[K]; }; /** * Creates parsers for accounts. * * This is intended to be called once at initialization. * * @param idl The IDL. */ export const generateAccountParsers = >( idl: Idl, ): AccountParsers => { const coder = new BorshAccountsCoder(idl); return generateAccountParsersFromCoder( idl.accounts?.map((a) => a.name), coder, ); }; /** * Creates parsers for accounts. * * This is intended to be called once at initialization. * * @param idl The IDL. */ export const generateAccountParsersFromCoder = ( accountNames: string[] | undefined, coder: AccountsCoder, ): AccountParsers => { return (accountNames ?? []).reduce((parsers, account) => { parsers[camelCase(account) as keyof M] = (data: Buffer) => coder.decode(account, data); return parsers; }, {} as AccountParsers); };