How do I transfer lamports between 3 accounts owned by my program and system program?

Let’s say I have 3 accounts: A (owned by my program), B (owned by system program), and C (owned by system program).

B and C are from wallets. C is signed. B is not.

I want to transfer some amount from A to B in my program. Since this debits A, I can simply do:

**B.try_borrow_mut_lamports()? += some_amount;
**A.lamports.borrow_mut() -= some_amount;

Now I want to transfer a different amount from C to A in my program. Since this debits C which is owned by the system program, I’ll have to use system_instruction::transfer. Otherwise, I’d get the error: ExternalAccountLamportSpend:

invoke(
    &system_instruction::transfer(
        &C_pubkey,
        &A_pubkey,
        new_amount
    ),
    &[
        C.clone(),
        A.clone()
    ]
)?;

However, when I do both transfers, I’ll get the error: UnbalancedInstruction. But any one transfer works on its own.

How do I get around this issue? I’m not sure why it is unbalanced. If anything, the two transfers are not really related to each other.

Thank you!

1 Like

Hey @t4n1n well explained question!

Unfortunately I’m not sure what the answer is, and more unfortunately I’m pretty much the only person answering questions on the forum so you’ll probably have better luck on the Solana discord, again…

Good luck! :slight_smile:

No worries. I’ve asked in Discord.

I’ve figured out the workaround though. If I do invoke first, then it works.

There seems to be a check around modified lamports before calling invoking. But I’m not sure how to find out more about it. It sounds like a bug because the order of operations shouldn’t matter here.

Where should I report an issue like this?

I’m pretty sure a GitHub issue makes the most sense:

1 Like

I’m currently dealing with this issue. Have you found any solution for that?

1 Like