|
| 1 | +//! CPI API for interacting with the SPL shared memory |
| 2 | +//! [program](https://github.com/solana-labs/solana-program-library/tree/master/shared-memory). |
| 3 | +
|
| 4 | +use anchor_lang::{Accounts, CpiContext}; |
| 5 | +use solana_program::account_info::AccountInfo; |
| 6 | +use solana_program::declare_id; |
| 7 | +use solana_program::entrypoint::ProgramResult; |
| 8 | +use solana_program::instruction::{AccountMeta, Instruction}; |
| 9 | +use solana_program::program; |
| 10 | + |
| 11 | +// TODO: update this once the final shared memory program gets released. |
| 12 | +// shmem4EWT2sPdVGvTZCzXXRAURL9G5vpPxNwSeKhHUL. |
| 13 | +declare_id!("DynWy94wrWp5RimU49creYMQ5py3Up8BBNS4VA73VCpi"); |
| 14 | + |
| 15 | +/// `ret` writes the given `data` field to the shared memory account |
| 16 | +/// acting as a return value that can be used across CPI. |
| 17 | +/// The caleee should use this to write data into the shared memory account. |
| 18 | +/// The caler should use the account directly to pull out and interpret the |
| 19 | +/// bytes. Shared memory serialization is not specified and is up to the |
| 20 | +/// caller and callee. |
| 21 | +pub fn ret<'a, 'b, 'c, 'info>( |
| 22 | + ctx: CpiContext<'a, 'b, 'c, 'info, Ret<'info>>, |
| 23 | + data: Vec<u8>, |
| 24 | +) -> ProgramResult { |
| 25 | + let instruction = Instruction { |
| 26 | + program_id: *ctx.program.key, |
| 27 | + accounts: vec![AccountMeta::new(*ctx.accounts.buffer.key, false)], |
| 28 | + data, |
| 29 | + }; |
| 30 | + let mut accounts = vec![ctx.accounts.buffer]; |
| 31 | + accounts.push(ctx.program.clone()); |
| 32 | + program::invoke(&instruction, &accounts) |
| 33 | +} |
| 34 | + |
| 35 | +#[derive(Accounts)] |
| 36 | +pub struct Ret<'info> { |
| 37 | + #[account(mut)] |
| 38 | + pub buffer: AccountInfo<'info>, |
| 39 | +} |
| 40 | + |
| 41 | +// A set of accounts that can be used with shared memory. |
| 42 | +#[derive(Accounts)] |
| 43 | +pub struct Shmem<'info> { |
| 44 | + // Shared memory account to write the return value into. |
| 45 | + #[account(mut, "shmem.owner == shmem_program.key")] |
| 46 | + pub shmem: AccountInfo<'info>, |
| 47 | + #[account("shmem_program.key == &ID")] |
| 48 | + pub shmem_program: AccountInfo<'info>, |
| 49 | +} |
0 commit comments