Build an AMM
Create an automated market maker with constant product formula
In this tutorial, you'll learn how to build an AMM (Automated Market Maker) using the OYL AMM architecture. We'll cover liquidity pools, the constant product formula, and swap mechanics.
Key Concepts
AMM Architecture
The OYL AMM uses a factory pattern with these components:
Pool Storage Layout
Each pool stores the following state:
// Pool storage layout
/alkane/0 -> AlkaneId: First token in pair
/alkane/1 -> AlkaneId: Second token in pair
/factory_id -> AlkaneId: Factory that created this pool
/totalsupply -> u128: LP token total supply
/klast -> U256: k value after last operation
/totalfeeper1000 -> u128: Fee rate (3 = 0.3%)
/blockTimestampLast-> u32: Last update timestamp
/price0CumLast -> U256: Cumulative price 0
/price1CumLast -> U256: Cumulative price 1
/claimablefees -> u128: Unclaimed protocol fees
/name -> String: LP token nameConstant Product Formula
The AMM maintains the invariant: reserve0 * reserve1 = k
// Constant Product: x * y = k
//
// When swapping dx for dy:
// (x + dx) * (y - dy) = k
// dy = y - k/(x + dx)
// dy = y * dx / (x + dx) (simplified, ignoring fees)
//
// With 0.3% fee:
// dx_with_fee = dx * (1000 - 3) / 1000
// dy = y * dx_with_fee / (x + dx_with_fee)
fn get_amount_out(
amount_in: u128,
reserve_in: u128,
reserve_out: u128,
fee_per_1000: u128,
) -> Result<u128> {
if amount_in == 0 {
return Err(anyhow!("INSUFFICIENT_INPUT_AMOUNT"));
}
if reserve_in == 0 || reserve_out == 0 {
return Err(anyhow!("INSUFFICIENT_LIQUIDITY"));
}
// amount_in with fee applied
let amount_in_with_fee = U256::from(amount_in) * U256::from(1000 - fee_per_1000);
// Calculate output amount
let numerator = amount_in_with_fee * U256::from(reserve_out);
let denominator = U256::from(reserve_in) * U256::from(1000) + amount_in_with_fee;
let amount_out: u128 = (numerator / denominator).try_into()?;
Ok(amount_out)
}Adding Liquidity
When users add liquidity, LP tokens are minted proportionally:
fn add_liquidity(&self) -> Result<CallResponse> {
let context = self.context()?;
let parcel = context.incoming_alkanes.clone();
// Verify exactly 2 tokens sent (the pair tokens)
self.check_inputs(&context.myself, &parcel, 2)?;
// Get current and previous reserves
let (reserve_a, reserve_b) = self.reserves()?;
let (previous_a, previous_b) = self.previous_reserves(&parcel)?;
// Calculate amounts deposited
let amount_a_in = reserve_a.value - previous_a.value;
let amount_b_in = reserve_b.value - previous_b.value;
// Mint protocol fee share if applicable
self._mint_fee(previous_a.value, previous_b.value)?;
let total_supply = self.total_supply();
let liquidity: u128;
if total_supply == 0 {
// First deposit: LP tokens = sqrt(amount_a * amount_b) - MINIMUM_LIQUIDITY
let root_k = (U256::from(amount_a_in) * U256::from(amount_b_in)).sqrt();
liquidity = root_k.try_into::<u128>()? - MINIMUM_LIQUIDITY;
// Lock MINIMUM_LIQUIDITY forever to prevent price manipulation
self.set_total_supply(MINIMUM_LIQUIDITY);
} else {
// Subsequent deposits: mint proportional to smaller ratio
let liquidity_a = U256::from(amount_a_in) * U256::from(total_supply)
/ U256::from(previous_a.value);
let liquidity_b = U256::from(amount_b_in) * U256::from(total_supply)
/ U256::from(previous_b.value);
liquidity = min(liquidity_a, liquidity_b).try_into()?;
}
if liquidity == 0 {
return Err(anyhow!("INSUFFICIENT_LIQUIDITY_MINTED"));
}
// Update TWAP oracle
self._update_cum_prices(previous_a.value, previous_b.value)?;
// Update k value
let new_k = U256::from(reserve_a.value) * U256::from(reserve_b.value);
self.set_k_last(new_k);
// Return minted LP tokens
let mut response = CallResponse::default();
response.alkanes.pay(self.mint(&context, liquidity)?);
Ok(response)
}Removing Liquidity
Burn LP tokens to withdraw proportional share of reserves:
fn withdraw_and_burn(&self) -> Result<CallResponse> {
let context = self.context()?;
let parcel = context.incoming_alkanes;
// Verify exactly 1 token sent (LP token)
self.check_inputs(&context.myself, &parcel, 1)?;
let incoming = parcel.0[0].clone();
if incoming.id != context.myself {
return Err(anyhow!("can only burn LP alkane for this pair"));
}
let liquidity = incoming.value;
let (previous_a, previous_b) = self.previous_reserves(&parcel)?;
// Mint protocol fee
self._mint_fee(previous_a.value, previous_b.value)?;
let (reserve_a, reserve_b) = self.reserves()?;
let total_supply = self.total_supply();
// Calculate withdrawal amounts proportional to LP tokens
let amount_a: u128 = (U256::from(liquidity) * U256::from(reserve_a.value)
/ U256::from(total_supply)).try_into()?;
let amount_b: u128 = (U256::from(liquidity) * U256::from(reserve_b.value)
/ U256::from(total_supply)).try_into()?;
if amount_a == 0 || amount_b == 0 {
return Err(anyhow!("INSUFFICIENT_LIQUIDITY_BURNED"));
}
// Burn LP tokens
self.decrease_total_supply(liquidity)?;
// Update TWAP oracle
self._update_cum_prices(previous_a.value, previous_b.value)?;
// Update k value
let new_k = U256::from(reserve_a.value - amount_a)
* U256::from(reserve_b.value - amount_b);
self.set_k_last(new_k);
// Return withdrawn tokens
let mut response = CallResponse::default();
response.alkanes = AlkaneTransferParcel(vec![
AlkaneTransfer { id: reserve_a.id, value: amount_a },
AlkaneTransfer { id: reserve_b.id, value: amount_b },
]);
Ok(response)
}Swap Implementation
Execute a swap while maintaining the constant product invariant:
fn swap(
&self,
amount_0_out: u128,
amount_1_out: u128,
to: AlkaneId,
data: Vec<u128>,
) -> Result<CallResponse> {
// Validate outputs
if amount_0_out == 0 && amount_1_out == 0 {
return Err(anyhow!("INSUFFICIENT_OUTPUT_AMOUNT"));
}
let context = self.context()?;
let parcel = context.incoming_alkanes.clone();
// Get reserves before incoming tokens were added
let (reserve_0, reserve_1) = self.previous_reserves(&parcel)?;
// Check sufficient liquidity
if amount_0_out >= reserve_0.value || amount_1_out >= reserve_1.value {
return Err(anyhow!("INSUFFICIENT_LIQUIDITY"));
}
// Prevent sending to token addresses
if to == reserve_0.id || to == reserve_1.id {
return Err(anyhow!("INVALID_TO"));
}
// Build output parcel
let mut alkane_transfer = AlkaneTransferParcel::default();
if amount_0_out > 0 {
alkane_transfer.0.push(AlkaneTransfer {
id: reserve_0.id.clone(),
value: amount_0_out,
});
}
if amount_1_out > 0 {
alkane_transfer.0.push(AlkaneTransfer {
id: reserve_1.id.clone(),
value: amount_1_out,
});
}
// Handle flash swaps (callback) or regular swaps
let mut response = CallResponse::default();
let should_send_to_extcall = !data.is_empty() && to != AlkaneId::new(0, 0);
if should_send_to_extcall {
// Flash swap: call recipient with tokens, expect payment in callback
let mut extcall_input = vec![SWAP_EXTCALL_OPCODE];
extcall_input.extend(context.caller.clone().into_iter());
extcall_input.push(amount_0_out);
extcall_input.push(amount_1_out);
extcall_input.extend(data);
self.call(
&Cellpack { target: to, inputs: extcall_input },
&alkane_transfer,
self.fuel(),
)?;
} else {
// Regular swap: return tokens directly
response.alkanes = alkane_transfer;
}
// Calculate new balances
let (mut balance_0, mut balance_1) = self.reserves()?;
if !should_send_to_extcall {
balance_0.value -= amount_0_out;
balance_1.value -= amount_1_out;
}
// Calculate input amounts
let amount_0_in = if balance_0.value > reserve_0.value - amount_0_out {
balance_0.value - (reserve_0.value - amount_0_out)
} else { 0 };
let amount_1_in = if balance_1.value > reserve_1.value - amount_1_out {
balance_1.value - (reserve_1.value - amount_1_out)
} else { 0 };
if amount_0_in == 0 && amount_1_in == 0 {
return Err(anyhow!("INSUFFICIENT_INPUT_AMOUNT"));
}
// Verify K invariant with fees
let total_fee = self.total_fee_per_1000();
let balance_0_adjusted = U256::from(balance_0.value) * U256::from(1000)
- U256::from(amount_0_in) * U256::from(total_fee);
let balance_1_adjusted = U256::from(balance_1.value) * U256::from(1000)
- U256::from(amount_1_in) * U256::from(total_fee);
if balance_0_adjusted * balance_1_adjusted
< U256::from(reserve_0.value) * U256::from(reserve_1.value) * U256::from(1000000) {
return Err(anyhow!("K is not maintained"));
}
// Update TWAP oracle
self._update_cum_prices(reserve_0.value, reserve_1.value)?;
Ok(response)
}TWAP Oracle
Track cumulative prices for time-weighted average price calculations:
fn _update_cum_prices(&self, reserve0: u128, reserve1: u128) -> Result<()> {
let block_header = self.block_header()?;
let current_timestamp = block_header.time;
let last_timestamp = self.block_timestamp_last();
let time_elapsed = current_timestamp - last_timestamp;
// Only update if time has passed and reserves exist
if time_elapsed > 0 && reserve0 != 0 && reserve1 != 0 {
// Price0 = reserve1 / reserve0 (scaled by 2^128)
// Price1 = reserve0 / reserve1 (scaled by 2^128)
let price0_cumulative = (U256::from(reserve1) << 128)
/ U256::from(reserve0) * U256::from(time_elapsed);
let price1_cumulative = (U256::from(reserve0) << 128)
/ U256::from(reserve1) * U256::from(time_elapsed);
self.increase_price_cumulative(price0_cumulative, price1_cumulative);
}
self.set_block_timestamp_last(current_timestamp);
Ok(())
}
// External function to read TWAP
fn get_price_cumulative_last(&self) -> Result<CallResponse> {
let context = self.context()?;
let mut response = CallResponse::forward(&context.incoming_alkanes);
let (p0, p1) = self.price_cumulative();
response.data.extend_from_slice(&p0.to_le_bytes::<32>());
response.data.extend_from_slice(&p1.to_le_bytes::<32>());
Ok(response)
}Deployment Steps
Deploy the AMM system in the following order:
# 1. Deploy Auth Token Factory
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[3,65517,100]:v0:v0" \
--envelope ./alkanes_std_auth_token.wasm \
--from p2tr:0 --fee-rate 1 --mine -y
# 2. Deploy Pool Beacon Proxy Template
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[3,780993,36863]:v0:v0" \
--envelope ./alkanes_std_beacon_proxy.wasm \
--from p2tr:0 --fee-rate 1 --mine -y
# 3. Deploy Factory Logic
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[3,65524,50]:v0:v0" \
--envelope ./factory.wasm \
--from p2tr:0 --fee-rate 1 --mine -y
# 4. Deploy Pool Logic
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[3,65520,50]:v0:v0" \
--envelope ./pool.wasm \
--from p2tr:0 --fee-rate 1 --mine -y
# 5. Deploy Upgradeable Factory Proxy
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[3,65522,32767,4,65524,5]:v0:v0" \
--envelope ./alkanes_std_upgradeable.wasm \
--from p2tr:0 --fee-rate 1 --mine -y
# 6. Deploy Pool Upgradeable Beacon
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[3,65523,32767,4,65520,5]:v0:v0" \
--envelope ./alkanes_std_upgradeable_beacon.wasm \
--from p2tr:0 --fee-rate 1 --mine -y
# 7. Initialize Factory
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes execute "[4,65522,0,780993,4,65523]:v0:v0" \
--inputs 2:1:1 \
--from p2tr:0 --fee-rate 1 --mine -yCreating a Pool
Create a new liquidity pool through the factory:
# Create DIESEL/frBTC pool
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes init-pool \
--pair "2:0,32:0" \
--liquidity "300000000:50000" \
--to p2tr:0 \
--from p2tr:0 \
--change p2tr:0 \
--factory "4:65522" \
--mine \
-y
# The pool will be created at the next available [2, n]
# LP tokens will be sent to your addressExecuting Swaps
Swap tokens through an existing pool:
# Swap DIESEL for frBTC
# Pool ID: 2:12345 (replace with actual pool ID)
alkanes-cli -p regtest \
--wallet-file ~/.alkanes/wallet.json \
--passphrase "password" \
alkanes swap \
--pool "2:12345" \
--amount-in "1000000" \
--token-in "2:0" \
--min-out "900" \
--to p2tr:0 \
--from p2tr:0 \
--mine \
-y
# Query pool reserves
alkanes-cli -p regtest alkanes simulate "2:12345:97"
# Query LP token total supply
alkanes-cli -p regtest alkanes simulate "2:12345:101"Flash Swaps
Execute swaps where payment happens in callback (advanced):
// Flash swap callback contract
#[derive(MessageDispatch)]
pub enum FlashSwapMessage {
// Callback from pool during flash swap
#[opcode(73776170)] // "swap" as u128
OnSwap {
sender: AlkaneId,
amount_0_out: u128,
amount_1_out: u128,
data_len: u128,
// ... data follows
},
}
impl MyFlashSwapContract {
fn on_swap(
&self,
sender: AlkaneId,
amount_0_out: u128,
amount_1_out: u128,
data_len: u128,
) -> Result<CallResponse> {
let context = self.context()?;
// Use the borrowed tokens for arbitrage, liquidations, etc.
// ...
// Calculate repayment (must return more than borrowed)
let fee = 3; // 0.3%
let repay_amount = amount_0_out * (1000 + fee) / 1000;
// Return tokens to pool
let mut response = CallResponse::default();
response.alkanes.0.push(AlkaneTransfer {
id: /* token_0_id */,
value: repay_amount,
});
Ok(response)
}
}Fee Collection
Protocol fees are collected and distributed to governance:
fn collect_fees(&self) -> Result<CallResponse> {
// Only factory can collect fees
self._only_factory_caller()?;
let context = self.context()?;
let (previous_a, previous_b) = self.previous_reserves(&context.incoming_alkanes)?;
// Calculate and mint fee share
self._mint_fee(previous_a.value, previous_b.value)?;
// Transfer claimable fees as LP tokens
let mut response = CallResponse::forward(&context.incoming_alkanes);
response.alkanes.pay(AlkaneTransfer {
id: context.myself,
value: self.claimable_fees(),
});
// Reset claimable fees
self.set_claimable_fees(0);
// Update k
let new_k = U256::from(previous_a.value) * U256::from(previous_b.value);
self.set_k_last(new_k);
Ok(response)
}
// Fee calculation (Uniswap v2 style)
fn _mint_fee(&self, previous_a: u128, previous_b: u128) -> Result<()> {
let total_supply = self.total_supply();
let k_last = self.k_last();
if !k_last.is_zero() {
let root_k = (U256::from(previous_a) * U256::from(previous_b)).sqrt();
let root_k_last = k_last.sqrt();
if root_k > root_k_last {
// Mint fee share to protocol
let numerator = U256::from(total_supply) * (root_k - root_k_last);
let total_fee = self.total_fee_per_1000();
let denominator = root_k * U256::from(total_fee - 1) / U256::from(1)
+ root_k_last;
let liquidity: u128 = (numerator / denominator).try_into()?;
self.increase_total_supply(liquidity)?;
self.set_claimable_fees(self.claimable_fees() + liquidity);
}
}
Ok(())
}