Skip to main content
The atomic swap example swaps two tokens between two authorized parties atomically while following the limits they set. This is example demonstrates advanced usage of Soroban auth framework and assumes the reader is familiar with the auth example and with Soroban token usage. Open in Codespaces Open in Codeanywhere

Run the Example

First go through the Setup process to get your development environment configured, then clone the v23.0.0 tag of soroban-examples repository:
Or, skip the development environment setup and open this example in GitHub Codespaces or Code Anywhere. To run the tests for the example use cargo test.
You should see the output:

Code

atomic_swap/src/lib.rs
Ref: https://github.com/stellar/soroban-examples/tree/v23.0.0/atomic_swap

How it Works

The example contract requires two Address-es to authorize their parts of the swap operation: one Address wants to sell a given amount of token A for token B at a given price and another Address wants to sell token B for token A at a given price. The contract swaps the tokens atomically, but only if the requested minimum price is respected for both parties. Open the atomic_swap/src/lib.rs file or see the code above to follow along.

Swap authorization

Authorization of swap function leverages require_auth_for_args Soroban host function. Both a and b need to authorize symmetric arguments: token they sell, token they buy, amount of token they sell, minimum amount of token they want to receive. This means that a and b can be freely exchanged in the invocation arguments (as long as the respective arguments are changed too).

Moving the tokens

The swap itself is implemented via two token moves: from a to b and from b to a. The token move is implemented via allowance: the users don’t need to know each other in order to perform the swap, and instead they authorize the swap contract to spend the necessary amount of token on their behalf via transfer. Soroban auth framework makes sure that the transfer signatures would have the proper context, and they won’t be usable outside the swap contract invocation.

Tests

Open the atomic_swap/src/test.rs file to follow along. Refer to another examples for the general information on the test setup. The interesting part for this example is verification of swap authorization:
env.auths() returns all the authorizations. In the case of swap four authorizations are expected. Two for each address authorizing, because each address authorizes not only the swap, but the approve all on the token being sent.