Last active
December 9, 2024 20:02
-
-
Save ssadler/d1e36b725e4909cbe7b3c0c644cf1999 to your computer and use it in GitHub Desktop.
Anchor Refcell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this example, there are multiple "entites" made from multiple sets of accounts in the context. | |
// Would like to be able to pass around (partially) mutable entities, is use case for RefCell. | |
struct MyEntity<'a, 'b> { | |
pub &'a mut entity, | |
pub &'b ata | |
} | |
#[derive(Accounts)] | |
pub struct MyContext<'info> { | |
pub entity0: Account<'info, u64>, | |
pub entity0_ata: Account<'info, token::TokenAccount>, | |
pub entity1: Account<'info, u64>, | |
pub entity1_ata: Account<'info, token::TokenAccount> | |
} | |
impl<'info> MyContext<'info> { | |
fn get_entity0(&mut self) -> MyEntity { entity: &self.entity0, ata: &mut self.entity0_ata } // Bad borrows | |
fn get_entity1(&mut self) -> MyEntity { entity: &self.entity1, ata: &mut self.entity1_ata } | |
} | |
fn do_something_with_entity(ctx: &ctx, entity: mut MyEntity) {} | |
#[program] | |
pub mod my_program { | |
use super::*; | |
fn do_with_entity(ctx: Context<...>) -> Result<()> { | |
do_something_with_entity(&ctx, ctx.get_entity0()); | |
do_something_with_entity(&ctx, ctx.get_entity1()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment