2

I have a couple deployed programs on Devnet. Is there a standard way of calling functions on a deployed program, assuming I have the IDL?

Obviously I could write a test but a test typically deploys a new program instance.

In ETH, the equivalent is creating a new contract instance with an address + ABI.

Curious if there is an equivalent in anchor that I can theoretically call via some command...

1 Answer 1

3

If you want to use anchor test but want to skip the deploy process, you can add the flag --skip-deploy to the command.

Additionally, if you want to use a script or a frontend to call your program, you'll want to follow a few steps:

Import Anchor:

import * as anchor from "@coral-xyz/anchor";

Initialize a connection:

const connection = new anchor.web3.Connection("<your RPC endpoint>", 'confirmed');

Initialize the anchor provider:

const opts = {
  preflightCommitment: 'processed' as anchor.web3.ConfirmOptions,
};

const provider = new anchor.AnchorProvider(
  connection,
  wallet as anchor.Wallet, //if using typescript
  opts.preflightCommitment
);

Import your IDL from "/target/types/<program_name>.ts":

import { StockpileV2 } from "../idl/idl";
import { IDL } from "../idl/idl";

Reference your program:

const idl = IDL as anchor.Idl;
const program = new anchor.Program(
   idl,
   new PublicKey("<programId>"),
   provider
) as unknown as anchor.Program<ProgramNamespace>;

Now you can call instructions from your program:

let tx = await program.methods
   .someInstruction(<some args...>)
   .accounts({
      // some accounts...
}).rpc();

Or:

// make sure @solana/web.js is installed
let tx = new Transaction();

let instruction = await program.methods
   .someInstruction(<some args...>)
   .accounts({
      // some accounts...
}).instruction();

tx.add(instruction);

Writing anchor tests will look somewhat similar to this, and implementation will vary.

Quick note: A good practice I've benefitted from is exporting the connection instance, and creating reusable functions for initializing your provider & program. This helps keep your code brief and readable (can add an edit showing this if needed)

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.