Skip to main content

Balance-Conditional Transfers

In some use cases, you may want to execute a transfer if and only if an account has at least a certain balance.

It would be unsafe to check an account's balance using the lookup_accounts and then perform the transfer, because these requests are not be atomic and the account's balance may change between the lookup and the transfer.

You can atomically run a check against an account's balance before executing a transfer by using a control or temporary account and linked transfers.

Preconditions

1. Target Account Must Have a Limited Balance

The account for whom you want to do the balance check must have one of these flags set:

2. Create a Control Account

There must also be a designated control account. As you can see below, this account will never actually take control of the target account's funds, but we will set up simultaneous transfers in and out of the control account.

Executing a Balance-Conditional Transfer

The balance-conditional transfer consists of 3 linked transfers.

We will refer to two amounts:

  • The threshold amount is the minimum amount the target account should have in order to execute the transfer.
  • The transfer amount is the amount we want to transfer if and only if the target account's balance meets the threshold.

If the Source Account Has a Credit Balance

TransferDebit AccountCredit AccountAmountPending IdFlags
1SourceControlThreshold-flags.linked, pending
2---1flags.linked, void_pending_transfer
3SourceDestinationTransfer-N/A

If the Source Account Has a Debit Balance

TransferDebit AccountCredit AccountAmountPending IdFlags
1ControlSourceThreshold-flags.linked, pending
2---1flags.linked, void_pending_transfer
3DestinationSourceTransfer-N/A

Understanding the Mechanism

Each of the 3 transfers is linked, meaning they will all succeed or fail together.

The first transfer attempts to transfer the threshold amount to the control account. If this transfer would cause the source account's net balance to go below zero, the account's balance limit flag would ensure that the first transfer fails. If the first transfer fails, the other two linked transfers would also fail.

If the first transfer succeeds, it means that the source account did have the threshold balance. In this case, the second transfer cancels the first transfer (returning the threshold amount to the source account). Then, the third transfer would execute the desired transfer to the ultimate destination account.

Note that in the tables above, we do the balance check on the source account. The balance check could also be applied to the destination account instead.