Skip to content

Commit cdc1681

Browse files
committed
added the possibility to return lamports back after an account has been shrunk
1 parent 7c601f7 commit cdc1681

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

core/rust/utils/src/account.rs

+21-10
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,28 @@ pub fn resize_or_reallocate_account_raw<'a>(
6565
) -> ProgramResult {
6666
let rent = Rent::get()?;
6767
let new_minimum_balance = rent.minimum_balance(new_size);
68+
let current_ta_lamports = target_account.lamports();
69+
let account_infos = &[
70+
funding_account.clone(),
71+
target_account.clone(),
72+
system_program.clone(),
73+
];
6874

69-
let lamports_diff = new_minimum_balance.saturating_sub(target_account.lamports());
70-
invoke(
71-
&system_instruction::transfer(funding_account.key, target_account.key, lamports_diff),
72-
&[
73-
funding_account.clone(),
74-
target_account.clone(),
75-
system_program.clone(),
76-
],
77-
)?;
78-
75+
// account will be shrunk
76+
if target_account.data_len() > new_size {
77+
let lamports_diff = new_minimum_balance.saturating_sub(current_ta_lamports);
78+
invoke(
79+
&system_instruction::transfer(funding_account.key, target_account.key, lamports_diff),
80+
account_infos,
81+
)?;
82+
} else {
83+
// account will be extended
84+
let excess_lamports = current_ta_lamports.saturating_sub(new_minimum_balance);
85+
invoke(
86+
&system_instruction::transfer(target_account.key, funding_account.key, excess_lamports),
87+
account_infos,
88+
)?;
89+
}
7990
target_account.realloc(new_size, false)?;
8091

8192
Ok(())

0 commit comments

Comments
 (0)