How to do Cross Program Invocation
A cross program invocation, is simply put calling another program's instruction
inside our program. One best example to put forth is Uniswap's swap
functionality. The UniswapV2Router
contract, calls the necessary logic to
swap, and calls the ERC20
contract's transfer function to swap from one person
to another. The same way, we can call a program's instruction to have multitude
of purposes.
Lets have a look at our first example which is the
SPL Token Program's transfer
instruction. The required accounts we would need
for a transfer to happen are
- The Source Token Account (The account which we are holding our tokens)
- The Destination Token Account (The account which we would be transferring our tokens to)
- The Source Token Account's Holder (Our wallet address which we would be signing for)
The corresponding client instruction would be as follows. For knowing the mint and token creation instructions, please refer to the full code nearby.
Now let's take a look at another example, which is
System Program's create_account
instruction. There is a slight difference
between the above mentioned instruction and this. There, we never had to pass
the token_program
as one of the accounts inside the invoke
function.
However, there are exceptions where you are required to pass the invoking
instruction's program_id
. In our case it would be the System Program's
program_id. ("11111111111111111111111111111111"). So now the required accounts
would be
- The payer account who funds the rent
- The account which is going to be created
- System Program account
The respective client side code will look as follows