// ISC License // // Copyright (c) 2023, aeternity developers // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. // Under no circumstances, whether in tort (including negligence), contract, or otherwise, // unless required by applicable law, shall Aeternity Anstalt be liable for damages, // including any direct, indirect, special, incidental, // or consequential damages of any nature arising out of the deployment or use of this smart contract, // notwithstanding that Aeternity Anstalt may have been advised of the possibility of such damages. @compiler >= 6 include "./lib/Utils.aes" include "./lib/UQ112x112.aes" include "./lib/Math.aes" include "./interfaces/IAedexV2Pair.aes" include "./interfaces/IAedexV2Callback.aes" include "./interfaces/IAedexV2FactoryForPair.aes" include "Option.aes" include "./interfaces/IAEX9Minimal.aes" contract AedexV2Pair = type owner = address type spender = address type allowance_accounts = IAEX9Minimal.allowance_accounts type allowances = map(allowance_accounts, int) type balances = map(owner, int) datatype event // AEX9 compliant events = Transfer(address /*indexed from*/, address /*indexed to*/, int /*value*/) | Approval(address /*indexed owner*/, address /*indexed spender*/, int /*value*/) | Allowance(address /*indexed owner*/, address /*indexed spender*/, int /*value*/) | Mint(address /*indexed owner*/, int /*value*/) | Burn(address /*indexed owner*/, int /*value*/) // AedexV2Pair specific events | LockLiquidity(int) | PairMint(address /*indexed sender*/, int /*amount0*/, int /*amount1*/) | PairBurn(address /*indexed sender*/, address /*indexed to*/, string /*int amount0 | int amount1*/ ) | SwapTokens( address /*indexed sender*/ , address /*indexed to*/ , string /* , int amount0_in, , int amount1_in, , int amount0_out, , int amount1_out, */ ) //represents the new pair balances of token0 and token1 | Sync(int /*reserve0*/, int /*reserve1*/) record state = { //token area total_supply: int , balance_of: balances , locked_liquidity: int , allowances: allowances , factory: IAedexV2FactoryForPair , token0: IAEX9Minimal , token1: IAEX9Minimal , reserve0: int // uses single storage slot, accessible via get_reserves , reserve1: int // uses single storage slot, accessible via get_reserves , block_timestamp_last: int // uses single storage slot, accessible via get_reserves , price0_cumulative_last: int , price1_cumulative_last: int , min_liquidity: int // Pairs burn the first MINIMUM_LIQUIDITY pool tokens. // We are choosing the default value of 1000 to ameliorate rounding errors // and increase the theoretical minimum tick size for liquidity provision. // But other values can be chosen as well. , k_last: int // reserve0 * reserve1, as of immediately after the most recent liquidity event // NOTE: // refers to k from XYK model (x * y = k equation) // https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/how-uniswap-works // https://medium.com/phoenix-finance/understanding-the-xyk-model-of-pooled-liquidity-7340fdc20d9c , debug_time: option(int) } entrypoint init( factory: IAedexV2FactoryForPair , token0: IAEX9Minimal , token1: IAEX9Minimal , min_liquidity: option(int) , debug_time: option(int) // If this is set to Some(...) the pair will enter in debug mode // and `timestamp()` will get the value from it. After this point, // to modify it's value `set_debug_time` should be called. // Otherwise if the contract initialization sets `debug_time` to `None`, // `timestamp()` will be reflected by the Chain.timestamp // and any further set_debug_time call will result with an error ) = { total_supply = 0 , balance_of = {} , locked_liquidity = 0 , allowances = {} , factory = factory , token0 = token0 , token1 = token1 , reserve0 = 0 , reserve1 = 0 , block_timestamp_last = 0 , price0_cumulative_last = 0 , price1_cumulative_last = 0 , k_last = 0 , debug_time = debug_time , min_liquidity = Option.default(1000, min_liquidity) } //------------------------------------------------------------------------------ // VIEWERS //------------------------------------------------------------------------------ entrypoint meta_info(): IAEX9Minimal.meta_info = let meta0 = state.token0.meta_info() let meta1 = state.token1.meta_info() { name = Utils.concat_xs([meta0.name, " vs ", meta1.name]) , symbol = Utils.concat_xs([meta0.symbol, "/", meta1.symbol]) , decimals = 18 } entrypoint aex9_extensions() : list(string) = ["allowances"] entrypoint total_supply() : int = state.total_supply entrypoint balances() : balances = state.balance_of entrypoint balance(address: address): option(int) = Map.lookup(address, state.balance_of) entrypoint allowances() : allowances = state.allowances entrypoint allowance(allowance_accounts : allowance_accounts) : option(int) = Map.lookup(allowance_accounts, state.allowances) entrypoint allowance_for_caller(from_account: address) : option(int) = allowance({ from_account = from_account, for_account = Call.caller }) //we don't have an owner to make veto decisions over the pair contract entrypoint owner() : address = Contract.address entrypoint price0_cumulative_last() = state.price0_cumulative_last entrypoint price1_cumulative_last() = state.price1_cumulative_last entrypoint get_reserves(): IAedexV2Pair.reserves = { reserve0 = state.reserve0 , reserve1 = state.reserve1 , block_timestamp_last = state.block_timestamp_last } entrypoint minimum_liquidity() = state.min_liquidity entrypoint factory() = state.factory entrypoint token0() = state.token0 entrypoint token1() = state.token1 //------------------------------------------------------------------------------ // STATEFUL SPECIFIC ENTRYPOINTS //------------------------------------------------------------------------------ stateful entrypoint set_debug_time(time: int) = require_positive([time]) require(Option.is_some(state.debug_time), "AedexV2Pair: NOT_DEBUG_MODE") put( state { debug_time = Some(time) } ) // New Pair tokens will be minted and assigned to the given address based on the received token0 and token1 amounts. // The newly received tokens are inferred from the difference between state.balance0/1 and state.reserve0/1. // After the Pair tokens will be minted the reserves amounts will be updated to reflect the current token balances. // Usage: From the caller contract, befor calling the mint entrypoint, token0 & token1 amounts // should be transfered to the Pair address (Contract.address) // NOTE(1): If factory.set_fee_to() is set to Some( address ), the liquidity representing the fee will be minted to that address // NOTE(2): This low-level function should be called from a contract which performs important safety checks stateful entrypoint mint(to: address): int = let (reserve0, reserve1) = (state.reserve0, state.reserve1) let (balance0, balance1) = get_balances() let amount0 = balance0 - reserve0 let amount1 = balance1 - reserve1 let fee_on = mint_fee(reserve0, reserve1) let total_supply = state.total_supply // must be defined here since totalSupply can update in gc let liquidity = let min_liq = state.min_liquidity if (total_supply == 0) mint_update(None, min_liq) // permanently lock the first MINIMUM_LIQUIDITY tokens Math.sqrt(amount0 * amount1) - min_liq else Math.min((amount0*total_supply) / reserve0, (amount1*total_supply) / reserve1) require(liquidity > 0, "AedexV2Pair: INSUFFICIENT_LIQUIDITY_MINTED") mint_update(Some(to), liquidity) update(balance0, balance1, reserve0, reserve1) if (fee_on) put( state{ k_last = state.reserve0*state.reserve1 }) // reserve0 and reserve1 are up-to-date Chain.event( PairMint(Call.caller, amount0, amount1) ) liquidity // Burns (removes) Pair tokens and transfers the token0/1 amounts to a given address. // Usage: // 1. Prior the call the desiered liquidity must be transfered from the liquidity provider balance // to the Pair address // 2. Call the burn entrypoint with the destiantion wallet in which the tokens(0&1) are expected to be received // How it works: // 1. All the Pair tokens found in state.balance_of[Contract.address] will be removed // and the exact value will be substracted from the state.totalSupply // 2. Token0/1 amounts ,proportional with the burned liquidity, will be transfered to the given address // NOTE(1): If factory.set_fee_to() is set to Some( address ), liquidity representing the fee, will be minted to that address // NOTE(2): This low-level function should be called from a contract which performs important safety checks stateful entrypoint burn(to: address): IAedexV2Pair.amounts = let (reserve0, reserve1) = (state.reserve0, state.reserve1) let (balance0, balance1) = get_balances() let liquidity = Option.default(0, balance(Contract.address)) let fee_on = mint_fee(reserve0, reserve1) let total_supply = state.total_supply // must be defined here since totalSupply // can update in mintFee let amount0 = (liquidity*balance0) / total_supply // using balances ensures pro-rata distribution let amount1 = (liquidity*balance1) / total_supply // using balances ensures pro-rata distribution //in most of the cases balance(Contract.address) will equal the liquidity, //unless during the mint_fee the balance(Contract.address) increased burn_update(liquidity) require(amount0 >= 0 && amount1 >= 0,"AedexV2Pair: NEGATIVE_VALUE_ON_TRANSFER") state.token0.transfer(to, amount0) state.token1.transfer(to, amount1) let (balance0,balance1) = get_balances() update(balance0, balance1, reserve0, reserve1) if (fee_on) put( state{ k_last = state.reserve0*state.reserve1 }) // reserve0 and reserve1 are up-to-date Chain.event( PairBurn(Call.caller, to, Utils.xsToPayload([amount0, amount1])) ) {amount0 = amount0, amount1 = amount1} // Transfers expected token amounts(`amount0_out` & `amount1_out`) to a given address (`to`) in exchange // for the counterpart token amounts(1&0) expected to be received into Pair address (Contract.address). // The input tokens should be transfered prior the swap entrypoint call or at the latest during the // callback_opt call (if this was provided) // NOTE: This low-level function should be called from a contract which performs important safety checks stateful entrypoint swap( amount0_out: int , amount1_out: int , to: address , callback_opt: option(IAedexV2Callback) ): unit = require(amount0_out > 0 || amount1_out > 0, "AedexV2Pair: INSUFFICIENT_OUTPUT_AMOUNT") let (reserve0, reserve1) = (state.reserve0, state.reserve1) require(amount0_out < reserve0 && amount1_out < reserve1, "AedexV2Pair: INSUFFICIENT_LIQUIDITY") let token0 = state.token0 let token1 = state.token1 require(to != token0.address && to != token1.address, "AedexV2Pair: INVALID_TO") if (amount0_out > 0) token0.transfer(to, amount0_out) // optimistically transfer tokens if (amount1_out > 0) token1.transfer(to, amount1_out) // optimistically transfer tokens Option.map((callback) => callback.aedex_v2_call(Call.caller, amount0_out, amount1_out), callback_opt) let (balance0, balance1) = get_balances() let amount0_in = if(balance0 > reserve0 - amount0_out) balance0 - (reserve0 - amount0_out) else 0 let amount1_in = if(balance1 > reserve1 - amount1_out) balance1 - (reserve1 - amount1_out) else 0 require(amount0_in > 0 || amount1_in > 0, "AedexV2Pair: INSUFFICIENT_INPUT_AMOUNT") let balance0_adjusted = balance0*1000 - amount0_in*3 let balance1_adjusted = balance1*1000 - amount1_in*3 require( balance0_adjusted*balance1_adjusted >= reserve0*reserve1*1000000, "AedexV2Pair: INSUFFICIENT_BALANCE" ) update(balance0, balance1, reserve0, reserve1) Chain.event( SwapTokens( Call.caller, to, Utils.xsToPayload([ amount0_in, amount1_in, amount0_out, amount1_out]) )) // Force balances to match reserves stateful entrypoint skim(to: address ) = let token0 = state.token0 let token1 = state.token1 let balance0 = Option.default(0, token0.balance(Contract.address)) let balance1 = Option.default(0, token1.balance(Contract.address)) let amount0 = balance0 - state.reserve0 let amount1 = balance1 - state.reserve1 require(amount0 >= 0 && amount1 >= 0, "AedexV2Pair: NEGATIVE_VALUE_ON_TRANSFER") token0.transfer(to, amount0) token1.transfer(to, amount1) // Force reserves to match balances stateful entrypoint sync() = let token0 = state.token0 let token1 = state.token1 let balance0 = Option.default(0, token0.balance(Contract.address)) let balance1 = Option.default(0, token1.balance(Contract.address)) update( balance0 , balance1 , state.reserve0 , state.reserve1 ) //------------------------------------------------------------------------------ // AEX9 STATEFUL ENTRYPOINTS //------------------------------------------------------------------------------ stateful entrypoint create_allowance(for_account: address, value: int) = require_positive([value]) let allowance_accounts = { from_account = Call.caller, for_account = for_account } require_allowance_not_existent(allowance_accounts) put(state{ allowances[allowance_accounts] = value }) Chain.event(Allowance(Call.caller, for_account, value)) stateful entrypoint transfer(recipient: address, amount: int): unit = internal_transfer(Call.caller, recipient, amount) stateful entrypoint transfer_allowance(from_account: address, to_account: address, value: int) = let allowance_accounts = { from_account = from_account, for_account = Call.caller } internal_transfer(from_account, to_account, value) internal_change_allowance(allowance_accounts, -value) stateful entrypoint change_allowance(for_account: address, value_change: int) = let allowance_accounts = { from_account = Call.caller, for_account = for_account } internal_change_allowance(allowance_accounts, value_change) stateful entrypoint reset_allowance(for_account: address) = let allowance_accounts = { from_account = Call.caller, for_account = for_account } internal_change_allowance(allowance_accounts, - state.allowances[allowance_accounts]) //------------------------------------------------------------------------------ // INTERNALS //------------------------------------------------------------------------------ stateful function mint_update(to_opt: option(address), value: int) = require_positive([value]) switch(to_opt) Some(to) => put(state { total_supply @ p = p + value , balance_of[ to = 0] @ p = p + value }) Chain.event( Mint( to, value )) None => put(state { total_supply @ p = p + value , locked_liquidity @ p = p + value }) Chain.event( Mint( Contract.address, value )) Chain.event( LockLiquidity(value) ) stateful function burn_update(value: int) = require(value > 0, "AedexV2Pair: INSUFFICIENT_LIQUIDITY_BURNED") let total_supply = state.total_supply // we are using twice: verification and update require(total_supply >= value , "AedexV2Pair: INSUFFICIENT_TOTAL_SUPPLY") let balance = state.balance_of[ Contract.address ] // using twice: verification and update require(balance >= value , "AedexV2Pair: INSUFFICIENT_BALANCE_FOR_BURNING") put(state { total_supply = total_supply - value , balance_of[ Contract.address ] = balance - value }) Chain.event( Burn(Contract.address, value) ) // Update reserves and, on the first call per block, price accumulators stateful function update(balance0: int, balance1: int, reserve0: int, reserve1: int) = require_positive([ balance0, balance1, reserve0, reserve1]) let block_timestamp = timestamp() let time_elapsed = block_timestamp - state.block_timestamp_last if (time_elapsed > 0 && reserve0 != 0 && reserve1 != 0) put(state { price0_cumulative_last @ p = p + (UQ112x112.encode(reserve1)/reserve0)*time_elapsed , price1_cumulative_last @ p = p + (UQ112x112.encode(reserve0)/reserve1)*time_elapsed }) put( state { reserve0 = balance0 , reserve1 = balance1 , block_timestamp_last = block_timestamp }) Chain.event( Sync(balance0, balance1) ) // actually new reserve0&reserve1 stateful function internal_transfer(sender: address, recipient: address, amount: int) = require_positive([amount]) require_balance(sender, amount) put(state{ balance_of[sender] @ b = b - amount }) put(state{ balance_of[recipient = 0] @ b = b + amount }) Chain.event(Transfer(sender, recipient, amount)) stateful function internal_change_allowance(allowance_accounts : allowance_accounts, value_change : int) = let allowance = require_allowance(allowance_accounts, value_change) let new_allowance = allowance + value_change require_positive([new_allowance]) put(state{ allowances[allowance_accounts] = new_allowance }) Chain.event(Allowance(allowance_accounts.from_account, allowance_accounts.for_account, new_allowance)) function get_balances() = let balance0 = Option.default(0, state.token0.balance(Contract.address)) let balance1 = Option.default(0, state.token1.balance(Contract.address)) (balance0, balance1) function timestamp() = Option.default(Chain.timestamp, state.debug_time) function require_positive(xs: list(int)): unit = Utils.require_positive_xs("AedexV2Pair", xs) // If fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) stateful function mint_fee(reserve0: int, reserve1: int): bool = require_positive([reserve0, reserve1]) let k_last = state.k_last switch(state.factory.fee_to()) Some(fee_to) => if (k_last != 0) let root_k = Math.sqrt(reserve0 * reserve1) let root_k_last_last = Math.sqrt(k_last) if (root_k > root_k_last_last) let numerator = state.total_supply * (root_k - root_k_last_last) let denominator = root_k*5 + root_k_last_last let liquidity = numerator / denominator if (liquidity > 0) mint_update(Some(fee_to), liquidity) true None => if( k_last != 0) put( state { k_last = 0}) false function require_allowance_not_existent(allowance_accounts : allowance_accounts) = switch(allowance(allowance_accounts)) None => None Some(_) => abort("AedexV2Pair: ALLOWANCE_ALREADY_EXISTENT") function require_balance(account : address, value : int) = switch(balance(account)) Some(balance) => require(balance >= value, "AedexV2Pair: INSUFFICIENT_BALANCE_FOR_TRANSFER") None => abort("AedexV2Pair: BALANCE_ACCOUNT_NOT_EXISTENT") function require_allowance(allowance_accounts : allowance_accounts, value : int) : int = switch(allowance(allowance_accounts)) Some(allowance) => require(allowance + value >= 0, "AedexV2Pair: INSUFFICIENT_ALLOWANCE") allowance None => abort("AedexV2Pair: ALLOWANCE_NOT_EXISTENT")