Run the Example
First go through the Setup process to get your development environment configured, then clone thev23.0.0 tag of soroban-examples repository:
cargo test.
Code
atomic_swap/src/lib.rs
How it Works
The example contract requires twoAddress-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
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
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 theatomic_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.