refactor: use buffer-layout to clean up buffer encoding

This commit is contained in:
Michael Vines
2018-10-06 11:13:58 -07:00
parent a596e99b4a
commit 17b73306fe
7 changed files with 137 additions and 85 deletions

View File

@ -1,9 +1,10 @@
// @flow
import assert from 'assert';
import * as BufferLayout from 'buffer-layout';
import {Transaction} from './transaction';
import {PublicKey} from './publickey';
import * as Layout from './layout';
/**
* Factory class for transactions to interact with the System program
@ -26,23 +27,24 @@ export class SystemProgram {
space: number,
programId: PublicKey
): Transaction {
const userdata = Buffer.alloc(4 + 8 + 8 + 1 + 32);
let pos = 0;
userdata.writeUInt32LE(0, pos); // Create Account instruction
pos += 4;
const userdataLayout = BufferLayout.struct([
BufferLayout.u32('instruction'),
BufferLayout.ns64('tokens'),
BufferLayout.ns64('space'),
Layout.publicKey('programId'),
]);
userdata.writeUInt32LE(tokens, pos); // tokens as i64
pos += 8;
userdata.writeUInt32LE(space, pos); // space as u64
pos += 8;
const programIdBytes = programId.toBuffer();
programIdBytes.copy(userdata, pos);
pos += programIdBytes.length;
assert(pos <= userdata.length);
const userdata = Buffer.alloc(userdataLayout.span);
userdataLayout.encode(
{
instruction: 0, // Create Account instruction
tokens,
space,
programId: programId.toBuffer(),
},
userdata,
);
return new Transaction({
fee: 0,
@ -56,15 +58,19 @@ export class SystemProgram {
* Generate a Transaction that moves tokens from one account to another
*/
static move(from: PublicKey, to: PublicKey, amount: number): Transaction {
const userdata = Buffer.alloc(4 + 8);
let pos = 0;
userdata.writeUInt32LE(2, pos); // Move instruction
pos += 4;
const userdataLayout = BufferLayout.struct([
BufferLayout.u32('instruction'),
BufferLayout.ns64('amount'),
]);
userdata.writeUInt32LE(amount, pos); // amount as u64
pos += 8;
assert(pos === userdata.length);
const userdata = Buffer.alloc(userdataLayout.span);
userdataLayout.encode(
{
instruction: 2, // Move instruction
amount,
},
userdata,
);
return new Transaction({
fee: 0,
@ -78,17 +84,19 @@ export class SystemProgram {
* Generate a Transaction that assigns an account to a program
*/
static assign(from: PublicKey, programId: PublicKey): Transaction {
const userdata = Buffer.alloc(4 + 32);
let pos = 0;
const userdataLayout = BufferLayout.struct([
BufferLayout.u32('instruction'),
Layout.publicKey('programId'),
]);
userdata.writeUInt32LE(1, pos); // Assign instruction
pos += 4;
const programIdBytes = programId.toBuffer();
programIdBytes.copy(userdata, pos);
pos += programIdBytes.length;
assert(pos === userdata.length);
const userdata = Buffer.alloc(userdataLayout.span);
userdataLayout.encode(
{
instruction: 1, // Assign instruction
programId: programId.toBuffer(),
},
userdata,
);
return new Transaction({
fee: 0,