1

我正在尝试在以太坊上使用 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);
})();
4

1 回答 1

1

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

至于你的其他问题,requestAirdrop需要 a 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

于 2021-09-29T09:57:51.960 回答