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

@ -27,8 +27,8 @@ function generateConfig(configType, format) {
}),
generateTypescript
? typescript({
browserslist: false,
})
browserslist: false,
})
: undefined,
babel({
exclude: '**/node_modules/**',

View File

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

View File

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

View File

@ -1,5 +1,3 @@
// @flow
import {Account} from './account';
import {PublicKey} from './publickey';
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';
/**
* https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11
*
* @private
* @internal
*/
export const FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');
/**
* @typedef {Object} FeeCalculator
* @property {number} lamportsPerSignature lamports Cost in lamports to validate a signature
* Calculator for transaction fees.
*/
export type FeeCalculator = {
lamportsPerSignature: number,
};
export interface FeeCalculator {
/** 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 * as BufferLayout from 'buffer-layout';
@ -9,16 +7,18 @@ import * as Layout from './layout';
* @typedef {Object} InstructionType
* @property (index} The Instruction index (from solana upstream program)
* @property (BufferLayout} The BufferLayout to use to build data
* @internal
*/
export type InstructionType = {|
index: number,
layout: typeof BufferLayout,
|};
export type InstructionType = {
index: number;
layout: typeof BufferLayout;
};
/**
* 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 =
type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);
const data = Buffer.alloc(allocLength);
@ -29,8 +29,9 @@ export function encodeData(type: InstructionType, fields: Object): Buffer {
/**
* 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;
try {
data = type.layout.decode(buffer);

View File

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

View File

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

View File

@ -1,5 +1,3 @@
// @flow
import bs58 from 'bs58';
import {Buffer} from 'buffer';
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
*/
export type MessageHeader = {
numRequiredSignatures: number,
numReadonlySignedAccounts: number,
numReadonlyUnsignedAccounts: number,
numRequiredSignatures: number;
numReadonlySignedAccounts: number;
numReadonlyUnsignedAccounts: number;
};
/**
@ -34,9 +32,9 @@ export type MessageHeader = {
* @property {string} data The program input data encoded as base 58
*/
export type CompiledInstruction = {
programIdIndex: number,
accounts: number[],
data: string,
programIdIndex: number;
accounts: number[];
data: string;
};
/**
@ -48,11 +46,11 @@ export type CompiledInstruction = {
* @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.
*/
type MessageArgs = {
header: MessageHeader,
accountKeys: string[],
recentBlockhash: Blockhash,
instructions: CompiledInstruction[],
export type MessageArgs = {
header: MessageHeader;
accountKeys: string[];
recentBlockhash: Blockhash;
instructions: CompiledInstruction[];
};
const PUBKEY_LENGTH = 32;
@ -87,17 +85,17 @@ export class Message {
serialize(): Buffer {
const numKeys = this.accountKeys.length;
let keyCount = [];
let keyCount: number[] = [];
shortvec.encodeLength(keyCount, numKeys);
const instructions = this.instructions.map(instruction => {
const {accounts, programIdIndex} = instruction;
const data = bs58.decode(instruction.data);
let keyIndicesCount = [];
let keyIndicesCount: number[] = [];
shortvec.encodeLength(keyIndicesCount, accounts.length);
let dataCount = [];
let dataCount: number[] = [];
shortvec.encodeLength(dataCount, data.length);
return {
@ -109,7 +107,7 @@ export class Message {
};
});
let instructionCount = [];
let instructionCount: number[] = [];
shortvec.encodeLength(instructionCount, instructions.length);
let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);
Buffer.from(instructionCount).copy(instructionBuffer);
@ -179,9 +177,9 @@ export class Message {
// Slice up wire data
let byteArray = [...buffer];
const numRequiredSignatures = byteArray.shift();
const numReadonlySignedAccounts = byteArray.shift();
const numReadonlyUnsignedAccounts = byteArray.shift();
const numRequiredSignatures = byteArray.shift() as number;
const numReadonlySignedAccounts = byteArray.shift() as number;
const numReadonlyUnsignedAccounts = byteArray.shift() as number;
const accountCount = shortvec.decodeLength(byteArray);
let accountKeys = [];
@ -195,18 +193,21 @@ export class Message {
byteArray = byteArray.slice(PUBKEY_LENGTH);
const instructionCount = shortvec.decodeLength(byteArray);
let instructions = [];
let instructions: CompiledInstruction[] = [];
for (let i = 0; i < instructionCount; i++) {
let instruction = {};
instruction.programIdIndex = byteArray.shift();
const programIdIndex = byteArray.shift() as number;
const accountCount = shortvec.decodeLength(byteArray);
instruction.accounts = byteArray.slice(0, accountCount);
const accounts = byteArray.slice(0, accountCount);
byteArray = byteArray.slice(accountCount);
const dataLength = shortvec.decodeLength(byteArray);
const data = byteArray.slice(0, dataLength);
instruction.data = bs58.encode(Buffer.from(data));
const dataSlice = byteArray.slice(0, dataLength);
const data = bs58.encode(Buffer.from(dataSlice));
byteArray = byteArray.slice(dataLength);
instructions.push(instruction);
instructions.push({
programIdIndex,
accounts,
data,
});
}
const messageArgs = {

View File

@ -1,4 +1,3 @@
// @flow
import * as BufferLayout from 'buffer-layout';
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
*
* @private
* @internal
*/
const NonceAccountLayout = BufferLayout.struct([
BufferLayout.u32('version'),
@ -23,6 +22,12 @@ const NonceAccountLayout = BufferLayout.struct([
export const NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;
type NonceAccountArgs = {
authorizedPubkey: PublicKey;
nonce: Blockhash;
feeCalculator: FeeCalculator;
};
/**
* NonceAccount class
*/
@ -31,6 +36,15 @@ export class NonceAccount {
nonce: Blockhash;
feeCalculator: FeeCalculator;
/**
* @internal
*/
constructor(args: NonceAccountArgs) {
this.authorizedPubkey = args.authorizedPubkey;
this.nonce = args.nonce;
this.feeCalculator = args.feeCalculator;
}
/**
* Deserialize NonceAccount from the account data.
*
@ -41,10 +55,10 @@ export class NonceAccount {
buffer: Buffer | Uint8Array | Array<number>,
): NonceAccount {
const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);
nonceAccount.authorizedPubkey = new PublicKey(
nonceAccount.authorizedPubkey,
);
nonceAccount.nonce = new PublicKey(nonceAccount.nonce).toString();
return nonceAccount;
return new NonceAccount({
authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),
nonce: new PublicKey(nonceAccount.nonce).toString(),
feeCalculator: nonceAccount.feeCalculator,
});
}
}

View File

@ -1,15 +1,9 @@
// @flow
import BN from 'bn.js';
import bs58 from 'bs58';
import nacl from 'tweetnacl';
import {sha256} from 'crypto-hash';
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
*/
@ -19,10 +13,12 @@ export const MAX_SEED_LENGTH = 32;
* A public key
*/
export class PublicKey {
/** @internal */
_bn: BN;
/**
* 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>) {
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 {
return this.toBase58();
@ -130,7 +126,7 @@ export class PublicKey {
static async findProgramAddress(
seeds: Array<Buffer | Uint8Array>,
programId: PublicKey,
): Promise<PublicKeyNonce> {
): Promise<[PublicKey, number]> {
let nonce = 255;
let address;
while (nonce != 0) {
@ -147,10 +143,13 @@ export class PublicKey {
}
}
// @ts-ignore
let naclLowLevel = nacl.lowlevel;
// Check that a pubkey is on the curve.
// This function and its dependents were sourced from:
// https://github.com/dchest/tweetnacl-js/blob/f1ec050ceae0861f34280e62498b1d3ed9c350c6/nacl.js#L792
function is_on_curve(p) {
function is_on_curve(p: any) {
var r = [
naclLowLevel.gf(),
naclLowLevel.gf(),
@ -213,7 +212,7 @@ let I = naclLowLevel.gf([
0x2480,
0x2b83,
]);
function neq25519(a, b) {
function neq25519(a: any, b: any) {
var c = new Uint8Array(32),
d = new Uint8Array(32);
naclLowLevel.pack25519(c, a);

View File

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

View File

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

View File

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

View File

@ -1,4 +1,3 @@
// @flow
import {PublicKey} from './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
// Syscall account
/**
* @ignore
* @internal
*/
export const NUM_TICKS_PER_SECOND = 160;
/**
* @ignore
* @internal
*/
export const DEFAULT_TICKS_PER_SLOT = 64;
/**
* @ignore
* @internal
*/
export const NUM_SLOTS_PER_SECOND =
NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;
/**
* @ignore
* @internal
*/
export const MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,3 @@
// @flow
/**
* 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 {expect} from 'chai';
import nacl from 'tweetnacl';

View File

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