Solana: How to call up an anchor program that has a pda using cpi

**Calling an Anchor Program with PDA in Solana with C++

Anchor programs are a core part of the Solana ecosystem, enabling distributed, self-executing contracts. In this article, we will explore how to call an anchor program from another Solana program, especially when the called program has its own PDA (Program Data Area). We will cover both the intro and the main parts of the code.

Prerequisites

Before diving into the example, make sure you have a basic understanding of Solana, Anchor programs, and C++. You will also need to have the Solana CLI setup on your machine. In this example, we will use the Solana CLI to interact with our Anchor program and the “solana-program” library.

Program A: Initialize the PDA

Anchor program A (A) has an initialization function that initializes its own PDA:

pragma strength ^0,8,0;

import "

import "

contract AnchorProgramA {

// Initialize the PDA

function initializePda() public {

// Create a new SafeERC20 instance and set the base URI

uint256 _baseUri = 0x5cC7bDf9a1d1F5e8E39f7e24c3AeBf6e1b34e78a4a2ef2a0f7df;

// Create a new SafeERC20 instance with the base URI

SafeERC20 _pda = SafeERC20(_baseUri);

}

}

Anchor Program B: Calling A’s initialization function

Anchor Program B (B) wants to call the initialization function of “A”. We create a hook program that calls “A” and then returns control back to the caller.

pragma strength ^0,8,0;

import "

import "

contract AnchorProgramB {

// Call A's initialization function and get the PDA

function callA() public {

// Call A's initialization function

AnchorProgramA(A).initializePda();

// Get PDA from A

uint256 _pda = solana_program.decode_pda(A);

}

}

Solution B

In order for “B” to call the called program, we need a way to interact with it. We can use the “solana-program” library to create an anchor program that can call another one.

pragma strength ^0,8,0;

import "

import "

import "

contract SolanaAnchor {

// Call the A initialization function and get the PDA

function callA() public {

AnchorProgramA(A).initializePda();

uint256 _pda = solana_program.decode_pda(A);

}

}

Return B to call A

To get “B” back to call “A”, we need a way to interact with the Solana anchor program. We can use the “solana-program” library to create an anchor program that calls another one.

pragma strength ^0,8,0;

import "

import "

import "

contract SolanaProgram {

// Call the function to initialize B and get the PDA

function callB() public {

AnchorProgramB(B).callA();

}

}

Example

Here is an example of how the “SolanaAnchor” and “SolanaProgram” programs can be used in a more complex scenario:

“`strength

pragma strength ^0,8,0;

import “