2021-02-02 10:53:24 +08:00
|
|
|
import {Buffer} from 'buffer';
|
2019-12-23 11:46:49 -07:00
|
|
|
import * as BufferLayout from 'buffer-layout';
|
|
|
|
|
|
|
|
import * as Layout from './layout';
|
|
|
|
|
|
|
|
/**
|
2021-03-15 11:01:35 +08:00
|
|
|
* @internal
|
2019-12-23 11:46:49 -07:00
|
|
|
*/
|
2021-03-15 11:01:35 +08:00
|
|
|
export type InstructionType = {
|
2021-03-31 18:48:41 +08:00
|
|
|
/** The Instruction index (from solana upstream program) */
|
2021-03-15 11:01:35 +08:00
|
|
|
index: number;
|
2021-03-31 18:48:41 +08:00
|
|
|
/** The BufferLayout to use to build data */
|
2021-03-15 11:01:35 +08:00
|
|
|
layout: typeof BufferLayout;
|
|
|
|
};
|
2019-12-23 11:46:49 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Populate a buffer of instruction data using an InstructionType
|
2021-03-15 11:01:35 +08:00
|
|
|
* @internal
|
2019-12-23 11:46:49 -07:00
|
|
|
*/
|
2021-03-15 11:01:35 +08:00
|
|
|
export function encodeData(type: InstructionType, fields?: any): Buffer {
|
2019-12-23 11:46:49 -07:00
|
|
|
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;
|
|
|
|
}
|
2020-03-02 23:58:10 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Decode instruction data buffer using an InstructionType
|
2021-03-15 11:01:35 +08:00
|
|
|
* @internal
|
2020-03-02 23:58:10 +08:00
|
|
|
*/
|
2021-03-15 11:01:35 +08:00
|
|
|
export function decodeData(type: InstructionType, buffer: Buffer): any {
|
2020-03-02 23:58:10 +08:00
|
|
|
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;
|
|
|
|
}
|