fix: add TypeScript buffer type to instruction.ts

This commit is contained in:
steveluscher 2022-03-23 21:08:10 -07:00 committed by Steven Luscher
parent 023fc028bc
commit b516a25132
1 changed files with 15 additions and 5 deletions

View File

@ -3,21 +3,28 @@ import * as BufferLayout from '@solana/buffer-layout';
import * as Layout from './layout';
export interface IInstructionInputData {
readonly instruction: number;
}
/**
* @internal
*/
export type InstructionType = {
export type InstructionType<TInputData extends IInstructionInputData> = {
/** The Instruction index (from solana upstream program) */
index: number;
/** The BufferLayout to use to build data */
layout: BufferLayout.Layout;
layout: BufferLayout.Layout<TInputData>;
};
/**
* Populate a buffer of instruction data using an InstructionType
* @internal
*/
export function encodeData(type: InstructionType, fields?: any): Buffer {
export function encodeData<TInputData extends IInstructionInputData>(
type: InstructionType<TInputData>,
fields?: any,
): Buffer {
const allocLength =
type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);
const data = Buffer.alloc(allocLength);
@ -30,8 +37,11 @@ export function encodeData(type: InstructionType, fields?: any): Buffer {
* Decode instruction data buffer using an InstructionType
* @internal
*/
export function decodeData(type: InstructionType, buffer: Buffer): any {
let data;
export function decodeData<TInputData extends IInstructionInputData>(
type: InstructionType<TInputData>,
buffer: Buffer,
): TInputData {
let data: TInputData;
try {
data = type.layout.decode(buffer);
} catch (err) {