solana/web3.js/src/instruction.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

import {Buffer} from 'buffer';
import * as BufferLayout from '@solana/buffer-layout';
import * as Layout from './layout';
/**
2021-03-14 20:01:35 -07:00
* @internal
*/
2021-03-14 20:01:35 -07:00
export type InstructionType = {
2021-03-31 03:48:41 -07:00
/** The Instruction index (from solana upstream program) */
2021-03-14 20:01:35 -07:00
index: number;
2021-03-31 03:48:41 -07:00
/** The BufferLayout to use to build data */
layout: BufferLayout.Layout;
2021-03-14 20:01:35 -07:00
};
/**
* Populate a buffer of instruction data using an InstructionType
2021-03-14 20:01:35 -07:00
* @internal
*/
2021-03-14 20:01:35 -07:00
export function encodeData(type: InstructionType, fields?: any): Buffer {
const allocLength =
type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);
const data = Buffer.alloc(allocLength);
const layoutFields = Object.assign({instruction: type.index}, fields);
type.layout.encode(layoutFields, data);
return data;
}
/**
* Decode instruction data buffer using an InstructionType
2021-03-14 20:01:35 -07:00
* @internal
*/
2021-03-14 20:01:35 -07:00
export function decodeData(type: InstructionType, buffer: Buffer): any {
let data;
try {
data = type.layout.decode(buffer);
} catch (err) {
throw new Error('invalid instruction; ' + err);
}
if (data.instruction !== type.index) {
throw new Error(
`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`,
);
}
return data;
}