【问题标题】:How to save keypairs and send tokens in Solana, using node.js?如何使用 node.js 在 Solana 中保存密钥对和发送令牌?
【发布时间】:2021-11-20 22:55:39
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js cryptography solana


    【解决方案1】:

    要将生成的密钥对保存在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2021-01-07
      • 2017-01-02
      • 1970-01-01
      • 2019-10-13
      • 2019-12-15
      • 1970-01-01
      相关资源
      最近更新 更多