Unlocking Solana's Potential: A Deep Dive into Cross-Program Invocation (CPI)
Published: 2024-02-29 20:03:32

This blog explores Cross-Program Invocation (CPI) within Solana – a crucial tool for enhancing the capabilities of your DApps.

Let's delve into the essence of CPI and its significance for your Solana programs.

## What is Cross-Program Invocation (CPI)?
At its core, CPI empowers Solana programs to seamlessly communicate and collaborate with each other. Imagine breaking down your applications into modular components, each fulfilling a specific role, and effortlessly allowing them to interact. This is the essence of CPI – an avenue for enhanced modularity, scalability, and collaboration within the Solana blockchain.

## Why Should You Use CPI in Your Solana Program?
**Modularity and Reusability**
CPI fosters a modular approach to development, enabling you to craft independent components that can be reused across projects. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kscfpbjtkwwe29b8j9om.png)
This streamlines your coding process and enhances the maintainability of your Solana programs.

**Scalability**
Each Solana program can focus on a specific task, and through CPI, these programs collaborate seamlessly to achieve more complex functionalities.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tpz6q89s6s53rgjva1wy.png)
Your applications can scale with efficiency and adaptability.

**Enhanced Collaboration**
CPI enables you to leverage and contribute to a growing repository of programs on Solana.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/geibapfwxeoj02hpwmtm.png)
CPI facilitates collaboration between developers and teams. Different programs can be developed independently, and CPI acts as the bridge that connects these programs.


## Cross-Program Invocation (CPI) in Solana Development
**Overview**
Developers can leverage CPI for calling between programs, achieved by one program invoking an instruction of the other. The invoking program is halted until the invoked program finishes processing the instruction. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzua2p7smuyznojl8rto.png)
You could think of CPI like sending a t-shirt through FedEx. The sender goes to the FedEx office, drops off a package and pays the fee. FedEx handles the transport and delivery, then provides you correspondence of delivery. Only in this case the calling program (you) wait at the FedEx office until the package is delivered.

**Under the Hood**
A client could create a transaction that modifies two accounts, each owned by separate on-chain programs. 

In this example, there are two on-chain programs, `drip` and `creator`.

```
let message = Message::new(vec![
    drip_instruction::subscribe(&dragon_pubkey),
    creator_instruction::airdrop_art(&slayer_pubkey),
]);
client.send_and_confirm_message(&[&dragon_keypair, &slayer_keypair], &message);
```
In this modified example, the client allows the `drip` program to perform various operations, including invoking instructions from the `creator` program. 

```
let message = Message::new(vec![
    drip_instruction::execute_operations(&dragon_pubkey, &slayer_pubkey),
]);
client.send_and_confirm_message(&[&dragon_keypair, &slayer_keypair], &message); 
```

The `drip` program has a function `execute_operations()` that combines actions such as subscribing and airdropping art. 

```
mod drip {
    use creator_instruction;

    fn airdrop_art(accounts: &[AccountInfo]) -> Result<()> {
        // Implementation for airdropping art
        ...
    }

    fn execute_operations(accounts: &[AccountInfo]) -> Result<()> {
        let dragon_pubkey = accounts[1].key;
        let creator_instruction = creator_instruction::subscribe(&dragon_pubkey);
        invoke(&creator_instruction, accounts)?;

        airdrop_art(accounts)?;
    }
} 
```
In the `drip` module, the `execute_operations()` function is responsible for combining multiple actions, including the invocation of the `subscribe()` instruction from the `creator` program. The `invoke()` function is a built-in Solana runtime feature used to route instructions to the specified program via the instruction's `program_id` field.


## Benefits of Using CPI in Solana Programs
**Efficiency in Resource Utilization**
CPI optimizes resource utilization by allowing developers to leverage existing programs rather than building everything from scratch. This accelerates development cycles and reduces the overall resource footprint of Solana applications.

**Interoperability Across Projects**
Different Solana programs can be written in different languages or use different libraries. Cross-program invocations allow these programs to interact with each other regardless of their implementation details, promoting interoperability within the Solana ecosystem. This interoperability is crucial for the growth of the Solana ecosystem, fostering innovation and diversity in decentralized applications.

