Maxence Dubois
Maxence Dubois

Reputation: 17

Connect to a Solana custom program without a wallet / frontend

I would like to be able to connect to my custom solana program without using any frontend object.

Currently, my provider method uses "window.solana" which I want to avoid.

The idea is to be able to sign transaction from a backend without having to retrieve object from a frontend. The transactions will be signed and paid directly by the program.

This how I am calling the my program now:

const network = clusterApiUrl("devnet");
const opts = {
    preflightCommitment: "processed",
};
const { SystemProgram } = web3;


const getProvider = () => {
        const connection = new Connection(network, opts.preflightCommitment);
        const provider = new AnchorProvider(
            connection,
            window.solana,
            opts.preflightCommitment
        );
        return provider;
    };

const provider = getProvider();
const program = new Program(idl, programID, provider);

Upvotes: 1

Views: 973

Answers (1)

Fawnzee
Fawnzee

Reputation: 46

Anchor's Wallet class allows for exactly that form of implementation, as it is inherited from NodeWallet.

You need to instantiate an @solana/web3.js Keypair object, likely from your provided secret key, and then pass the keypair into the Anchor Wallet constructor. You can then pass the Wallet object into the AnchorProvider, no frontend adapters needed.

For your code, see below, where the Base58SecretKey comes from exporting private key of your desired signer on Phantom (or another wallet). You can also import the keypair using a uint8 array or Keypair.generate() for testing, if you prefer.

import * as anchor from "@project-serum/anchor";

const getProvider = () => {
        const connection = new Connection(network, opts.preflightCommitment);
        const keypair = new anchor.web3.Keypair.fromSecretKey(anchor.utils.bytes.bs58.decode("Base58SecretKey"))
        const wallet = new Wallet(keypair);
        const provider = new AnchorProvider(
            connection,
            wallet,
            opts.preflightCommitment
        );
        return provider;
    };

Upvotes: 1

Related Questions