Stellar
Constant-product swaps on Soroban
x·y=k in Rust with checked arithmetic and native XLM handling.
Overview
CosmoDEX's pool takes the fee off the input in basis points, then prices the output with the constant-product formula. Every step uses checked maths, so an overflow aborts rather than mispricing a trade.
The code
contracts/pool/src/lib.rsView on GitHub ↗
pub fn swap(e: Env, caller: Address, input_token: Address, amount_in: i128) -> i128 {
caller.require_auth();
Self::check_nonnegative_amount(amount_in);
let mut pool_info: PoolInfo = e.storage().instance().get(&symbol_short!("pool")).unwrap();
assert!(amount_in > 0, "Amount in must be > 0");
// …choose token_in / token_out and reserves, handle native XLM…
// Calculate amount after fee with overflow protection
let amount_in_with_fee = checked_div(
checked_mul(amount_in, checked_sub(BPS_DENOMINATOR, FEE_BPS)), BPS_DENOMINATOR);
// Calculate amount out using constant product formula with overflow protection
let numerator = checked_mul(reserve_out, amount_in_with_fee);
let denominator = checked_add(reserve_in, amount_in_with_fee);
let amount_out = checked_div(numerator, denominator);
// …
}
How it works
- Caller authorisation and input validation before any transfer
- A separate path for pools that hold native XLM
- Fee applied in basis points before pricing