ts: Allow adding types for AccountsCoder names (#764)

This commit is contained in:
Ian Macalinao 2021-09-19 16:12:30 -07:00 committed by GitHub
parent 9426918c4b
commit 296f4b6b2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 11 deletions

View File

@ -11,28 +11,25 @@ export const ACCOUNT_DISCRIMINATOR_SIZE = 8;
/** /**
* Encodes and decodes account objects. * Encodes and decodes account objects.
*/ */
export class AccountsCoder { export class AccountsCoder<A extends string = string> {
/** /**
* Maps account type identifier to a layout. * Maps account type identifier to a layout.
*/ */
private accountLayouts: Map<string, Layout>; private accountLayouts: Map<A, Layout>;
public constructor(idl: Idl) { public constructor(idl: Idl) {
if (idl.accounts === undefined) { if (idl.accounts === undefined) {
this.accountLayouts = new Map(); this.accountLayouts = new Map();
return; return;
} }
const layouts: [string, Layout][] = idl.accounts.map((acc) => { const layouts: [A, Layout][] = idl.accounts.map((acc) => {
return [acc.name, IdlCoder.typeDefLayout(acc, idl.types)]; return [acc.name as A, IdlCoder.typeDefLayout(acc, idl.types)];
}); });
this.accountLayouts = new Map(layouts); this.accountLayouts = new Map(layouts);
} }
public async encode<T = any>( public async encode<T = any>(accountName: A, account: T): Promise<Buffer> {
accountName: string,
account: T
): Promise<Buffer> {
const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer. const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer.
const layout = this.accountLayouts.get(accountName); const layout = this.accountLayouts.get(accountName);
if (!layout) { if (!layout) {
@ -44,7 +41,7 @@ export class AccountsCoder {
return Buffer.concat([discriminator, accountData]); return Buffer.concat([discriminator, accountData]);
} }
public decode<T = any>(accountName: string, ix: Buffer): T { public decode<T = any>(accountName: A, ix: Buffer): T {
// Chop off the discriminator before decoding. // Chop off the discriminator before decoding.
const data = ix.slice(8); const data = ix.slice(8);
const layout = this.accountLayouts.get(accountName); const layout = this.accountLayouts.get(accountName);

View File

@ -20,7 +20,7 @@ export { StateCoder, stateDiscriminator } from "./state";
/** /**
* Coder provides a facade for encoding and decoding all IDL related objects. * Coder provides a facade for encoding and decoding all IDL related objects.
*/ */
export default class Coder { export default class Coder<A extends string = string> {
/** /**
* Instruction coder. * Instruction coder.
*/ */
@ -29,7 +29,7 @@ export default class Coder {
/** /**
* Account coder. * Account coder.
*/ */
readonly accounts: AccountsCoder; readonly accounts: AccountsCoder<A>;
/** /**
* Types coder. * Types coder.