@@ -3,6 +3,7 @@ use solana_program::{
3
3
entrypoint:: ProgramResult ,
4
4
msg,
5
5
program:: { invoke, invoke_signed} ,
6
+ program_error:: ProgramError ,
6
7
pubkey:: Pubkey ,
7
8
rent:: Rent ,
8
9
system_instruction,
@@ -65,31 +66,38 @@ pub fn resize_or_reallocate_account_raw<'a>(
65
66
) -> ProgramResult {
66
67
let rent = Rent :: get ( ) ?;
67
68
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
+
69
75
let account_infos = & [
70
76
funding_account. clone ( ) ,
71
77
target_account. clone ( ) ,
72
78
system_program. clone ( ) ,
73
79
] ;
74
80
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 ( ) {
78
82
invoke (
79
83
& system_instruction:: transfer ( funding_account. key , target_account. key , lamports_diff) ,
80
84
account_infos,
81
85
) ?;
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 {
85
87
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 ) ,
87
89
account_infos,
88
90
) ?;
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 ) ?;
89
98
}
90
- target_account. realloc ( new_size, false ) ?;
91
99
92
- Ok ( ( ) )
100
+ target_account . realloc ( new_size , false )
93
101
}
94
102
95
103
/// Close src_account and transfer lamports to dst_account, lifted from Solana Cookbook
0 commit comments