**Future-Proofing Your Projects**
Embracing CPI ensures that your Solana programs are future-proof. As the Solana ecosystem continues to evolve, the ability to interconnect programs becomes increasingly vital. By incorporating CPI, you position your projects to adapt to emerging standards and protocols.

**Security & Isolation**
By separating different components of your dApp into individual programs, you can enforce security boundaries and minimize the potential impact of bugs or vulnerabilities. Each program runs in its own isolated environment, reducing the risk of malicious attacks or unintended side effects.

## Examples of CPI with Popular Solana Programs
To provide a practical understanding of CPI, let's explore a few examples with popular Solana programs:

**Integration with Jupiter DEX**
Imagine integrating your custom liquidity management program with Jupiter's Decentralized Exchange (DEX) using CPI. This would enable your program to seamlessly interact with Jupiter's DEX, opening up new possibilities for decentralized finance applications.

**Collaboration with Mango Markets**
Utilizing CPI, you can create a Solana program that collaborates with Mango Markets, enhancing the capabilities of both programs. This collaborative approach can lead to the development of advanced decentralized trading strategies.

**Cross-Program Communication in DeFi Projects**
Implementing CPI in decentralized finance (DeFi) projects allows for cross-program communication between lending, borrowing, and yield farming programs. This modular approach fosters innovation and flexibility within the DeFi ecosystem on Solana.

**Escrowless P2P NFT Transactions on Marketplaces**
Auction House & Auctioneer are two programs deployed by Metaplex that, when coupled together via CPI, enable users to list and exchange assets on Solana without the need for a marketplace escrow service. The Auctioneer program manages the auction itself (i.e., the auction timer, bids, etc.), while the Auction House program manages the state of auctions (i.e., nft locking, token transfer, etc.). 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fok4h7pd6ix0507svatu.png)

The programming for this CPI is as follows:

```
    actor client as Client
    participant auctioneer as Auctioneer
    participant auctionHouse as Auction House

    client ->> +auctioneer : create timed auction
    alt CPI
        auctioneer ->> +auctionHouse : delegate nft
        auctionHouse ->> -auctioneer : ok
    end
    auctioneer ->> -client : auction created
```


As a result of CPI, instead of the tokens being locked in a centralized escrow wallet during the listing, users retain full custody of their NFTs without losing access to them. This means that users reap the benefits of their NFTs (i.e., receive airdrops, access any token-gated content, etc.) until the moment the NFT sells. The NFT and funds are directly exchanged between the creator and collector — meaning no middlemen.


## Case Study: Utilizing CPI to Solve the Existing Problem of Master Edition Interoperability
**Synopsis**
Independant creators on Solana can mint Limited & Open Edition NFTs to monetize their artwork. Open Editions are digital collectibles that can be minted without any limit to the number of copies that collectors can generate. Limited Editions are a similar concept, however the creator sets a certain limit for the number of collectible copies that can be printed.  

**Problem**
The Token Metadata program currently only supports printing editions from a master edition if the signer is also the owner of the token. This forces creators to escrow their master edition token when listing an edition sale on a marketplace, as the marketplace must be the owner of the token in order to print editions. This prevents the creator from being able to list their master edition to be printed on multiple marketplaces concurrently.

**Solution**
[MIP-7](https://github.com/metaplex-foundation/mpl-token-metadata/pull/84) is a Metaplex proposal that aims to solve the problem of composability and interoperability with master editions as it relates to printing editions concurrently across marketplaces. The implementation of the proposal would allow marketplace programs to act as the delegate print authority - when a user buys a print, the marketplace program calls the Token Metadata program via CPI with it's PDA as the signer to actually create the print. As a result, creators are empowered to list their master edition to be printed on multiple marketplaces concurrently.


## Conclusion
By incorporating CPI into your Solana programs, developers unlock endless possibilities. Your applications become more efficient, scalable, and ready to adapt to evolving standards and protocols within the Solana ecosystem.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgkrujfrryvi317cjk2l.png)
In conclusion, Cross-Program Invocation (CPI) is a powerful tool for builders, providing a pathway to modular, scalable, and collaborative development.

Stay tuned for more insights and hands-on guides as we continue to explore the frontiers of Solana developer infrastructure!

Happy coding!