UNPKG

@solana-developers/helpers

Version:
56 lines 2.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.airdropIfRequired = exports.initializeKeypair = void 0; const web3_js_1 = require("@solana/web3.js"); const keypair_1 = require("./keypair"); const DEFAULT_AIRDROP_AMOUNT = 1 * web3_js_1.LAMPORTS_PER_SOL; const DEFAULT_MINIMUM_BALANCE = 0.5 * web3_js_1.LAMPORTS_PER_SOL; const DEFAULT_ENV_KEYPAIR_VARIABLE_NAME = "PRIVATE_KEY"; // TODO: honestly initializeKeypair is a bit vague // we can probably give this a better name, // just not sure what yet const initializeKeypair = async (connection, options) => { const { keypairPath, envFileName, envVariableName = DEFAULT_ENV_KEYPAIR_VARIABLE_NAME, airdropAmount = DEFAULT_AIRDROP_AMOUNT, minimumBalance = DEFAULT_MINIMUM_BALANCE, } = options || {}; let keypair; if (keypairPath) { keypair = await (0, keypair_1.getKeypairFromFile)(keypairPath); } else if (process.env[envVariableName]) { keypair = (0, keypair_1.getKeypairFromEnvironment)(envVariableName); } else { keypair = web3_js_1.Keypair.generate(); await (0, keypair_1.addKeypairToEnvFile)(keypair, envVariableName, envFileName); } if (airdropAmount) { await (0, exports.airdropIfRequired)(connection, keypair.publicKey, airdropAmount, minimumBalance); } return keypair; }; exports.initializeKeypair = initializeKeypair; // Not exported as we don't want to encourage people to // request airdrops when they don't need them, ie - don't bother // the faucet unless you really need to! const requestAndConfirmAirdrop = async (connection, publicKey, amount) => { const airdropTransactionSignature = await connection.requestAirdrop(publicKey, amount); // Wait for airdrop confirmation const latestBlockHash = await connection.getLatestBlockhash(); await connection.confirmTransaction({ blockhash: latestBlockHash.blockhash, lastValidBlockHeight: latestBlockHash.lastValidBlockHeight, signature: airdropTransactionSignature, }, // "finalized" is slow but we must be absolutely sure // the airdrop has gone through "finalized"); return connection.getBalance(publicKey, "finalized"); }; const airdropIfRequired = async (connection, publicKey, airdropAmount, minimumBalance) => { const balance = await connection.getBalance(publicKey, "confirmed"); if (balance < minimumBalance) { return requestAndConfirmAirdrop(connection, publicKey, airdropAmount); } return balance; }; exports.airdropIfRequired = airdropIfRequired; //# sourceMappingURL=airdrop.js.map