fahad
fahad

Reputation: 111

Sign a function call using private key solana/web3

I am trying to call a certain function of my custom smart contract on the solana blockchain using solana web3. I am trying to sign the function call using my private key instead of signing it through the phantom wallet. Is there any possible way to do that?

Upvotes: 0

Views: 1968

Answers (1)

shadeglare
shadeglare

Reputation: 7536

You can always compose a call for a solana program manually. Someting like this:

import * as fs from "fs";
import * as web3 from "@solana/web3.js";

const rawPayerKeypair = JSON.parse(fs.readFileSync("PATH_TO_KEYPAIR", "utf-8"));
const payerKeypair = web3.Keypair.fromSecretKey(Buffer.from(rawPayerKeypair));
const programId = new web3.Pubkey("CALLED_PROGRAM_ID");

const url = web3.clusterApiUrl("devnet");
const connection = new web3.Connection(url);

const instruction = new web3.TransactionInstruction({
  keys: [
    { pubkey: payerKeypair.publicKey, isSigner: true, isWritable: true }
  ],
  programId,
  // Put the transaction instruction here.
  data: Buffer.from([])
});
const transaction = new web3.Transaction().add(instruction);
const response = await web3.sendAndConfirmTransaction(connection, transaction, [payerKeypair]);
console.log(response);

Upvotes: 3

Related Questions