In a transaction, I’m trying to close an ATA and a PDA. The ATA is closed by calling close_account from the SPL Token 2022 crate / On Chain Program, and the rent exemption can be sent without any issue to the signing & transaction fee payer account.
For the PDA (called record below) though, I haven’t managed to do it. I can close the account, but only if I send the rent exemption lamports to an ad-hoc account that I add to the transaction just for that purpose. If I try to send the rent exemption to the signing & fee transaction payer account, I get an error: sum of account balances before and after instruction do not match. The accounts are all writable in this context.
Basically, the code is:
for account in accounts {
instruction_whatever(account)?;
let lamports = account.lamports();
**account.try_borrow_mut_lamports()? -= lamports;
**payer.try_borrow_mut_lamports()? += lamports;
}
another_instruction()?;
It works just fine if I replace payer by a 'random' account, but otherwise it doesn’t work and it’s a bit annoying to have to use another account just for that.
I’m guessing it has to do with the balance of the paying account being changed to pay for the transaction and messing things up, but it feels weird. Is there a trick that I’ve missed somewhere?