如何使用我的私钥文件加载我的 Solana 钱包?

How do I load my Solana wallet using my private key file?

我正在尝试使用我通过 Solana 命令行生成的私钥在 JavaScript / Node.js 中创建一个钱包。 我想使用 web3.Keypair.fromSeed() 方法。

这是我目前采取的步骤。

  1. 创建了一个 solana 钱包:solana-keygen new -o keyfile.json
  2. 显示该文件中的内容——它是一个 64 字节数组(这是一个测试密钥,所以不用担心这个 私钥

[237,158,92,107,132,192,1,57,8,20,213,108,29,227,37,8,3,105,196,244,8,221,184,199,62,253,98,131,33,165,165,215,14,7,46,23,221,242,240,226,94,79,161,31,192,163,13, 25,106,53,34,215,83,124,162,156,8,97,194,180,213,179,33,68]

但是,对 fromSeed() 的调用只需要 32 个字节。 3. 检查 solana 地址,以便我知道什么时候一切正常:

>  solana address -->
wm4MapPtFaUoSsyBJppVnChYMGvHzTeAL6BNZ5GmSqH

那是 public 键

如何调用 web3.Keypair.fromSeed() 来加载私钥并获取我的 public 地址(又名 public 密钥)?

let web3 = require('@solana/web3.js');
let splToken = require('@solana/spl-token');

// load up the first 32 bytes of the 64 byte array that was in our keyfile.json
// Only need the first 32 bytes so I use slice() just to make sure it's the correct length
let firstWinPrivKey = [237,158,92,107,132,192,1,57,8,20,213,108,29,227,37,8,3,105,196,244,8,221,184,199,62,253,98,131,33,165,165,215,14,7,46,23,221,242,240,226,94,79,161,31,192,163,13,25,106,53,34,215,83,124,162,156,8,97,194,180,213,179,33,68]
    .slice(0,32);
  // print the length of the array so we know it is correct
  // the fromSeed() method requires 32 bytes

 console.log(firstWinPrivKey.length);
  let firstWinWallet = web3.Keypair.fromSeed(Uint8Array.from(firstWinPrivKey));
  console.log(firstWinWallet.secretKey);
  console.log(firstWinWallet.publicKey.toString());

请注意,您必须将数组转换为 Uint8Array (Uint8Array.from()) 当我们打印出 secretKey 时,您会看到您传入的相同字节。

最后,当我们打印出 publicKey 时,您会看到我们在命令行中看到的相同值

> solana address

现在您可以在代码中使用钱包了。

这是这个简短脚本的最终输出:

32
Uint8Array(64) [
  237, 158,  92, 107, 132, 192,   1,  57,   8,  20, 213,
  108,  29, 227,  37,   8,   3, 105, 196, 244,   8, 221,
  184, 199,  62, 253,  98, 131,  33, 165, 165, 215,  14,
    7,  46,  23, 221, 242, 240, 226,  94,  79, 161,  31,
  192, 163,  13,  25, 106,  53,  34, 215,  83, 124, 162,
  156,   8,  97, 194, 180, 213, 179,  33,  68
]
wm4MapPtFaUoSsyBJppVnChYMGvHzTeAL6BNZ5GmSqH