shmem.rs 1.9 KB

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