React to FA2 receiving

The following question has been asked on Telegram:

My contract needs to know if a fa2 token is received in a function or not and then I will have to perform other logic.

Standard way in FA2: invert the control

The standard way in FA2 is to reverse the logic.

From (what you expected to do):

  1. Alice calls transfer on FA2.

  2. Contract C reacts to the receive.

To (what is recommended to do):

  1. Alice calls update_operators on FA2 to add C as operator.

  2. Alice calls C to start the logic.

  3. C reacts to call by calling transfer on FA2 from Alice’s token to itself.

  4. Alice calls update_operators on FA2 to remove C as operator.

Step 1, 2 and 4 starts a transaction. Those three transactions can be batched in one big batch-transaction.

1 Like

Here is a more detailed answer by chatGPT.
Please let me know if that’s useful.

Initiating FA2 Token Transfer and Performing Additional Logic by Inverting the Control

In FA2, a recommended approach to initiate a token transfer and execute additional logic is to invert the control. Instead of the contract reacting to a token transfer, the control is reversed by making the contract an operator and allowing it to manage the transfer. Here’s a step-by-step explanation:

  1. Add contract as an operator: Alice calls the update_operators entry point on the FA2 contract to add contract C as an operator. This grants C permission to manage Alice’s tokens on her behalf.

  2. Initiate the logic: Alice invokes a custom entry point (e.g., perform_logic) on contract C to start the process. Contract C will then manage the token transfer and execute any additional logic required.

  3. Contract C initiates the transfer and executes logic: In response to the perform_logic call, contract C calls the transfer entry point on the FA2 contract to initiate the transfer of tokens from Alice to itself or another destination. FA2 does not detect the receive; instead, it processes the transfer as instructed by contract C. After initiating the token transfer, contract C proceeds with the additional logic as needed.

  4. Remove contract as an operator: Once the process is complete, Alice calls the update_operators entry point on the FA2 contract again, this time to remove contract C as an operator, revoking its permission to manage her tokens.

By following these steps and inverting the control, contract C initiates the transfer of an FA2 token through a direct call from Alice and performs any additional logic as required. Keep in mind that the transition to the new syntax might require slight adjustments in the implementation, but the overall approach should remain the same.

1 Like