feat: add Keypair class and deprecate Account (#17098)

* feat: add Keypair class and deprecate Account

* chore: fix lint issues

* chore: rename TransactionSigner to Signer
This commit is contained in:
Justin Starry
2021-05-07 16:59:51 +08:00
committed by GitHub
parent 0b5167bf51
commit f43f0afa55
20 changed files with 339 additions and 213 deletions

View File

@ -48,7 +48,7 @@
"flow:gen": "flowgen lib/index.d.ts -o module.flow.js", "flow:gen": "flowgen lib/index.d.ts -o module.flow.js",
"type:gen": "./scripts/typegen.sh", "type:gen": "./scripts/typegen.sh",
"lint": "set -ex; npm run pretty; eslint . --ext .js,.ts", "lint": "set -ex; npm run pretty; eslint . --ext .js,.ts",
"lint:fix": "npm run pretty:fix && eslint . --fix", "lint:fix": "npm run pretty:fix && eslint . --fix --ext .js,.ts",
"ok": "run-s lint test doc", "ok": "run-s lint test doc",
"pretty": "prettier --check '{,{src,test}/**/}*.{j,t}s'", "pretty": "prettier --check '{,{src,test}/**/}*.{j,t}s'",
"pretty:fix": "prettier --write '{,{src,test}/**/}*.{j,t}s'", "pretty:fix": "prettier --write '{,{src,test}/**/}*.{j,t}s'",

View File

@ -6,6 +6,8 @@ import {PublicKey} from './publickey';
/** /**
* An account key pair (public and secret keys). * An account key pair (public and secret keys).
*
* @deprecated since v1.10.0, please use {@link Keypair} instead.
*/ */
export class Account { export class Account {
/** @internal */ /** @internal */

View File

@ -1,7 +1,7 @@
import {Account} from './account';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
import {Loader} from './loader'; import {Loader} from './loader';
import type {Connection} from './connection'; import type {Connection} from './connection';
import type {Signer} from './keypair';
export const BPF_LOADER_PROGRAM_ID = new PublicKey( export const BPF_LOADER_PROGRAM_ID = new PublicKey(
'BPFLoader2111111111111111111111111111111111', 'BPFLoader2111111111111111111111111111111111',
@ -33,8 +33,8 @@ export class BpfLoader {
*/ */
static load( static load(
connection: Connection, connection: Connection,
payer: Account, payer: Signer,
program: Account, program: Signer,
elf: Buffer | Uint8Array | Array<number>, elf: Buffer | Uint8Array | Array<number>,
loaderProgramId: PublicKey, loaderProgramId: PublicKey,
): Promise<boolean> { ): Promise<boolean> {

View File

@ -29,6 +29,7 @@ import {IWSRequestParams} from 'rpc-websockets/dist/lib/client';
import {AgentManager} from './agent-manager'; import {AgentManager} from './agent-manager';
import {NonceAccount} from './nonce-account'; import {NonceAccount} from './nonce-account';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
import {Signer} from './keypair';
import {MS_PER_SLOT} from './timing'; import {MS_PER_SLOT} from './timing';
import {Transaction} from './transaction'; import {Transaction} from './transaction';
import {Message} from './message'; import {Message} from './message';
@ -37,7 +38,6 @@ import {promiseTimeout} from './util/promise-timeout';
import {toBuffer} from './util/to-buffer'; import {toBuffer} from './util/to-buffer';
import type {Blockhash} from './blockhash'; import type {Blockhash} from './blockhash';
import type {FeeCalculator} from './fee-calculator'; import type {FeeCalculator} from './fee-calculator';
import type {Account} from './account';
import type {TransactionSignature} from './transaction'; import type {TransactionSignature} from './transaction';
import type {CompiledInstruction} from './message'; import type {CompiledInstruction} from './message';
@ -3213,7 +3213,7 @@ export class Connection {
*/ */
async simulateTransaction( async simulateTransaction(
transaction: Transaction, transaction: Transaction,
signers?: Array<Account>, signers?: Array<Signer>,
): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> { ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> {
if (transaction.nonceInfo && signers) { if (transaction.nonceInfo && signers) {
transaction.sign(...signers); transaction.sign(...signers);
@ -3274,7 +3274,7 @@ export class Connection {
*/ */
async sendTransaction( async sendTransaction(
transaction: Transaction, transaction: Transaction,
signers: Array<Account>, signers: Array<Signer>,
options?: SendOptions, options?: SendOptions,
): Promise<TransactionSignature> { ): Promise<TransactionSignature> {
if (transaction.nonceInfo) { if (transaction.nonceInfo) {

View File

@ -4,6 +4,7 @@ export * from './bpf-loader-deprecated';
export * from './bpf-loader'; export * from './bpf-loader';
export * from './connection'; export * from './connection';
export * from './fee-calculator'; export * from './fee-calculator';
export * from './keypair';
export * from './loader'; export * from './loader';
export * from './message'; export * from './message';
export * from './nonce-account'; export * from './nonce-account';

84
web3.js/src/keypair.ts Normal file
View File

@ -0,0 +1,84 @@
import * as nacl from 'tweetnacl';
import type {SignKeyPair} from 'tweetnacl';
import {PublicKey} from './publickey';
/**
* Keypair signer interface
*/
export interface Signer {
publicKey: PublicKey;
secretKey: Uint8Array;
}
/**
* An account keypair used for signing transactions.
*/
export class Keypair {
/**
* @internal
*
* Create a new keypair instance from a {@link SignKeyPair}.
*
* @param keypair ed25519 keypair
*/
constructor(private keypair: SignKeyPair) {}
/**
* Generate a new random keypair
*/
static generate(): Keypair {
return new Keypair(nacl.sign.keyPair());
}
/**
* Create a keypair from a raw secret key byte array.
*
* This method should only be used to recreate a keypair from a previously
* generated secret key. Generating keypairs from a random seed should be done
* with the {@link Keypair.fromSeed} method.
*
* @throws error if the provided secret key is invalid and validation is not skipped.
*
* @param secretKey secret key byte array
* @param options: skip secret key validation
*/
static fromSecretKey(
secretKey: Uint8Array,
options?: {skipValidation?: boolean},
): Keypair {
const keypair = nacl.sign.keyPair.fromSecretKey(secretKey);
if (!options || !options.skipValidation) {
const encoder = new TextEncoder();
const signData = encoder.encode('@solana/web3.js-validation-v1');
const signature = nacl.sign.detached(signData, keypair.secretKey);
if (!nacl.sign.detached.verify(signData, signature, keypair.publicKey)) {
throw new Error('provided secretKey is invalid');
}
}
return new Keypair(keypair);
}
/**
* Generate a keypair from a 32 byte seed.
*
* @param seed seed byte array
*/
static fromSeed(seed: Uint8Array): Keypair {
return new Keypair(nacl.sign.keyPair.fromSeed(seed));
}
/**
* The public key for this keypair
*/
get publicKey(): PublicKey {
return new PublicKey(this.keypair.publicKey);
}
/**
* The raw secret key for this keypair
*/
get secretKey(): Uint8Array {
return this.keypair.secretKey;
}
}

View File

@ -1,13 +1,13 @@
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import * as BufferLayout from 'buffer-layout'; import * as BufferLayout from 'buffer-layout';
import {Account} from './account';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
import {Transaction, PACKET_DATA_SIZE} from './transaction'; import {Transaction, PACKET_DATA_SIZE} from './transaction';
import {SYSVAR_RENT_PUBKEY} from './sysvar'; import {SYSVAR_RENT_PUBKEY} from './sysvar';
import {sendAndConfirmTransaction} from './util/send-and-confirm-transaction'; import {sendAndConfirmTransaction} from './util/send-and-confirm-transaction';
import {sleep} from './util/sleep'; import {sleep} from './util/sleep';
import type {Connection} from './connection'; import type {Connection} from './connection';
import type {Signer} from './keypair';
import {SystemProgram} from './system-program'; import {SystemProgram} from './system-program';
// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the // Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the
@ -58,8 +58,8 @@ export class Loader {
*/ */
static async load( static async load(
connection: Connection, connection: Connection,
payer: Account, payer: Signer,
program: Account, program: Signer,
programId: PublicKey, programId: PublicKey,
data: Buffer | Uint8Array | Array<number>, data: Buffer | Uint8Array | Array<number>,
): Promise<boolean> { ): Promise<boolean> {

View File

@ -3,13 +3,13 @@ import nacl from 'tweetnacl';
import bs58 from 'bs58'; import bs58 from 'bs58';
import {Buffer} from 'buffer'; import {Buffer} from 'buffer';
import type {CompiledInstruction} from './message';
import {Message} from './message'; import {Message} from './message';
import {PublicKey} from './publickey'; import {PublicKey} from './publickey';
import {Account} from './account';
import * as shortvec from './util/shortvec-encoding'; import * as shortvec from './util/shortvec-encoding';
import type {Blockhash} from './blockhash';
import {toBuffer} from './util/to-buffer'; import {toBuffer} from './util/to-buffer';
import type {Signer} from './keypair';
import type {Blockhash} from './blockhash';
import type {CompiledInstruction} from './message';
/** /**
* Transaction signature as base-58 encoded string * Transaction signature as base-58 encoded string
@ -432,7 +432,7 @@ export class Transaction {
} }
/** /**
* Sign the Transaction with the specified accounts. Multiple signatures may * Sign the Transaction with the specified signers. Multiple signatures may
* be applied to a Transaction. The first signature is considered "primary" * be applied to a Transaction. The first signature is considered "primary"
* and is used identify and confirm transactions. * and is used identify and confirm transactions.
* *
@ -445,7 +445,7 @@ export class Transaction {
* *
* The Transaction must be assigned a valid `recentBlockhash` before invoking this method * The Transaction must be assigned a valid `recentBlockhash` before invoking this method
*/ */
sign(...signers: Array<Account>) { sign(...signers: Array<Signer>) {
if (signers.length === 0) { if (signers.length === 0) {
throw new Error('No signers'); throw new Error('No signers');
} }
@ -480,7 +480,7 @@ export class Transaction {
* *
* All the caveats from the `sign` method apply to `partialSign` * All the caveats from the `sign` method apply to `partialSign`
*/ */
partialSign(...signers: Array<Account>) { partialSign(...signers: Array<Signer>) {
if (signers.length === 0) { if (signers.length === 0) {
throw new Error('No signers'); throw new Error('No signers');
} }
@ -505,7 +505,7 @@ export class Transaction {
/** /**
* @internal * @internal
*/ */
_partialSign(message: Message, ...signers: Array<Account>) { _partialSign(message: Message, ...signers: Array<Signer>) {
const signData = message.serialize(); const signData = message.serialize();
signers.forEach(signer => { signers.forEach(signer => {
const signature = nacl.sign.detached(signData, signer.secretKey); const signature = nacl.sign.detached(signData, signer.secretKey);

View File

@ -1,7 +1,7 @@
import {Connection} from '../connection'; import {Connection} from '../connection';
import {Transaction} from '../transaction'; import {Transaction} from '../transaction';
import type {Account} from '../account';
import type {ConfirmOptions} from '../connection'; import type {ConfirmOptions} from '../connection';
import type {Signer} from '../keypair';
import type {TransactionSignature} from '../transaction'; import type {TransactionSignature} from '../transaction';
/** /**
@ -11,14 +11,14 @@ import type {TransactionSignature} from '../transaction';
* *
* @param {Connection} connection * @param {Connection} connection
* @param {Transaction} transaction * @param {Transaction} transaction
* @param {Array<Account>} signers * @param {Array<Signer>} signers
* @param {ConfirmOptions} [options] * @param {ConfirmOptions} [options]
* @returns {Promise<TransactionSignature>} * @returns {Promise<TransactionSignature>}
*/ */
export async function sendAndConfirmTransaction( export async function sendAndConfirmTransaction(
connection: Connection, connection: Connection,
transaction: Transaction, transaction: Transaction,
signers: Array<Account>, signers: Array<Signer>,
options?: ConfirmOptions, options?: ConfirmOptions,
): Promise<TransactionSignature> { ): Promise<TransactionSignature> {
const sendOptions = options && { const sendOptions = options && {

View File

@ -7,7 +7,7 @@ import {
BpfLoader, BpfLoader,
Transaction, Transaction,
sendAndConfirmTransaction, sendAndConfirmTransaction,
Account, Keypair,
} from '../src'; } from '../src';
import {url} from './url'; import {url} from './url';
import {BPF_LOADER_PROGRAM_ID} from '../src/bpf-loader'; import {BPF_LOADER_PROGRAM_ID} from '../src/bpf-loader';
@ -20,8 +20,8 @@ if (process.env.TEST_LIVE) {
describe('load BPF program', () => { describe('load BPF program', () => {
const connection = new Connection(url, 'confirmed'); const connection = new Connection(url, 'confirmed');
let program = new Account(); let program = Keypair.generate();
let payerAccount = new Account(); let payerAccount = Keypair.generate();
let programData: Buffer; let programData: Buffer;
before(async function () { before(async function () {
@ -55,7 +55,7 @@ if (process.env.TEST_LIVE) {
}); });
// First load will fail part way due to lack of funds // First load will fail part way due to lack of funds
const insufficientPayerAccount = new Account(); const insufficientPayerAccount = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
address: insufficientPayerAccount.publicKey, address: insufficientPayerAccount.publicKey,
@ -208,7 +208,7 @@ if (process.env.TEST_LIVE) {
keys: [ keys: [
{pubkey: payerAccount.publicKey, isSigner: true, isWritable: true}, {pubkey: payerAccount.publicKey, isSigner: true, isWritable: true},
], ],
programId: new Account().publicKey, programId: Keypair.generate().publicKey,
}); });
simulatedTransaction.setSigners(payerAccount.publicKey); simulatedTransaction.setSigners(payerAccount.publicKey);

View File

@ -16,6 +16,7 @@ import {
PublicKey, PublicKey,
StakeProgram, StakeProgram,
sendAndConfirmTransaction, sendAndConfirmTransaction,
Keypair,
} from '../src'; } from '../src';
import {DEFAULT_TICKS_PER_SLOT, NUM_TICKS_PER_SECOND} from '../src/timing'; import {DEFAULT_TICKS_PER_SLOT, NUM_TICKS_PER_SECOND} from '../src/timing';
import {MOCK_PORT, url} from './url'; import {MOCK_PORT, url} from './url';
@ -132,7 +133,7 @@ describe('Connection', () => {
} }
it('get account info - not found', async () => { it('get account info - not found', async () => {
const account = new Account(); const account = Keypair.generate();
await mockRpcResponse({ await mockRpcResponse({
method: 'getAccountInfo', method: 'getAccountInfo',
@ -155,9 +156,9 @@ describe('Connection', () => {
}); });
it('get program accounts', async () => { it('get program accounts', async () => {
const account0 = new Account(); const account0 = Keypair.generate();
const account1 = new Account(); const account1 = Keypair.generate();
const programId = new Account(); const programId = Keypair.generate();
{ {
await helpers.airdrop({ await helpers.airdrop({
@ -543,7 +544,7 @@ describe('Connection', () => {
}); });
it('get balance', async () => { it('get balance', async () => {
const account = new Account(); const account = Keypair.generate();
await mockRpcResponse({ await mockRpcResponse({
method: 'getBalance', method: 'getBalance',
@ -821,7 +822,7 @@ describe('Connection', () => {
total: 1000000, total: 1000000,
circulating: 100000, circulating: 100000,
nonCirculating: 900000, nonCirculating: 900000,
nonCirculatingAccounts: [new Account().publicKey.toBase58()], nonCirculatingAccounts: [Keypair.generate().publicKey.toBase58()],
}, },
withContext: true, withContext: true,
}); });
@ -1429,7 +1430,7 @@ describe('Connection', () => {
const resultSignature = bs58.encode(result.transaction.signature); const resultSignature = bs58.encode(result.transaction.signature);
expect(resultSignature).to.eq(confirmedTransaction); expect(resultSignature).to.eq(confirmedTransaction);
const newAddress = new Account().publicKey; const newAddress = Keypair.generate().publicKey;
const recentSignature = await helpers.airdrop({ const recentSignature = await helpers.airdrop({
connection, connection,
address: newAddress, address: newAddress,
@ -1826,7 +1827,7 @@ describe('Connection', () => {
total: 1000, total: 1000,
circulating: 100, circulating: 100,
nonCirculating: 900, nonCirculating: 900,
nonCirculatingAccounts: [new Account().publicKey.toBase58()], nonCirculatingAccounts: [Keypair.generate().publicKey.toBase58()],
}, },
withContext: true, withContext: true,
}); });
@ -1880,7 +1881,7 @@ describe('Connection', () => {
if (process.env.TEST_LIVE) { if (process.env.TEST_LIVE) {
describe('token methods', () => { describe('token methods', () => {
const connection = new Connection(url, 'confirmed'); const connection = new Connection(url, 'confirmed');
const newAccount = new Account().publicKey; const newAccount = Keypair.generate().publicKey;
let testToken: Token; let testToken: Token;
let testTokenPubkey: PublicKey; let testTokenPubkey: PublicKey;
@ -1900,7 +1901,7 @@ describe('Connection', () => {
const mintOwner = new Account(); const mintOwner = new Account();
const accountOwner = new Account(); const accountOwner = new Account();
const token = await Token.createMint( const token = await Token.createMint(
connection, connection as any,
payerAccount, payerAccount,
mintOwner.publicKey, mintOwner.publicKey,
null, null,
@ -1912,7 +1913,7 @@ describe('Connection', () => {
await token.mintTo(tokenAccount, mintOwner, [], 11111); await token.mintTo(tokenAccount, mintOwner, [], 11111);
const token2 = await Token.createMint( const token2 = await Token.createMint(
connection, connection as any,
payerAccount, payerAccount,
mintOwner.publicKey, mintOwner.publicKey,
null, null,
@ -2095,8 +2096,8 @@ describe('Connection', () => {
it('consistent preflightCommitment', async () => { it('consistent preflightCommitment', async () => {
const connection = new Connection(url, 'singleGossip'); const connection = new Connection(url, 'singleGossip');
const sender = new Account(); const sender = Keypair.generate();
const recipient = new Account(); const recipient = Keypair.generate();
let signature = await connection.requestAirdrop( let signature = await connection.requestAirdrop(
sender.publicKey, sender.publicKey,
2 * LAMPORTS_PER_SOL, 2 * LAMPORTS_PER_SOL,
@ -2118,7 +2119,7 @@ describe('Connection', () => {
method: 'getLargestAccounts', method: 'getLargestAccounts',
params: [], params: [],
value: new Array(20).fill(0).map(() => ({ value: new Array(20).fill(0).map(() => ({
address: new Account().publicKey.toBase58(), address: Keypair.generate().publicKey.toBase58(),
lamports: 1000, lamports: 1000,
})), })),
withContext: true, withContext: true,
@ -2129,7 +2130,7 @@ describe('Connection', () => {
}); });
it('stake activation should throw when called for not delegated account', async () => { it('stake activation should throw when called for not delegated account', async () => {
const publicKey = new Account().publicKey; const publicKey = Keypair.generate().publicKey;
await mockRpcResponse({ await mockRpcResponse({
method: 'getStakeActivation', method: 'getStakeActivation',
params: [publicKey.toBase58(), {}], params: [publicKey.toBase58(), {}],
@ -2147,7 +2148,7 @@ describe('Connection', () => {
)[0]; )[0];
const votePubkey = new PublicKey(voteAccount.votePubkey); const votePubkey = new PublicKey(voteAccount.votePubkey);
const authorized = new Account(); const authorized = Keypair.generate();
let signature = await connection.requestAirdrop( let signature = await connection.requestAirdrop(
authorized.publicKey, authorized.publicKey,
2 * LAMPORTS_PER_SOL, 2 * LAMPORTS_PER_SOL,
@ -2158,7 +2159,7 @@ describe('Connection', () => {
StakeProgram.space, StakeProgram.space,
); );
const newStakeAccount = new Account(); const newStakeAccount = Keypair.generate();
let createAndInitialize = StakeProgram.createAccount({ let createAndInitialize = StakeProgram.createAccount({
fromPubkey: authorized.publicKey, fromPubkey: authorized.publicKey,
stakePubkey: newStakeAccount.publicKey, stakePubkey: newStakeAccount.publicKey,
@ -2209,7 +2210,7 @@ describe('Connection', () => {
if (mockServer) { if (mockServer) {
it('stake activation should only accept state with valid string literals', async () => { it('stake activation should only accept state with valid string literals', async () => {
const publicKey = new Account().publicKey; const publicKey = Keypair.generate().publicKey;
const addStakeActivationMock = async (state: any) => { const addStakeActivationMock = async (state: any) => {
await mockRpcResponse({ await mockRpcResponse({
@ -2250,7 +2251,7 @@ describe('Connection', () => {
}); });
it('request airdrop', async () => { it('request airdrop', async () => {
const account = new Account(); const account = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
@ -2328,7 +2329,7 @@ describe('Connection', () => {
}); });
it('transaction failure', async () => { it('transaction failure', async () => {
const payer = new Account(); const payer = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
@ -2336,7 +2337,7 @@ describe('Connection', () => {
amount: LAMPORTS_PER_SOL, amount: LAMPORTS_PER_SOL,
}); });
const newAccount = new Account(); const newAccount = Keypair.generate();
let transaction = new Transaction().add( let transaction = new Transaction().add(
SystemProgram.createAccount({ SystemProgram.createAccount({
fromPubkey: payer.publicKey, fromPubkey: payer.publicKey,
@ -2391,8 +2392,8 @@ describe('Connection', () => {
it('transaction', async () => { it('transaction', async () => {
connection._commitment = 'confirmed'; connection._commitment = 'confirmed';
const accountFrom = new Account(); const accountFrom = Keypair.generate();
const accountTo = new Account(); const accountTo = Keypair.generate();
const minimumAmount = await connection.getMinimumBalanceForRentExemption( const minimumAmount = await connection.getMinimumBalanceForRentExemption(
0, 0,
); );
@ -2494,8 +2495,8 @@ describe('Connection', () => {
it('multi-instruction transaction', async () => { it('multi-instruction transaction', async () => {
connection._commitment = 'confirmed'; connection._commitment = 'confirmed';
const accountFrom = new Account(); const accountFrom = Keypair.generate();
const accountTo = new Account(); const accountTo = Keypair.generate();
let signature = await connection.requestAirdrop( let signature = await connection.requestAirdrop(
accountFrom.publicKey, accountFrom.publicKey,
@ -2572,8 +2573,8 @@ describe('Connection', () => {
// } // }
// const connection = new Connection(url, 'confirmed'); // const connection = new Connection(url, 'confirmed');
// const owner = new Account(); // const owner = Keypair.generate();
// const programAccount = new Account(); // const programAccount = Keypair.generate();
// const mockCallback = jest.fn(); // const mockCallback = jest.fn();
@ -2633,8 +2634,8 @@ describe('Connection', () => {
it('program account change notification', async () => { it('program account change notification', async () => {
connection._commitment = 'confirmed'; connection._commitment = 'confirmed';
const owner = new Account(); const owner = Keypair.generate();
const programAccount = new Account(); const programAccount = Keypair.generate();
const balanceNeeded = await connection.getMinimumBalanceForRentExemption( const balanceNeeded = await connection.getMinimumBalanceForRentExemption(
0, 0,
); );
@ -2737,7 +2738,7 @@ describe('Connection', () => {
it('logs notification', async () => { it('logs notification', async () => {
let listener: number | undefined; let listener: number | undefined;
const owner = new Account(); const owner = Keypair.generate();
const [logsRes, ctx] = await new Promise(resolve => { const [logsRes, ctx] = await new Promise(resolve => {
let received = false; let received = false;
listener = connection.onLogs( listener = connection.onLogs(

View File

@ -0,0 +1,50 @@
import {expect} from 'chai';
import {Buffer} from 'buffer';
import {Keypair} from '../src';
describe('Keypair', () => {
it('generate new keypair', () => {
const keypair = Keypair.generate();
expect(keypair.secretKey).to.have.length(64);
});
it('create keypair from secret key', () => {
const secretKey = Buffer.from(
'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIg==',
'base64',
);
const keypair = Keypair.fromSecretKey(secretKey);
expect(keypair.publicKey.toBase58()).to.eq(
'2q7pyhPwAwZ3QMfZrnAbDhnh9mDUqycszcpf86VgQxhF',
);
});
it('creating keypair from invalid secret key throws error', () => {
const secretKey = Buffer.from(
'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIG==',
'base64',
);
expect(() => {
Keypair.fromSecretKey(secretKey);
}).to.throw('provided secretKey is invalid');
});
it('creating keypair from invalid secret key succeeds if validation is skipped', () => {
const secretKey = Buffer.from(
'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIG==',
'base64',
);
const keypair = Keypair.fromSecretKey(secretKey, {skipValidation: true});
expect(keypair.publicKey.toBase58()).to.eq(
'2q7pyhPwAwZ3QMfZrnAbDhnh9mDUqycszcpf86VgQxhD',
);
});
it('generate keypair from random seed', () => {
const keypair = Keypair.fromSeed(Uint8Array.from(Array(32).fill(8)));
expect(keypair.publicKey.toBase58()).to.eq(
'2KW2XRd9kwqet15Aha2oK3tYvd3nWbTFH1MBiRAv1BE1',
);
});
});

View File

@ -4,7 +4,7 @@ import invariant from 'assert';
import * as mockttp from 'mockttp'; import * as mockttp from 'mockttp';
import {mockRpcMessage} from './rpc-websockets'; import {mockRpcMessage} from './rpc-websockets';
import {Account, Connection, PublicKey, Transaction} from '../../src'; import {Connection, PublicKey, Transaction, Signer} from '../../src';
import type {Commitment, HttpHeaders, RpcParams} from '../../src/connection'; import type {Commitment, HttpHeaders, RpcParams} from '../../src/connection';
export const mockServer: mockttp.Mockttp | undefined = export const mockServer: mockttp.Mockttp | undefined =
@ -141,7 +141,7 @@ const processTransaction = async ({
}: { }: {
connection: Connection; connection: Connection;
transaction: Transaction; transaction: Transaction;
signers: Array<Account>; signers: Array<Signer>;
commitment: Commitment; commitment: Commitment;
err?: any; err?: any;
}) => { }) => {

View File

@ -3,11 +3,11 @@ import {Buffer} from 'buffer';
import {expect} from 'chai'; import {expect} from 'chai';
import { import {
Account,
Connection, Connection,
SystemProgram, SystemProgram,
Transaction, Transaction,
PublicKey, PublicKey,
Keypair,
} from '../src'; } from '../src';
import {NONCE_ACCOUNT_LENGTH} from '../src/nonce-account'; import {NONCE_ACCOUNT_LENGTH} from '../src/nonce-account';
import {MOCK_PORT, url} from './url'; import {MOCK_PORT, url} from './url';
@ -19,7 +19,7 @@ const expectedData = (authorizedPubkey: PublicKey): [string, string] => {
expectedData.writeInt32LE(0, 0); // Version, 4 bytes expectedData.writeInt32LE(0, 0); // Version, 4 bytes
expectedData.writeInt32LE(1, 4); // State, 4 bytes expectedData.writeInt32LE(1, 4); // State, 4 bytes
authorizedPubkey.toBuffer().copy(expectedData, 8); // authorizedPubkey, 32 bytes authorizedPubkey.toBuffer().copy(expectedData, 8); // authorizedPubkey, 32 bytes
const mockNonce = new Account(); const mockNonce = Keypair.generate();
mockNonce.publicKey.toBuffer().copy(expectedData, 40); // Hash, 32 bytes mockNonce.publicKey.toBuffer().copy(expectedData, 40); // Hash, 32 bytes
expectedData.writeUInt16LE(5000, 72); // feeCalculator, 8 bytes expectedData.writeUInt16LE(5000, 72); // feeCalculator, 8 bytes
return [expectedData.toString('base64'), 'base64']; return [expectedData.toString('base64'), 'base64'];
@ -45,8 +45,8 @@ describe('Nonce', () => {
} }
it('create and query nonce account', async () => { it('create and query nonce account', async () => {
const from = new Account(); const from = Keypair.generate();
const nonceAccount = new Account(); const nonceAccount = Keypair.generate();
await mockRpcResponse({ await mockRpcResponse({
method: 'getMinimumBalanceForRentExemption', method: 'getMinimumBalanceForRentExemption',
@ -109,7 +109,7 @@ describe('Nonce', () => {
}); });
it('create and query nonce account with seed', async () => { it('create and query nonce account with seed', async () => {
const from = new Account(); const from = Keypair.generate();
const seed = 'seed'; const seed = 'seed';
const noncePubkey = await PublicKey.createWithSeed( const noncePubkey = await PublicKey.createWithSeed(
from.publicKey, from.publicKey,

View File

@ -3,7 +3,7 @@ import {Buffer} from 'buffer';
import {expect, use} from 'chai'; import {expect, use} from 'chai';
import chaiAsPromised from 'chai-as-promised'; import chaiAsPromised from 'chai-as-promised';
import {Account} from '../src/account'; import {Keypair} from '../src/keypair';
import {PublicKey, MAX_SEED_LENGTH} from '../src/publickey'; import {PublicKey, MAX_SEED_LENGTH} from '../src/publickey';
use(chaiAsPromised); use(chaiAsPromised);
@ -331,7 +331,7 @@ describe('PublicKey', function () {
}); });
it('isOnCurve', () => { it('isOnCurve', () => {
let onCurve = new Account().publicKey; let onCurve = Keypair.generate().publicKey;
expect(PublicKey.isOnCurve(onCurve.toBuffer())).to.be.true; expect(PublicKey.isOnCurve(onCurve.toBuffer())).to.be.true;
// A program address, yanked from one of the above tests. This is a pretty // A program address, yanked from one of the above tests. This is a pretty
// poor test vector since it was created by the same code it is testing. // poor test vector since it was created by the same code it is testing.

View File

@ -4,7 +4,7 @@ import {privateKeyVerify, ecdsaSign, publicKeyCreate} from 'secp256k1';
import { import {
Connection, Connection,
Account, Keypair,
sendAndConfirmTransaction, sendAndConfirmTransaction,
LAMPORTS_PER_SOL, LAMPORTS_PER_SOL,
Transaction, Transaction,
@ -15,7 +15,7 @@ import {url} from './url';
const randomPrivateKey = () => { const randomPrivateKey = () => {
let privateKey; let privateKey;
do { do {
privateKey = new Account().secretKey.slice(0, 32); privateKey = Keypair.generate().secretKey.slice(0, 32);
} while (!privateKeyVerify(privateKey)); } while (!privateKeyVerify(privateKey));
return privateKey; return privateKey;
}; };
@ -25,7 +25,7 @@ if (process.env.TEST_LIVE) {
const privateKey = randomPrivateKey(); const privateKey = randomPrivateKey();
const publicKey = publicKeyCreate(privateKey, false).slice(1); const publicKey = publicKeyCreate(privateKey, false).slice(1);
const ethAddress = Secp256k1Program.publicKeyToEthAddress(publicKey); const ethAddress = Secp256k1Program.publicKeyToEthAddress(publicKey);
const from = new Account(); const from = Keypair.generate();
const connection = new Connection(url, 'confirmed'); const connection = new Connection(url, 'confirmed');
before(async function () { before(async function () {

View File

@ -2,7 +2,7 @@ import {expect, use} from 'chai';
import chaiAsPromised from 'chai-as-promised'; import chaiAsPromised from 'chai-as-promised';
import { import {
Account, Keypair,
Authorized, Authorized,
Connection, Connection,
Lockup, Lockup,
@ -22,14 +22,14 @@ use(chaiAsPromised);
describe('StakeProgram', () => { describe('StakeProgram', () => {
it('createAccountWithSeed', async () => { it('createAccountWithSeed', async () => {
const fromPubkey = new Account().publicKey; const fromPubkey = Keypair.generate().publicKey;
const seed = 'test string'; const seed = 'test string';
const newAccountPubkey = await PublicKey.createWithSeed( const newAccountPubkey = await PublicKey.createWithSeed(
fromPubkey, fromPubkey,
seed, seed,
StakeProgram.programId, StakeProgram.programId,
); );
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const authorized = new Authorized(authorizedPubkey, authorizedPubkey); const authorized = new Authorized(authorizedPubkey, authorizedPubkey);
const lockup = new Lockup(0, 0, fromPubkey); const lockup = new Lockup(0, 0, fromPubkey);
const lamports = 123; const lamports = 123;
@ -63,9 +63,9 @@ describe('StakeProgram', () => {
}); });
it('createAccount', () => { it('createAccount', () => {
const fromPubkey = new Account().publicKey; const fromPubkey = Keypair.generate().publicKey;
const newAccountPubkey = new Account().publicKey; const newAccountPubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const authorized = new Authorized(authorizedPubkey, authorizedPubkey); const authorized = new Authorized(authorizedPubkey, authorizedPubkey);
const lockup = new Lockup(0, 0, fromPubkey); const lockup = new Lockup(0, 0, fromPubkey);
const lamports = 123; const lamports = 123;
@ -96,9 +96,9 @@ describe('StakeProgram', () => {
}); });
it('delegate', () => { it('delegate', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const votePubkey = new Account().publicKey; const votePubkey = Keypair.generate().publicKey;
const params = { const params = {
stakePubkey, stakePubkey,
authorizedPubkey, authorizedPubkey,
@ -111,9 +111,9 @@ describe('StakeProgram', () => {
}); });
it('authorize', () => { it('authorize', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const newAuthorizedPubkey = new Account().publicKey; const newAuthorizedPubkey = Keypair.generate().publicKey;
const stakeAuthorizationType = StakeAuthorizationLayout.Staker; const stakeAuthorizationType = StakeAuthorizationLayout.Staker;
const params = { const params = {
stakePubkey, stakePubkey,
@ -128,11 +128,11 @@ describe('StakeProgram', () => {
}); });
it('authorize with custodian', () => { it('authorize with custodian', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const newAuthorizedPubkey = new Account().publicKey; const newAuthorizedPubkey = Keypair.generate().publicKey;
const stakeAuthorizationType = StakeAuthorizationLayout.Withdrawer; const stakeAuthorizationType = StakeAuthorizationLayout.Withdrawer;
const custodianPubkey = new Account().publicKey; const custodianPubkey = Keypair.generate().publicKey;
const params = { const params = {
stakePubkey, stakePubkey,
authorizedPubkey, authorizedPubkey,
@ -147,11 +147,11 @@ describe('StakeProgram', () => {
}); });
it('authorizeWithSeed', () => { it('authorizeWithSeed', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorityBase = new Account().publicKey; const authorityBase = Keypair.generate().publicKey;
const authoritySeed = 'test string'; const authoritySeed = 'test string';
const authorityOwner = new Account().publicKey; const authorityOwner = Keypair.generate().publicKey;
const newAuthorizedPubkey = new Account().publicKey; const newAuthorizedPubkey = Keypair.generate().publicKey;
const stakeAuthorizationType = StakeAuthorizationLayout.Staker; const stakeAuthorizationType = StakeAuthorizationLayout.Staker;
const params = { const params = {
stakePubkey, stakePubkey,
@ -170,13 +170,13 @@ describe('StakeProgram', () => {
}); });
it('authorizeWithSeed with custodian', () => { it('authorizeWithSeed with custodian', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorityBase = new Account().publicKey; const authorityBase = Keypair.generate().publicKey;
const authoritySeed = 'test string'; const authoritySeed = 'test string';
const authorityOwner = new Account().publicKey; const authorityOwner = Keypair.generate().publicKey;
const newAuthorizedPubkey = new Account().publicKey; const newAuthorizedPubkey = Keypair.generate().publicKey;
const stakeAuthorizationType = StakeAuthorizationLayout.Staker; const stakeAuthorizationType = StakeAuthorizationLayout.Staker;
const custodianPubkey = new Account().publicKey; const custodianPubkey = Keypair.generate().publicKey;
const params = { const params = {
stakePubkey, stakePubkey,
authorityBase, authorityBase,
@ -195,9 +195,9 @@ describe('StakeProgram', () => {
}); });
it('split', () => { it('split', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const splitStakePubkey = new Account().publicKey; const splitStakePubkey = Keypair.generate().publicKey;
const params = { const params = {
stakePubkey, stakePubkey,
authorizedPubkey, authorizedPubkey,
@ -221,9 +221,9 @@ describe('StakeProgram', () => {
}); });
it('withdraw', () => { it('withdraw', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const toPubkey = new Account().publicKey; const toPubkey = Keypair.generate().publicKey;
const params = { const params = {
stakePubkey, stakePubkey,
authorizedPubkey, authorizedPubkey,
@ -237,10 +237,10 @@ describe('StakeProgram', () => {
}); });
it('withdraw with custodian', () => { it('withdraw with custodian', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const toPubkey = new Account().publicKey; const toPubkey = Keypair.generate().publicKey;
const custodianPubkey = new Account().publicKey; const custodianPubkey = Keypair.generate().publicKey;
const params = { const params = {
stakePubkey, stakePubkey,
authorizedPubkey, authorizedPubkey,
@ -255,8 +255,8 @@ describe('StakeProgram', () => {
}); });
it('deactivate', () => { it('deactivate', () => {
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const params = {stakePubkey, authorizedPubkey}; const params = {stakePubkey, authorizedPubkey};
const transaction = StakeProgram.deactivate(params); const transaction = StakeProgram.deactivate(params);
expect(transaction.instructions).to.have.length(1); expect(transaction.instructions).to.have.length(1);
@ -265,14 +265,14 @@ describe('StakeProgram', () => {
}); });
it('StakeInstructions', async () => { it('StakeInstructions', async () => {
const from = new Account(); const from = Keypair.generate();
const seed = 'test string'; const seed = 'test string';
const newAccountPubkey = await PublicKey.createWithSeed( const newAccountPubkey = await PublicKey.createWithSeed(
from.publicKey, from.publicKey,
seed, seed,
StakeProgram.programId, StakeProgram.programId,
); );
const authorized = new Account(); const authorized = Keypair.generate();
const amount = 123; const amount = 123;
const recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'; // Arbitrary known recentBlockhash const recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'; // Arbitrary known recentBlockhash
const createWithSeed = StakeProgram.createAccountWithSeed({ const createWithSeed = StakeProgram.createAccountWithSeed({
@ -305,8 +305,8 @@ describe('StakeProgram', () => {
); );
}).to.throw(); }).to.throw();
const stake = new Account(); const stake = Keypair.generate();
const vote = new Account(); const vote = Keypair.generate();
const delegate = StakeProgram.delegate({ const delegate = StakeProgram.delegate({
stakePubkey: stake.publicKey, stakePubkey: stake.publicKey,
authorizedPubkey: authorized.publicKey, authorizedPubkey: authorized.publicKey,
@ -332,14 +332,14 @@ describe('StakeProgram', () => {
)[0]; )[0];
const votePubkey = new PublicKey(voteAccount.votePubkey); const votePubkey = new PublicKey(voteAccount.votePubkey);
const payer = new Account(); const payer = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
address: payer.publicKey, address: payer.publicKey,
amount: 2 * LAMPORTS_PER_SOL, amount: 2 * LAMPORTS_PER_SOL,
}); });
const authorized = new Account(); const authorized = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
address: authorized.publicKey, address: authorized.publicKey,
@ -359,7 +359,7 @@ describe('StakeProgram', () => {
{ {
// Create Stake account without seed // Create Stake account without seed
const newStakeAccount = new Account(); const newStakeAccount = Keypair.generate();
let createAndInitialize = StakeProgram.createAccount({ let createAndInitialize = StakeProgram.createAccount({
fromPubkey: payer.publicKey, fromPubkey: payer.publicKey,
stakePubkey: newStakeAccount.publicKey, stakePubkey: newStakeAccount.publicKey,
@ -427,7 +427,7 @@ describe('StakeProgram', () => {
}); });
// Test that withdraw fails before deactivation // Test that withdraw fails before deactivation
const recipient = new Account(); const recipient = Keypair.generate();
let withdraw = StakeProgram.withdraw({ let withdraw = StakeProgram.withdraw({
stakePubkey: newAccountPubkey, stakePubkey: newAccountPubkey,
authorizedPubkey: authorized.publicKey, authorizedPubkey: authorized.publicKey,
@ -471,7 +471,7 @@ describe('StakeProgram', () => {
expect(recipientBalance).to.eq(minimumAmount + 20); expect(recipientBalance).to.eq(minimumAmount + 20);
// Split stake // Split stake
const newStake = new Account(); const newStake = Keypair.generate();
let split = StakeProgram.split({ let split = StakeProgram.split({
stakePubkey: newAccountPubkey, stakePubkey: newAccountPubkey,
authorizedPubkey: authorized.publicKey, authorizedPubkey: authorized.publicKey,
@ -490,7 +490,7 @@ describe('StakeProgram', () => {
expect(balance).to.eq(minimumAmount + 2); expect(balance).to.eq(minimumAmount + 2);
// Authorize to new account // Authorize to new account
const newAuthorized = new Account(); const newAuthorized = Keypair.generate();
await connection.requestAirdrop( await connection.requestAirdrop(
newAuthorized.publicKey, newAuthorized.publicKey,
LAMPORTS_PER_SOL, LAMPORTS_PER_SOL,

View File

@ -2,7 +2,7 @@ import {Buffer} from 'buffer';
import {expect} from 'chai'; import {expect} from 'chai';
import { import {
Account, Keypair,
Connection, Connection,
PublicKey, PublicKey,
StakeProgram, StakeProgram,
@ -21,8 +21,8 @@ import {url} from './url';
describe('SystemProgram', () => { describe('SystemProgram', () => {
it('createAccount', () => { it('createAccount', () => {
const params = { const params = {
fromPubkey: new Account().publicKey, fromPubkey: Keypair.generate().publicKey,
newAccountPubkey: new Account().publicKey, newAccountPubkey: Keypair.generate().publicKey,
lamports: 123, lamports: 123,
space: 0, space: 0,
programId: SystemProgram.programId, programId: SystemProgram.programId,
@ -39,8 +39,8 @@ describe('SystemProgram', () => {
it('transfer', () => { it('transfer', () => {
const params = { const params = {
fromPubkey: new Account().publicKey, fromPubkey: Keypair.generate().publicKey,
toPubkey: new Account().publicKey, toPubkey: Keypair.generate().publicKey,
lamports: 123, lamports: 123,
}; };
const transaction = new Transaction().add(SystemProgram.transfer(params)); const transaction = new Transaction().add(SystemProgram.transfer(params));
@ -51,12 +51,12 @@ describe('SystemProgram', () => {
it('transferWithSeed', () => { it('transferWithSeed', () => {
const params = { const params = {
fromPubkey: new Account().publicKey, fromPubkey: Keypair.generate().publicKey,
basePubkey: new Account().publicKey, basePubkey: Keypair.generate().publicKey,
toPubkey: new Account().publicKey, toPubkey: Keypair.generate().publicKey,
lamports: 123, lamports: 123,
seed: '你好', seed: '你好',
programId: new Account().publicKey, programId: Keypair.generate().publicKey,
}; };
const transaction = new Transaction().add(SystemProgram.transfer(params)); const transaction = new Transaction().add(SystemProgram.transfer(params));
expect(transaction.instructions).to.have.length(1); expect(transaction.instructions).to.have.length(1);
@ -68,7 +68,7 @@ describe('SystemProgram', () => {
it('allocate', () => { it('allocate', () => {
const params = { const params = {
accountPubkey: new Account().publicKey, accountPubkey: Keypair.generate().publicKey,
space: 42, space: 42,
}; };
const transaction = new Transaction().add(SystemProgram.allocate(params)); const transaction = new Transaction().add(SystemProgram.allocate(params));
@ -79,11 +79,11 @@ describe('SystemProgram', () => {
it('allocateWithSeed', () => { it('allocateWithSeed', () => {
const params = { const params = {
accountPubkey: new Account().publicKey, accountPubkey: Keypair.generate().publicKey,
basePubkey: new Account().publicKey, basePubkey: Keypair.generate().publicKey,
seed: '你好', seed: '你好',
space: 42, space: 42,
programId: new Account().publicKey, programId: Keypair.generate().publicKey,
}; };
const transaction = new Transaction().add(SystemProgram.allocate(params)); const transaction = new Transaction().add(SystemProgram.allocate(params));
expect(transaction.instructions).to.have.length(1); expect(transaction.instructions).to.have.length(1);
@ -95,8 +95,8 @@ describe('SystemProgram', () => {
it('assign', () => { it('assign', () => {
const params = { const params = {
accountPubkey: new Account().publicKey, accountPubkey: Keypair.generate().publicKey,
programId: new Account().publicKey, programId: Keypair.generate().publicKey,
}; };
const transaction = new Transaction().add(SystemProgram.assign(params)); const transaction = new Transaction().add(SystemProgram.assign(params));
expect(transaction.instructions).to.have.length(1); expect(transaction.instructions).to.have.length(1);
@ -106,10 +106,10 @@ describe('SystemProgram', () => {
it('assignWithSeed', () => { it('assignWithSeed', () => {
const params = { const params = {
accountPubkey: new Account().publicKey, accountPubkey: Keypair.generate().publicKey,
basePubkey: new Account().publicKey, basePubkey: Keypair.generate().publicKey,
seed: '你好', seed: '你好',
programId: new Account().publicKey, programId: Keypair.generate().publicKey,
}; };
const transaction = new Transaction().add(SystemProgram.assign(params)); const transaction = new Transaction().add(SystemProgram.assign(params));
expect(transaction.instructions).to.have.length(1); expect(transaction.instructions).to.have.length(1);
@ -120,10 +120,10 @@ describe('SystemProgram', () => {
}); });
it('createAccountWithSeed', () => { it('createAccountWithSeed', () => {
const fromPubkey = new Account().publicKey; const fromPubkey = Keypair.generate().publicKey;
const params = { const params = {
fromPubkey, fromPubkey,
newAccountPubkey: new Account().publicKey, newAccountPubkey: Keypair.generate().publicKey,
basePubkey: fromPubkey, basePubkey: fromPubkey,
seed: 'hi there', seed: 'hi there',
lamports: 123, lamports: 123,
@ -141,10 +141,10 @@ describe('SystemProgram', () => {
}); });
it('createNonceAccount', () => { it('createNonceAccount', () => {
const fromPubkey = new Account().publicKey; const fromPubkey = Keypair.generate().publicKey;
const params = { const params = {
fromPubkey, fromPubkey,
noncePubkey: new Account().publicKey, noncePubkey: Keypair.generate().publicKey,
authorizedPubkey: fromPubkey, authorizedPubkey: fromPubkey,
lamports: 123, lamports: 123,
}; };
@ -176,10 +176,10 @@ describe('SystemProgram', () => {
}); });
it('createNonceAccount with seed', () => { it('createNonceAccount with seed', () => {
const fromPubkey = new Account().publicKey; const fromPubkey = Keypair.generate().publicKey;
const params = { const params = {
fromPubkey, fromPubkey,
noncePubkey: new Account().publicKey, noncePubkey: Keypair.generate().publicKey,
authorizedPubkey: fromPubkey, authorizedPubkey: fromPubkey,
basePubkey: fromPubkey, basePubkey: fromPubkey,
seed: 'hi there', seed: 'hi there',
@ -216,8 +216,8 @@ describe('SystemProgram', () => {
it('nonceAdvance', () => { it('nonceAdvance', () => {
const params = { const params = {
noncePubkey: new Account().publicKey, noncePubkey: Keypair.generate().publicKey,
authorizedPubkey: new Account().publicKey, authorizedPubkey: Keypair.generate().publicKey,
}; };
const instruction = SystemProgram.nonceAdvance(params); const instruction = SystemProgram.nonceAdvance(params);
expect(params).to.eql(SystemInstruction.decodeNonceAdvance(instruction)); expect(params).to.eql(SystemInstruction.decodeNonceAdvance(instruction));
@ -225,9 +225,9 @@ describe('SystemProgram', () => {
it('nonceWithdraw', () => { it('nonceWithdraw', () => {
const params = { const params = {
noncePubkey: new Account().publicKey, noncePubkey: Keypair.generate().publicKey,
authorizedPubkey: new Account().publicKey, authorizedPubkey: Keypair.generate().publicKey,
toPubkey: new Account().publicKey, toPubkey: Keypair.generate().publicKey,
lamports: 123, lamports: 123,
}; };
const transaction = new Transaction().add( const transaction = new Transaction().add(
@ -240,9 +240,9 @@ describe('SystemProgram', () => {
it('nonceAuthorize', () => { it('nonceAuthorize', () => {
const params = { const params = {
noncePubkey: new Account().publicKey, noncePubkey: Keypair.generate().publicKey,
authorizedPubkey: new Account().publicKey, authorizedPubkey: Keypair.generate().publicKey,
newAuthorizedPubkey: new Account().publicKey, newAuthorizedPubkey: Keypair.generate().publicKey,
}; };
const transaction = new Transaction().add( const transaction = new Transaction().add(
@ -254,8 +254,8 @@ describe('SystemProgram', () => {
}); });
it('non-SystemInstruction error', () => { it('non-SystemInstruction error', () => {
const from = new Account(); const from = Keypair.generate();
const to = new Account(); const to = Keypair.generate();
const badProgramId = { const badProgramId = {
keys: [ keys: [
@ -271,8 +271,8 @@ describe('SystemProgram', () => {
); );
}).to.throw(); }).to.throw();
const stakePubkey = new Account().publicKey; const stakePubkey = Keypair.generate().publicKey;
const authorizedPubkey = new Account().publicKey; const authorizedPubkey = Keypair.generate().publicKey;
const params = {stakePubkey, authorizedPubkey}; const params = {stakePubkey, authorizedPubkey};
const transaction = StakeProgram.deactivate(params); const transaction = StakeProgram.deactivate(params);
@ -289,16 +289,16 @@ describe('SystemProgram', () => {
if (process.env.TEST_LIVE) { if (process.env.TEST_LIVE) {
it('live Nonce actions', async () => { it('live Nonce actions', async () => {
const connection = new Connection(url, 'confirmed'); const connection = new Connection(url, 'confirmed');
const nonceAccount = new Account(); const nonceAccount = Keypair.generate();
const from = new Account(); const from = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
address: from.publicKey, address: from.publicKey,
amount: 2 * LAMPORTS_PER_SOL, amount: 2 * LAMPORTS_PER_SOL,
}); });
const to = new Account(); const to = Keypair.generate();
const newAuthority = new Account(); const newAuthority = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
address: newAuthority.publicKey, address: newAuthority.publicKey,
@ -403,7 +403,7 @@ describe('SystemProgram', () => {
// Wait for blockhash to advance // Wait for blockhash to advance
await sleep(500); await sleep(500);
const withdrawAccount = new Account(); const withdrawAccount = Keypair.generate();
const withdrawNonce = new Transaction().add( const withdrawNonce = new Transaction().add(
SystemProgram.nonceWithdraw({ SystemProgram.nonceWithdraw({
noncePubkey: nonceAccount.publicKey, noncePubkey: nonceAccount.publicKey,
@ -429,7 +429,7 @@ describe('SystemProgram', () => {
it('live withSeed actions', async () => { it('live withSeed actions', async () => {
const connection = new Connection(url, 'confirmed'); const connection = new Connection(url, 'confirmed');
const baseAccount = new Account(); const baseAccount = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,
address: baseAccount.publicKey, address: baseAccount.publicKey,
@ -437,7 +437,7 @@ describe('SystemProgram', () => {
}); });
const basePubkey = baseAccount.publicKey; const basePubkey = baseAccount.publicKey;
const seed = 'hi there'; const seed = 'hi there';
const programId = new Account().publicKey; const programId = Keypair.generate().publicKey;
const createAccountWithSeedAddress = await PublicKey.createWithSeed( const createAccountWithSeedAddress = await PublicKey.createWithSeed(
basePubkey, basePubkey,
seed, seed,
@ -474,8 +474,8 @@ describe('SystemProgram', () => {
expect(createAccountWithSeedBalance).to.eq(minimumAmount); expect(createAccountWithSeedBalance).to.eq(minimumAmount);
// Test CreateAccountWithSeed where fromPubkey != basePubkey // Test CreateAccountWithSeed where fromPubkey != basePubkey
const uniqueFromAccount = new Account(); const uniqueFromAccount = Keypair.generate();
const newBaseAccount = new Account(); const newBaseAccount = Keypair.generate();
const createAccountWithSeedAddress2 = await PublicKey.createWithSeed( const createAccountWithSeedAddress2 = await PublicKey.createWithSeed(
newBaseAccount.publicKey, newBaseAccount.publicKey,
seed, seed,
@ -510,7 +510,7 @@ describe('SystemProgram', () => {
expect(createAccountWithSeedBalance2).to.eq(minimumAmount); expect(createAccountWithSeedBalance2).to.eq(minimumAmount);
// Transfer to a derived address to prep for TransferWithSeed // Transfer to a derived address to prep for TransferWithSeed
const programId2 = new Account().publicKey; const programId2 = Keypair.generate().publicKey;
const transferWithSeedAddress = await PublicKey.createWithSeed( const transferWithSeedAddress = await PublicKey.createWithSeed(
basePubkey, basePubkey,
seed, seed,
@ -534,7 +534,7 @@ describe('SystemProgram', () => {
expect(transferWithSeedAddressBalance).to.eq(3 * minimumAmount); expect(transferWithSeedAddressBalance).to.eq(3 * minimumAmount);
// Test TransferWithSeed // Test TransferWithSeed
const programId3 = new Account(); const programId3 = Keypair.generate();
const toPubkey = await PublicKey.createWithSeed( const toPubkey = await PublicKey.createWithSeed(
basePubkey, basePubkey,
seed, seed,

View File

@ -3,7 +3,7 @@ import invariant from 'assert';
import {expect} from 'chai'; import {expect} from 'chai';
import { import {
Account, Keypair,
Connection, Connection,
Transaction, Transaction,
SystemProgram, SystemProgram,
@ -33,9 +33,9 @@ describe('Transaction Payer', () => {
} }
it('transaction-payer', async () => { it('transaction-payer', async () => {
const accountPayer = new Account(); const accountPayer = Keypair.generate();
const accountFrom = new Account(); const accountFrom = Keypair.generate();
const accountTo = new Account(); const accountTo = Keypair.generate();
await helpers.airdrop({ await helpers.airdrop({
connection, connection,

View File

@ -4,7 +4,7 @@ import {Buffer} from 'buffer';
import nacl from 'tweetnacl'; import nacl from 'tweetnacl';
import {expect} from 'chai'; import {expect} from 'chai';
import {Account} from '../src/account'; import {Keypair} from '../src/keypair';
import {PublicKey} from '../src/publickey'; import {PublicKey} from '../src/publickey';
import {Transaction} from '../src/transaction'; import {Transaction} from '../src/transaction';
import {StakeProgram} from '../src/stake-program'; import {StakeProgram} from '../src/stake-program';
@ -15,11 +15,11 @@ import {toBuffer} from '../src/util/to-buffer';
describe('Transaction', () => { describe('Transaction', () => {
describe('compileMessage', () => { describe('compileMessage', () => {
it('accountKeys are ordered', () => { it('accountKeys are ordered', () => {
const payer = new Account(); const payer = Keypair.generate();
const account2 = new Account(); const account2 = Keypair.generate();
const account3 = new Account(); const account3 = Keypair.generate();
const recentBlockhash = new Account().publicKey.toBase58(); const recentBlockhash = Keypair.generate().publicKey.toBase58();
const programId = new Account().publicKey; const programId = Keypair.generate().publicKey;
const transaction = new Transaction({recentBlockhash}).add({ const transaction = new Transaction({recentBlockhash}).add({
keys: [ keys: [
{pubkey: account3.publicKey, isSigner: true, isWritable: false}, {pubkey: account3.publicKey, isSigner: true, isWritable: false},
@ -42,10 +42,10 @@ describe('Transaction', () => {
}); });
it('payer is first account meta', () => { it('payer is first account meta', () => {
const payer = new Account(); const payer = Keypair.generate();
const other = new Account(); const other = Keypair.generate();
const recentBlockhash = new Account().publicKey.toBase58(); const recentBlockhash = Keypair.generate().publicKey.toBase58();
const programId = new Account().publicKey; const programId = Keypair.generate().publicKey;
const transaction = new Transaction({recentBlockhash}).add({ const transaction = new Transaction({recentBlockhash}).add({
keys: [ keys: [
{pubkey: other.publicKey, isSigner: true, isWritable: true}, {pubkey: other.publicKey, isSigner: true, isWritable: true},
@ -64,10 +64,10 @@ describe('Transaction', () => {
}); });
it('validation', () => { it('validation', () => {
const payer = new Account(); const payer = Keypair.generate();
const other = new Account(); const other = Keypair.generate();
const recentBlockhash = new Account().publicKey.toBase58(); const recentBlockhash = Keypair.generate().publicKey.toBase58();
const programId = new Account().publicKey; const programId = Keypair.generate().publicKey;
const transaction = new Transaction(); const transaction = new Transaction();
expect(() => { expect(() => {
@ -92,7 +92,7 @@ describe('Transaction', () => {
transaction.compileMessage(); transaction.compileMessage();
}).to.throw('Transaction fee payer required'); }).to.throw('Transaction fee payer required');
transaction.setSigners(payer.publicKey, new Account().publicKey); transaction.setSigners(payer.publicKey, Keypair.generate().publicKey);
expect(() => { expect(() => {
transaction.compileMessage(); transaction.compileMessage();
@ -109,9 +109,9 @@ describe('Transaction', () => {
}); });
it('payer is writable', () => { it('payer is writable', () => {
const payer = new Account(); const payer = Keypair.generate();
const recentBlockhash = new Account().publicKey.toBase58(); const recentBlockhash = Keypair.generate().publicKey.toBase58();
const programId = new Account().publicKey; const programId = Keypair.generate().publicKey;
const transaction = new Transaction({recentBlockhash}).add({ const transaction = new Transaction({recentBlockhash}).add({
keys: [{pubkey: payer.publicKey, isSigner: true, isWritable: false}], keys: [{pubkey: payer.publicKey, isSigner: true, isWritable: false}],
programId, programId,
@ -127,8 +127,8 @@ describe('Transaction', () => {
}); });
it('partialSign', () => { it('partialSign', () => {
const account1 = new Account(); const account1 = Keypair.generate();
const account2 = new Account(); const account2 = Keypair.generate();
const recentBlockhash = account1.publicKey.toBase58(); // Fake recentBlockhash const recentBlockhash = account1.publicKey.toBase58(); // Fake recentBlockhash
const transfer = SystemProgram.transfer({ const transfer = SystemProgram.transfer({
fromPubkey: account1.publicKey, fromPubkey: account1.publicKey,
@ -176,11 +176,11 @@ describe('Transaction', () => {
}); });
describe('dedupe', () => { describe('dedupe', () => {
const payer = new Account(); const payer = Keypair.generate();
const duplicate1 = payer; const duplicate1 = payer;
const duplicate2 = payer; const duplicate2 = payer;
const recentBlockhash = new Account().publicKey.toBase58(); const recentBlockhash = Keypair.generate().publicKey.toBase58();
const programId = new Account().publicKey; const programId = Keypair.generate().publicKey;
it('setSigners', () => { it('setSigners', () => {
const transaction = new Transaction({recentBlockhash}).add({ const transaction = new Transaction({recentBlockhash}).add({
@ -236,8 +236,8 @@ describe('Transaction', () => {
}); });
it('transfer signatures', () => { it('transfer signatures', () => {
const account1 = new Account(); const account1 = Keypair.generate();
const account2 = new Account(); const account2 = Keypair.generate();
const recentBlockhash = account1.publicKey.toBase58(); // Fake recentBlockhash const recentBlockhash = account1.publicKey.toBase58(); // Fake recentBlockhash
const transfer1 = SystemProgram.transfer({ const transfer1 = SystemProgram.transfer({
fromPubkey: account1.publicKey, fromPubkey: account1.publicKey,
@ -265,8 +265,8 @@ describe('Transaction', () => {
}); });
it('dedup signatures', () => { it('dedup signatures', () => {
const account1 = new Account(); const account1 = Keypair.generate();
const account2 = new Account(); const account2 = Keypair.generate();
const recentBlockhash = account1.publicKey.toBase58(); // Fake recentBlockhash const recentBlockhash = account1.publicKey.toBase58(); // Fake recentBlockhash
const transfer1 = SystemProgram.transfer({ const transfer1 = SystemProgram.transfer({
fromPubkey: account1.publicKey, fromPubkey: account1.publicKey,
@ -287,9 +287,9 @@ describe('Transaction', () => {
}); });
it('use nonce', () => { it('use nonce', () => {
const account1 = new Account(); const account1 = Keypair.generate();
const account2 = new Account(); const account2 = Keypair.generate();
const nonceAccount = new Account(); const nonceAccount = Keypair.generate();
const nonce = account2.publicKey.toBase58(); // Fake Nonce hash const nonce = account2.publicKey.toBase58(); // Fake Nonce hash
const nonceInfo = { const nonceInfo = {
@ -319,8 +319,8 @@ describe('Transaction', () => {
expect(transferTransaction.instructions[0].data).to.eql(expectedData); expect(transferTransaction.instructions[0].data).to.eql(expectedData);
expect(transferTransaction.recentBlockhash).to.eq(nonce); expect(transferTransaction.recentBlockhash).to.eq(nonce);
const stakeAccount = new Account(); const stakeAccount = Keypair.generate();
const voteAccount = new Account(); const voteAccount = Keypair.generate();
const stakeTransaction = new Transaction({nonceInfo}).add( const stakeTransaction = new Transaction({nonceInfo}).add(
StakeProgram.delegate({ StakeProgram.delegate({
stakePubkey: stakeAccount.publicKey, stakePubkey: stakeAccount.publicKey,
@ -339,10 +339,7 @@ describe('Transaction', () => {
}); });
it('parse wire format and serialize', () => { it('parse wire format and serialize', () => {
const keypair = nacl.sign.keyPair.fromSeed( const sender = Keypair.fromSeed(Uint8Array.from(Array(32).fill(8))); // Arbitrary known account
Uint8Array.from(Array(32).fill(8)),
);
const sender = new Account(Buffer.from(keypair.secretKey)); // Arbitrary known account
const recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'; // Arbitrary known recentBlockhash const recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'; // Arbitrary known recentBlockhash
const recipient = new PublicKey( const recipient = new PublicKey(
'J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i99', 'J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i99',
@ -405,10 +402,7 @@ describe('Transaction', () => {
}); });
it('serialize unsigned transaction', () => { it('serialize unsigned transaction', () => {
const keypair = nacl.sign.keyPair.fromSeed( const sender = Keypair.fromSeed(Uint8Array.from(Array(32).fill(8))); // Arbitrary known account
Uint8Array.from(Array(32).fill(8)),
);
const sender = new Account(Buffer.from(keypair.secretKey)); // Arbitrary known account
const recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'; // Arbitrary known recentBlockhash const recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'; // Arbitrary known recentBlockhash
const recipient = new PublicKey( const recipient = new PublicKey(
'J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i99', 'J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i99',
@ -489,10 +483,7 @@ describe('Transaction', () => {
}); });
it('deprecated - externally signed stake delegate', () => { it('deprecated - externally signed stake delegate', () => {
const from_keypair = nacl.sign.keyPair.fromSeed( const authority = Keypair.fromSeed(Uint8Array.from(Array(32).fill(1)));
Uint8Array.from(Array(32).fill(1)),
);
const authority = new Account(Buffer.from(from_keypair.secretKey));
const stake = new PublicKey(2); const stake = new PublicKey(2);
const recentBlockhash = new PublicKey(3).toBuffer(); const recentBlockhash = new PublicKey(3).toBuffer();
const vote = new PublicKey(4); const vote = new PublicKey(4);
@ -511,10 +502,7 @@ describe('Transaction', () => {
}); });
it('externally signed stake delegate', () => { it('externally signed stake delegate', () => {
const from_keypair = nacl.sign.keyPair.fromSeed( const authority = Keypair.fromSeed(Uint8Array.from(Array(32).fill(1)));
Uint8Array.from(Array(32).fill(1)),
);
const authority = new Account(Buffer.from(from_keypair.secretKey));
const stake = new PublicKey(2); const stake = new PublicKey(2);
const recentBlockhash = new PublicKey(3).toBuffer(); const recentBlockhash = new PublicKey(3).toBuffer();
const vote = new PublicKey(4); const vote = new PublicKey(4);