6

Is there a simple way to set up a new AnchorProvider to create a new Program without a connected wallet? Below is a workaround by creating a placeholder wallet, is there a better way?

// Create a mock wallet as placeholder to set up AnchorProvider
const MockWallet = {
  signTransaction: () => Promise.reject(),
  signAllTransactions: () => Promise.reject(),
  publicKey: Keypair.generate().publicKey,
}

// Create a connection to cluster
const connection = new Connection(clusterApiUrl("..."))

// Create an AnchorProvider using connection and mock wallet
const provider = new AnchorProvider(connection, MockWallet, {})

// Set the provider as the default provider
setProvider(provider)

// Create a new Program
const programId = new PublicKey("...")
export const program = new Program(
  IDL as Idl,
  programId
) as unknown as Program<MyProgram>
0

2 Answers 2

2

NodeWallet with random keypair may be not the best option. If you look deeper into anchor typescript client, u will see, that Program client requires Provider interface and this interface has only one required field - connection, the rest is optional. So here is the best solution of ur problem:

const connection = new Connection(clusterApiUrl("..."))
const anonymousProgram = new Program<MyProgram>(IDL, PROGRAM_ID, { connection })
2

You can solve this issue by using NodeWallet

Here is an example

import * as anchor from "@project-serum/anchor";
import NodeWallet from "@project-serum/anchor/dist/cjs/nodewallet";
import { clusterApiUrl, Connection, Keypair, PublicKey } from "@solana/web3.js";
import ProgramIDL from "./thread_program.json";

async function main() {
  let connection = new Connection(clusterApiUrl("devnet"));
  let wallet = new NodeWallet(new Keypair());
  const provider = new anchor.AnchorProvider(connection, wallet, {
    commitment: "processed",
  });

  const programId = ProgramIDL.metadata.address;
  const program = new anchor.Program(
    ProgramIDL as anchor.Idl,
    programId,
    provider
  );

  ...
}

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.