diff --git a/web3.js/rollup.config.js b/web3.js/rollup.config.js index 383268c7b3..41b1dfa47c 100644 --- a/web3.js/rollup.config.js +++ b/web3.js/rollup.config.js @@ -27,8 +27,8 @@ function generateConfig(configType, format) { }), generateTypescript ? typescript({ - browserslist: false, - }) + browserslist: false, + }) : undefined, babel({ exclude: '**/node_modules/**', diff --git a/web3.js/src/account.js b/web3.js/src/account.ts similarity index 89% rename from web3.js/src/account.js rename to web3.js/src/account.ts index a0df039979..9145c9deff 100644 --- a/web3.js/src/account.js +++ b/web3.js/src/account.ts @@ -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; /** diff --git a/web3.js/src/agent-manager.js b/web3.js/src/agent-manager.ts similarity index 83% rename from web3.js/src/agent-manager.js rename to web3.js/src/agent-manager.ts index aff5a28f74..0a99f8640e 100644 --- a/web3.js/src/agent-manager.js +++ b/web3.js/src/agent-manager.ts @@ -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 | 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; } diff --git a/web3.js/src/blockhash.js b/web3.js/src/blockhash.js deleted file mode 100644 index fc4677ffcf..0000000000 --- a/web3.js/src/blockhash.js +++ /dev/null @@ -1,6 +0,0 @@ -// @flow - -/** - * @typedef {string} Blockhash - */ -export type Blockhash = string; diff --git a/web3.js/src/blockhash.ts b/web3.js/src/blockhash.ts new file mode 100644 index 0000000000..40ee40667c --- /dev/null +++ b/web3.js/src/blockhash.ts @@ -0,0 +1,4 @@ +/** + * Blockhash as Base58 string. + */ +export type Blockhash = string; diff --git a/web3.js/src/bpf-loader-deprecated.js b/web3.js/src/bpf-loader-deprecated.ts similarity index 93% rename from web3.js/src/bpf-loader-deprecated.js rename to web3.js/src/bpf-loader-deprecated.ts index 907552de82..b1735dd495 100644 --- a/web3.js/src/bpf-loader-deprecated.js +++ b/web3.js/src/bpf-loader-deprecated.ts @@ -1,5 +1,3 @@ -// @flow - import {PublicKey} from './publickey'; export const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey( diff --git a/web3.js/src/bpf-loader.js b/web3.js/src/bpf-loader.ts similarity index 99% rename from web3.js/src/bpf-loader.js rename to web3.js/src/bpf-loader.ts index 26aae3b1da..f4924e0167 100644 --- a/web3.js/src/bpf-loader.js +++ b/web3.js/src/bpf-loader.ts @@ -1,5 +1,3 @@ -// @flow - import {Account} from './account'; import {PublicKey} from './publickey'; import {Loader} from './loader'; diff --git a/web3.js/src/buffer-layout.d.ts b/web3.js/src/buffer-layout.d.ts new file mode 100644 index 0000000000..f27644b6d3 --- /dev/null +++ b/web3.js/src/buffer-layout.d.ts @@ -0,0 +1 @@ +declare module 'buffer-layout'; diff --git a/web3.js/src/connection.js b/web3.js/src/connection.ts similarity index 83% rename from web3.js/src/connection.js rename to web3.js/src/connection.ts index e06967800e..36c3922f46 100644 --- a/web3.js/src/connection.js +++ b/web3.js/src/connection.ts @@ -1,11 +1,8 @@ -// @flow - import assert from 'assert'; import bs58 from 'bs58'; import {Buffer} from 'buffer'; import {parse as urlParse, format as urlFormat} from 'url'; -import fetch from 'node-fetch'; -import jayson from 'jayson/lib/client/browser'; +import fetch, {Response} from 'node-fetch'; import { type as pick, number, @@ -22,9 +19,12 @@ import { create, tuple, unknown, + any, } from 'superstruct'; import type {Struct} from 'superstruct'; import {Client as RpcWebSocketClient} from 'rpc-websockets'; +import RpcClient from 'jayson/lib/client/browser'; +import {IWSRequestParams} from 'rpc-websockets/dist/lib/client'; import {AgentManager} from './agent-manager'; import {NonceAccount} from './nonce-account'; @@ -55,82 +55,72 @@ const BufferFromRawAccountData = coerce( value => Buffer.from(value[0], 'base64'), ); -export const BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000; - type RpcRequest = (methodName: string, args: Array) => any; -type TokenAccountsFilter = - | {| - mint: PublicKey, - |} - | {| - programId: PublicKey, - |}; +export type TokenAccountsFilter = + | { + mint: PublicKey; + } + | { + programId: PublicKey; + }; /** * Extra contextual information for RPC responses - * - * @typedef {Object} Context - * @property {number} slot */ -type Context = { - slot: number, +export type Context = { + slot: number; }; /** * Options for sending transactions - * - * @typedef {Object} SendOptions - * @property {boolean | undefined} skipPreflight disable transaction verification step - * @property {Commitment | undefined} preflightCommitment preflight commitment level */ export type SendOptions = { - skipPreflight?: boolean, - preflightCommitment?: Commitment, + /** disable transaction verification step */ + skipPreflight?: boolean; + /** preflight commitment level */ + preflightCommitment?: Commitment; }; /** * Options for confirming transactions - * - * @typedef {Object} ConfirmOptions - * @property {boolean | undefined} skipPreflight disable transaction verification step - * @property {Commitment | undefined} commitment desired commitment level - * @property {Commitment | undefined} preflightCommitment preflight commitment level */ export type ConfirmOptions = { - skipPreflight?: boolean, - commitment?: Commitment, - preflightCommitment?: Commitment, + /** disable transaction verification step */ + skipPreflight?: boolean; + /** desired commitment level */ + commitment?: Commitment; + /** preflight commitment level */ + preflightCommitment?: Commitment; }; /** * Options for getConfirmedSignaturesForAddress2 * * @typedef {Object} ConfirmedSignaturesForAddress2Options - * @property {TransactionSignature | undefined} before start searching backwards from this transaction signature. - * If not provided the search starts from the highest max confirmed block. - * @property {number | undefined} limit maximum transaction signatures to return (between 1 and 1,000, default: 1,000). - * */ export type ConfirmedSignaturesForAddress2Options = { - before?: TransactionSignature, - limit?: number, + /** + * Start searching backwards from this transaction signature. + * @remark If not provided the search starts from the highest max confirmed block. + */ + before?: TransactionSignature; + /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */ + limit?: number; }; /** * RPC Response with extra contextual information - * - * @typedef {Object} RpcResponseAndContext - * @property {Context} context - * @property {T} value response */ -type RpcResponseAndContext = { - context: Context, - value: T, +export type RpcResponseAndContext = { + /** response context */ + context: Context; + /** response value */ + value: T; }; /** - * @private + * @internal */ function createRpcResult(result: Struct) { return union([ @@ -145,7 +135,7 @@ function createRpcResult(result: Struct) { error: pick({ code: unknown(), message: string(), - data: optional(unknown()), + data: optional(any()), }), }), ]); @@ -154,7 +144,7 @@ function createRpcResult(result: Struct) { const UnknownRpcResult = createRpcResult(unknown()); /** - * @private + * @internal */ function jsonRpcResult(schema: Struct) { return coerce(createRpcResult(schema), UnknownRpcResult, value => { @@ -170,7 +160,7 @@ function jsonRpcResult(schema: Struct) { } /** - * @private + * @internal */ function jsonRpcResultAndContext(value: Struct) { return jsonRpcResult( @@ -184,7 +174,7 @@ function jsonRpcResultAndContext(value: Struct) { } /** - * @private + * @internal */ function notificationResultAndContext(value: Struct) { return pick({ @@ -233,9 +223,9 @@ export type LargestAccountsFilter = 'circulating' | 'nonCirculating'; * @property {Commitment|undefined} commitment The level of commitment desired * @property {LargestAccountsFilter|undefined} filter Filter largest accounts by whether they are part of the circulating supply */ -type GetLargestAccountsConfig = { - commitment: ?Commitment, - filter: ?LargestAccountsFilter, +export type GetLargestAccountsConfig = { + commitment?: Commitment; + filter?: LargestAccountsFilter; }; /** @@ -245,7 +235,7 @@ type GetLargestAccountsConfig = { * @property {boolean} searchTransactionHistory enable searching status history, not needed for recent transactions */ export type SignatureStatusConfig = { - searchTransactionHistory: boolean, + searchTransactionHistory: boolean; }; /** @@ -258,12 +248,12 @@ export type SignatureStatusConfig = { * @property {string|null} rpc JSON RPC network address for the node (null if not available) * @property {string|null} version Software version of the node (null if not available) */ -type ContactInfo = { - pubkey: string, - gossip: string | null, - tpu: string | null, - rpc: string | null, - version: string | null, +export type ContactInfo = { + pubkey: string; + gossip: string | null; + tpu: string | null; + rpc: string | null; + version: string | null; }; /** @@ -278,14 +268,14 @@ type ContactInfo = { * @property {number} commission A percentage (0-100) of rewards payout owed to the voter * @property {number} lastVote Most recent slot voted on by this vote account */ -type VoteAccountInfo = { - votePubkey: string, - nodePubkey: string, - activatedStake: number, - epochVoteAccount: boolean, - epochCredits: Array<[number, number, number]>, - commission: number, - lastVote: number, +export type VoteAccountInfo = { + votePubkey: string; + nodePubkey: string; + activatedStake: number; + epochVoteAccount: boolean; + epochCredits: Array<[number, number, number]>; + commission: number; + lastVote: number; }; /** @@ -295,9 +285,9 @@ type VoteAccountInfo = { * @property {Array} current Active vote accounts * @property {Array} delinquent Inactive vote accounts */ -type VoteAccountStatus = { - current: Array, - delinquent: Array, +export type VoteAccountStatus = { + current: Array; + delinquent: Array; }; /** @@ -311,12 +301,12 @@ type VoteAccountStatus = { * @property {number} taper * @property {number} terminal */ -type InflationGovernor = { - foundation: number, - foundationTerm: number, - initial: number, - taper: number, - terminal: number, +export type InflationGovernor = { + foundation: number; + foundationTerm: number; + initial: number; + taper: number; + terminal: number; }; const GetInflationGovernorResult = pick({ @@ -338,13 +328,13 @@ const GetInflationGovernorResult = pick({ * @property {number} blockHeight * @property {number} transactionCount */ -type EpochInfo = { - epoch: number, - slotIndex: number, - slotsInEpoch: number, - absoluteSlot: number, - blockHeight: number | null, - transactionCount: number | null, +export type EpochInfo = { + epoch: number; + slotIndex: number; + slotsInEpoch: number; + absoluteSlot: number; + blockHeight?: number; + transactionCount?: number; }; const GetEpochInfoResult = pick({ @@ -367,12 +357,12 @@ const GetEpochInfoResult = pick({ * @property {number} firstNormalEpoch The first epoch with `slotsPerEpoch` slots * @property {number} firstNormalSlot The first slot of `firstNormalEpoch` */ -type EpochSchedule = { - slotsPerEpoch: number, - leaderScheduleSlotOffset: number, - warmup: boolean, - firstNormalEpoch: number, - firstNormalSlot: number, +export type EpochSchedule = { + slotsPerEpoch: number; + leaderScheduleSlotOffset: number; + warmup: boolean; + firstNormalEpoch: number; + firstNormalSlot: number; }; const GetEpochScheduleResult = pick({ @@ -389,12 +379,11 @@ const GetEpochScheduleResult = pick({ * * @typedef {Object} LeaderSchedule */ -type LeaderSchedule = { - [address: string]: number[], +export type LeaderSchedule = { + [address: string]: number[]; }; -// TODO: check if validating array(number()) is still extremely slow -const GetLeaderScheduleResult = record(string(), unknown()); +const GetLeaderScheduleResult = record(string(), array(number())); /** * Transaction error or null @@ -408,9 +397,9 @@ const SignatureStatusResult = pick({ err: TransactionErrorResult, }); -type Version = { - 'solana-core': string, - 'feature-set'?: number, +export type Version = { + 'solana-core': string; + 'feature-set'?: number; }; /** @@ -424,9 +413,9 @@ const VersionResult = pick({ 'feature-set': optional(number()), }); -type SimulatedTransactionResponse = { - err: TransactionError | string | null, - logs: Array | null, +export type SimulatedTransactionResponse = { + err: TransactionError | string | null; + logs: Array | null; }; const SimulatedTransactionResponseStruct = jsonRpcResultAndContext( @@ -436,15 +425,15 @@ const SimulatedTransactionResponseStruct = jsonRpcResultAndContext( }), ); -type ParsedInnerInstruction = { - index: number, - instructions: (ParsedInstruction | PartiallyDecodedInstruction)[], +export type ParsedInnerInstruction = { + index: number; + instructions: (ParsedInstruction | PartiallyDecodedInstruction)[]; }; -type TokenBalance = { - accountIndex: number, - mint: string, - uiTokenAmount: TokenAmount, +export type TokenBalance = { + accountIndex: number; + mint: string; + uiTokenAmount: TokenAmount; }; /** @@ -460,20 +449,20 @@ type TokenBalance = { * @property {Array} postTokenBalances The token balances of the transaction accounts after processing * @property {object|null} err The error result of transaction processing */ -type ParsedConfirmedTransactionMeta = { - fee: number, - innerInstructions?: ParsedInnerInstruction[], - preBalances: Array, - postBalances: Array, - logMessages?: Array, - preTokenBalances?: Array, - postTokenBalances?: Array, - err: TransactionError | null, +export type ParsedConfirmedTransactionMeta = { + fee: number; + innerInstructions?: ParsedInnerInstruction[] | null; + preBalances: Array; + postBalances: Array; + logMessages?: Array | null; + preTokenBalances?: Array | null; + postTokenBalances?: Array | null; + err: TransactionError | null; }; -type CompiledInnerInstruction = { - index: number, - instructions: CompiledInstruction[], +export type CompiledInnerInstruction = { + index: number; + instructions: CompiledInstruction[]; }; /** @@ -489,15 +478,15 @@ type CompiledInnerInstruction = { * @property {Array} postTokenBalances The token balances of the transaction accounts after processing * @property {object|null} err The error result of transaction processing */ -type ConfirmedTransactionMeta = { - fee: number, - innerInstructions?: CompiledInnerInstruction[], - preBalances: Array, - postBalances: Array, - logMessages?: Array, - preTokenBalances?: Array, - postTokenBalances?: Array, - err: TransactionError | null, +export type ConfirmedTransactionMeta = { + fee: number; + innerInstructions?: CompiledInnerInstruction[] | null; + preBalances: Array; + postBalances: Array; + logMessages?: Array | null; + preTokenBalances?: Array | null; + postTokenBalances?: Array | null; + err: TransactionError | null; }; /** @@ -509,26 +498,24 @@ type ConfirmedTransactionMeta = { * @property {ConfirmedTransactionMeta|null} meta Metadata produced from the transaction * @property {number|null|undefined} blockTime The unix timestamp of when the transaction was processed */ -type ConfirmedTransaction = { - slot: number, - transaction: Transaction, - meta: ConfirmedTransactionMeta | null, - blockTime?: number | null, +export type ConfirmedTransaction = { + slot: number; + transaction: Transaction; + meta: ConfirmedTransactionMeta | null; + blockTime?: number | null; }; /** * A partially decoded transaction instruction - * - * @typedef {Object} ParsedMessageAccount - * @property {PublicKey} pubkey Public key of the account - * @property {PublicKey} accounts Indicates if the account signed the transaction - * @property {string} data Raw base-58 instruction data */ -type PartiallyDecodedInstruction = {| - programId: PublicKey, - accounts: Array, - data: string, -|}; +export type PartiallyDecodedInstruction = { + /** Program id called by this instruction */ + programId: PublicKey; + /** Public keys of accounts passed to this instruction */ + accounts: Array; + /** Raw base-58 instruction data */ + data: string; +}; /** * A parsed transaction message account @@ -538,10 +525,10 @@ type PartiallyDecodedInstruction = {| * @property {boolean} signer Indicates if the account signed the transaction * @property {boolean} writable Indicates if the account is writable for this transaction */ -type ParsedMessageAccount = { - pubkey: PublicKey, - signer: boolean, - writable: boolean, +export type ParsedMessageAccount = { + pubkey: PublicKey; + signer: boolean; + writable: boolean; }; /** @@ -552,11 +539,11 @@ type ParsedMessageAccount = { * @property {PublicKey} programId ID of the program for this instruction * @property {any} parsed Parsed instruction info */ -type ParsedInstruction = {| - program: string, - programId: PublicKey, - parsed: any, -|}; +export type ParsedInstruction = { + program: string; + programId: PublicKey; + parsed: any; +}; /** * A parsed transaction message @@ -566,10 +553,10 @@ type ParsedInstruction = {| * @property {Array} instructions The atomically executed instructions for the transaction * @property {string} recentBlockhash Recent blockhash */ -type ParsedMessage = { - accountKeys: ParsedMessageAccount[], - instructions: (ParsedInstruction | PartiallyDecodedInstruction)[], - recentBlockhash: string, +export type ParsedMessage = { + accountKeys: ParsedMessageAccount[]; + instructions: (ParsedInstruction | PartiallyDecodedInstruction)[]; + recentBlockhash: string; }; /** @@ -579,9 +566,9 @@ type ParsedMessage = { * @property {Array} signatures Signatures for the transaction * @property {ParsedMessage} message Message of the transaction */ -type ParsedTransaction = { - signatures: Array, - message: ParsedMessage, +export type ParsedTransaction = { + signatures: Array; + message: ParsedMessage; }; /** @@ -593,11 +580,11 @@ type ParsedTransaction = { * @property {ConfirmedTransactionMeta|null} meta Metadata produced from the transaction * @property {number|null|undefined} blockTime The unix timestamp of when the transaction was processed */ -type ParsedConfirmedTransaction = { - slot: number, - transaction: ParsedTransaction, - meta: ParsedConfirmedTransactionMeta | null, - blockTime?: number | null, +export type ParsedConfirmedTransaction = { + slot: number; + transaction: ParsedTransaction; + meta: ParsedConfirmedTransactionMeta | null; + blockTime?: number | null; }; /** @@ -610,20 +597,20 @@ type ParsedConfirmedTransaction = { * @property {Array} transactions Vector of transactions and status metas * @property {Array} rewards Vector of block rewards */ -type ConfirmedBlock = { - blockhash: Blockhash, - previousBlockhash: Blockhash, - parentSlot: number, +export type ConfirmedBlock = { + blockhash: Blockhash; + previousBlockhash: Blockhash; + parentSlot: number; transactions: Array<{ - transaction: Transaction, - meta: ConfirmedTransactionMeta | null, - }>, - rewards: Array<{ - pubkey: string, - lamports: number, - postBalance: number | null, - rewardType: string | null, - }>, + transaction: Transaction; + meta: ConfirmedTransactionMeta | null; + }>; + rewards?: Array<{ + pubkey: string; + lamports: number; + postBalance: number | null; + rewardType: string | null; + }>; }; /** @@ -635,20 +622,20 @@ type ConfirmedBlock = { * @property {number} numSlots Number of slots in a sample window * @property {number} samplePeriodSecs Sample window in seconds */ -type PerfSample = { - slot: number, - numTransactions: number, - numSlots: number, - samplePeriodSecs: number, +export type PerfSample = { + slot: number; + numTransactions: number; + numSlots: number; + samplePeriodSecs: number; }; function createRpcRequest(url: string, useHttps: boolean): RpcRequest { - let agentManager; + let agentManager: AgentManager | undefined; if (!process.env.BROWSER) { agentManager = new AgentManager(useHttps); } - const server = jayson(async (request, callback) => { + const clientBrowser = new RpcClient(async (request, callback) => { const agent = agentManager ? agentManager.requestStart() : undefined; const options = { method: 'POST', @@ -661,7 +648,7 @@ function createRpcRequest(url: string, useHttps: boolean): RpcRequest { try { let too_many_requests_retries = 5; - let res = {}; + let res: Response; let waitTime = 500; for (;;) { res = await fetch(url, options); @@ -690,11 +677,11 @@ function createRpcRequest(url: string, useHttps: boolean): RpcRequest { } finally { agentManager && agentManager.requestEnd(); } - }); + }, {}); return (method, args) => { return new Promise((resolve, reject) => { - server.request(method, args, (err, response) => { + clientBrowser.request(method, args, (err: any, response: any) => { if (err) { reject(err); return; @@ -739,11 +726,11 @@ const SlotRpcResult = jsonRpcResult(number()); * @property {number} nonCirculating Non-circulating supply in lamports * @property {Array} nonCirculatingAccounts List of non-circulating account addresses */ -type Supply = { - total: number, - circulating: number, - nonCirculating: number, - nonCirculatingAccounts: Array, +export type Supply = { + total: number; + circulating: number; + nonCirculating: number; + nonCirculatingAccounts: Array; }; /** @@ -768,11 +755,11 @@ const GetSupplyRpcResult = jsonRpcResultAndContext( * @property {number | null} uiAmount Token amount as float, accounts for decimals * @property {string | undefined} uiAmountString Token amount as string, accounts for decimals */ -type TokenAmount = { - amount: string, - decimals: number, - uiAmount: number | null, - uiAmountString?: string, +export type TokenAmount = { + amount: string; + decimals: number; + uiAmount: number | null; + uiAmountString?: string; }; /** @@ -795,12 +782,12 @@ const TokenAmountResult = pick({ * @property {number | null} uiAmount Token amount as float, accounts for decimals * @property {string | undefined} uiAmountString Token amount as string, accounts for decimals */ -type TokenAccountBalancePair = { - address: PublicKey, - amount: string, - decimals: number, - uiAmount: number, - uiAmountString?: string, +export type TokenAccountBalancePair = { + address: PublicKey; + amount: string; + decimals: number; + uiAmount: number | null; + uiAmountString?: string; }; /** @@ -867,9 +854,9 @@ const GetParsedTokenAccountsByOwner = jsonRpcResultAndContext( * @property {PublicKey} address * @property {number} lamports */ -type AccountBalancePair = { - address: PublicKey, - lamports: number, +export type AccountBalancePair = { + address: PublicKey; + lamports: number; }; /** @@ -885,7 +872,7 @@ const GetLargestAccountsRpcResult = jsonRpcResultAndContext( ); /** - * @private + * @internal */ const AccountInfoResult = pick({ executable: boolean(), @@ -896,7 +883,7 @@ const AccountInfoResult = pick({ }); /** - * @private + * @internal */ const KeyedAccountInfoResult = pick({ pubkey: PublicKeyFromString, @@ -916,7 +903,7 @@ const ParsedOrRawAccountData = coerce( ); /** - * @private + * @internal */ const ParsedAccountInfoResult = pick({ executable: boolean(), @@ -932,7 +919,7 @@ const KeyedParsedAccountInfoResult = pick({ }); /** - * @private + * @internal */ const StakeActivationResult = pick({ state: union([ @@ -977,7 +964,7 @@ const AccountNotificationResult = pick({ }); /** - * @private + * @internal */ const ProgramAccountInfoResult = pick({ pubkey: PublicKeyFromString, @@ -993,7 +980,7 @@ const ProgramAccountNotificationResult = pick({ }); /** - * @private + * @internal */ const SlotInfoResult = pick({ parent: number(), @@ -1080,7 +1067,7 @@ const GetSignatureStatusesRpcResult = jsonRpcResultAndContext( const GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number()); /** - * @private + * @internal */ const ConfirmedTransactionResult = pick({ signatures: array(string()), @@ -1154,7 +1141,7 @@ const ParsedOrRawInstruction = coerce( ); /** - * @private + * @internal */ const ParsedConfirmedTransactionResult = pick({ signatures: array(string()), @@ -1178,7 +1165,7 @@ const TokenBalanceResult = pick({ }); /** - * @private + * @internal */ const ConfirmedTransactionMetaResult = pick({ err: TransactionErrorResult, @@ -1207,7 +1194,7 @@ const ConfirmedTransactionMetaResult = pick({ }); /** - * @private + * @internal */ const ParsedConfirmedTransactionMetaResult = pick({ err: TransactionErrorResult, @@ -1344,9 +1331,9 @@ const SendTransactionRpcResult = jsonRpcResult(string()); * @property {number} root The root block of the current slot's fork */ export type SlotInfo = { - slot: number, - parent: number, - root: number, + slot: number; + parent: number; + root: number; }; /** @@ -1357,10 +1344,10 @@ export type SlotInfo = { * @property {any} parsed Parsed account data * @property {number} space Space used by account data */ -type ParsedAccountData = { - program: string, - parsed: any, - space: number, +export type ParsedAccountData = { + program: string; + parsed: any; + space: number; }; /** @@ -1371,10 +1358,10 @@ type ParsedAccountData = { * @property {number} active: stake active during the epoch * @property {number} inactive: stake inactive during the epoch */ -type StakeActivationData = { - state: 'active' | 'inactive' | 'activating' | 'deactivating', - active: number, - inactive: number, +export type StakeActivationData = { + state: 'active' | 'inactive' | 'activating' | 'deactivating'; + active: number; + inactive: number; }; /** @@ -1386,11 +1373,11 @@ type StakeActivationData = { * @property {T} data Optional data assigned to the account * @property {boolean} executable `true` if this account's data contains a loaded program */ -type AccountInfo = { - executable: boolean, - owner: PublicKey, - lamports: number, - data: T, +export type AccountInfo = { + executable: boolean; + owner: PublicKey; + lamports: number; + data: T; }; /** @@ -1401,8 +1388,8 @@ type AccountInfo = { * @property {AccountInfo} accountInfo */ export type KeyedAccountInfo = { - accountId: PublicKey, - accountInfo: AccountInfo, + accountId: PublicKey; + accountInfo: AccountInfo; }; /** @@ -1414,18 +1401,18 @@ export type AccountChangeCallback = ( ) => void; /** - * @private + * @internal */ type SubscriptionId = 'subscribing' | number; /** - * @private + * @internal */ type AccountSubscriptionInfo = { - publicKey: string, // PublicKey of the account as a base 58 string - callback: AccountChangeCallback, - commitment: ?Commitment, - subscriptionId: ?SubscriptionId, // null when there's no current server subscription id + publicKey: string; // PublicKey of the account as a base 58 string + callback: AccountChangeCallback; + commitment?: Commitment; + subscriptionId: SubscriptionId | null; // null when there's no current server subscription id }; /** @@ -1437,13 +1424,13 @@ export type ProgramAccountChangeCallback = ( ) => void; /** - * @private + * @internal */ type ProgramAccountSubscriptionInfo = { - programId: string, // PublicKey of the program as a base 58 string - callback: ProgramAccountChangeCallback, - commitment: ?Commitment, - subscriptionId: ?SubscriptionId, // null when there's no current server subscription id + programId: string; // PublicKey of the program as a base 58 string + callback: ProgramAccountChangeCallback; + commitment?: Commitment; + subscriptionId: SubscriptionId | null; // null when there's no current server subscription id }; /** @@ -1452,11 +1439,11 @@ type ProgramAccountSubscriptionInfo = { export type SlotChangeCallback = (slotInfo: SlotInfo) => void; /** - * @private + * @internal */ type SlotSubscriptionInfo = { - callback: SlotChangeCallback, - subscriptionId: ?SubscriptionId, // null when there's no current server subscription id + callback: SlotChangeCallback; + subscriptionId: SubscriptionId | null; // null when there's no current server subscription id }; /** @@ -1468,13 +1455,13 @@ export type SignatureResultCallback = ( ) => void; /** - * @private + * @internal */ type SignatureSubscriptionInfo = { - signature: TransactionSignature, // TransactionSignature as a base 58 string - callback: SignatureResultCallback, - commitment: ?Commitment, - subscriptionId: ?SubscriptionId, // null when there's no current server subscription id + signature: TransactionSignature; // TransactionSignature as a base 58 string + callback: SignatureResultCallback; + commitment?: Commitment; + subscriptionId: SubscriptionId | null; // null when there's no current server subscription id }; /** @@ -1483,11 +1470,11 @@ type SignatureSubscriptionInfo = { export type RootChangeCallback = (root: number) => void; /** - * @private + * @internal */ type RootSubscriptionInfo = { - callback: RootChangeCallback, - subscriptionId: ?SubscriptionId, // null when there's no current server subscription id + callback: RootChangeCallback; + subscriptionId: SubscriptionId | null; // null when there's no current server subscription id }; /** @@ -1495,9 +1482,9 @@ type RootSubscriptionInfo = { * * @typedef {Object} SignatureResult */ -export type SignatureResult = {| - err: TransactionError | null, -|}; +export type SignatureResult = { + err: TransactionError | null; +}; /** * Transaction error @@ -1521,18 +1508,16 @@ export type TransactionConfirmationStatus = /** * Signature status - * - * @typedef {Object} SignatureStatus - * @property {number} slot when the transaction was processed - * @property {number | null} confirmations the number of blocks that have been confirmed and voted on in the fork containing `slot` (TODO) - * @property {TransactionError | null} err error, if any - * @property {?TransactionConfirmationStatus} confirmationStatus the transaction's cluster confirmation status, if data available. Possible responses: `processed`, `confirmed`, `finalized` */ export type SignatureStatus = { - slot: number, - confirmations: number | null, - err: TransactionError | null, - confirmationStatus?: TransactionConfirmationStatus, + /** when the transaction was processed */ + slot: number; + /** the number of blocks that have been confirmed and voted on in the fork containing `slot` */ + confirmations: number | null; + /** transaction error, if any */ + err: TransactionError | null; + /** cluster confirmation status, if data available. Possible responses: `processed`, `confirmed`, `finalized` */ + confirmationStatus?: TransactionConfirmationStatus; }; /** @@ -1546,51 +1531,62 @@ export type SignatureStatus = { * @property {number | null | undefined} blockTime The unix timestamp of when the transaction was processed */ export type ConfirmedSignatureInfo = { - signature: string, - slot: number, - err: TransactionError | null, - memo: string | null, - blockTime?: number | null, + signature: string; + slot: number; + err: TransactionError | null; + memo: string | null; + blockTime?: number | null; }; /** * A connection to a fullnode JSON RPC endpoint */ export class Connection { - _rpcEndpoint: string; - _rpcRequest: RpcRequest; - _rpcWebSocket: RpcWebSocketClient; - _rpcWebSocketConnected: boolean = false; - _rpcWebSocketHeartbeat: IntervalID | null = null; - _rpcWebSocketIdleTimeout: TimeoutID | null = null; + /** @internal */ _commitment?: Commitment; + /** @internal */ _rpcEndpoint: string; + /** @internal */ _rpcRequest: RpcRequest; + /** @internal */ _rpcWebSocket: RpcWebSocketClient; + /** @internal */ _rpcWebSocketConnected: boolean = false; + /** @internal */ _rpcWebSocketHeartbeat: ReturnType< + typeof setInterval + > | null = null; + /** @internal */ _rpcWebSocketIdleTimeout: ReturnType< + typeof setTimeout + > | null = null; - _commitment: ?Commitment; - _blockhashInfo: { - recentBlockhash: Blockhash | null, - lastFetch: Date, - simulatedSignatures: Array, - transactionSignatures: Array, + /** @internal */ _disableBlockhashCaching: boolean = false; + /** @internal */ _pollingBlockhash: boolean = false; + /** @internal */ _blockhashInfo: { + recentBlockhash: Blockhash | null; + lastFetch: number; + simulatedSignatures: Array; + transactionSignatures: Array; }; - _disableBlockhashCaching: boolean = false; - _pollingBlockhash: boolean = false; - _accountChangeSubscriptions: {[number]: AccountSubscriptionInfo} = {}; - _accountChangeSubscriptionCounter: number = 0; - _programAccountChangeSubscriptions: { - [number]: ProgramAccountSubscriptionInfo, + + /** @internal */ _accountChangeSubscriptionCounter: number = 0; + /** @internal */ _accountChangeSubscriptions: { + [id: number]: AccountSubscriptionInfo; } = {}; - _programAccountChangeSubscriptionCounter: number = 0; - _slotSubscriptions: { - [number]: SlotSubscriptionInfo, + + /** @internal */ _programAccountChangeSubscriptionCounter: number = 0; + /** @internal */ _programAccountChangeSubscriptions: { + [id: number]: ProgramAccountSubscriptionInfo; } = {}; - _slotSubscriptionCounter: number = 0; - _signatureSubscriptions: { - [number]: SignatureSubscriptionInfo, + + /** @internal */ _rootSubscriptionCounter: number = 0; + /** @internal */ _rootSubscriptions: { + [id: number]: RootSubscriptionInfo; } = {}; - _signatureSubscriptionCounter: number = 0; - _rootSubscriptions: { - [number]: RootSubscriptionInfo, + + /** @internal */ _signatureSubscriptionCounter: number = 0; + /** @internal */ _signatureSubscriptions: { + [id: number]: SignatureSubscriptionInfo; + } = {}; + + /** @internal */ _slotSubscriptionCounter: number = 0; + /** @internal */ _slotSubscriptions: { + [id: number]: SlotSubscriptionInfo; } = {}; - _rootSubscriptionCounter: number = 0; /** * Establish a JSON RPC connection @@ -1598,7 +1594,7 @@ export class Connection { * @param endpoint URL to the fullnode JSON RPC endpoint * @param commitment optional default commitment level */ - constructor(endpoint: string, commitment: ?Commitment) { + constructor(endpoint: string, commitment?: Commitment) { this._rpcEndpoint = endpoint; let url = urlParse(endpoint); @@ -1608,7 +1604,7 @@ export class Connection { this._commitment = commitment; this._blockhashInfo = { recentBlockhash: null, - lastFetch: new Date(0), + lastFetch: 0, transactionSignatures: [], simulatedSignatures: [], }; @@ -1656,7 +1652,7 @@ export class Connection { /** * The default commitment used for requests */ - get commitment(): ?Commitment { + get commitment(): Commitment | undefined { return this._commitment; } @@ -1665,12 +1661,12 @@ export class Connection { */ async getBalanceAndContext( publicKey: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { const args = this._buildArgs([publicKey.toBase58()], commitment); const unsafeRes = await this._rpcRequest('getBalance', args); const res = create(unsafeRes, jsonRpcResultAndContext(number())); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get balance for ' + publicKey.toBase58() + @@ -1686,7 +1682,7 @@ export class Connection { */ async getBalance( publicKey: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise { return await this.getBalanceAndContext(publicKey, commitment) .then(x => x.value) @@ -1703,7 +1699,7 @@ export class Connection { async getBlockTime(slot: number): Promise { const unsafeRes = await this._rpcRequest('getBlockTime', [slot]); const res = create(unsafeRes, jsonRpcResult(nullable(number()))); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get block time for slot ' + slot + ': ' + res.error.message, ); @@ -1718,7 +1714,7 @@ export class Connection { async getMinimumLedgerSlot(): Promise { const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []); const res = create(unsafeRes, jsonRpcResult(number())); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get minimum ledger slot: ' + res.error.message, ); @@ -1732,7 +1728,7 @@ export class Connection { async getFirstAvailableBlock(): Promise { const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []); const res = create(unsafeRes, SlotRpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get first available block: ' + res.error.message, ); @@ -1744,12 +1740,12 @@ export class Connection { * Fetch information about the current supply */ async getSupply( - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getSupply', args); const res = create(unsafeRes, GetSupplyRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get supply: ' + res.error.message); } return res.result; @@ -1760,12 +1756,12 @@ export class Connection { */ async getTokenSupply( tokenMintAddress: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { const args = this._buildArgs([tokenMintAddress.toBase58()], commitment); const unsafeRes = await this._rpcRequest('getTokenSupply', args); const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); - if (res.error) { + if ('error' in res) { throw new Error('failed to get token supply: ' + res.error.message); } return res.result; @@ -1776,12 +1772,12 @@ export class Connection { */ async getTokenAccountBalance( tokenAddress: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { const args = this._buildArgs([tokenAddress.toBase58()], commitment); const unsafeRes = await this._rpcRequest('getTokenAccountBalance', args); const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get token account balance: ' + res.error.message, ); @@ -1797,14 +1793,14 @@ export class Connection { async getTokenAccountsByOwner( ownerAddress: PublicKey, filter: TokenAccountsFilter, - commitment: ?Commitment, + commitment?: Commitment, ): Promise< RpcResponseAndContext< - Array<{pubkey: PublicKey, account: AccountInfo}>, - >, + Array<{pubkey: PublicKey; account: AccountInfo}> + > > { - let _args = [ownerAddress.toBase58()]; - if (filter.mint) { + let _args: any[] = [ownerAddress.toBase58()]; + if ('mint' in filter) { _args.push({mint: filter.mint.toBase58()}); } else { _args.push({programId: filter.programId.toBase58()}); @@ -1813,7 +1809,7 @@ export class Connection { const args = this._buildArgs(_args, commitment, 'base64'); const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args); const res = create(unsafeRes, GetTokenAccountsByOwner); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get token accounts owned by account ' + ownerAddress.toBase58() + @@ -1832,14 +1828,14 @@ export class Connection { async getParsedTokenAccountsByOwner( ownerAddress: PublicKey, filter: TokenAccountsFilter, - commitment: ?Commitment, + commitment?: Commitment, ): Promise< RpcResponseAndContext< - Array<{pubkey: PublicKey, account: AccountInfo}>, - >, + Array<{pubkey: PublicKey; account: AccountInfo}> + > > { - let _args = [ownerAddress.toBase58()]; - if (filter.mint) { + let _args: any[] = [ownerAddress.toBase58()]; + if ('mint' in filter) { _args.push({mint: filter.mint.toBase58()}); } else { _args.push({programId: filter.programId.toBase58()}); @@ -1848,7 +1844,7 @@ export class Connection { const args = this._buildArgs(_args, commitment, 'jsonParsed'); const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args); const res = create(unsafeRes, GetParsedTokenAccountsByOwner); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get token accounts owned by account ' + ownerAddress.toBase58() + @@ -1863,7 +1859,7 @@ export class Connection { * Fetch the 20 largest accounts with their current balances */ async getLargestAccounts( - config: ?GetLargestAccountsConfig, + config?: GetLargestAccountsConfig, ): Promise>> { const arg = { ...config, @@ -1872,7 +1868,7 @@ export class Connection { const args = arg.filter || arg.commitment ? [arg] : []; const unsafeRes = await this._rpcRequest('getLargestAccounts', args); const res = create(unsafeRes, GetLargestAccountsRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get largest accounts: ' + res.error.message); } return res.result; @@ -1884,12 +1880,12 @@ export class Connection { */ async getTokenLargestAccounts( mintAddress: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise>> { const args = this._buildArgs([mintAddress.toBase58()], commitment); const unsafeRes = await this._rpcRequest('getTokenLargestAccounts', args); const res = create(unsafeRes, GetTokenLargestAccountsResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get token largest accounts: ' + res.error.message, ); @@ -1902,7 +1898,7 @@ export class Connection { */ async getAccountInfoAndContext( publicKey: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise | null>> { const args = this._buildArgs([publicKey.toBase58()], commitment, 'base64'); const unsafeRes = await this._rpcRequest('getAccountInfo', args); @@ -1910,7 +1906,7 @@ export class Connection { unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult)), ); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get info about account ' + publicKey.toBase58() + @@ -1926,9 +1922,9 @@ export class Connection { */ async getParsedAccountInfo( publicKey: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise< - RpcResponseAndContext | null>, + RpcResponseAndContext | null> > { const args = this._buildArgs( [publicKey.toBase58()], @@ -1940,7 +1936,7 @@ export class Connection { unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)), ); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get info about account ' + publicKey.toBase58() + @@ -1956,7 +1952,7 @@ export class Connection { */ async getAccountInfo( publicKey: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise | null> { try { const res = await this.getAccountInfoAndContext(publicKey, commitment); @@ -1973,8 +1969,8 @@ export class Connection { */ async getStakeActivation( publicKey: PublicKey, - commitment: ?Commitment, - epoch: ?number, + commitment?: Commitment, + epoch?: number, ): Promise { const args = this._buildArgs( [publicKey.toBase58()], @@ -1985,7 +1981,7 @@ export class Connection { const unsafeRes = await this._rpcRequest('getStakeActivation', args); const res = create(unsafeRes, jsonRpcResult(StakeActivationResult)); - if (res.error) { + if ('error' in res) { throw new Error( `failed to get Stake Activation ${publicKey.toBase58()}: ${ res.error.message @@ -2002,12 +1998,12 @@ export class Connection { */ async getProgramAccounts( programId: PublicKey, - commitment: ?Commitment, - ): Promise}>> { + commitment?: Commitment, + ): Promise}>> { const args = this._buildArgs([programId.toBase58()], commitment, 'base64'); const unsafeRes = await this._rpcRequest('getProgramAccounts', args); const res = create(unsafeRes, jsonRpcResult(array(KeyedAccountInfoResult))); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get accounts owned by program ' + programId.toBase58() + @@ -2025,12 +2021,12 @@ export class Connection { */ async getParsedProgramAccounts( programId: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise< Array<{ - pubkey: PublicKey, - account: AccountInfo, - }>, + pubkey: PublicKey; + account: AccountInfo; + }> > { const args = this._buildArgs( [programId.toBase58()], @@ -2042,7 +2038,7 @@ export class Connection { unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult)), ); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get accounts owned by program ' + programId.toBase58() + @@ -2058,7 +2054,7 @@ export class Connection { */ async confirmTransaction( signature: TransactionSignature, - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { let decodedSignature; try { @@ -2078,13 +2074,13 @@ export class Connection { try { subscriptionId = this.onSignature( signature, - (result, context) => { + (result: SignatureResult, context: Context) => { subscriptionId = undefined; response = { context, value: result, }; - resolve(); + resolve(null); }, subscriptionCommitment, ); @@ -2135,7 +2131,7 @@ export class Connection { async getClusterNodes(): Promise> { const unsafeRes = await this._rpcRequest('getClusterNodes', []); const res = create(unsafeRes, jsonRpcResult(array(ContactInfoResult))); - if (res.error) { + if ('error' in res) { throw new Error('failed to get cluster nodes: ' + res.error.message); } return res.result; @@ -2144,11 +2140,11 @@ export class Connection { /** * Return the list of nodes that are currently participating in the cluster */ - async getVoteAccounts(commitment: ?Commitment): Promise { + async getVoteAccounts(commitment?: Commitment): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getVoteAccounts', args); const res = create(unsafeRes, GetVoteAccounts); - if (res.error) { + if ('error' in res) { throw new Error('failed to get vote accounts: ' + res.error.message); } return res.result; @@ -2157,11 +2153,11 @@ export class Connection { /** * Fetch the current slot that the node is processing */ - async getSlot(commitment: ?Commitment): Promise { + async getSlot(commitment?: Commitment): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getSlot', args); const res = create(unsafeRes, jsonRpcResult(number())); - if (res.error) { + if ('error' in res) { throw new Error('failed to get slot: ' + res.error.message); } return res.result; @@ -2170,11 +2166,11 @@ export class Connection { /** * Fetch the current slot leader of the cluster */ - async getSlotLeader(commitment: ?Commitment): Promise { + async getSlotLeader(commitment?: Commitment): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getSlotLeader', args); const res = create(unsafeRes, jsonRpcResult(string())); - if (res.error) { + if ('error' in res) { throw new Error('failed to get slot leader: ' + res.error.message); } return res.result; @@ -2185,7 +2181,7 @@ export class Connection { */ async getSignatureStatus( signature: TransactionSignature, - config: ?SignatureStatusConfig, + config?: SignatureStatusConfig, ): Promise> { const {context, value: values} = await this.getSignatureStatuses( [signature], @@ -2201,15 +2197,15 @@ export class Connection { */ async getSignatureStatuses( signatures: Array, - config: ?SignatureStatusConfig, + config?: SignatureStatusConfig, ): Promise>> { - const params = [signatures]; + const params: any[] = [signatures]; if (config) { params.push(config); } const unsafeRes = await this._rpcRequest('getSignatureStatuses', params); const res = create(unsafeRes, GetSignatureStatusesRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get signature status: ' + res.error.message); } return res.result; @@ -2218,11 +2214,11 @@ export class Connection { /** * Fetch the current transaction count of the cluster */ - async getTransactionCount(commitment: ?Commitment): Promise { + async getTransactionCount(commitment?: Commitment): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getTransactionCount', args); const res = create(unsafeRes, jsonRpcResult(number())); - if (res.error) { + if ('error' in res) { throw new Error('failed to get transaction count: ' + res.error.message); } return res.result; @@ -2231,11 +2227,11 @@ export class Connection { /** * Fetch the current total currency supply of the cluster in lamports */ - async getTotalSupply(commitment: ?Commitment): Promise { + async getTotalSupply(commitment?: Commitment): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getTotalSupply', args); const res = create(unsafeRes, jsonRpcResult(number())); - if (res.error) { + if ('error' in res) { throw new Error('failed to get total supply: ' + res.error.message); } return res.result; @@ -2245,12 +2241,12 @@ export class Connection { * Fetch the cluster InflationGovernor parameters */ async getInflationGovernor( - commitment: ?Commitment, + commitment?: Commitment, ): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getInflationGovernor', args); const res = create(unsafeRes, GetInflationGovernorRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get inflation: ' + res.error.message); } return res.result; @@ -2259,11 +2255,11 @@ export class Connection { /** * Fetch the Epoch Info parameters */ - async getEpochInfo(commitment: ?Commitment): Promise { + async getEpochInfo(commitment?: Commitment): Promise { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getEpochInfo', args); const res = create(unsafeRes, GetEpochInfoRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get epoch info: ' + res.error.message); } return res.result; @@ -2275,7 +2271,7 @@ export class Connection { async getEpochSchedule(): Promise { const unsafeRes = await this._rpcRequest('getEpochSchedule', []); const res = create(unsafeRes, GetEpochScheduleRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get epoch schedule: ' + res.error.message); } return res.result; @@ -2288,7 +2284,7 @@ export class Connection { async getLeaderSchedule(): Promise { const unsafeRes = await this._rpcRequest('getLeaderSchedule', []); const res = create(unsafeRes, GetLeaderScheduleRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get leader schedule: ' + res.error.message); } return res.result; @@ -2300,7 +2296,7 @@ export class Connection { */ async getMinimumBalanceForRentExemption( dataLength: number, - commitment: ?Commitment, + commitment?: Commitment, ): Promise { const args = this._buildArgs([dataLength], commitment); const unsafeRes = await this._rpcRequest( @@ -2308,7 +2304,7 @@ export class Connection { args, ); const res = create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult); - if (res.error) { + if ('error' in res) { console.warn('Unable to fetch minimum balance for rent exemption'); return 0; } @@ -2320,14 +2316,14 @@ export class Connection { * @return {Promise>} */ async getRecentBlockhashAndContext( - commitment: ?Commitment, + commitment?: Commitment, ): Promise< - RpcResponseAndContext<{blockhash: Blockhash, feeCalculator: FeeCalculator}>, + RpcResponseAndContext<{blockhash: Blockhash; feeCalculator: FeeCalculator}> > { const args = this._buildArgs([], commitment); const unsafeRes = await this._rpcRequest('getRecentBlockhash', args); const res = create(unsafeRes, GetRecentBlockhashAndContextRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get recent blockhash: ' + res.error.message); } return res.result; @@ -2338,7 +2334,7 @@ export class Connection { * @return {Promise>} */ async getRecentPerformanceSamples( - limit: ?number, + limit?: number, ): Promise> { const args = this._buildArgs(limit ? [limit] : []); const unsafeRes = await this._rpcRequest( @@ -2346,7 +2342,7 @@ export class Connection { args, ); const res = create(unsafeRes, GetRecentPerformanceSamplesRpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get recent performance samples: ' + res.error.message, ); @@ -2360,7 +2356,7 @@ export class Connection { */ async getFeeCalculatorForBlockhash( blockhash: Blockhash, - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { const args = this._buildArgs([blockhash], commitment); const unsafeRes = await this._rpcRequest( @@ -2369,13 +2365,13 @@ export class Connection { ); const res = create(unsafeRes, GetFeeCalculatorRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get fee calculator: ' + res.error.message); } const {context, value} = res.result; return { context, - value: value.feeCalculator, + value: value !== null ? value.feeCalculator : null, }; } @@ -2384,8 +2380,8 @@ export class Connection { * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>} */ async getRecentBlockhash( - commitment: ?Commitment, - ): Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}> { + commitment?: Commitment, + ): Promise<{blockhash: Blockhash; feeCalculator: FeeCalculator}> { try { const res = await this.getRecentBlockhashAndContext(commitment); return res.value; @@ -2400,7 +2396,7 @@ export class Connection { async getVersion(): Promise { const unsafeRes = await this._rpcRequest('getVersion', []); const res = create(unsafeRes, jsonRpcResult(VersionResult)); - if (res.error) { + if ('error' in res) { throw new Error('failed to get version: ' + res.error.message); } return res.result; @@ -2413,7 +2409,7 @@ export class Connection { async getConfirmedBlock(slot: number): Promise { const unsafeRes = await this._rpcRequest('getConfirmedBlock', [slot]); const res = create(unsafeRes, GetConfirmedBlockRpcResult); - if (res.error) { + if ('error' in res) { throw new Error('failed to get confirmed block: ' + res.error.message); } const result = res.result; @@ -2433,7 +2429,7 @@ export class Connection { signature, ]); const res = create(unsafeRes, GetConfirmedTransactionRpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get confirmed transaction: ' + res.error.message, ); @@ -2452,7 +2448,7 @@ export class Connection { 'jsonParsed', ]); const res = create(unsafeRes, GetParsedConfirmedTransactionRpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get confirmed transaction: ' + res.error.message, ); @@ -2478,7 +2474,7 @@ export class Connection { [address.toBase58(), startSlot, endSlot], ); const res = create(unsafeRes, GetConfirmedSignaturesForAddressRpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get confirmed signatures for address: ' + res.error.message, ); @@ -2496,14 +2492,14 @@ export class Connection { */ async getConfirmedSignaturesForAddress2( address: PublicKey, - options: ?ConfirmedSignaturesForAddress2Options, + options?: ConfirmedSignaturesForAddress2Options, ): Promise> { const unsafeRes = await this._rpcRequest( 'getConfirmedSignaturesForAddress2', [address.toBase58(), options], ); const res = create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'failed to get confirmed signatures for address: ' + res.error.message, ); @@ -2516,7 +2512,7 @@ export class Connection { */ async getNonceAndContext( nonceAccount: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise> { const {context, value: accountInfo} = await this.getAccountInfoAndContext( nonceAccount, @@ -2539,7 +2535,7 @@ export class Connection { */ async getNonce( nonceAccount: PublicKey, - commitment: ?Commitment, + commitment?: Commitment, ): Promise { return await this.getNonceAndContext(nonceAccount, commitment) .then(x => x.value) @@ -2565,7 +2561,7 @@ export class Connection { amount, ]); const res = create(unsafeRes, RequestAirdropRpcResult); - if (res.error) { + if ('error' in res) { throw new Error( 'airdrop to ' + to.toBase58() + ' failed: ' + res.error.message, ); @@ -2573,6 +2569,9 @@ export class Connection { return res.result; } + /** + * @internal + */ async _recentBlockhash(disableCache: boolean): Promise { if (!disableCache) { // Wait for polling to finish @@ -2580,9 +2579,9 @@ export class Connection { await sleep(100); } // Attempt to use a recent blockhash for up to 30 seconds - const expired = - Date.now() - this._blockhashInfo.lastFetch >= - BLOCKHASH_CACHE_TIMEOUT_MS; + const BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000; + const timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch; + const expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS; if (this._blockhashInfo.recentBlockhash !== null && !expired) { return this._blockhashInfo.recentBlockhash; } @@ -2591,6 +2590,9 @@ export class Connection { return await this._pollNewBlockhash(); } + /** + * @internal + */ async _pollNewBlockhash(): Promise { this._pollingBlockhash = true; try { @@ -2601,7 +2603,7 @@ export class Connection { if (this._blockhashInfo.recentBlockhash != blockhash) { this._blockhashInfo = { recentBlockhash: blockhash, - lastFetch: new Date(), + lastFetch: Date.now(), transactionSignatures: [], simulatedSignatures: [], }; @@ -2663,15 +2665,15 @@ export class Connection { encoding: 'base64', commitment: this.commitment, }; - const args = [encodedTransaction, config]; if (signers) { config.sigVerify = true; } + const args = [encodedTransaction, config]; const unsafeRes = await this._rpcRequest('simulateTransaction', args); const res = create(unsafeRes, SimulatedTransactionResponseStruct); - if (res.error) { + if ('error' in res) { throw new Error('failed to simulate transaction: ' + res.error.message); } return res.result; @@ -2718,7 +2720,7 @@ export class Connection { */ async sendRawTransaction( rawTransaction: Buffer | Uint8Array | Array, - options: ?SendOptions, + options?: SendOptions, ): Promise { const encodedTransaction = toBuffer(rawTransaction).toString('base64'); const result = await this.sendEncodedTransaction( @@ -2734,10 +2736,9 @@ export class Connection { */ async sendEncodedTransaction( encodedTransaction: string, - options: ?SendOptions, + options?: SendOptions, ): Promise { const config: any = {encoding: 'base64'}; - const args = [encodedTransaction, config]; const skipPreflight = options && options.skipPreflight; const preflightCommitment = (options && options.preflightCommitment) || this.commitment; @@ -2749,10 +2750,11 @@ export class Connection { config.preflightCommitment = preflightCommitment; } + const args = [encodedTransaction, config]; const unsafeRes = await this._rpcRequest('sendTransaction', args); const res = create(unsafeRes, SendTransactionRpcResult); - if (res.error) { - if (res.error.data) { + if ('error' in res) { + if ('data' in res.error) { const logs = res.error.data.logs; if (logs && Array.isArray(logs)) { const traceIndent = '\n '; @@ -2766,7 +2768,7 @@ export class Connection { } /** - * @private + * @internal */ _wsOnOpen() { this._rpcWebSocketConnected = true; @@ -2778,18 +2780,20 @@ export class Connection { } /** - * @private + * @internal */ _wsOnError(err: Error) { console.error('ws error:', err.message); } /** - * @private + * @internal */ _wsOnClose(code: number) { - clearInterval(this._rpcWebSocketHeartbeat); - this._rpcWebSocketHeartbeat = null; + if (this._rpcWebSocketHeartbeat) { + clearInterval(this._rpcWebSocketHeartbeat); + this._rpcWebSocketHeartbeat = null; + } if (code === 1000) { // explicit close, check if any subscriptions have been made since close @@ -2802,18 +2806,18 @@ export class Connection { } /** - * @private + * @internal */ - async _subscribe( - sub: SubInfo, + async _subscribe( + sub: {subscriptionId: SubscriptionId | null}, rpcMethod: string, - rpcArgs: RpcArgs, + rpcArgs: IWSRequestParams, ) { if (sub.subscriptionId == null) { sub.subscriptionId = 'subscribing'; try { const id = await this._rpcWebSocket.call(rpcMethod, rpcArgs); - if (sub.subscriptionId === 'subscribing') { + if (typeof id === 'number' && sub.subscriptionId === 'subscribing') { // eslint-disable-next-line require-atomic-updates sub.subscriptionId = id; } @@ -2828,10 +2832,10 @@ export class Connection { } /** - * @private + * @internal */ - async _unsubscribe( - sub: SubInfo, + async _unsubscribe( + sub: {subscriptionId: SubscriptionId | null}, rpcMethod: string, ) { const subscriptionId = sub.subscriptionId; @@ -2846,28 +2850,28 @@ export class Connection { } /** - * @private + * @internal */ _resetSubscriptions() { - (Object.values(this._accountChangeSubscriptions): any).forEach( + Object.values(this._accountChangeSubscriptions).forEach( s => (s.subscriptionId = null), ); - (Object.values(this._programAccountChangeSubscriptions): any).forEach( + Object.values(this._programAccountChangeSubscriptions).forEach( s => (s.subscriptionId = null), ); - (Object.values(this._signatureSubscriptions): any).forEach( + Object.values(this._signatureSubscriptions).forEach( s => (s.subscriptionId = null), ); - (Object.values(this._slotSubscriptions): any).forEach( + Object.values(this._slotSubscriptions).forEach( s => (s.subscriptionId = null), ); - (Object.values(this._rootSubscriptions): any).forEach( + Object.values(this._rootSubscriptions).forEach( s => (s.subscriptionId = null), ); } /** - * @private + * @internal */ _updateSubscriptions() { const accountKeys = Object.keys(this._accountChangeSubscriptions).map( @@ -2946,19 +2950,14 @@ export class Connection { } /** - * @private + * @internal */ - _wsOnAccountNotification(notification: Object) { + _wsOnAccountNotification(notification: object) { const res = create(notification, AccountNotificationResult); - if (res.error) { - throw new Error('account notification failed: ' + res.error.message); - } - const keys = Object.keys(this._accountChangeSubscriptions).map(Number); - for (let id of keys) { - const sub = this._accountChangeSubscriptions[id]; + for (const sub of Object.values(this._accountChangeSubscriptions)) { if (sub.subscriptionId === res.subscription) { sub.callback(res.result.value, res.result.context); - return true; + return; } } } @@ -2974,7 +2973,7 @@ export class Connection { onAccountChange( publicKey: PublicKey, callback: AccountChangeCallback, - commitment: ?Commitment, + commitment?: Commitment, ): number { const id = ++this._accountChangeSubscriptionCounter; this._accountChangeSubscriptions[id] = { @@ -3004,20 +3003,11 @@ export class Connection { } /** - * @private + * @internal */ _wsOnProgramAccountNotification(notification: Object) { const res = create(notification, ProgramAccountNotificationResult); - if (res.error) { - throw new Error( - 'program account notification failed: ' + res.error.message, - ); - } - const keys = Object.keys(this._programAccountChangeSubscriptions).map( - Number, - ); - for (let id of keys) { - const sub = this._programAccountChangeSubscriptions[id]; + for (const sub of Object.values(this._programAccountChangeSubscriptions)) { if (sub.subscriptionId === res.subscription) { const {value, context} = res.result; sub.callback( @@ -3027,7 +3017,7 @@ export class Connection { }, context, ); - return true; + return; } } } @@ -3044,7 +3034,7 @@ export class Connection { onProgramAccountChange( programId: PublicKey, callback: ProgramAccountChangeCallback, - commitment: ?Commitment, + commitment?: Commitment, ): number { const id = ++this._programAccountChangeSubscriptionCounter; this._programAccountChangeSubscriptions[id] = { @@ -3074,19 +3064,14 @@ export class Connection { } /** - * @private + * @internal */ _wsOnSlotNotification(notification: Object) { const res = create(notification, SlotNotificationResult); - if (res.error) { - throw new Error('slot notification failed: ' + res.error.message); - } - const keys = Object.keys(this._slotSubscriptions).map(Number); - for (let id of keys) { - const sub = this._slotSubscriptions[id]; + for (const sub of Object.values(this._slotSubscriptions)) { if (sub.subscriptionId === res.subscription) { sub.callback(res.result); - return true; + return; } } } @@ -3123,9 +3108,12 @@ export class Connection { } } + /** + * @internal + */ _buildArgs( args: Array, - override: ?Commitment, + override?: Commitment, encoding?: 'jsonParsed' | 'base64', extra?: any, ): Array { @@ -3147,20 +3135,15 @@ export class Connection { } /** - * @private + * @internal */ _wsOnSignatureNotification(notification: Object) { const res = create(notification, SignatureNotificationResult); - if (res.error) { - throw new Error('signature notification failed: ' + res.error.message); - } - const keys = Object.keys(this._signatureSubscriptions).map(Number); - for (let id of keys) { - const sub = this._signatureSubscriptions[id]; + for (const [id, sub] of Object.entries(this._signatureSubscriptions)) { if (sub.subscriptionId === res.subscription) { // Signatures subscriptions are auto-removed by the RPC service so // no need to explicitly send an unsubscribe message - delete this._signatureSubscriptions[id]; + delete this._signatureSubscriptions[Number(id)]; this._updateSubscriptions(); sub.callback(res.result.value, res.result.context); return; @@ -3179,7 +3162,7 @@ export class Connection { onSignature( signature: TransactionSignature, callback: SignatureResultCallback, - commitment: ?Commitment, + commitment?: Commitment, ): number { const id = ++this._signatureSubscriptionCounter; this._signatureSubscriptions[id] = { @@ -3209,19 +3192,14 @@ export class Connection { } /** - * @private + * @internal */ _wsOnRootNotification(notification: Object) { const res = create(notification, RootNotificationResult); - if (res.error) { - throw new Error('root notification failed: ' + res.error.message); - } - const keys = Object.keys(this._rootSubscriptions).map(Number); - for (let id of keys) { - const sub = this._rootSubscriptions[id]; + for (const sub of Object.values(this._rootSubscriptions)) { if (sub.subscriptionId === res.subscription) { sub.callback(res.result); - return true; + return; } } } diff --git a/web3.js/src/fee-calculator.js b/web3.js/src/fee-calculator.ts similarity index 55% rename from web3.js/src/fee-calculator.js rename to web3.js/src/fee-calculator.ts index c8f19491f4..c229816da6 100644 --- a/web3.js/src/fee-calculator.js +++ b/web3.js/src/fee-calculator.ts @@ -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; +} diff --git a/web3.js/src/index.js b/web3.js/src/index.js deleted file mode 100644 index db4d3897cf..0000000000 --- a/web3.js/src/index.js +++ /dev/null @@ -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; diff --git a/web3.js/src/index.ts b/web3.js/src/index.ts new file mode 100644 index 0000000000..5784d58faa --- /dev/null +++ b/web3.js/src/index.ts @@ -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; diff --git a/web3.js/src/instruction.js b/web3.js/src/instruction.ts similarity index 84% rename from web3.js/src/instruction.js rename to web3.js/src/instruction.ts index 1ce4cfff0d..d8fec7b763 100644 --- a/web3.js/src/instruction.js +++ b/web3.js/src/instruction.ts @@ -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); diff --git a/web3.js/src/layout.js b/web3.js/src/layout.ts similarity index 88% rename from web3.js/src/layout.js rename to web3.js/src/layout.ts index 1e45fc4134..61aba540bb 100644 --- a/web3.js/src/layout.js +++ b/web3.js/src/layout.ts @@ -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') { diff --git a/web3.js/src/loader.js b/web3.js/src/loader.ts similarity index 99% rename from web3.js/src/loader.js rename to web3.js/src/loader.ts index 62e7cd81b0..93bc7b040c 100644 --- a/web3.js/src/loader.js +++ b/web3.js/src/loader.ts @@ -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 */ diff --git a/web3.js/src/message.js b/web3.js/src/message.ts similarity index 86% rename from web3.js/src/message.js rename to web3.js/src/message.ts index 734164a6b9..17a23179c5 100644 --- a/web3.js/src/message.js +++ b/web3.js/src/message.ts @@ -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 = { diff --git a/web3.js/src/nonce-account.js b/web3.js/src/nonce-account.ts similarity index 69% rename from web3.js/src/nonce-account.js rename to web3.js/src/nonce-account.ts index 99d0d6e750..4de457fae8 100644 --- a/web3.js/src/nonce-account.js +++ b/web3.js/src/nonce-account.ts @@ -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, ): 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, + }); } } diff --git a/web3.js/src/publickey.js b/web3.js/src/publickey.ts similarity index 95% rename from web3.js/src/publickey.js rename to web3.js/src/publickey.ts index c5573fa079..e459d21985 100644 --- a/web3.js/src/publickey.js +++ b/web3.js/src/publickey.ts @@ -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) { 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, programId: PublicKey, - ): Promise { + ): 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); diff --git a/web3.js/src/secp256k1-program.js b/web3.js/src/secp256k1-program.ts similarity index 89% rename from web3.js/src/secp256k1-program.js rename to web3.js/src/secp256k1-program.ts index 325fea2873..476ebfbb11 100644 --- a/web3.js/src/secp256k1-program.js +++ b/web3.js/src/secp256k1-program.ts @@ -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} signature * @property {number} recoveryId */ -export type CreateSecp256k1InstructionWithPublicKeyParams = {| - publicKey: Buffer | Uint8Array | Array, - message: Buffer | Uint8Array | Array, - signature: Buffer | Uint8Array | Array, - recoveryId: number, -|}; +export type CreateSecp256k1InstructionWithPublicKeyParams = { + publicKey: Buffer | Uint8Array | Array; + message: Buffer | Uint8Array | Array; + signature: Buffer | Uint8Array | Array; + recoveryId: number; +}; /** * Params for creating an secp256k1 instruction using an Ethereum address @@ -40,12 +38,12 @@ export type CreateSecp256k1InstructionWithPublicKeyParams = {| * @property {Buffer | Uint8Array | Array} signature * @property {number} recoveryId */ -export type CreateSecp256k1InstructionWithEthAddressParams = {| - ethAddress: Buffer | Uint8Array | Array | string, - message: Buffer | Uint8Array | Array, - signature: Buffer | Uint8Array | Array, - recoveryId: number, -|}; +export type CreateSecp256k1InstructionWithEthAddressParams = { + ethAddress: Buffer | Uint8Array | Array | string; + message: Buffer | Uint8Array | Array; + signature: Buffer | Uint8Array | Array; + recoveryId: number; +}; /** * Params for creating an secp256k1 instruction using a private key @@ -53,10 +51,10 @@ export type CreateSecp256k1InstructionWithEthAddressParams = {| * @property {Buffer | Uint8Array | Array} privateKey * @property {Buffer | Uint8Array | Array} message */ -export type CreateSecp256k1InstructionWithPrivateKeyParams = {| - privateKey: Buffer | Uint8Array | Array, - message: Buffer | Uint8Array | Array, -|}; +export type CreateSecp256k1InstructionWithPrivateKeyParams = { + privateKey: Buffer | Uint8Array | Array; + message: Buffer | Uint8Array | Array; +}; 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( diff --git a/web3.js/src/stake-program.js b/web3.js/src/stake-program.ts similarity index 81% rename from web3.js/src/stake-program.js rename to web3.js/src/stake-program.ts index e76d2ddad3..ca61b4cb62 100644 --- a/web3.js/src/stake-program.js +++ b/web3.js/src/stake-program.ts @@ -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, 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; +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 */ diff --git a/web3.js/src/system-program.js b/web3.js/src/system-program.ts similarity index 88% rename from web3.js/src/system-program.js rename to web3.js/src/system-program.ts index 1ba4daf2f5..e3127409e1 100644 --- a/web3.js/src/system-program.js +++ b/web3.js/src/system-program.ts @@ -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, 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; +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(), diff --git a/web3.js/src/sysvar.js b/web3.js/src/sysvar.ts similarity index 98% rename from web3.js/src/sysvar.js rename to web3.js/src/sysvar.ts index 07b4170898..a8ed4af641 100644 --- a/web3.js/src/sysvar.js +++ b/web3.js/src/sysvar.ts @@ -1,4 +1,3 @@ -// @flow import {PublicKey} from './publickey'; export const SYSVAR_CLOCK_PUBKEY = new PublicKey( diff --git a/web3.js/src/timing.js b/web3.js/src/timing.ts similarity index 86% rename from web3.js/src/timing.js rename to web3.js/src/timing.ts index 64b6457ffc..6ba998717e 100644 --- a/web3.js/src/timing.js +++ b/web3.js/src/timing.ts @@ -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; diff --git a/web3.js/src/transaction.js b/web3.js/src/transaction.ts similarity index 95% rename from web3.js/src/transaction.js rename to web3.js/src/transaction.ts index e79475cd46..f3a99728c0 100644 --- a/web3.js/src/transaction.js +++ b/web3.js/src/transaction.ts @@ -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, - programId: PublicKey, - data?: Buffer, -|}; +export type TransactionInstructionCtorFields = { + keys: Array; + 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} signatures One or more signatures * */ -type TransactionCtorFields = {| - recentBlockhash?: Blockhash | null, - nonceInfo?: NonceInformation | null, - feePayer?: PublicKey | null, - signatures?: Array, -|}; +type TransactionCtorFields = { + recentBlockhash?: Blockhash | null; + nonceInfo?: NonceInformation | null; + feePayer?: PublicKey | null; + signatures?: Array; +}; /** * 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) { 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 { 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); diff --git a/web3.js/src/util/cluster.js b/web3.js/src/util/cluster.ts similarity index 96% rename from web3.js/src/util/cluster.js rename to web3.js/src/util/cluster.ts index 2fe3a1157a..bfc913c479 100644 --- a/web3.js/src/util/cluster.js +++ b/web3.js/src/util/cluster.ts @@ -1,8 +1,3 @@ -//@flow - -/** - * @private - */ const endpoint = { http: { devnet: 'http://devnet.solana.com', diff --git a/web3.js/src/util/promise-timeout.js b/web3.js/src/util/promise-timeout.ts similarity index 54% rename from web3.js/src/util/promise-timeout.js rename to web3.js/src/util/promise-timeout.ts index 8219b4e9bb..1d75969550 100644 --- a/web3.js/src/util/promise-timeout.js +++ b/web3.js/src/util/promise-timeout.ts @@ -1,15 +1,13 @@ -// @flow - export function promiseTimeout( promise: Promise, timeoutMs: number, ): Promise { - let timeoutId: TimeoutID; - const timeoutPromise = new Promise(resolve => { + let timeoutId: ReturnType; + const timeoutPromise: Promise = 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; }); diff --git a/web3.js/src/util/send-and-confirm-raw-transaction.js b/web3.js/src/util/send-and-confirm-raw-transaction.ts similarity index 99% rename from web3.js/src/util/send-and-confirm-raw-transaction.js rename to web3.js/src/util/send-and-confirm-raw-transaction.ts index 3e231e481e..23c088d8bb 100644 --- a/web3.js/src/util/send-and-confirm-raw-transaction.js +++ b/web3.js/src/util/send-and-confirm-raw-transaction.ts @@ -1,5 +1,3 @@ -// @flow - import {Connection} from '../connection'; import type {TransactionSignature} from '../transaction'; import type {ConfirmOptions} from '../connection'; diff --git a/web3.js/src/util/send-and-confirm-transaction.js b/web3.js/src/util/send-and-confirm-transaction.ts similarity index 99% rename from web3.js/src/util/send-and-confirm-transaction.js rename to web3.js/src/util/send-and-confirm-transaction.ts index 4f0477a1f3..afaea10928 100644 --- a/web3.js/src/util/send-and-confirm-transaction.js +++ b/web3.js/src/util/send-and-confirm-transaction.ts @@ -1,5 +1,3 @@ -// @flow - import {Connection} from '../connection'; import {Transaction} from '../transaction'; import type {Account} from '../account'; diff --git a/web3.js/src/util/shortvec-encoding.js b/web3.js/src/util/shortvec-encoding.ts similarity index 92% rename from web3.js/src/util/shortvec-encoding.js rename to web3.js/src/util/shortvec-encoding.ts index 80aa431871..ee8c727ee5 100644 --- a/web3.js/src/util/shortvec-encoding.js +++ b/web3.js/src/util/shortvec-encoding.ts @@ -1,10 +1,8 @@ -// @flow - export function decodeLength(bytes: Array): 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) { diff --git a/web3.js/src/util/sleep.js b/web3.js/src/util/sleep.ts similarity index 92% rename from web3.js/src/util/sleep.js rename to web3.js/src/util/sleep.ts index 961d48c457..96228f338c 100644 --- a/web3.js/src/util/sleep.js +++ b/web3.js/src/util/sleep.ts @@ -1,5 +1,3 @@ -// @flow - // zzz export function sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); diff --git a/web3.js/src/util/to-buffer.js b/web3.js/src/util/to-buffer.ts similarity index 96% rename from web3.js/src/util/to-buffer.js rename to web3.js/src/util/to-buffer.ts index 03fa1f14a7..d7a43425b9 100644 --- a/web3.js/src/util/to-buffer.js +++ b/web3.js/src/util/to-buffer.ts @@ -1,5 +1,3 @@ -// @flow - import {Buffer} from 'buffer'; export const toBuffer = (arr: Buffer | Uint8Array | Array): Buffer => { diff --git a/web3.js/src/validator-info.js b/web3.js/src/validator-info.ts similarity index 92% rename from web3.js/src/validator-info.js rename to web3.js/src/validator-info.ts index 82d0b35d63..3e5ebd4977 100644 --- a/web3.js/src/validator-info.js +++ b/web3.js/src/validator-info.ts @@ -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(), diff --git a/web3.js/src/vote-account.js b/web3.js/src/vote-account.ts similarity index 57% rename from web3.js/src/vote-account.js rename to web3.js/src/vote-account.ts index 7e0803e21f..9005ab09ad 100644 --- a/web3.js/src/vote-account.js +++ b/web3.js/src/vote-account.ts @@ -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; + rootSlot: number | null; + epoch: number; + credits: number; + lastEpochCredits: number; + epochCredits: Array; +}; + /** * VoteAccount class */ @@ -74,6 +86,22 @@ export class VoteAccount { lastEpochCredits: number; epochCredits: Array; + /** + * @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, ): 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, + }); } } diff --git a/web3.js/test/account.test.js b/web3.js/test/account.test.js index bf6c5d8a81..ce72c1c0ce 100644 --- a/web3.js/test/account.test.js +++ b/web3.js/test/account.test.js @@ -1,4 +1,3 @@ -// @flow import {expect} from 'chai'; import {Buffer} from 'buffer'; diff --git a/web3.js/test/agent-manager.test.js b/web3.js/test/agent-manager.test.js index dad49e2f42..071144458c 100644 --- a/web3.js/test/agent-manager.test.js +++ b/web3.js/test/agent-manager.test.js @@ -1,5 +1,3 @@ -// @flow - import {expect} from 'chai'; import {AgentManager, DESTROY_TIMEOUT_MS} from '../src/agent-manager'; diff --git a/web3.js/test/bpf-loader.test.js b/web3.js/test/bpf-loader.test.js index f07e479ed5..b4aacd3de5 100644 --- a/web3.js/test/bpf-loader.test.js +++ b/web3.js/test/bpf-loader.test.js @@ -1,5 +1,3 @@ -// @flow - import fs from 'mz/fs'; import {expect, use} from 'chai'; import chaiAsPromised from 'chai-as-promised'; diff --git a/web3.js/test/cluster.test.js b/web3.js/test/cluster.test.js index 2b58424262..0ff1dbdadc 100644 --- a/web3.js/test/cluster.test.js +++ b/web3.js/test/cluster.test.js @@ -1,5 +1,3 @@ -// @flow - import {expect} from 'chai'; import {clusterApiUrl} from '../src/util/cluster'; diff --git a/web3.js/test/connection.test.js b/web3.js/test/connection.test.js index 7577bee5d6..2f304c9bd1 100644 --- a/web3.js/test/connection.test.js +++ b/web3.js/test/connection.test.js @@ -1,4 +1,3 @@ -// @flow import bs58 from 'bs58'; import {Buffer} from 'buffer'; import {Token, u64} from '@solana/spl-token'; diff --git a/web3.js/test/mocks/rpc-http.js b/web3.js/test/mocks/rpc-http.js index 9104f10a64..15804c19a8 100644 --- a/web3.js/test/mocks/rpc-http.js +++ b/web3.js/test/mocks/rpc-http.js @@ -1,5 +1,3 @@ -// @flow - import bs58 from 'bs58'; import BN from 'bn.js'; import * as mockttp from 'mockttp'; diff --git a/web3.js/test/mocks/rpc-websockets.js b/web3.js/test/mocks/rpc-websockets.js index 87a03452aa..6e68f90812 100644 --- a/web3.js/test/mocks/rpc-websockets.js +++ b/web3.js/test/mocks/rpc-websockets.js @@ -1,5 +1,3 @@ -// @flow - import {Client as LiveClient} from 'rpc-websockets'; import {expect} from 'chai'; import sinon from 'sinon'; diff --git a/web3.js/test/nonce.test.js b/web3.js/test/nonce.test.js index dcef9af9e9..ae4c185d93 100644 --- a/web3.js/test/nonce.test.js +++ b/web3.js/test/nonce.test.js @@ -1,5 +1,3 @@ -// @flow - import bs58 from 'bs58'; import {Buffer} from 'buffer'; import {expect} from 'chai'; diff --git a/web3.js/test/publickey.test.js b/web3.js/test/publickey.test.js index 87fc128748..a16d7faa5f 100644 --- a/web3.js/test/publickey.test.js +++ b/web3.js/test/publickey.test.js @@ -1,4 +1,3 @@ -// @flow import BN from 'bn.js'; import {Buffer} from 'buffer'; import {expect, use} from 'chai'; diff --git a/web3.js/test/secp256k1-program.test.js b/web3.js/test/secp256k1-program.test.js index 7e24f24d82..762798078b 100644 --- a/web3.js/test/secp256k1-program.test.js +++ b/web3.js/test/secp256k1-program.test.js @@ -1,5 +1,3 @@ -// @flow - import {Buffer} from 'buffer'; import {keccak_256} from 'js-sha3'; import {privateKeyVerify, ecdsaSign, publicKeyCreate} from 'secp256k1'; diff --git a/web3.js/test/shortvec-encoding.test.js b/web3.js/test/shortvec-encoding.test.js index 9d96897ce3..4cc711a0c1 100644 --- a/web3.js/test/shortvec-encoding.test.js +++ b/web3.js/test/shortvec-encoding.test.js @@ -1,5 +1,3 @@ -// @flow - import {expect} from 'chai'; import {decodeLength, encodeLength} from '../src/util/shortvec-encoding'; diff --git a/web3.js/test/stake-program.test.js b/web3.js/test/stake-program.test.js index a767425ef0..1788c38400 100644 --- a/web3.js/test/stake-program.test.js +++ b/web3.js/test/stake-program.test.js @@ -1,5 +1,3 @@ -// @flow - import {expect, use} from 'chai'; import chaiAsPromised from 'chai-as-promised'; diff --git a/web3.js/test/system-program.test.js b/web3.js/test/system-program.test.js index ae3a16eca9..895cff04a9 100644 --- a/web3.js/test/system-program.test.js +++ b/web3.js/test/system-program.test.js @@ -1,5 +1,3 @@ -// @flow - import {Buffer} from 'buffer'; import {expect} from 'chai'; diff --git a/web3.js/test/transaction-payer.test.js b/web3.js/test/transaction-payer.test.js index d1bc317ead..313f89eb08 100644 --- a/web3.js/test/transaction-payer.test.js +++ b/web3.js/test/transaction-payer.test.js @@ -1,5 +1,3 @@ -// @flow - import base58 from 'bs58'; import {expect} from 'chai'; diff --git a/web3.js/test/transaction.test.js b/web3.js/test/transaction.test.js index b7efd8bd91..e34b187cef 100644 --- a/web3.js/test/transaction.test.js +++ b/web3.js/test/transaction.test.js @@ -1,4 +1,3 @@ -// @flow import bs58 from 'bs58'; import {Buffer} from 'buffer'; import nacl from 'tweetnacl'; diff --git a/web3.js/test/url.js b/web3.js/test/url.js index be667c4a96..bd28b20991 100644 --- a/web3.js/test/url.js +++ b/web3.js/test/url.js @@ -1,5 +1,3 @@ -// @flow - /** * The connection url to use when running unit tests against a live cluster */ diff --git a/web3.js/test/validator-info.test.js b/web3.js/test/validator-info.test.js index 4fbf88d1aa..f52d193ca6 100644 --- a/web3.js/test/validator-info.test.js +++ b/web3.js/test/validator-info.test.js @@ -1,4 +1,3 @@ -// @flow import {Buffer} from 'buffer'; import {expect} from 'chai'; import nacl from 'tweetnacl'; diff --git a/web3.js/test/websocket.test.js b/web3.js/test/websocket.test.js index 0ffbc6c410..aa60d99e3e 100644 --- a/web3.js/test/websocket.test.js +++ b/web3.js/test/websocket.test.js @@ -1,4 +1,3 @@ -// @flow import bs58 from 'bs58'; import {Buffer} from 'buffer'; import {expect, use} from 'chai';