solanasolana-web3jsanchor-solana

How to specify instruction of anchor program with solana web3 js?


In @solana/web3.js when you create a transaction instruction, you specify pubkeys of your accounts, program id, and just raw bytes of your "data" parameter. In anchor program you declare your module to be a program with corresponding attribute, and now your pub functions become instructions. I could not find in the anchor book, how specifically they serialize their instruction name. How do I specify for my JavaScript frontend which instruction do I want it to execute?


Solution

  • How do I specify for my JavaScript frontend which instruction I want it to execute?

    Anchor uses IDL(Interface Description Language) for this purpose. whenever you complete your Solana program you can build it(anchor build). With this command, you have exported idl in root/target/idl folder. You can deploy this file to Solana network and fetch it and make a program in any client like ts(typescript) because of its mapping. You can open up one of the IDL.json files for better understanding. with this file, you can call instructions or use accounts of your Solana program.

    Also, you have another file with ts extension inside root/target/types. We use this file inside anchor test for creating a program with that and also for specifying which instruction or account we want to use. Also, this file is useful for creating anchor programs inside clients. Because this file contains "export const IDL.....". So, we can use this file for creating program like this:

    import { PROGRAM_ID } from "./constants"; //program account public key
    import { IDL } from "./your_directory_of_programs"; // directory of copy/paste types/your_program.ts file
    
    export function getProgramInstance(connection, wallet) {
      if (!wallet.publicKey) return;
      const provider = new anchor.AnchorProvider(
        connection,
        wallet,
        anchor.AnchorProvider.defaultOptions()
      );
      // Read the generated IDL.
      const idl = IDL;
      // Address of the deployed program.
      const programId = PROGRAM_ID;
      // Generate the program client from IDL.
      const program = new anchor.Program(idl, programId, provider);
      return program;
    }
    
    

    and call any instruction like this:

    await program.methods.yourInstruction().accounts({}).signers().rpc();
    

    Read this part of the Solana Cookbook for more details of what's going on when we want to call instruction of program from TS or any other clients.