|
@@ -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) => {
|
|
|
|
- return [acc.name, IdlCoder.typeDefLayout(acc, idl.types)];
|
|
|
|
|
|
+ const layouts: [A, Layout][] = idl.accounts.map((acc) => {
|
|
|
|
+ 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>(
|
|
|
|
- accountName: string,
|
|
|
|
- account: T
|
|
|
|
- ): Promise<Buffer> {
|
|
|
|
|
|
+ public async encode<T = any>(accountName: A, 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);
|