Swap Execution Logic
The module executes swaps in both directions of the pair: the user sells BTC for USDT (Inventory Fill phase) or buys BTC for USDT (Inventory Release phase). Below are step-by-step scenarios for both directions and the exact inventory balance changes.
5.1 User sells BTC (BTC → USDT)
This is the Inventory Fill phase: the system buys BTC from the user and accumulates it.
Sequence:
- Rate fixing. The BTC/USDT rate is fixed through hedging: the trade price is determined at swap creation and does not change while the user completes their part.
- The user sends BTC to the address issued by the system.
- Waiting for confirmations. The system waits for the required number of network confirmations.
- Inventory crediting and payout. After confirmations, the system increases BTC inventory and sends USDT to the user.
Balance changes:
inventory_BTC += amount_BTC # BTC inventory grows (purchase)
inventory_USDT -= amount_USDT # USDT stock decreases (payout to the user)
Execution pseudocode:
on_swap_btc_to_usdt(amount_BTC):
rate = pricing_engine.final_rate(“BTC/USDT”) # rate fixing (hedging)
amount_USDT = amount_BTC * rate
btc_tx = await_user_deposit(amount_BTC) # user sends BTC
wait_confirmations(btc_tx) # network confirmations
inventory_BTC += amount_BTC # Inventory Fill
inventory_USDT -= amount_USDT
send_usdt_to_user(amount_USDT) # payout
5.2 User buys BTC (USDT → BTC)
This is the Inventory Release phase: the system sells BTC from previously accumulated inventory.
Sequence:
- Inventory check. BTC availability in inventory is verified: available_balance >= amount_BTC. If available BTC is insufficient, the trade is not executed from inventory.
- Rate fixing and swap creation.
- The user sends USDT.
- Payout from inventory. Previously accumulated BTC is used: the system deducts it from inventory, and the user receives BTC.
Balance changes:
inventory_BTC -= amount_BTC # BTC inventory decreases (sale from stock)
inventory_USDT += amount_USDT # USDT stock grows (user payment)
Execution pseudocode:
on_swap_usdt_to_btc(amount_BTC):
require inventory_BTC.available_balance >= amount_BTC # inventory check
rate = pricing_engine.final_rate(“BTC/USDT”)
amount_USDT = amount_BTC * rate
usdt_tx = await_user_payment(amount_USDT) # user pays USDT
wait_confirmations(usdt_tx)
inventory_BTC -= amount_BTC # Inventory Release
inventory_USDT += amount_USDT
send_btc_to_user(amount_BTC) # payout from inventory
Model symmetry
The two scenarios mirror each other: one user’s order replenishes inventory, the next user’s order spends it. The BTC bought during the Fill phase from user A becomes the payout source during the Release phase for user B. The position state between phases is tracked by the Inventory Model, and the price that balances the flow is formed by the Pricing Engine.
See also