0

I'm attempting to create a keypair json I can save to my directory in solana.py that I can use on a local Solana test validator. Unsure if there's any built-in functions within solana.py to do so, I attempted to do it through converting the keypair instance created to a dict, then converting that dict to a json, and then I was intending to create a file from the json.

I ran into an issue though attempting to convert the dict into a json. Below is the code attempting to do so.

from solana.keypair import Keypair
import json

#Create Keypair
created_keypair = Keypair()

#Convert Keypair object to a dict
keypair_dict = created_keypair.__dict__
assert type(keypair_dict) is dict

#Convert dict to a json
keypair_json = json.dumps(keypair_dict)

The following is the error I'm running into when converting keypair_dict into a json.

TypeError: Object of type Keypair is not JSON serializable

1 Answer 1

3

That library misuses a bunch of words. I believe the secret_key field is in fact the full keypair (ed25519 secret/private keys are 32-bytes). You should be able to convert the byte array into a uint array and JSON encode that.

$ python3
Python 3.8.10 (default, Jun 22 2022, 20:18:18)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from solana.keypair import Keypair
>>> keypair = Keypair.generate()
>>> keypair.public_key
Bd4gfiEKWKeRairAHRbni6NHWmghQCksVHa7uMa9p2CD
>>> import json
>>> json.dumps([int(i) for i in keypair.secret_key])
'[180, 107, 77, 46, 147, 221, 193, 153, 12, 122, 232, 70, 37, 87, 183, 74, 134, 182, 192, 1, 4, 152, 198, 178, 121, 234, 26, 122, 176, 45, 249, 202, 157, 209, 241, 157, 189, 171, 216, 122, 125, 17, 77, 237, 208, 239, 88, 136, 90, 91, 38, 166, 190, 152, 159, 13, 250, 243, 8, 100, 68, 162, 78, 38]'
>>>
$ cat >test.json <<<'[180, 107, 77, 46, 147, 221, 193, 153, 12, 122, 232, 70, 37, 87, 183, 74, 134, 182, 192, 1, 4, 152, 198, 178, 121, 234, 26, 122, 176, 45, 249, 202, 157, 209, 241, 157, 189, 171, 216, 122, 125, 17, 77, 237, 208, 239, 88, 136, 90, 91, 38, 166, 190, 152, 159, 13, 250, 243, 8, 100, 68, 162, 78, 38]'
$ solana-keygen pubkey test.json
Bd4gfiEKWKeRairAHRbni6NHWmghQCksVHa7uMa9p2CD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.