如何使用 node.js 在 Solana 中保存密钥对和发送令牌?

How to save keypairs and send tokens in Solana, using node.js?

我正在尝试在以太坊上使用 Solana 作为特定解决方案。

我正在使用 NPM 来定位 Solana 的 API。使用的包是 @solana/web3.js@solana/spl-token。我已经能够成功创建连接并生成密钥对。我希望能够保存生成的密钥对,但我面临的问题是它是经过编码的,第二个要强调的问题是当我使用 .toString(); 时。它解码得很好,但不能用于空投。

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);
})();

要在 JS 中保存生成的密钥对,最好的办法是在密钥对对象 [1] 上使用 secretKey,然后将其写入文件。要重新加载它,您将读取该文件,然后使用 fromSecretKey 取回您的密钥对 [2]

至于你的其他问题,requestAirdrop 需要一个 PublicKey,所以你应该这样做:

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