Question about the process you are performing in Placing Orders in DEX Sample

Hello,
I was reading the code in the DEX Sample and was wondering about the part where the trade is actually executed.

In the description of the dox, it says that it only executes the exact matching order.

DEX Sample - Placing Orders

After depositing funds to the exchange, the user can place orders. An order consists of two tuples. from: (Token1, amount1) and to: (Token2, amount2) . These orders get added to the exchange. What happens to these orders is specific to the exchange implementation. This sample provides a simple exchange that only executes exactly matching orders. Be aware this is just a toy exchange, and the exchange functionality is just for completeness. Hint: The exchange can be greedy sometimes :wink:

The code, on the other hand, executes the order if it is a partial match, and the tokens left over from the trade seem to be tokens back to the DEX itself.

examples/exchange.mo

What specific calculations are being performed here to scrutinize the order?

  • What is the reason for calculating the a_to_amount and b_to_amount?
  • What are the implications of this calculation?

[exchange.mo]

            label iter_matches for(b in matches.vals()) {
                var a_to_amount = 0;
                var b_to_amount = 0;
                // Check if some orders can be completed in their entirety.
                if (b.fromAmount >= a.toAmount) {
                    a_to_amount := a.toAmount;
                };
                if (a.fromAmount >= b.toAmount) {
                    b_to_amount := b.toAmount;
                };

                // Check if some orders can be completed partially.
                if (a_to_amount == 0 and b_to_amount > 0) {
                    a_to_amount := b.fromAmount;
                    // Verify that we can complete the partial order with natural number tokens remaining.
                    if ((a_to_amount * a.fromAmount) % a.toAmount != 0)
                    {
                        continue iter_matches;
                    };
                };
                if (b_to_amount == 0 and a_to_amount > 0) {
                    b_to_amount := a.fromAmount;
                    // Verify that we can complete the partial order with natural number tokens remaining.
                    if ((b_to_amount * b.fromAmount) % b.toAmount != 0)
                    {
                        continue iter_matches;
                    };
                };

                if (a_to_amount > 0 and b_to_amount > 0) {
                    processTrade(dex, a, b, a_to_amount, b_to_amount);
                }
            };

I am afraid this is a question about the DEX mechanism itself.
Thank you in advance.