From b59bd702c2133b1cd4d9f42f37a08616ff973bbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanis=C5=82aw=20Drozd?= Date: Tue, 27 Sep 2022 08:53:59 +0200 Subject: [PATCH] p2w: Monitor and realloc() + rent adjuist on cfg account size change (#305) * p2w: Monitor and realloc() + rent adjuist on cfg account size change * p2w/set_config: reorder data assignment and realloc() --- solana/pyth2wormhole/client/src/lib.rs | 3 +- .../pyth2wormhole/program/src/set_config.rs | 42 ++++++++++++++++++- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/solana/pyth2wormhole/client/src/lib.rs b/solana/pyth2wormhole/client/src/lib.rs index 92db445a..465fc48e 100644 --- a/solana/pyth2wormhole/client/src/lib.rs +++ b/solana/pyth2wormhole/client/src/lib.rs @@ -144,6 +144,8 @@ pub fn gen_set_config_tx( AccountMeta::new(owner.pubkey(), true), // payer AccountMeta::new(payer.pubkey(), true), + // system_program + AccountMeta::new(system_program::id(), false), ]; let ix_data = ( @@ -163,7 +165,6 @@ pub fn gen_set_config_tx( Ok(tx_signed) } - pub fn gen_set_is_active_tx( payer: Keypair, p2w_addr: Pubkey, diff --git a/solana/pyth2wormhole/program/src/set_config.rs b/solana/pyth2wormhole/program/src/set_config.rs index 87bf8247..417d3169 100644 --- a/solana/pyth2wormhole/program/src/set_config.rs +++ b/solana/pyth2wormhole/program/src/set_config.rs @@ -1,4 +1,13 @@ -use solana_program::pubkey::Pubkey; +use borsh::BorshSerialize; + +use solana_program::{ + program::invoke, + program_error::ProgramError, + pubkey::Pubkey, + rent::Rent, + system_instruction, + sysvar::Sysvar, +}; use solitaire::{ trace, AccountState, @@ -18,6 +27,8 @@ use crate::config::{ Pyth2WormholeConfig, }; +use std::cmp::Ordering; + #[derive(FromAccounts)] pub struct SetConfig<'b> { /// Current config used by the program @@ -26,11 +37,13 @@ pub struct SetConfig<'b> { pub current_owner: Mut>>, /// Payer account for updating the account data pub payer: Mut>>, + /// Used for rent adjustment transfer + pub system_program: Info<'b>, } /// Alters the current settings of pyth2wormhole pub fn set_config( - _ctx: &ExecutionContext, + ctx: &ExecutionContext, accs: &mut SetConfig, data: Pyth2WormholeConfig, ) -> SoliResult<()> { @@ -45,7 +58,32 @@ pub fn set_config( )); } + let old_size = accs.config.info().data_len(); + let new_size = data.try_to_vec()?.len(); + + // Realloc if mismatched + if old_size != new_size { + accs.config.info().realloc(new_size, false)?; + } + accs.config.1 = data; + // Adjust lamports + let mut acc_lamports = accs.config.info().lamports(); + + let new_lamports = Rent::get()?.minimum_balance(new_size); + + let diff_lamports: u64 = (acc_lamports as i64 - new_lamports as i64).abs() as u64; + + if acc_lamports < new_lamports { + // Less than enough lamports, debit the payer + let transfer_ix = system_instruction::transfer( + accs.payer.info().key, + accs.config.info().key, + diff_lamports, + ); + invoke(&transfer_ix, ctx.accounts)?; + } + Ok(()) }