Reputation: 87
I am attempting at using Solana over Ethereum for a particular solution.
I am using NPM to target Solana's API's. The packages being used are @solana/web3.js
and @solana/spl-token
. I've been able to create a successful connection and generate keypairs. I would like to be able to save a generated keypair, but the problem I face is that it's encoded, and the second issue to highlight is when I use the .toString(); it decodes it just fine but that can't be used in an airdrop.
const solanaWeb3 = require("@solana/web3.js"),
const solanatoken = require("@solana/spl-token");
(async () => {
// Connect to cluster
var connection = new solanaWeb3.Connection(
solanaWeb3.clusterApiUrl("devnet"),
"confirmed"
);
// Generate a new wallet keypair and airdrop SOL
var wallet = solanaWeb3.Keypair.generate();
console.log("public key...", wallet.publicKey)
// The stringPK is an example of what wallet.publicKey returns. When taking wallet.publicKey and using .toString(); it returns the decoded publicKey but that can't be used in an airdrop.
const stringPK = `_bn: <BN: e8a4421b46f76fdeac76819ab21708cc4a4b9c9c7fc2a22e373443539cee1a81>`;
console.log("private key...", JSON.stringify(wallet.secretKey.toString()));
console.log(solanaWeb3.PublicKey.decode(wallet.publicKey));
var airdropSignature = await connection.requestAirdrop(
stringPK,
solanaWeb3.LAMPORTS_PER_SOL
);
//wait for airdrop confirmation
await connection.confirmTransaction(airdropSignature);
let account = await connection.getAccountInfo(wallet.publicKey);
console.log(account);
})();
Upvotes: 1
Views: 1861
Reputation: 8402
To save the generated keypair in JS, your best bet is to use secretKey
on the Keypair object [1], write that to a file. To load it back up, you'll read that file and then use fromSecretKey
to get back your Keypair [2]
As for your other issue, requestAirdrop
takes a PublicKey
, so instead, you should just do:
var airdropSignature = await connection.requestAirdrop(
wallet.publicKey,
solanaWeb3.LAMPORTS_PER_SOL
);
[1] https://solana-labs.github.io/solana-web3.js/classes/Keypair.html#secretKey
[2] https://solana-labs.github.io/solana-web3.js/classes/Keypair.html#fromSecretKey
Upvotes: 1