Skip to content

Instantly share code, notes, and snippets.

@wphan
Last active August 30, 2024 18:18
Show Gist options
  • Save wphan/e21fc16eb2558cee820615cdf4ba2bbd to your computer and use it in GitHub Desktop.
Save wphan/e21fc16eb2558cee820615cdf4ba2bbd to your computer and use it in GitHub Desktop.
convert between common solana keypair formats
#!/Users/ww/.pyenv/versions/3.10.11/bin/python3
# Required parameters:
# @raycast.schemaVersion 1
# @raycast.title Convert Solana Private Key
# @raycast.mode fullOutput
# Optional parameters:
# @raycast.icon 🔒
# @raycast.argument1 { "type": "text", "placeholder": "Private key or filepath" }
# @raycast.packageName Solana utils
# Documentation:
# @raycast.description Converts solana private key from file to/from byte array and base58
# @raycast.author wphan
# @raycast.authorURL https://github.com/wphan
import sys
import base58
from solana.keypair import Keypair
import json
import os
def handle_privkey_str(contents):
private_key_bytes= None
if ',' in contents:
if not contents.startswith("[") and not contents.endswith("]"):
contents = "[" + contents + "]"
pk_array = bytes(json.loads(contents))
private_key_bytes = pk_array
else:
private_key_bytes = base58.b58decode(contents)
keypair = Keypair.from_secret_key(private_key_bytes)
base58_encoded_secret_key = base58.b58encode(keypair.secret_key).decode('utf-8')
print("Public Address:", keypair.public_key.to_base58().decode('utf-8'))
print("Private Key: ", base58_encoded_secret_key)
print("Private Key: ", json.dumps(list(keypair.secret_key)).replace(" ", ""))
abs_path = os.path.expanduser(sys.argv[1])
if os.path.exists(abs_path):
print(f"opening {abs_path}")
with open(abs_path, "r") as f:
contents = f.read().strip()
handle_privkey_str(contents)
else:
handle_privkey_str(sys.argv[1].strip())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment