chore: migrate to typescript

This commit is contained in:
Justin Starry 2021-03-15 11:01:35 +08:00 committed by Justin Starry
parent 3eb9f7b3eb
commit f912c63b22
51 changed files with 948 additions and 980 deletions

View File

@ -1,6 +1,5 @@
// @flow import * as nacl from 'tweetnacl';
import nacl from 'tweetnacl'; import type {SignKeyPair as KeyPair} from 'tweetnacl';
import type {KeyPair} from 'tweetnacl';
import {toBuffer} from './util/to-buffer'; import {toBuffer} from './util/to-buffer';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
@ -9,6 +8,7 @@ import {PublicKey} from './publickey';
* An account key pair (public and secret keys). * An account key pair (public and secret keys).
*/ */
export class Account { export class Account {
/** @internal */
_keypair: KeyPair; _keypair: KeyPair;
/** /**

View File

@ -1,5 +1,3 @@
// @flow
import http from 'http'; import http from 'http';
import https from 'https'; import https from 'https';
@ -8,7 +6,7 @@ export const DESTROY_TIMEOUT_MS = 5000;
export class AgentManager { export class AgentManager {
_agent: http.Agent | https.Agent; _agent: http.Agent | https.Agent;
_activeRequests = 0; _activeRequests = 0;
_destroyTimeout: TimeoutID | null = null; _destroyTimeout: ReturnType<typeof setTimeout> | null = null;
_useHttps: boolean; _useHttps: boolean;
static _newAgent(useHttps: boolean): http.Agent | https.Agent { static _newAgent(useHttps: boolean): http.Agent | https.Agent {
@ -27,8 +25,10 @@ export class AgentManager {
requestStart(): http.Agent | https.Agent { requestStart(): http.Agent | https.Agent {
this._activeRequests++; this._activeRequests++;
if (this._destroyTimeout !== null) {
clearTimeout(this._destroyTimeout); clearTimeout(this._destroyTimeout);
this._destroyTimeout = null; this._destroyTimeout = null;
}
return this._agent; return this._agent;
} }

View File

@ -1,6 +0,0 @@
// @flow
/**
* @typedef {string} Blockhash
*/
export type Blockhash = string;

4
web3.js/src/blockhash.ts Normal file
View File

@ -0,0 +1,4 @@
/**
* Blockhash as Base58 string.
*/
export type Blockhash = string;

View File

@ -1,5 +1,3 @@
// @flow
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
export const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey( export const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey(

View File

@ -1,5 +1,3 @@
// @flow
import {Account} from './account'; import {Account} from './account';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
import {Loader} from './loader'; import {Loader} from './loader';

1
web3.js/src/buffer-layout.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module 'buffer-layout';

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,17 @@
// @flow // @ts-ignore
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
/** /**
* https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11 * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11
* *
* @private * @internal
*/ */
export const FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature'); export const FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');
/** /**
* @typedef {Object} FeeCalculator * Calculator for transaction fees.
* @property {number} lamportsPerSignature lamports Cost in lamports to validate a signature
*/ */
export type FeeCalculator = { export interface FeeCalculator {
lamportsPerSignature: number, /** Cost in lamports to validate a signature. */
}; lamportsPerSignature: number;
}

View File

@ -1,42 +0,0 @@
// @flow
export {Account} from './account';
export {BPF_LOADER_DEPRECATED_PROGRAM_ID} from './bpf-loader-deprecated';
export {BpfLoader, BPF_LOADER_PROGRAM_ID} from './bpf-loader';
export {Connection} from './connection';
export {Loader} from './loader';
export {Message} from './message';
export {NonceAccount, NONCE_ACCOUNT_LENGTH} from './nonce-account';
export {MAX_SEED_LENGTH, PublicKey} from './publickey';
export {
STAKE_CONFIG_ID,
Authorized,
Lockup,
StakeAuthorizationLayout,
StakeInstruction,
STAKE_INSTRUCTION_LAYOUTS,
StakeProgram,
} from './stake-program';
export {
SystemInstruction,
SystemProgram,
SYSTEM_INSTRUCTION_LAYOUTS,
} from './system-program';
export {Secp256k1Program} from './secp256k1-program';
export {Transaction, TransactionInstruction} from './transaction';
export {VALIDATOR_INFO_KEY, ValidatorInfo} from './validator-info';
export {VOTE_PROGRAM_ID, VoteAccount} from './vote-account';
export {
SYSVAR_CLOCK_PUBKEY,
SYSVAR_RENT_PUBKEY,
SYSVAR_REWARDS_PUBKEY,
SYSVAR_STAKE_HISTORY_PUBKEY,
SYSVAR_INSTRUCTIONS_PUBKEY,
} from './sysvar';
export {sendAndConfirmTransaction} from './util/send-and-confirm-transaction';
export {sendAndConfirmRawTransaction} from './util/send-and-confirm-raw-transaction';
export {clusterApiUrl} from './util/cluster';
/**
* There are 1-billion lamports in one SOL
*/
export const LAMPORTS_PER_SOL = 1000000000;

25
web3.js/src/index.ts Normal file
View File

@ -0,0 +1,25 @@
export * from './account';
export * from './blockhash';
export * from './bpf-loader-deprecated';
export * from './bpf-loader';
export * from './connection';
export * from './fee-calculator';
export * from './loader';
export * from './message';
export * from './nonce-account';
export * from './publickey';
export * from './stake-program';
export * from './system-program';
export * from './secp256k1-program';
export * from './transaction';
export * from './validator-info';
export * from './vote-account';
export * from './sysvar';
export * from './util/send-and-confirm-transaction';
export * from './util/send-and-confirm-raw-transaction';
export * from './util/cluster';
/**
* There are 1-billion lamports in one SOL
*/
export const LAMPORTS_PER_SOL = 1000000000;

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
@ -9,16 +7,18 @@ import * as Layout from './layout';
* @typedef {Object} InstructionType * @typedef {Object} InstructionType
* @property (index} The Instruction index (from solana upstream program) * @property (index} The Instruction index (from solana upstream program)
* @property (BufferLayout} The BufferLayout to use to build data * @property (BufferLayout} The BufferLayout to use to build data
* @internal
*/ */
export type InstructionType = {| export type InstructionType = {
index: number, index: number;
layout: typeof BufferLayout, layout: typeof BufferLayout;
|}; };
/** /**
* Populate a buffer of instruction data using an InstructionType * Populate a buffer of instruction data using an InstructionType
* @internal
*/ */
export function encodeData(type: InstructionType, fields: Object): Buffer { export function encodeData(type: InstructionType, fields?: any): Buffer {
const allocLength = const allocLength =
type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields); type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);
const data = Buffer.alloc(allocLength); const data = Buffer.alloc(allocLength);
@ -29,8 +29,9 @@ export function encodeData(type: InstructionType, fields: Object): Buffer {
/** /**
* Decode instruction data buffer using an InstructionType * Decode instruction data buffer using an InstructionType
* @internal
*/ */
export function decodeData(type: InstructionType, buffer: Buffer): Object { export function decodeData(type: InstructionType, buffer: Buffer): any {
let data; let data;
try { try {
data = type.layout.decode(buffer); data = type.layout.decode(buffer);

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
@ -32,19 +30,19 @@ export const rustString = (property: string = 'string') => {
const _decode = rsl.decode.bind(rsl); const _decode = rsl.decode.bind(rsl);
const _encode = rsl.encode.bind(rsl); const _encode = rsl.encode.bind(rsl);
rsl.decode = (buffer, offset) => { rsl.decode = (buffer: any, offset: any) => {
const data = _decode(buffer, offset); const data = _decode(buffer, offset);
return data.chars.toString('utf8'); return data.chars.toString('utf8');
}; };
rsl.encode = (str, buffer, offset) => { rsl.encode = (str: any, buffer: any, offset: any) => {
const data = { const data = {
chars: Buffer.from(str, 'utf8'), chars: Buffer.from(str, 'utf8'),
}; };
return _encode(data, buffer, offset); return _encode(data, buffer, offset);
}; };
rsl.alloc = str => { rsl.alloc = (str: any) => {
return ( return (
BufferLayout.u32().span + BufferLayout.u32().span +
BufferLayout.u32().span + BufferLayout.u32().span +
@ -79,9 +77,9 @@ export const lockup = (property: string = 'lockup') => {
); );
}; };
export function getAlloc(type: Object, fields: Object): number { export function getAlloc(type: any, fields: any): number {
let alloc = 0; let alloc = 0;
type.layout.fields.forEach(item => { type.layout.fields.forEach((item: any) => {
if (item.span >= 0) { if (item.span >= 0) {
alloc += item.span; alloc += item.span;
} else if (typeof item.alloc === 'function') { } else if (typeof item.alloc === 'function') {

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
@ -16,6 +14,11 @@ import {SystemProgram} from './system-program';
* Program loader interface * Program loader interface
*/ */
export class Loader { export class Loader {
/**
* @internal
*/
constructor() {}
/** /**
* Amount of program data placed in each load Transaction * Amount of program data placed in each load Transaction
*/ */

View File

@ -1,5 +1,3 @@
// @flow
import bs58 from 'bs58'; import bs58 from 'bs58';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
@ -20,9 +18,9 @@ import * as shortvec from './util/shortvec-encoding';
* @property {number} numReadonlyUnsignedAccounts The last `numReadonlySignedAccounts` of the unsigned keys are read-only accounts * @property {number} numReadonlyUnsignedAccounts The last `numReadonlySignedAccounts` of the unsigned keys are read-only accounts
*/ */
export type MessageHeader = { export type MessageHeader = {
numRequiredSignatures: number, numRequiredSignatures: number;
numReadonlySignedAccounts: number, numReadonlySignedAccounts: number;
numReadonlyUnsignedAccounts: number, numReadonlyUnsignedAccounts: number;
}; };
/** /**
@ -34,9 +32,9 @@ export type MessageHeader = {
* @property {string} data The program input data encoded as base 58 * @property {string} data The program input data encoded as base 58
*/ */
export type CompiledInstruction = { export type CompiledInstruction = {
programIdIndex: number, programIdIndex: number;
accounts: number[], accounts: number[];
data: string, data: string;
}; };
/** /**
@ -48,11 +46,11 @@ export type CompiledInstruction = {
* @property {Blockhash} recentBlockhash The hash of a recent ledger block * @property {Blockhash} recentBlockhash The hash of a recent ledger block
* @property {CompiledInstruction[]} instructions Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. * @property {CompiledInstruction[]} instructions Instructions that will be executed in sequence and committed in one atomic transaction if all succeed.
*/ */
type MessageArgs = { export type MessageArgs = {
header: MessageHeader, header: MessageHeader;
accountKeys: string[], accountKeys: string[];
recentBlockhash: Blockhash, recentBlockhash: Blockhash;
instructions: CompiledInstruction[], instructions: CompiledInstruction[];
}; };
const PUBKEY_LENGTH = 32; const PUBKEY_LENGTH = 32;
@ -87,17 +85,17 @@ export class Message {
serialize(): Buffer { serialize(): Buffer {
const numKeys = this.accountKeys.length; const numKeys = this.accountKeys.length;
let keyCount = []; let keyCount: number[] = [];
shortvec.encodeLength(keyCount, numKeys); shortvec.encodeLength(keyCount, numKeys);
const instructions = this.instructions.map(instruction => { const instructions = this.instructions.map(instruction => {
const {accounts, programIdIndex} = instruction; const {accounts, programIdIndex} = instruction;
const data = bs58.decode(instruction.data); const data = bs58.decode(instruction.data);
let keyIndicesCount = []; let keyIndicesCount: number[] = [];
shortvec.encodeLength(keyIndicesCount, accounts.length); shortvec.encodeLength(keyIndicesCount, accounts.length);
let dataCount = []; let dataCount: number[] = [];
shortvec.encodeLength(dataCount, data.length); shortvec.encodeLength(dataCount, data.length);
return { return {
@ -109,7 +107,7 @@ export class Message {
}; };
}); });
let instructionCount = []; let instructionCount: number[] = [];
shortvec.encodeLength(instructionCount, instructions.length); shortvec.encodeLength(instructionCount, instructions.length);
let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE); let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);
Buffer.from(instructionCount).copy(instructionBuffer); Buffer.from(instructionCount).copy(instructionBuffer);
@ -179,9 +177,9 @@ export class Message {
// Slice up wire data // Slice up wire data
let byteArray = [...buffer]; let byteArray = [...buffer];
const numRequiredSignatures = byteArray.shift(); const numRequiredSignatures = byteArray.shift() as number;
const numReadonlySignedAccounts = byteArray.shift(); const numReadonlySignedAccounts = byteArray.shift() as number;
const numReadonlyUnsignedAccounts = byteArray.shift(); const numReadonlyUnsignedAccounts = byteArray.shift() as number;
const accountCount = shortvec.decodeLength(byteArray); const accountCount = shortvec.decodeLength(byteArray);
let accountKeys = []; let accountKeys = [];
@ -195,18 +193,21 @@ export class Message {
byteArray = byteArray.slice(PUBKEY_LENGTH); byteArray = byteArray.slice(PUBKEY_LENGTH);
const instructionCount = shortvec.decodeLength(byteArray); const instructionCount = shortvec.decodeLength(byteArray);
let instructions = []; let instructions: CompiledInstruction[] = [];
for (let i = 0; i < instructionCount; i++) { for (let i = 0; i < instructionCount; i++) {
let instruction = {}; const programIdIndex = byteArray.shift() as number;
instruction.programIdIndex = byteArray.shift();
const accountCount = shortvec.decodeLength(byteArray); const accountCount = shortvec.decodeLength(byteArray);
instruction.accounts = byteArray.slice(0, accountCount); const accounts = byteArray.slice(0, accountCount);
byteArray = byteArray.slice(accountCount); byteArray = byteArray.slice(accountCount);
const dataLength = shortvec.decodeLength(byteArray); const dataLength = shortvec.decodeLength(byteArray);
const data = byteArray.slice(0, dataLength); const dataSlice = byteArray.slice(0, dataLength);
instruction.data = bs58.encode(Buffer.from(data)); const data = bs58.encode(Buffer.from(dataSlice));
byteArray = byteArray.slice(dataLength); byteArray = byteArray.slice(dataLength);
instructions.push(instruction); instructions.push({
programIdIndex,
accounts,
data,
});
} }
const messageArgs = { const messageArgs = {

View File

@ -1,4 +1,3 @@
// @flow
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
import type {Blockhash} from './blockhash'; import type {Blockhash} from './blockhash';
@ -11,7 +10,7 @@ import {toBuffer} from './util/to-buffer';
/** /**
* See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32 * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32
* *
* @private * @internal
*/ */
const NonceAccountLayout = BufferLayout.struct([ const NonceAccountLayout = BufferLayout.struct([
BufferLayout.u32('version'), BufferLayout.u32('version'),
@ -23,6 +22,12 @@ const NonceAccountLayout = BufferLayout.struct([
export const NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span; export const NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;
type NonceAccountArgs = {
authorizedPubkey: PublicKey;
nonce: Blockhash;
feeCalculator: FeeCalculator;
};
/** /**
* NonceAccount class * NonceAccount class
*/ */
@ -31,6 +36,15 @@ export class NonceAccount {
nonce: Blockhash; nonce: Blockhash;
feeCalculator: FeeCalculator; feeCalculator: FeeCalculator;
/**
* @internal
*/
constructor(args: NonceAccountArgs) {
this.authorizedPubkey = args.authorizedPubkey;
this.nonce = args.nonce;
this.feeCalculator = args.feeCalculator;
}
/** /**
* Deserialize NonceAccount from the account data. * Deserialize NonceAccount from the account data.
* *
@ -41,10 +55,10 @@ export class NonceAccount {
buffer: Buffer | Uint8Array | Array<number>, buffer: Buffer | Uint8Array | Array<number>,
): NonceAccount { ): NonceAccount {
const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0); const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);
nonceAccount.authorizedPubkey = new PublicKey( return new NonceAccount({
nonceAccount.authorizedPubkey, authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),
); nonce: new PublicKey(nonceAccount.nonce).toString(),
nonceAccount.nonce = new PublicKey(nonceAccount.nonce).toString(); feeCalculator: nonceAccount.feeCalculator,
return nonceAccount; });
} }
} }

View File

@ -1,15 +1,9 @@
// @flow
import BN from 'bn.js'; import BN from 'bn.js';
import bs58 from 'bs58'; import bs58 from 'bs58';
import nacl from 'tweetnacl'; import nacl from 'tweetnacl';
import {sha256} from 'crypto-hash'; import {sha256} from 'crypto-hash';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
let naclLowLevel = nacl.lowlevel;
type PublicKeyNonce = [PublicKey, number]; // This type exists to workaround an esdoc parse error
/** /**
* Maximum length of derived pubkey seed * Maximum length of derived pubkey seed
*/ */
@ -19,10 +13,12 @@ export const MAX_SEED_LENGTH = 32;
* A public key * A public key
*/ */
export class PublicKey { export class PublicKey {
/** @internal */
_bn: BN; _bn: BN;
/** /**
* Create a new PublicKey object * Create a new PublicKey object
* @param value ed25519 public key as buffer or base-58 encoded string
*/ */
constructor(value: number | string | Buffer | Uint8Array | Array<number>) { constructor(value: number | string | Buffer | Uint8Array | Array<number>) {
if (typeof value === 'string') { if (typeof value === 'string') {
@ -70,7 +66,7 @@ export class PublicKey {
} }
/** /**
* Returns a string representation of the public key * Return the base-58 representation of the public key
*/ */
toString(): string { toString(): string {
return this.toBase58(); return this.toBase58();
@ -130,7 +126,7 @@ export class PublicKey {
static async findProgramAddress( static async findProgramAddress(
seeds: Array<Buffer | Uint8Array>, seeds: Array<Buffer | Uint8Array>,
programId: PublicKey, programId: PublicKey,
): Promise<PublicKeyNonce> { ): Promise<[PublicKey, number]> {
let nonce = 255; let nonce = 255;
let address; let address;
while (nonce != 0) { while (nonce != 0) {
@ -147,10 +143,13 @@ export class PublicKey {
} }
} }
// @ts-ignore
let naclLowLevel = nacl.lowlevel;
// Check that a pubkey is on the curve. // Check that a pubkey is on the curve.
// This function and its dependents were sourced from: // This function and its dependents were sourced from:
// https://github.com/dchest/tweetnacl-js/blob/f1ec050ceae0861f34280e62498b1d3ed9c350c6/nacl.js#L792 // https://github.com/dchest/tweetnacl-js/blob/f1ec050ceae0861f34280e62498b1d3ed9c350c6/nacl.js#L792
function is_on_curve(p) { function is_on_curve(p: any) {
var r = [ var r = [
naclLowLevel.gf(), naclLowLevel.gf(),
naclLowLevel.gf(), naclLowLevel.gf(),
@ -213,7 +212,7 @@ let I = naclLowLevel.gf([
0x2480, 0x2480,
0x2b83, 0x2b83,
]); ]);
function neq25519(a, b) { function neq25519(a: any, b: any) {
var c = new Uint8Array(32), var c = new Uint8Array(32),
d = new Uint8Array(32); d = new Uint8Array(32);
naclLowLevel.pack25519(c, a); naclLowLevel.pack25519(c, a);

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
import secp256k1 from 'secp256k1'; import secp256k1 from 'secp256k1';
@ -25,12 +23,12 @@ const SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;
* @property {Buffer | Uint8Array | Array<number>} signature * @property {Buffer | Uint8Array | Array<number>} signature
* @property {number} recoveryId * @property {number} recoveryId
*/ */
export type CreateSecp256k1InstructionWithPublicKeyParams = {| export type CreateSecp256k1InstructionWithPublicKeyParams = {
publicKey: Buffer | Uint8Array | Array<number>, publicKey: Buffer | Uint8Array | Array<number>;
message: Buffer | Uint8Array | Array<number>, message: Buffer | Uint8Array | Array<number>;
signature: Buffer | Uint8Array | Array<number>, signature: Buffer | Uint8Array | Array<number>;
recoveryId: number, recoveryId: number;
|}; };
/** /**
* Params for creating an secp256k1 instruction using an Ethereum address * Params for creating an secp256k1 instruction using an Ethereum address
@ -40,12 +38,12 @@ export type CreateSecp256k1InstructionWithPublicKeyParams = {|
* @property {Buffer | Uint8Array | Array<number>} signature * @property {Buffer | Uint8Array | Array<number>} signature
* @property {number} recoveryId * @property {number} recoveryId
*/ */
export type CreateSecp256k1InstructionWithEthAddressParams = {| export type CreateSecp256k1InstructionWithEthAddressParams = {
ethAddress: Buffer | Uint8Array | Array<number> | string, ethAddress: Buffer | Uint8Array | Array<number> | string;
message: Buffer | Uint8Array | Array<number>, message: Buffer | Uint8Array | Array<number>;
signature: Buffer | Uint8Array | Array<number>, signature: Buffer | Uint8Array | Array<number>;
recoveryId: number, recoveryId: number;
|}; };
/** /**
* Params for creating an secp256k1 instruction using a private key * Params for creating an secp256k1 instruction using a private key
@ -53,10 +51,10 @@ export type CreateSecp256k1InstructionWithEthAddressParams = {|
* @property {Buffer | Uint8Array | Array<number>} privateKey * @property {Buffer | Uint8Array | Array<number>} privateKey
* @property {Buffer | Uint8Array | Array<number>} message * @property {Buffer | Uint8Array | Array<number>} message
*/ */
export type CreateSecp256k1InstructionWithPrivateKeyParams = {| export type CreateSecp256k1InstructionWithPrivateKeyParams = {
privateKey: Buffer | Uint8Array | Array<number>, privateKey: Buffer | Uint8Array | Array<number>;
message: Buffer | Uint8Array | Array<number>, message: Buffer | Uint8Array | Array<number>;
|}; };
const SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([ const SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([
BufferLayout.u8('numSignatures'), BufferLayout.u8('numSignatures'),
@ -73,6 +71,11 @@ const SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([
]); ]);
export class Secp256k1Program { export class Secp256k1Program {
/**
* @internal
*/
constructor() {}
/** /**
* Public key that identifies the secp256k1 program * Public key that identifies the secp256k1 program
*/ */
@ -126,13 +129,15 @@ export class Secp256k1Program {
): TransactionInstruction { ): TransactionInstruction {
const {ethAddress: rawAddress, message, signature, recoveryId} = params; const {ethAddress: rawAddress, message, signature, recoveryId} = params;
let ethAddress = rawAddress; let ethAddress;
if (typeof rawAddress === 'string') { if (typeof rawAddress === 'string') {
if (rawAddress.startsWith('0x')) { if (rawAddress.startsWith('0x')) {
ethAddress = Buffer.from(rawAddress.substr(2), 'hex'); ethAddress = Buffer.from(rawAddress.substr(2), 'hex');
} else { } else {
ethAddress = Buffer.from(rawAddress, 'hex'); ethAddress = Buffer.from(rawAddress, 'hex');
} }
} else {
ethAddress = rawAddress;
} }
assert( assert(

View File

@ -1,8 +1,6 @@
// @flow
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
import {encodeData, decodeData} from './instruction'; import {encodeData, decodeData, InstructionType} from './instruction';
import * as Layout from './layout'; import * as Layout from './layout';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
import {SystemProgram} from './system-program'; import {SystemProgram} from './system-program';
@ -13,16 +11,27 @@ import {
} from './sysvar'; } from './sysvar';
import {Transaction, TransactionInstruction} from './transaction'; import {Transaction, TransactionInstruction} from './transaction';
/**
* Address of the stake config account which configures the rate
* of stake warmup and cooldown as well as the slashing penalty.
*/
export const STAKE_CONFIG_ID = new PublicKey( export const STAKE_CONFIG_ID = new PublicKey(
'StakeConfig11111111111111111111111111111111', 'StakeConfig11111111111111111111111111111111',
); );
/**
* Stake account authority info
*/
export class Authorized { export class Authorized {
/** stake authority */
staker: PublicKey; staker: PublicKey;
/** withdraw authority */
withdrawer: PublicKey; withdrawer: PublicKey;
/** /**
* Create a new Authorized object * Create a new Authorized object
* @param staker the stake authority
* @param withdrawer the withdraw authority
*/ */
constructor(staker: PublicKey, withdrawer: PublicKey) { constructor(staker: PublicKey, withdrawer: PublicKey) {
this.staker = staker; this.staker = staker;
@ -30,9 +39,15 @@ export class Authorized {
} }
} }
/**
* Stake account lockup info
*/
export class Lockup { export class Lockup {
/** Unix timestamp of lockup expiration */
unixTimestamp: number; unixTimestamp: number;
/** Epoch of lockup expiration */
epoch: number; epoch: number;
/** Lockup custodian authority */
custodian: PublicKey; custodian: PublicKey;
/** /**
@ -47,153 +62,113 @@ export class Lockup {
/** /**
* Create stake account transaction params * Create stake account transaction params
* @typedef {Object} CreateStakeAccountParams
* @property {PublicKey} fromPubkey
* @property {PublicKey} stakePubkey
* @property {Authorized} authorized
* @property {Lockup} lockup
* @property {number} lamports
*/ */
export type CreateStakeAccountParams = {| export type CreateStakeAccountParams = {
fromPubkey: PublicKey, /** Address of the account which will fund creation */
stakePubkey: PublicKey, fromPubkey: PublicKey;
authorized: Authorized, /** Address of the new stake account */
lockup: Lockup, stakePubkey: PublicKey;
lamports: number, /** Authorities of the new stake account */
|}; authorized: Authorized;
/** Lockup of the new stake account */
lockup: Lockup;
/** Funding amount */
lamports: number;
};
/** /**
* Create stake account with seed transaction params * Create stake account with seed transaction params
* @typedef {Object} CreateStakeAccountWithSeedParams
* @property {PublicKey} fromPubkey
* @property {PublicKey} stakePubkey
* @property {PublicKey} basePubkey
* @property {string} seed
* @property {Authorized} authorized
* @property {Lockup} lockup
* @property {number} lamports
*/ */
export type CreateStakeAccountWithSeedParams = {| export type CreateStakeAccountWithSeedParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
stakePubkey: PublicKey, stakePubkey: PublicKey;
basePubkey: PublicKey, basePubkey: PublicKey;
seed: string, seed: string;
authorized: Authorized, authorized: Authorized;
lockup: Lockup, lockup: Lockup;
lamports: number, lamports: number;
|}; };
/** /**
* Initialize stake instruction params * Initialize stake instruction params
* @typedef {Object} InitializeStakeParams
* @property {PublicKey} stakePubkey
* @property {Authorized} authorized
* @property {Lockup} lockup
*/ */
export type InitializeStakeParams = {| export type InitializeStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorized: Authorized, authorized: Authorized;
lockup: Lockup, lockup: Lockup;
|}; };
/** /**
* Delegate stake instruction params * Delegate stake instruction params
* @typedef {Object} DelegateStakeParams
* @property {PublicKey} stakePubkey
* @property {PublicKey} authorizedPubkey
* @property {PublicKey} votePubkey
*/ */
export type DelegateStakeParams = {| export type DelegateStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
votePubkey: PublicKey, votePubkey: PublicKey;
|}; };
/** /**
* Authorize stake instruction params * Authorize stake instruction params
* @typedef {Object} AuthorizeStakeParams
* @property {PublicKey} stakePubkey
* @property {PublicKey} authorizedPubkey
* @property {PublicKey} newAuthorizedPubkey
* @property {StakeAuthorizationType} stakeAuthorizationType
* @property {PublicKey} custodianPubkey
*/ */
export type AuthorizeStakeParams = {| export type AuthorizeStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
newAuthorizedPubkey: PublicKey, newAuthorizedPubkey: PublicKey;
stakeAuthorizationType: StakeAuthorizationType, stakeAuthorizationType: StakeAuthorizationType;
custodianPubkey?: PublicKey, custodianPubkey?: PublicKey;
|}; };
/** /**
* Authorize stake instruction params using a derived key * Authorize stake instruction params using a derived key
* @typedef {Object} AuthorizeWithSeedStakeParams
* @property {PublicKey} stakePubkey
* @property {PublicKey} authorityBase
* @property {string} authoritySeed
* @property {PublicKey} authorityOwner
* @property {PublicKey} newAuthorizedPubkey
* @property {StakeAuthorizationType} stakeAuthorizationType
* @property {PublicKey} custodianPubkey
*/ */
export type AuthorizeWithSeedStakeParams = {| export type AuthorizeWithSeedStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorityBase: PublicKey, authorityBase: PublicKey;
authoritySeed: string, authoritySeed: string;
authorityOwner: PublicKey, authorityOwner: PublicKey;
newAuthorizedPubkey: PublicKey, newAuthorizedPubkey: PublicKey;
stakeAuthorizationType: StakeAuthorizationType, stakeAuthorizationType: StakeAuthorizationType;
custodianPubkey?: PublicKey, custodianPubkey?: PublicKey;
|}; };
/** /**
* Split stake instruction params * Split stake instruction params
* @typedef {Object} SplitStakeParams
* @property {PublicKey} stakePubkey
* @property {PublicKey} authorizedPubkey
* @property {PublicKey} splitStakePubkey
* @property {number} lamports
*/ */
export type SplitStakeParams = {| export type SplitStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
splitStakePubkey: PublicKey, splitStakePubkey: PublicKey;
lamports: number, lamports: number;
|}; };
/** /**
* Withdraw stake instruction params * Withdraw stake instruction params
* @typedef {Object} WithdrawStakeParams
* @property {PublicKey} stakePubkey
* @property {PublicKey} authorizedPubkey
* @property {PublicKey} toPubkey
* @property {number} lamports
* @property {PublicKey} custodianPubkey
*/ */
export type WithdrawStakeParams = {| export type WithdrawStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
toPubkey: PublicKey, toPubkey: PublicKey;
lamports: number, lamports: number;
custodianPubkey?: PublicKey, custodianPubkey?: PublicKey;
|}; };
/** /**
* Deactivate stake instruction params * Deactivate stake instruction params
* @typedef {Object} DeactivateStakeParams
* @property {PublicKey} stakePubkey
* @property {PublicKey} authorizedPubkey
*/ */
export type DeactivateStakeParams = {| export type DeactivateStakeParams = {
stakePubkey: PublicKey, stakePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
|}; };
/** /**
* Stake Instruction class * Stake Instruction class
*/ */
export class StakeInstruction { export class StakeInstruction {
/**
* @internal
*/
constructor() {}
/** /**
* Decode a stake instruction and retrieve the instruction type. * Decode a stake instruction and retrieve the instruction type.
*/ */
@ -205,10 +180,11 @@ export class StakeInstruction {
const instructionTypeLayout = BufferLayout.u32('instruction'); const instructionTypeLayout = BufferLayout.u32('instruction');
const typeIndex = instructionTypeLayout.decode(instruction.data); const typeIndex = instructionTypeLayout.decode(instruction.data);
let type; let type: StakeInstructionType | undefined;
for (const t of Object.keys(STAKE_INSTRUCTION_LAYOUTS)) { for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {
if (STAKE_INSTRUCTION_LAYOUTS[t].index == typeIndex) { if (layout.index == typeIndex) {
type = t; type = ixType as StakeInstructionType;
break;
} }
} }
@ -387,7 +363,7 @@ export class StakeInstruction {
} }
/** /**
* @private * @internal
*/ */
static checkProgramId(programId: PublicKey) { static checkProgramId(programId: PublicKey) {
if (!programId.equals(StakeProgram.programId)) { if (!programId.equals(StakeProgram.programId)) {
@ -396,7 +372,7 @@ export class StakeInstruction {
} }
/** /**
* @private * @internal
*/ */
static checkKeyLength(keys: Array<any>, expectedLength: number) { static checkKeyLength(keys: Array<any>, expectedLength: number) {
if (keys.length < expectedLength) { if (keys.length < expectedLength) {
@ -409,15 +385,22 @@ export class StakeInstruction {
/** /**
* An enumeration of valid StakeInstructionType's * An enumeration of valid StakeInstructionType's
* @typedef { 'Initialize' | 'Authorize' | 'AuthorizeWithSeed' | 'Delegate' | 'Split' | 'Withdraw'
| 'Deactivate' } StakeInstructionType
*/ */
export type StakeInstructionType = $Keys<typeof STAKE_INSTRUCTION_LAYOUTS>; export type StakeInstructionType =
| 'AuthorizeWithSeed'
| 'Authorize'
| 'Deactivate'
| 'Delegate'
| 'Initialize'
| 'Split'
| 'Withdraw';
/** /**
* An enumeration of valid stake InstructionType's * An enumeration of valid stake InstructionType's
*/ */
export const STAKE_INSTRUCTION_LAYOUTS = Object.freeze({ export const STAKE_INSTRUCTION_LAYOUTS: {
[type in StakeInstructionType]: InstructionType;
} = Object.freeze({
Initialize: { Initialize: {
index: 0, index: 0,
layout: BufferLayout.struct([ layout: BufferLayout.struct([
@ -472,9 +455,9 @@ export const STAKE_INSTRUCTION_LAYOUTS = Object.freeze({
* @typedef {Object} StakeAuthorizationType * @typedef {Object} StakeAuthorizationType
* @property (index} The Stake Authorization index (from solana-stake-program) * @property (index} The Stake Authorization index (from solana-stake-program)
*/ */
export type StakeAuthorizationType = {| export type StakeAuthorizationType = {
index: number, index: number;
|}; };
/** /**
* An enumeration of valid StakeAuthorizationLayout's * An enumeration of valid StakeAuthorizationLayout's
@ -492,6 +475,11 @@ export const StakeAuthorizationLayout = Object.freeze({
* Factory class for transactions to interact with the Stake program * Factory class for transactions to interact with the Stake program
*/ */
export class StakeProgram { export class StakeProgram {
/**
* @internal
*/
constructor() {}
/** /**
* Public key that identifies the Stake program * Public key that identifies the Stake program
*/ */

View File

@ -1,8 +1,6 @@
// @flow
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
import {encodeData, decodeData} from './instruction'; import {encodeData, decodeData, InstructionType} from './instruction';
import * as Layout from './layout'; import * as Layout from './layout';
import {NONCE_ACCOUNT_LENGTH} from './nonce-account'; import {NONCE_ACCOUNT_LENGTH} from './nonce-account';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
@ -18,13 +16,13 @@ import {Transaction, TransactionInstruction} from './transaction';
* @property {number} space * @property {number} space
* @property {PublicKey} programId * @property {PublicKey} programId
*/ */
export type CreateAccountParams = {| export type CreateAccountParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
newAccountPubkey: PublicKey, newAccountPubkey: PublicKey;
lamports: number, lamports: number;
space: number, space: number;
programId: PublicKey, programId: PublicKey;
|}; };
/** /**
* Transfer system transaction params * Transfer system transaction params
@ -33,11 +31,11 @@ export type CreateAccountParams = {|
* @property {PublicKey} toPubkey * @property {PublicKey} toPubkey
* @property {number} lamports * @property {number} lamports
*/ */
export type TransferParams = {| export type TransferParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
toPubkey: PublicKey, toPubkey: PublicKey;
lamports: number, lamports: number;
|}; };
/** /**
* Assign system transaction params * Assign system transaction params
@ -45,10 +43,10 @@ export type TransferParams = {|
* @property {PublicKey} accountPubkey * @property {PublicKey} accountPubkey
* @property {PublicKey} programId * @property {PublicKey} programId
*/ */
export type AssignParams = {| export type AssignParams = {
accountPubkey: PublicKey, accountPubkey: PublicKey;
programId: PublicKey, programId: PublicKey;
|}; };
/** /**
* Create account with seed system transaction params * Create account with seed system transaction params
@ -61,15 +59,15 @@ export type AssignParams = {|
* @property {number} space * @property {number} space
* @property {PublicKey} programId * @property {PublicKey} programId
*/ */
export type CreateAccountWithSeedParams = {| export type CreateAccountWithSeedParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
newAccountPubkey: PublicKey, newAccountPubkey: PublicKey;
basePubkey: PublicKey, basePubkey: PublicKey;
seed: string, seed: string;
lamports: number, lamports: number;
space: number, space: number;
programId: PublicKey, programId: PublicKey;
|}; };
/** /**
* Create nonce account system transaction params * Create nonce account system transaction params
@ -79,12 +77,12 @@ export type CreateAccountWithSeedParams = {|
* @property {PublicKey} authorizedPubkey * @property {PublicKey} authorizedPubkey
* @property {number} lamports * @property {number} lamports
*/ */
export type CreateNonceAccountParams = {| export type CreateNonceAccountParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
noncePubkey: PublicKey, noncePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
lamports: number, lamports: number;
|}; };
/** /**
* Create nonce account with seed system transaction params * Create nonce account with seed system transaction params
@ -96,14 +94,14 @@ export type CreateNonceAccountParams = {|
* @property {string} seed * @property {string} seed
* @property {number} lamports * @property {number} lamports
*/ */
export type CreateNonceAccountWithSeedParams = {| export type CreateNonceAccountWithSeedParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
noncePubkey: PublicKey, noncePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
lamports: number, lamports: number;
basePubkey: PublicKey, basePubkey: PublicKey;
seed: string, seed: string;
|}; };
/** /**
* Initialize nonce account system instruction params * Initialize nonce account system instruction params
@ -111,10 +109,10 @@ export type CreateNonceAccountWithSeedParams = {|
* @property {PublicKey} noncePubkey * @property {PublicKey} noncePubkey
* @property {PublicKey} authorizedPubkey * @property {PublicKey} authorizedPubkey
*/ */
export type InitializeNonceParams = {| export type InitializeNonceParams = {
noncePubkey: PublicKey, noncePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
|}; };
/** /**
* Advance nonce account system instruction params * Advance nonce account system instruction params
@ -122,10 +120,10 @@ export type InitializeNonceParams = {|
* @property {PublicKey} noncePubkey * @property {PublicKey} noncePubkey
* @property {PublicKey} authorizedPubkey * @property {PublicKey} authorizedPubkey
*/ */
export type AdvanceNonceParams = {| export type AdvanceNonceParams = {
noncePubkey: PublicKey, noncePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
|}; };
/** /**
* Withdraw nonce account system transaction params * Withdraw nonce account system transaction params
@ -135,12 +133,12 @@ export type AdvanceNonceParams = {|
* @property {PublicKey} toPubkey * @property {PublicKey} toPubkey
* @property {number} lamports * @property {number} lamports
*/ */
export type WithdrawNonceParams = {| export type WithdrawNonceParams = {
noncePubkey: PublicKey, noncePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
toPubkey: PublicKey, toPubkey: PublicKey;
lamports: number, lamports: number;
|}; };
/** /**
* Authorize nonce account system transaction params * Authorize nonce account system transaction params
@ -149,11 +147,11 @@ export type WithdrawNonceParams = {|
* @property {PublicKey} authorizedPubkey * @property {PublicKey} authorizedPubkey
* @property {PublicKey} newAuthorizedPubkey * @property {PublicKey} newAuthorizedPubkey
*/ */
export type AuthorizeNonceParams = {| export type AuthorizeNonceParams = {
noncePubkey: PublicKey, noncePubkey: PublicKey;
authorizedPubkey: PublicKey, authorizedPubkey: PublicKey;
newAuthorizedPubkey: PublicKey, newAuthorizedPubkey: PublicKey;
|}; };
/** /**
* Allocate account system transaction params * Allocate account system transaction params
@ -161,10 +159,10 @@ export type AuthorizeNonceParams = {|
* @property {PublicKey} accountPubkey * @property {PublicKey} accountPubkey
* @property {number} space * @property {number} space
*/ */
export type AllocateParams = {| export type AllocateParams = {
accountPubkey: PublicKey, accountPubkey: PublicKey;
space: number, space: number;
|}; };
/** /**
* Allocate account with seed system transaction params * Allocate account with seed system transaction params
@ -175,13 +173,13 @@ export type AllocateParams = {|
* @property {number} space * @property {number} space
* @property {PublicKey} programId * @property {PublicKey} programId
*/ */
export type AllocateWithSeedParams = {| export type AllocateWithSeedParams = {
accountPubkey: PublicKey, accountPubkey: PublicKey;
basePubkey: PublicKey, basePubkey: PublicKey;
seed: string, seed: string;
space: number, space: number;
programId: PublicKey, programId: PublicKey;
|}; };
/** /**
* Assign account with seed system transaction params * Assign account with seed system transaction params
@ -191,12 +189,12 @@ export type AllocateWithSeedParams = {|
* @property {string} seed * @property {string} seed
* @property {PublicKey} programId * @property {PublicKey} programId
*/ */
export type AssignWithSeedParams = {| export type AssignWithSeedParams = {
accountPubkey: PublicKey, accountPubkey: PublicKey;
basePubkey: PublicKey, basePubkey: PublicKey;
seed: string, seed: string;
programId: PublicKey, programId: PublicKey;
|}; };
/** /**
* Transfer with seed system transaction params * Transfer with seed system transaction params
@ -208,19 +206,24 @@ export type AssignWithSeedParams = {|
* @property {string} seed * @property {string} seed
* @property {PublicKey} programId * @property {PublicKey} programId
*/ */
export type TransferWithSeedParams = {| export type TransferWithSeedParams = {
fromPubkey: PublicKey, fromPubkey: PublicKey;
basePubkey: PublicKey, basePubkey: PublicKey;
toPubkey: PublicKey, toPubkey: PublicKey;
lamports: number, lamports: number;
seed: string, seed: string;
programId: PublicKey, programId: PublicKey;
|}; };
/** /**
* System Instruction class * System Instruction class
*/ */
export class SystemInstruction { export class SystemInstruction {
/**
* @internal
*/
constructor() {}
/** /**
* Decode a system instruction and retrieve the instruction type. * Decode a system instruction and retrieve the instruction type.
*/ */
@ -232,10 +235,11 @@ export class SystemInstruction {
const instructionTypeLayout = BufferLayout.u32('instruction'); const instructionTypeLayout = BufferLayout.u32('instruction');
const typeIndex = instructionTypeLayout.decode(instruction.data); const typeIndex = instructionTypeLayout.decode(instruction.data);
let type; let type: SystemInstructionType | undefined;
for (const t of Object.keys(SYSTEM_INSTRUCTION_LAYOUTS)) { for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {
if (SYSTEM_INSTRUCTION_LAYOUTS[t].index == typeIndex) { if (layout.index == typeIndex) {
type = t; type = ixType as SystemInstructionType;
break;
} }
} }
@ -502,7 +506,7 @@ export class SystemInstruction {
} }
/** /**
* @private * @internal
*/ */
static checkProgramId(programId: PublicKey) { static checkProgramId(programId: PublicKey) {
if (!programId.equals(SystemProgram.programId)) { if (!programId.equals(SystemProgram.programId)) {
@ -511,7 +515,7 @@ export class SystemInstruction {
} }
/** /**
* @private * @internal
*/ */
static checkKeyLength(keys: Array<any>, expectedLength: number) { static checkKeyLength(keys: Array<any>, expectedLength: number) {
if (keys.length < expectedLength) { if (keys.length < expectedLength) {
@ -524,16 +528,27 @@ export class SystemInstruction {
/** /**
* An enumeration of valid SystemInstructionType's * An enumeration of valid SystemInstructionType's
* @typedef {'Create' | 'Assign' | 'Transfer' | 'CreateWithSeed'
| 'AdvanceNonceAccount' | 'WithdrawNonceAccount' | 'InitializeNonceAccount'
| 'AuthorizeNonceAccount'} SystemInstructionType
*/ */
export type SystemInstructionType = $Keys<typeof SYSTEM_INSTRUCTION_LAYOUTS>; export type SystemInstructionType =
| 'AdvanceNonceAccount'
| 'Allocate'
| 'AllocateWithSeed'
| 'Assign'
| 'AssignWithSeed'
| 'AuthorizeNonceAccount'
| 'Create'
| 'CreateWithSeed'
| 'InitializeNonceAccount'
| 'Transfer'
| 'TransferWithSeed'
| 'WithdrawNonceAccount';
/** /**
* An enumeration of valid system InstructionType's * An enumeration of valid system InstructionType's
*/ */
export const SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({ export const SYSTEM_INSTRUCTION_LAYOUTS: {
[type in SystemInstructionType]: InstructionType;
} = Object.freeze({
Create: { Create: {
index: 0, index: 0,
layout: BufferLayout.struct([ layout: BufferLayout.struct([
@ -634,6 +649,11 @@ export const SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({
* Factory class for transactions to interact with the System program * Factory class for transactions to interact with the System program
*/ */
export class SystemProgram { export class SystemProgram {
/**
* @internal
*/
constructor() {}
/** /**
* Public key that identifies the System program * Public key that identifies the System program
*/ */
@ -670,7 +690,7 @@ export class SystemProgram {
): TransactionInstruction { ): TransactionInstruction {
let data; let data;
let keys; let keys;
if (params.basePubkey) { if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed; const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;
data = encodeData(type, { data = encodeData(type, {
lamports: params.lamports, lamports: params.lamports,
@ -706,7 +726,7 @@ export class SystemProgram {
): TransactionInstruction { ): TransactionInstruction {
let data; let data;
let keys; let keys;
if (params.basePubkey) { if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed; const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;
data = encodeData(type, { data = encodeData(type, {
base: params.basePubkey.toBuffer(), base: params.basePubkey.toBuffer(),
@ -767,7 +787,7 @@ export class SystemProgram {
params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams, params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams,
): Transaction { ): Transaction {
const transaction = new Transaction(); const transaction = new Transaction();
if (params.basePubkey && params.seed) { if ('basePubkey' in params && 'seed' in params) {
transaction.add( transaction.add(
SystemProgram.createAccountWithSeed({ SystemProgram.createAccountWithSeed({
fromPubkey: params.fromPubkey, fromPubkey: params.fromPubkey,
@ -904,7 +924,7 @@ export class SystemProgram {
): TransactionInstruction { ): TransactionInstruction {
let data; let data;
let keys; let keys;
if (params.basePubkey) { if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed; const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;
data = encodeData(type, { data = encodeData(type, {
base: params.basePubkey.toBuffer(), base: params.basePubkey.toBuffer(),

View File

@ -1,4 +1,3 @@
// @flow
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
export const SYSVAR_CLOCK_PUBKEY = new PublicKey( export const SYSVAR_CLOCK_PUBKEY = new PublicKey(

View File

@ -1,25 +1,23 @@
// @flow
// TODO: These constants should be removed in favor of reading them out of a // TODO: These constants should be removed in favor of reading them out of a
// Syscall account // Syscall account
/** /**
* @ignore * @internal
*/ */
export const NUM_TICKS_PER_SECOND = 160; export const NUM_TICKS_PER_SECOND = 160;
/** /**
* @ignore * @internal
*/ */
export const DEFAULT_TICKS_PER_SLOT = 64; export const DEFAULT_TICKS_PER_SLOT = 64;
/** /**
* @ignore * @internal
*/ */
export const NUM_SLOTS_PER_SECOND = export const NUM_SLOTS_PER_SECOND =
NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT; NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;
/** /**
* @ignore * @internal
*/ */
export const MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND; export const MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;

View File

@ -1,5 +1,3 @@
// @flow
import invariant from 'assert'; import invariant from 'assert';
import nacl from 'tweetnacl'; import nacl from 'tweetnacl';
import bs58 from 'bs58'; import bs58 from 'bs58';
@ -45,9 +43,9 @@ const SIGNATURE_LENGTH = 64;
* @property {boolean} isWritable True if the `pubkey` can be loaded as a read-write account. * @property {boolean} isWritable True if the `pubkey` can be loaded as a read-write account.
*/ */
export type AccountMeta = { export type AccountMeta = {
pubkey: PublicKey, pubkey: PublicKey;
isSigner: boolean, isSigner: boolean;
isWritable: boolean, isWritable: boolean;
}; };
/** /**
@ -58,11 +56,11 @@ export type AccountMeta = {
* @property {PublicKey} programId * @property {PublicKey} programId
* @property {?Buffer} data * @property {?Buffer} data
*/ */
export type TransactionInstructionCtorFields = {| export type TransactionInstructionCtorFields = {
keys: Array<AccountMeta>, keys: Array<AccountMeta>;
programId: PublicKey, programId: PublicKey;
data?: Buffer, data?: Buffer;
|}; };
/** /**
* Configuration object for Transaction.serialize() * Configuration object for Transaction.serialize()
@ -72,8 +70,8 @@ export type TransactionInstructionCtorFields = {|
* @property {boolean|undefined} verifySignatures Verify provided signatures (default: true) * @property {boolean|undefined} verifySignatures Verify provided signatures (default: true)
*/ */
export type SerializeConfig = { export type SerializeConfig = {
requireAllSignatures?: boolean, requireAllSignatures?: boolean;
verifySignatures?: boolean, verifySignatures?: boolean;
}; };
/** /**
@ -106,12 +104,12 @@ export class TransactionInstruction {
} }
/** /**
* @private * @internal
*/ */
type SignaturePubkeyPair = {| type SignaturePubkeyPair = {
signature: Buffer | null, signature: Buffer | null;
publicKey: PublicKey, publicKey: PublicKey;
|}; };
/** /**
* List of Transaction object fields that may be initialized at construction * List of Transaction object fields that may be initialized at construction
@ -122,12 +120,12 @@ type SignaturePubkeyPair = {|
* @property {?Array<SignaturePubkeyPair>} signatures One or more signatures * @property {?Array<SignaturePubkeyPair>} signatures One or more signatures
* *
*/ */
type TransactionCtorFields = {| type TransactionCtorFields = {
recentBlockhash?: Blockhash | null, recentBlockhash?: Blockhash | null;
nonceInfo?: NonceInformation | null, nonceInfo?: NonceInformation | null;
feePayer?: PublicKey | null, feePayer?: PublicKey | null;
signatures?: Array<SignaturePubkeyPair>, signatures?: Array<SignaturePubkeyPair>;
|}; };
/** /**
* NonceInformation to be used to build a Transaction. * NonceInformation to be used to build a Transaction.
@ -136,10 +134,10 @@ type TransactionCtorFields = {|
* @property {Blockhash} nonce The current Nonce blockhash * @property {Blockhash} nonce The current Nonce blockhash
* @property {TransactionInstruction} nonceInstruction AdvanceNonceAccount Instruction * @property {TransactionInstruction} nonceInstruction AdvanceNonceAccount Instruction
*/ */
type NonceInformation = {| type NonceInformation = {
nonce: Blockhash, nonce: Blockhash;
nonceInstruction: TransactionInstruction, nonceInstruction: TransactionInstruction;
|}; };
/** /**
* Transaction class * Transaction class
@ -164,7 +162,7 @@ export class Transaction {
/** /**
* The transaction fee payer * The transaction fee payer
*/ */
feePayer: ?PublicKey; feePayer?: PublicKey;
/** /**
* The instructions to atomically execute * The instructions to atomically execute
@ -174,13 +172,13 @@ export class Transaction {
/** /**
* A recent transaction id. Must be populated by the caller * A recent transaction id. Must be populated by the caller
*/ */
recentBlockhash: ?Blockhash; recentBlockhash?: Blockhash;
/** /**
* Optional Nonce information. If populated, transaction will use a durable * Optional Nonce information. If populated, transaction will use a durable
* Nonce hash instead of a recentBlockhash. Must be populated by the caller * Nonce hash instead of a recentBlockhash. Must be populated by the caller
*/ */
nonceInfo: ?NonceInformation; nonceInfo?: NonceInformation;
/** /**
* Construct an empty Transaction * Construct an empty Transaction
@ -194,7 +192,7 @@ export class Transaction {
*/ */
add( add(
...items: Array< ...items: Array<
Transaction | TransactionInstruction | TransactionInstructionCtorFields, Transaction | TransactionInstruction | TransactionInstructionCtorFields
> >
): Transaction { ): Transaction {
if (items.length === 0) { if (items.length === 0) {
@ -384,7 +382,7 @@ export class Transaction {
} }
/** /**
* @private * @internal
*/ */
_compile(): Message { _compile(): Message {
const message = this.compileMessage(); const message = this.compileMessage();
@ -517,7 +515,7 @@ export class Transaction {
} }
/** /**
* @private * @internal
*/ */
_partialSign(message: Message, ...signers: Array<Account>) { _partialSign(message: Message, ...signers: Array<Account>) {
const signData = message.serialize(); const signData = message.serialize();
@ -538,7 +536,7 @@ export class Transaction {
} }
/** /**
* @private * @internal
*/ */
_addSignature(pubkey: PublicKey, signature: Buffer) { _addSignature(pubkey: PublicKey, signature: Buffer) {
invariant(signature.length === 64); invariant(signature.length === 64);
@ -561,7 +559,7 @@ export class Transaction {
} }
/** /**
* @private * @internal
*/ */
_verifySignatures(signData: Buffer, requireAllSignatures: boolean): boolean { _verifySignatures(signData: Buffer, requireAllSignatures: boolean): boolean {
for (const {signature, publicKey} of this.signatures) { for (const {signature, publicKey} of this.signatures) {
@ -601,11 +599,11 @@ export class Transaction {
} }
/** /**
* @private * @internal
*/ */
_serialize(signData: Buffer): Buffer { _serialize(signData: Buffer): Buffer {
const {signatures} = this; const {signatures} = this;
const signatureCount = []; const signatureCount: number[] = [];
shortvec.encodeLength(signatureCount, signatures.length); shortvec.encodeLength(signatureCount, signatures.length);
const transactionLength = const transactionLength =
signatureCount.length + signatures.length * 64 + signData.length; signatureCount.length + signatures.length * 64 + signData.length;
@ -634,7 +632,7 @@ export class Transaction {
/** /**
* Deprecated method * Deprecated method
* @private * @internal
*/ */
get keys(): Array<PublicKey> { get keys(): Array<PublicKey> {
invariant(this.instructions.length === 1); invariant(this.instructions.length === 1);
@ -643,7 +641,7 @@ export class Transaction {
/** /**
* Deprecated method * Deprecated method
* @private * @internal
*/ */
get programId(): PublicKey { get programId(): PublicKey {
invariant(this.instructions.length === 1); invariant(this.instructions.length === 1);
@ -652,7 +650,7 @@ export class Transaction {
/** /**
* Deprecated method * Deprecated method
* @private * @internal
*/ */
get data(): Buffer { get data(): Buffer {
invariant(this.instructions.length === 1); invariant(this.instructions.length === 1);

View File

@ -1,8 +1,3 @@
//@flow
/**
* @private
*/
const endpoint = { const endpoint = {
http: { http: {
devnet: 'http://devnet.solana.com', devnet: 'http://devnet.solana.com',

View File

@ -1,15 +1,13 @@
// @flow
export function promiseTimeout<T>( export function promiseTimeout<T>(
promise: Promise<T>, promise: Promise<T>,
timeoutMs: number, timeoutMs: number,
): Promise<T | null> { ): Promise<T | null> {
let timeoutId: TimeoutID; let timeoutId: ReturnType<typeof setTimeout>;
const timeoutPromise = new Promise(resolve => { const timeoutPromise: Promise<null> = new Promise(resolve => {
timeoutId = setTimeout(() => resolve(null), timeoutMs); timeoutId = setTimeout(() => resolve(null), timeoutMs);
}); });
return Promise.race([promise, timeoutPromise]).then(result => { return Promise.race([promise, timeoutPromise]).then((result: T | null) => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
return result; return result;
}); });

View File

@ -1,5 +1,3 @@
// @flow
import {Connection} from '../connection'; import {Connection} from '../connection';
import type {TransactionSignature} from '../transaction'; import type {TransactionSignature} from '../transaction';
import type {ConfirmOptions} from '../connection'; import type {ConfirmOptions} from '../connection';

View File

@ -1,5 +1,3 @@
// @flow
import {Connection} from '../connection'; import {Connection} from '../connection';
import {Transaction} from '../transaction'; import {Transaction} from '../transaction';
import type {Account} from '../account'; import type {Account} from '../account';

View File

@ -1,10 +1,8 @@
// @flow
export function decodeLength(bytes: Array<number>): number { export function decodeLength(bytes: Array<number>): number {
let len = 0; let len = 0;
let size = 0; let size = 0;
for (;;) { for (;;) {
let elem = bytes.shift(); let elem = bytes.shift() as number;
len |= (elem & 0x7f) << (size * 7); len |= (elem & 0x7f) << (size * 7);
size += 1; size += 1;
if ((elem & 0x80) === 0) { if ((elem & 0x80) === 0) {

View File

@ -1,5 +1,3 @@
// @flow
// zzz // zzz
export function sleep(ms: number): Promise<void> { export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
export const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => { export const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import { import {
assert as assertType, assert as assertType,
@ -17,12 +15,12 @@ export const VALIDATOR_INFO_KEY = new PublicKey(
); );
/** /**
* @private * @internal
*/ */
type ConfigKey = {| type ConfigKey = {
publicKey: PublicKey, publicKey: PublicKey;
isSigner: boolean, isSigner: boolean;
|}; };
/** /**
* Info used to identity validators. * Info used to identity validators.
@ -33,12 +31,12 @@ type ConfigKey = {|
* @property {?string} details optional, extra information the validator chose to share * @property {?string} details optional, extra information the validator chose to share
* @property {?string} keybaseUsername optional, used to identify validators on keybase.io * @property {?string} keybaseUsername optional, used to identify validators on keybase.io
*/ */
export type Info = {| export type Info = {
name: string, name: string;
website?: string, website?: string;
details?: string, details?: string;
keybaseUsername?: string, keybaseUsername?: string;
|}; };
const InfoString = pick({ const InfoString = pick({
name: string(), name: string(),

View File

@ -1,4 +1,3 @@
// @flow
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
import * as Layout from './layout'; import * as Layout from './layout';
@ -9,24 +8,24 @@ export const VOTE_PROGRAM_ID = new PublicKey(
'Vote111111111111111111111111111111111111111', 'Vote111111111111111111111111111111111111111',
); );
export type Lockout = {| export type Lockout = {
slot: number, slot: number;
confirmationCount: number, confirmationCount: number;
|}; };
/** /**
* History of how many credits earned by the end of each epoch * History of how many credits earned by the end of each epoch
*/ */
export type EpochCredits = {| export type EpochCredits = {
epoch: number, epoch: number;
credits: number, credits: number;
prevCredits: number, prevCredits: number;
|}; };
/** /**
* See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88 * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88
* *
* @private * @internal
*/ */
const VoteAccountLayout = BufferLayout.struct([ const VoteAccountLayout = BufferLayout.struct([
Layout.publicKey('nodePubkey'), Layout.publicKey('nodePubkey'),
@ -59,6 +58,19 @@ const VoteAccountLayout = BufferLayout.struct([
), ),
]); ]);
type VoteAccountArgs = {
nodePubkey: PublicKey;
authorizedVoterPubkey: PublicKey;
authorizedWithdrawerPubkey: PublicKey;
commission: number;
votes: Array<Lockout>;
rootSlot: number | null;
epoch: number;
credits: number;
lastEpochCredits: number;
epochCredits: Array<EpochCredits>;
};
/** /**
* VoteAccount class * VoteAccount class
*/ */
@ -74,6 +86,22 @@ export class VoteAccount {
lastEpochCredits: number; lastEpochCredits: number;
epochCredits: Array<EpochCredits>; epochCredits: Array<EpochCredits>;
/**
* @internal
*/
constructor(args: VoteAccountArgs) {
this.nodePubkey = args.nodePubkey;
this.authorizedVoterPubkey = args.authorizedVoterPubkey;
this.authorizedWithdrawerPubkey = args.authorizedWithdrawerPubkey;
this.commission = args.commission;
this.votes = args.votes;
this.rootSlot = args.rootSlot;
this.epoch = args.epoch;
this.credits = args.credits;
this.lastEpochCredits = args.lastEpochCredits;
this.epochCredits = args.epochCredits;
}
/** /**
* Deserialize VoteAccount from the account data. * Deserialize VoteAccount from the account data.
* *
@ -84,14 +112,23 @@ export class VoteAccount {
buffer: Buffer | Uint8Array | Array<number>, buffer: Buffer | Uint8Array | Array<number>,
): VoteAccount { ): VoteAccount {
const va = VoteAccountLayout.decode(toBuffer(buffer), 0); const va = VoteAccountLayout.decode(toBuffer(buffer), 0);
va.nodePubkey = new PublicKey(va.nodePubkey);
va.authorizedVoterPubkey = new PublicKey(va.authorizedVoterPubkey); let rootSlot: number | null = va.rootSlot;
va.authorizedWithdrawerPubkey = new PublicKey(
va.authorizedWithdrawerPubkey,
);
if (!va.rootSlotValid) { if (!va.rootSlotValid) {
va.rootSlot = null; rootSlot = null;
} }
return va;
return new VoteAccount({
nodePubkey: new PublicKey(va.nodePubkey),
authorizedVoterPubkey: new PublicKey(va.authorizedVoterPubkey),
authorizedWithdrawerPubkey: new PublicKey(va.authorizedWithdrawerPubkey),
commission: va.commission,
votes: va.votes,
rootSlot,
epoch: va.epoch,
credits: va.credits,
lastEpochCredits: va.lastEpochCredits,
epochCredits: va.epochCredits,
});
} }
} }

View File

@ -1,4 +1,3 @@
// @flow
import {expect} from 'chai'; import {expect} from 'chai';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';

View File

@ -1,5 +1,3 @@
// @flow
import {expect} from 'chai'; import {expect} from 'chai';
import {AgentManager, DESTROY_TIMEOUT_MS} from '../src/agent-manager'; import {AgentManager, DESTROY_TIMEOUT_MS} from '../src/agent-manager';

View File

@ -1,5 +1,3 @@
// @flow
import fs from 'mz/fs'; import fs from 'mz/fs';
import {expect, use} from 'chai'; import {expect, use} from 'chai';
import chaiAsPromised from 'chai-as-promised'; import chaiAsPromised from 'chai-as-promised';

View File

@ -1,5 +1,3 @@
// @flow
import {expect} from 'chai'; import {expect} from 'chai';
import {clusterApiUrl} from '../src/util/cluster'; import {clusterApiUrl} from '../src/util/cluster';

View File

@ -1,4 +1,3 @@
// @flow
import bs58 from 'bs58'; import bs58 from 'bs58';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {Token, u64} from '@solana/spl-token'; import {Token, u64} from '@solana/spl-token';

View File

@ -1,5 +1,3 @@
// @flow
import bs58 from 'bs58'; import bs58 from 'bs58';
import BN from 'bn.js'; import BN from 'bn.js';
import * as mockttp from 'mockttp'; import * as mockttp from 'mockttp';

View File

@ -1,5 +1,3 @@
// @flow
import {Client as LiveClient} from 'rpc-websockets'; import {Client as LiveClient} from 'rpc-websockets';
import {expect} from 'chai'; import {expect} from 'chai';
import sinon from 'sinon'; import sinon from 'sinon';

View File

@ -1,5 +1,3 @@
// @flow
import bs58 from 'bs58'; import bs58 from 'bs58';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {expect} from 'chai'; import {expect} from 'chai';

View File

@ -1,4 +1,3 @@
// @flow
import BN from 'bn.js'; import BN from 'bn.js';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {expect, use} from 'chai'; import {expect, use} from 'chai';

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {keccak_256} from 'js-sha3'; import {keccak_256} from 'js-sha3';
import {privateKeyVerify, ecdsaSign, publicKeyCreate} from 'secp256k1'; import {privateKeyVerify, ecdsaSign, publicKeyCreate} from 'secp256k1';

View File

@ -1,5 +1,3 @@
// @flow
import {expect} from 'chai'; import {expect} from 'chai';
import {decodeLength, encodeLength} from '../src/util/shortvec-encoding'; import {decodeLength, encodeLength} from '../src/util/shortvec-encoding';

View File

@ -1,5 +1,3 @@
// @flow
import {expect, use} from 'chai'; import {expect, use} from 'chai';
import chaiAsPromised from 'chai-as-promised'; import chaiAsPromised from 'chai-as-promised';

View File

@ -1,5 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {expect} from 'chai'; import {expect} from 'chai';

View File

@ -1,5 +1,3 @@
// @flow
import base58 from 'bs58'; import base58 from 'bs58';
import {expect} from 'chai'; import {expect} from 'chai';

View File

@ -1,4 +1,3 @@
// @flow
import bs58 from 'bs58'; import bs58 from 'bs58';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import nacl from 'tweetnacl'; import nacl from 'tweetnacl';

View File

@ -1,5 +1,3 @@
// @flow
/** /**
* The connection url to use when running unit tests against a live cluster * The connection url to use when running unit tests against a live cluster
*/ */

View File

@ -1,4 +1,3 @@
// @flow
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {expect} from 'chai'; import {expect} from 'chai';
import nacl from 'tweetnacl'; import nacl from 'tweetnacl';

View File

@ -1,4 +1,3 @@
// @flow
import bs58 from 'bs58'; import bs58 from 'bs58';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import {expect, use} from 'chai'; import {expect, use} from 'chai';