Skip to content

Commit 777df49

Browse files
committed
fixed behaviour
1 parent cdc1681 commit 777df49

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

core/rust/utils/src/account.rs

+18-10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use solana_program::{
33
entrypoint::ProgramResult,
44
msg,
55
program::{invoke, invoke_signed},
6+
program_error::ProgramError,
67
pubkey::Pubkey,
78
rent::Rent,
89
system_instruction,
@@ -65,31 +66,38 @@ pub fn resize_or_reallocate_account_raw<'a>(
6566
) -> ProgramResult {
6667
let rent = Rent::get()?;
6768
let new_minimum_balance = rent.minimum_balance(new_size);
68-
let current_ta_lamports = target_account.lamports();
69+
let lamports_diff =
70+
new_minimum_balance.abs_diff(target_account.lamports());
71+
if lamports_diff == 0 {
72+
return Ok(());
73+
}
74+
6975
let account_infos = &[
7076
funding_account.clone(),
7177
target_account.clone(),
7278
system_program.clone(),
7379
];
7480

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);
81+
if new_size > target_account.data_len() {
7882
invoke(
7983
&system_instruction::transfer(funding_account.key, target_account.key, lamports_diff),
8084
account_infos,
8185
)?;
82-
} else {
83-
// account will be extended
84-
let excess_lamports = current_ta_lamports.saturating_sub(new_minimum_balance);
86+
} else if target_account.owner == system_program.owner {
8587
invoke(
86-
&system_instruction::transfer(target_account.key, funding_account.key, excess_lamports),
88+
&system_instruction::transfer(target_account.key, funding_account.key, lamports_diff),
8789
account_infos,
8890
)?;
91+
} else {
92+
(**target_account.try_borrow_mut_lamports()?)
93+
.checked_sub(lamports_diff)
94+
.ok_or(ProgramError::InvalidRealloc)?;
95+
(**funding_account.try_borrow_mut_lamports()?)
96+
.checked_add(lamports_diff)
97+
.ok_or(ProgramError::InvalidRealloc)?;
8998
}
90-
target_account.realloc(new_size, false)?;
9199

92-
Ok(())
100+
target_account.realloc(new_size, false)
93101
}
94102

95103
/// Close src_account and transfer lamports to dst_account, lifted from Solana Cookbook

0 commit comments

Comments
 (0)