JS/TS Client

Anchor provides a Typescript client library (@coral-xyz/anchor) that simplifies the process of interacting with Solana programs from the client in JavaScript or TypeScript.

Program en el Cliente #

To use the client library, first create an instance of a Program using the IDL file generated by Anchor.

Creating an instance of the Program requires the program's IDL and an AnchorProvider. An AnchorProvider is an abstraction that combines two things:

  • Connection - la conexión a un clúster de Solana (es decir, localhost, devnet, mainnet)
  • Wallet - (opcional) una billetera por defecto utilizada para pagar y firmar transacciones

When integrating with a frontend using the wallet adapter, you'll need to set up the AnchorProvider and Program.

import { Program, AnchorProvider, setProvider } from "@coral-xyz/anchor";
import { useAnchorWallet, useConnection } from "@solana/wallet-adapter-react";
import type { HelloAnchor } from "./idlType";
import idl from "./idl.json";
 
const { connection } = useConnection();
const wallet = useAnchorWallet();
 
const provider = new AnchorProvider(connection, wallet, {});
setProvider(provider);
 
export const program = new Program(idl as HelloAnchor, {
  connection,
});

In the code snippet above:

  • idl.json is the IDL file generated by Anchor, found at /target/idl/<program-name>.json in an Anchor project.
  • idlType.ts is the IDL type (for use with TS), found at /target/types/<program-name>.ts in an Anchor project.

Alternativamente, puedes crear una instancia del Program utilizando solo el IDL y la Connection a un clúster de Solana. This means there is no default Wallet, but allows you to use the Program to fetch accounts or build instructions without a connected wallet.

import { clusterApiUrl, Connection, PublicKey } from "@solana/web3.js";
import { Program } from "@coral-xyz/anchor";
import type { HelloAnchor } from "./idlType";
import idl from "./idl.json";
 
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
 
export const program = new Program(idl as HelloAnchor, {
  connection,
});

Instrucciones de invocación #

Once the Program is set up using a program IDL, you can use the Anchor MethodsBuilder to:

  • Build individual instructions
  • Build transactions
  • Build and send transactions

The basic format looks like the following:

program.methods - This is the builder API for creating instruction calls from the program's IDL

await program.methods
  .instructionName(instructionData)
  .accounts({})
  .signers([])
  .rpc();

Anchor provides multiple methods for building program instructions:

The rpc() method sends a signed transaction with the specified instruction and returns a TransactionSignature.

When using .rpc, the Wallet from the Provider is automatically included as a signer.

// Generate keypair for the new account
const newAccountKp = new Keypair();
 
const data = new BN(42);
const transactionSignature = await program.methods
  .initialize(data)
  .accounts({
    newAccount: newAccountKp.publicKey,
    signer: wallet.publicKey,
    systemProgram: SystemProgram.programId,
  })
  .signers([newAccountKp])
  .rpc();

Solicitar cuentas #

The Program client simplifies the process of fetching and deserializing accounts created by your Anchor program.

Use program.account followed by the name of the account type defined in the IDL. Anchor provides multiple methods for fetching accounts.

Use all() to fetch all existing accounts for a specific account type.

const accounts = await program.account.newAccount.all();