Reputation: 1753
I want users to come and mint tokens on my website. I have followed Solana docs and came across the following code in the Javascript client section.
var web3Connection = new web3.Connection(
web3.clusterApiUrl("devnet"),
'confirmed',
);
// Generate a new wallet keypair and airdrop SOL
var fromWallet = web3.Keypair.generate();
var fromAirdropSignature = await web3Connection.requestAirdrop(
fromWallet.publicKey,
web3.LAMPORTS_PER_SOL,
);
//wait for airdrop confirmation
await web3Connection.confirmTransaction(fromAirdropSignature);
//create new token mint
let mint = await splToken.Token.createMint(
web3Connection,
fromWallet,
fromWallet.publicKey,
null,
9,
splToken.TOKEN_PROGRAM_ID,
);
Please correct me if wrong. I think ideally, I should create the wallet and keypair from CLI and then use them through env variables or some secured config in code to mint, transfer. etc.
If the above is correct, how can I create the web3.Keypair object with my existing publicKey and secret values instead of generating a random one?
Upvotes: 4
Views: 9092
Reputation: 2397
Create a new file to generate the publicKey, call it createKey.js
(or related). Use this simple code:
const fs = require('fs')
const anchor = require('@project-serum/anchor')
const account = anchor.web3.Keypair.generate()
fs.writeFileSync('./keypair.json', JSON.stringify(account))
Inside your JavaScript client you can extract this key by using the fromSecretKey
method.
import keyPair from './keypair.json';
const tempArraySecret = Object.values(keyPair._keypair.secretKey);
const secret = new Uint8Array(tempArraySecret)
const account = web3.Keypair.fromSecretKey(secret);
Upvotes: 2
Reputation: 8402
You can create a Keypair
instance using fromSecretKey
and passing in the array of bytes from your keypair file: https://solana-labs.github.io/solana-web3.js/classes/Keypair.html#fromSecretKey
There's a nice example doing exactly that: https://github.com/solana-labs/solana/blob/b16f2da44414be6f211352ed336812131622bae7/docs/src/developing/clients/javascript-reference.md#example-usage-2
Upvotes: 6