5

I'm trying to understand how these wallet extensions sign transactions before sending them to the blockchain. With Solana CLI, you can simply reference a keypair.json and transactions go through without the need of the fancy UI. Same thing with Sugar CLI commands. I would like to know how to do that in javascript, I'm looking for something like transaction.signer = pubkey.

I've dug as far as this on metaplex candy machine ui repo's code, but I can't find how this wallet.signAllTransactions work technically. enter image description here

1 Answer 1

4

You can create a Keypair object from a private key:

import { Keypair } from '@solana/web3.js'
import base58 from 'bs58'

const yourPrivateKey = 'abcdef...' // base58 encoded
const keypair = Keypair.fromSecretKey(base58.decode(yourPrivateKey))

A Keypair is a Signer, so you can pass it to eg. transaction.sign(keypair). See docs here

Internally a wallet extension has access to the private key, so it can create a Keypair object and use it to sign transactions.

BTW you don't need to be writing a wallet extension to make use of this. Other use cases could be a Node script or an API that can perform a Solana transaction without any user input.

To do the same directly from a keypair file you can use this:

import { Keypair } from '@solana/web3.js'
import fs from 'fs'

const bytes = JSON.parse(fs.readFileSync('/path/to/keypair.json'))
const keypair = Keypair.fromSecretKey(new Uint8Array(bytes));
console.log(keypair.publicKey.toBase58())

A keypair.json file contains a JSON array of the raw bytes, so you don't need to decode it.

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.