Import phantom wallet private key into solana CLI

Viewed 16685

I need to use a Phantom Wallet through the Solana CLI, but I'm unable to configure it.

For example, to check balance using

solana balance --keypair fileexportedfromphantom

but can't read the info.

How do I convert that private key into a valid form for use in Solana CLI?

2 Answers

Try:

solana-keygen recover 'prompt://?key=0/0' -o <file.json>

And enter the 24-word recovery phrase from Phantom under "Show Secret Recovery Phrase".

This is because Phantom uses the 0/0 derivation path for wallets and needs the extra provided path to get to the correct account.

You can use the same command with 1/0, 2/0 ... N/0 to get the different Phantom derived accounts.

See here for more info about hierarchical derivation with the Solana tools: https://docs.solana.com/wallet-guide/paper-wallet#hierarchical-derivation

Or use the Solflare wallet to check the derivation paths for your particular 24 word phrase here: https://solflare.com/access


As per the recent comment from @FutForFut, this assumes you have or want to use the Secret Recovery Phrase from Phantom. In certain cases, you might only have the private key from Phantom ("Show Private Key") in menus. This is a base58 encoded key, and you'll need to convert that into a byte-array in a JSON file.

Here's the Javascript snippet, using the bs58 package (https://www.npmjs.com/package/bs58):

const bs58 = require('bs58');
const fs = require('fs');
b = bs58.decode('privatekeyexportedfromphantom');
j = new Uint8Array(b.buffer, b.byteOffset, b.byteLength / Uint8Array.BYTES_PER_ELEMENT);
fs.writeFileSync('key.json', `[${j}]`);

Update fields privatekeyexportedfromphantom and key.json as required.

It's a bit annoying, but you'll have to decode the base-58 private key returned by Phantom into an array of bytes. Here's a simple Python code snippet to accomplish this, using the base58 package (https://pypi.org/project/base58/):

import base58
byte_array = base58.b58decode(MY_PRIVATE_KEY_IN_BASE58)
json_string = "[" + ",".join(map(lambda b: str(b), byte_array)) + "]"
print(json_string)

You can pipe that output to a file, and then use that as your --keypair with the CLI tools.

Related