Introduction
In the ever-evolving landscape of blockchain technology, Solana has emerged as one of the most powerful blockchains, offering unparalleled performance and scalability for decentralized applications (dApps) and cryptocurrencies. At the heart of Solana's robust architecture lies one of the fundamental features known as Cross Program Invocation (CPI), a mechanism that revolutionizes program interactions. In this article, we will learn about Cross Program Invocation (CPI) in Solana, how that works, and how it can help developers to use existing program's instruction in their program.
What is Cross Program Invocation (CPI)?
Cross Program Invocation (CPI) in Solana fundamentally enables smart contracts, or programs, to seamlessly interact with one another, similar to functions invoking each other in traditional programming paradigms. In terms of blockchain, we can say CPI is when one program invokes instructions from another program. It is like an API that is internally calling other APIs. This enables developers to build modular and composable applications, facilitating code reuse, scalability, and security.
Example. Decentralized Voting Application
Imagine a decentralized voting application built on the Solana blockchain. This application allows users to cast votes securely and transparently without needing a central authority.
- Voter Registration: Jill wants to register as a voter in the decentralized voting application. She interacts with the voter registration smart contract, providing her identity details.
- Verification Program: The voter registration contract invokes a verification program using CPI. This program verifies Jill's identity against a list of eligible voters stored on-chain. If Jill's identity is verified, the program returns a positive verification status to the registration contract.
- Vote Casting: Once verified, Jill can cast her vote using the voting interface provided by the application. Her vote is recorded on the blockchain along with her verified identity.
This is just one of the examples in which Cross Program Invocation is being used. Many other dApps (Decentralized Applications) are using CPI to ease their tasks.
Program of Cross-Program Invocation (CPI)
Below is an example of a Solana program that uses CPI.
use anchor_lang::prelude::*;
use anchor_lang::solana_program::{program::invoke, system_instruction};
declare_id!("..."); //program id
#[program]
pub mod cpi_invoke {
use super::*;
pub fn sol_transfer(ctx: Context<SolTransfer>, amount: u64) -> Result<()> {
msg!("Starting SOL transfer...");
let from_pubkey = ctx.accounts.sender.to_account_info();
let to_pubkey = ctx.accounts.recipient.to_account_info();
let program_id = ctx.accounts.system_program.to_account_info();
msg!("Creating transfer instruction...");
let instruction = &system_instruction::transfer(&from_pubkey.key(), &to_pubkey.key(), amount);
msg!("Invoking transfer instruction...");
invoke(instruction, &[from_pubkey, to_pubkey, program_id])?;
msg!("SOL transfer successful!");
Ok(())
}
}
#[derive(Accounts)]
pub struct SolTransfer<'info> {
#[account(mut)]
sender: Signer<'info>,
#[account(mut)]
recipient: SystemAccount<'info>,
system_program: Program<'info, System>,
}
In the above code, we have used CPI from the transfer of SOL tokens between accounts. The sol_transfer function handles the transfer process by creating and invoking a transfer instruction confirming a successful transfer. The SolTransfer structure defines the necessary accounts: the sender who must sign the transaction, the recipient to receive the SOL, and the system_program to facilitate the transfer.
What is the depth of Cross Program Invocation (CPI)?
The depth of Cross Program Invocation (CPI) in Solana refers to the level of nesting allowed when one program invokes another program. In Solana, CPI supports a depth of up to 4 levels of nested invocations. This means that a program can invoke another program, which in turn can invoke a third program, and so on, up to a maximum of 4 levels deep.
However, it's essential to note that while Solana technically supports up to 4 levels of nested invocations, developers should consider the potential complexity and resource consumption associated with deeply nested CPI calls. Excessive nesting can lead to increased transaction costs, longer execution times, and potential resource exhaustion, impacting the performance and scalability of the application.
Therefore, developers should carefully design their programs and limit the depth of CPI calls to ensure optimal performance and efficiency within the Solana ecosystem.
Example of depth of Cross Program Invocation (CPI)
Imagine there are 6 programs; Program A, B, C, D, E, and F.
- Program A invokes instruction from program B; this is allowed as the depth will be 1.
- Program B invokes instruction from program C; this is allowed as the depth will be 2.
- Program C invokes instruction from program D; this is allowed as the depth will be 3.
- Program D invokes instruction from program E; this is allowed as the depth will be 4.
- Program E invokes instruction from program F; this is not allowed as the depth will be 5 and is not allowed by Solana.
Importance of CPI in Solana
Cross Program Invocation (CPI) plays an important role in Solana's ecosystem, unlocking many possibilities for developers. Some of them are-
- Modularity Promotion: CPI promotes modularity by allowing developers to break down their applications into reusable code components.
- Code Reusability: With CPI, developers can leverage existing code components across different applications, accelerating the development process and reducing maintenance overhead.
- Seamless Integration: Developers can invoke multiple programs to perform complex tasks, such as token swaps, identity verification, or data validation. This seamless integration of functionalities enhances the flexibility and versatility of Solana-based applications, enabling developers to build innovative solutions across various industries.
- Innovation Catalyst: Developers can experiment with different combinations of smart contracts and functionalities, leading to the creation of novel decentralized solutions.
- Scalability Enhancement: CPI contributes to the scalability of the Solana blockchain by promoting efficient resource utilization and minimizing overhead in program execution.
How CPI Works in Solana's Architecture?
Solana's unique account-based model forms the foundation for CPI. Following are the steps in which CPI works-
- Instruction Reception: Solana programs receive instructions as part of transactions sent to the blockchain.
- CPI Instruction Construction: If a program needs to invoke another program, it constructs a CPI instruction specifying the target program's ID and any required data.
- Dispatching CPI Instruction: The CPI instruction is added to the transaction's instruction list and sent to the Solana network for execution.
- Invocation of Target Program: When executed, the target program specified in the CPI instruction is invoked to perform its logic autonomously.
- Returning Control: After completion, the control returns to the caller program, allowing it to continue its execution.
- Complex Interactions: CPI enables programs to interact seamlessly, facilitating the development of complex decentralized applications on Solana.
How does signer privilege work in CPI?
In Solana, the signer privilege refers to the authority or permission granted to an account to sign transactions and authorize changes to the account's state. When using Cross Program Invocation (CPI) in Solana, the signer privilege plays a crucial role in determining the permissions required for invoking other programs.
In Solana. when one program asks another program to do something on its behalf, the permission for that action comes from the original request, not the second request.
Example: Suppose there is a transaction that triggers the execution of program A. Within program A's execution, it makes a CPI to program B. The signer privileges, which are the ability to modify data or transfer tokens, that were attached to the original transaction invoking program A, are passed along to program B during this CPI.
Suppose program A creates a PDA during its execution and then initiates a CPI to program B. Here, if program B needs to access or modify the data, it can do so as A authorized program B, but only within the scope of permissions and authority granted by A during CPI.
Challenges and Considerations in CPI
While CPI unlocks unprecedented opportunities, it also presents unique challenges. Resource management becomes paramount, as CPIs can impose significant computational overhead. Security considerations escalate with each invocation, necessitating robust validation mechanisms and error-handling protocols to mitigate risks effectively and uphold the integrity of the blockchain.
Conclusion
Cross Program Invocation (CPI) in Solana represents a paradigm advancement in blockchain development, allowing developers to create modular, scalable, and secure applications. Using CPI, developers can open up new frontiers of creativity, accelerating the adoption of decentralized technology throughout industries. As Solana continues to evolve, mastering CPI will be instrumental in realizing the full potential of blockchain technology and shaping a more inclusive and sustainable future.