repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_factory/src/testing/mock_querier.rs
contracts/mirror_factory/src/testing/mock_querier.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, from_slice, to_binary, Api, CanonicalAddr, Coin, ContractResult, Decimal, Empty, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, WasmQuery, }; use cosmwasm_storage::to_length_prefixed; use crate::querier::MintAssetConfig; use std::collections::HashMap; use tefi_oracle::hub::PriceResponse; use terraswap::asset::{AssetInfo, PairInfo}; /// mock_dependencies is a drop-in replacement for cosmwasm_std::testing::mock_dependencies /// this uses our CustomQuerier. pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new(MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)])); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<Empty>, terraswap_factory_querier: TerraswapFactoryQuerier, oracle_price_querier: OraclePriceQuerier, mint_querier: MintQuerier, } #[derive(Clone, Default)] pub struct TerraswapFactoryQuerier { pairs: HashMap<String, String>, } impl TerraswapFactoryQuerier { pub fn new(pairs: &[(&String, &String)]) -> Self { TerraswapFactoryQuerier { pairs: pairs_to_map(pairs), } } } pub(crate) fn pairs_to_map(pairs: &[(&String, &String)]) -> HashMap<String, String> { let mut pairs_map: HashMap<String, String> = HashMap::new(); for (key, pair) in pairs.iter() { pairs_map.insert(key.to_string(), pair.to_string()); } pairs_map } #[derive(Clone, Default)] pub struct OraclePriceQuerier { // this lets us iterate over all pairs that match the first string oracle_price: HashMap<String, Decimal>, } impl OraclePriceQuerier { pub fn new(oracle_price: &[(&String, &Decimal)]) -> Self { OraclePriceQuerier { oracle_price: oracle_price_to_map(oracle_price), } } } pub(crate) fn oracle_price_to_map( oracle_price: &[(&String, &Decimal)], ) -> HashMap<String, Decimal> { let mut oracle_price_map: HashMap<String, Decimal> = HashMap::new(); for (base_quote, oracle_price) in oracle_price.iter() { oracle_price_map.insert((*base_quote).clone(), **oracle_price); } oracle_price_map } #[derive(Clone, Default)] pub struct MintQuerier { configs: HashMap<String, (Decimal, Decimal)>, } impl MintQuerier { pub fn new(configs: &[(&String, &(Decimal, Decimal))]) -> Self { MintQuerier { configs: configs_to_map(configs), } } } pub(crate) fn configs_to_map( configs: &[(&String, &(Decimal, Decimal))], ) -> HashMap<String, (Decimal, Decimal)> { let mut configs_map: HashMap<String, (Decimal, Decimal)> = HashMap::new(); for (contract_addr, touple) in configs.iter() { configs_map.insert(contract_addr.to_string(), (touple.0, touple.1)); } configs_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<Empty> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Pair { asset_infos: [AssetInfo; 2], }, Price { asset_token: String, timeframe: Option<u64>, }, } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<Empty>) -> QuerierResult { match &request { QueryRequest::Wasm(WasmQuery::Smart { contract_addr: _, msg, }) => match from_binary(msg).unwrap() { QueryMsg::Pair { asset_infos } => { let key = asset_infos[0].to_string() + asset_infos[1].to_string().as_str(); match self.terraswap_factory_querier.pairs.get(&key) { Some(v) => SystemResult::Ok(ContractResult::from(to_binary(&PairInfo { contract_addr: "pair".to_string(), liquidity_token: v.to_string(), asset_infos: [ AssetInfo::NativeToken { denom: "uusd".to_string(), }, AssetInfo::NativeToken { denom: "uusd".to_string(), }, ], }))), None => SystemResult::Err(SystemError::InvalidRequest { error: "No pair info exists".to_string(), request: msg.as_slice().into(), }), } } QueryMsg::Price { asset_token, timeframe: _, } => match self.oracle_price_querier.oracle_price.get(&asset_token) { Some(base_price) => { SystemResult::Ok(ContractResult::from(to_binary(&PriceResponse { rate: *base_price, last_updated: 1000u64, }))) } None => SystemResult::Err(SystemError::InvalidRequest { error: "No oracle price exists".to_string(), request: msg.as_slice().into(), }), }, }, QueryRequest::Wasm(WasmQuery::Raw { contract_addr: _, key, }) => { let key: &[u8] = key.as_slice(); let prefix_asset_config = to_length_prefixed(b"asset_config").to_vec(); let api: MockApi = MockApi::default(); if key.len() > prefix_asset_config.len() && key[..prefix_asset_config.len()].to_vec() == prefix_asset_config { let rest_key: &[u8] = &key[prefix_asset_config.len()..]; let asset_token: String = api .addr_humanize(&(CanonicalAddr::from(rest_key.to_vec()))) .unwrap() .to_string(); let config = match self.mint_querier.configs.get(&asset_token) { Some(v) => v, None => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Mint Config is not found for {}", asset_token), request: key.into(), }) } }; SystemResult::Ok(ContractResult::from(to_binary(&MintAssetConfig { token: api.addr_canonicalize(&asset_token).unwrap(), auction_discount: config.0, min_collateral_ratio: config.1, ipo_params: None, }))) } else { panic!("DO NOT ENTER HERE") } } _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new(base: MockQuerier<Empty>) -> Self { WasmMockQuerier { base, terraswap_factory_querier: TerraswapFactoryQuerier::default(), mint_querier: MintQuerier::default(), oracle_price_querier: OraclePriceQuerier::default(), } } // configure the terraswap pair pub fn with_terraswap_pairs(&mut self, pairs: &[(&String, &String)]) { self.terraswap_factory_querier = TerraswapFactoryQuerier::new(pairs); } pub fn with_mint_configs(&mut self, configs: &[(&String, &(Decimal, Decimal))]) { self.mint_querier = MintQuerier::new(configs); } // configure the oracle price mock querier pub fn with_oracle_price(&mut self, oracle_price: &[(&String, &Decimal)]) { self.oracle_price_querier = OraclePriceQuerier::new(oracle_price); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_factory/src/testing/mod.rs
contracts/mirror_factory/src/testing/mod.rs
mod mock_querier; mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_factory/examples/schema.rs
contracts/mirror_factory/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::factory::{ ConfigResponse, DistributionInfoResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(MigrateMsg), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(DistributionInfoResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/contract.rs
contracts/mirror_mint/src/contract.rs
use crate::{ asserts::{assert_auction_discount, assert_min_collateral_ratio, assert_protocol_fee}, migration::migrate_asset_configs, positions::{ auction, burn, deposit, mint, open_position, query_next_position_idx, query_position, query_positions, withdraw, }, state::{ read_asset_config, read_config, store_asset_config, store_config, store_position_idx, AssetConfig, Config, }, }; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ attr, from_binary, to_binary, Addr, Binary, CanonicalAddr, CosmosMsg, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, }; use cw20::Cw20ReceiveMsg; use mirror_protocol::mint::{ AssetConfigResponse, ConfigResponse, Cw20HookMsg, ExecuteMsg, IPOParams, InstantiateMsg, QueryMsg, }; use mirror_protocol::{ collateral_oracle::{ExecuteMsg as CollateralOracleExecuteMsg, SourceType}, mint::MigrateMsg, }; use terraswap::asset::{Asset, AssetInfo}; pub const MIN_CR_ALLOWED: &str = "1.1"; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { let config = Config { owner: deps.api.addr_canonicalize(&msg.owner)?, oracle: deps.api.addr_canonicalize(&msg.oracle)?, collector: deps.api.addr_canonicalize(&msg.collector)?, collateral_oracle: deps.api.addr_canonicalize(&msg.collateral_oracle)?, staking: deps.api.addr_canonicalize(&msg.staking)?, terraswap_factory: deps.api.addr_canonicalize(&msg.terraswap_factory)?, lock: deps.api.addr_canonicalize(&msg.lock)?, base_denom: msg.base_denom, token_code_id: msg.token_code_id, protocol_fee_rate: assert_protocol_fee(msg.protocol_fee_rate)?, }; store_config(deps.storage, &config)?; store_position_idx(deps.storage, Uint128::from(1u128))?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> { match msg { ExecuteMsg::Receive(msg) => receive_cw20(deps, env, info, msg), ExecuteMsg::UpdateConfig { owner, oracle, collector, collateral_oracle, terraswap_factory, lock, token_code_id, protocol_fee_rate, staking, } => update_config( deps, info, owner, oracle, collector, collateral_oracle, terraswap_factory, lock, token_code_id, protocol_fee_rate, staking, ), ExecuteMsg::UpdateAsset { asset_token, auction_discount, min_collateral_ratio, ipo_params, } => { let asset_addr = deps.api.addr_validate(asset_token.as_str())?; update_asset( deps, info, asset_addr, auction_discount, min_collateral_ratio, ipo_params, ) } ExecuteMsg::RegisterAsset { asset_token, auction_discount, min_collateral_ratio, ipo_params, } => { let asset_addr = deps.api.addr_validate(asset_token.as_str())?; register_asset( deps, info, asset_addr, auction_discount, min_collateral_ratio, ipo_params, ) } ExecuteMsg::RegisterMigration { asset_token, end_price, } => { let asset_addr = deps.api.addr_validate(asset_token.as_str())?; register_migration(deps, info, asset_addr, end_price) } ExecuteMsg::TriggerIPO { asset_token } => { let asset_addr = deps.api.addr_validate(asset_token.as_str())?; trigger_ipo(deps, info, asset_addr) } ExecuteMsg::OpenPosition { collateral, asset_info, collateral_ratio, short_params, } => { // only native token can be deposited directly if !collateral.is_native_token() { return Err(StdError::generic_err("unauthorized")); } // Check the actual deposit happens collateral.assert_sent_native_token_balance(&info)?; open_position( deps, env, info.sender, collateral, asset_info, collateral_ratio, short_params, ) } ExecuteMsg::Deposit { position_idx, collateral, } => { // only native token can be deposited directly if !collateral.is_native_token() { return Err(StdError::generic_err("unauthorized")); } // Check the actual deposit happens collateral.assert_sent_native_token_balance(&info)?; deposit(deps, info.sender, position_idx, collateral) } ExecuteMsg::Withdraw { position_idx, collateral, } => withdraw(deps, info.sender, position_idx, collateral), ExecuteMsg::Mint { position_idx, asset, short_params, } => mint(deps, env, info.sender, position_idx, asset, short_params), } } pub fn receive_cw20( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> StdResult<Response> { let passed_asset: Asset = Asset { info: AssetInfo::Token { contract_addr: info.sender.to_string(), }, amount: cw20_msg.amount, }; match from_binary(&cw20_msg.msg) { Ok(Cw20HookMsg::OpenPosition { asset_info, collateral_ratio, short_params, }) => { let cw20_sender = deps.api.addr_validate(cw20_msg.sender.as_str())?; open_position( deps, env, cw20_sender, passed_asset, asset_info, collateral_ratio, short_params, ) } Ok(Cw20HookMsg::Deposit { position_idx }) => { let cw20_sender = deps.api.addr_validate(cw20_msg.sender.as_str())?; deposit(deps, cw20_sender, position_idx, passed_asset) } Ok(Cw20HookMsg::Burn { position_idx }) => { let cw20_sender = deps.api.addr_validate(cw20_msg.sender.as_str())?; burn(deps, env, cw20_sender, position_idx, passed_asset) } Ok(Cw20HookMsg::Auction { position_idx }) => { let cw20_sender = deps.api.addr_validate(cw20_msg.sender.as_str())?; auction(deps, cw20_sender, position_idx, passed_asset) } Err(_) => Err(StdError::generic_err("invalid cw20 hook message")), } } #[allow(clippy::too_many_arguments)] pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, oracle: Option<String>, collector: Option<String>, collateral_oracle: Option<String>, terraswap_factory: Option<String>, lock: Option<String>, token_code_id: Option<u64>, protocol_fee_rate: Option<Decimal>, staking: Option<String>, ) -> StdResult<Response> { let mut config: Config = read_config(deps.storage)?; if deps.api.addr_canonicalize(info.sender.as_str())? != config.owner { return Err(StdError::generic_err("unauthorized")); } if let Some(owner) = owner { config.owner = deps.api.addr_canonicalize(&owner)?; } if let Some(oracle) = oracle { config.oracle = deps.api.addr_canonicalize(&oracle)?; } if let Some(collector) = collector { config.collector = deps.api.addr_canonicalize(&collector)?; } if let Some(collateral_oracle) = collateral_oracle { config.collateral_oracle = deps.api.addr_canonicalize(&collateral_oracle)?; } if let Some(terraswap_factory) = terraswap_factory { config.terraswap_factory = deps.api.addr_canonicalize(&terraswap_factory)?; } if let Some(lock) = lock { config.lock = deps.api.addr_canonicalize(&lock)?; } if let Some(token_code_id) = token_code_id { config.token_code_id = token_code_id; } if let Some(protocol_fee_rate) = protocol_fee_rate { assert_protocol_fee(protocol_fee_rate)?; config.protocol_fee_rate = protocol_fee_rate; } if let Some(staking) = staking { config.staking = deps.api.addr_canonicalize(&staking)?; } store_config(deps.storage, &config)?; Ok(Response::new().add_attribute("action", "update_config")) } pub fn update_asset( deps: DepsMut, info: MessageInfo, asset_token: Addr, auction_discount: Option<Decimal>, min_collateral_ratio: Option<Decimal>, ipo_params: Option<IPOParams>, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let asset_token_raw = deps.api.addr_canonicalize(asset_token.as_str())?; let mut asset: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; if deps.api.addr_canonicalize(info.sender.as_str())? != config.owner { return Err(StdError::generic_err("unauthorized")); } if let Some(auction_discount) = auction_discount { assert_auction_discount(auction_discount)?; asset.auction_discount = auction_discount; } if let Some(min_collateral_ratio) = min_collateral_ratio { assert_min_collateral_ratio(min_collateral_ratio)?; asset.min_collateral_ratio = min_collateral_ratio; } if let Some(ipo_params) = ipo_params { assert_min_collateral_ratio(ipo_params.min_collateral_ratio_after_ipo)?; asset.ipo_params = Some(ipo_params); } store_asset_config(deps.storage, &asset_token_raw, &asset)?; Ok(Response::new().add_attribute("action", "update_asset")) } pub fn register_asset( deps: DepsMut, info: MessageInfo, asset_token: Addr, auction_discount: Decimal, min_collateral_ratio: Decimal, ipo_params: Option<IPOParams>, ) -> StdResult<Response> { assert_auction_discount(auction_discount)?; assert_min_collateral_ratio(min_collateral_ratio)?; let config: Config = read_config(deps.storage)?; // permission check if deps.api.addr_canonicalize(info.sender.as_str())? != config.owner { return Err(StdError::generic_err("unauthorized")); } let asset_token_raw = deps.api.addr_canonicalize(asset_token.as_str())?; if read_asset_config(deps.storage, &asset_token_raw).is_ok() { return Err(StdError::generic_err("Asset was already registered")); } let mut messages: Vec<CosmosMsg> = vec![]; // check if it is a preIPO asset if let Some(params) = ipo_params.clone() { assert_min_collateral_ratio(params.min_collateral_ratio_after_ipo)?; } else { // only non-preIPO assets can be used as collateral messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps .api .addr_humanize(&config.collateral_oracle)? .to_string(), funds: vec![], msg: to_binary(&CollateralOracleExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: asset_token.to_string(), }, multiplier: Decimal::one(), // default collateral multiplier for new mAssets price_source: SourceType::TefiOracle { oracle_addr: deps.api.addr_humanize(&config.oracle)?.to_string(), }, })?, })); } // Store temp info into base asset store store_asset_config( deps.storage, &asset_token_raw, &AssetConfig { token: deps.api.addr_canonicalize(asset_token.as_str())?, auction_discount, min_collateral_ratio, end_price: None, ipo_params, }, )?; Ok(Response::new() .add_attributes(vec![ attr("action", "register"), attr("asset_token", asset_token), ]) .add_messages(messages)) } pub fn register_migration( deps: DepsMut, info: MessageInfo, asset_token: Addr, end_price: Decimal, ) -> StdResult<Response> { let config = read_config(deps.storage)?; if config.owner != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } let asset_token_raw = deps.api.addr_canonicalize(asset_token.as_str())?; let asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; // update asset config store_asset_config( deps.storage, &asset_token_raw, &AssetConfig { end_price: Some(end_price), min_collateral_ratio: Decimal::percent(100), ipo_params: None, ..asset_config }, )?; // flag asset as revoked in the collateral oracle Ok(Response::new() .add_messages(vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps .api .addr_humanize(&config.collateral_oracle)? .to_string(), funds: vec![], msg: to_binary(&CollateralOracleExecuteMsg::RevokeCollateralAsset { asset: AssetInfo::Token { contract_addr: asset_token.to_string(), }, })?, })]) .add_attributes(vec![ attr("action", "migrate_asset"), attr("asset_token", asset_token.as_str()), attr("end_price", end_price.to_string()), ])) } pub fn trigger_ipo(deps: DepsMut, info: MessageInfo, asset_token: Addr) -> StdResult<Response> { let config = read_config(deps.storage)?; let asset_token_raw: CanonicalAddr = deps.api.addr_canonicalize(asset_token.as_str())?; let mut asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; let ipo_params: IPOParams = match asset_config.ipo_params { Some(v) => v, None => return Err(StdError::generic_err("Asset does not have IPO params")), }; let trigger_addr = deps.api.addr_validate(&ipo_params.trigger_addr)?; // only trigger addr can trigger ipo if trigger_addr != info.sender { return Err(StdError::generic_err("unauthorized")); } asset_config.min_collateral_ratio = ipo_params.min_collateral_ratio_after_ipo; asset_config.ipo_params = None; store_asset_config(deps.storage, &asset_token_raw, &asset_config)?; // register asset in collateral oracle Ok(Response::new() .add_messages(vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps .api .addr_humanize(&config.collateral_oracle)? .to_string(), funds: vec![], msg: to_binary(&CollateralOracleExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: asset_token.to_string(), }, multiplier: Decimal::one(), // default collateral multiplier for new mAssets price_source: SourceType::TefiOracle { oracle_addr: deps.api.addr_humanize(&config.oracle)?.to_string(), }, })?, })]) .add_attributes(vec![ attr("action", "trigger_ipo"), attr("asset_token", asset_token.as_str()), ])) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), QueryMsg::AssetConfig { asset_token } => to_binary(&query_asset_config(deps, asset_token)?), QueryMsg::Position { position_idx } => to_binary(&query_position(deps, position_idx)?), QueryMsg::Positions { owner_addr, asset_token, start_after, limit, order_by, } => to_binary(&query_positions( deps, owner_addr, asset_token, start_after, limit, order_by, )?), QueryMsg::NextPositionIdx {} => to_binary(&query_next_position_idx(deps)?), } } pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let state = read_config(deps.storage)?; let resp = ConfigResponse { owner: deps.api.addr_humanize(&state.owner)?.to_string(), oracle: deps.api.addr_humanize(&state.oracle)?.to_string(), staking: deps.api.addr_humanize(&state.staking)?.to_string(), collector: deps.api.addr_humanize(&state.collector)?.to_string(), collateral_oracle: deps .api .addr_humanize(&state.collateral_oracle)? .to_string(), terraswap_factory: deps .api .addr_humanize(&state.terraswap_factory)? .to_string(), lock: deps.api.addr_humanize(&state.lock)?.to_string(), base_denom: state.base_denom, token_code_id: state.token_code_id, protocol_fee_rate: state.protocol_fee_rate, }; Ok(resp) } pub fn query_asset_config(deps: Deps, asset_token: String) -> StdResult<AssetConfigResponse> { let asset_config: AssetConfig = read_asset_config( deps.storage, &deps.api.addr_canonicalize(asset_token.as_str())?, )?; let resp = AssetConfigResponse { token: deps .api .addr_humanize(&asset_config.token) .unwrap() .to_string(), auction_discount: asset_config.auction_discount, min_collateral_ratio: asset_config.min_collateral_ratio, end_price: asset_config.end_price, ipo_params: asset_config.ipo_params, }; Ok(resp) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> StdResult<Response> { // change oracle address to point to new tefi hub let mut config: Config = read_config(deps.storage)?; config.oracle = deps.api.addr_canonicalize(&msg.tefi_oracle_contract)?; store_config(deps.storage, &config)?; // just to check that there are no ipo assets so that the ipo params type can be changed migrate_asset_configs(deps.storage)?; Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/lib.rs
contracts/mirror_mint/src/lib.rs
mod asserts; pub mod contract; mod math; mod migration; mod positions; mod querier; mod state; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/math.rs
contracts/mirror_mint/src/math.rs
use cosmwasm_std::{Decimal, Uint128}; const DECIMAL_FRACTIONAL: Uint128 = Uint128::new(1_000_000_000u128); pub fn reverse_decimal(decimal: Decimal) -> Decimal { Decimal::from_ratio(DECIMAL_FRACTIONAL, decimal * DECIMAL_FRACTIONAL) } pub fn decimal_subtraction(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio( (DECIMAL_FRACTIONAL * a) .checked_sub(DECIMAL_FRACTIONAL * b) .unwrap(), DECIMAL_FRACTIONAL, ) } /// return a / b pub fn decimal_division(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio(DECIMAL_FRACTIONAL * a, b * DECIMAL_FRACTIONAL) } pub fn decimal_multiplication(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio(a * DECIMAL_FRACTIONAL * b, DECIMAL_FRACTIONAL) } pub fn decimal_min(a: Decimal, b: Decimal) -> Decimal { if a < b { a } else { b } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/state.rs
contracts/mirror_mint/src/state.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, Decimal, StdError, StdResult, Storage, Uint128}; use cosmwasm_storage::{singleton, singleton_read, Bucket, ReadonlyBucket}; use mirror_protocol::common::OrderBy; use mirror_protocol::mint::IPOParams; use std::convert::TryInto; use terraswap::asset::{AssetInfoRaw, AssetRaw}; pub static PREFIX_ASSET_CONFIG: &[u8] = b"asset_config"; static PREFIX_POSITION: &[u8] = b"position"; static PREFIX_INDEX_BY_USER: &[u8] = b"by_user"; static PREFIX_INDEX_BY_ASSET: &[u8] = b"by_asset"; static PREFIX_SHORT_POSITION: &[u8] = b"short_position"; pub static KEY_CONFIG: &[u8] = b"config"; static KEY_POSITION_IDX: &[u8] = b"position_idx"; pub fn store_position_idx(storage: &mut dyn Storage, position_idx: Uint128) -> StdResult<()> { singleton(storage, KEY_POSITION_IDX).save(&position_idx) } pub fn read_position_idx(storage: &dyn Storage) -> StdResult<Uint128> { singleton_read(storage, KEY_POSITION_IDX).load() } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub oracle: CanonicalAddr, pub collector: CanonicalAddr, pub collateral_oracle: CanonicalAddr, pub staking: CanonicalAddr, pub terraswap_factory: CanonicalAddr, pub lock: CanonicalAddr, pub base_denom: String, pub token_code_id: u64, pub protocol_fee_rate: Decimal, } pub fn store_config(storage: &mut dyn Storage, config: &Config) -> StdResult<()> { singleton(storage, KEY_CONFIG).save(config) } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, KEY_CONFIG).load() } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct AssetConfig { pub token: CanonicalAddr, pub auction_discount: Decimal, pub min_collateral_ratio: Decimal, pub end_price: Option<Decimal>, pub ipo_params: Option<IPOParams>, } pub fn store_asset_config( storage: &mut dyn Storage, asset_token: &CanonicalAddr, asset: &AssetConfig, ) -> StdResult<()> { let mut asset_bucket: Bucket<AssetConfig> = Bucket::new(storage, PREFIX_ASSET_CONFIG); asset_bucket.save(asset_token.as_slice(), asset) } pub fn read_asset_config( storage: &dyn Storage, asset_token: &CanonicalAddr, ) -> StdResult<AssetConfig> { let asset_bucket: ReadonlyBucket<AssetConfig> = ReadonlyBucket::new(storage, PREFIX_ASSET_CONFIG); let res = asset_bucket.load(asset_token.as_slice()); match res { Ok(data) => Ok(data), _ => Err(StdError::generic_err("no asset data stored")), } } // check if the asset has either end_price or pre_ipo_price pub fn read_fixed_price(storage: &dyn Storage, asset_info: &AssetInfoRaw) -> Option<Decimal> { match asset_info { AssetInfoRaw::Token { contract_addr } => { let asset_bucket: ReadonlyBucket<AssetConfig> = ReadonlyBucket::new(storage, PREFIX_ASSET_CONFIG); let res = asset_bucket.load(contract_addr.as_slice()); match res { Ok(data) => { if data.end_price.is_some() { data.end_price } else { data.ipo_params.map(|ipo_params| ipo_params.pre_ipo_price) } } _ => None, } } _ => None, } } pub fn store_short_position(storage: &mut dyn Storage, idx: Uint128) -> StdResult<()> { let mut short_position_bucket: Bucket<bool> = Bucket::new(storage, PREFIX_SHORT_POSITION); short_position_bucket.save(&idx.u128().to_be_bytes(), &true) } pub fn remove_short_position(storage: &mut dyn Storage, idx: Uint128) { let mut short_position_bucket: Bucket<bool> = Bucket::new(storage, PREFIX_SHORT_POSITION); short_position_bucket.remove(&idx.u128().to_be_bytes()) } pub fn is_short_position(storage: &dyn Storage, idx: Uint128) -> StdResult<bool> { let short_position_bucket: ReadonlyBucket<bool> = ReadonlyBucket::new(storage, PREFIX_SHORT_POSITION); let res = short_position_bucket.may_load(&idx.u128().to_be_bytes())?; Ok(res.is_some()) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Position { pub idx: Uint128, pub owner: CanonicalAddr, pub collateral: AssetRaw, pub asset: AssetRaw, } /// create position with index pub fn create_position( storage: &mut dyn Storage, idx: Uint128, position: &Position, ) -> StdResult<()> { let mut position_bucket: Bucket<Position> = Bucket::new(storage, PREFIX_POSITION); position_bucket.save(&idx.u128().to_be_bytes(), position)?; let mut position_indexer_by_user: Bucket<bool> = Bucket::multilevel(storage, &[PREFIX_INDEX_BY_USER, position.owner.as_slice()]); position_indexer_by_user.save(&idx.u128().to_be_bytes(), &true)?; let mut position_indexer_by_asset: Bucket<bool> = Bucket::multilevel( storage, &[PREFIX_INDEX_BY_ASSET, position.asset.info.as_bytes()], ); position_indexer_by_asset.save(&idx.u128().to_be_bytes(), &true)?; Ok(()) } /// store position with idx pub fn store_position( storage: &mut dyn Storage, idx: Uint128, position: &Position, ) -> StdResult<()> { let mut position_bucket: Bucket<Position> = Bucket::new(storage, PREFIX_POSITION); position_bucket.save(&idx.u128().to_be_bytes(), position)?; Ok(()) } /// remove position with idx pub fn remove_position(storage: &mut dyn Storage, idx: Uint128) -> StdResult<()> { let position: Position = read_position(storage, idx)?; let mut position_bucket: Bucket<Position> = Bucket::new(storage, PREFIX_POSITION); position_bucket.remove(&idx.u128().to_be_bytes()); // remove indexer let mut position_indexer_by_user: Bucket<bool> = Bucket::multilevel(storage, &[PREFIX_INDEX_BY_USER, position.owner.as_slice()]); position_indexer_by_user.remove(&idx.u128().to_be_bytes()); // remove indexer let mut position_indexer_by_asset: Bucket<bool> = Bucket::multilevel( storage, &[PREFIX_INDEX_BY_ASSET, position.asset.info.as_bytes()], ); position_indexer_by_asset.remove(&idx.u128().to_be_bytes()); // remove short position flag remove_short_position(storage, idx); Ok(()) } /// read position from store with position idx pub fn read_position(storage: &dyn Storage, idx: Uint128) -> StdResult<Position> { let position_bucket: ReadonlyBucket<Position> = ReadonlyBucket::new(storage, PREFIX_POSITION); position_bucket.load(&idx.u128().to_be_bytes()) } // settings for pagination const MAX_LIMIT: u32 = 30; const DEFAULT_LIMIT: u32 = 10; pub fn read_positions( storage: &dyn Storage, start_after: Option<Uint128>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<Position>> { let position_bucket: ReadonlyBucket<Position> = ReadonlyBucket::new(storage, PREFIX_POSITION); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start(start_after), None, OrderBy::Asc), _ => (None, calc_range_end(start_after), OrderBy::Desc), }; position_bucket .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (_, v) = item?; Ok(v) }) .collect() } pub fn read_positions_with_user_indexer( storage: &dyn Storage, position_owner: &CanonicalAddr, start_after: Option<Uint128>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<Position>> { let position_indexer: ReadonlyBucket<bool> = ReadonlyBucket::multilevel(storage, &[PREFIX_INDEX_BY_USER, position_owner.as_slice()]); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start(start_after), None, OrderBy::Asc), _ => (None, calc_range_end(start_after), OrderBy::Desc), }; position_indexer .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (k, _) = item?; read_position(storage, Uint128::from(bytes_to_u128(&k)?)) }) .collect() } pub fn read_positions_with_asset_indexer( storage: &dyn Storage, asset_token: &CanonicalAddr, start_after: Option<Uint128>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<Position>> { let position_indexer: ReadonlyBucket<bool> = ReadonlyBucket::multilevel(storage, &[PREFIX_INDEX_BY_ASSET, asset_token.as_slice()]); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start(start_after), None, OrderBy::Asc), _ => (None, calc_range_end(start_after), OrderBy::Desc), }; position_indexer .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (k, _) = item?; read_position(storage, Uint128::from(bytes_to_u128(&k)?)) }) .collect() } fn bytes_to_u128(data: &[u8]) -> StdResult<u128> { match data[0..16].try_into() { Ok(bytes) => Ok(u128::from_be_bytes(bytes)), Err(_) => Err(StdError::generic_err( "Corrupted data found. 16 byte expected.", )), } } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_start(start_after: Option<Uint128>) -> Option<Vec<u8>> { start_after.map(|idx| { let mut v = idx.u128().to_be_bytes().to_vec(); v.push(1); v }) } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_end(start_after: Option<Uint128>) -> Option<Vec<u8>> { start_after.map(|idx| idx.u128().to_be_bytes().to_vec()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/asserts.rs
contracts/mirror_mint/src/asserts.rs
use std::str::FromStr; use crate::{ contract::MIN_CR_ALLOWED, state::{AssetConfig, Position}, }; use cosmwasm_std::{Decimal, Deps, Env, StdError, StdResult}; use terraswap::asset::{Asset, AssetInfo}; // Check zero balance & same collateral with position pub fn assert_collateral(deps: Deps, position: &Position, collateral: &Asset) -> StdResult<()> { if !collateral .info .equal(&position.collateral.info.to_normal(deps.api)?) || collateral.amount.is_zero() { return Err(StdError::generic_err("Wrong collateral")); } Ok(()) } // Check zero balance & same asset with position pub fn assert_asset(deps: Deps, position: &Position, asset: &Asset) -> StdResult<()> { if !asset.info.equal(&position.asset.info.to_normal(deps.api)?) || asset.amount.is_zero() { return Err(StdError::generic_err("Wrong asset")); } Ok(()) } pub fn assert_migrated_asset(asset_config: &AssetConfig) -> StdResult<()> { if asset_config.end_price.is_some() { return Err(StdError::generic_err( "Operation is not allowed for the deprecated asset", )); } Ok(()) } pub fn assert_revoked_collateral( load_collateral_res: (Decimal, Decimal, bool), ) -> StdResult<(Decimal, Decimal)> { if load_collateral_res.2 { return Err(StdError::generic_err( "The collateral asset provided is no longer valid", )); } Ok((load_collateral_res.0, load_collateral_res.1)) } pub fn assert_auction_discount(auction_discount: Decimal) -> StdResult<()> { if auction_discount > Decimal::one() { Err(StdError::generic_err( "auction_discount must be smaller than 1", )) } else { Ok(()) } } pub fn assert_min_collateral_ratio(min_collateral_ratio: Decimal) -> StdResult<()> { if min_collateral_ratio < Decimal::from_str(MIN_CR_ALLOWED)? { Err(StdError::generic_err(format!( "min_collateral_ratio must be bigger or equal than {}", MIN_CR_ALLOWED ))) } else { Ok(()) } } pub fn assert_protocol_fee(protocol_fee_rate: Decimal) -> StdResult<Decimal> { if protocol_fee_rate >= Decimal::one() { Err(StdError::generic_err( "protocol_fee_rate must be smaller than 1", )) } else { Ok(protocol_fee_rate) } } pub fn assert_mint_period(env: &Env, asset_config: &AssetConfig) -> StdResult<()> { if let Some(ipo_params) = asset_config.ipo_params.clone() { if ipo_params.mint_end < env.block.time.seconds() { return Err(StdError::generic_err(format!( "The minting period for this asset ended at time {}", ipo_params.mint_end ))); } } Ok(()) } pub fn assert_pre_ipo_collateral( base_denom: String, asset_config: &AssetConfig, collateral_info: &AssetInfo, ) -> StdResult<()> { if asset_config.ipo_params.is_some() { match collateral_info { AssetInfo::Token { .. } => { return Err(StdError::generic_err(format!( "Only {} can be used as collateral for preIPO assets", base_denom ))) } AssetInfo::NativeToken { denom } => { if *denom != base_denom { return Err(StdError::generic_err(format!( "Only {} can be used as collateral for preIPO assets", base_denom ))); } } } } Ok(()) } pub fn assert_burn_period(env: &Env, asset_config: &AssetConfig) -> StdResult<()> { if let Some(ipo_params) = asset_config.ipo_params.clone() { if ipo_params.mint_end < env.block.time.seconds() { return Err(StdError::generic_err(format!( "Burning is disabled for assets with limitied minting time. Mint period ended at time {}", ipo_params.mint_end ))); } } Ok(()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/querier.rs
contracts/mirror_mint/src/querier.rs
use cosmwasm_std::{ to_binary, Addr, Decimal, Deps, QuerierWrapper, QueryRequest, StdResult, WasmQuery, }; use crate::{ math::decimal_division, state::{read_config, read_fixed_price, Config}, }; use mirror_protocol::collateral_oracle::{ CollateralInfoResponse, CollateralPriceResponse, QueryMsg as CollateralOracleQueryMsg, }; use tefi_oracle::hub::{HubQueryMsg as OracleQueryMsg, PriceResponse}; use terraswap::asset::AssetInfoRaw; const PRICE_EXPIRE_TIME: u64 = 60; pub fn load_asset_price( deps: Deps, oracle: Addr, asset: &AssetInfoRaw, check_expire: bool, ) -> StdResult<Decimal> { let config: Config = read_config(deps.storage)?; // check if the asset has a stored end_price or pre_ipo_price let stored_price = read_fixed_price(deps.storage, asset); let price: Decimal = if let Some(stored_price) = stored_price { stored_price } else { let asset_denom: String = (asset.to_normal(deps.api)?).to_string(); if asset_denom == config.base_denom { Decimal::one() } else { // fetch price from oracle query_price(&deps.querier, oracle, asset_denom, None, check_expire)? } }; Ok(price) } pub fn load_collateral_info( deps: Deps, collateral_oracle: Addr, collateral: &AssetInfoRaw, check_expire: bool, ) -> StdResult<(Decimal, Decimal, bool)> { let config: Config = read_config(deps.storage)?; let collateral_denom: String = (collateral.to_normal(deps.api)?).to_string(); // base collateral if collateral_denom == config.base_denom { return Ok((Decimal::one(), Decimal::one(), false)); } // check if the collateral is a revoked mAsset, will ignore pre_ipo_price since all preIPO // assets are not whitelisted in collateral oracle let end_price = read_fixed_price(deps.storage, collateral); if let Some(end_price) = end_price { // load collateral_multiplier from collateral oracle // if asset is revoked, no need to check for old price let (collateral_multiplier, _) = query_collateral_info(&deps.querier, collateral_oracle, collateral_denom)?; Ok((end_price, collateral_multiplier, true)) } else { // load collateral info from collateral oracle let (collateral_oracle_price, collateral_multiplier, is_revoked) = query_collateral( &deps.querier, collateral_oracle, collateral_denom, check_expire, )?; Ok((collateral_oracle_price, collateral_multiplier, is_revoked)) } } pub fn query_price( querier: &QuerierWrapper, oracle: Addr, base_asset: String, quote_asset: Option<String>, check_expire: bool, ) -> StdResult<Decimal> { let timeframe: Option<u64> = if check_expire { Some(PRICE_EXPIRE_TIME) } else { None }; let base_res: PriceResponse = querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: oracle.to_string(), msg: to_binary(&OracleQueryMsg::Price { asset_token: base_asset, timeframe, })?, }))?; let rate = if let Some(quote_asset) = quote_asset { let quote_res: PriceResponse = querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: oracle.to_string(), msg: to_binary(&OracleQueryMsg::Price { asset_token: quote_asset, timeframe, })?, }))?; decimal_division(base_res.rate, quote_res.rate) } else { base_res.rate }; Ok(rate) } // queries the collateral oracle to get the asset rate and multiplier pub fn query_collateral( querier: &QuerierWrapper, collateral_oracle: Addr, asset: String, check_expire: bool, ) -> StdResult<(Decimal, Decimal, bool)> { let timeframe: Option<u64> = if check_expire { Some(PRICE_EXPIRE_TIME) } else { None }; let res: CollateralPriceResponse = querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: collateral_oracle.to_string(), msg: to_binary(&CollateralOracleQueryMsg::CollateralPrice { asset, timeframe })?, }))?; Ok((res.rate, res.multiplier, res.is_revoked)) } // queries only collateral information (multiplier and is_revoked), without price pub fn query_collateral_info( querier: &QuerierWrapper, collateral_oracle: Addr, asset: String, ) -> StdResult<(Decimal, bool)> { let res: CollateralInfoResponse = querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: collateral_oracle.to_string(), msg: to_binary(&CollateralOracleQueryMsg::CollateralAssetInfo { asset })?, }))?; Ok((res.multiplier, res.is_revoked)) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/positions.rs
contracts/mirror_mint/src/positions.rs
use cosmwasm_std::{ attr, to_binary, Addr, Attribute, CosmosMsg, Decimal, Deps, DepsMut, Env, Response, StdError, StdResult, Uint128, WasmMsg, }; use crate::{ asserts::{ assert_asset, assert_burn_period, assert_collateral, assert_migrated_asset, assert_mint_period, assert_pre_ipo_collateral, assert_revoked_collateral, }, math::{ decimal_division, decimal_min, decimal_multiplication, decimal_subtraction, reverse_decimal, }, querier::{load_asset_price, load_collateral_info}, state::{ create_position, is_short_position, read_asset_config, read_config, read_position, read_position_idx, read_positions, read_positions_with_asset_indexer, read_positions_with_user_indexer, remove_position, store_position, store_position_idx, store_short_position, AssetConfig, Config, Position, }, }; use cw20::Cw20ExecuteMsg; use mirror_protocol::{ common::OrderBy, lock::ExecuteMsg as LockExecuteMsg, mint::{NextPositionIdxResponse, PositionResponse, PositionsResponse, ShortParams}, staking::ExecuteMsg as StakingExecuteMsg, }; use terraswap::{ asset::{Asset, AssetInfo, AssetInfoRaw, AssetRaw}, pair::Cw20HookMsg as PairCw20HookMsg, querier::query_pair_info, }; pub fn open_position( deps: DepsMut, env: Env, sender: Addr, collateral: Asset, asset_info: AssetInfo, collateral_ratio: Decimal, short_params: Option<ShortParams>, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; if collateral.amount.is_zero() { return Err(StdError::generic_err("Wrong collateral")); } // assert the collateral is listed and has not been migrated/revoked let collateral_info_raw: AssetInfoRaw = collateral.info.to_raw(deps.api)?; let collateral_oracle: Addr = deps.api.addr_humanize(&config.collateral_oracle)?; let (collateral_price, collateral_multiplier) = assert_revoked_collateral( load_collateral_info(deps.as_ref(), collateral_oracle, &collateral_info_raw, true)?, )?; // assert asset migrated let asset_info_raw: AssetInfoRaw = asset_info.to_raw(deps.api)?; let asset_token_raw = match asset_info_raw.clone() { AssetInfoRaw::Token { contract_addr } => contract_addr, _ => panic!("DO NOT ENTER HERE"), }; let asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; assert_migrated_asset(&asset_config)?; // for assets with limited minting period (preIPO assets), assert minting phase as well as pre-ipo collateral assert_mint_period(&env, &asset_config)?; assert_pre_ipo_collateral(config.base_denom.clone(), &asset_config, &collateral.info)?; if collateral_ratio < decimal_multiplication(asset_config.min_collateral_ratio, collateral_multiplier) { return Err(StdError::generic_err( "Can not open a position with low collateral ratio than minimum", )); } let oracle: Addr = deps.api.addr_humanize(&config.oracle)?; let asset_price: Decimal = load_asset_price(deps.as_ref(), oracle, &asset_info_raw, true)?; let asset_price_in_collateral_asset = decimal_division(collateral_price, asset_price); // Convert collateral to mint amount let mint_amount = collateral.amount * asset_price_in_collateral_asset * reverse_decimal(collateral_ratio); if mint_amount.is_zero() { return Err(StdError::generic_err("collateral is too small")); } let position_idx = read_position_idx(deps.storage)?; let asset_info_raw = asset_info.to_raw(deps.api)?; create_position( deps.storage, position_idx, &Position { idx: position_idx, owner: deps.api.addr_canonicalize(sender.as_str())?, collateral: AssetRaw { amount: collateral.amount, info: collateral_info_raw, }, asset: AssetRaw { amount: mint_amount, info: asset_info_raw, }, }, )?; // If the short_params exists, the position is // flagged as short position. so if want to make short position, // the one must pass at least empty {} as short_params let is_short: bool; let asset_token = deps.api.addr_humanize(&asset_config.token)?.to_string(); let messages: Vec<CosmosMsg> = if let Some(short_params) = short_params { is_short = true; store_short_position(deps.storage, position_idx)?; // need to sell the tokens to terraswap // load pair contract address let pair_info = query_pair_info( &deps.querier, deps.api.addr_humanize(&config.terraswap_factory)?, &[ AssetInfo::NativeToken { denom: config.base_denom, }, asset_info.clone(), ], )?; // 1. Mint token to itself // 2. Swap token and send to lock contract // 3. Call lock hook on lock contract // 4. Increase short token in staking contract let lock_contract = deps.api.addr_humanize(&config.lock)?.to_string(); vec![ CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.clone(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: env.contract.address.to_string(), amount: mint_amount, })?, }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.clone(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_info.contract_addr, amount: mint_amount, msg: to_binary(&PairCw20HookMsg::Swap { belief_price: short_params.belief_price, max_spread: short_params.max_spread, to: Some(lock_contract.clone()), })?, })?, }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: lock_contract, funds: vec![], msg: to_binary(&LockExecuteMsg::LockPositionFundsHook { position_idx, receiver: sender.to_string(), })?, }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.staking)?.to_string(), funds: vec![], msg: to_binary(&StakingExecuteMsg::IncreaseShortToken { asset_token, staker_addr: sender.to_string(), amount: mint_amount, })?, }), ] } else { is_short = false; vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token, funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: sender.to_string(), amount: mint_amount, })?, })] }; store_position_idx(deps.storage, position_idx + Uint128::from(1u128))?; Ok(Response::new() .add_attributes(vec![ attr("action", "open_position"), attr("position_idx", position_idx.to_string()), attr( "mint_amount", mint_amount.to_string() + &asset_info.to_string(), ), attr("collateral_amount", collateral.to_string()), attr("is_short", is_short.to_string()), ]) .add_messages(messages)) } pub fn deposit( deps: DepsMut, sender: Addr, position_idx: Uint128, collateral: Asset, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let mut position: Position = read_position(deps.storage, position_idx)?; let position_owner = deps.api.addr_humanize(&position.owner)?; if sender != position_owner { return Err(StdError::generic_err("unauthorized")); } // Check the given collateral has same asset info // with position's collateral token // also Check the collateral amount is non-zero assert_collateral(deps.as_ref(), &position, &collateral)?; // assert the collateral is listed and has not been migrated/revoked let collateral_oracle: Addr = deps.api.addr_humanize(&config.collateral_oracle)?; assert_revoked_collateral(load_collateral_info( deps.as_ref(), collateral_oracle, &position.collateral.info, false, )?)?; // assert asset migrated match position.asset.info.clone() { AssetInfoRaw::Token { contract_addr } => { assert_migrated_asset(&read_asset_config(deps.storage, &contract_addr)?)? } _ => panic!("DO NOT ENTER HERE"), }; // Increase collateral amount position.collateral.amount += collateral.amount; store_position(deps.storage, position_idx, &position)?; Ok(Response::new().add_attributes(vec![ attr("action", "deposit"), attr("position_idx", position_idx.to_string()), attr("deposit_amount", collateral.to_string()), ])) } pub fn withdraw( deps: DepsMut, sender: Addr, position_idx: Uint128, collateral: Option<Asset>, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let mut position: Position = read_position(deps.storage, position_idx)?; let position_owner = deps.api.addr_humanize(&position.owner)?; if sender != position_owner { return Err(StdError::generic_err("unauthorized")); } // if collateral is not provided, withraw all collateral let collateral: Asset = if let Some(collateral) = collateral { // Check the given collateral has same asset info // with position's collateral token // also Check the collateral amount is non-zero assert_collateral(deps.as_ref(), &position, &collateral)?; if position.collateral.amount < collateral.amount { return Err(StdError::generic_err( "Cannot withdraw more than you provide", )); } collateral } else { position.collateral.to_normal(deps.api)? }; let asset_token_raw = match position.asset.info.clone() { AssetInfoRaw::Token { contract_addr } => contract_addr, _ => panic!("DO NOT ENTER HERE"), }; let asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; let oracle: Addr = deps.api.addr_humanize(&config.oracle)?; let asset_price: Decimal = load_asset_price(deps.as_ref(), oracle, &position.asset.info, true)?; // Fetch collateral info from collateral oracle let collateral_oracle: Addr = deps.api.addr_humanize(&config.collateral_oracle)?; let (collateral_price, mut collateral_multiplier, _collateral_is_revoked) = load_collateral_info( deps.as_ref(), collateral_oracle, &position.collateral.info, true, )?; // ignore multiplier for delisted assets if asset_config.end_price.is_some() { collateral_multiplier = Decimal::one(); } // Compute new collateral amount let collateral_amount: Uint128 = position.collateral.amount.checked_sub(collateral.amount)?; // Convert asset to collateral unit let asset_value_in_collateral_asset: Uint128 = position.asset.amount * decimal_division(asset_price, collateral_price); // Check minimum collateral ratio is satisfied if asset_value_in_collateral_asset * asset_config.min_collateral_ratio * collateral_multiplier > collateral_amount { return Err(StdError::generic_err( "Cannot withdraw collateral over than minimum collateral ratio", )); } let mut messages: Vec<CosmosMsg> = vec![]; position.collateral.amount = collateral_amount; if position.collateral.amount == Uint128::zero() && position.asset.amount == Uint128::zero() { // if it is a short position, release locked funds if is_short_position(deps.storage, position_idx)? { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.lock)?.to_string(), funds: vec![], msg: to_binary(&LockExecuteMsg::ReleasePositionFunds { position_idx })?, })); } remove_position(deps.storage, position_idx)?; } else { store_position(deps.storage, position_idx, &position)?; } // Compute tax amount let tax_amount = collateral.compute_tax(&deps.querier)?; Ok(Response::new() .add_messages( vec![ vec![collateral.clone().into_msg(&deps.querier, position_owner)?], messages, ] .concat(), ) .add_attributes(vec![ attr("action", "withdraw"), attr("position_idx", position_idx.to_string()), attr("withdraw_amount", collateral.to_string()), attr( "tax_amount", tax_amount.to_string() + &collateral.info.to_string(), ), ])) } pub fn mint( deps: DepsMut, env: Env, sender: Addr, position_idx: Uint128, asset: Asset, short_params: Option<ShortParams>, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let mint_amount = asset.amount; let mut position: Position = read_position(deps.storage, position_idx)?; let position_owner = deps.api.addr_humanize(&position.owner)?; if sender != position_owner { return Err(StdError::generic_err("unauthorized")); } assert_asset(deps.as_ref(), &position, &asset)?; let asset_token_raw = match position.asset.info.clone() { AssetInfoRaw::Token { contract_addr } => contract_addr, _ => panic!("DO NOT ENTER HERE"), }; // assert the asset migrated let asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; assert_migrated_asset(&asset_config)?; // assert the collateral is listed and has not been migrated/revoked let collateral_oracle: Addr = deps.api.addr_humanize(&config.collateral_oracle)?; let (collateral_price, collateral_multiplier) = assert_revoked_collateral(load_collateral_info( deps.as_ref(), collateral_oracle, &position.collateral.info, true, )?)?; // for assets with limited minting period (preIPO assets), assert minting phase assert_mint_period(&env, &asset_config)?; let oracle: Addr = deps.api.addr_humanize(&config.oracle)?; let asset_price: Decimal = load_asset_price(deps.as_ref(), oracle, &position.asset.info, true)?; // Compute new asset amount let asset_amount: Uint128 = mint_amount + position.asset.amount; // Convert asset to collateral unit let asset_value_in_collateral_asset: Uint128 = asset_amount * decimal_division(asset_price, collateral_price); // Check minimum collateral ratio is satisfied if asset_value_in_collateral_asset * asset_config.min_collateral_ratio * collateral_multiplier > position.collateral.amount { return Err(StdError::generic_err( "Cannot mint asset over than min collateral ratio", )); } position.asset.amount += mint_amount; store_position(deps.storage, position_idx, &position)?; let asset_token = deps.api.addr_humanize(&asset_config.token)?; // If the position is flagged as short position. // immediately sell the token to terraswap // and execute staking short token let messages: Vec<CosmosMsg> = if is_short_position(deps.storage, position_idx)? { // need to sell the tokens to terraswap // load pair contract address let pair_info = query_pair_info( &deps.querier, deps.api.addr_humanize(&config.terraswap_factory)?, &[ AssetInfo::NativeToken { denom: config.base_denom, }, asset.info.clone(), ], )?; // 1. Mint token to itself // 2. Swap token and send to lock contract // 3. Call lock hook on lock contract // 4. Increase short token in staking contract let lock_contract = deps.api.addr_humanize(&config.lock)?; vec![ CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: env.contract.address.to_string(), amount: mint_amount, })?, }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_info.contract_addr, amount: mint_amount, msg: to_binary( &(if let Some(short_params) = short_params { PairCw20HookMsg::Swap { belief_price: short_params.belief_price, max_spread: short_params.max_spread, to: Some(lock_contract.to_string()), } } else { PairCw20HookMsg::Swap { belief_price: None, max_spread: None, to: Some(lock_contract.to_string()), } }), )?, })?, }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: lock_contract.to_string(), funds: vec![], msg: to_binary(&LockExecuteMsg::LockPositionFundsHook { position_idx, receiver: position_owner.to_string(), })?, }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.staking)?.to_string(), funds: vec![], msg: to_binary(&StakingExecuteMsg::IncreaseShortToken { asset_token: asset_token.to_string(), staker_addr: position_owner.to_string(), amount: mint_amount, })?, }), ] } else { vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&asset_config.token)?.to_string(), msg: to_binary(&Cw20ExecuteMsg::Mint { amount: mint_amount, recipient: position_owner.to_string(), })?, funds: vec![], })] }; Ok(Response::new() .add_attributes(vec![ attr("action", "mint"), attr("position_idx", position_idx.to_string()), attr("mint_amount", asset.to_string()), ]) .add_messages(messages)) } pub fn burn( deps: DepsMut, env: Env, sender: Addr, position_idx: Uint128, asset: Asset, ) -> StdResult<Response> { let burn_amount = asset.amount; let config: Config = read_config(deps.storage)?; let mut position: Position = read_position(deps.storage, position_idx)?; let position_owner = deps.api.addr_humanize(&position.owner)?; let collateral_info: AssetInfo = position.collateral.info.to_normal(deps.api)?; // Check the asset has same token with position asset // also Check burn amount is non-zero assert_asset(deps.as_ref(), &position, &asset)?; let asset_token_raw = match position.asset.info.clone() { AssetInfoRaw::Token { contract_addr } => contract_addr, _ => panic!("DO NOT ENTER HERE"), }; let asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; if position.asset.amount < burn_amount { return Err(StdError::generic_err( "Cannot burn asset more than you mint", )); } let mut messages: Vec<CosmosMsg> = vec![]; let mut attributes: Vec<Attribute> = vec![]; // For preIPO assets, burning should be disabled after the minting period is over. // Burning is enabled again after IPO event is triggered, when ipo_params are set to None assert_burn_period(&env, &asset_config)?; // Check if it is a short position let is_short_position: bool = is_short_position(deps.storage, position_idx)?; // fetch collateral info from collateral oracle let collateral_oracle: Addr = deps.api.addr_humanize(&config.collateral_oracle)?; let (collateral_price, _collateral_multiplier, _collateral_is_revoked) = load_collateral_info( deps.as_ref(), collateral_oracle, &position.collateral.info, true, )?; // If the collateral is default denom asset and the asset is deprecated, // anyone can execute burn the asset to any position without permission let mut close_position: bool = false; if let Some(end_price) = asset_config.end_price { let asset_price: Decimal = end_price; let collateral_price_in_asset = decimal_division(asset_price, collateral_price); // Burn deprecated asset to receive collaterals back let conversion_rate = Decimal::from_ratio(position.collateral.amount, position.asset.amount); let mut refund_collateral = Asset { info: collateral_info.clone(), amount: std::cmp::min( burn_amount * collateral_price_in_asset, burn_amount * conversion_rate, ), }; position.asset.amount = position.asset.amount.checked_sub(burn_amount).unwrap(); position.collateral.amount = position .collateral .amount .checked_sub(refund_collateral.amount) .unwrap(); // due to rounding, include 1 if position.collateral.amount <= Uint128::from(1u128) && position.asset.amount == Uint128::zero() { close_position = true; remove_position(deps.storage, position_idx)?; } else { store_position(deps.storage, position_idx, &position)?; } // Subtract protocol fee from refunded collateral let protocol_fee = Asset { info: collateral_info, amount: burn_amount * collateral_price_in_asset * config.protocol_fee_rate, }; if !protocol_fee.amount.is_zero() { messages.push( protocol_fee .clone() .into_msg(&deps.querier, deps.api.addr_humanize(&config.collector)?)?, ); refund_collateral.amount = refund_collateral .amount .checked_sub(protocol_fee.amount) .unwrap(); } attributes.push(attr("protocol_fee", protocol_fee.to_string())); // Refund collateral msg messages.push(refund_collateral.clone().into_msg(&deps.querier, sender)?); attributes.push(attr( "refund_collateral_amount", refund_collateral.to_string(), )); } else { if sender != position_owner { return Err(StdError::generic_err("unauthorized")); } let oracle = deps.api.addr_humanize(&config.oracle)?; let asset_price: Decimal = load_asset_price(deps.as_ref(), oracle, &asset.info.to_raw(deps.api)?, true)?; let collateral_price_in_asset: Decimal = decimal_division(asset_price, collateral_price); // Subtract the protocol fee from the position's collateral let protocol_fee = Asset { info: collateral_info, amount: burn_amount * collateral_price_in_asset * config.protocol_fee_rate, }; if !protocol_fee.amount.is_zero() { messages.push( protocol_fee .clone() .into_msg(&deps.querier, deps.api.addr_humanize(&config.collector)?)?, ); position.collateral.amount = position .collateral .amount .checked_sub(protocol_fee.amount)? } attributes.push(attr("protocol_fee", protocol_fee.to_string())); // Update asset amount position.asset.amount = position.asset.amount.checked_sub(burn_amount).unwrap(); store_position(deps.storage, position_idx, &position)?; } // If the position is flagged as short position. // decrease short token amount from the staking contract let asset_token = deps.api.addr_humanize(&asset_config.token)?; if is_short_position { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.staking)?.to_string(), msg: to_binary(&StakingExecuteMsg::DecreaseShortToken { asset_token: asset_token.to_string(), staker_addr: position_owner.to_string(), amount: burn_amount, })?, funds: vec![], })); if close_position { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.lock)?.to_string(), funds: vec![], msg: to_binary(&LockExecuteMsg::ReleasePositionFunds { position_idx })?, })); } } Ok(Response::new() .add_messages( vec![ vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Burn { amount: burn_amount, })?, funds: vec![], })], messages, ] .concat(), ) .add_attributes( vec![ vec![ attr("action", "burn"), attr("position_idx", position_idx.to_string()), attr("burn_amount", asset.to_string()), ], attributes, ] .concat(), )) } pub fn auction( deps: DepsMut, sender: Addr, position_idx: Uint128, asset: Asset, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let mut position: Position = read_position(deps.storage, position_idx)?; let position_owner = deps.api.addr_humanize(&position.owner)?; assert_asset(deps.as_ref(), &position, &asset)?; let asset_token_raw = match position.asset.info.clone() { AssetInfoRaw::Token { contract_addr } => contract_addr, _ => panic!("DO NOT ENTER HERE"), }; let asset_config: AssetConfig = read_asset_config(deps.storage, &asset_token_raw)?; assert_migrated_asset(&asset_config)?; let asset_token = deps.api.addr_humanize(&asset_config.token)?; let collateral_info = position.collateral.info.to_normal(deps.api)?; if asset.amount > position.asset.amount { return Err(StdError::generic_err( "Cannot liquidate more than the position amount".to_string(), )); } let oracle: Addr = deps.api.addr_humanize(&config.oracle)?; let asset_price: Decimal = load_asset_price(deps.as_ref(), oracle, &position.asset.info, true)?; // fetch collateral info from collateral oracle let collateral_oracle: Addr = deps.api.addr_humanize(&config.collateral_oracle)?; let (collateral_price, collateral_multiplier, _collateral_is_revoked) = load_collateral_info( deps.as_ref(), collateral_oracle, &position.collateral.info, true, )?; // Compute collateral price in asset unit let collateral_price_in_asset: Decimal = decimal_division(asset_price, collateral_price); // Check the position is in auction state // asset_amount * price_to_collateral * auction_threshold > collateral_amount let asset_value_in_collateral_asset: Uint128 = position.asset.amount * collateral_price_in_asset; if asset_value_in_collateral_asset * asset_config.min_collateral_ratio * collateral_multiplier < position.collateral.amount { return Err(StdError::generic_err( "Cannot liquidate a safely collateralized position", )); } // auction discount is min(min_cr - 1, auction_discount) let auction_discount: Decimal = decimal_min( asset_config.auction_discount, decimal_subtraction(asset_config.min_collateral_ratio, Decimal::one()), ); // Compute discounted price let discounted_price: Decimal = decimal_division( collateral_price_in_asset, decimal_subtraction(Decimal::one(), auction_discount), ); // Convert asset value in discounted collateral unit let asset_value_in_collateral_asset: Uint128 = asset.amount * discounted_price; let mut messages: Vec<CosmosMsg> = vec![]; // Cap return collateral amount to position collateral amount // If the given asset amount exceeds the amount required to liquidate position, // left asset amount will be refunded to the executor. let (return_collateral_amount, refund_asset_amount) = if asset_value_in_collateral_asset > position.collateral.amount { // refunds left asset to position liquidator let refund_asset_amount = asset_value_in_collateral_asset .checked_sub(position.collateral.amount) .unwrap() * reverse_decimal(discounted_price); if !refund_asset_amount.is_zero() { let refund_asset: Asset = Asset { info: asset.info.clone(), amount: refund_asset_amount, }; messages.push(refund_asset.into_msg(&deps.querier, sender.clone())?); } (position.collateral.amount, refund_asset_amount) } else { (asset_value_in_collateral_asset, Uint128::zero()) }; let liquidated_asset_amount = asset.amount.checked_sub(refund_asset_amount).unwrap(); let left_asset_amount = position .asset .amount .checked_sub(liquidated_asset_amount) .unwrap(); let left_collateral_amount = position .collateral .amount .checked_sub(return_collateral_amount) .unwrap(); // Check if it is a short position let is_short_position: bool = is_short_position(deps.storage, position_idx)?; let mut close_position: bool = false; if left_collateral_amount.is_zero() { // all collaterals are sold out close_position = true; remove_position(deps.storage, position_idx)?; } else if left_asset_amount.is_zero() { // all assets are paid close_position = true; remove_position(deps.storage, position_idx)?; // refunds left collaterals to position owner let refund_collateral: Asset = Asset { info: collateral_info.clone(), amount: left_collateral_amount, }; messages.push(refund_collateral.into_msg(&deps.querier, position_owner.clone())?); } else { position.collateral.amount = left_collateral_amount; position.asset.amount = left_asset_amount; store_position(deps.storage, position_idx, &position)?; } // token burn message messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Burn { amount: liquidated_asset_amount, })?, funds: vec![], })); // Deduct protocol fee let protocol_fee = liquidated_asset_amount * collateral_price_in_asset * config.protocol_fee_rate; let return_collateral_amount = return_collateral_amount.checked_sub(protocol_fee).unwrap(); // return collateral to liquidation initiator(sender) let return_collateral_asset = Asset { info: collateral_info.clone(), amount: return_collateral_amount, }; let tax_amount = return_collateral_asset.compute_tax(&deps.querier)?; messages.push(return_collateral_asset.into_msg(&deps.querier, sender)?); // protocol fee sent to collector let protocol_fee_asset = Asset { info: collateral_info.clone(), amount: protocol_fee, };
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
true
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/migration.rs
contracts/mirror_mint/src/migration.rs
use cosmwasm_storage::Bucket; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, Decimal, Order, StdError, StdResult, Storage}; use crate::state::{AssetConfig, PREFIX_ASSET_CONFIG}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyAssetConfig { pub token: CanonicalAddr, pub auction_discount: Decimal, pub min_collateral_ratio: Decimal, pub end_price: Option<Decimal>, pub ipo_params: Option<LegacyIPOParams>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyIPOParams { pub mint_end: u64, pub pre_ipo_price: Decimal, pub min_collateral_ratio_after_ipo: Decimal, } pub fn migrate_asset_configs(storage: &mut dyn Storage) -> StdResult<()> { let mut legacy_asset_configs_bucket: Bucket<LegacyAssetConfig> = Bucket::new(storage, PREFIX_ASSET_CONFIG); let mut asset_configs: Vec<(CanonicalAddr, LegacyAssetConfig)> = vec![]; for item in legacy_asset_configs_bucket.range(None, None, Order::Ascending) { let (k, p) = item?; asset_configs.push((CanonicalAddr::from(k), p)); } for (asset, _) in asset_configs.clone().into_iter() { legacy_asset_configs_bucket.remove(asset.as_slice()); } let mut new_asset_configs_bucket: Bucket<AssetConfig> = Bucket::new(storage, PREFIX_ASSET_CONFIG); for (asset, asset_config) in asset_configs.into_iter() { if asset_config.ipo_params.is_some() { return Err(StdError::generic_err( "can not exeucte migration while there is an ipo event", )); } let new_asset_config = &AssetConfig { token: asset_config.token, auction_discount: asset_config.auction_discount, min_collateral_ratio: asset_config.min_collateral_ratio, end_price: asset_config.end_price, ipo_params: None, }; new_asset_configs_bucket.save(asset.as_slice(), new_asset_config)?; } Ok(()) } #[cfg(test)] mod migrate_tests { use crate::state::read_asset_config; use super::*; use cosmwasm_std::{testing::mock_dependencies, Api}; pub fn asset_configs_old_store(storage: &mut dyn Storage) -> Bucket<LegacyAssetConfig> { Bucket::new(storage, PREFIX_ASSET_CONFIG) } #[test] fn test_asset_configs_migration() { let mut deps = mock_dependencies(&[]); let mut legacy_store = asset_configs_old_store(&mut deps.storage); let asset_config = LegacyAssetConfig { token: deps.api.addr_canonicalize("mAPPL").unwrap(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), end_price: None, ipo_params: None, }; legacy_store .save(asset_config.token.as_slice(), &asset_config) .unwrap(); migrate_asset_configs(deps.as_mut().storage).unwrap(); let new_asset_config: AssetConfig = read_asset_config(deps.as_mut().storage, &asset_config.token).unwrap(); assert_eq!( new_asset_config, AssetConfig { token: asset_config.token, auction_discount: asset_config.auction_discount, min_collateral_ratio: asset_config.min_collateral_ratio, end_price: asset_config.end_price, ipo_params: None, } ); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/testing/mock_querier.rs
contracts/mirror_mint/src/testing/mock_querier.rs
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, from_slice, to_binary, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, WasmQuery, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use mirror_protocol::collateral_oracle::CollateralPriceResponse; use tefi_oracle::hub::PriceResponse; use terra_cosmwasm::{TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper, TerraRoute}; use terraswap::{asset::AssetInfo, asset::PairInfo}; /// mock_dependencies is a drop-in replacement for cosmwasm_std::testing::mock_dependencies /// this uses our CustomQuerier. pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new(MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)])); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<TerraQueryWrapper>, tax_querier: TaxQuerier, oracle_price_querier: OraclePriceQuerier, collateral_oracle_querier: CollateralOracleQuerier, terraswap_pair_querier: TerraswapPairQuerier, } #[derive(Clone, Default)] pub struct TaxQuerier { rate: Decimal, // this lets us iterate over all pairs that match the first string caps: HashMap<String, Uint128>, } impl TaxQuerier { pub fn new(rate: Decimal, caps: &[(&String, &Uint128)]) -> Self { TaxQuerier { rate, caps: caps_to_map(caps), } } } pub(crate) fn caps_to_map(caps: &[(&String, &Uint128)]) -> HashMap<String, Uint128> { let mut owner_map: HashMap<String, Uint128> = HashMap::new(); for (denom, cap) in caps.iter() { owner_map.insert(denom.to_string(), **cap); } owner_map } #[derive(Clone, Default)] pub struct OraclePriceQuerier { // this lets us iterate over all pairs that match the first string oracle_price: HashMap<String, Decimal>, } impl OraclePriceQuerier { pub fn new(oracle_price: &[(&String, &Decimal)]) -> Self { OraclePriceQuerier { oracle_price: oracle_price_to_map(oracle_price), } } } pub(crate) fn oracle_price_to_map( oracle_price: &[(&String, &Decimal)], ) -> HashMap<String, Decimal> { let mut oracle_price_map: HashMap<String, Decimal> = HashMap::new(); for (base_quote, oracle_price) in oracle_price.iter() { oracle_price_map.insert((*base_quote).clone(), **oracle_price); } oracle_price_map } #[derive(Clone, Default)] pub struct CollateralOracleQuerier { // this lets us iterate over all pairs that match the first string collateral_infos: HashMap<String, (Decimal, Decimal, bool)>, } impl CollateralOracleQuerier { pub fn new(collateral_infos: &[(&String, &Decimal, &Decimal, &bool)]) -> Self { CollateralOracleQuerier { collateral_infos: collateral_infos_to_map(collateral_infos), } } } pub(crate) fn collateral_infos_to_map( collateral_infos: &[(&String, &Decimal, &Decimal, &bool)], ) -> HashMap<String, (Decimal, Decimal, bool)> { let mut collateral_infos_map: HashMap<String, (Decimal, Decimal, bool)> = HashMap::new(); for (collateral, collateral_price, collateral_multiplier, is_revoked) in collateral_infos.iter() { collateral_infos_map.insert( (*collateral).clone(), (**collateral_price, **collateral_multiplier, **is_revoked), ); } collateral_infos_map } #[derive(Clone, Default)] pub struct TerraswapPairQuerier { // this lets us iterate over all pairs that match the first string pairs: HashMap<String, String>, } impl TerraswapPairQuerier { pub fn new(pairs: &[(&String, &String, &String)]) -> Self { TerraswapPairQuerier { pairs: paris_to_map(pairs), } } } pub(crate) fn paris_to_map(pairs: &[(&String, &String, &String)]) -> HashMap<String, String> { let mut pairs_map: HashMap<String, String> = HashMap::new(); for (asset1, asset2, pair) in pairs.iter() { pairs_map.insert((asset1.to_string() + asset2).clone(), pair.to_string()); } pairs_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<TerraQueryWrapper> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum MockQueryMsg { Price { asset_token: String, timeframe: Option<u64>, }, CollateralPrice { asset: String, }, Pair { asset_infos: [AssetInfo; 2], }, } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<TerraQueryWrapper>) -> QuerierResult { match &request { QueryRequest::Custom(TerraQueryWrapper { route, query_data }) => { if route == &TerraRoute::Treasury { match query_data { TerraQuery::TaxRate {} => { let res = TaxRateResponse { rate: self.tax_querier.rate, }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } TerraQuery::TaxCap { denom } => { let cap = self .tax_querier .caps .get(denom) .copied() .unwrap_or_default(); let res = TaxCapResponse { cap }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } _ => panic!("DO NOT ENTER HERE"), } } else { panic!("DO NOT ENTER HERE") } } QueryRequest::Wasm(WasmQuery::Smart { contract_addr: _, msg, }) => match from_binary(msg).unwrap() { MockQueryMsg::Price { asset_token, timeframe: _, } => match self.oracle_price_querier.oracle_price.get(&asset_token) { Some(base_price) => { SystemResult::Ok(ContractResult::from(to_binary(&PriceResponse { rate: *base_price, last_updated: 1000u64, }))) } None => SystemResult::Err(SystemError::InvalidRequest { error: "No oracle price exists".to_string(), request: msg.as_slice().into(), }), }, MockQueryMsg::CollateralPrice { asset } => { match self.collateral_oracle_querier.collateral_infos.get(&asset) { Some(collateral_info) => SystemResult::Ok(ContractResult::from(to_binary( &CollateralPriceResponse { asset, rate: collateral_info.0, last_updated: 1000u64, multiplier: collateral_info.1, is_revoked: collateral_info.2, }, ))), None => SystemResult::Err(SystemError::InvalidRequest { error: "Collateral info does not exist".to_string(), request: msg.as_slice().into(), }), } } MockQueryMsg::Pair { asset_infos } => { match self .terraswap_pair_querier .pairs .get(&(asset_infos[0].to_string() + &asset_infos[1].to_string())) { Some(pair) => { SystemResult::Ok(ContractResult::from(to_binary(&PairInfo { asset_infos, contract_addr: pair.to_string(), liquidity_token: "liquidity".to_string(), }))) } None => SystemResult::Err(SystemError::InvalidRequest { error: "No pair exists".to_string(), request: msg.as_slice().into(), }), } } }, _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new(base: MockQuerier<TerraQueryWrapper>) -> Self { WasmMockQuerier { base, tax_querier: TaxQuerier::default(), oracle_price_querier: OraclePriceQuerier::default(), collateral_oracle_querier: CollateralOracleQuerier::default(), terraswap_pair_querier: TerraswapPairQuerier::default(), } } // configure the token owner mock querier pub fn with_tax(&mut self, rate: Decimal, caps: &[(&String, &Uint128)]) { self.tax_querier = TaxQuerier::new(rate, caps); } // configure the oracle price mock querier pub fn with_oracle_price(&mut self, oracle_price: &[(&String, &Decimal)]) { self.oracle_price_querier = OraclePriceQuerier::new(oracle_price); } // configure the collateral oracle mock querier pub fn with_collateral_infos( &mut self, collateral_infos: &[(&String, &Decimal, &Decimal, &bool)], ) { self.collateral_oracle_querier = CollateralOracleQuerier::new(collateral_infos); } // configure the terraswap factory pair mock querier pub fn with_terraswap_pair(&mut self, pairs: &[(&String, &String, &String)]) { self.terraswap_pair_querier = TerraswapPairQuerier::new(pairs); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/testing/short_test.rs
contracts/mirror_mint/src/testing/short_test.rs
use crate::contract::{execute, instantiate, query}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ attr, from_binary, to_binary, BankMsg, BlockInfo, Coin, CosmosMsg, Decimal, Env, SubMsg, Timestamp, Uint128, WasmMsg, }; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use mirror_protocol::lock::ExecuteMsg as LockExecuteMsg; use mirror_protocol::mint::{ Cw20HookMsg, ExecuteMsg, InstantiateMsg, PositionResponse, QueryMsg, ShortParams, }; use mirror_protocol::staking::ExecuteMsg as StakingExecuteMsg; use terraswap::{ asset::{Asset, AssetInfo}, pair::Cw20HookMsg as PairCw20HookMsg, }; static TOKEN_CODE_ID: u64 = 10u64; fn mock_env_with_block_time(time: u64) -> Env { let env = mock_env(); // register time Env { block: BlockInfo { height: 1, time: Timestamp::from_seconds(time), chain_id: "columbus".to_string(), }, ..env } } #[test] fn open_short_position() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env(); let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env(); let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env(); let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // register terraswap pair deps.querier.with_terraswap_pair(&[( &"uusd".to_string(), &"asset0000".to_string(), &"pair0000".to_string(), )]); let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: Some(ShortParams { belief_price: None, max_spread: None, }), }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "open_position"), attr("position_idx", "1"), attr("mint_amount", "666666asset0000"), attr("collateral_amount", "1000000uusd"), attr("is_short", "true"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: MOCK_CONTRACT_ADDR.to_string(), amount: Uint128::from(666666u128), }) .unwrap() })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { contract: "pair0000".to_string(), amount: Uint128::from(666666u128), msg: to_binary(&PairCw20HookMsg::Swap { belief_price: None, max_spread: None, to: Some("lock0000".to_string()), }) .unwrap() }) .unwrap() })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "lock0000".to_string(), funds: vec![], msg: to_binary(&LockExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(1u128), receiver: "addr0000".to_string(), }) .unwrap(), })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "staking0000".to_string(), funds: vec![], msg: to_binary(&StakingExecuteMsg::IncreaseShortToken { asset_token: "asset0000".to_string(), staker_addr: "addr0000".to_string(), amount: Uint128::from(666666u128), }) .unwrap(), })) ] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Position { position_idx: Uint128::from(1u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128::from(1u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: true, } ); } #[test] fn mint_short_position() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env(); let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // register terraswap pair deps.querier.with_terraswap_pair(&[( &"uusd".to_string(), &"asset0000".to_string(), &"pair0000".to_string(), )]); let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(200), short_params: Some(ShortParams { belief_price: None, max_spread: None, }), }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // mint more tokens from the short position let msg = ExecuteMsg::Mint { position_idx: Uint128::from(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(100u128), }, short_params: None, }; let env = mock_env_with_block_time(1000); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "mint"), attr("position_idx", "1"), attr("mint_amount", "100asset0000"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: MOCK_CONTRACT_ADDR.to_string(), amount: Uint128::from(100u128), }) .unwrap() })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { contract: "pair0000".to_string(), amount: Uint128::from(100u128), msg: to_binary(&PairCw20HookMsg::Swap { belief_price: None, max_spread: None, to: Some("lock0000".to_string()), }) .unwrap() }) .unwrap() })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "lock0000".to_string(), funds: vec![], msg: to_binary(&LockExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(1u128), receiver: "addr0000".to_string(), }) .unwrap(), })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "staking0000".to_string(), funds: vec![], msg: to_binary(&StakingExecuteMsg::IncreaseShortToken { asset_token: "asset0000".to_string(), staker_addr: "addr0000".to_string(), amount: Uint128::from(100u128), }) .unwrap(), })) ] ); } #[test] fn burn_short_position() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // register terraswap pair deps.querier.with_terraswap_pair(&[( &"uusd".to_string(), &"asset0000".to_string(), &"pair0000".to_string(), )]); let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(200), short_params: Some(ShortParams { belief_price: None, max_spread: None, }), }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // burn asset tokens from the short position let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(100u128), msg: to_binary(&Cw20HookMsg::Burn { position_idx: Uint128::from(1u128), }) .unwrap(), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "burn"), attr("position_idx", "1"), attr("burn_amount", "100asset0000"), // value = 100 attr("protocol_fee", "1uusd"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Burn { amount: Uint128::from(100u128), }) .unwrap(), })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "collector0000".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(1u128) }], })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "staking0000".to_string(), funds: vec![], msg: to_binary(&StakingExecuteMsg::DecreaseShortToken { staker_addr: "addr0000".to_string(), asset_token: "asset0000".to_string(), amount: Uint128::from(100u128), }) .unwrap(), })) ] ); } #[test] fn auction_short_position() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), staking: "staking0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // register terraswap pair deps.querier.with_terraswap_pair(&[( &"uusd".to_string(), &"asset0000".to_string(), &"pair0000".to_string(), )]); let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: Some(ShortParams { belief_price: None, max_spread: None, }), }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // asset price increased deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(115)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(100u128), msg: to_binary(&Cw20HookMsg::Auction { position_idx: Uint128::from(1u128), }) .unwrap(), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "auction"), attr("position_idx", "1"), attr("owner", "addr0000"), attr("return_collateral_amount", "142uusd"), attr("liquidated_amount", "100asset0000"), attr("tax_amount", "0uusd"), attr("protocol_fee", "1uusd"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), msg: to_binary(&Cw20ExecuteMsg::Burn { amount: Uint128::from(100u128), }) .unwrap(), funds: vec![], })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0000".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(142u128) }], })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "collector0000".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(1u128) }] })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "staking0000".to_string(), funds: vec![], msg: to_binary(&StakingExecuteMsg::DecreaseShortToken { staker_addr: "addr0000".to_string(), asset_token: "asset0000".to_string(), amount: Uint128::from(100u128), }) .unwrap(), })) ] ); } #[test] fn close_short_position() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), ]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(200), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // register terraswap pair deps.querier.with_terraswap_pair(&[( &"uusd".to_string(), &"asset0000".to_string(), &"pair0000".to_string(), )]); let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(200u128), // will mint 100 mAsset and lock 100 UST }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(200), short_params: Some(ShortParams { belief_price: None, max_spread: None, }), }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(200u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // burn all asset tokens from the short position let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(100u128), msg: to_binary(&Cw20HookMsg::Burn { position_idx: Uint128::from(1u128), }) .unwrap(), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0000", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // withdraw all collateral let msg = ExecuteMsg::Withdraw { position_idx: Uint128::from(1u128), collateral: Some(Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(199u128), // 1 collateral spent as protocol fee }), }; let env = mock_env_with_block_time(1000); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); dbg!(&res.messages); // refunds collateral and releases locked funds from lock contract assert!(res .messages .contains(&SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "lock0000".to_string(), funds: vec![], msg: to_binary(&LockExecuteMsg::ReleasePositionFunds { position_idx: Uint128::from(1u128), }) .unwrap(), })))) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/testing/mod.rs
contracts/mirror_mint/src/testing/mod.rs
mod contract_test; mod mock_querier; mod positions_test; mod pre_ipo_test; mod short_test;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/testing/contract_test.rs
contracts/mirror_mint/src/testing/contract_test.rs
use crate::contract::{execute, instantiate, query}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info}; use cosmwasm_std::{from_binary, to_binary, CosmosMsg, Decimal, StdError, SubMsg, WasmMsg}; use mirror_protocol::collateral_oracle::{ExecuteMsg::RegisterCollateralAsset, SourceType}; use mirror_protocol::mint::{ AssetConfigResponse, ConfigResponse, ExecuteMsg, IPOParams, InstantiateMsg, QueryMsg, }; use terraswap::asset::AssetInfo; static TOKEN_CODE_ID: u64 = 10u64; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom: "uusd".to_string(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // it worked, let's query the state let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap(); let config: ConfigResponse = from_binary(&res).unwrap(); assert_eq!("owner0000", config.owner.as_str()); assert_eq!("uusd", config.base_denom); assert_eq!("oracle0000", config.oracle.as_str()); assert_eq!("staking0000", config.staking.as_str()); assert_eq!("collector0000", config.collector.as_str()); assert_eq!("terraswap_factory", config.terraswap_factory.as_str()); assert_eq!("lock0000", config.lock.as_str()); assert_eq!(TOKEN_CODE_ID, config.token_code_id); assert_eq!(Decimal::percent(1), config.protocol_fee_rate); } #[test] fn update_config() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom: "uusd".to_string(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // update owner let info = mock_info("owner0000", &[]); let msg = ExecuteMsg::UpdateConfig { owner: Some("owner0001".to_string()), oracle: None, collector: None, terraswap_factory: None, lock: None, token_code_id: Some(100u64), protocol_fee_rate: None, collateral_oracle: None, staking: None, }; let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // it worked, let's query the state let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap(); let config: ConfigResponse = from_binary(&res).unwrap(); assert_eq!("owner0001", config.owner.as_str()); assert_eq!(100u64, config.token_code_id); // Unauthorized err let info = mock_info("owner0000", &[]); let msg = ExecuteMsg::UpdateConfig { owner: None, oracle: None, collector: None, terraswap_factory: None, lock: None, token_code_id: None, protocol_fee_rate: None, collateral_oracle: None, staking: None, }; let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"), _ => panic!("Must return unauthorized error"), } } #[test] fn register_asset() { let mut deps = mock_dependencies(&[]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "collateraloracle0000".to_string(), funds: vec![], msg: to_binary(&RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, multiplier: Decimal::one(), price_source: SourceType::TefiOracle { oracle_addr: "oracle0000".to_string(), }, }) .unwrap(), }))] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::AssetConfig { asset_token: "asset0000".to_string(), }, ) .unwrap(); let asset_config: AssetConfigResponse = from_binary(&res).unwrap(); assert_eq!( asset_config, AssetConfigResponse { token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), end_price: None, ipo_params: None, } ); // must be failed with the already registered token error let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "Asset was already registered"), _ => panic!("DO NOT ENTER HERE"), } // must be failed with unauthorized error let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0001", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "unauthorized"), _ => panic!("DO NOT ENTER HERE"), } // must be failed with unauthorized error let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(150), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "auction_discount must be smaller than 1") } _ => panic!("DO NOT ENTER HERE"), } // must be failed with unauthorized error let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(50), ipo_params: None, }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "min_collateral_ratio must be bigger or equal than 1.1") } _ => panic!("DO NOT ENTER HERE"), } } #[test] fn update_asset() { let mut deps = mock_dependencies(&[]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::UpdateAsset { asset_token: "asset0000".to_string(), auction_discount: Some(Decimal::percent(30)), min_collateral_ratio: Some(Decimal::percent(200)), ipo_params: Some(IPOParams { min_collateral_ratio_after_ipo: Decimal::percent(150), mint_end: 10000u64, pre_ipo_price: Decimal::percent(1), trigger_addr: "ipotrigger0000".to_string(), }), }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let res = query( deps.as_ref(), mock_env(), QueryMsg::AssetConfig { asset_token: "asset0000".to_string(), }, ) .unwrap(); let asset_config: AssetConfigResponse = from_binary(&res).unwrap(); assert_eq!( asset_config, AssetConfigResponse { token: "asset0000".to_string(), auction_discount: Decimal::percent(30), min_collateral_ratio: Decimal::percent(200), end_price: None, ipo_params: Some(IPOParams { min_collateral_ratio_after_ipo: Decimal::percent(150), mint_end: 10000u64, pre_ipo_price: Decimal::percent(1), trigger_addr: "ipotrigger0000".to_string(), }), } ); let msg = ExecuteMsg::UpdateAsset { asset_token: "asset0000".to_string(), auction_discount: Some(Decimal::percent(130)), min_collateral_ratio: Some(Decimal::percent(150)), ipo_params: None, }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "auction_discount must be smaller than 1") } _ => panic!("Must return unauthorized error"), } let msg = ExecuteMsg::UpdateAsset { asset_token: "asset0000".to_string(), auction_discount: Some(Decimal::percent(30)), min_collateral_ratio: Some(Decimal::percent(50)), ipo_params: None, }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "min_collateral_ratio must be bigger or equal than 1.1") } _ => panic!("Must return unauthorized error"), } let msg = ExecuteMsg::UpdateAsset { asset_token: "asset0000".to_string(), auction_discount: Some(Decimal::percent(30)), min_collateral_ratio: Some(Decimal::percent(200)), ipo_params: None, }; let info = mock_info("owner0001", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "unauthorized"), _ => panic!("Must return unauthorized error"), } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/testing/positions_test.rs
contracts/mirror_mint/src/testing/positions_test.rs
use crate::contract::{execute, instantiate, query}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info}; use cosmwasm_std::{ attr, from_binary, to_binary, BankMsg, BlockInfo, Coin, CosmosMsg, Decimal, Env, StdError, SubMsg, Timestamp, Uint128, WasmMsg, }; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use mirror_protocol::common::OrderBy; use mirror_protocol::mint::{ Cw20HookMsg, ExecuteMsg, InstantiateMsg, PositionResponse, PositionsResponse, QueryMsg, }; use terraswap::asset::{Asset, AssetInfo}; static TOKEN_CODE_ID: u64 = 10u64; fn mock_env_with_block_time(time: u64) -> Env { let env = mock_env(); // register time Env { block: BlockInfo { height: 1, time: Timestamp::from_seconds(time), chain_id: "columbus".to_string(), }, ..env } } #[test] fn open_position() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::percent(50), &Decimal::percent(200), // 2 collateral_multiplier &false, )]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // open position with unknown collateral let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { msg: to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: "asset9999".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset9999", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap_err(); // expect error // must fail; collateral ratio is too low let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(140), short_params: None, }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!( msg, "Can not open a position with low collateral ratio than minimum" ), _ => panic!("DO NOT ENTER ERROR"), } // successful attempt let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "open_position"), attr("position_idx", "1"), attr("mint_amount", "666666asset0000"), attr("collateral_amount", "1000000uusd"), attr("is_short", "false"), ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: "addr0000".to_string(), amount: Uint128::from(666666u128), }) .unwrap(), }))] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Position { position_idx: Uint128::from(1u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128::from(1u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: false, } ); // can query positions let res = query( deps.as_ref(), mock_env(), QueryMsg::Positions { owner_addr: Some("addr0000".to_string()), asset_token: None, limit: None, start_after: None, order_by: Some(OrderBy::Asc), }, ) .unwrap(); let positions: PositionsResponse = from_binary(&res).unwrap(); assert_eq!( positions, PositionsResponse { positions: vec![PositionResponse { idx: Uint128::from(1u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: false, }], } ); // Cannot directly deposit token let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::Token { contract_addr: "asset0001".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let res = execute(deps.as_mut(), env, info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "unauthorized"), _ => panic!("DO NOT ENTER HERE"), } let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { msg: to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(300), // 15 * 2 (multiplier) short_params: None, }) .unwrap(), sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0001", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "open_position"), attr("position_idx", "2"), attr("mint_amount", "166666asset0000"), // 1000000 * 0.5 (price to asset) * 0.5 multiplier / 1.5 (mcr) attr("collateral_amount", "1000000asset0001"), attr("is_short", "false"), ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { recipient: "addr0000".to_string(), amount: Uint128::from(166666u128), }) .unwrap(), }))] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Position { position_idx: Uint128::from(2u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128::from(2u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(166666u128), }, collateral: Asset { info: AssetInfo::Token { contract_addr: "asset0001".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: false, } ); // can query positions let res = query( deps.as_ref(), mock_env(), QueryMsg::Positions { owner_addr: Some("addr0000".to_string()), asset_token: None, limit: None, start_after: None, order_by: Some(OrderBy::Desc), }, ) .unwrap(); let positions: PositionsResponse = from_binary(&res).unwrap(); assert_eq!( positions, PositionsResponse { positions: vec![ PositionResponse { idx: Uint128::from(2u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(166666u128), }, collateral: Asset { info: AssetInfo::Token { contract_addr: "asset0001".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: false, }, PositionResponse { idx: Uint128::from(1u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: false, } ], } ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Positions { owner_addr: Some("addr0000".to_string()), asset_token: None, limit: None, start_after: Some(Uint128::from(2u128)), order_by: Some(OrderBy::Desc), }, ) .unwrap(); let positions: PositionsResponse = from_binary(&res).unwrap(); assert_eq!( positions, PositionsResponse { positions: vec![PositionResponse { idx: Uint128::from(1u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, is_short: false, }], } ); } #[test] fn deposit() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::percent(50), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // open uusd-asset0000 position let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // open asset0001-asset0000 position let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { msg: to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0001", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::Deposit { position_idx: Uint128::from(1u128), collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let res = query( deps.as_ref(), mock_env(), QueryMsg::Position { position_idx: Uint128::from(1u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128::from(1u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(2000000u128), }, is_short: false, } ); // unauthorized failed; must be executed from token contract let msg = ExecuteMsg::Deposit { position_idx: Uint128::from(2u128), collateral: Asset { info: AssetInfo::Token { contract_addr: "asset0001".to_string(), }, amount: Uint128::from(1000000u128), }, }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "unauthorized"), _ => panic!("Must return unauthorized error"), } // deposit other token asset let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::Deposit { position_idx: Uint128::from(2u128), }) .unwrap(), }); let info = mock_info("asset0001", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let res = query( deps.as_ref(), mock_env(), QueryMsg::Position { position_idx: Uint128::from(2u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128::from(2u128), owner: "addr0000".to_string(), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(333333u128), }, collateral: Asset { info: AssetInfo::Token { contract_addr: "asset0001".to_string(), }, amount: Uint128::from(2000000u128), }, is_short: false, } ); } #[test] fn mint() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // open uusd-asset0000 position let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // open asset0001-asset0000 position let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { msg: to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0001", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::Deposit { position_idx: Uint128::from(1u128), collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // deposit other token asset let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::Deposit { position_idx: Uint128::from(2u128), }) .unwrap(), }); let info = mock_info("asset0001", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // failed to mint; due to min_collateral_ratio // price 100, collateral 1000000, min_collateral_ratio 150% // x * price * min_collateral_ratio < collateral // x < collateral/(price*min_collateral_ratio) = 10000 / 1.5 let msg = ExecuteMsg::Mint { position_idx: Uint128::from(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(6668u128), }, short_params: None, }; let env = mock_env_with_block_time(1000u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot mint asset over than min collateral ratio") } _ => panic!("DO NOT ENTER HERE"), } // successfully mint within the min_collateral_ratio let msg = ExecuteMsg::Mint { position_idx: Uint128::from(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(6667u128), }, short_params: None, }; let env = mock_env_with_block_time(1000u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Mint { amount: Uint128::from(6667u128), recipient: "addr0000".to_string(), }) .unwrap(), }))] ); assert_eq!( res.attributes, vec![ attr("action", "mint"), attr("position_idx", "1"), attr("mint_amount", "6667asset0000") ] ); // mint with other token; failed due to min collateral ratio let msg = ExecuteMsg::Mint { position_idx: Uint128::from(2u128), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(333334u128), }, short_params: None, }; let env = mock_env_with_block_time(1000u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot mint asset over than min collateral ratio") } _ => panic!("DO NOT ENTER HERE"), } // mint with other token; let msg = ExecuteMsg::Mint { position_idx: Uint128::from(2u128), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(333333u128), }, short_params: None, }; let env = mock_env_with_block_time(1000u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "asset0000".to_string(), msg: to_binary(&Cw20ExecuteMsg::Mint { amount: Uint128::from(333333u128), recipient: "addr0000".to_string(), }) .unwrap(), funds: vec![], }))] ); assert_eq!( res.attributes, vec![ attr("action", "mint"), attr("position_idx", "2"), attr("mint_amount", "333333asset0000") ] ); } #[test] fn burn() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), staking: "staking0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterAsset { asset_token: "asset0001".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // open uusd-asset0000 position let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time(1000); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // open asset0001-asset0000 position let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { msg: to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), }); let env = mock_env_with_block_time(1000); let info = mock_info("asset0001", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::Deposit { position_idx: Uint128::from(1u128), collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000u128), }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // deposit other token asset let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::Deposit { position_idx: Uint128::from(2u128), }) .unwrap(), }); let info = mock_info("asset0001", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Mint { position_idx: Uint128::from(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: "asset0000".to_string(), }, amount: Uint128::from(6667u128), }, short_params: None, }; let env = mock_env_with_block_time(1000u64); let info = mock_info("addr0000", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // failed to burn more than the position amount let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(13334u128), msg: to_binary(&Cw20HookMsg::Burn { position_idx: Uint128::from(1u128), }) .unwrap(), });
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
true
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/src/testing/pre_ipo_test.rs
contracts/mirror_mint/src/testing/pre_ipo_test.rs
use crate::contract::{execute, instantiate, query}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info}; use cosmwasm_std::{ attr, from_binary, to_binary, BlockInfo, Coin, CosmosMsg, Decimal, Env, StdError, SubMsg, Timestamp, Uint128, WasmMsg, }; use cw20::Cw20ReceiveMsg; use mirror_protocol::collateral_oracle::{ExecuteMsg::RegisterCollateralAsset, SourceType}; use mirror_protocol::mint::{ AssetConfigResponse, Cw20HookMsg, ExecuteMsg, IPOParams, InstantiateMsg, QueryMsg, }; use terraswap::asset::{Asset, AssetInfo}; static TOKEN_CODE_ID: u64 = 10u64; fn mock_env_with_block_time(time: u64) -> Env { let env = mock_env(); // register time Env { block: BlockInfo { height: 1, time: Timestamp::from_seconds(time), chain_id: "columbus".to_string(), }, ..env } } #[test] fn pre_ipo_assets() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"preIPOAsset0000".to_string(), &Decimal::from_ratio(10u128, 1u128), ), ]); let base_denom = "uusd".to_string(); let msg = InstantiateMsg { owner: "owner0000".to_string(), oracle: "oracle0000".to_string(), collector: "collector0000".to_string(), staking: "staking0000".to_string(), collateral_oracle: "collateraloracle0000".to_string(), terraswap_factory: "terraswap_factory".to_string(), lock: "lock0000".to_string(), base_denom, token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let creator_env = mock_env(); let creator_info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), creator_env.clone(), creator_info, msg).unwrap(); // register preIPO asset with mint_end parameter (10 blocks) let mint_end = creator_env.block.time.plus_seconds(10u64).seconds(); let msg = ExecuteMsg::RegisterAsset { asset_token: "preIPOAsset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(1000), ipo_params: Some(IPOParams { mint_end, min_collateral_ratio_after_ipo: Decimal::percent(150), pre_ipo_price: Decimal::percent(100), trigger_addr: "ipotrigger0000".to_string(), }), }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(res.messages.len(), 0); // not registered as collateral /////////////////// // Minting phase /////////////////// let mut current_time = creator_env.block.time.plus_seconds(1).seconds(); // open position successfully at creation_height + 1 let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(2000000000u128), }, asset_info: AssetInfo::Token { contract_addr: "preIPOAsset0000".to_string(), }, collateral_ratio: Decimal::percent(2000), short_params: None, }; let env = mock_env_with_block_time(current_time); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(2000000000u128), }], ); let res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "open_position"), attr("position_idx", "1"), attr("mint_amount", "100000000preIPOAsset0000"), // 2000% cr with pre_ipo_price=1 attr("collateral_amount", "2000000000uusd"), attr("is_short", "false"), ] ); // mint successfully at creation_time + 1 let msg = ExecuteMsg::Mint { position_idx: Uint128::from(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: "preIPOAsset0000".to_string(), }, amount: Uint128::from(2000000u128), }, short_params: None, }; let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // burn successfully at creation_time + 1 let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::Burn { position_idx: Uint128::from(1u128), }) .unwrap(), }); let env = mock_env_with_block_time(current_time); let info = mock_info("preIPOAsset0000", &[]); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); /////////////////// // Trading phase /////////////////// current_time = creator_env.block.time.plus_seconds(11).seconds(); // > mint_end // open position disabled let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(1000000000u128), }, asset_info: AssetInfo::Token { contract_addr: "preIPOAsset0000".to_string(), }, collateral_ratio: Decimal::percent(10000), short_params: None, }; let env = mock_env_with_block_time(current_time); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000000u128), }], ); let res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap_err(); assert_eq!( res, StdError::generic_err(format!( "The minting period for this asset ended at time {}", mint_end )) ); // mint disabled let msg = ExecuteMsg::Mint { position_idx: Uint128::from(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: "preIPOAsset0000".to_string(), }, amount: Uint128::from(2000000u128), }, short_params: None, }; let res = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert_eq!( res, StdError::generic_err(format!( "The minting period for this asset ended at time {}", mint_end )) ); // burn disabled let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::Burn { position_idx: Uint128::from(1u128), }) .unwrap(), }); let env = mock_env_with_block_time(current_time); let info = mock_info("preIPOAsset0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert_eq!( res, StdError::generic_err(format!( "Burning is disabled for assets with limitied minting time. Mint period ended at time {}", mint_end )) ); /////////////////// // IPO/Migration /////////////////// current_time = creator_env.block.time.plus_seconds(20).seconds(); // register migration initiated by the trigger address let msg = ExecuteMsg::TriggerIPO { asset_token: "preIPOAsset0000".to_string(), }; // unauthorized attempt let info = mock_info("owner", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // succesfull attempt let env = mock_env_with_block_time(current_time); let info = mock_info("ipotrigger0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "trigger_ipo"), attr("asset_token", "preIPOAsset0000"), ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "collateraloracle0000".to_string(), funds: vec![], msg: to_binary(&RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "preIPOAsset0000".to_string(), }, multiplier: Decimal::one(), price_source: SourceType::TefiOracle { oracle_addr: "oracle0000".to_string(), }, }) .unwrap(), }))] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::AssetConfig { asset_token: "preIPOAsset0000".to_string(), }, ) .unwrap(); let asset_config_res: AssetConfigResponse = from_binary(&res).unwrap(); // traditional asset configuration, price is obtained from the oracle assert_eq!( asset_config_res, AssetConfigResponse { token: "preIPOAsset0000".to_string(), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), end_price: None, ipo_params: None, } ); // open position as a postIPO asset let msg = ExecuteMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128::from(9000u128), }, asset_info: AssetInfo::Token { contract_addr: "preIPOAsset0000".to_string(), }, collateral_ratio: Decimal::percent(150), // new minCR short_params: None, }; let env = mock_env_with_block_time(1000u64); let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(9000u128), }], ); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "open_position"), attr("position_idx", "2"), attr("mint_amount", "599preIPOAsset0000"), // 150% cr with oracle_price=10 attr("collateral_amount", "9000uusd"), attr("is_short", "false"), ] ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_mint/examples/schema.rs
contracts/mirror_mint/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::mint::{ AssetConfigResponse, ConfigResponse, Cw20HookMsg, ExecuteMsg, InstantiateMsg, NextPositionIdxResponse, PositionResponse, PositionsResponse, QueryMsg, ShortParams, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(ShortParams), &out_dir); export_schema(&schema_for!(Cw20HookMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(NextPositionIdxResponse), &out_dir); export_schema(&schema_for!(AssetConfigResponse), &out_dir); export_schema(&schema_for!(PositionResponse), &out_dir); export_schema(&schema_for!(PositionsResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/contract.rs
contracts/mirror_collateral_oracle/src/contract.rs
use crate::migration::{migrate_collateral_infos, migrate_config}; use crate::querier::query_price; use crate::state::{ read_collateral_info, read_collateral_infos, read_config, store_collateral_info, store_config, CollateralAssetInfo, Config, }; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ to_binary, Binary, CanonicalAddr, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, }; use mirror_protocol::collateral_oracle::{ CollateralInfoResponse, CollateralInfosResponse, CollateralPriceResponse, ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, SourceType, }; use terraswap::asset::AssetInfo; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { store_config( deps.storage, &Config { owner: deps.api.addr_canonicalize(&msg.owner)?, mint_contract: deps.api.addr_canonicalize(&msg.mint_contract)?, base_denom: msg.base_denom, }, )?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, _env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> StdResult<Response> { match msg { ExecuteMsg::UpdateConfig { owner, mint_contract, base_denom, } => update_config(deps, info, owner, mint_contract, base_denom), ExecuteMsg::RegisterCollateralAsset { asset, price_source, multiplier, } => register_collateral(deps, info, asset, price_source, multiplier), ExecuteMsg::RevokeCollateralAsset { asset } => revoke_collateral(deps, info, asset), ExecuteMsg::UpdateCollateralPriceSource { asset, price_source, } => update_collateral_source(deps, info, asset, price_source), ExecuteMsg::UpdateCollateralMultiplier { asset, multiplier } => { update_collateral_multiplier(deps, info, asset, multiplier) } } } #[allow(clippy::too_many_arguments)] pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, mint_contract: Option<String>, base_denom: Option<String>, ) -> StdResult<Response> { let mut config: Config = read_config(deps.storage)?; if deps.api.addr_canonicalize(info.sender.as_str())? != config.owner { return Err(StdError::generic_err("unauthorized")); } if let Some(owner) = owner { config.owner = deps.api.addr_canonicalize(&owner)?; } if let Some(mint_contract) = mint_contract { config.mint_contract = deps.api.addr_canonicalize(&mint_contract)?; } if let Some(base_denom) = base_denom { config.base_denom = base_denom; } store_config(deps.storage, &config)?; Ok(Response::default()) } pub fn register_collateral( deps: DepsMut, info: MessageInfo, asset: AssetInfo, price_source: SourceType, multiplier: Decimal, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_address_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; // only contract onwner and mint contract can register a new collateral if config.owner != sender_address_raw && config.mint_contract != sender_address_raw { return Err(StdError::generic_err("unauthorized")); } if read_collateral_info(deps.storage, &asset.to_string()).is_ok() { return Err(StdError::generic_err("Collateral was already registered")); } if multiplier.is_zero() { return Err(StdError::generic_err("Multiplier must be bigger than 0")); } store_collateral_info( deps.storage, &CollateralAssetInfo { asset: asset.to_string(), multiplier, price_source, is_revoked: false, }, )?; Ok(Response::default()) } pub fn revoke_collateral( deps: DepsMut, info: MessageInfo, asset: AssetInfo, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_address_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; // only owner and mint contract can revoke a collateral assets if config.owner != sender_address_raw && config.mint_contract != sender_address_raw { return Err(StdError::generic_err("unauthorized")); } let mut collateral_info: CollateralAssetInfo = if let Ok(collateral) = read_collateral_info(deps.storage, &asset.to_string()) { collateral } else { return Err(StdError::generic_err("Collateral not found")); }; collateral_info.is_revoked = true; store_collateral_info(deps.storage, &collateral_info)?; Ok(Response::default()) } pub fn update_collateral_source( deps: DepsMut, info: MessageInfo, asset: AssetInfo, price_source: SourceType, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_address_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; // only contract onwner can update collateral query if config.owner != sender_address_raw { return Err(StdError::generic_err("unauthorized")); } let mut collateral_info: CollateralAssetInfo = if let Ok(collateral) = read_collateral_info(deps.storage, &asset.to_string()) { collateral } else { return Err(StdError::generic_err("Collateral not found")); }; collateral_info.price_source = price_source; store_collateral_info(deps.storage, &collateral_info)?; Ok(Response::default()) } pub fn update_collateral_multiplier( deps: DepsMut, info: MessageInfo, asset: AssetInfo, multiplier: Decimal, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_address_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; // only factory contract can update collateral premium if config.owner != sender_address_raw { return Err(StdError::generic_err("unauthorized")); } let mut collateral_info: CollateralAssetInfo = if let Ok(collateral) = read_collateral_info(deps.storage, &asset.to_string()) { collateral } else { return Err(StdError::generic_err("Collateral not found")); }; if multiplier.is_zero() { return Err(StdError::generic_err("Multiplier must be bigger than 0")); } collateral_info.multiplier = multiplier; store_collateral_info(deps.storage, &collateral_info)?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), QueryMsg::CollateralPrice { asset, timeframe } => { to_binary(&query_collateral_price(deps, env, asset, timeframe)?) } QueryMsg::CollateralAssetInfo { asset } => to_binary(&query_collateral_info(deps, asset)?), QueryMsg::CollateralAssetInfos {} => to_binary(&query_collateral_infos(deps)?), } } pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let config = read_config(deps.storage)?; let resp = ConfigResponse { owner: deps.api.addr_humanize(&config.owner)?.to_string(), mint_contract: deps.api.addr_humanize(&config.mint_contract)?.to_string(), base_denom: config.base_denom, }; Ok(resp) } pub fn query_collateral_price( deps: Deps, env: Env, quote_asset: String, timeframe: Option<u64>, ) -> StdResult<CollateralPriceResponse> { let config: Config = read_config(deps.storage)?; let collateral: CollateralAssetInfo = if let Ok(res) = read_collateral_info(deps.storage, &quote_asset) { res } else { return Err(StdError::generic_err("Collateral asset not found")); }; let (price, last_updated): (Decimal, u64) = query_price( deps, env, &config, &quote_asset, timeframe, &collateral.price_source, )?; Ok(CollateralPriceResponse { asset: collateral.asset, rate: price, last_updated, multiplier: collateral.multiplier, is_revoked: collateral.is_revoked, }) } pub fn query_collateral_info(deps: Deps, quote_asset: String) -> StdResult<CollateralInfoResponse> { let collateral: CollateralAssetInfo = if let Ok(res) = read_collateral_info(deps.storage, &quote_asset) { res } else { return Err(StdError::generic_err("Collateral asset not found")); }; Ok(CollateralInfoResponse { asset: collateral.asset, source_type: collateral.price_source.to_string(), multiplier: collateral.multiplier, is_revoked: collateral.is_revoked, }) } pub fn query_collateral_infos(deps: Deps) -> StdResult<CollateralInfosResponse> { let infos: Vec<CollateralInfoResponse> = read_collateral_infos(deps.storage)?; Ok(CollateralInfosResponse { collaterals: infos }) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> StdResult<Response> { migrate_config(deps.storage)?; deps.api.addr_validate(&msg.mirror_tefi_oracle_addr)?; migrate_collateral_infos(deps.storage, msg.mirror_tefi_oracle_addr)?; Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/lib.rs
contracts/mirror_collateral_oracle/src/lib.rs
pub mod contract; pub mod math; pub mod migration; pub mod querier; pub mod state; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/math.rs
contracts/mirror_collateral_oracle/src/math.rs
use cosmwasm_std::{Decimal, Uint128}; const DECIMAL_FRACTIONAL: Uint128 = Uint128::new(1_000_000_000u128); /// return a / b pub fn decimal_division(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio(DECIMAL_FRACTIONAL * a, b * DECIMAL_FRACTIONAL) } pub fn decimal_multiplication(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio(a * DECIMAL_FRACTIONAL * b, DECIMAL_FRACTIONAL) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/state.rs
contracts/mirror_collateral_oracle/src/state.rs
use cosmwasm_std::{CanonicalAddr, Decimal, Order, StdResult, Storage}; use cosmwasm_storage::{singleton, singleton_read, Bucket, ReadonlyBucket}; use mirror_protocol::collateral_oracle::{CollateralInfoResponse, SourceType}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; pub static PREFIX_COLLATERAL_ASSET_INFO: &[u8] = b"collateral_asset_info"; pub static KEY_CONFIG: &[u8] = b"config"; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub mint_contract: CanonicalAddr, pub base_denom: String, } pub fn store_config(storage: &mut dyn Storage, config: &Config) -> StdResult<()> { singleton(storage, KEY_CONFIG).save(config) } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, KEY_CONFIG).load() } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct CollateralAssetInfo { pub asset: String, pub price_source: SourceType, pub multiplier: Decimal, pub is_revoked: bool, } pub fn store_collateral_info( storage: &mut dyn Storage, collateral: &CollateralAssetInfo, ) -> StdResult<()> { let mut collaterals_bucket: Bucket<CollateralAssetInfo> = Bucket::new(storage, PREFIX_COLLATERAL_ASSET_INFO); collaterals_bucket.save(collateral.asset.as_bytes(), collateral) } #[allow(clippy::ptr_arg)] pub fn read_collateral_info(storage: &dyn Storage, id: &String) -> StdResult<CollateralAssetInfo> { let price_bucket: ReadonlyBucket<CollateralAssetInfo> = ReadonlyBucket::new(storage, PREFIX_COLLATERAL_ASSET_INFO); price_bucket.load(id.as_bytes()) } pub fn read_collateral_infos(storage: &dyn Storage) -> StdResult<Vec<CollateralInfoResponse>> { let price_bucket: ReadonlyBucket<CollateralAssetInfo> = ReadonlyBucket::new(storage, PREFIX_COLLATERAL_ASSET_INFO); price_bucket .range(None, None, Order::Ascending) .map(|item| { let (_, v) = item?; Ok(CollateralInfoResponse { asset: v.asset, source_type: v.price_source.to_string(), multiplier: v.multiplier, is_revoked: v.is_revoked, }) }) .collect() }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/querier.rs
contracts/mirror_collateral_oracle/src/querier.rs
use crate::math::decimal_multiplication; use crate::state::Config; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::{ to_binary, Addr, Decimal, Deps, Env, QuerierWrapper, QueryRequest, StdError, StdResult, Timestamp, Uint128, WasmQuery, }; use mirror_protocol::collateral_oracle::SourceType; use serde::{Deserialize, Serialize}; use tefi_oracle::hub::{ HubQueryMsg as TeFiOracleQueryMsg, PriceResponse as TeFiOraclePriceResponse, }; use terra_cosmwasm::{ExchangeRatesResponse, TerraQuerier}; use terraswap::asset::{Asset, AssetInfo}; use terraswap::pair::QueryMsg as AMMPairQueryMsg; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(rename_all = "snake_case")] pub enum SourceQueryMsg { // Query message for terraswap pool Pool {}, // Query message for anchor market EpochState { block_height: Option<u64>, distributed_interest: Option<Uint256>, }, // Query message for lunax State {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct AMMPairResponse { // queries return pool assets pub assets: [Asset; 2], } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct AnchorMarketResponse { // anchor market queries return exchange rate in Decimal256 pub exchange_rate: Decimal256, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct LunaxState { pub total_staked: Uint128, pub exchange_rate: Decimal, pub last_reconciled_batch_id: u64, pub current_undelegation_batch_id: u64, pub last_undelegation_time: Timestamp, pub last_swap_time: Timestamp, pub last_reinvest_time: Timestamp, pub validators: Vec<Addr>, pub reconciled_funds_to_withdraw: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct LunaxStateResponse { pub state: LunaxState, } #[allow(clippy::ptr_arg)] pub fn query_price( deps: Deps, env: Env, config: &Config, asset: &String, timeframe: Option<u64>, price_source: &SourceType, ) -> StdResult<(Decimal, u64)> { match price_source { SourceType::FixedPrice { price } => Ok((*price, u64::MAX)), SourceType::TefiOracle { oracle_addr } => { let res: TeFiOraclePriceResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: oracle_addr.to_string(), msg: to_binary(&TeFiOracleQueryMsg::Price { asset_token: asset.to_string(), timeframe, }) .unwrap(), }))?; Ok((res.rate, res.last_updated)) } SourceType::AmmPair { pair_addr, intermediate_denom, } => { let res: AMMPairResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: pair_addr.to_string(), msg: to_binary(&AMMPairQueryMsg::Pool {}).unwrap(), }))?; let assets: [Asset; 2] = res.assets; // query intermediate denom if it exists let query_denom: String = match intermediate_denom.clone() { Some(v) => v, None => config.base_denom.clone(), }; let queried_rate: Decimal = if assets[0].info.equal(&AssetInfo::NativeToken { denom: query_denom.clone(), }) { Decimal::from_ratio(assets[0].amount, assets[1].amount) } else if assets[1].info.equal(&AssetInfo::NativeToken { denom: query_denom.clone(), }) { Decimal::from_ratio(assets[1].amount, assets[0].amount) } else { return Err(StdError::generic_err("Invalid pool")); }; // if intermediate denom exists, calculate final rate let rate: Decimal = if intermediate_denom.is_some() { // (query_denom / intermediate_denom) * (intermedaite_denom / base_denom) = (query_denom / base_denom) let native_rate: Decimal = query_native_rate(&deps.querier, query_denom, config.base_denom.clone())?; decimal_multiplication(queried_rate, native_rate) } else { queried_rate }; Ok((rate, u64::MAX)) } SourceType::AnchorMarket { anchor_market_addr } => { let res: AnchorMarketResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: anchor_market_addr.to_string(), msg: to_binary(&SourceQueryMsg::EpochState { block_height: Some(env.block.height), distributed_interest: None, }) .unwrap(), }))?; let rate: Decimal = res.exchange_rate.into(); Ok((rate, u64::MAX)) } SourceType::Lunax { staking_contract_addr, } => { let res: LunaxStateResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: staking_contract_addr.to_string(), msg: to_binary(&SourceQueryMsg::State {}).unwrap(), }))?; // get lunax price in ust let luna_ust_price: Decimal = query_native_rate( &deps.querier, "uluna".to_string(), config.base_denom.clone(), )?; let rate = decimal_multiplication(res.state.exchange_rate, luna_ust_price); Ok((rate, u64::MAX)) } SourceType::Native { native_denom } => { let rate: Decimal = query_native_rate( &deps.querier, native_denom.clone(), config.base_denom.clone(), )?; Ok((rate, u64::MAX)) } } } fn query_native_rate( querier: &QuerierWrapper, base_denom: String, quote_denom: String, ) -> StdResult<Decimal> { let terra_querier = TerraQuerier::new(querier); let res: ExchangeRatesResponse = terra_querier.query_exchange_rates(base_denom, vec![quote_denom])?; Ok(res.exchange_rates[0].exchange_rate) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/migration.rs
contracts/mirror_collateral_oracle/src/migration.rs
use cosmwasm_storage::{singleton, singleton_read, Bucket, ReadonlySingleton, Singleton}; use mirror_protocol::collateral_oracle::SourceType; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, Decimal, Order, StdError, StdResult, Storage}; use crate::state::{CollateralAssetInfo, Config, KEY_CONFIG, PREFIX_COLLATERAL_ASSET_INFO}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyConfig { pub owner: CanonicalAddr, pub mint_contract: CanonicalAddr, pub base_denom: String, pub mirror_oracle: CanonicalAddr, pub anchor_oracle: CanonicalAddr, pub band_oracle: CanonicalAddr, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyCollateralAssetInfo { pub asset: String, pub price_source: LegacySourceType, pub multiplier: Decimal, pub is_revoked: bool, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum LegacySourceType { MirrorOracle {}, AnchorOracle {}, BandOracle {}, FixedPrice { price: Decimal, }, Terraswap { terraswap_pair_addr: String, intermediate_denom: Option<String>, }, AnchorMarket { anchor_market_addr: String, }, Native { native_denom: String, }, Lunax { staking_contract_addr: String, }, } pub fn migrate_config(storage: &mut dyn Storage) -> StdResult<()> { let legacty_store: ReadonlySingleton<LegacyConfig> = singleton_read(storage, KEY_CONFIG); let legacy_config: LegacyConfig = legacty_store.load()?; let config = Config { owner: legacy_config.owner, mint_contract: legacy_config.mint_contract, base_denom: legacy_config.base_denom, }; let mut store: Singleton<Config> = singleton(storage, KEY_CONFIG); store.save(&config)?; Ok(()) } pub fn migrate_collateral_infos( storage: &mut dyn Storage, mirror_tefi_oracle_addr: String, ) -> StdResult<()> { let mut legacy_collateral_infos_bucket: Bucket<LegacyCollateralAssetInfo> = Bucket::new(storage, PREFIX_COLLATERAL_ASSET_INFO); let mut collateral_infos: Vec<(String, LegacyCollateralAssetInfo)> = vec![]; for item in legacy_collateral_infos_bucket.range(None, None, Order::Ascending) { let (k, p) = item?; collateral_infos.push((String::from_utf8(k)?, p)); } for (asset, _) in collateral_infos.clone().into_iter() { legacy_collateral_infos_bucket.remove(asset.as_bytes()); } let mut new_pool_infos_bucket: Bucket<CollateralAssetInfo> = Bucket::new(storage, PREFIX_COLLATERAL_ASSET_INFO); for (_, legacy_collateral_info) in collateral_infos.into_iter() { let new_price_source: SourceType = match legacy_collateral_info.price_source { LegacySourceType::BandOracle { .. } => { return Err(StdError::generic_err("not supported")) } // currently there are no assets with this config LegacySourceType::AnchorOracle { .. } => SourceType::TefiOracle { oracle_addr: mirror_tefi_oracle_addr.clone(), }, LegacySourceType::MirrorOracle { .. } => SourceType::TefiOracle { oracle_addr: mirror_tefi_oracle_addr.clone(), }, LegacySourceType::AnchorMarket { anchor_market_addr } => { SourceType::AnchorMarket { anchor_market_addr } } LegacySourceType::FixedPrice { price } => SourceType::FixedPrice { price }, LegacySourceType::Native { native_denom } => SourceType::Native { native_denom }, LegacySourceType::Terraswap { terraswap_pair_addr, intermediate_denom, } => SourceType::AmmPair { pair_addr: terraswap_pair_addr, intermediate_denom, }, LegacySourceType::Lunax { staking_contract_addr, } => SourceType::Lunax { staking_contract_addr, }, }; let new_collateral_info = &CollateralAssetInfo { asset: legacy_collateral_info.asset, multiplier: legacy_collateral_info.multiplier, price_source: new_price_source, is_revoked: legacy_collateral_info.is_revoked, }; new_pool_infos_bucket.save(new_collateral_info.asset.as_bytes(), new_collateral_info)?; } Ok(()) } #[cfg(test)] mod migrate_tests { use crate::state::read_collateral_info; use super::*; use cosmwasm_std::testing::mock_dependencies; pub fn collateral_infos_old_store( storage: &mut dyn Storage, ) -> Bucket<LegacyCollateralAssetInfo> { Bucket::new(storage, PREFIX_COLLATERAL_ASSET_INFO) } #[test] fn test_collateral_infos_migration() { let mut deps = mock_dependencies(&[]); let mut legacy_store = collateral_infos_old_store(&mut deps.storage); let col_info_1 = LegacyCollateralAssetInfo { asset: "mAPPL0000".to_string(), multiplier: Decimal::one(), price_source: LegacySourceType::MirrorOracle {}, is_revoked: false, }; let col_info_2 = LegacyCollateralAssetInfo { asset: "anc0000".to_string(), multiplier: Decimal::one(), price_source: LegacySourceType::Terraswap { terraswap_pair_addr: "pair0000".to_string(), intermediate_denom: None, }, is_revoked: false, }; let col_info_3 = LegacyCollateralAssetInfo { asset: "bluna0000".to_string(), multiplier: Decimal::one(), price_source: LegacySourceType::AnchorOracle {}, is_revoked: false, }; legacy_store .save(col_info_1.asset.as_bytes(), &col_info_1) .unwrap(); legacy_store .save(col_info_2.asset.as_bytes(), &col_info_2) .unwrap(); legacy_store .save(col_info_3.asset.as_bytes(), &col_info_3) .unwrap(); migrate_collateral_infos(deps.as_mut().storage, "mirrortefi0000".to_string()).unwrap(); let new_col_info_1: CollateralAssetInfo = read_collateral_info(deps.as_mut().storage, &col_info_1.asset).unwrap(); let new_col_info_2: CollateralAssetInfo = read_collateral_info(deps.as_mut().storage, &col_info_2.asset).unwrap(); let new_col_info_3: CollateralAssetInfo = read_collateral_info(deps.as_mut().storage, &col_info_3.asset).unwrap(); assert_eq!( new_col_info_1, CollateralAssetInfo { asset: "mAPPL0000".to_string(), multiplier: Decimal::one(), price_source: SourceType::TefiOracle { oracle_addr: "mirrortefi0000".to_string(), }, is_revoked: false, } ); assert_eq!( new_col_info_2, CollateralAssetInfo { asset: "anc0000".to_string(), multiplier: Decimal::one(), price_source: SourceType::AmmPair { pair_addr: "pair0000".to_string(), intermediate_denom: None, }, is_revoked: false, } ); assert_eq!( new_col_info_3, CollateralAssetInfo { asset: "bluna0000".to_string(), multiplier: Decimal::one(), price_source: SourceType::TefiOracle { oracle_addr: "mirrortefi0000".to_string(), }, is_revoked: false, } ) } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/testing/tests.rs
contracts/mirror_collateral_oracle/src/testing/tests.rs
use crate::contract::{ execute, instantiate, query_collateral_info, query_collateral_price, query_config, }; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info}; use cosmwasm_std::{Decimal, StdError, Uint128}; use mirror_protocol::collateral_oracle::{ CollateralInfoResponse, CollateralPriceResponse, ExecuteMsg, InstantiateMsg, SourceType, }; use terraswap::asset::AssetInfo; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // it worked, let's query the state let value = query_config(deps.as_ref()).unwrap(); assert_eq!("owner0000", value.owner.as_str()); assert_eq!("mint0000", value.mint_contract.as_str()); assert_eq!("uusd", value.base_denom.as_str()); } #[test] fn update_config() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // update owner let info = mock_info("owner0000", &[]); let msg = ExecuteMsg::UpdateConfig { owner: Some("owner0001".to_string()), mint_contract: Some("mint0001".to_string()), base_denom: Some("uluna".to_string()), }; let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // it worked, let's query the state let value = query_config(deps.as_ref()).unwrap(); assert_eq!("owner0001", value.owner.as_str()); assert_eq!("mint0001", value.mint_contract.as_str()); assert_eq!("uluna", value.base_denom.as_str()); // Unauthorized err let info = mock_info("owner0000", &[]); let msg = ExecuteMsg::UpdateConfig { owner: None, mint_contract: None, base_denom: None, }; let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"), _ => panic!("Must return unauthorized error"), } } #[test] fn register_collateral() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"mTSLA".to_string(), &Decimal::percent(100)), ]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "mTSLA".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::TefiOracle { oracle_addr: "mirrorOracle0000".to_string(), }, }; // unauthorized attempt let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // query collateral info let query_res = query_collateral_info(deps.as_ref(), "mTSLA".to_string()).unwrap(); assert_eq!( query_res, CollateralInfoResponse { asset: "mTSLA".to_string(), source_type: "tefi_oracle".to_string(), multiplier: Decimal::percent(100), is_revoked: false, } ) } #[test] fn update_collateral() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"mTSLA".to_string(), &Decimal::percent(100)), ]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "mTSLA".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::TefiOracle { oracle_addr: "mirrorOracle0000".to_string(), }, }; // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // query collateral info let query_res = query_collateral_info(deps.as_ref(), "mTSLA".to_string()).unwrap(); assert_eq!( query_res, CollateralInfoResponse { asset: "mTSLA".to_string(), source_type: "tefi_oracle".to_string(), multiplier: Decimal::percent(100), is_revoked: false, } ); // update collateral query let msg = ExecuteMsg::UpdateCollateralPriceSource { asset: AssetInfo::Token { contract_addr: "mTSLA".to_string(), }, price_source: SourceType::FixedPrice { price: Decimal::zero(), }, }; // unauthorized attempt let info = mock_info("factory0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // query the updated collateral let query_res = query_collateral_info(deps.as_ref(), "mTSLA".to_string()).unwrap(); assert_eq!( query_res, CollateralInfoResponse { asset: "mTSLA".to_string(), source_type: "fixed_price".to_string(), multiplier: Decimal::percent(100), is_revoked: false, } ); // update collateral premium - invalid msg let msg = ExecuteMsg::UpdateCollateralMultiplier { asset: AssetInfo::Token { contract_addr: "mTSLA".to_string(), }, multiplier: Decimal::zero(), }; // invalid multiplier let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); assert_eq!( res, StdError::generic_err("Multiplier must be bigger than 0") ); // update collateral premium - valid msg let msg = ExecuteMsg::UpdateCollateralMultiplier { asset: AssetInfo::Token { contract_addr: "mTSLA".to_string(), }, multiplier: Decimal::percent(120), }; // unauthorized attempt let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // query the updated collateral let query_res = query_collateral_info(deps.as_ref(), "mTSLA".to_string()).unwrap(); assert_eq!( query_res, CollateralInfoResponse { asset: "mTSLA".to_string(), source_type: "fixed_price".to_string(), multiplier: Decimal::percent(120), is_revoked: false, } ) } #[test] fn get_oracle_price() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"mTSLA".to_string(), &Decimal::percent(100)), ]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "mTSLA".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::TefiOracle { oracle_addr: "mirrorOracle0000".to_string(), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "mTSLA".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "mTSLA".to_string(), rate: Decimal::percent(100), last_updated: 1000u64, multiplier: Decimal::percent(100), is_revoked: false, } ); } #[test] fn get_amm_pair_price() { let mut deps = mock_dependencies(&[]); deps.querier.with_terraswap_pools(&[ ( &"ustancpair0000".to_string(), ( &"uusd".to_string(), &Uint128::from(1u128), &"anc0000".to_string(), &Uint128::from(100u128), ), ), ( &"lunablunapair0000".to_string(), ( &"uluna".to_string(), &Uint128::from(18u128), &"bluna0000".to_string(), &Uint128::from(2u128), ), ), ]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "anc0000".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::AmmPair { pair_addr: "ustancpair0000".to_string(), intermediate_denom: None, }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "anc0000".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "anc0000".to_string(), rate: Decimal::from_ratio(1u128, 100u128), last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); // register collateral with intermediate denom let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "bluna0000".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::AmmPair { pair_addr: "lunablunapair0000".to_string(), intermediate_denom: Some("uluna".to_string()), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "bluna0000".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "bluna0000".to_string(), rate: Decimal::from_ratio(45u128, 1u128), // 9 / 1 * 5 / 1 last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); } #[test] fn get_fixed_price() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "aUST".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::FixedPrice { price: Decimal::from_ratio(1u128, 2u128), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "aUST".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "aUST".to_string(), rate: Decimal::from_ratio(1u128, 2u128), last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); } #[test] fn get_anchor_market_price() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "aust0000".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::AnchorMarket { anchor_market_addr: "anchormarket0000".to_string(), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "aust0000".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "aust0000".to_string(), rate: Decimal::from_ratio(10u128, 3u128), last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); } #[test] fn get_lunax_price() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "lunax0000".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::Lunax { staking_contract_addr: "lunaxstaking0000".to_string(), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "lunax0000".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "lunax0000".to_string(), rate: Decimal::from_ratio(55u128, 10u128), // exchange rate = 1.1 i.e 1 ulunax = 1.1 uluna and 1 uluna = 5 uusd last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); } #[test] fn get_native_price() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::NativeToken { denom: "uluna".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::Native { native_denom: "uluna".to_string(), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "uluna".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "uluna".to_string(), rate: Decimal::from_ratio(5u128, 1u128), last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); } #[test] fn revoke_collateral() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::RegisterCollateralAsset { asset: AssetInfo::Token { contract_addr: "aUST".to_string(), }, multiplier: Decimal::percent(100), price_source: SourceType::FixedPrice { price: Decimal::one(), }, }; let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // attempt to query price let query_res = query_collateral_price(deps.as_ref(), mock_env(), "aUST".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "aUST".to_string(), rate: Decimal::one(), last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: false, } ); // revoke the asset let msg = ExecuteMsg::RevokeCollateralAsset { asset: AssetInfo::Token { contract_addr: "aUST".to_string(), }, }; // unauthorized attempt let info = mock_info("factory0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // query the revoked collateral let query_res = query_collateral_info(deps.as_ref(), "aUST".to_string()).unwrap(); assert_eq!( query_res, CollateralInfoResponse { asset: "aUST".to_string(), source_type: "fixed_price".to_string(), multiplier: Decimal::percent(100), is_revoked: true, } ); // attempt to query price of revoked asset let query_res = query_collateral_price(deps.as_ref(), mock_env(), "aUST".to_string(), None).unwrap(); assert_eq!( query_res, CollateralPriceResponse { asset: "aUST".to_string(), rate: Decimal::one(), last_updated: u64::MAX, multiplier: Decimal::percent(100), is_revoked: true, } ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/testing/mock_querier.rs
contracts/mirror_collateral_oracle/src/testing/mock_querier.rs
use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, from_slice, to_binary, Addr, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Timestamp, Uint128, WasmQuery, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::str::FromStr; use tefi_oracle::hub::PriceResponse as TeFiOraclePriceResponse; use terra_cosmwasm::{ ExchangeRateItem, ExchangeRatesResponse, TerraQuery, TerraQueryWrapper, TerraRoute, }; use terraswap::asset::{Asset, AssetInfo}; use terraswap::pair::PoolResponse; /// mock_dependencies is a drop-in replacement for cosmwasm_std::testing::mock_dependencies /// this uses our CustomQuerier. pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new(MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)])); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<TerraQueryWrapper>, oracle_price_querier: OraclePriceQuerier, terraswap_pools_querier: TerraswapPoolsQuerier, } #[derive(Clone, Default)] pub struct OraclePriceQuerier { // this lets us iterate over all pairs that match the first string oracle_price: HashMap<String, Decimal>, } impl OraclePriceQuerier { pub fn new(oracle_price: &[(&String, &Decimal)]) -> Self { OraclePriceQuerier { oracle_price: oracle_price_to_map(oracle_price), } } } pub(crate) fn oracle_price_to_map( oracle_price: &[(&String, &Decimal)], ) -> HashMap<String, Decimal> { let mut oracle_price_map: HashMap<String, Decimal> = HashMap::new(); for (base_quote, oracle_price) in oracle_price.iter() { oracle_price_map.insert((*base_quote).clone(), **oracle_price); } oracle_price_map } #[derive(Clone, Default)] pub struct TerraswapPoolsQuerier { pools: HashMap<String, (String, Uint128, String, Uint128)>, } impl TerraswapPoolsQuerier { #[allow(clippy::type_complexity)] pub fn new(pools: &[(&String, (&String, &Uint128, &String, &Uint128))]) -> Self { TerraswapPoolsQuerier { pools: pools_to_map(pools), } } } #[allow(clippy::type_complexity)] pub(crate) fn pools_to_map( pools: &[(&String, (&String, &Uint128, &String, &Uint128))], ) -> HashMap<String, (String, Uint128, String, Uint128)> { let mut pools_map: HashMap<String, (String, Uint128, String, Uint128)> = HashMap::new(); for (key, pool) in pools.iter() { pools_map.insert( key.to_string(), (pool.0.clone(), *pool.1, pool.2.clone(), *pool.3), ); } pools_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<TerraQueryWrapper> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct EpochStateResponse { exchange_rate: Decimal256, aterra_supply: Uint256, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct LunaxState { pub total_staked: Uint128, pub exchange_rate: Decimal, pub last_reconciled_batch_id: u64, pub current_undelegation_batch_id: u64, pub last_undelegation_time: Timestamp, pub last_swap_time: Timestamp, pub last_reinvest_time: Timestamp, pub validators: Vec<Addr>, pub reconciled_funds_to_withdraw: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct LunaxStateResponse { pub state: LunaxState, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Price { asset_token: String, timeframe: Option<u64>, }, Pool {}, EpochState { block_heigth: Option<u64>, distributed_interest: Option<Uint256>, }, State {}, } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<TerraQueryWrapper>) -> QuerierResult { match &request { QueryRequest::Custom(TerraQueryWrapper { route, query_data }) => { if &TerraRoute::Oracle == route { match query_data { TerraQuery::ExchangeRates { base_denom: _, quote_denoms: _, } => { let res = ExchangeRatesResponse { exchange_rates: vec![ExchangeRateItem { quote_denom: "uusd".to_string(), exchange_rate: Decimal::from_ratio(5u128, 1u128), }], base_denom: "uluna".to_string(), }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } _ => panic!("DO NOT ENTER HERE"), } } else { panic!("DO NOT ENTER HERE") } } QueryRequest::Wasm(WasmQuery::Smart { contract_addr, msg }) => match from_binary(msg) .unwrap() { QueryMsg::Price { asset_token, timeframe: _, } => match self.oracle_price_querier.oracle_price.get(&asset_token) { Some(base_price) => SystemResult::Ok(ContractResult::from(to_binary( &TeFiOraclePriceResponse { rate: *base_price, last_updated: 1000u64, }, ))), None => SystemResult::Err(SystemError::InvalidRequest { error: "No oracle price exists".to_string(), request: msg.as_slice().into(), }), }, QueryMsg::Pool {} => match self.terraswap_pools_querier.pools.get(contract_addr) { Some(v) => SystemResult::Ok(ContractResult::from(to_binary(&PoolResponse { assets: [ Asset { amount: v.1, info: AssetInfo::NativeToken { denom: v.0.clone() }, }, Asset { amount: v.3, info: AssetInfo::Token { contract_addr: v.2.to_string(), }, }, ], total_share: Uint128::zero(), }))), None => SystemResult::Err(SystemError::InvalidRequest { error: "No pair info exists".to_string(), request: msg.as_slice().into(), }), }, QueryMsg::EpochState { .. } => { SystemResult::Ok(ContractResult::from(to_binary(&EpochStateResponse { exchange_rate: Decimal256::from_ratio(10, 3), aterra_supply: Uint256::from_str("123123123").unwrap(), }))) } QueryMsg::State {} => { SystemResult::Ok(ContractResult::from(to_binary(&LunaxStateResponse { state: LunaxState { total_staked: Uint128::new(10000000), exchange_rate: Decimal::from_ratio(11_u128, 10_u128), // 1 lunax = 1.1 luna last_reconciled_batch_id: 1, current_undelegation_batch_id: 3, last_undelegation_time: Timestamp::from_seconds(1642932518), last_swap_time: Timestamp::from_seconds(1643116118), last_reinvest_time: Timestamp::from_seconds(1643105318), validators: vec![ Addr::unchecked("valid0001"), Addr::unchecked("valid0002"), Addr::unchecked("valid0003"), ], reconciled_funds_to_withdraw: Uint128::new(150_u128), }, }))) } }, _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new(base: MockQuerier<TerraQueryWrapper>) -> Self { WasmMockQuerier { base, oracle_price_querier: OraclePriceQuerier::default(), terraswap_pools_querier: TerraswapPoolsQuerier::default(), } } // configure the oracle price mock querier pub fn with_oracle_price(&mut self, oracle_price: &[(&String, &Decimal)]) { self.oracle_price_querier = OraclePriceQuerier::new(oracle_price); } #[allow(clippy::type_complexity)] pub fn with_terraswap_pools( &mut self, pairs: &[(&String, (&String, &Uint128, &String, &Uint128))], ) { self.terraswap_pools_querier = TerraswapPoolsQuerier::new(pairs); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/src/testing/mod.rs
contracts/mirror_collateral_oracle/src/testing/mod.rs
mod mock_querier; mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collateral_oracle/examples/schema.rs
contracts/mirror_collateral_oracle/examples/schema.rs
use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::collateral_oracle::{ CollateralInfoResponse, CollateralInfosResponse, CollateralPriceResponse, ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, }; use std::env::current_dir; use std::fs::create_dir_all; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(MigrateMsg), &out_dir); export_schema(&schema_for!(CollateralInfoResponse), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(CollateralInfosResponse), &out_dir); export_schema(&schema_for!(CollateralPriceResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_community/src/contract.rs
contracts/mirror_community/src/contract.rs
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use crate::state::{read_config, store_config, Config}; use cosmwasm_std::{ attr, to_binary, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, }; use mirror_protocol::community::{ ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, }; use cw20::Cw20ExecuteMsg; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { store_config( deps.storage, &Config { owner: deps.api.addr_canonicalize(&msg.owner)?, mirror_token: deps.api.addr_canonicalize(&msg.mirror_token)?, spend_limit: msg.spend_limit, }, )?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, _env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> StdResult<Response> { match msg { ExecuteMsg::UpdateConfig { owner, spend_limit } => { udpate_config(deps, info, owner, spend_limit) } ExecuteMsg::Spend { recipient, amount } => spend(deps, info, recipient, amount), } } pub fn udpate_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, spend_limit: Option<Uint128>, ) -> StdResult<Response> { let mut config: Config = read_config(deps.storage)?; if config.owner != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } if let Some(owner) = owner { config.owner = deps.api.addr_canonicalize(&owner)?; } if let Some(spend_limit) = spend_limit { config.spend_limit = spend_limit; } store_config(deps.storage, &config)?; Ok(Response::new().add_attributes(vec![attr("action", "update_config")])) } /// Spend /// Owner can execute spend operation to send /// `amount` of MIR token to `recipient` for community purpose pub fn spend( deps: DepsMut, info: MessageInfo, recipient: String, amount: Uint128, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; if config.owner != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } if config.spend_limit < amount { return Err(StdError::generic_err("Cannot spend more than spend_limit")); } let mirror_token = deps.api.addr_humanize(&config.mirror_token)?.to_string(); Ok(Response::new() .add_message(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: mirror_token, funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: recipient.clone(), amount, })?, })) .add_attributes(vec![ attr("action", "spend"), attr("recipient", recipient), attr("amount", amount), ])) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), } } pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let state = read_config(deps.storage)?; let resp = ConfigResponse { owner: deps.api.addr_humanize(&state.owner)?.to_string(), mirror_token: deps.api.addr_humanize(&state.mirror_token)?.to_string(), spend_limit: state.spend_limit, }; Ok(resp) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> { Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_community/src/lib.rs
contracts/mirror_community/src/lib.rs
pub mod contract; pub mod state; #[cfg(test)] mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_community/src/tests.rs
contracts/mirror_community/src/tests.rs
use crate::contract::{execute, instantiate, query}; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{from_binary, to_binary, CosmosMsg, StdError, SubMsg, Uint128, WasmMsg}; use cw20::Cw20ExecuteMsg; use mirror_protocol::community::{ConfigResponse, ExecuteMsg, InstantiateMsg, QueryMsg}; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mirror_token: "mirror0000".to_string(), spend_limit: Uint128::from(1000000u128), }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // it worked, let's query the state let config: ConfigResponse = from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap()).unwrap(); assert_eq!("owner0000", config.owner.as_str()); assert_eq!("mirror0000", config.mirror_token.as_str()); assert_eq!(Uint128::from(1000000u128), config.spend_limit); } #[test] fn update_config() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mirror_token: "mirror0000".to_string(), spend_limit: Uint128::from(1000000u128), }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // it worked, let's query the state let config: ConfigResponse = from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap()).unwrap(); assert_eq!("owner0000", config.owner.as_str()); assert_eq!("mirror0000", config.mirror_token.as_str()); assert_eq!(Uint128::from(1000000u128), config.spend_limit); let msg = ExecuteMsg::UpdateConfig { owner: Some("owner0001".to_string()), spend_limit: None, }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(StdError::GenericErr { msg, .. }) => { assert_eq!(msg, "unauthorized") } _ => panic!("DO NOT ENTER HERE"), } let info = mock_info("owner0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let config: ConfigResponse = from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap()).unwrap(); assert_eq!( config, ConfigResponse { owner: "owner0001".to_string(), mirror_token: "mirror0000".to_string(), spend_limit: Uint128::from(1000000u128), } ); // Update spend_limit let msg = ExecuteMsg::UpdateConfig { owner: None, spend_limit: Some(Uint128::from(2000000u128)), }; let info = mock_info("owner0001", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg); let config: ConfigResponse = from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap()).unwrap(); assert_eq!( config, ConfigResponse { owner: "owner0001".to_string(), mirror_token: "mirror0000".to_string(), spend_limit: Uint128::from(2000000u128), } ); } #[test] fn test_spend() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mirror_token: "mirror0000".to_string(), spend_limit: Uint128::from(1000000u128), }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // permission failed let msg = ExecuteMsg::Spend { recipient: "addr0000".to_string(), amount: Uint128::from(1000000u128), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => { assert_eq!(msg, "unauthorized") } _ => panic!("DO NOT ENTER HERE"), } // failed due to spend limit let msg = ExecuteMsg::Spend { recipient: "addr0000".to_string(), amount: Uint128::from(2000000u128), }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => { assert_eq!(msg, "Cannot spend more than spend_limit") } _ => panic!("DO NOT ENTER HERE"), } let msg = ExecuteMsg::Spend { recipient: "addr0000".to_string(), amount: Uint128::from(1000000u128), }; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "mirror0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: "addr0000".to_string(), amount: Uint128::from(1000000u128), }) .unwrap(), }))] ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_community/src/state.rs
contracts/mirror_community/src/state.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, StdResult, Storage, Uint128}; use cosmwasm_storage::{singleton, singleton_read}; static KEY_CONFIG: &[u8] = b"config"; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, // mirror gov address pub mirror_token: CanonicalAddr, // mirror token address pub spend_limit: Uint128, // spend limit per each `spend` request } pub fn store_config(storage: &mut dyn Storage, config: &Config) -> StdResult<()> { singleton(storage, KEY_CONFIG).save(config) } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, KEY_CONFIG).load() }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_community/examples/schema.rs
contracts/mirror_community/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::community::{ConfigResponse, ExecuteMsg, InstantiateMsg, QueryMsg}; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/contract.rs
contracts/mirror_limit_order/src/contract.rs
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ from_binary, to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, }; use crate::order::{ cancel_order, execute_order, query_last_order_id, query_order, query_orders, submit_order, }; use crate::state::init_last_order_id; use cw20::Cw20ReceiveMsg; use mirror_protocol::limit_order::{Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; use terraswap::asset::{Asset, AssetInfo}; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, _msg: InstantiateMsg, ) -> StdResult<Response> { init_last_order_id(deps.storage)?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, _env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> StdResult<Response> { match msg { ExecuteMsg::Receive(msg) => receive_cw20(deps, info, msg), ExecuteMsg::SubmitOrder { offer_asset, ask_asset, } => { if !offer_asset.is_native_token() { return Err(StdError::generic_err("must provide native token")); } offer_asset.assert_sent_native_token_balance(&info)?; submit_order(deps, info.sender, offer_asset, ask_asset) } ExecuteMsg::CancelOrder { order_id } => cancel_order(deps, info, order_id), ExecuteMsg::ExecuteOrder { execute_asset, order_id, } => { if !execute_asset.is_native_token() { return Err(StdError::generic_err("must provide native token")); } execute_asset.assert_sent_native_token_balance(&info)?; execute_order(deps, info.sender, execute_asset, order_id) } } } pub fn receive_cw20( deps: DepsMut, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> StdResult<Response> { let sender = deps.api.addr_validate(cw20_msg.sender.as_str())?; let provided_asset = Asset { info: AssetInfo::Token { contract_addr: info.sender.to_string(), }, amount: cw20_msg.amount, }; match from_binary(&cw20_msg.msg) { Ok(Cw20HookMsg::SubmitOrder { ask_asset }) => { submit_order(deps, sender, provided_asset, ask_asset) } Ok(Cw20HookMsg::ExecuteOrder { order_id }) => { execute_order(deps, sender, provided_asset, order_id) } Err(_) => Err(StdError::generic_err("invalid cw20 hook message")), } } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Order { order_id } => to_binary(&query_order(deps, order_id)?), QueryMsg::Orders { bidder_addr, start_after, limit, order_by, } => to_binary(&query_orders( deps, bidder_addr, start_after, limit, order_by, )?), QueryMsg::LastOrderId {} => to_binary(&query_last_order_id(deps)?), } } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> { Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/lib.rs
contracts/mirror_limit_order/src/lib.rs
pub mod contract; pub mod state; mod order; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/order.rs
contracts/mirror_limit_order/src/order.rs
use crate::state::{ increase_last_order_id, read_last_order_id, read_order, read_orders, read_orders_with_bidder_indexer, remove_order, store_order, Order, }; use cosmwasm_std::{ attr, Addr, CosmosMsg, Decimal, Deps, DepsMut, MessageInfo, Response, StdError, StdResult, Uint128, }; use mirror_protocol::common::OrderBy; use mirror_protocol::limit_order::{LastOrderIdResponse, OrderResponse, OrdersResponse}; use terraswap::asset::Asset; pub fn submit_order( deps: DepsMut, sender: Addr, offer_asset: Asset, ask_asset: Asset, ) -> StdResult<Response> { let order_id = increase_last_order_id(deps.storage)?; let offer_asset_raw = offer_asset.to_raw(deps.api)?; let ask_asset_raw = ask_asset.to_raw(deps.api)?; store_order( deps.storage, &Order { order_id, bidder_addr: deps.api.addr_canonicalize(sender.as_str())?, offer_asset: offer_asset_raw, ask_asset: ask_asset_raw, filled_offer_amount: Uint128::zero(), filled_ask_amount: Uint128::zero(), }, )?; Ok(Response::new().add_attributes(vec![ attr("action", "submit_order"), attr("order_id", order_id.to_string()), attr("bidder_addr", sender), attr("offer_asset", offer_asset.to_string()), attr("ask_asset", ask_asset.to_string()), ])) } pub fn cancel_order(deps: DepsMut, info: MessageInfo, order_id: u64) -> StdResult<Response> { let order: Order = read_order(deps.storage, order_id)?; if order.bidder_addr != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } // Compute refund asset let left_offer_amount = order .offer_asset .amount .checked_sub(order.filled_offer_amount)?; let bidder_refund = Asset { info: order.offer_asset.info.to_normal(deps.api)?, amount: left_offer_amount, }; // Build refund msg let messages = if left_offer_amount > Uint128::zero() { vec![bidder_refund.clone().into_msg(&deps.querier, info.sender)?] } else { vec![] }; remove_order(deps.storage, &order); Ok(Response::new().add_messages(messages).add_attributes(vec![ attr("action", "cancel_order"), attr("order_id", order_id.to_string()), attr("bidder_refund", bidder_refund.to_string()), ])) } pub fn execute_order( deps: DepsMut, sender: Addr, execute_asset: Asset, order_id: u64, ) -> StdResult<Response> { let mut order: Order = read_order(deps.storage, order_id)?; if !execute_asset .info .equal(&order.ask_asset.info.to_normal(deps.api)?) { return Err(StdError::generic_err("invalid asset given")); } // Compute left offer & ask amount let left_offer_amount = order .offer_asset .amount .checked_sub(order.filled_offer_amount)?; let left_ask_amount = order .ask_asset .amount .checked_sub(order.filled_ask_amount)?; if left_ask_amount < execute_asset.amount || left_offer_amount.is_zero() { return Err(StdError::generic_err("insufficient order amount left")); } // Cap the send amount to left_offer_amount let executor_receive = Asset { info: order.offer_asset.info.to_normal(deps.api)?, amount: if left_ask_amount == execute_asset.amount { left_offer_amount } else { std::cmp::min( left_offer_amount, execute_asset.amount * Decimal::from_ratio(order.offer_asset.amount, order.ask_asset.amount), ) }, }; let bidder_addr = deps.api.addr_humanize(&order.bidder_addr)?; let bidder_receive = execute_asset; // When left amount is zero, close order if left_ask_amount == bidder_receive.amount { remove_order(deps.storage, &order); } else { order.filled_ask_amount += bidder_receive.amount; order.filled_offer_amount += executor_receive.amount; store_order(deps.storage, &order)?; } let mut messages: Vec<CosmosMsg> = vec![]; if !executor_receive.amount.is_zero() { messages.push( executor_receive .clone() .into_msg(&deps.querier, deps.api.addr_validate(sender.as_str())?)?, ); } if !bidder_receive.amount.is_zero() { messages.push( bidder_receive .clone() .into_msg(&deps.querier, bidder_addr)?, ); } Ok(Response::new().add_messages(messages).add_attributes(vec![ attr("action", "execute_order"), attr("order_id", order_id.to_string()), attr("executor_receive", executor_receive.to_string()), attr("bidder_receive", bidder_receive.to_string()), ])) } pub fn query_order(deps: Deps, order_id: u64) -> StdResult<OrderResponse> { let order: Order = read_order(deps.storage, order_id)?; let resp = OrderResponse { order_id: order.order_id, bidder_addr: deps.api.addr_humanize(&order.bidder_addr)?.to_string(), offer_asset: order.offer_asset.to_normal(deps.api)?, ask_asset: order.ask_asset.to_normal(deps.api)?, filled_offer_amount: order.filled_offer_amount, filled_ask_amount: order.filled_ask_amount, }; Ok(resp) } pub fn query_orders( deps: Deps, bidder_addr: Option<String>, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<OrdersResponse> { let orders: Vec<Order> = if let Some(bidder_addr) = bidder_addr { let bidder_addr_raw = deps.api.addr_canonicalize(&bidder_addr)?; read_orders_with_bidder_indexer( deps.storage, &bidder_addr_raw, start_after, limit, order_by, )? } else { read_orders(deps.storage, start_after, limit, order_by)? }; let resp = OrdersResponse { orders: orders .iter() .map(|order| { Ok(OrderResponse { order_id: order.order_id, bidder_addr: deps.api.addr_humanize(&order.bidder_addr)?.to_string(), offer_asset: order.offer_asset.to_normal(deps.api)?, ask_asset: order.ask_asset.to_normal(deps.api)?, filled_offer_amount: order.filled_offer_amount, filled_ask_amount: order.filled_ask_amount, }) }) .collect::<StdResult<Vec<OrderResponse>>>()?, }; Ok(resp) } pub fn query_last_order_id(deps: Deps) -> StdResult<LastOrderIdResponse> { let last_order_id = read_last_order_id(deps.storage)?; let resp = LastOrderIdResponse { last_order_id }; Ok(resp) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/state.rs
contracts/mirror_limit_order/src/state.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, StdError, StdResult, Storage, Uint128}; use cosmwasm_storage::{singleton, singleton_read, Bucket, ReadonlyBucket}; use mirror_protocol::common::OrderBy; use std::convert::TryInto; use terraswap::asset::AssetRaw; static KEY_LAST_ORDER_ID: &[u8] = b"last_order_id"; static PREFIX_ORDER: &[u8] = b"order"; static PREFIX_ORDER_BY_BIDDER: &[u8] = b"order_by_bidder"; pub fn init_last_order_id(storage: &mut dyn Storage) -> StdResult<()> { singleton(storage, KEY_LAST_ORDER_ID).save(&0u64) } pub fn increase_last_order_id(storage: &mut dyn Storage) -> StdResult<u64> { singleton(storage, KEY_LAST_ORDER_ID).update(|v| Ok(v + 1)) } pub fn read_last_order_id(storage: &dyn Storage) -> StdResult<u64> { singleton_read(storage, KEY_LAST_ORDER_ID).load() } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Order { pub order_id: u64, pub bidder_addr: CanonicalAddr, pub offer_asset: AssetRaw, pub ask_asset: AssetRaw, pub filled_offer_amount: Uint128, pub filled_ask_amount: Uint128, } pub fn store_order(storage: &mut dyn Storage, order: &Order) -> StdResult<()> { Bucket::new(storage, PREFIX_ORDER).save(&order.order_id.to_be_bytes(), order)?; Bucket::multilevel( storage, &[PREFIX_ORDER_BY_BIDDER, order.bidder_addr.as_slice()], ) .save(&order.order_id.to_be_bytes(), &true)?; Ok(()) } pub fn remove_order(storage: &mut dyn Storage, order: &Order) { Bucket::<Order>::new(storage, PREFIX_ORDER).remove(&order.order_id.to_be_bytes()); Bucket::<Order>::multilevel( storage, &[PREFIX_ORDER_BY_BIDDER, order.bidder_addr.as_slice()], ) .remove(&order.order_id.to_be_bytes()); } pub fn read_order(storage: &dyn Storage, order_id: u64) -> StdResult<Order> { ReadonlyBucket::new(storage, PREFIX_ORDER).load(&order_id.to_be_bytes()) } pub fn read_orders_with_bidder_indexer( storage: &dyn Storage, bidder_addr: &CanonicalAddr, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<Order>> { let position_indexer: ReadonlyBucket<bool> = ReadonlyBucket::multilevel(storage, &[PREFIX_ORDER_BY_BIDDER, bidder_addr.as_slice()]); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start(start_after), None, OrderBy::Asc), _ => (None, calc_range_end(start_after), OrderBy::Desc), }; position_indexer .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (k, _) = item?; read_order(storage, bytes_to_u64(&k)?) }) .collect() } // settings for pagination const MAX_LIMIT: u32 = 30; const DEFAULT_LIMIT: u32 = 10; pub fn read_orders( storage: &dyn Storage, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<Order>> { let position_bucket: ReadonlyBucket<Order> = ReadonlyBucket::new(storage, PREFIX_ORDER); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start(start_after), None, OrderBy::Asc), _ => (None, calc_range_end(start_after), OrderBy::Desc), }; position_bucket .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (_, v) = item?; Ok(v) }) .collect() } fn bytes_to_u64(data: &[u8]) -> StdResult<u64> { match data[0..8].try_into() { Ok(bytes) => Ok(u64::from_be_bytes(bytes)), Err(_) => Err(StdError::generic_err( "Corrupted data found. 8 byte expected.", )), } } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_start(start_after: Option<u64>) -> Option<Vec<u8>> { start_after.map(|id| { let mut v = id.to_be_bytes().to_vec(); v.push(1); v }) } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_end(start_after: Option<u64>) -> Option<Vec<u8>> { start_after.map(|id| id.to_be_bytes().to_vec()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/testing/tests.rs
contracts/mirror_limit_order/src/testing/tests.rs
use cosmwasm_std::testing::{mock_env, mock_info}; use cosmwasm_std::{ attr, from_binary, to_binary, BankMsg, Coin, CosmosMsg, Decimal, StdError, SubMsg, Uint128, WasmMsg, }; use crate::contract::{execute, instantiate, query}; use crate::testing::mock_querier::mock_dependencies; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use mirror_protocol::common::OrderBy; use mirror_protocol::limit_order::{ Cw20HookMsg, ExecuteMsg, InstantiateMsg, LastOrderIdResponse, OrderResponse, OrdersResponse, QueryMsg, }; use terraswap::asset::{Asset, AssetInfo}; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); } #[test] fn submit_order() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::SubmitOrder { offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "mAAPL".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "mAAPL".to_string(), }, }, }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "must provide native token"), _ => panic!("DO NOT ENTER HERE"), } let msg = ExecuteMsg::SubmitOrder { offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "mAAPL".to_string(), }, }, }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!( msg, "Native token balance mismatch between the argument and the transferred" ), _ => panic!("DO NOT ENTER HERE"), } let msg = ExecuteMsg::SubmitOrder { offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "mAAPL".to_string(), }, }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "submit_order"), attr("order_id", 1.to_string()), attr("bidder_addr", "addr0000"), attr("offer_asset", "1000000uusd"), attr("ask_asset", "1000000mAAPL"), ] ); assert_eq!( from_binary::<LastOrderIdResponse>( &query(deps.as_ref(), mock_env(), QueryMsg::LastOrderId {}).unwrap() ) .unwrap(), LastOrderIdResponse { last_order_id: 1 } ); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::new(1000000u128), msg: to_binary(&Cw20HookMsg::SubmitOrder { ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, }) .unwrap(), }); let info = mock_info("mAAPL", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "submit_order"), attr("order_id", 2.to_string()), attr("bidder_addr", "addr0000"), attr("offer_asset", "1000000mAAPL"), attr("ask_asset", "1000000uusd"), ] ); assert_eq!( from_binary::<LastOrderIdResponse>( &query(deps.as_ref(), mock_env(), QueryMsg::LastOrderId {}).unwrap() ) .unwrap(), LastOrderIdResponse { last_order_id: 2 } ); } #[test] fn cancel_order_native_token() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::new(1000000u128))], ); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::SubmitOrder { offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "mAAPL".to_string(), }, }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), mock_env(), info.clone(), msg).unwrap(); let msg = ExecuteMsg::CancelOrder { order_id: 1 }; // failed verfication failed let wrong_info = mock_info("addr0001", &[]); let res = execute(deps.as_mut(), mock_env(), wrong_info, msg.clone()); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"), _ => panic!("DO NOT ENTER HERE"), } let res = execute(deps.as_mut(), mock_env(), info.clone(), msg.clone()).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "cancel_order"), attr("order_id", 1.to_string()), attr("bidder_refund", "1000000uusd") ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0000".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::new(990099u128), }] }))] ); // failed no order exists let res = execute(deps.as_mut(), mock_env(), info, msg); assert!(res.is_err()) } #[test] fn cancel_order_token() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::new(1000000u128))], ); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::new(1000000u128), msg: to_binary(&Cw20HookMsg::SubmitOrder { ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, }) .unwrap(), }); let info = mock_info("mAAPL", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::CancelOrder { order_id: 1 }; // failed verfication failed let wrong_info = mock_info("addr0001", &[]); let res = execute(deps.as_mut(), mock_env(), wrong_info, msg.clone()); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"), _ => panic!("DO NOT ENTER HERE"), } let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info.clone(), msg.clone()).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "cancel_order"), attr("order_id", 1.to_string()), attr("bidder_refund", "1000000mAAPL") ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "mAAPL".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { amount: Uint128::new(1000000u128), recipient: "addr0000".to_string(), }) .unwrap(), }))] ); // failed no order exists let res = execute(deps.as_mut(), mock_env(), info, msg); assert!(res.is_err()) } #[test] fn execute_order_native_token() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[ (&"uusd".to_string(), &Uint128::new(1000000u128)), (&"ukrw".to_string(), &Uint128::new(1000000u128)), ], ); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::SubmitOrder { offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "ukrw".to_string(), }, }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), mock_env(), info.clone(), msg).unwrap(); // assertion; native asset balance let msg = ExecuteMsg::ExecuteOrder { execute_asset: Asset { amount: Uint128::new(500000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, order_id: 1u64, }; let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!( msg, "Native token balance mismatch between the argument and the transferred" ), _ => panic!("DO NOT ENTER HERE"), } // cannot execute order with other asset let info = mock_info( "addr0001", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(500000u128), }], ); let res = execute(deps.as_mut(), mock_env(), info, msg); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "invalid asset given"), _ => panic!("DO NOT ENTER HERE"), } // partial execute let info = mock_info( "addr0001", &[Coin { denom: "ukrw".to_string(), amount: Uint128::from(500000u128), }], ); let msg = ExecuteMsg::ExecuteOrder { execute_asset: Asset { amount: Uint128::new(500000u128), info: AssetInfo::NativeToken { denom: "ukrw".to_string(), }, }, order_id: 1u64, }; let res = execute(deps.as_mut(), mock_env(), info.clone(), msg.clone()).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "execute_order"), attr("order_id", 1.to_string()), attr("executor_receive", "500000uusd"), attr("bidder_receive", "500000ukrw"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0001".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(495049u128) }] })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0000".to_string(), amount: vec![Coin { denom: "ukrw".to_string(), amount: Uint128::from(495049u128) }] })), ] ); let resp: OrderResponse = from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Order { order_id: 1 }).unwrap()) .unwrap(); assert_eq!(resp.filled_ask_amount, Uint128::new(500000u128)); assert_eq!(resp.filled_offer_amount, Uint128::new(500000u128)); // fill left amount let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "execute_order"), attr("order_id", 1.to_string()), attr("executor_receive", "500000uusd"), attr("bidder_receive", "500000ukrw"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0001".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(495049u128) }] })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0000".to_string(), amount: vec![Coin { denom: "ukrw".to_string(), amount: Uint128::from(495049u128) }] })), ] ); assert!(query(deps.as_ref(), mock_env(), QueryMsg::Order { order_id: 1 }).is_err()) } #[test] fn execute_order_token() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[ (&"uusd".to_string(), &Uint128::new(1000000u128)), (&"ukrw".to_string(), &Uint128::new(1000000u128)), ], ); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::SubmitOrder { ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "token0001".to_string(), }, }, }) .unwrap(), }); let info = mock_info("token0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // cannot execute order with other asset let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0001".to_string(), amount: Uint128::from(500000u128), msg: to_binary(&Cw20HookMsg::ExecuteOrder { order_id: 1u64 }).unwrap(), }); let info = mock_info("token0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "invalid asset given"), _ => panic!("DO NOT ENTER HERE"), } // partial execute let info = mock_info("token0001", &[]); let res = execute(deps.as_mut(), mock_env(), info.clone(), msg.clone()).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "execute_order"), attr("order_id", 1.to_string()), attr("executor_receive", "500000token0000"), attr("bidder_receive", "500000token0001"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "token0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: "addr0001".to_string(), amount: Uint128::from(500000u128) }) .unwrap(), })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "token0001".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: "addr0000".to_string(), amount: Uint128::from(500000u128) }) .unwrap(), })), ] ); let resp: OrderResponse = from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Order { order_id: 1 }).unwrap()) .unwrap(); assert_eq!(resp.filled_ask_amount, Uint128::new(500000u128)); assert_eq!(resp.filled_offer_amount, Uint128::new(500000u128)); // fill left amount let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "execute_order"), attr("order_id", 1.to_string()), attr("executor_receive", "500000token0000"), attr("bidder_receive", "500000token0001"), ] ); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "token0000".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: "addr0001".to_string(), amount: Uint128::from(500000u128) }) .unwrap(), })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "token0001".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: "addr0000".to_string(), amount: Uint128::from(500000u128) }) .unwrap(), })), ] ); assert!(query(deps.as_ref(), mock_env(), QueryMsg::Order { order_id: 1 }).is_err()) } #[test] fn orders_querier() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[ (&"uusd".to_string(), &Uint128::new(1000000u128)), (&"ukrw".to_string(), &Uint128::new(1000000u128)), ], ); let msg = InstantiateMsg {}; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::SubmitOrder { offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "ukrw".to_string(), }, }, }; let info = mock_info( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(1000000u128), }], ); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: "addr0000".to_string(), amount: Uint128::from(1000000u128), msg: to_binary(&Cw20HookMsg::SubmitOrder { ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "token0001".to_string(), }, }, }) .unwrap(), }); let info = mock_info("token0000", &[]); let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let order_1 = OrderResponse { order_id: 1u64, bidder_addr: "addr0000".to_string(), offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::NativeToken { denom: "ukrw".to_string(), }, }, filled_offer_amount: Uint128::zero(), filled_ask_amount: Uint128::zero(), }; let order_2 = OrderResponse { order_id: 2u64, bidder_addr: "addr0000".to_string(), offer_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "token0000".to_string(), }, }, ask_asset: Asset { amount: Uint128::from(1000000u128), info: AssetInfo::Token { contract_addr: "token0001".to_string(), }, }, filled_offer_amount: Uint128::zero(), filled_ask_amount: Uint128::zero(), }; assert_eq!( OrdersResponse { orders: vec![order_1.clone(), order_2.clone(),], }, from_binary::<OrdersResponse>( &query( deps.as_ref(), mock_env(), QueryMsg::Orders { bidder_addr: Some("addr0000".to_string()), start_after: None, limit: None, order_by: Some(OrderBy::Asc), } ) .unwrap() ) .unwrap() ); assert_eq!( OrdersResponse { orders: vec![order_1.clone(), order_2.clone(),], }, from_binary::<OrdersResponse>( &query( deps.as_ref(), mock_env(), QueryMsg::Orders { bidder_addr: None, start_after: None, limit: None, order_by: Some(OrderBy::Asc), } ) .unwrap() ) .unwrap() ); // DESC test assert_eq!( OrdersResponse { orders: vec![order_2.clone(), order_1.clone(),], }, from_binary::<OrdersResponse>( &query( deps.as_ref(), mock_env(), QueryMsg::Orders { bidder_addr: None, start_after: None, limit: None, order_by: Some(OrderBy::Desc), } ) .unwrap() ) .unwrap() ); // different bidder assert_eq!( OrdersResponse { orders: vec![] }, from_binary::<OrdersResponse>( &query( deps.as_ref(), mock_env(), QueryMsg::Orders { bidder_addr: Some("addr0001".to_string()), start_after: None, limit: None, order_by: None, } ) .unwrap() ) .unwrap() ); // start after DESC assert_eq!( OrdersResponse { orders: vec![order_1], }, from_binary::<OrdersResponse>( &query( deps.as_ref(), mock_env(), QueryMsg::Orders { bidder_addr: None, start_after: Some(2u64), limit: None, order_by: Some(OrderBy::Desc), } ) .unwrap() ) .unwrap() ); // start after ASC assert_eq!( OrdersResponse { orders: vec![order_2], }, from_binary::<OrdersResponse>( &query( deps.as_ref(), mock_env(), QueryMsg::Orders { bidder_addr: None, start_after: Some(1u64), limit: None, order_by: Some(OrderBy::Asc), } ) .unwrap() ) .unwrap() ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/testing/mock_querier.rs
contracts/mirror_limit_order/src/testing/mock_querier.rs
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_slice, to_binary, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use terra_cosmwasm::{TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper, TerraRoute}; /// mock_dependencies is a drop-in replacement for cosmwasm_std::testing::mock_dependencies /// this uses our CustomQuerier. pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new(MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)])); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<TerraQueryWrapper>, tax_querier: TaxQuerier, } #[derive(Clone, Default)] pub struct TaxQuerier { rate: Decimal, // this lets us iterate over all pairs that match the first string caps: HashMap<String, Uint128>, } impl TaxQuerier { pub fn new(rate: Decimal, caps: &[(&String, &Uint128)]) -> Self { TaxQuerier { rate, caps: caps_to_map(caps), } } } pub(crate) fn caps_to_map(caps: &[(&String, &Uint128)]) -> HashMap<String, Uint128> { let mut owner_map: HashMap<String, Uint128> = HashMap::new(); for (denom, cap) in caps.iter() { owner_map.insert(denom.to_string(), **cap); } owner_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<TerraQueryWrapper> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum MockQueryMsg { Price {}, } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<TerraQueryWrapper>) -> QuerierResult { match &request { QueryRequest::Custom(TerraQueryWrapper { route, query_data }) => { if route == &TerraRoute::Treasury { match query_data { TerraQuery::TaxRate {} => { let res = TaxRateResponse { rate: self.tax_querier.rate, }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } TerraQuery::TaxCap { denom } => { let cap = self .tax_querier .caps .get(denom) .copied() .unwrap_or_default(); let res = TaxCapResponse { cap }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } _ => panic!("DO NOT ENTER HERE"), } } else { panic!("DO NOT ENTER HERE") } } _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new(base: MockQuerier<TerraQueryWrapper>) -> Self { WasmMockQuerier { base, tax_querier: TaxQuerier::default(), } } // configure the token owner mock querier pub fn with_tax(&mut self, rate: Decimal, caps: &[(&String, &Uint128)]) { self.tax_querier = TaxQuerier::new(rate, caps); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/src/testing/mod.rs
contracts/mirror_limit_order/src/testing/mod.rs
mod mock_querier; mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_limit_order/examples/schema.rs
contracts/mirror_limit_order/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::limit_order::{ Cw20HookMsg, ExecuteMsg, InstantiateMsg, OrderResponse, OrdersResponse, QueryMsg, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(Cw20HookMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(OrderResponse), &out_dir); export_schema(&schema_for!(OrdersResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_short_reward/src/contract.rs
contracts/mirror_short_reward/src/contract.rs
use crate::math::{ decimal_division, decimal_multiplication, decimal_subtraction, erf_plus_one, Sign, }; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ to_binary, Binary, Decimal, Deps, DepsMut, Empty, Env, MessageInfo, Response, StdResult, }; use mirror_protocol::short_reward::{ ExecuteMsg, InstantiateMsg, QueryMsg, ShortRewardWeightResponse, }; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( _deps: DepsMut, _env: Env, _info: MessageInfo, _msg: InstantiateMsg, ) -> StdResult<Response> { Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( _deps: DepsMut, _env: Env, _info: MessageInfo, _msg: ExecuteMsg, ) -> StdResult<Response> { Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(_deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::ShortRewardWeight { premium_rate } => { to_binary(&query_short_reward_weight(premium_rate)?) } } } pub fn query_short_reward_weight(premium_rate: Decimal) -> StdResult<ShortRewardWeightResponse> { if premium_rate > Decimal::percent(7) { return Ok(ShortRewardWeightResponse { short_reward_weight: Decimal::percent(80), }); } let one = Decimal::one(); let two = one + one; let e10 = 10000000000u128; let sqrt_two = Decimal::from_ratio(14142135624u128, e10); let p = decimal_multiplication(premium_rate, Decimal::from_ratio(100u128, 1u128)); let (sign_x, x) = if p > two { ( Sign::Positive, decimal_division(decimal_subtraction(p, two)?, sqrt_two), ) } else { ( Sign::Negative, decimal_division(decimal_subtraction(two, p)?, sqrt_two), ) }; let short_reward_weight: Decimal = decimal_division(erf_plus_one(sign_x, x)?, Decimal::from_ratio(5u128, 2u128)); Ok(ShortRewardWeightResponse { short_reward_weight, }) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(_deps: DepsMut, _env: Env, _msg: Empty) -> StdResult<Response> { Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_short_reward/src/lib.rs
contracts/mirror_short_reward/src/lib.rs
pub mod contract; mod math; #[cfg(test)] mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_short_reward/src/tests.rs
contracts/mirror_short_reward/src/tests.rs
use crate::contract::query_short_reward_weight; use crate::math::{erf_plus_one, Sign}; use cosmwasm_std::Decimal; #[test] fn short_reward_weight_test() { let e6 = 1000000u128; let e7 = 10000000u128; assert_eq!( query_short_reward_weight(Decimal::zero()) .unwrap() .short_reward_weight, Decimal::from_ratio(5236u128, e6) ); assert_eq!( query_short_reward_weight(Decimal::percent(1)) .unwrap() .short_reward_weight, Decimal::from_ratio(1268336u128, e7), ); assert_eq!( query_short_reward_weight(Decimal::percent(2)) .unwrap() .short_reward_weight, Decimal::percent(40) ); assert_eq!( query_short_reward_weight(Decimal::percent(4)) .unwrap() .short_reward_weight, Decimal::from_ratio(7817996u128, e7) ); assert_eq!( query_short_reward_weight(Decimal::percent(8)) .unwrap() .short_reward_weight, Decimal::percent(80) ); assert_eq!( query_short_reward_weight(Decimal::percent(15)) .unwrap() .short_reward_weight, Decimal::percent(80) ); } #[test] fn erf_plus_one_test() { let e6 = 1000000u128; let e10 = 10000000000u128; assert_eq!( erf_plus_one(Sign::Negative, Decimal::from_ratio(21213203435u128, e10)).unwrap(), Decimal::zero() ); assert_eq!( erf_plus_one(Sign::Negative, Decimal::from_ratio(14142135623u128, e10)).unwrap(), Decimal::from_ratio(13090u128, e6) ); assert_eq!( erf_plus_one(Sign::Positive, Decimal::zero()).unwrap(), Decimal::from_ratio(1000000u128, e6) ); assert_eq!( erf_plus_one(Sign::Positive, Decimal::from_ratio(14142135623u128, e10)).unwrap(), Decimal::from_ratio(1954499u128, e6) ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_short_reward/src/math.rs
contracts/mirror_short_reward/src/math.rs
use cosmwasm_std::{Decimal, StdResult, Uint128}; const DECIMAL_FRACTIONAL: Uint128 = Uint128::new(1_000_000_000u128); pub fn decimal_division(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio(DECIMAL_FRACTIONAL * a, b * DECIMAL_FRACTIONAL) } pub fn decimal_subtraction(a: Decimal, b: Decimal) -> StdResult<Decimal> { Ok(Decimal::from_ratio( (a * DECIMAL_FRACTIONAL).checked_sub(b * DECIMAL_FRACTIONAL)?, DECIMAL_FRACTIONAL, )) } pub fn decimal_multiplication(a: Decimal, b: Decimal) -> Decimal { Decimal::from_ratio(a * DECIMAL_FRACTIONAL * b, DECIMAL_FRACTIONAL) } pub fn reverse_decimal(decimal: Decimal) -> Decimal { Decimal::from_ratio(DECIMAL_FRACTIONAL, decimal * DECIMAL_FRACTIONAL) } // p == premium * 100 pub fn erf_plus_one(sign_x: Sign, x: Decimal) -> StdResult<Decimal> { let e6 = 1000000u128; let e10 = 10000000000u128; let a1 = Decimal::from_ratio(705230784u128, e10); let a2 = Decimal::from_ratio(422820123u128, e10); let a3 = Decimal::from_ratio(92705272u128, e10); let a4 = Decimal::from_ratio(1520143u128, e10); let a5 = Decimal::from_ratio(2765672u128, e10); let a6 = Decimal::from_ratio(430638u128, e10); let one = Decimal::one(); let two = one + one; // ((((((a6 * x) + a5) * x + a4 ) * x + a3) * x + a2) * x + a1) * x + 1 let sign = sign_x.clone(); let num = decimal_multiplication(a6, x); let (sign, num) = sum_and_multiply_x(sign, Sign::Positive, sign_x.clone(), num, a5, x)?; let (sign, num) = sum_and_multiply_x(sign, Sign::Positive, sign_x.clone(), num, a4, x)?; let (sign, num) = sum_and_multiply_x(sign, Sign::Positive, sign_x.clone(), num, a3, x)?; let (sign, num) = sum_and_multiply_x(sign, Sign::Positive, sign_x.clone(), num, a2, x)?; let (sign, num) = sum_and_multiply_x(sign, Sign::Positive, sign_x, num, a1, x)?; let num = if sign == Sign::Positive { num + one } else if num > one { decimal_subtraction(num, one)? } else { decimal_subtraction(one, num)? }; // ignore sign let num2 = decimal_multiplication(num, num); let num4 = decimal_multiplication(num2, num2); let num8 = decimal_multiplication(num4, num4); let num16 = decimal_multiplication(num8, num8); let reverse_num16 = reverse_decimal(num16); if reverse_num16 > two { return Ok(Decimal::zero()); } let erf_plus_one = decimal_subtraction(two, reverse_num16); // maximum error: 3 * 10^-7 // so only use 6 decimal digits Ok(Decimal::from_ratio(erf_plus_one? * e6.into(), e6)) } #[derive(PartialEq, Clone)] pub enum Sign { Positive, Negative, } // return (sign, result) fn sum_and_multiply_x( sign_1: Sign, sign_2: Sign, sign_x: Sign, num1: Decimal, num2: Decimal, x: Decimal, ) -> StdResult<(Sign, Decimal)> { if sign_1 == sign_2 { let val = decimal_multiplication(num1 + num2, x); if sign_1 == sign_x { Ok((Sign::Positive, val)) } else { Ok((Sign::Negative, val)) } } else if num1 > num2 { let val = decimal_multiplication(decimal_subtraction(num1, num2)?, x); if sign_1 == sign_x { Ok((Sign::Positive, val)) } else { Ok((Sign::Negative, val)) } } else { let val = decimal_multiplication(decimal_subtraction(num2, num1)?, x); if sign_2 == sign_x { Ok((Sign::Positive, val)) } else { Ok((Sign::Negative, val)) } } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_short_reward/examples/schema.rs
contracts/mirror_short_reward/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::short_reward::{ ExecuteMsg, InstantiateMsg, QueryMsg, ShortRewardWeightResponse, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(ShortRewardWeightResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/contract.rs
contracts/mirror_gov/src/contract.rs
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use crate::migrate::migrate_config; use crate::querier::load_token_balance; use crate::staking::{ deposit_reward, query_shares, query_staker, stake_voting_rewards, stake_voting_tokens, withdraw_voting_rewards, withdraw_voting_tokens, }; use crate::state::{ bank_read, bank_store, config_read, config_store, poll_additional_params_read, poll_additional_params_store, poll_indexer_store, poll_read, poll_store, poll_voter_read, poll_voter_store, read_poll_voters, read_polls, read_tmp_poll_id, state_read, state_store, store_tmp_poll_id, Config, ExecuteData, Poll, PollAdditionalParams, State, }; use cosmwasm_std::{ attr, from_binary, to_binary, Api, Binary, CosmosMsg, Decimal, Deps, DepsMut, Env, MessageInfo, Reply, ReplyOn, Response, StdError, StdResult, SubMsg, Uint128, WasmMsg, }; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use mirror_protocol::common::OrderBy; use mirror_protocol::gov::{ ConfigResponse, Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, PollAdminAction, PollConfig, PollExecuteMsg, PollResponse, PollStatus, PollsResponse, QueryMsg, StateResponse, VoteOption, VoterInfo, VotersResponse, VotersResponseItem, }; const MIN_TITLE_LENGTH: usize = 4; const MAX_TITLE_LENGTH: usize = 64; const MIN_DESC_LENGTH: usize = 4; const MAX_DESC_LENGTH: usize = 256; const MIN_LINK_LENGTH: usize = 12; const MAX_LINK_LENGTH: usize = 128; const MAX_POLLS_IN_PROGRESS: usize = 50; const POLL_EXECUTE_REPLY_ID: u64 = 1; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { validate_poll_config(&msg.default_poll_config)?; validate_poll_config(&msg.migration_poll_config)?; validate_poll_config(&msg.auth_admin_poll_config)?; validate_voter_weight(msg.voter_weight)?; let config = Config { mirror_token: deps.api.addr_canonicalize(&msg.mirror_token)?, owner: deps.api.addr_canonicalize(info.sender.as_str())?, effective_delay: msg.effective_delay, default_poll_config: msg.default_poll_config, migration_poll_config: msg.migration_poll_config, auth_admin_poll_config: msg.auth_admin_poll_config, voter_weight: msg.voter_weight, snapshot_period: msg.snapshot_period, admin_manager: deps.api.addr_canonicalize(&msg.admin_manager)?, poll_gas_limit: msg.poll_gas_limit, }; let state = State { contract_addr: deps.api.addr_canonicalize(env.contract.address.as_str())?, poll_count: 0, total_share: Uint128::zero(), total_deposit: Uint128::zero(), pending_voting_rewards: Uint128::zero(), }; config_store(deps.storage).save(&config)?; state_store(deps.storage).save(&state)?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> { match msg { ExecuteMsg::Receive(msg) => receive_cw20(deps, env, info, msg), ExecuteMsg::UpdateConfig { owner, effective_delay, default_poll_config, migration_poll_config, auth_admin_poll_config, voter_weight, snapshot_period, admin_manager, poll_gas_limit, } => update_config( deps, info, owner, effective_delay, default_poll_config, migration_poll_config, auth_admin_poll_config, voter_weight, snapshot_period, admin_manager, poll_gas_limit, ), ExecuteMsg::WithdrawVotingTokens { amount } => withdraw_voting_tokens(deps, info, amount), ExecuteMsg::WithdrawVotingRewards { poll_id } => { withdraw_voting_rewards(deps, info, poll_id) } ExecuteMsg::StakeVotingRewards { poll_id } => stake_voting_rewards(deps, info, poll_id), ExecuteMsg::CastVote { poll_id, vote, amount, } => cast_vote(deps, env, info, poll_id, vote, amount), ExecuteMsg::EndPoll { poll_id } => end_poll(deps, env, poll_id), ExecuteMsg::ExecutePoll { poll_id } => execute_poll(deps, env, poll_id), ExecuteMsg::SnapshotPoll { poll_id } => snapshot_poll(deps, env, poll_id), } } pub fn receive_cw20( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> StdResult<Response> { // only asset contract can execute this message let config: Config = config_read(deps.storage).load()?; if config.mirror_token != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } match from_binary(&cw20_msg.msg) { Ok(Cw20HookMsg::StakeVotingTokens {}) => { stake_voting_tokens(deps, cw20_msg.sender, cw20_msg.amount) } Ok(Cw20HookMsg::CreatePoll { title, description, link, execute_msg, admin_action, }) => create_poll( deps, env, cw20_msg.sender, cw20_msg.amount, title, description, link, execute_msg, admin_action, ), Ok(Cw20HookMsg::DepositReward {}) => deposit_reward(deps, cw20_msg.amount), Err(_) => Err(StdError::generic_err("invalid cw20 hook message")), } } #[cfg_attr(not(feature = "library"), entry_point)] pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> { match msg.id { POLL_EXECUTE_REPLY_ID => { let poll_id: u64 = read_tmp_poll_id(deps.storage)?; failed_poll(deps, poll_id) } _ => Err(StdError::generic_err("reply id is invalid")), } } #[allow(clippy::too_many_arguments)] pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, effective_delay: Option<u64>, default_poll_config: Option<PollConfig>, migration_poll_config: Option<PollConfig>, auth_admin_poll_config: Option<PollConfig>, voter_weight: Option<Decimal>, snapshot_period: Option<u64>, admin_manager: Option<String>, poll_gas_limit: Option<u64>, ) -> StdResult<Response> { let api = deps.api; config_store(deps.storage).update(|mut config| { if config.owner != api.addr_canonicalize(info.sender.as_str())? { return Err(StdError::generic_err("unauthorized")); } if let Some(owner) = owner { config.owner = api.addr_canonicalize(&owner)?; } if let Some(default_poll_config) = default_poll_config { validate_poll_config(&default_poll_config)?; config.default_poll_config = default_poll_config; } if let Some(migration_poll_config) = migration_poll_config { validate_poll_config(&migration_poll_config)?; config.migration_poll_config = migration_poll_config; } if let Some(auth_admin_poll_config) = auth_admin_poll_config { validate_poll_config(&auth_admin_poll_config)?; config.auth_admin_poll_config = auth_admin_poll_config; } if let Some(effective_delay) = effective_delay { config.effective_delay = effective_delay; } if let Some(voter_weight) = voter_weight { validate_voter_weight(voter_weight)?; config.voter_weight = voter_weight; } if let Some(snapshot_period) = snapshot_period { config.snapshot_period = snapshot_period; } if let Some(admin_manager) = admin_manager { config.admin_manager = api.addr_canonicalize(&admin_manager)?; } if let Some(poll_gas_limit) = poll_gas_limit { config.poll_gas_limit = poll_gas_limit; } Ok(config) })?; Ok(Response::default()) } /// validate_title returns an error if the title is invalid fn validate_title(title: &str) -> StdResult<()> { if title.len() < MIN_TITLE_LENGTH { Err(StdError::generic_err("Title too short")) } else if title.len() > MAX_TITLE_LENGTH { Err(StdError::generic_err("Title too long")) } else { Ok(()) } } /// validate_description returns an error if the description is invalid fn validate_description(description: &str) -> StdResult<()> { if description.len() < MIN_DESC_LENGTH { Err(StdError::generic_err("Description too short")) } else if description.len() > MAX_DESC_LENGTH { Err(StdError::generic_err("Description too long")) } else { Ok(()) } } /// validate_link returns an error if the link is invalid fn validate_link(link: &Option<String>) -> StdResult<()> { if let Some(link) = link { if link.len() < MIN_LINK_LENGTH { Err(StdError::generic_err("Link too short")) } else if link.len() > MAX_LINK_LENGTH { Err(StdError::generic_err("Link too long")) } else { Ok(()) } } else { Ok(()) } } fn validate_poll_config(poll_config: &PollConfig) -> StdResult<()> { validate_quorum(poll_config.quorum)?; validate_threshold(poll_config.threshold)?; Ok(()) } /// validate_quorum returns an error if the quorum is invalid /// (we require 0-1) fn validate_quorum(quorum: Decimal) -> StdResult<()> { if quorum > Decimal::one() { Err(StdError::generic_err("quorum must be 0 to 1")) } else { Ok(()) } } /// validate_threshold returns an error if the threshold is invalid /// (we require 0-1) fn validate_threshold(threshold: Decimal) -> StdResult<()> { if threshold > Decimal::one() { Err(StdError::generic_err("threshold must be 0 to 1")) } else { Ok(()) } } pub fn validate_voter_weight(voter_weight: Decimal) -> StdResult<()> { if voter_weight >= Decimal::one() { Err(StdError::generic_err("voter_weight must be smaller than 1")) } else { Ok(()) } } pub fn validate_migrations(api: &dyn Api, migrations: &[(String, u64, Binary)]) -> StdResult<()> { for (addr, _, _) in migrations.iter() { api.addr_validate(addr)?; } Ok(()) } /* * Creates a new poll */ #[allow(clippy::too_many_arguments)] pub fn create_poll( deps: DepsMut, env: Env, proposer: String, deposit_amount: Uint128, title: String, description: String, link: Option<String>, poll_execute_msg: Option<PollExecuteMsg>, poll_admin_action: Option<PollAdminAction>, ) -> StdResult<Response> { validate_title(&title)?; validate_description(&description)?; validate_link(&link)?; let config: Config = config_store(deps.storage).load()?; let current_seconds = env.block.time.seconds(); let (proposal_deposit, end_time, max_polls_in_progress) = match poll_admin_action.clone() { None => ( config.default_poll_config.proposal_deposit, current_seconds + config.default_poll_config.voting_period, MAX_POLLS_IN_PROGRESS, ), Some(PollAdminAction::ExecuteMigrations { migrations }) => { // check that contract addresses are valid validate_migrations(deps.api, &migrations)?; ( config.migration_poll_config.proposal_deposit, current_seconds + config.migration_poll_config.voting_period, MAX_POLLS_IN_PROGRESS + 10usize, // increase maximum to prevent mailcious users from authorizing migrations ) } // all other admin actions have the most restrictive parameters _ => ( config.auth_admin_poll_config.proposal_deposit, current_seconds + config.auth_admin_poll_config.voting_period, MAX_POLLS_IN_PROGRESS + 10usize, ), }; if deposit_amount < proposal_deposit { return Err(StdError::generic_err(format!( "Must deposit more than {} token", proposal_deposit ))); } let polls_in_progress: usize = read_polls( deps.storage, Some(PollStatus::InProgress), None, None, None, Some(true), )? .len(); if polls_in_progress.gt(&max_polls_in_progress) { return Err(StdError::generic_err("Too many polls in progress")); } let mut state: State = state_store(deps.storage).load()?; let poll_id = state.poll_count + 1; // Increase poll count & total deposit amount state.poll_count += 1; state.total_deposit += deposit_amount; let poll_execute_data = if let Some(poll_execute_msg) = poll_execute_msg { if poll_admin_action.is_some() { return Err(StdError::generic_err( "Can not make a poll with normal action and admin action", )); } let target_contract = deps.api.addr_canonicalize(&poll_execute_msg.contract)?; let contract_raw = deps.api.addr_canonicalize(env.contract.address.as_str())?; if target_contract.eq(&config.admin_manager) || target_contract.eq(&contract_raw) { return Err(StdError::generic_err( "Can not make a normal pool targeting the admin_manager or gov contract", )); } Some(ExecuteData { contract: target_contract, msg: poll_execute_msg.msg, }) } else { None }; let sender_address_raw = deps.api.addr_canonicalize(&proposer)?; let new_poll = Poll { id: poll_id, creator: sender_address_raw, status: PollStatus::InProgress, yes_votes: Uint128::zero(), no_votes: Uint128::zero(), abstain_votes: Uint128::zero(), end_time, title, description, link, execute_data: poll_execute_data, deposit_amount, total_balance_at_end_poll: None, voters_reward: Uint128::zero(), staked_amount: None, }; poll_store(deps.storage).save(&poll_id.to_be_bytes(), &new_poll)?; poll_indexer_store(deps.storage, &PollStatus::InProgress) .save(&poll_id.to_be_bytes(), &true)?; if let Some(poll_admin_action) = poll_admin_action { poll_additional_params_store(deps.storage).save( &poll_id.to_be_bytes(), &PollAdditionalParams { admin_action: poll_admin_action, }, )?; } state_store(deps.storage).save(&state)?; let r = Response::new().add_attributes(vec![ attr("action", "create_poll"), attr( "creator", deps.api.addr_humanize(&new_poll.creator)?.as_str(), ), attr("poll_id", &poll_id.to_string()), attr("end_time", new_poll.end_time.to_string()), ]); Ok(r) } /* * Ends a poll. */ pub fn end_poll(deps: DepsMut, env: Env, poll_id: u64) -> StdResult<Response> { let config: Config = config_store(deps.storage).load()?; let mut a_poll: Poll = poll_store(deps.storage).load(&poll_id.to_be_bytes())?; let (target_quorum, target_threshold, is_fast_track) = match poll_additional_params_read(deps.storage).load(&poll_id.to_be_bytes()) { Ok(params) => match params.admin_action { PollAdminAction::ExecuteMigrations { .. } => ( config.migration_poll_config.quorum, config.migration_poll_config.threshold, true, ), _ => ( config.auth_admin_poll_config.quorum, config.auth_admin_poll_config.threshold, false, ), }, _ => ( config.default_poll_config.quorum, config.default_poll_config.threshold, false, ), }; if a_poll.status != PollStatus::InProgress { return Err(StdError::generic_err("Poll is not in progress")); } let current_seconds = env.block.time.seconds(); if a_poll.end_time > current_seconds && !is_fast_track { return Err(StdError::generic_err("Voting period has not expired")); } let no = a_poll.no_votes.u128(); let yes = a_poll.yes_votes.u128(); let abstain = a_poll.abstain_votes.u128(); let tallied_weight = yes + no + abstain; let mut poll_status = PollStatus::Rejected; let mut rejected_reason = ""; let mut passed = false; let mut messages: Vec<CosmosMsg> = vec![]; let mut state: State = state_read(deps.storage).load()?; let (quorum, staked_weight) = if state.total_share.u128() == 0 { (Decimal::zero(), Uint128::zero()) } else if let Some(staked_amount) = a_poll.staked_amount { ( Decimal::from_ratio(tallied_weight, staked_amount), staked_amount, ) } else { let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let staked_weight = load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance)?; ( Decimal::from_ratio(tallied_weight, staked_weight), staked_weight, ) }; if tallied_weight == 0 || quorum < target_quorum { // Quorum: More than quorum of the total staked tokens at the end of the voting // period need to have participated in the vote. rejected_reason = "Quorum not reached"; } else { if yes != 0u128 && Decimal::from_ratio(yes, yes + no) > target_threshold { //Threshold: More than 50% of the tokens that participated in the vote // (after excluding “Abstain” votes) need to have voted in favor of the proposal (“Yes”). poll_status = PollStatus::Passed; passed = true; } else { rejected_reason = "Threshold not reached"; } // Refunds deposit only when quorum is reached if !a_poll.deposit_amount.is_zero() { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.mirror_token)?.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: deps.api.addr_humanize(&a_poll.creator)?.to_string(), amount: a_poll.deposit_amount, })?, })) } } // if the poll is fast track and is rejected, we return error instead of updating state // the poll can still pass until the poll end_time if poll_status.eq(&PollStatus::Rejected) && is_fast_track && a_poll.end_time > current_seconds { return Err(StdError::generic_err( "Fastrack poll has not reached the target quorum or threshold", )); } // Decrease total deposit amount state.total_deposit = state.total_deposit.checked_sub(a_poll.deposit_amount)?; state_store(deps.storage).save(&state)?; // Update poll indexer poll_indexer_store(deps.storage, &PollStatus::InProgress).remove(&a_poll.id.to_be_bytes()); poll_indexer_store(deps.storage, &poll_status).save(&a_poll.id.to_be_bytes(), &true)?; // Update poll status a_poll.status = poll_status; a_poll.total_balance_at_end_poll = Some(staked_weight); poll_store(deps.storage).save(&poll_id.to_be_bytes(), &a_poll)?; Ok(Response::new().add_messages(messages).add_attributes(vec![ attr("action", "end_poll"), attr("poll_id", &poll_id.to_string()), attr("rejected_reason", rejected_reason), attr("passed", &passed.to_string()), ])) } /* * Execute a msg of passed poll. */ pub fn execute_poll(deps: DepsMut, env: Env, poll_id: u64) -> StdResult<Response> { let config: Config = config_read(deps.storage).load()?; let mut a_poll: Poll = poll_store(deps.storage).load(&poll_id.to_be_bytes())?; let (is_fast_track, admin_msg) = match poll_additional_params_read(deps.storage).load(&poll_id.to_be_bytes()) { Ok(params) => match params.admin_action { PollAdminAction::ExecuteMigrations { .. } => (true, Some(params.admin_action)), _ => (false, Some(params.admin_action)), }, _ => (false, None), }; if a_poll.status != PollStatus::Passed { return Err(StdError::generic_err("Poll is not in passed status")); } let current_seconds = env.block.time.seconds(); if !is_fast_track && a_poll.end_time + config.effective_delay > current_seconds { return Err(StdError::generic_err("Effective delay has not expired")); } poll_indexer_store(deps.storage, &PollStatus::Passed).remove(&poll_id.to_be_bytes()); poll_indexer_store(deps.storage, &PollStatus::Executed).save(&poll_id.to_be_bytes(), &true)?; a_poll.status = PollStatus::Executed; poll_store(deps.storage).save(&poll_id.to_be_bytes(), &a_poll)?; // if is not possible to create a poll with both admin_msg and execute_data, only one per poll let execute_msg: CosmosMsg = if let Some(execute_data) = a_poll.execute_data { CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&execute_data.contract)?.to_string(), msg: execute_data.msg, funds: vec![], }) } else if let Some(admin_msg) = admin_msg { match admin_msg { PollAdminAction::UpdateConfig { .. } => CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&admin_msg)?, funds: vec![], }), _ => CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.admin_manager)?.to_string(), msg: to_binary(&admin_msg)?, funds: vec![], }), } } else { return Err(StdError::generic_err("The poll does not have execute_data")); }; // the execution will reply in case of failure, to mark the poll as failed let execute_submsg = SubMsg { msg: execute_msg, gas_limit: Some(config.poll_gas_limit), id: POLL_EXECUTE_REPLY_ID, reply_on: ReplyOn::Error, }; store_tmp_poll_id(deps.storage, a_poll.id)?; Ok(Response::new() .add_submessage(execute_submsg) .add_attributes(vec![ attr("action", "execute_poll"), attr("poll_id", poll_id.to_string()), ])) } /* * If the executed message of a passed poll fails, it is marked as failed */ pub fn failed_poll(deps: DepsMut, poll_id: u64) -> StdResult<Response> { let mut a_poll: Poll = poll_store(deps.storage).load(&poll_id.to_be_bytes())?; poll_indexer_store(deps.storage, &PollStatus::Executed).remove(&poll_id.to_be_bytes()); poll_indexer_store(deps.storage, &PollStatus::Failed).save(&poll_id.to_be_bytes(), &true)?; a_poll.status = PollStatus::Failed; poll_store(deps.storage).save(&poll_id.to_be_bytes(), &a_poll)?; Ok(Response::new().add_attribute("action", "failed_poll")) } /* * User casts a vote on the provided poll id */ pub fn cast_vote( deps: DepsMut, env: Env, info: MessageInfo, poll_id: u64, vote: VoteOption, amount: Uint128, ) -> StdResult<Response> { let sender_address_raw = deps.api.addr_canonicalize(info.sender.as_str())?; let config = config_read(deps.storage).load()?; let state = state_read(deps.storage).load()?; if poll_id == 0 || state.poll_count < poll_id { return Err(StdError::generic_err("Poll does not exist")); } let mut a_poll: Poll = poll_store(deps.storage).load(&poll_id.to_be_bytes())?; let current_seconds = env.block.time.seconds(); if a_poll.status != PollStatus::InProgress || current_seconds > a_poll.end_time { return Err(StdError::generic_err("Poll is not in progress")); } // Check the voter already has a vote on the poll if poll_voter_read(deps.storage, poll_id) .load(sender_address_raw.as_slice()) .is_ok() { return Err(StdError::generic_err("User has already voted.")); } let key = &sender_address_raw.as_slice(); let mut token_manager = bank_read(deps.storage).may_load(key)?.unwrap_or_default(); // convert share to amount let total_share = state.total_share; let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let total_balance = load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance)?; if token_manager .share .multiply_ratio(total_balance, total_share) < amount { return Err(StdError::generic_err( "User does not have enough staked tokens.", )); } // update tally info match vote { VoteOption::Yes => a_poll.yes_votes += amount, VoteOption::No => a_poll.no_votes += amount, VoteOption::Abstain => a_poll.abstain_votes += amount, } let vote_info = VoterInfo { vote, balance: amount, }; token_manager .locked_balance .push((poll_id, vote_info.clone())); token_manager.participated_polls = vec![]; bank_store(deps.storage).save(key, &token_manager)?; // store poll voter && and update poll data poll_voter_store(deps.storage, poll_id).save(sender_address_raw.as_slice(), &vote_info)?; // processing snapshot let time_to_end = a_poll.end_time - current_seconds; if time_to_end < config.snapshot_period && a_poll.staked_amount.is_none() { a_poll.staked_amount = Some(total_balance); } poll_store(deps.storage).save(&poll_id.to_be_bytes(), &a_poll)?; Ok(Response::new().add_attributes(vec![ attr("action", "cast_vote"), attr("poll_id", &poll_id.to_string()), attr("amount", &amount.to_string()), attr("voter", &info.sender.to_string()), attr("vote_option", vote_info.vote.to_string()), ])) } /* * SnapshotPoll is used to take a snapshot of the staked amount for quorum calculation */ pub fn snapshot_poll(deps: DepsMut, env: Env, poll_id: u64) -> StdResult<Response> { let config: Config = config_read(deps.storage).load()?; let mut a_poll: Poll = poll_store(deps.storage).load(&poll_id.to_be_bytes())?; if a_poll.status != PollStatus::InProgress { return Err(StdError::generic_err("Poll is not in progress")); } let current_seconds = env.block.time.seconds(); let time_to_end = a_poll.end_time - current_seconds; if time_to_end > config.snapshot_period { return Err(StdError::generic_err("Cannot snapshot at this time")); } if a_poll.staked_amount.is_some() { return Err(StdError::generic_err("Snapshot has already occurred")); } // store the current staked amount for quorum calculation let state: State = state_store(deps.storage).load()?; let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let staked_amount = load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance)?; a_poll.staked_amount = Some(staked_amount); poll_store(deps.storage).save(&poll_id.to_be_bytes(), &a_poll)?; Ok(Response::new().add_attributes(vec![ attr("action", "snapshot_poll"), attr("poll_id", poll_id.to_string()), attr("staked_amount", staked_amount), ])) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), QueryMsg::State {} => to_binary(&query_state(deps)?), QueryMsg::Staker { address } => to_binary(&query_staker(deps, address)?), QueryMsg::Poll { poll_id } => to_binary(&query_poll(deps, poll_id)?), QueryMsg::Polls { filter, start_after, limit, order_by, } => to_binary(&query_polls(deps, filter, start_after, limit, order_by)?), QueryMsg::Voter { poll_id, address } => to_binary(&query_voter(deps, poll_id, address)?), QueryMsg::Voters { poll_id, start_after, limit, order_by, } => to_binary(&query_voters(deps, poll_id, start_after, limit, order_by)?), QueryMsg::Shares { start_after, limit, order_by, } => to_binary(&query_shares(deps, start_after, limit, order_by)?), } } fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let config: Config = config_read(deps.storage).load()?; Ok(ConfigResponse { owner: deps.api.addr_humanize(&config.owner)?.to_string(), mirror_token: deps.api.addr_humanize(&config.mirror_token)?.to_string(), effective_delay: config.effective_delay, default_poll_config: config.default_poll_config, migration_poll_config: config.migration_poll_config, auth_admin_poll_config: config.auth_admin_poll_config, voter_weight: config.voter_weight, snapshot_period: config.snapshot_period, admin_manager: deps.api.addr_humanize(&config.admin_manager)?.to_string(), poll_gas_limit: config.poll_gas_limit, }) } fn query_state(deps: Deps) -> StdResult<StateResponse> { let state: State = state_read(deps.storage).load()?; Ok(StateResponse { poll_count: state.poll_count, total_share: state.total_share, total_deposit: state.total_deposit, pending_voting_rewards: state.pending_voting_rewards, }) } fn query_poll(deps: Deps, poll_id: u64) -> StdResult<PollResponse> { let poll = match poll_read(deps.storage).may_load(&poll_id.to_be_bytes())? { Some(poll) => poll, None => return Err(StdError::generic_err("Poll does not exist")), }; let admin_action = poll_additional_params_read(deps.storage) .load(&poll_id.to_be_bytes()) .map(|params| Some(params.admin_action)) .unwrap_or_default(); Ok(PollResponse { id: poll.id, creator: deps.api.addr_humanize(&poll.creator).unwrap().to_string(), status: poll.status, end_time: poll.end_time, title: poll.title, description: poll.description, link: poll.link, deposit_amount: poll.deposit_amount, execute_data: if let Some(execute_data) = poll.execute_data { Some(PollExecuteMsg { contract: deps.api.addr_humanize(&execute_data.contract)?.to_string(), msg: execute_data.msg, }) } else { None }, yes_votes: poll.yes_votes, no_votes: poll.no_votes, abstain_votes: poll.abstain_votes, total_balance_at_end_poll: poll.total_balance_at_end_poll, voters_reward: poll.voters_reward, staked_amount: poll.staked_amount, admin_action, }) } fn query_polls( deps: Deps, filter: Option<PollStatus>, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<PollsResponse> { let polls = read_polls(deps.storage, filter, start_after, limit, order_by, None)?; let poll_responses: StdResult<Vec<PollResponse>> = polls .iter() .map(|poll| { let admin_action = poll_additional_params_read(deps.storage) .load(&poll.id.to_be_bytes()) .map(|params| Some(params.admin_action)) .unwrap_or_default(); Ok(PollResponse { id: poll.id, creator: deps.api.addr_humanize(&poll.creator).unwrap().to_string(), status: poll.status.clone(), end_time: poll.end_time, title: poll.title.to_string(), description: poll.description.to_string(), link: poll.link.clone(), deposit_amount: poll.deposit_amount, execute_data: if let Some(execute_data) = poll.execute_data.clone() { Some(PollExecuteMsg { contract: deps.api.addr_humanize(&execute_data.contract)?.to_string(),
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
true
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/lib.rs
contracts/mirror_gov/src/lib.rs
pub mod contract; mod migrate; mod querier; mod staking; pub mod state; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/migrate.rs
contracts/mirror_gov/src/migrate.rs
use cosmwasm_std::{CanonicalAddr, Decimal, DepsMut, StdResult, Uint128}; use cosmwasm_storage::{singleton, singleton_read, ReadonlySingleton, Singleton}; use mirror_protocol::gov::PollConfig; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::state::{Config, KEY_CONFIG}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyConfig { pub owner: CanonicalAddr, pub mirror_token: CanonicalAddr, pub quorum: Decimal, pub threshold: Decimal, pub voting_period: u64, pub effective_delay: u64, pub expiration_period: u64, // deprecated, to remove on next state migration pub proposal_deposit: Uint128, pub voter_weight: Decimal, pub snapshot_period: u64, } pub fn migrate_config( deps: DepsMut, migration_poll_config: PollConfig, auth_admin_poll_config: PollConfig, admin_manager: String, poll_gas_limit: u64, ) -> StdResult<()> { let legacty_store: ReadonlySingleton<LegacyConfig> = singleton_read(deps.storage, KEY_CONFIG); let legacy_config: LegacyConfig = legacty_store.load()?; let config = Config { mirror_token: legacy_config.mirror_token, owner: legacy_config.owner, effective_delay: legacy_config.effective_delay, voter_weight: legacy_config.voter_weight, snapshot_period: legacy_config.snapshot_period, default_poll_config: PollConfig { proposal_deposit: legacy_config.proposal_deposit, voting_period: legacy_config.voting_period, quorum: legacy_config.quorum, threshold: legacy_config.threshold, }, migration_poll_config, auth_admin_poll_config, admin_manager: deps.api.addr_canonicalize(&admin_manager)?, poll_gas_limit, }; let mut store: Singleton<Config> = singleton(deps.storage, KEY_CONFIG); store.save(&config)?; Ok(()) } #[cfg(test)] mod migrate_tests { use crate::state::config_read; use super::*; use cosmwasm_std::{testing::mock_dependencies, Api, Storage}; pub fn config_old_store(storage: &mut dyn Storage) -> Singleton<LegacyConfig> { Singleton::new(storage, KEY_CONFIG) } #[test] fn test_config_migration() { let mut deps = mock_dependencies(&[]); let mut legacy_config_store = config_old_store(&mut deps.storage); legacy_config_store .save(&LegacyConfig { mirror_token: deps.api.addr_canonicalize("mir0000").unwrap(), owner: deps.api.addr_canonicalize("owner0000").unwrap(), quorum: Decimal::one(), threshold: Decimal::one(), voting_period: 100u64, effective_delay: 100u64, expiration_period: 100u64, proposal_deposit: Uint128::from(100000u128), voter_weight: Decimal::percent(50), snapshot_period: 20u64, }) .unwrap(); let migration_poll_config = PollConfig { quorum: Decimal::percent(60), threshold: Decimal::percent(60), proposal_deposit: Uint128::from(99999u128), voting_period: 888u64, }; let auth_admin_poll_config = PollConfig { quorum: Decimal::percent(70), threshold: Decimal::percent(70), proposal_deposit: Uint128::from(99999000u128), voting_period: 88800u64, }; migrate_config( deps.as_mut(), migration_poll_config.clone(), auth_admin_poll_config.clone(), "admin_manager".to_string(), 4_000_000u64, ) .unwrap(); let config: Config = config_read(&deps.storage).load().unwrap(); assert_eq!( config, Config { mirror_token: deps.api.addr_canonicalize("mir0000").unwrap(), owner: deps.api.addr_canonicalize("owner0000").unwrap(), default_poll_config: PollConfig { quorum: Decimal::one(), threshold: Decimal::one(), voting_period: 100u64, proposal_deposit: Uint128::from(100000u128), }, migration_poll_config, auth_admin_poll_config, effective_delay: 100u64, voter_weight: Decimal::percent(50u64), snapshot_period: 20u64, admin_manager: deps.api.addr_canonicalize("admin_manager").unwrap(), poll_gas_limit: 4_000_000u64, } ) } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/state.rs
contracts/mirror_gov/src/state.rs
use cosmwasm_std::{Binary, CanonicalAddr, Decimal, StdResult, Storage, Uint128}; use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, Bucket, ReadonlyBucket, ReadonlySingleton, Singleton, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use mirror_protocol::common::OrderBy; use mirror_protocol::gov::{PollAdminAction, PollConfig, PollStatus, VoterInfo}; pub static KEY_CONFIG: &[u8] = b"config"; static KEY_STATE: &[u8] = b"state"; static KEY_TMP_POLL_ID: &[u8] = b"tmp_poll_id"; static PREFIX_POLL_INDEXER: &[u8] = b"poll_indexer"; static PREFIX_POLL_VOTER: &[u8] = b"poll_voter"; static PREFIX_POLL: &[u8] = b"poll"; static PREFIX_BANK: &[u8] = b"bank"; static PREFIX_POLL_ADDITIONAL_PARAMS: &[u8] = b"poll_additional_params"; const MAX_LIMIT: u32 = 30; const DEFAULT_LIMIT: u32 = 10; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub mirror_token: CanonicalAddr, pub effective_delay: u64, pub default_poll_config: PollConfig, pub migration_poll_config: PollConfig, pub auth_admin_poll_config: PollConfig, pub voter_weight: Decimal, pub snapshot_period: u64, pub admin_manager: CanonicalAddr, pub poll_gas_limit: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct State { pub contract_addr: CanonicalAddr, pub poll_count: u64, pub total_share: Uint128, pub total_deposit: Uint128, pub pending_voting_rewards: Uint128, } #[derive(Default, Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct TokenManager { pub share: Uint128, // total staked balance pub locked_balance: Vec<(u64, VoterInfo)>, // maps poll_id to weight voted pub participated_polls: Vec<u64>, // poll_id } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Poll { pub id: u64, pub creator: CanonicalAddr, pub status: PollStatus, pub yes_votes: Uint128, pub no_votes: Uint128, pub abstain_votes: Uint128, pub end_time: u64, pub title: String, pub description: String, pub link: Option<String>, pub execute_data: Option<ExecuteData>, pub deposit_amount: Uint128, /// Total balance at the end poll pub total_balance_at_end_poll: Option<Uint128>, pub voters_reward: Uint128, pub staked_amount: Option<Uint128>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PollAdditionalParams { pub admin_action: PollAdminAction, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ExecuteData { pub contract: CanonicalAddr, pub msg: Binary, } pub fn store_tmp_poll_id(storage: &mut dyn Storage, tmp_poll_id: u64) -> StdResult<()> { singleton(storage, KEY_TMP_POLL_ID).save(&tmp_poll_id) } pub fn read_tmp_poll_id(storage: &dyn Storage) -> StdResult<u64> { singleton_read(storage, KEY_TMP_POLL_ID).load() } pub fn config_store(storage: &mut dyn Storage) -> Singleton<Config> { singleton(storage, KEY_CONFIG) } pub fn config_read(storage: &dyn Storage) -> ReadonlySingleton<Config> { singleton_read(storage, KEY_CONFIG) } pub fn state_store(storage: &mut dyn Storage) -> Singleton<State> { singleton(storage, KEY_STATE) } pub fn state_read(storage: &dyn Storage) -> ReadonlySingleton<State> { singleton_read(storage, KEY_STATE) } pub fn poll_store(storage: &mut dyn Storage) -> Bucket<Poll> { bucket(storage, PREFIX_POLL) } pub fn poll_read(storage: &dyn Storage) -> ReadonlyBucket<Poll> { bucket_read(storage, PREFIX_POLL) } pub fn poll_additional_params_store(storage: &mut dyn Storage) -> Bucket<PollAdditionalParams> { bucket(storage, PREFIX_POLL_ADDITIONAL_PARAMS) } pub fn poll_additional_params_read(storage: &dyn Storage) -> ReadonlyBucket<PollAdditionalParams> { bucket_read(storage, PREFIX_POLL_ADDITIONAL_PARAMS) } pub fn poll_indexer_store<'a>( storage: &'a mut dyn Storage, status: &PollStatus, ) -> Bucket<'a, bool> { Bucket::multilevel( storage, &[PREFIX_POLL_INDEXER, status.to_string().as_bytes()], ) } pub fn poll_voter_store(storage: &mut dyn Storage, poll_id: u64) -> Bucket<VoterInfo> { Bucket::multilevel(storage, &[PREFIX_POLL_VOTER, &poll_id.to_be_bytes()]) } pub fn poll_voter_read(storage: &dyn Storage, poll_id: u64) -> ReadonlyBucket<VoterInfo> { ReadonlyBucket::multilevel(storage, &[PREFIX_POLL_VOTER, &poll_id.to_be_bytes()]) } pub fn read_poll_voters<'a>( storage: &'a dyn Storage, poll_id: u64, start_after: Option<CanonicalAddr>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<(CanonicalAddr, VoterInfo)>> { let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start_addr(start_after), None, OrderBy::Asc), _ => (None, calc_range_end_addr(start_after), OrderBy::Desc), }; let voters: ReadonlyBucket<'a, VoterInfo> = ReadonlyBucket::multilevel(storage, &[PREFIX_POLL_VOTER, &poll_id.to_be_bytes()]); voters .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (k, v) = item?; Ok((CanonicalAddr::from(k), v)) }) .collect() } pub fn read_polls<'a>( storage: &'a dyn Storage, filter: Option<PollStatus>, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, remove_hard_cap: Option<bool>, ) -> StdResult<Vec<Poll>> { let mut limit: usize = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; if let Some(remove_hard_cap) = remove_hard_cap { if remove_hard_cap { limit = usize::MAX; } } let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start(start_after), None, OrderBy::Asc), _ => (None, calc_range_end(start_after), OrderBy::Desc), }; if let Some(status) = filter { let poll_indexer: ReadonlyBucket<'a, bool> = ReadonlyBucket::multilevel( storage, &[PREFIX_POLL_INDEXER, status.to_string().as_bytes()], ); poll_indexer .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (k, _) = item?; poll_read(storage).load(&k) }) .collect() } else { let polls: ReadonlyBucket<'a, Poll> = ReadonlyBucket::new(storage, PREFIX_POLL); polls .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (_, v) = item?; Ok(v) }) .collect() } } pub fn bank_store(storage: &mut dyn Storage) -> Bucket<TokenManager> { bucket(storage, PREFIX_BANK) } pub fn bank_read(storage: &dyn Storage) -> ReadonlyBucket<TokenManager> { bucket_read(storage, PREFIX_BANK) } pub fn read_bank_stakers<'a>( storage: &'a dyn Storage, start_after: Option<CanonicalAddr>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<Vec<(CanonicalAddr, TokenManager)>> { let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let (start, end, order_by) = match order_by { Some(OrderBy::Asc) => (calc_range_start_addr(start_after), None, OrderBy::Asc), _ => (None, calc_range_end_addr(start_after), OrderBy::Desc), }; let stakers: ReadonlyBucket<'a, TokenManager> = ReadonlyBucket::new(storage, PREFIX_BANK); stakers .range(start.as_deref(), end.as_deref(), order_by.into()) .take(limit) .map(|item| { let (k, v) = item?; Ok((CanonicalAddr::from(k), v)) }) .collect() } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_start(start_after: Option<u64>) -> Option<Vec<u8>> { start_after.map(|id| { let mut v = id.to_be_bytes().to_vec(); v.push(1); v }) } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_end(start_after: Option<u64>) -> Option<Vec<u8>> { start_after.map(|id| id.to_be_bytes().to_vec()) } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_start_addr(start_after: Option<CanonicalAddr>) -> Option<Vec<u8>> { start_after.map(|addr| { let mut v = addr.as_slice().to_vec(); v.push(1); v }) } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_end_addr(start_after: Option<CanonicalAddr>) -> Option<Vec<u8>> { start_after.map(|addr| addr.as_slice().to_vec()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/staking.rs
contracts/mirror_gov/src/staking.rs
use crate::querier::load_token_balance; use crate::state::{ bank_read, bank_store, config_read, config_store, poll_read, poll_store, poll_voter_read, poll_voter_store, read_bank_stakers, read_polls, state_read, state_store, Config, Poll, State, TokenManager, }; use cosmwasm_std::{ attr, to_binary, CanonicalAddr, CosmosMsg, Deps, DepsMut, MessageInfo, Response, StdError, StdResult, Storage, Uint128, WasmMsg, }; use cw20::Cw20ExecuteMsg; use mirror_protocol::common::OrderBy; use mirror_protocol::gov::{ PollStatus, SharesResponse, SharesResponseItem, StakerResponse, VoterInfo, }; pub fn stake_voting_tokens(deps: DepsMut, sender: String, amount: Uint128) -> StdResult<Response> { if amount.is_zero() { return Err(StdError::generic_err("Insufficient funds sent")); } let sender_address_raw = deps.api.addr_canonicalize(&sender)?; let key = &sender_address_raw.as_slice(); let mut token_manager = bank_read(deps.storage).may_load(key)?.unwrap_or_default(); let config: Config = config_store(deps.storage).load()?; let mut state: State = state_store(deps.storage).load()?; // balance already increased, so subtract deposit amount let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let total_balance = load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance + amount)?; let share = if total_balance.is_zero() || state.total_share.is_zero() { amount } else { amount.multiply_ratio(state.total_share, total_balance) }; token_manager.share += share; state.total_share += share; state_store(deps.storage).save(&state)?; bank_store(deps.storage).save(key, &token_manager)?; Ok(Response::new().add_attributes(vec![ attr("action", "staking"), attr("sender", sender.as_str()), attr("share", share.to_string()), attr("amount", amount.to_string()), ])) } // Withdraw amount if not staked. By default all funds will be withdrawn. pub fn withdraw_voting_tokens( deps: DepsMut, info: MessageInfo, amount: Option<Uint128>, ) -> StdResult<Response> { let sender_address_raw = deps.api.addr_canonicalize(info.sender.as_str())?; let key = sender_address_raw.as_slice(); if let Some(mut token_manager) = bank_read(deps.storage).may_load(key)? { let config: Config = config_store(deps.storage).load()?; let mut state: State = state_store(deps.storage).load()?; // Load total share & total balance except proposal deposit amount let total_share = state.total_share.u128(); let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let total_balance = (load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance))? .u128(); let user_locked_balance = compute_locked_balance(deps.storage, &mut token_manager, &sender_address_raw)?; let user_locked_share = user_locked_balance * total_share / total_balance; let user_share = token_manager.share.u128(); let withdraw_share = amount .map(|v| std::cmp::max(v.multiply_ratio(total_share, total_balance).u128(), 1u128)) .unwrap_or_else(|| user_share - user_locked_share); let withdraw_amount = amount .map(|v| v.u128()) .unwrap_or_else(|| withdraw_share * total_balance / total_share); if user_locked_share + withdraw_share > user_share { Err(StdError::generic_err( "User is trying to withdraw too many tokens.", )) } else { let share = user_share - withdraw_share; token_manager.share = Uint128::from(share); bank_store(deps.storage).save(key, &token_manager)?; state.total_share = Uint128::from(total_share - withdraw_share); state_store(deps.storage).save(&state)?; send_tokens( deps, &config.mirror_token, &sender_address_raw, withdraw_amount, "withdraw", ) } } else { Err(StdError::generic_err("Nothing staked")) } } // returns the largest locked amount in participated polls. fn compute_locked_balance( storage: &mut dyn Storage, token_manager: &mut TokenManager, voter: &CanonicalAddr, ) -> StdResult<u128> { // filter out not in-progress polls and get max locked let mut lock_entries_to_remove: Vec<u64> = vec![]; let max_locked = token_manager .locked_balance .iter() .filter(|(poll_id, _)| { let poll: Poll = poll_read(storage).load(&poll_id.to_be_bytes()).unwrap(); // cleanup not needed information, voting info in polls with no rewards if poll.status != PollStatus::InProgress && poll.voters_reward.is_zero() { poll_voter_store(storage, *poll_id).remove(voter.as_slice()); lock_entries_to_remove.push(*poll_id); } poll.status == PollStatus::InProgress }) .map(|(_, v)| v.balance.u128()) .max() .unwrap_or_default(); // cleanup, check if there was any voter info removed token_manager .locked_balance .retain(|(poll_id, _)| !lock_entries_to_remove.contains(poll_id)); Ok(max_locked) } pub fn deposit_reward(deps: DepsMut, amount: Uint128) -> StdResult<Response> { let config = config_read(deps.storage).load()?; let mut polls_in_progress = read_polls( deps.storage, Some(PollStatus::InProgress), None, None, None, Some(true), // remove hard cap to get all polls )?; if config.voter_weight.is_zero() || polls_in_progress.is_empty() { return Ok(Response::new().add_attributes(vec![ attr("action", "deposit_reward"), attr("amount", amount.to_string()), ])); } let voter_rewards = amount * config.voter_weight; let rewards_per_poll = voter_rewards.multiply_ratio(Uint128::new(1), polls_in_progress.len() as u128); if rewards_per_poll.is_zero() { return Err(StdError::generic_err("Reward deposited is too small")); } for poll in polls_in_progress.iter_mut() { poll.voters_reward += rewards_per_poll; poll_store(deps.storage) .save(&poll.id.to_be_bytes(), poll) .unwrap() } state_store(deps.storage).update(|mut state| -> StdResult<_> { state.pending_voting_rewards += voter_rewards; Ok(state) })?; Ok(Response::new().add_attributes(vec![ attr("action", "deposit_reward"), attr("amount", amount.to_string()), ])) } pub fn withdraw_voting_rewards( deps: DepsMut, info: MessageInfo, poll_id: Option<u64>, ) -> StdResult<Response> { let config: Config = config_store(deps.storage).load()?; let sender_address_raw = deps.api.addr_canonicalize(info.sender.as_str())?; let key = sender_address_raw.as_slice(); let mut token_manager = bank_read(deps.storage) .load(key) .map_err(|_| StdError::generic_err("Nothing staked"))?; let (user_reward_amount, w_polls) = withdraw_user_voting_rewards(deps.storage, &sender_address_raw, &token_manager, poll_id)?; if user_reward_amount.eq(&0u128) { return Err(StdError::generic_err("Nothing to withdraw")); } // cleanup, remove from locked_balance the polls from which we withdrew the rewards token_manager .locked_balance .retain(|(poll_id, _)| !w_polls.contains(poll_id)); bank_store(deps.storage).save(key, &token_manager)?; state_store(deps.storage).update(|mut state| -> StdResult<_> { state.pending_voting_rewards = state .pending_voting_rewards .checked_sub(Uint128::new(user_reward_amount))?; Ok(state) })?; send_tokens( deps, &config.mirror_token, &sender_address_raw, user_reward_amount, "withdraw_voting_rewards", ) } pub fn stake_voting_rewards( deps: DepsMut, info: MessageInfo, poll_id: Option<u64>, ) -> StdResult<Response> { let config: Config = config_store(deps.storage).load()?; let mut state: State = state_store(deps.storage).load()?; let sender_address_raw = deps.api.addr_canonicalize(info.sender.as_str())?; let key = sender_address_raw.as_slice(); let mut token_manager = bank_read(deps.storage) .load(key) .map_err(|_| StdError::generic_err("Nothing staked"))?; let (user_reward_amount, w_polls) = withdraw_user_voting_rewards(deps.storage, &sender_address_raw, &token_manager, poll_id)?; if user_reward_amount.eq(&0u128) { return Err(StdError::generic_err("Nothing to withdraw")); } // add the withdrawn rewards to stake pool and calculate share let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let total_balance = load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance)?; state.pending_voting_rewards = state .pending_voting_rewards .checked_sub(Uint128::new(user_reward_amount))?; let share: Uint128 = if total_balance.is_zero() || state.total_share.is_zero() { Uint128::new(user_reward_amount) } else { Uint128::new(user_reward_amount).multiply_ratio(state.total_share, total_balance) }; token_manager.share += share; state.total_share += share; // cleanup, remove from locked_balance the polls from which we withdrew the rewards token_manager .locked_balance .retain(|(poll_id, _)| !w_polls.contains(poll_id)); state_store(deps.storage).save(&state)?; bank_store(deps.storage).save(key, &token_manager)?; Ok(Response::new().add_attributes(vec![ attr("action", "stake_voting_rewards"), attr("staker", info.sender.as_str()), attr("share", share.to_string()), attr("amount", user_reward_amount.to_string()), ])) } fn withdraw_user_voting_rewards( storage: &mut dyn Storage, user_address: &CanonicalAddr, token_manager: &TokenManager, poll_id: Option<u64>, ) -> StdResult<(u128, Vec<u64>)> { let w_polls: Vec<(Poll, VoterInfo)> = match poll_id { Some(poll_id) => { let poll: Poll = poll_read(storage).load(&poll_id.to_be_bytes())?; let voter_info = poll_voter_read(storage, poll_id).load(user_address.as_slice())?; if poll.status == PollStatus::InProgress { return Err(StdError::generic_err("This poll is still in progress")); } if poll.voters_reward.is_zero() { return Err(StdError::generic_err("This poll has no voting rewards")); } vec![(poll, voter_info)] } None => get_withdrawable_polls(storage, token_manager, user_address), }; let user_reward_amount: u128 = w_polls .iter() .map(|(poll, voting_info)| { // remove voter info from the poll poll_voter_store(storage, poll.id).remove(user_address.as_slice()); // calculate reward share let total_votes = poll.no_votes.u128() + poll.yes_votes.u128() + poll.abstain_votes.u128(); let poll_voting_reward = poll .voters_reward .multiply_ratio(voting_info.balance, total_votes); poll_voting_reward.u128() }) .sum(); Ok(( user_reward_amount, w_polls.iter().map(|(poll, _)| poll.id).collect(), )) } fn get_withdrawable_polls( storage: &dyn Storage, token_manager: &TokenManager, user_address: &CanonicalAddr, ) -> Vec<(Poll, VoterInfo)> { let w_polls: Vec<(Poll, VoterInfo)> = token_manager .locked_balance .iter() .map(|(poll_id, _)| { let poll: Poll = poll_read(storage).load(&poll_id.to_be_bytes()).unwrap(); let voter_info_res: StdResult<VoterInfo> = poll_voter_read(storage, *poll_id).load(user_address.as_slice()); (poll, voter_info_res) }) .filter(|(poll, voter_info_res)| { poll.status != PollStatus::InProgress && voter_info_res.is_ok() && !poll.voters_reward.is_zero() }) .map(|(poll, voter_info_res)| (poll, voter_info_res.unwrap())) .collect(); w_polls } fn send_tokens( deps: DepsMut, asset_token: &CanonicalAddr, recipient: &CanonicalAddr, amount: u128, action: &str, ) -> StdResult<Response> { let contract_human = deps.api.addr_humanize(asset_token)?.to_string(); let recipient_human = deps.api.addr_humanize(recipient)?.to_string(); let attributes = vec![ attr("action", action), attr("recipient", recipient_human.as_str()), attr("amount", &amount.to_string()), ]; let r = Response::new() .add_attributes(attributes) .add_message(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: contract_human, msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: recipient_human, amount: Uint128::from(amount), })?, funds: vec![], })); Ok(r) } pub fn query_staker(deps: Deps, address: String) -> StdResult<StakerResponse> { let addr_raw = deps.api.addr_canonicalize(&address).unwrap(); let config: Config = config_read(deps.storage).load()?; let state: State = state_read(deps.storage).load()?; let mut token_manager = bank_read(deps.storage) .may_load(addr_raw.as_slice())? .unwrap_or_default(); // calculate pending voting rewards let w_polls: Vec<(Poll, VoterInfo)> = get_withdrawable_polls(deps.storage, &token_manager, &addr_raw); let mut user_reward_amount = Uint128::zero(); let w_polls_res: Vec<(u64, Uint128)> = w_polls .iter() .map(|(poll, voting_info)| { // calculate reward share let total_votes = poll.no_votes + poll.yes_votes + poll.abstain_votes; let poll_voting_reward = poll .voters_reward .multiply_ratio(voting_info.balance, total_votes); user_reward_amount += poll_voting_reward; (poll.id, poll_voting_reward) }) .collect(); // filter out not in-progress polls token_manager.locked_balance.retain(|(poll_id, _)| { let poll: Poll = poll_read(deps.storage) .load(&poll_id.to_be_bytes()) .unwrap(); poll.status == PollStatus::InProgress }); let total_locked_balance = state.total_deposit + state.pending_voting_rewards; let total_balance = load_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?.to_string(), &state.contract_addr, )? .checked_sub(total_locked_balance)?; Ok(StakerResponse { balance: if !state.total_share.is_zero() { token_manager .share .multiply_ratio(total_balance, state.total_share) } else { Uint128::zero() }, share: token_manager.share, locked_balance: token_manager.locked_balance, pending_voting_rewards: user_reward_amount, withdrawable_polls: w_polls_res, }) } pub fn query_shares( deps: Deps, start_after: Option<String>, limit: Option<u32>, order_by: Option<OrderBy>, ) -> StdResult<SharesResponse> { let stakers: Vec<(CanonicalAddr, TokenManager)> = if let Some(start_after) = start_after { read_bank_stakers( deps.storage, Some(deps.api.addr_canonicalize(&start_after)?), limit, order_by, )? } else { read_bank_stakers(deps.storage, None, limit, order_by)? }; let stakers_shares: Vec<SharesResponseItem> = stakers .iter() .map(|item| { let (k, v) = item; SharesResponseItem { staker: deps.api.addr_humanize(k).unwrap().to_string(), share: v.share, } }) .collect(); Ok(SharesResponse { stakers: stakers_shares, }) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/querier.rs
contracts/mirror_gov/src/querier.rs
use cosmwasm_std::{ Binary, CanonicalAddr, QuerierWrapper, QueryRequest, StdResult, Uint128, WasmQuery, }; use cosmwasm_storage::to_length_prefixed; pub fn load_token_balance( querier: &QuerierWrapper, contract_addr: String, account_addr: &CanonicalAddr, ) -> StdResult<Uint128> { // load balance form the token contract let res: Uint128 = querier .query(&QueryRequest::Wasm(WasmQuery::Raw { contract_addr, key: Binary::from(concat( &to_length_prefixed(b"balance").to_vec(), account_addr.as_slice(), )), })) .unwrap_or_else(|_| Uint128::zero()); Ok(res) } #[inline] fn concat(namespace: &[u8], key: &[u8]) -> Vec<u8> { let mut k = namespace.to_vec(); k.extend_from_slice(key); k }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/testing/tests.rs
contracts/mirror_gov/src/testing/tests.rs
use crate::contract::{execute, instantiate, query, reply}; use crate::querier::load_token_balance; use crate::state::{ bank_read, bank_store, config_read, poll_indexer_store, poll_store, poll_voter_read, poll_voter_store, state_read, Config, Poll, State, TokenManager, }; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ attr, coins, from_binary, to_binary, Addr, Api, CanonicalAddr, ContractResult, CosmosMsg, Decimal, Deps, DepsMut, Env, Reply, ReplyOn, Response, StdError, SubMsg, Timestamp, Uint128, WasmMsg, }; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use mirror_protocol::admin_manager::ExecuteMsg as ManagerExecuteMsg; use mirror_protocol::common::OrderBy; use mirror_protocol::community::MigrateMsg; use mirror_protocol::gov::{ ConfigResponse, Cw20HookMsg, ExecuteMsg, InstantiateMsg, PollAdminAction, PollConfig, PollExecuteMsg, PollResponse, PollStatus, PollsResponse, QueryMsg, SharesResponse, SharesResponseItem, StakerResponse, StateResponse, VoteOption, VoterInfo, VotersResponse, VotersResponseItem, }; const VOTING_TOKEN: &str = "voting_token"; const TEST_CREATOR: &str = "creator"; const TEST_VOTER: &str = "voter1"; const TEST_VOTER_2: &str = "voter2"; const TEST_VOTER_3: &str = "voter3"; const TEST_COLLECTOR: &str = "collector"; const TEST_ADMIN_MANAGER: &str = "admin_manager"; const DEFAULT_QUORUM: u64 = 30u64; const DEFAULT_THRESHOLD: u64 = 50u64; const DEFAULT_VOTING_PERIOD: u64 = 10000u64; const DEFAULT_MIGRATION_QUORUM: u64 = 40u64; const DEFAULT_MIGRATION_THRESHOLD: u64 = 60u64; const DEFAULT_MIGRATION_VOTING_PERIOD: u64 = 20000u64; const DEFAULT_AUTH_ADMIN_QUORUM: u64 = 50u64; const DEFAULT_AUTH_ADMIN_THRESHOLD: u64 = 70u64; const DEFAULT_AUTH_ADMIN_VOTING_PERIOD: u64 = 30000u64; const DEFAULT_EFFECTIVE_DELAY: u64 = 10000u64; const DEFAULT_PROPOSAL_DEPOSIT: u128 = 10000000000u128; const DEFAULT_MIGRATION_PROPOSAL_DEPOSIT: u128 = 20000000000u128; const DEFAULT_AUTH_ADMIN_PROPOSAL_DEPOSIT: u128 = 30000000000u128; const DEFAULT_VOTER_WEIGHT: Decimal = Decimal::zero(); const DEFAULT_SNAPSHOT_PERIOD: u64 = 10u64; const DEFAULT_POLL_GAS_LIMIT: u64 = 4_000_000u64; fn mock_instantiate(deps: DepsMut) { let msg = init_msg(); let info = mock_info(TEST_CREATOR, &[]); let _res = instantiate(deps, mock_env(), info, msg) .expect("contract successfully handles InstantiateMsg"); } fn mock_env_height(height: u64, time: u64) -> Env { let mut env = mock_env(); env.block.height = height; env.block.time = Timestamp::from_seconds(time); env } fn init_msg() -> InstantiateMsg { InstantiateMsg { mirror_token: VOTING_TOKEN.to_string(), default_poll_config: PollConfig { proposal_deposit: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), voting_period: DEFAULT_VOTING_PERIOD, quorum: Decimal::percent(DEFAULT_QUORUM), threshold: Decimal::percent(DEFAULT_THRESHOLD), }, migration_poll_config: PollConfig { proposal_deposit: Uint128::new(DEFAULT_MIGRATION_PROPOSAL_DEPOSIT), voting_period: DEFAULT_MIGRATION_VOTING_PERIOD, quorum: Decimal::percent(DEFAULT_MIGRATION_QUORUM), threshold: Decimal::percent(DEFAULT_MIGRATION_THRESHOLD), }, auth_admin_poll_config: PollConfig { proposal_deposit: Uint128::new(DEFAULT_AUTH_ADMIN_PROPOSAL_DEPOSIT), voting_period: DEFAULT_AUTH_ADMIN_VOTING_PERIOD, quorum: Decimal::percent(DEFAULT_AUTH_ADMIN_QUORUM), threshold: Decimal::percent(DEFAULT_AUTH_ADMIN_THRESHOLD), }, effective_delay: DEFAULT_EFFECTIVE_DELAY, voter_weight: DEFAULT_VOTER_WEIGHT, snapshot_period: DEFAULT_SNAPSHOT_PERIOD, admin_manager: TEST_ADMIN_MANAGER.to_string(), poll_gas_limit: DEFAULT_POLL_GAS_LIMIT, } } #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = init_msg(); let info = mock_info(TEST_CREATOR, &coins(2, VOTING_TOKEN)); let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); let config: Config = config_read(&deps.storage).load().unwrap(); assert_eq!( config, Config { mirror_token: deps.api.addr_canonicalize(VOTING_TOKEN).unwrap(), owner: deps.api.addr_canonicalize(TEST_CREATOR).unwrap(), default_poll_config: PollConfig { proposal_deposit: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), voting_period: DEFAULT_VOTING_PERIOD, quorum: Decimal::percent(DEFAULT_QUORUM), threshold: Decimal::percent(DEFAULT_THRESHOLD), }, migration_poll_config: PollConfig { proposal_deposit: Uint128::new(DEFAULT_MIGRATION_PROPOSAL_DEPOSIT), voting_period: DEFAULT_MIGRATION_VOTING_PERIOD, quorum: Decimal::percent(DEFAULT_MIGRATION_QUORUM), threshold: Decimal::percent(DEFAULT_MIGRATION_THRESHOLD), }, auth_admin_poll_config: PollConfig { proposal_deposit: Uint128::new(DEFAULT_AUTH_ADMIN_PROPOSAL_DEPOSIT), voting_period: DEFAULT_AUTH_ADMIN_VOTING_PERIOD, quorum: Decimal::percent(DEFAULT_AUTH_ADMIN_QUORUM), threshold: Decimal::percent(DEFAULT_AUTH_ADMIN_THRESHOLD), }, effective_delay: DEFAULT_EFFECTIVE_DELAY, voter_weight: DEFAULT_VOTER_WEIGHT, snapshot_period: DEFAULT_SNAPSHOT_PERIOD, admin_manager: deps.api.addr_canonicalize(TEST_ADMIN_MANAGER).unwrap(), poll_gas_limit: DEFAULT_POLL_GAS_LIMIT, } ); let state: State = state_read(&deps.storage).load().unwrap(); assert_eq!( state, State { contract_addr: deps.api.addr_canonicalize(MOCK_CONTRACT_ADDR).unwrap(), poll_count: 0, total_share: Uint128::zero(), total_deposit: Uint128::zero(), pending_voting_rewards: Uint128::zero(), } ); } #[test] fn poll_not_found() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let res = query(deps.as_ref(), mock_env(), QueryMsg::Poll { poll_id: 1 }); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Poll does not exist"), Err(e) => panic!("Unexpected error: {:?}", e), _ => panic!("Must return error"), } } #[test] fn fails_create_poll_invalid_quorum() { let mut deps = mock_dependencies(&[]); let info = mock_info("voter", &coins(11, VOTING_TOKEN)); let msg = InstantiateMsg { default_poll_config: PollConfig { quorum: Decimal::percent(101), ..init_msg().default_poll_config }, ..init_msg() }; let res = instantiate(deps.as_mut(), mock_env(), info, msg); match res { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "quorum must be 0 to 1"), Err(e) => panic!("Unexpected error: {:?}", e), } } #[test] fn fails_create_poll_invalid_threshold() { let mut deps = mock_dependencies(&[]); let info = mock_info("voter", &coins(11, VOTING_TOKEN)); let msg = InstantiateMsg { default_poll_config: PollConfig { threshold: Decimal::percent(101), ..init_msg().default_poll_config }, ..init_msg() }; let res = instantiate(deps.as_mut(), mock_env(), info, msg); match res { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "threshold must be 0 to 1"), Err(e) => panic!("Unexpected error: {:?}", e), } } #[test] fn fails_create_poll_invalid_title() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let msg = create_poll_msg( "a".to_string(), "test".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let info = mock_info(VOTING_TOKEN, &[]); match execute(deps.as_mut(), mock_env(), info.clone(), msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Title too short"), Err(_) => panic!("Unknown error"), } let msg = create_poll_msg( "0123456789012345678901234567890123456789012345678901234567890123401234567890123456789012345678901234567890123456789012345678901234012345678901234567890123456789012345678901234567890123456789012340123456789012345678901234567890123456789012345678901234567890123401234567890123456789012345678901234567890123456789012345678901234".to_string(), "test".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); match execute(deps.as_mut(), mock_env(), info, msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Title too long"), Err(_) => panic!("Unknown error"), } } #[test] fn fails_create_poll_invalid_description() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let msg = create_poll_msg( "test".to_string(), "a".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let info = mock_info(VOTING_TOKEN, &[]); match execute(deps.as_mut(), mock_env(), info.clone(), msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Description too short"), Err(_) => panic!("Unknown error"), } let msg = create_poll_msg( "test".to_string(), "0123456789012345678901234567890123456789012345678901234567890123401234567890123456789012345678901234567890123456789012345678901234012345678901234567890123456789012345678901234567890123456789012340123456789012345678901234567890123456789012345678901234567890123401234567890123456789012345678901234567890123456789012345678901234".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); match execute(deps.as_mut(), mock_env(), info, msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Description too long"), Err(_) => panic!("Unknown error"), } } #[test] fn fails_create_poll_invalid_link() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let msg = create_poll_msg( "test".to_string(), "test".to_string(), Some("http://hih".to_string()), None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let info = mock_info(VOTING_TOKEN, &[]); match execute(deps.as_mut(), mock_env(), info.clone(), msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Link too short"), Err(_) => panic!("Unknown error"), } let msg = create_poll_msg( "test".to_string(), "test".to_string(), Some("0123456789012345678901234567890123456789012345678901234567890123401234567890123456789012345678901234567890123456789012345678901234012345678901234567890123456789012345678901234567890123456789012340123456789012345678901234567890123456789012345678901234567890123401234567890123456789012345678901234567890123456789012345678901234".to_string()), None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); match execute(deps.as_mut(), mock_env(), info, msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Link too long"), Err(_) => panic!("Unknown error"), } } #[test] fn fails_create_poll_invalid_deposit() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: TEST_CREATOR.to_string(), amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT - 1), msg: to_binary(&Cw20HookMsg::CreatePoll { title: "TESTTEST".to_string(), description: "TESTTEST".to_string(), link: None, execute_msg: None, admin_action: None, }) .unwrap(), }); let info = mock_info(VOTING_TOKEN, &[]); match execute(deps.as_mut(), mock_env(), info, msg) { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!( msg, format!("Must deposit more than {} token", DEFAULT_PROPOSAL_DEPOSIT) ), Err(_) => panic!("Unknown error"), } } fn create_poll_msg( title: String, description: String, link: Option<String>, execute_msg: Option<PollExecuteMsg>, admin_action: Option<PollAdminAction>, proposal_deposit: Uint128, ) -> ExecuteMsg { ExecuteMsg::Receive(Cw20ReceiveMsg { sender: TEST_CREATOR.to_string(), amount: proposal_deposit, msg: to_binary(&Cw20HookMsg::CreatePoll { title, description, link, execute_msg, admin_action, }) .unwrap(), }) } #[test] fn happy_days_create_poll() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let env = mock_env_height(0, 10000); let info = mock_info(VOTING_TOKEN, &[]); let msg = create_poll_msg( "test".to_string(), "test".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let execute_res = execute(deps.as_mut(), env.clone(), info, msg).unwrap(); assert_create_poll_result( 1, env.block.time.plus_seconds(DEFAULT_VOTING_PERIOD).seconds(), TEST_CREATOR, execute_res, deps.as_ref(), Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); } #[test] fn query_polls() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let env = mock_env_height(0, 0); let info = mock_info(VOTING_TOKEN, &[]); let msg = create_poll_msg( "test".to_string(), "test".to_string(), Some("http://google.com".to_string()), None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let _execute_res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap(); let msg = create_poll_msg( "test2".to_string(), "test2".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let _execute_res = execute(deps.as_mut(), env, info, msg).unwrap(); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: None, start_after: None, limit: None, order_by: Some(OrderBy::Asc), }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!( response.polls, vec![ PollResponse { id: 1u64, creator: TEST_CREATOR.to_string(), status: PollStatus::InProgress, end_time: 10000u64, title: "test".to_string(), description: "test".to_string(), link: Some("http://google.com".to_string()), deposit_amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), execute_data: None, yes_votes: Uint128::zero(), no_votes: Uint128::zero(), total_balance_at_end_poll: None, voters_reward: Uint128::zero(), abstain_votes: Uint128::zero(), staked_amount: None, admin_action: None, }, PollResponse { id: 2u64, creator: TEST_CREATOR.to_string(), status: PollStatus::InProgress, end_time: 10000u64, title: "test2".to_string(), description: "test2".to_string(), link: None, deposit_amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), execute_data: None, yes_votes: Uint128::zero(), no_votes: Uint128::zero(), total_balance_at_end_poll: None, voters_reward: Uint128::zero(), abstain_votes: Uint128::zero(), staked_amount: None, admin_action: None, }, ] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: None, start_after: Some(1u64), limit: None, order_by: Some(OrderBy::Asc), }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!( response.polls, vec![PollResponse { id: 2u64, creator: TEST_CREATOR.to_string(), status: PollStatus::InProgress, end_time: 10000u64, title: "test2".to_string(), description: "test2".to_string(), link: None, deposit_amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), execute_data: None, yes_votes: Uint128::zero(), no_votes: Uint128::zero(), total_balance_at_end_poll: None, voters_reward: Uint128::zero(), abstain_votes: Uint128::zero(), staked_amount: None, admin_action: None, },] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: None, start_after: Some(2u64), limit: None, order_by: Some(OrderBy::Desc), }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!( response.polls, vec![PollResponse { id: 1u64, creator: TEST_CREATOR.to_string(), status: PollStatus::InProgress, end_time: 10000u64, title: "test".to_string(), description: "test".to_string(), link: Some("http://google.com".to_string()), deposit_amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), execute_data: None, yes_votes: Uint128::zero(), no_votes: Uint128::zero(), total_balance_at_end_poll: None, voters_reward: Uint128::zero(), abstain_votes: Uint128::zero(), staked_amount: None, admin_action: None, }] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: Some(PollStatus::InProgress), start_after: Some(1u64), limit: None, order_by: Some(OrderBy::Asc), }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!( response.polls, vec![PollResponse { id: 2u64, creator: TEST_CREATOR.to_string(), status: PollStatus::InProgress, end_time: 10000u64, title: "test2".to_string(), description: "test2".to_string(), link: None, deposit_amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), execute_data: None, yes_votes: Uint128::zero(), no_votes: Uint128::zero(), total_balance_at_end_poll: None, voters_reward: Uint128::zero(), abstain_votes: Uint128::zero(), staked_amount: None, admin_action: None, },] ); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: Some(PollStatus::Passed), start_after: None, limit: None, order_by: None, }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!(response.polls, vec![]); } #[test] fn create_poll_no_quorum() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let env = mock_env_height(0, 0); let info = mock_info(VOTING_TOKEN, &[]); let msg = create_poll_msg( "test".to_string(), "test".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let execute_res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_create_poll_result( 1, DEFAULT_VOTING_PERIOD, TEST_CREATOR, execute_res, deps.as_ref(), Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); } #[test] fn fails_end_poll_before_end_time() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); let env = mock_env_height(0, 0); let info = mock_info(VOTING_TOKEN, &[]); let msg = create_poll_msg( "test".to_string(), "test".to_string(), None, None, None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let execute_res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_create_poll_result( 1, DEFAULT_VOTING_PERIOD, TEST_CREATOR, execute_res, deps.as_ref(), Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let res = query(deps.as_ref(), mock_env(), QueryMsg::Poll { poll_id: 1 }).unwrap(); let value: PollResponse = from_binary(&res).unwrap(); assert_eq!(DEFAULT_VOTING_PERIOD, value.end_time); let msg = ExecuteMsg::EndPoll { poll_id: 1 }; let env = mock_env_height(0, 0); let info = mock_info(TEST_CREATOR, &[]); let execute_res = execute(deps.as_mut(), env, info, msg); match execute_res { Ok(_) => panic!("Must return error"), Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Voting period has not expired"), Err(e) => panic!("Unexpected error: {:?}", e), } } #[test] fn happy_days_end_poll() { const POLL_START_TIME: u64 = 1000; const POLL_ID: u64 = 1; let stake_amount = 1000; let mut deps = mock_dependencies(&coins(1000, VOTING_TOKEN)); mock_instantiate(deps.as_mut()); let mut creator_env = mock_env_height(0, POLL_START_TIME); let mut creator_info = mock_info(VOTING_TOKEN, &coins(2, VOTING_TOKEN)); let exec_msg_bz = to_binary(&Cw20ExecuteMsg::Burn { amount: Uint128::new(123), }) .unwrap(); let msg = create_poll_msg( "test".to_string(), "test".to_string(), None, Some(PollExecuteMsg { contract: VOTING_TOKEN.to_string(), msg: exec_msg_bz.clone(), }), None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let execute_res = execute( deps.as_mut(), creator_env.clone(), creator_info.clone(), msg, ) .unwrap(); assert_create_poll_result( 1, creator_env .block .time .plus_seconds(DEFAULT_VOTING_PERIOD) .nanos() / 1_000_000_000u64, TEST_CREATOR, execute_res, deps.as_ref(), Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); deps.querier.with_token_balances(&[( &VOTING_TOKEN.to_string(), &[( &MOCK_CONTRACT_ADDR.to_string(), &Uint128::new((stake_amount + DEFAULT_PROPOSAL_DEPOSIT) as u128), )], )]); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: TEST_VOTER.to_string(), amount: Uint128::from(stake_amount as u128), msg: to_binary(&Cw20HookMsg::StakeVotingTokens {}).unwrap(), }); let info = mock_info(VOTING_TOKEN, &[]); let execute_res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_stake_tokens_result( stake_amount, DEFAULT_PROPOSAL_DEPOSIT, stake_amount, 1, execute_res, deps.as_ref(), ); let msg = ExecuteMsg::CastVote { poll_id: 1, vote: VoteOption::Yes, amount: Uint128::from(stake_amount), }; let env = mock_env_height(0, POLL_START_TIME); let info = mock_info(TEST_VOTER, &[]); let execute_res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( execute_res.attributes, vec![ attr("action", "cast_vote"), attr("poll_id", POLL_ID.to_string()), attr("amount", "1000"), attr("voter", TEST_VOTER), attr("vote_option", "yes"), ] ); // not in passed status let msg = ExecuteMsg::ExecutePoll { poll_id: 1 }; let execute_res = execute( deps.as_mut(), creator_env.clone(), creator_info.clone(), msg, ) .unwrap_err(); match execute_res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "Poll is not in passed status"), _ => panic!("DO NOT ENTER HERE"), } creator_info.sender = Addr::unchecked(TEST_CREATOR); creator_env.block.time = creator_env.block.time.plus_seconds(DEFAULT_VOTING_PERIOD); let msg = ExecuteMsg::EndPoll { poll_id: 1 }; let execute_res = execute( deps.as_mut(), creator_env.clone(), creator_info.clone(), msg, ) .unwrap(); assert_eq!( execute_res.attributes, vec![ attr("action", "end_poll"), attr("poll_id", "1"), attr("rejected_reason", ""), attr("passed", "true"), ] ); assert_eq!( execute_res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: VOTING_TOKEN.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient: TEST_CREATOR.to_string(), amount: Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), }) .unwrap(), funds: vec![], }))] ); // End poll will withdraw deposit balance deps.querier.with_token_balances(&[( &VOTING_TOKEN.to_string(), &[( &MOCK_CONTRACT_ADDR.to_string(), &Uint128::new(stake_amount as u128), )], )]); // effective delay has not expired let msg = ExecuteMsg::ExecutePoll { poll_id: 1 }; let execute_res = execute( deps.as_mut(), creator_env.clone(), creator_info.clone(), msg, ) .unwrap_err(); match execute_res { StdError::GenericErr { msg, .. } => assert_eq!(msg, "Effective delay has not expired"), _ => panic!("DO NOT ENTER HERE"), } creator_env.block.time = creator_env.block.time.plus_seconds(DEFAULT_EFFECTIVE_DELAY); let msg = ExecuteMsg::ExecutePoll { poll_id: 1 }; let execute_res = execute(deps.as_mut(), creator_env, creator_info, msg).unwrap(); assert_eq!( execute_res.messages, vec![SubMsg { msg: CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: VOTING_TOKEN.to_string(), msg: exec_msg_bz, funds: vec![], }), gas_limit: Some(DEFAULT_POLL_GAS_LIMIT), id: 1u64, reply_on: ReplyOn::Error, }] ); assert_eq!( execute_res.attributes, vec![attr("action", "execute_poll"), attr("poll_id", "1"),] ); // Query executed polls let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: Some(PollStatus::Passed), start_after: None, limit: None, order_by: None, }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!(response.polls.len(), 0); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: Some(PollStatus::InProgress), start_after: None, limit: None, order_by: None, }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!(response.polls.len(), 0); let res = query( deps.as_ref(), mock_env(), QueryMsg::Polls { filter: Some(PollStatus::Executed), start_after: None, limit: None, order_by: Some(OrderBy::Desc), }, ) .unwrap(); let response: PollsResponse = from_binary(&res).unwrap(); assert_eq!(response.polls.len(), 1); // staker locked token must disappeared let res = query( deps.as_ref(), mock_env(), QueryMsg::Staker { address: TEST_VOTER.to_string(), }, ) .unwrap(); let response: StakerResponse = from_binary(&res).unwrap(); assert_eq!( response, StakerResponse { balance: Uint128::new(stake_amount), share: Uint128::new(stake_amount), locked_balance: vec![], pending_voting_rewards: Uint128::zero(), withdrawable_polls: vec![], } ); } #[test] fn failed_execute_poll() { const POLL_START_TIME: u64 = 1000; const POLL_ID: u64 = 1; let stake_amount = 1000; let mut deps = mock_dependencies(&coins(1000, VOTING_TOKEN)); mock_instantiate(deps.as_mut()); let mut creator_env = mock_env_height(0, POLL_START_TIME); let creator_info = mock_info(VOTING_TOKEN, &coins(2, VOTING_TOKEN)); let exec_msg_bz = to_binary(&Cw20ExecuteMsg::Burn { amount: Uint128::new(123), }) .unwrap(); let msg = create_poll_msg( "test".to_string(), "test".to_string(), None, Some(PollExecuteMsg { contract: VOTING_TOKEN.to_string(), msg: exec_msg_bz.clone(), }), None, Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); let execute_res = execute( deps.as_mut(), creator_env.clone(), creator_info.clone(), msg, ) .unwrap(); assert_create_poll_result( 1, creator_env .block .time .plus_seconds(DEFAULT_VOTING_PERIOD) .seconds(), TEST_CREATOR, execute_res, deps.as_ref(), Uint128::new(DEFAULT_PROPOSAL_DEPOSIT), ); deps.querier.with_token_balances(&[( &VOTING_TOKEN.to_string(), &[( &MOCK_CONTRACT_ADDR.to_string(), &Uint128::new((stake_amount + DEFAULT_PROPOSAL_DEPOSIT) as u128), )], )]); let msg = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: TEST_VOTER.to_string(), amount: Uint128::from(stake_amount as u128), msg: to_binary(&Cw20HookMsg::StakeVotingTokens {}).unwrap(), }); let info = mock_info(VOTING_TOKEN, &[]); let execute_res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_stake_tokens_result( stake_amount, DEFAULT_PROPOSAL_DEPOSIT, stake_amount, 1, execute_res, deps.as_ref(), ); let msg = ExecuteMsg::CastVote { poll_id: 1, vote: VoteOption::Yes, amount: Uint128::from(stake_amount), }; let env = mock_env_height(0, POLL_START_TIME); let info = mock_info(TEST_VOTER, &[]); let execute_res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( execute_res.attributes, vec![ attr("action", "cast_vote"), attr("poll_id", POLL_ID.to_string()), attr("amount", "1000"), attr("voter", TEST_VOTER), attr("vote_option", "yes"), ] ); creator_env.block.time = creator_env.block.time.plus_seconds(DEFAULT_VOTING_PERIOD); let msg = ExecuteMsg::EndPoll { poll_id: 1 }; let execute_res = execute( deps.as_mut(), creator_env.clone(), creator_info.clone(), msg, ) .unwrap(); assert_eq!( execute_res.attributes, vec![ attr("action", "end_poll"), attr("poll_id", "1"), attr("rejected_reason", ""), attr("passed", "true"), ] ); assert_eq!( execute_res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: VOTING_TOKEN.to_string(), msg: to_binary(&Cw20ExecuteMsg::Transfer {
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
true
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/testing/mock_querier.rs
contracts/mirror_gov/src/testing/mock_querier.rs
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_slice, to_binary, Addr, Api, CanonicalAddr, Coin, ContractResult, Empty, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, WasmQuery, }; use cosmwasm_storage::to_length_prefixed; use std::collections::HashMap; /// mock_dependencies is a drop-in replacement for cosmwasm_std::testing::mock_dependencies /// this uses our CustomQuerier. pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new(MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)])); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<Empty>, token_querier: TokenQuerier, } #[derive(Clone, Default)] pub struct TokenQuerier { // this lets us iterate over all pairs that match the first string balances: HashMap<String, HashMap<String, Uint128>>, } impl TokenQuerier { pub fn new(balances: &[(&String, &[(&String, &Uint128)])]) -> Self { TokenQuerier { balances: balances_to_map(balances), } } } pub(crate) fn balances_to_map( balances: &[(&String, &[(&String, &Uint128)])], ) -> HashMap<String, HashMap<String, Uint128>> { let mut balances_map: HashMap<String, HashMap<String, Uint128>> = HashMap::new(); for (contract_addr, balances) in balances.iter() { let mut contract_balances_map: HashMap<String, Uint128> = HashMap::new(); for (addr, balance) in balances.iter() { contract_balances_map.insert(addr.to_string(), **balance); } balances_map.insert(contract_addr.to_string(), contract_balances_map); } balances_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<Empty> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<Empty>) -> QuerierResult { match &request { QueryRequest::Wasm(WasmQuery::Raw { contract_addr, key }) => { let key: &[u8] = key.as_slice(); let balances: &HashMap<String, Uint128> = match self.token_querier.balances.get(contract_addr) { Some(balances) => balances, None => { return SystemResult::Err(SystemError::InvalidRequest { error: format!( "No balance info exists for the contract {}", contract_addr ), request: key.into(), }) } }; let prefix_balance = to_length_prefixed(b"balance").to_vec(); if key[..prefix_balance.len()].to_vec() == prefix_balance { let key_address: &[u8] = &key[prefix_balance.len()..]; let address_raw: CanonicalAddr = CanonicalAddr::from(key_address); let api: MockApi = MockApi::default(); let address: Addr = match api.addr_humanize(&address_raw) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: key.into(), }) } }; let balance = match balances.get(&address.to_string()) { Some(v) => v, None => { return SystemResult::Err(SystemError::InvalidRequest { error: "Balance not found".to_string(), request: key.into(), }) } }; SystemResult::Ok(ContractResult::from(to_binary(&balance))) } else { panic!("DO NOT ENTER HERE") } } _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new(base: MockQuerier<Empty>) -> Self { WasmMockQuerier { base, token_querier: TokenQuerier::default(), } } // configure the mint whitelist mock querier pub fn with_token_balances(&mut self, balances: &[(&String, &[(&String, &Uint128)])]) { self.token_querier = TokenQuerier::new(balances); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/src/testing/mod.rs
contracts/mirror_gov/src/testing/mod.rs
mod mock_querier; mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_gov/examples/schema.rs
contracts/mirror_gov/examples/schema.rs
use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use std::env::current_dir; use std::fs::create_dir_all; use mirror_protocol::gov::{ ConfigResponse, Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, PollCountResponse, PollExecuteMsg, PollResponse, PollsResponse, QueryMsg, SharesResponse, StakerResponse, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(Cw20HookMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(StakerResponse), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(PollResponse), &out_dir); export_schema(&schema_for!(PollExecuteMsg), &out_dir); export_schema(&schema_for!(PollsResponse), &out_dir); export_schema(&schema_for!(PollCountResponse), &out_dir); export_schema(&schema_for!(SharesResponse), &out_dir); export_schema(&schema_for!(MigrateMsg), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/contract.rs
contracts/mirror_admin_manager/src/contract.rs
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult}; use mirror_protocol::admin_manager::{ExecuteMsg, InstantiateMsg, QueryMsg}; use crate::{ error::ContractError, handle::{authorize_claim, claim_admin, execute_migrations, update_owner}, query::{query_auth_records, query_config, query_migration_records}, state::{Config, CONFIG}, }; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { let config = Config { owner: deps.api.addr_canonicalize(&msg.owner)?, admin_claim_period: msg.admin_claim_period, }; CONFIG.save(deps.storage, &config)?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::UpdateOwner { owner } => update_owner(deps, info, owner), ExecuteMsg::AuthorizeClaim { authorized_addr } => { authorize_claim(deps, info, env, authorized_addr) } ExecuteMsg::ClaimAdmin { contract } => claim_admin(deps, info, env, contract), ExecuteMsg::ExecuteMigrations { migrations } => { execute_migrations(deps, info, env, migrations) } } } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), QueryMsg::AuthRecords { start_after, limit } => { to_binary(&query_auth_records(deps, start_after, limit)?) } QueryMsg::MigrationRecords { start_after, limit } => { to_binary(&query_migration_records(deps, start_after, limit)?) } } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/lib.rs
contracts/mirror_admin_manager/src/lib.rs
pub mod contract; mod error; mod handle; mod query; mod state; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/state.rs
contracts/mirror_admin_manager/src/state.rs
use cosmwasm_std::{Api, Binary, CanonicalAddr, Order, StdResult, Storage}; use cw_storage_plus::{Bound, Item, Map, U64Key}; use mirror_protocol::admin_manager::{ AuthRecordResponse, AuthRecordsResponse, ConfigResponse, MigrationItem, MigrationRecordResponse, MigrationRecordsResponse, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; pub const CONFIG: Item<Config> = Item::new("config"); pub const MIGRATION_RECORDS_BY_TIME: Map<U64Key, MigrationRecord> = Map::new("migration_records"); pub const AUTH_RECORDS_BY_TIME: Map<U64Key, AuthRecord> = Map::new("auth_records"); pub const AUTH_LIST: Map<&[u8], u64> = Map::new("auth_list"); const MAX_LIMIT: u32 = 30; const DEFAULT_LIMIT: u32 = 10; ////////////////////////////////////////////////////////////////////// /// CONFIG ////////////////////////////////////////////////////////////////////// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub admin_claim_period: u64, } impl Config { pub fn as_res(&self, api: &dyn Api) -> StdResult<ConfigResponse> { let res = ConfigResponse { owner: api.addr_humanize(&self.owner)?.to_string(), admin_claim_period: self.admin_claim_period, }; Ok(res) } } ////////////////////////////////////////////////////////////////////// /// AUTH RECORDS ////////////////////////////////////////////////////////////////////// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct AuthRecord { pub address: CanonicalAddr, pub start_time: u64, pub end_time: u64, } impl AuthRecord { pub fn as_res(&self, api: &dyn Api) -> StdResult<AuthRecordResponse> { let res = AuthRecordResponse { address: api.addr_humanize(&self.address)?.to_string(), start_time: self.start_time, end_time: self.end_time, }; Ok(res) } } pub fn create_auth_record( storage: &mut dyn Storage, addr_raw: CanonicalAddr, claim_start: u64, claim_end: u64, ) -> StdResult<()> { let record = AuthRecord { address: addr_raw.clone(), start_time: claim_start, end_time: claim_end, }; // stores the record and adds a new entry to the list AUTH_LIST.save(storage, addr_raw.as_slice(), &claim_end)?; AUTH_RECORDS_BY_TIME.save(storage, claim_start.into(), &record)?; Ok(()) } pub fn is_addr_authorized( storage: &dyn Storage, addr_raw: CanonicalAddr, current_time: u64, ) -> bool { match AUTH_LIST.load(storage, addr_raw.as_slice()) { Ok(claim_end) => claim_end >= current_time, Err(_) => false, } } pub fn read_latest_auth_records( storage: &dyn Storage, api: &dyn Api, start_after: Option<u64>, limit: Option<u32>, ) -> StdResult<AuthRecordsResponse> { let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let end = calc_range_end(start_after).map(Bound::exclusive); let records: Vec<AuthRecordResponse> = AUTH_RECORDS_BY_TIME .range(storage, None, end, Order::Descending) .take(limit) .map(|item| { let (_, record) = item?; record.as_res(api) }) .collect::<StdResult<Vec<AuthRecordResponse>>>()?; Ok(AuthRecordsResponse { records }) } ////////////////////////////////////////////////////////////////////// /// MIGRATION RECORDS ////////////////////////////////////////////////////////////////////// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrationRecord { pub executor: CanonicalAddr, pub time: u64, pub migrations: Vec<(CanonicalAddr, u64, Binary)>, } impl MigrationRecord { pub fn as_res(&self, api: &dyn Api) -> StdResult<MigrationRecordResponse> { let migration_items: Vec<MigrationItem> = self .migrations .iter() .map(|item| { let res = MigrationItem { contract: api.addr_humanize(&item.0)?.to_string(), new_code_id: item.1, msg: item.2.clone(), }; Ok(res) }) .collect::<StdResult<Vec<MigrationItem>>>()?; let res = MigrationRecordResponse { executor: api.addr_humanize(&self.executor)?.to_string(), time: self.time, migrations: migration_items, }; Ok(res) } } pub fn read_latest_migration_records( storage: &dyn Storage, api: &dyn Api, start_after: Option<u64>, limit: Option<u32>, ) -> StdResult<MigrationRecordsResponse> { let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let end = calc_range_end(start_after).map(Bound::exclusive); let records: Vec<MigrationRecordResponse> = MIGRATION_RECORDS_BY_TIME .range(storage, None, end, Order::Descending) .take(limit) .map(|item| { let (_, record) = item?; record.as_res(api) }) .collect::<StdResult<Vec<MigrationRecordResponse>>>()?; Ok(MigrationRecordsResponse { records }) } // this will set the first key after the provided key, by appending a 1 byte fn calc_range_end(start_after: Option<u64>) -> Option<Vec<u8>> { start_after.map(|id| id.to_be_bytes().to_vec()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/error.rs
contracts/mirror_admin_manager/src/error.rs
use cosmwasm_std::StdError; use thiserror::Error; #[derive(Error, Debug, PartialEq)] pub enum ContractError { #[error("{0}")] Std(#[from] StdError), #[error("Unauthorized")] Unauthorized {}, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/query.rs
contracts/mirror_admin_manager/src/query.rs
use cosmwasm_std::{Deps, StdResult}; use mirror_protocol::admin_manager::{ AuthRecordsResponse, ConfigResponse, MigrationRecordsResponse, }; use crate::state::{read_latest_auth_records, read_latest_migration_records, Config, CONFIG}; /// Queries contract Config pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let config: Config = CONFIG.load(deps.storage)?; config.as_res(deps.api) } /// Queries all auth records, ordered by timestamp (desc) pub fn query_auth_records( deps: Deps, start_after: Option<u64>, limit: Option<u32>, ) -> StdResult<AuthRecordsResponse> { read_latest_auth_records(deps.storage, deps.api, start_after, limit) } /// Queries all migration records, ordered by timestamp (desc) pub fn query_migration_records( deps: Deps, start_after: Option<u64>, limit: Option<u32>, ) -> StdResult<MigrationRecordsResponse> { read_latest_migration_records(deps.storage, deps.api, start_after, limit) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/handle.rs
contracts/mirror_admin_manager/src/handle.rs
use cosmwasm_std::{ attr, Binary, CanonicalAddr, CosmosMsg, DepsMut, Env, MessageInfo, Response, WasmMsg, }; use crate::{ error::ContractError, state::{ create_auth_record, is_addr_authorized, Config, MigrationRecord, CONFIG, MIGRATION_RECORDS_BY_TIME, }, }; /// Updates the owner of the contract pub fn update_owner( deps: DepsMut, info: MessageInfo, owner: String, ) -> Result<Response, ContractError> { let mut config: Config = CONFIG.load(deps.storage)?; let sender_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; if sender_raw != config.owner { return Err(ContractError::Unauthorized {}); } // validate and convert to raw deps.api.addr_validate(owner.as_str())?; let new_owner_raw: CanonicalAddr = deps.api.addr_canonicalize(owner.as_str())?; config.owner = new_owner_raw; CONFIG.save(deps.storage, &config)?; Ok(Response::new().add_attribute("action", "update_owner")) } /// Owner can authorize an `authorized_address` to execute `claim_admin` for a limited time period pub fn authorize_claim( deps: DepsMut, info: MessageInfo, env: Env, authorized_addr: String, ) -> Result<Response, ContractError> { let config: Config = CONFIG.load(deps.storage)?; let sender_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; if sender_raw != config.owner { return Err(ContractError::Unauthorized {}); } // validate and convert authorized address deps.api.addr_validate(authorized_addr.as_str())?; let authorized_addr_raw: CanonicalAddr = deps.api.addr_canonicalize(authorized_addr.as_str())?; let claim_start = env.block.time.seconds(); let claim_end = claim_start + config.admin_claim_period; create_auth_record(deps.storage, authorized_addr_raw, claim_start, claim_end)?; Ok(Response::new().add_attributes(vec![ attr("action", "authorize_claim"), attr("claim_start", claim_start.to_string()), attr("claim_end", claim_end.to_string()), ])) } /// An `authorized_address` can claim admin privilages on a `contract` during the auth period pub fn claim_admin( deps: DepsMut, info: MessageInfo, env: Env, contract: String, ) -> Result<Response, ContractError> { let sender_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; if !is_addr_authorized(deps.storage, sender_raw, env.block.time.seconds()) { return Err(ContractError::Unauthorized {}); } Ok(Response::new() .add_message(CosmosMsg::Wasm(WasmMsg::UpdateAdmin { contract_addr: contract.to_string(), admin: info.sender.to_string(), })) .add_attributes(vec![ attr("action", "claim_admin"), attr("contract", contract), ])) } /// Owner (gov contract) can execute_migrations on any of the managed contracts, creating a migration_record pub fn execute_migrations( deps: DepsMut, info: MessageInfo, env: Env, migrations: Vec<(String, u64, Binary)>, ) -> Result<Response, ContractError> { let config: Config = CONFIG.load(deps.storage)?; let sender_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; if sender_raw != config.owner { return Err(ContractError::Unauthorized {}); } let mut migration_msgs: Vec<CosmosMsg> = vec![]; let mut migrations_raw: Vec<(CanonicalAddr, u64, Binary)> = vec![]; for migration in migrations.iter() { migration_msgs.push(CosmosMsg::Wasm(WasmMsg::Migrate { contract_addr: migration.0.to_string(), new_code_id: migration.1, msg: migration.2.clone(), })); let contract_addr_raw: CanonicalAddr = deps.api.addr_canonicalize(migration.0.as_str())?; migrations_raw.push((contract_addr_raw, migration.1, migration.2.clone())); } let migration_record = MigrationRecord { executor: sender_raw, time: env.block.time.seconds(), migrations: migrations_raw, }; MIGRATION_RECORDS_BY_TIME.save( deps.storage, env.block.time.seconds().into(), &migration_record, )?; Ok(Response::new() .add_messages(migration_msgs) .add_attribute("action", "execute_migrations")) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/testing/tests.rs
contracts/mirror_admin_manager/src/testing/tests.rs
use crate::contract::{execute, instantiate, query}; use crate::error::ContractError; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{ attr, from_binary, to_binary, BlockInfo, CosmosMsg, Empty, Env, SubMsg, Timestamp, WasmMsg, }; use mirror_protocol::admin_manager::{ AuthRecordResponse, AuthRecordsResponse, ConfigResponse, ExecuteMsg, InstantiateMsg, MigrationItem, MigrationRecordResponse, MigrationRecordsResponse, QueryMsg, }; fn mock_env_with_block_time(time: u64) -> Env { let env = mock_env(); // register time Env { block: BlockInfo { height: 1, time: Timestamp::from_seconds(time), chain_id: "columbus".to_string(), }, ..env } } #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap(); let config: ConfigResponse = from_binary(&res).unwrap(); assert_eq!( config, ConfigResponse { owner: "owner0000".to_string(), admin_claim_period: 100u64, } ) } #[test] fn update_owner() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // update owner, unauth attempt let info = mock_info("addr0000", &[]); let msg = ExecuteMsg::UpdateOwner { owner: "owner0001".to_string(), }; let err = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(err, ContractError::Unauthorized {}); // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(res.attributes, vec![attr("action", "update_owner")]); let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap(); let config: ConfigResponse = from_binary(&res).unwrap(); assert_eq!( config, ConfigResponse { owner: "owner0001".to_string(), admin_claim_period: 100u64, } ) } #[test] fn execute_migrations() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::ExecuteMigrations { migrations: vec![ ( "contract0000".to_string(), 12u64, to_binary(&Empty {}).unwrap(), ), ( "contract0001".to_string(), 13u64, to_binary(&Empty {}).unwrap(), ), ], }; // unauthorized attempt let info = mock_info("addr0000", &[]); let err = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(err, ContractError::Unauthorized {}); // successfull attempt let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(res.attributes, vec![attr("action", "execute_migrations"),]); let res: MigrationRecordsResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::MigrationRecords { start_after: None, limit: None, }, ) .unwrap(), ) .unwrap(); assert_eq!( res, MigrationRecordsResponse { records: vec![MigrationRecordResponse { executor: "owner0000".to_string(), time: mock_env().block.time.seconds(), migrations: vec![ MigrationItem { contract: "contract0000".to_string(), new_code_id: 12u64, msg: to_binary(&Empty {}).unwrap(), }, MigrationItem { contract: "contract0001".to_string(), new_code_id: 13u64, msg: to_binary(&Empty {}).unwrap(), } ], }] } ); } #[test] fn authorize_claim() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::AuthorizeClaim { authorized_addr: "auth0000".to_string(), }; // unauthorized attempt let info = mock_info("addr0000", &[]); let err = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(err, ContractError::Unauthorized {}); // successfull attempt let info = mock_info("owner0000", &[]); let env = mock_env_with_block_time(10u64); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "authorize_claim"), attr("claim_start", "10"), attr("claim_end", "110"), // 10 + 100 ] ); let res: AuthRecordsResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::AuthRecords { start_after: None, limit: None, }, ) .unwrap(), ) .unwrap(); assert_eq!( res, AuthRecordsResponse { records: vec![AuthRecordResponse { address: "auth0000".to_string(), start_time: 10u64, end_time: 110u64, }] } ); } #[test] fn claim_admin() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::AuthorizeClaim { authorized_addr: "auth0000".to_string(), }; let info = mock_info("owner0000", &[]); let env = mock_env_with_block_time(10u64); execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::ClaimAdmin { contract: "contract0000".to_string(), }; // unauthorized attempt let info = mock_info("addr0000", &[]); let err = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(err, ContractError::Unauthorized {}); // claim after claim_end, exepct unauthorized error let info = mock_info("auth0000", &[]); let env = mock_env_with_block_time(111u64); let err = execute(deps.as_mut(), env, info.clone(), msg.clone()).unwrap_err(); assert_eq!(err, ContractError::Unauthorized {}); // successful attempt let env = mock_env_with_block_time(109u64); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "claim_admin"), attr("contract", "contract0000"), ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::UpdateAdmin { contract_addr: "contract0000".to_string(), admin: "auth0000".to_string(), }))] ) } #[test] fn query_auth_records() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::AuthorizeClaim { authorized_addr: "auth0000".to_string(), }; let info = mock_info("owner0000", &[]); let env = mock_env_with_block_time(10u64); execute(deps.as_mut(), env, info.clone(), msg).unwrap(); let msg = ExecuteMsg::AuthorizeClaim { authorized_addr: "auth0001".to_string(), }; let env = mock_env_with_block_time(20u64); execute(deps.as_mut(), env, info.clone(), msg).unwrap(); let msg = ExecuteMsg::AuthorizeClaim { authorized_addr: "auth0002".to_string(), }; let env = mock_env_with_block_time(30u64); execute(deps.as_mut(), env, info, msg).unwrap(); let res: AuthRecordsResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::AuthRecords { start_after: None, limit: None, }, ) .unwrap(), ) .unwrap(); assert_eq!( res, AuthRecordsResponse { records: vec![ AuthRecordResponse { address: "auth0002".to_string(), start_time: 30u64, end_time: 130u64, }, AuthRecordResponse { address: "auth0001".to_string(), start_time: 20u64, end_time: 120u64, }, AuthRecordResponse { address: "auth0000".to_string(), start_time: 10u64, end_time: 110u64, } ] } ); let res: AuthRecordsResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::AuthRecords { start_after: Some(21u64), limit: Some(1u32), }, ) .unwrap(), ) .unwrap(); assert_eq!( res, AuthRecordsResponse { records: vec![AuthRecordResponse { address: "auth0001".to_string(), start_time: 20u64, end_time: 120u64, },] } ); } #[test] fn query_migration_records() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), admin_claim_period: 100u64, }; let info = mock_info("addr0000", &[]); instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::ExecuteMigrations { migrations: vec![( "contract0000".to_string(), 12u64, to_binary(&Empty {}).unwrap(), )], }; let info = mock_info("owner0000", &[]); let env = mock_env_with_block_time(10u64); execute(deps.as_mut(), env, info.clone(), msg).unwrap(); let msg = ExecuteMsg::ExecuteMigrations { migrations: vec![( "contract0001".to_string(), 13u64, to_binary(&Empty {}).unwrap(), )], }; let env = mock_env_with_block_time(20u64); execute(deps.as_mut(), env, info.clone(), msg).unwrap(); let msg = ExecuteMsg::ExecuteMigrations { migrations: vec![( "contract0002".to_string(), 14u64, to_binary(&Empty {}).unwrap(), )], }; let env = mock_env_with_block_time(30u64); execute(deps.as_mut(), env, info, msg).unwrap(); let res: MigrationRecordsResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::MigrationRecords { start_after: None, limit: None, }, ) .unwrap(), ) .unwrap(); assert_eq!( res, MigrationRecordsResponse { records: vec![ MigrationRecordResponse { executor: "owner0000".to_string(), time: 30u64, migrations: vec![MigrationItem { contract: "contract0002".to_string(), new_code_id: 14u64, msg: to_binary(&Empty {}).unwrap(), },], }, MigrationRecordResponse { executor: "owner0000".to_string(), time: 20u64, migrations: vec![MigrationItem { contract: "contract0001".to_string(), new_code_id: 13u64, msg: to_binary(&Empty {}).unwrap(), },], }, MigrationRecordResponse { executor: "owner0000".to_string(), time: 10u64, migrations: vec![MigrationItem { contract: "contract0000".to_string(), new_code_id: 12u64, msg: to_binary(&Empty {}).unwrap(), },], }, ] } ); let res: MigrationRecordsResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::MigrationRecords { start_after: Some(21u64), limit: Some(1u32), }, ) .unwrap(), ) .unwrap(); assert_eq!( res, MigrationRecordsResponse { records: vec![MigrationRecordResponse { executor: "owner0000".to_string(), time: 20u64, migrations: vec![MigrationItem { contract: "contract0001".to_string(), new_code_id: 13u64, msg: to_binary(&Empty {}).unwrap(), },], },] } ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/src/testing/mod.rs
contracts/mirror_admin_manager/src/testing/mod.rs
mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_admin_manager/examples/schema.rs
contracts/mirror_admin_manager/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::admin_manager::{ AuthRecordResponse, ConfigResponse, ExecuteMsg, InstantiateMsg, MigrationRecordResponse, QueryMsg, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(AuthRecordResponse), &out_dir); export_schema(&schema_for!(MigrationRecordResponse), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/swap.rs
contracts/mirror_collector/src/swap.rs
use std::str::FromStr; use crate::errors::ContractError; use crate::state::{read_config, Config}; use cosmwasm_std::{ attr, to_binary, Addr, Coin, CosmosMsg, Decimal, DepsMut, Env, Response, WasmMsg, }; use cw20::Cw20ExecuteMsg; use mirror_protocol::collector::ExecuteMsg; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use terra_cosmwasm::{create_swap_msg, TerraMsgWrapper}; use terraswap::asset::{Asset, AssetInfo, PairInfo}; use terraswap::pair::{Cw20HookMsg as TerraswapCw20HookMsg, ExecuteMsg as TerraswapExecuteMsg}; use terraswap::querier::{query_balance, query_pair_info, query_token_balance}; const LUNA_DENOM: &str = "uluna"; const AMM_MAX_ALLOWED_SLIPPAGE: &str = "0.5"; #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum MoneyMarketCw20HookMsg { RedeemStable {}, } /// Convert /// Anyone can execute convert function to swap /// asset token => collateral token /// collateral token => MIR token pub fn convert( deps: DepsMut, env: Env, asset_token: Addr, ) -> Result<Response<TerraMsgWrapper>, ContractError> { let config: Config = read_config(deps.storage)?; let asset_token_raw = deps.api.addr_canonicalize(asset_token.as_str())?; if asset_token_raw == config.aust_token { anchor_redeem(deps, env, &config, asset_token) } else if asset_token_raw == config.bluna_token { bluna_swap(deps, env, &config, asset_token) } else if asset_token_raw == config.lunax_token { lunax_swap(deps, env, &config, asset_token) } else { direct_swap(deps, env, &config, asset_token) } } fn direct_swap( deps: DepsMut, env: Env, config: &Config, asset_token: Addr, ) -> Result<Response<TerraMsgWrapper>, ContractError> { let terraswap_factory_addr = deps.api.addr_humanize(&config.terraswap_factory)?; let asset_token_raw = deps.api.addr_canonicalize(asset_token.as_str())?; let pair_addr: String = if asset_token_raw == config.mirror_token && config.mir_ust_pair.is_some() { deps.api .addr_humanize(config.mir_ust_pair.as_ref().unwrap())? .to_string() } else { let pair_info: PairInfo = query_pair_info( &deps.querier, terraswap_factory_addr, &[ AssetInfo::NativeToken { denom: config.base_denom.clone(), }, AssetInfo::Token { contract_addr: asset_token.to_string(), }, ], )?; pair_info.contract_addr }; let mut messages: Vec<CosmosMsg<TerraMsgWrapper>> = vec![]; if config.mirror_token == asset_token_raw { // collateral token => MIR token let amount = query_balance( &deps.querier, env.contract.address, config.base_denom.clone(), )?; if !amount.is_zero() { let swap_asset = Asset { info: AssetInfo::NativeToken { denom: config.base_denom.clone(), }, amount, }; // deduct tax first let amount = (swap_asset.deduct_tax(&deps.querier)?).amount; messages = vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: pair_addr, msg: to_binary(&TerraswapExecuteMsg::Swap { offer_asset: Asset { amount, ..swap_asset }, max_spread: Some(Decimal::from_str(AMM_MAX_ALLOWED_SLIPPAGE)?), // currently need to set max_allowed_slippage for Astroport belief_price: None, to: None, })?, funds: vec![Coin { denom: config.base_denom.clone(), amount, }], })]; } } else { // asset token => collateral token let amount = query_token_balance(&deps.querier, asset_token.clone(), env.contract.address)?; if !amount.is_zero() { messages = vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_addr, amount, msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, // currently all mAsset swaps are on terraswap, so we set max_spread to None belief_price: None, to: None, })?, })?, funds: vec![], })]; } } Ok(Response::new() .add_attributes(vec![ attr("action", "convert"), attr("swap_type", "direct"), attr("asset_token", asset_token.as_str()), ]) .add_messages(messages)) } fn anchor_redeem( deps: DepsMut, env: Env, config: &Config, asset_token: Addr, ) -> Result<Response<TerraMsgWrapper>, ContractError> { let amount = query_token_balance(&deps.querier, asset_token.clone(), env.contract.address)?; let mut messages: Vec<CosmosMsg<TerraMsgWrapper>> = vec![]; if !amount.is_zero() { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: deps.api.addr_humanize(&config.anchor_market)?.to_string(), amount, msg: to_binary(&MoneyMarketCw20HookMsg::RedeemStable {})?, })?, funds: vec![], })); } Ok(Response::new().add_messages(messages).add_attributes(vec![ attr("action", "convert"), attr("swap_type", "anchor_redeem"), attr("asset_token", asset_token.as_str()), ])) } fn lunax_swap( deps: DepsMut, env: Env, config: &Config, asset_token: Addr, ) -> Result<Response<TerraMsgWrapper>, ContractError> { let terraswap_factory_addr = deps.api.addr_humanize(&config.terraswap_factory)?; let pair_info: PairInfo = query_pair_info( &deps.querier, terraswap_factory_addr, &[ AssetInfo::NativeToken { denom: LUNA_DENOM.to_string(), }, AssetInfo::Token { contract_addr: asset_token.to_string(), }, ], )?; let amount = query_token_balance( &deps.querier, asset_token.clone(), env.contract.address.clone(), )?; let mut messages: Vec<CosmosMsg<TerraMsgWrapper>> = vec![]; if !amount.is_zero() { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_info.contract_addr, amount, msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, })?, })?, funds: vec![], })); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::LunaSwapHook {})?, funds: vec![], })); } Ok(Response::new().add_messages(messages).add_attributes(vec![ attr("action", "convert"), attr("swap_type", "lunax_swap"), attr("asset_token", asset_token.as_str()), ])) } fn bluna_swap( deps: DepsMut, env: Env, config: &Config, asset_token: Addr, ) -> Result<Response<TerraMsgWrapper>, ContractError> { let terraswap_factory_addr = deps.api.addr_humanize(&config.terraswap_factory)?; let pair_info: PairInfo = query_pair_info( &deps.querier, terraswap_factory_addr, &[ AssetInfo::NativeToken { denom: LUNA_DENOM.to_string(), }, AssetInfo::Token { contract_addr: asset_token.to_string(), }, ], )?; let amount = query_token_balance( &deps.querier, asset_token.clone(), env.contract.address.clone(), )?; let mut messages: Vec<CosmosMsg<TerraMsgWrapper>> = vec![]; if !amount.is_zero() { messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: asset_token.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_info.contract_addr, amount, msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, })?, })?, funds: vec![], })); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::LunaSwapHook {})?, funds: vec![], })); } Ok(Response::new().add_messages(messages).add_attributes(vec![ attr("action", "convert"), attr("swap_type", "bluna_swap"), attr("asset_token", asset_token.as_str()), ])) } pub fn luna_swap_hook(deps: DepsMut, env: Env) -> Result<Response<TerraMsgWrapper>, ContractError> { let config: Config = read_config(deps.storage)?; let amount = query_balance(&deps.querier, env.contract.address, "uluna".to_string())?; let mut messages: Vec<CosmosMsg<TerraMsgWrapper>> = vec![]; if !amount.is_zero() { let offer_coin = Coin { amount, denom: LUNA_DENOM.to_string(), }; messages.push(create_swap_msg(offer_coin, config.base_denom)); } Ok(Response::new() .add_attributes(vec![attr("action", "luna_swap_hook")]) .add_messages(messages)) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/errors.rs
contracts/mirror_collector/src/errors.rs
use cosmwasm_std::{OverflowError, StdError}; use thiserror::Error; #[derive(Error, Debug, PartialEq)] pub enum ContractError { #[error("{0}")] Std(#[from] StdError), #[error("{0}")] OverflowError(#[from] OverflowError), #[error("Unauthorized")] Unauthorized {}, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/contract.rs
contracts/mirror_collector/src/contract.rs
use crate::errors::ContractError; use crate::migration::migrate_config; use crate::state::{read_config, store_config, Config}; use crate::swap::{convert, luna_swap_hook}; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ attr, to_binary, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Response, StdResult, WasmMsg, }; use cw20::Cw20ExecuteMsg; use mirror_protocol::collector::{ ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, }; use mirror_protocol::gov::Cw20HookMsg::DepositReward; use terra_cosmwasm::TerraMsgWrapper; use terraswap::querier::query_token_balance; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { let mir_ust_pair = if let Some(mir_ust_pair) = msg.mir_ust_pair { Some(deps.api.addr_canonicalize(&mir_ust_pair)?) } else { None }; store_config( deps.storage, &Config { owner: deps.api.addr_canonicalize(&msg.owner)?, distribution_contract: deps.api.addr_canonicalize(&msg.distribution_contract)?, terraswap_factory: deps.api.addr_canonicalize(&msg.terraswap_factory)?, mirror_token: deps.api.addr_canonicalize(&msg.mirror_token)?, base_denom: msg.base_denom, aust_token: deps.api.addr_canonicalize(&msg.aust_token)?, anchor_market: deps.api.addr_canonicalize(&msg.anchor_market)?, bluna_token: deps.api.addr_canonicalize(&msg.bluna_token)?, lunax_token: deps.api.addr_canonicalize(&msg.lunax_token)?, mir_ust_pair, }, )?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response<TerraMsgWrapper>, ContractError> { match msg { ExecuteMsg::UpdateConfig { owner, distribution_contract, terraswap_factory, mirror_token, base_denom, aust_token, anchor_market, bluna_token, mir_ust_pair, lunax_token, } => update_config( deps, info, owner, distribution_contract, terraswap_factory, mirror_token, base_denom, aust_token, anchor_market, bluna_token, mir_ust_pair, lunax_token, ), ExecuteMsg::Convert { asset_token } => { let asset_addr = deps.api.addr_validate(&asset_token)?; convert(deps, env, asset_addr) } ExecuteMsg::Distribute {} => distribute(deps, env), ExecuteMsg::LunaSwapHook {} => luna_swap_hook(deps, env), } } #[allow(clippy::too_many_arguments)] pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, distribution_contract: Option<String>, terraswap_factory: Option<String>, mirror_token: Option<String>, base_denom: Option<String>, aust_token: Option<String>, anchor_market: Option<String>, bluna_token: Option<String>, mir_ust_pair: Option<String>, lunax_token: Option<String>, ) -> Result<Response<TerraMsgWrapper>, ContractError> { let mut config: Config = read_config(deps.storage)?; if config.owner != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(ContractError::Unauthorized {}); } if let Some(owner) = owner { config.owner = deps.api.addr_canonicalize(&owner)?; } if let Some(distribution_contract) = distribution_contract { config.distribution_contract = deps.api.addr_canonicalize(&distribution_contract)?; } if let Some(terraswap_factory) = terraswap_factory { config.terraswap_factory = deps.api.addr_canonicalize(&terraswap_factory)?; } if let Some(mirror_token) = mirror_token { config.mirror_token = deps.api.addr_canonicalize(&mirror_token)?; } if let Some(base_denom) = base_denom { config.base_denom = base_denom; } if let Some(aust_token) = aust_token { config.aust_token = deps.api.addr_canonicalize(&aust_token)?; } if let Some(anchor_market) = anchor_market { config.anchor_market = deps.api.addr_canonicalize(&anchor_market)?; } if let Some(bluna_token) = bluna_token { config.bluna_token = deps.api.addr_canonicalize(&bluna_token)?; } // this triggers switching to use astroport for MIR swaps if let Some(mir_ust_pair) = mir_ust_pair { config.mir_ust_pair = Some(deps.api.addr_canonicalize(&mir_ust_pair)?); } if let Some(lunax_token) = lunax_token { config.lunax_token = deps.api.addr_canonicalize(&lunax_token)?; } store_config(deps.storage, &config)?; Ok(Response::new().add_attributes(vec![attr("action", "update_config")])) } // Anyone can execute send function to receive staking token rewards pub fn distribute(deps: DepsMut, env: Env) -> Result<Response<TerraMsgWrapper>, ContractError> { let config: Config = read_config(deps.storage)?; let amount = query_token_balance( &deps.querier, deps.api.addr_humanize(&config.mirror_token)?, env.contract.address, )?; Ok(Response::new() .add_messages(vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.mirror_token)?.to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: deps .api .addr_humanize(&config.distribution_contract)? .to_string(), amount, msg: to_binary(&DepositReward {})?, })?, funds: vec![], })]) .add_attributes(vec![ attr("action", "distribute"), attr("amount", amount.to_string()), ])) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), } } pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let state = read_config(deps.storage)?; let resp = ConfigResponse { owner: deps.api.addr_humanize(&state.owner)?.to_string(), distribution_contract: deps .api .addr_humanize(&state.distribution_contract)? .to_string(), terraswap_factory: deps .api .addr_humanize(&state.terraswap_factory)? .to_string(), mirror_token: deps.api.addr_humanize(&state.mirror_token)?.to_string(), base_denom: state.base_denom, aust_token: deps.api.addr_humanize(&state.aust_token)?.to_string(), anchor_market: deps.api.addr_humanize(&state.anchor_market)?.to_string(), bluna_token: deps.api.addr_humanize(&state.bluna_token)?.to_string(), mir_ust_pair: state .mir_ust_pair .map(|raw| deps.api.addr_humanize(&raw).unwrap().to_string()), lunax_token: deps.api.addr_humanize(&state.lunax_token)?.to_string(), }; Ok(resp) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> StdResult<Response> { migrate_config( deps.storage, deps.api.addr_canonicalize(msg.lunax_token.as_str())?, )?; Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/lib.rs
contracts/mirror_collector/src/lib.rs
pub mod contract; mod errors; mod migration; pub mod state; mod swap; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/state.rs
contracts/mirror_collector/src/state.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, StdResult, Storage}; use cosmwasm_storage::{singleton, singleton_read}; pub static KEY_CONFIG: &[u8] = b"config"; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub distribution_contract: CanonicalAddr, // collected rewards receiver pub terraswap_factory: CanonicalAddr, // terraswap factory contract pub mirror_token: CanonicalAddr, pub base_denom: String, // aUST params pub aust_token: CanonicalAddr, pub anchor_market: CanonicalAddr, // bLuna params pub bluna_token: CanonicalAddr, // Lunax params pub lunax_token: CanonicalAddr, // when set, use this address instead of querying from terraswap pub mir_ust_pair: Option<CanonicalAddr>, } pub fn store_config(storage: &mut dyn Storage, config: &Config) -> StdResult<()> { singleton(storage, KEY_CONFIG).save(config) } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, KEY_CONFIG).load() }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/migration.rs
contracts/mirror_collector/src/migration.rs
use cosmwasm_std::{CanonicalAddr, StdResult, Storage}; use cosmwasm_storage::{singleton, singleton_read, ReadonlySingleton, Singleton}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::state::{Config, KEY_CONFIG}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyConfig { pub owner: CanonicalAddr, pub distribution_contract: CanonicalAddr, pub terraswap_factory: CanonicalAddr, pub mirror_token: CanonicalAddr, pub base_denom: String, pub aust_token: CanonicalAddr, pub anchor_market: CanonicalAddr, pub bluna_token: CanonicalAddr, pub bluna_swap_denom: String, pub mir_ust_pair: Option<CanonicalAddr>, } pub fn migrate_config(storage: &mut dyn Storage, lunax_token: CanonicalAddr) -> StdResult<()> { let legacy_store: ReadonlySingleton<LegacyConfig> = singleton_read(storage, KEY_CONFIG); let legacy_config: LegacyConfig = legacy_store.load()?; let config = Config { owner: legacy_config.owner, distribution_contract: legacy_config.distribution_contract, terraswap_factory: legacy_config.terraswap_factory, mirror_token: legacy_config.mirror_token, base_denom: legacy_config.base_denom, aust_token: legacy_config.aust_token, anchor_market: legacy_config.anchor_market, bluna_token: legacy_config.bluna_token, lunax_token, mir_ust_pair: legacy_config.mir_ust_pair, }; let mut store: Singleton<Config> = singleton(storage, KEY_CONFIG); store.save(&config)?; Ok(()) } #[cfg(test)] mod migrate_tests { use crate::state::read_config; use super::*; use cosmwasm_std::{testing::mock_dependencies, Api}; pub fn config_old_store(storage: &mut dyn Storage) -> Singleton<LegacyConfig> { Singleton::new(storage, KEY_CONFIG) } #[test] fn test_config_migration() { let mut deps = mock_dependencies(&[]); let mut legacy_config_store = config_old_store(&mut deps.storage); legacy_config_store .save(&LegacyConfig { owner: deps.api.addr_canonicalize("owner0000").unwrap(), terraswap_factory: deps.api.addr_canonicalize("terraswapfactory").unwrap(), distribution_contract: deps.api.addr_canonicalize("gov0000").unwrap(), mirror_token: deps.api.addr_canonicalize("mirror0000").unwrap(), base_denom: "uusd".to_string(), aust_token: deps.api.addr_canonicalize("aust0000").unwrap(), anchor_market: deps.api.addr_canonicalize("anchormarket0000").unwrap(), bluna_token: deps.api.addr_canonicalize("bluna0000").unwrap(), bluna_swap_denom: "uluna".to_string(), mir_ust_pair: Some(deps.api.addr_canonicalize("astromirustpair0000").unwrap()), }) .unwrap(); migrate_config( &mut deps.storage, CanonicalAddr::from("lunax_token".as_bytes()), ) .unwrap(); let config: Config = read_config(&deps.storage).unwrap(); assert_eq!( config, Config { owner: deps.api.addr_canonicalize("owner0000").unwrap(), terraswap_factory: deps.api.addr_canonicalize("terraswapfactory").unwrap(), distribution_contract: deps.api.addr_canonicalize("gov0000").unwrap(), mirror_token: deps.api.addr_canonicalize("mirror0000").unwrap(), base_denom: "uusd".to_string(), aust_token: deps.api.addr_canonicalize("aust0000").unwrap(), anchor_market: deps.api.addr_canonicalize("anchormarket0000").unwrap(), bluna_token: deps.api.addr_canonicalize("bluna0000").unwrap(), lunax_token: CanonicalAddr::from("lunax_token".as_bytes()), mir_ust_pair: Some(deps.api.addr_canonicalize("astromirustpair0000").unwrap()), } ) } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/testing/tests.rs
contracts/mirror_collector/src/testing/tests.rs
use crate::contract::{execute, instantiate, query_config}; use crate::swap::MoneyMarketCw20HookMsg; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{to_binary, Coin, CosmosMsg, Decimal, SubMsg, Uint128, WasmMsg}; use cw20::Cw20ExecuteMsg; use mirror_protocol::collector::{ConfigResponse, ExecuteMsg, InstantiateMsg}; use mirror_protocol::gov::Cw20HookMsg::DepositReward; use terra_cosmwasm::{TerraMsg, TerraMsgWrapper, TerraRoute}; use terraswap::asset::{Asset, AssetInfo}; use terraswap::pair::{Cw20HookMsg as TerraswapCw20HookMsg, ExecuteMsg as TerraswapExecuteMsg}; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "mirror0000".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // it worked, let's query the state let config: ConfigResponse = query_config(deps.as_ref()).unwrap(); assert_eq!("terraswapfactory", config.terraswap_factory.as_str()); assert_eq!("uusd", config.base_denom.as_str()); } #[test] fn test_convert() { let mut deps = mock_dependencies(&[Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), }]); deps.querier.with_token_balances(&[( &"tokenAPPL".to_string(), &[(&MOCK_CONTRACT_ADDR.to_string(), &Uint128::from(100u128))], )]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::from(1000000u128))], ); deps.querier.with_terraswap_pairs(&[ (&"uusdtokenAPPL".to_string(), &"pairAPPL".to_string()), (&"uusdtokenMIRROR".to_string(), &"pairMIRROR".to_string()), ]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "tokenMIRROR".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Convert { asset_token: "tokenAPPL".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "tokenAPPL".to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: "pairAPPL".to_string(), amount: Uint128::from(100u128), msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, }) .unwrap(), }) .unwrap(), funds: vec![], }))] ); let msg = ExecuteMsg::Convert { asset_token: "tokenMIRROR".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // tax deduct 100 => 99 assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "pairMIRROR".to_string(), msg: to_binary(&TerraswapExecuteMsg::Swap { offer_asset: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string() }, amount: Uint128::from(99u128), }, max_spread: Some(Decimal::percent(50)), // astroport swap belief_price: None, to: None, }) .unwrap(), funds: vec![Coin { amount: Uint128::from(99u128), denom: "uusd".to_string(), }], }))] ); } #[test] fn test_convert_aust() { let mut deps = mock_dependencies(&[Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), }]); deps.querier.with_token_balances(&[( &"aust0000".to_string(), &[(&MOCK_CONTRACT_ADDR.to_string(), &Uint128::from(100u128))], )]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "mirror0000".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Convert { asset_token: "aust0000".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "aust0000".to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: "anchormarket0000".to_string(), amount: Uint128::from(100u128), msg: to_binary(&MoneyMarketCw20HookMsg::RedeemStable {}).unwrap(), }) .unwrap(), funds: vec![], }))] ); } #[test] fn test_convert_lunax() { let mut deps = mock_dependencies(&[Coin { denom: "uluna".to_string(), amount: Uint128::from(100u128), }]); deps.querier.with_token_balances(&[( &"lunax0000".to_string(), &[(&MOCK_CONTRACT_ADDR.to_string(), &Uint128::from(100u128))], )]); deps.querier .with_terraswap_pairs(&[(&"ulunalunax0000".to_string(), &"pairLunax".to_string())]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "mirror0000".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Convert { asset_token: "lunax0000".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "lunax0000".to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: "pairLunax".to_string(), amount: Uint128::from(100u128), msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, }) .unwrap(), }) .unwrap(), funds: vec![], })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: MOCK_CONTRACT_ADDR.to_string(), msg: to_binary(&ExecuteMsg::LunaSwapHook {}).unwrap(), funds: vec![], })), ] ); // suppose we sell the lunax for 100uluna let msg = ExecuteMsg::LunaSwapHook {}; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Custom(TerraMsgWrapper { route: TerraRoute::Market, msg_data: TerraMsg::Swap { offer_coin: Coin { amount: Uint128::from(100u128), denom: "uluna".to_string() }, ask_denom: "uusd".to_string(), }, }))], ) } #[test] fn test_convert_bluna() { let mut deps = mock_dependencies(&[Coin { denom: "uluna".to_string(), amount: Uint128::from(100u128), }]); deps.querier.with_token_balances(&[( &"bluna0000".to_string(), &[(&MOCK_CONTRACT_ADDR.to_string(), &Uint128::from(100u128))], )]); deps.querier .with_terraswap_pairs(&[(&"ulunabluna0000".to_string(), &"pairbLuna".to_string())]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "mirror0000".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Convert { asset_token: "bluna0000".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "bluna0000".to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: "pairbLuna".to_string(), amount: Uint128::from(100u128), msg: to_binary(&TerraswapCw20HookMsg::Swap { max_spread: None, belief_price: None, to: None, }) .unwrap(), }) .unwrap(), funds: vec![], })), SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: MOCK_CONTRACT_ADDR.to_string(), msg: to_binary(&ExecuteMsg::LunaSwapHook {}).unwrap(), funds: vec![], })), ] ); // suppose we sell the bluna for 100uluna let msg = ExecuteMsg::LunaSwapHook {}; let info = mock_info("owner0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Custom(TerraMsgWrapper { route: TerraRoute::Market, msg_data: TerraMsg::Swap { offer_coin: Coin { amount: Uint128::from(100u128), denom: "uluna".to_string() }, ask_denom: "uusd".to_string(), }, }))], ) } #[test] fn test_send() { let mut deps = mock_dependencies(&[]); deps.querier.with_token_balances(&[( &"mirror0000".to_string(), &[(&MOCK_CONTRACT_ADDR.to_string(), &Uint128::from(100u128))], )]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "mirror0000".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let msg = ExecuteMsg::Distribute {}; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "mirror0000".to_string(), msg: to_binary(&Cw20ExecuteMsg::Send { contract: "gov0000".to_string(), amount: Uint128::from(100u128), msg: to_binary(&DepositReward {}).unwrap(), }) .unwrap(), funds: vec![], }))] ) } #[test] fn test_set_astroport_mir_pair() { let mut deps = mock_dependencies(&[Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), }]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::from(1000000u128))], ); deps.querier .with_terraswap_pairs(&[(&"uusdtokenMIRROR".to_string(), &"pairMIRROR".to_string())]); let msg = InstantiateMsg { owner: "owner0000".to_string(), terraswap_factory: "terraswapfactory".to_string(), distribution_contract: "gov0000".to_string(), mirror_token: "tokenMIRROR".to_string(), base_denom: "uusd".to_string(), aust_token: "aust0000".to_string(), anchor_market: "anchormarket0000".to_string(), bluna_token: "bluna0000".to_string(), lunax_token: "lunax0000".to_string(), mir_ust_pair: None, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // first, try to swap when the pair is not set yet let msg = ExecuteMsg::Convert { asset_token: "tokenMIRROR".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // tax deduct 100 => 99 assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "pairMIRROR".to_string(), // terraswap pair msg: to_binary(&TerraswapExecuteMsg::Swap { offer_asset: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string() }, amount: Uint128::from(99u128), }, max_spread: Some(Decimal::percent(50)), belief_price: None, to: None, }) .unwrap(), funds: vec![Coin { amount: Uint128::from(99u128), denom: "uusd".to_string(), }], }))] ); // trigger the change by updating the configuration let msg = ExecuteMsg::UpdateConfig { owner: None, terraswap_factory: None, distribution_contract: None, mirror_token: None, base_denom: None, aust_token: None, anchor_market: None, bluna_token: None, mir_ust_pair: Some("astroportPAIR".to_string()), lunax_token: None, }; let info = mock_info("owner0000", &[]); execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // try again let msg = ExecuteMsg::Convert { asset_token: "tokenMIRROR".to_string(), }; let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // tax deduct 100 => 99 assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: "astroportPAIR".to_string(), // astroport pair msg: to_binary(&TerraswapExecuteMsg::Swap { // swap message format is same on astroport, will parse ok offer_asset: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string() }, amount: Uint128::from(99u128), }, max_spread: Some(Decimal::percent(50)), // astroport swap belief_price: None, to: None, }) .unwrap(), funds: vec![Coin { amount: Uint128::from(99u128), denom: "uusd".to_string(), }], }))] ); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/testing/mock_querier.rs
contracts/mirror_collector/src/testing/mock_querier.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, from_slice, to_binary, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, WasmQuery, }; use cw20::BalanceResponse; use std::collections::HashMap; use terra_cosmwasm::{TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper, TerraRoute}; use terraswap::asset::{AssetInfo, PairInfo}; /// mock_dependencies is a drop-in replacement for cosmwasm_std::testing::mock_dependencies /// this uses our CustomQuerier. pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new(MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)])); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<TerraQueryWrapper>, token_querier: TokenQuerier, tax_querier: TaxQuerier, terraswap_factory_querier: TerraswapFactoryQuerier, } #[derive(Clone, Default)] pub struct TokenQuerier { // this lets us iterate over all pairs that match the first string balances: HashMap<String, HashMap<String, Uint128>>, } impl TokenQuerier { pub fn new(balances: &[(&String, &[(&String, &Uint128)])]) -> Self { TokenQuerier { balances: balances_to_map(balances), } } } pub(crate) fn balances_to_map( balances: &[(&String, &[(&String, &Uint128)])], ) -> HashMap<String, HashMap<String, Uint128>> { let mut balances_map: HashMap<String, HashMap<String, Uint128>> = HashMap::new(); for (contract_addr, balances) in balances.iter() { let mut contract_balances_map: HashMap<String, Uint128> = HashMap::new(); for (addr, balance) in balances.iter() { contract_balances_map.insert(addr.to_string(), **balance); } balances_map.insert(contract_addr.to_string(), contract_balances_map); } balances_map } #[derive(Clone, Default)] pub struct TaxQuerier { rate: Decimal, // this lets us iterate over all pairs that match the first string caps: HashMap<String, Uint128>, } impl TaxQuerier { pub fn new(rate: Decimal, caps: &[(&String, &Uint128)]) -> Self { TaxQuerier { rate, caps: caps_to_map(caps), } } } pub(crate) fn caps_to_map(caps: &[(&String, &Uint128)]) -> HashMap<String, Uint128> { let mut owner_map: HashMap<String, Uint128> = HashMap::new(); for (denom, cap) in caps.iter() { owner_map.insert(denom.to_string(), **cap); } owner_map } #[derive(Clone, Default)] pub struct TerraswapFactoryQuerier { pairs: HashMap<String, String>, } impl TerraswapFactoryQuerier { pub fn new(pairs: &[(&String, &String)]) -> Self { TerraswapFactoryQuerier { pairs: pairs_to_map(pairs), } } } pub(crate) fn pairs_to_map(pairs: &[(&String, &String)]) -> HashMap<String, String> { let mut pairs_map: HashMap<String, String> = HashMap::new(); for (key, pair) in pairs.iter() { pairs_map.insert(key.to_string(), pair.to_string()); } pairs_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<TerraQueryWrapper> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Pair { asset_infos: [AssetInfo; 2] }, Balance { address: String }, } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<TerraQueryWrapper>) -> QuerierResult { match &request { QueryRequest::Custom(TerraQueryWrapper { route, query_data }) => { if route == &TerraRoute::Treasury { match query_data { TerraQuery::TaxRate {} => { let res = TaxRateResponse { rate: self.tax_querier.rate, }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } TerraQuery::TaxCap { denom } => { let cap = self .tax_querier .caps .get(denom) .copied() .unwrap_or_default(); let res = TaxCapResponse { cap }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } _ => panic!("DO NOT ENTER HERE"), } } else { panic!("DO NOT ENTER HERE") } } QueryRequest::Wasm(WasmQuery::Smart { contract_addr, msg }) => match from_binary(msg) .unwrap() { QueryMsg::Pair { asset_infos } => { let key = asset_infos[0].to_string() + asset_infos[1].to_string().as_str(); match self.terraswap_factory_querier.pairs.get(&key) { Some(v) => SystemResult::Ok(ContractResult::from(to_binary(&PairInfo { contract_addr: v.to_string(), liquidity_token: "liquidity".to_string(), asset_infos: [ AssetInfo::NativeToken { denom: "uusd".to_string(), }, AssetInfo::NativeToken { denom: "uusd".to_string(), }, ], }))), None => SystemResult::Err(SystemError::InvalidRequest { error: "No pair info exists".to_string(), request: msg.as_slice().into(), }), } } QueryMsg::Balance { address } => { let balances: &HashMap<String, Uint128> = match self.token_querier.balances.get(contract_addr) { Some(balances) => balances, None => { return SystemResult::Err(SystemError::InvalidRequest { error: format!( "No balance info exists for the contract {}", contract_addr ), request: msg.as_slice().into(), }) } }; let balance = match balances.get(&address) { Some(v) => *v, None => { return SystemResult::Ok(ContractResult::Ok( to_binary(&BalanceResponse { balance: Uint128::zero(), }) .unwrap(), )); } }; SystemResult::Ok(ContractResult::Ok( to_binary(&BalanceResponse { balance }).unwrap(), )) } }, _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new(base: MockQuerier<TerraQueryWrapper>) -> Self { WasmMockQuerier { base, token_querier: TokenQuerier::default(), tax_querier: TaxQuerier::default(), terraswap_factory_querier: TerraswapFactoryQuerier::default(), } } // configure the mint whitelist mock querier pub fn with_token_balances(&mut self, balances: &[(&String, &[(&String, &Uint128)])]) { self.token_querier = TokenQuerier::new(balances); } // configure the token owner mock querier pub fn with_tax(&mut self, rate: Decimal, caps: &[(&String, &Uint128)]) { self.tax_querier = TaxQuerier::new(rate, caps); } // configure the terraswap pair pub fn with_terraswap_pairs(&mut self, pairs: &[(&String, &String)]) { self.terraswap_factory_querier = TerraswapFactoryQuerier::new(pairs); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/src/testing/mod.rs
contracts/mirror_collector/src/testing/mod.rs
mod mock_querier; mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_collector/examples/schema.rs
contracts/mirror_collector/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::collector::{ ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(MigrateMsg), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/src/contract.rs
contracts/mirror_lock/src/contract.rs
use crate::state::{ read_config, read_position_lock_info, remove_position_lock_info, store_config, store_position_lock_info, total_locked_funds_read, total_locked_funds_store, Config, PositionLockInfo, }; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ attr, to_binary, Binary, CanonicalAddr, Deps, DepsMut, Empty, Env, MessageInfo, Response, StdError, StdResult, Uint128, }; use mirror_protocol::lock::{ ConfigResponse, ExecuteMsg, InstantiateMsg, PositionLockInfoResponse, QueryMsg, }; use terraswap::{ asset::{Asset, AssetInfo}, querier::query_balance, }; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { let config = Config { owner: deps.api.addr_canonicalize(&msg.owner)?, mint_contract: deps.api.addr_canonicalize(&msg.mint_contract)?, base_denom: msg.base_denom, lockup_period: msg.lockup_period, }; store_config(deps.storage, &config)?; total_locked_funds_store(deps.storage).save(&Uint128::zero())?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> { match msg { ExecuteMsg::UpdateConfig { owner, mint_contract, base_denom, lockup_period, } => update_config(deps, info, owner, mint_contract, base_denom, lockup_period), ExecuteMsg::LockPositionFundsHook { position_idx, receiver, } => lock_position_funds_hook(deps, env, info, position_idx, receiver), ExecuteMsg::UnlockPositionFunds { positions_idx } => { unlock_positions_funds(deps, env, info, positions_idx) } ExecuteMsg::ReleasePositionFunds { position_idx } => { release_position_funds(deps, env, info, position_idx) } } } pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, mint_contract: Option<String>, base_denom: Option<String>, lockup_period: Option<u64>, ) -> StdResult<Response> { let mut config: Config = read_config(deps.storage)?; if deps.api.addr_canonicalize(info.sender.as_str())? != config.owner { return Err(StdError::generic_err("unauthorized")); } if let Some(owner) = owner { config.owner = deps.api.addr_canonicalize(&owner)?; } if let Some(mint_contract) = mint_contract { config.mint_contract = deps.api.addr_canonicalize(&mint_contract)?; } if let Some(base_denom) = base_denom { config.base_denom = base_denom; } if let Some(lockup_period) = lockup_period { config.lockup_period = lockup_period; } store_config(deps.storage, &config)?; Ok(Response::new().add_attribute("action", "update_config")) } pub fn lock_position_funds_hook( deps: DepsMut, env: Env, info: MessageInfo, position_idx: Uint128, receiver: String, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_addr_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; if sender_addr_raw != config.mint_contract { return Err(StdError::generic_err("unauthorized")); } let current_balance: Uint128 = query_balance( &deps.querier, env.contract.address, config.base_denom.clone(), )?; let locked_funds: Uint128 = total_locked_funds_read(deps.storage).load()?; let position_locked_amount: Uint128 = current_balance.checked_sub(locked_funds)?; if position_locked_amount.is_zero() { // nothing to lock return Err(StdError::generic_err("Nothing to lock")); } let unlock_time: u64 = env.block.time.seconds() + config.lockup_period; let receiver_raw: CanonicalAddr = deps.api.addr_canonicalize(&receiver)?; let lock_info: PositionLockInfo = if let Ok(mut lock_info) = read_position_lock_info(deps.storage, position_idx) { // assert position receiver if receiver_raw != lock_info.receiver { // should never happen return Err(StdError::generic_err( "Receiver address do not match with existing record", )); } // increase amount lock_info.locked_amount += position_locked_amount; lock_info.unlock_time = unlock_time; lock_info } else { PositionLockInfo { idx: position_idx, receiver: receiver_raw, locked_amount: position_locked_amount, unlock_time, } }; store_position_lock_info(deps.storage, &lock_info)?; total_locked_funds_store(deps.storage).save(&current_balance)?; Ok(Response::new().add_attributes(vec![ attr("action", "lock_position_funds_hook"), attr("position_idx", position_idx.to_string()), attr( "locked_amount", position_locked_amount.to_string() + &config.base_denom, ), attr( "total_locked_amount", lock_info.locked_amount.to_string() + &config.base_denom, ), attr("unlock_time", unlock_time.to_string()), ])) } pub fn unlock_positions_funds( deps: DepsMut, env: Env, info: MessageInfo, positions_idx: Vec<Uint128>, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_addr_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; let unlockable_positions: Vec<PositionLockInfo> = positions_idx .iter() .filter_map(|position_idx| read_position_lock_info(deps.storage, *position_idx).ok()) .filter(|lock_info| { lock_info.receiver == sender_addr_raw && env.block.time.seconds() >= lock_info.unlock_time }) .collect(); let mut unlocked_positions: Vec<Uint128> = vec![]; let mut unlock_amount = Uint128::zero(); for lock_info in unlockable_positions { if unlocked_positions.contains(&lock_info.idx) { return Err(StdError::generic_err("Duplicate position_idx")); } unlocked_positions.push(lock_info.idx); // remove lock record remove_position_lock_info(deps.storage, lock_info.idx); unlock_amount += lock_info.locked_amount } let unlock_asset = Asset { info: AssetInfo::NativeToken { denom: config.base_denom.clone(), }, amount: unlock_amount, }; if unlock_asset.amount.is_zero() { return Err(StdError::generic_err( "There are no unlockable funds for the provided positions", )); } // decrease locked amount total_locked_funds_store(deps.storage).update(|current| { current .checked_sub(unlock_amount) .map_err(StdError::overflow) })?; let tax_amount: Uint128 = unlock_asset.compute_tax(&deps.querier)?; Ok(Response::new() .add_attributes(vec![ attr("action", "unlock_shorting_funds"), attr("unlocked_amount", unlock_asset.to_string()), attr("tax_amount", tax_amount.to_string() + &config.base_denom), ]) .add_message(unlock_asset.into_msg(&deps.querier, info.sender)?)) } pub fn release_position_funds( deps: DepsMut, _env: Env, info: MessageInfo, position_idx: Uint128, ) -> StdResult<Response> { let config: Config = read_config(deps.storage)?; let sender_addr_raw: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?; // only mint contract can force claim all funds, without checking lock period if sender_addr_raw != config.mint_contract { return Err(StdError::generic_err("unauthorized")); } let lock_info: PositionLockInfo = match read_position_lock_info(deps.storage, position_idx) { Ok(lock_info) => lock_info, Err(_) => { return Ok(Response::default()); // user previously unlocked funds, graceful return } }; // ingnore lock period, and unlock funds let unlock_amount: Uint128 = lock_info.locked_amount; let unlock_asset = Asset { info: AssetInfo::NativeToken { denom: config.base_denom.clone(), }, amount: unlock_amount, }; // remove position info remove_position_lock_info(deps.storage, position_idx); // decrease locked amount total_locked_funds_store(deps.storage).update(|current| { current .checked_sub(unlock_amount) .map_err(StdError::overflow) })?; let tax_amount: Uint128 = unlock_asset.compute_tax(&deps.querier)?; Ok(Response::new() .add_attributes(vec![ attr("action", "release_shorting_funds"), attr("position_idx", position_idx.to_string()), attr("unlocked_amount", unlock_asset.to_string()), attr("tax_amount", tax_amount.to_string() + &config.base_denom), ]) .add_message( unlock_asset.into_msg(&deps.querier, deps.api.addr_humanize(&lock_info.receiver)?)?, )) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&query_config(deps)?), QueryMsg::PositionLockInfo { position_idx } => { to_binary(&query_position_lock_info(deps, position_idx)?) } } } pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let state = read_config(deps.storage)?; let resp = ConfigResponse { owner: deps.api.addr_humanize(&state.owner)?.to_string(), mint_contract: deps.api.addr_humanize(&state.mint_contract)?.to_string(), base_denom: state.base_denom, lockup_period: state.lockup_period, }; Ok(resp) } pub fn query_position_lock_info( deps: Deps, position_idx: Uint128, ) -> StdResult<PositionLockInfoResponse> { let lock_info: PositionLockInfo = read_position_lock_info(deps.storage, position_idx)?; let resp = PositionLockInfoResponse { idx: lock_info.idx, receiver: deps.api.addr_humanize(&lock_info.receiver)?.to_string(), locked_amount: lock_info.locked_amount, unlock_time: lock_info.unlock_time, }; Ok(resp) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(_deps: DepsMut, _env: Env, _msg: Empty) -> StdResult<Response> { Ok(Response::default()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/src/lib.rs
contracts/mirror_lock/src/lib.rs
pub mod contract; mod state; #[cfg(test)] mod testing;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/src/state.rs
contracts/mirror_lock/src/state.rs
use cosmwasm_std::{CanonicalAddr, StdResult, Storage, Uint128}; use cosmwasm_storage::{ singleton, singleton_read, Bucket, ReadonlyBucket, ReadonlySingleton, Singleton, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; static PREFIX_LOCK_INFOS: &[u8] = b"lock_infos"; static KEY_CONFIG: &[u8] = b"config"; static KEY_TOTAL_LOCKED_FUNDS: &[u8] = b"total_locked_funds"; pub fn total_locked_funds_store(storage: &mut dyn Storage) -> Singleton<Uint128> { singleton(storage, KEY_TOTAL_LOCKED_FUNDS) } pub fn total_locked_funds_read(storage: &dyn Storage) -> ReadonlySingleton<Uint128> { singleton_read(storage, KEY_TOTAL_LOCKED_FUNDS) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub mint_contract: CanonicalAddr, pub base_denom: String, pub lockup_period: u64, } pub fn store_config(storage: &mut dyn Storage, config: &Config) -> StdResult<()> { singleton(storage, KEY_CONFIG).save(config) } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, KEY_CONFIG).load() } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PositionLockInfo { pub idx: Uint128, pub receiver: CanonicalAddr, pub locked_amount: Uint128, pub unlock_time: u64, } pub fn store_position_lock_info( storage: &mut dyn Storage, lock_info: &PositionLockInfo, ) -> StdResult<()> { let mut lock_infos_bucket: Bucket<PositionLockInfo> = Bucket::new(storage, PREFIX_LOCK_INFOS); lock_infos_bucket.save(&lock_info.idx.u128().to_be_bytes(), lock_info) } pub fn read_position_lock_info(storage: &dyn Storage, idx: Uint128) -> StdResult<PositionLockInfo> { let lock_infos_bucket: ReadonlyBucket<PositionLockInfo> = ReadonlyBucket::new(storage, PREFIX_LOCK_INFOS); lock_infos_bucket.load(&idx.u128().to_be_bytes()) } pub fn remove_position_lock_info(storage: &mut dyn Storage, idx: Uint128) { let mut lock_infos_bucket: Bucket<PositionLockInfo> = Bucket::new(storage, PREFIX_LOCK_INFOS); lock_infos_bucket.remove(&idx.u128().to_be_bytes()) }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/src/testing/tests.rs
contracts/mirror_lock/src/testing/tests.rs
use crate::contract::{execute, instantiate, query}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ attr, from_binary, BankMsg, BlockInfo, Coin, CosmosMsg, Decimal, Env, StdError, SubMsg, Timestamp, Uint128, }; use mirror_protocol::lock::{ ConfigResponse, ExecuteMsg, InstantiateMsg, PositionLockInfoResponse, QueryMsg, }; fn mock_env_with_block_time(time: u64) -> Env { let env = mock_env(); // register time Env { block: BlockInfo { height: 1, time: Timestamp::from_seconds(time), chain_id: "columbus".to_string(), }, ..env } } #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), lockup_period: 100u64, }; let info = mock_info("addr0000", &[]); // we can just call .unwrap() to assert this was a success let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // it worked, let's query the state let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap(); let config: ConfigResponse = from_binary(&res).unwrap(); assert_eq!("owner0000", config.owner.as_str()); assert_eq!("uusd", config.base_denom); assert_eq!("mint0000", config.mint_contract.as_str()); assert_eq!(100u64, config.lockup_period); } #[test] fn update_config() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), lockup_period: 100u64, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // update owner let info = mock_info("owner0000", &[]); let msg = ExecuteMsg::UpdateConfig { owner: Some("owner0001".to_string()), mint_contract: None, base_denom: None, lockup_period: None, }; let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // it worked, let's query the state let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap(); let config: ConfigResponse = from_binary(&res).unwrap(); assert_eq!("owner0001", config.owner.as_str()); // Unauthorized err let info = mock_info("owner0000", &[]); let msg = ExecuteMsg::UpdateConfig { owner: None, mint_contract: None, base_denom: None, lockup_period: None, }; let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); } #[test] fn lock_position_funds() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), lockup_period: 100u64, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); deps.querier.with_bank_balance( &MOCK_CONTRACT_ADDR.to_string(), vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), // lock 100uusd }], ); let msg = ExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(1u128), receiver: "addr0000".to_string(), }; // unauthorized attempt let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // successfull attempt let env = mock_env_with_block_time(20u64); let info = mock_info("mint0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "lock_position_funds_hook"), attr("position_idx", "1"), attr("locked_amount", "100uusd"), attr("total_locked_amount", "100uusd"), attr("unlock_time", "120"), ] ); // query lock info let res: PositionLockInfoResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::PositionLockInfo { position_idx: Uint128::from(1u128), }, ) .unwrap(), ) .unwrap(); assert_eq!( res, PositionLockInfoResponse { idx: Uint128::from(1u128), receiver: "addr0000".to_string(), locked_amount: Uint128::from(100u128), unlock_time: 120u64, } ); } #[test] fn unlock_position_funds() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1u64), &[(&"uusd".to_string(), &Uint128::from(100000000u128))], ); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), lockup_period: 100u64, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // lock 100 UST 3 times at different heights let msg = ExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(1u128), receiver: "addr0000".to_string(), }; let env = mock_env_with_block_time(1u64); let info = mock_info("mint0000", &[]); deps.querier.with_bank_balance( &MOCK_CONTRACT_ADDR.to_string(), vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), // lock 100uusd }], ); let _res = execute(deps.as_mut(), env, info, msg.clone()).unwrap(); let env = mock_env_with_block_time(10u64); let info = mock_info("mint0000", &[]); deps.querier.with_bank_balance( &MOCK_CONTRACT_ADDR.to_string(), vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(200u128), // lock 100uusd more }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); // query lock info let res: PositionLockInfoResponse = from_binary( &query( deps.as_ref(), mock_env(), QueryMsg::PositionLockInfo { position_idx: Uint128::from(1u128), }, ) .unwrap(), ) .unwrap(); assert_eq!( res, PositionLockInfoResponse { idx: Uint128::from(1u128), receiver: "addr0000".to_string(), locked_amount: Uint128::from(200u128), unlock_time: 10u64 + 100u64, // from last lock time } ); let msg = ExecuteMsg::UnlockPositionFunds { positions_idx: vec![Uint128::from(1u128)], }; // unauthorized attempt let info = mock_info("addr0001", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err(); assert_eq!( res, StdError::generic_err("There are no unlockable funds for the provided positions") ); // nothing to unlock let env = mock_env_with_block_time(50u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg.clone()).unwrap_err(); assert_eq!( res, StdError::generic_err("There are no unlockable funds for the provided positions") ); // unlock 200 UST let env = mock_env_with_block_time(120u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg.clone()).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "unlock_shorting_funds"), attr("unlocked_amount", "200uusd"), attr("tax_amount", "2uusd"), ] ); assert_eq!( res.messages, vec![SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "addr0000".to_string(), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(198u128), // minus tax }] }))] ); // lock info does not exist anymore let env = mock_env_with_block_time(120u64); let info = mock_info("mint0000", &[]); let res = execute(deps.as_mut(), env, info.clone(), msg).unwrap_err(); assert_eq!( res, StdError::generic_err("There are no unlockable funds for the provided positions") ); // lock 2 different positions let msg = ExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(2u128), receiver: "addr0000".to_string(), }; let env = mock_env_with_block_time(1u64); deps.querier.with_bank_balance( &MOCK_CONTRACT_ADDR.to_string(), vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), // lock 100uusd }], ); execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(3u128), receiver: "addr0000".to_string(), }; let env = mock_env_with_block_time(2u64); let info = mock_info("mint0000", &[]); deps.querier.with_bank_balance( &MOCK_CONTRACT_ADDR.to_string(), vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(300u128), // lock 200uusd }], ); execute(deps.as_mut(), env, info, msg).unwrap(); // unlock both positions let msg = ExecuteMsg::UnlockPositionFunds { positions_idx: vec![Uint128::from(2u128), Uint128::from(3u128)], }; let env = mock_env_with_block_time(102); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "unlock_shorting_funds"), attr("unlocked_amount", "300uusd"), attr("tax_amount", "3uusd"), ] ); } #[test] fn release_position_funds() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1u64), &[(&"uusd".to_string(), &Uint128::from(100000000u128))], ); let msg = InstantiateMsg { owner: "owner0000".to_string(), mint_contract: "mint0000".to_string(), base_denom: "uusd".to_string(), lockup_period: 100u64, }; let info = mock_info("addr0000", &[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // lock 100 UST let msg = ExecuteMsg::LockPositionFundsHook { position_idx: Uint128::from(1u128), receiver: "addr0000".to_string(), }; let env = mock_env_with_block_time(1u64); let info = mock_info("mint0000", &[]); deps.querier.with_bank_balance( &MOCK_CONTRACT_ADDR.to_string(), vec![Coin { denom: "uusd".to_string(), amount: Uint128::from(100u128), // lock 100uusd }], ); let _res = execute(deps.as_mut(), env, info, msg).unwrap(); let msg = ExecuteMsg::ReleasePositionFunds { position_idx: Uint128::from(1u128), }; // unauthorized attempt let env = mock_env_with_block_time(1u64); let info = mock_info("addr0000", &[]); let res = execute(deps.as_mut(), env, info, msg.clone()).unwrap_err(); assert_eq!(res, StdError::generic_err("unauthorized")); // only mint contract can unlock before lock period is over let env = mock_env_with_block_time(50u64); let info = mock_info("mint0000", &[]); let res = execute(deps.as_mut(), env.clone(), info.clone(), msg.clone()).unwrap(); assert_eq!( res.attributes, vec![ attr("action", "release_shorting_funds"), attr("position_idx", "1"), attr("unlocked_amount", "100uusd"), attr("tax_amount", "1uusd"), ] ); // lock info does not exist anymore let res = execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!(res.attributes.len(), 0); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/src/testing/mock_querier.rs
contracts/mirror_lock/src/testing/mock_querier.rs
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_slice, to_binary, Api, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, }; use std::collections::HashMap; use terra_cosmwasm::{TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper, TerraRoute}; pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> { let custom_querier: WasmMockQuerier = WasmMockQuerier::new( MockQuerier::new(&[(MOCK_CONTRACT_ADDR, contract_balance)]), MockApi::default(), ); OwnedDeps { api: MockApi::default(), storage: MockStorage::default(), querier: custom_querier, } } pub struct WasmMockQuerier { base: MockQuerier<TerraQueryWrapper>, tax_querier: TaxQuerier, } #[derive(Clone, Default)] pub struct TaxQuerier { rate: Decimal, // this lets us iterate over all pairs that match the first string caps: HashMap<String, Uint128>, } impl TaxQuerier { pub fn new(rate: Decimal, caps: &[(&String, &Uint128)]) -> Self { TaxQuerier { rate, caps: caps_to_map(caps), } } } pub(crate) fn caps_to_map(caps: &[(&String, &Uint128)]) -> HashMap<String, Uint128> { let mut owner_map: HashMap<String, Uint128> = HashMap::new(); for (denom, cap) in caps.iter() { owner_map.insert(denom.to_string(), **cap); } owner_map } impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here let request: QueryRequest<TerraQueryWrapper> = match from_slice(bin_request) { Ok(v) => v, Err(e) => { return SystemResult::Err(SystemError::InvalidRequest { error: format!("Parsing query request: {}", e), request: bin_request.into(), }) } }; self.handle_query(&request) } } impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest<TerraQueryWrapper>) -> QuerierResult { match &request { QueryRequest::Custom(TerraQueryWrapper { route, query_data }) => { if route == &TerraRoute::Treasury { match query_data { TerraQuery::TaxRate {} => { let res = TaxRateResponse { rate: self.tax_querier.rate, }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } TerraQuery::TaxCap { denom } => { let cap = self .tax_querier .caps .get(denom) .copied() .unwrap_or_default(); let res = TaxCapResponse { cap }; SystemResult::Ok(ContractResult::from(to_binary(&res))) } _ => panic!("DO NOT ENTER HERE"), } } else { panic!("DO NOT ENTER HERE") } } _ => self.base.handle_query(request), } } } impl WasmMockQuerier { pub fn new<A: Api>(base: MockQuerier<TerraQueryWrapper>, _api: A) -> Self { WasmMockQuerier { base, tax_querier: TaxQuerier::default(), } } #[allow(clippy::ptr_arg)] pub fn with_bank_balance(&mut self, addr: &String, balance: Vec<Coin>) { self.base.update_balance(addr, balance); } // configure the token owner mock querier pub fn with_tax(&mut self, rate: Decimal, caps: &[(&String, &Uint128)]) { self.tax_querier = TaxQuerier::new(rate, caps); } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/src/testing/mod.rs
contracts/mirror_lock/src/testing/mod.rs
mod mock_querier; mod tests;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/contracts/mirror_lock/examples/schema.rs
contracts/mirror_lock/examples/schema.rs
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mirror_protocol::lock::{ ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, PositionLockInfoResponse, QueryMsg, }; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(ConfigResponse), &out_dir); export_schema(&schema_for!(PositionLockInfoResponse), &out_dir); export_schema(&schema_for!(MigrateMsg), &out_dir); }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/gov.rs
packages/mirror_protocol/src/gov.rs
use cosmwasm_std::{Binary, Decimal, Uint128}; use cw20::Cw20ReceiveMsg; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; use crate::common::OrderBy; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub mirror_token: String, pub effective_delay: u64, pub default_poll_config: PollConfig, pub migration_poll_config: PollConfig, pub auth_admin_poll_config: PollConfig, pub voter_weight: Decimal, pub snapshot_period: u64, pub admin_manager: String, pub poll_gas_limit: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] #[allow(clippy::large_enum_variant)] pub enum ExecuteMsg { Receive(Cw20ReceiveMsg), UpdateConfig { owner: Option<String>, effective_delay: Option<u64>, default_poll_config: Option<PollConfig>, migration_poll_config: Option<PollConfig>, auth_admin_poll_config: Option<PollConfig>, voter_weight: Option<Decimal>, snapshot_period: Option<u64>, admin_manager: Option<String>, poll_gas_limit: Option<u64>, }, CastVote { poll_id: u64, vote: VoteOption, amount: Uint128, }, WithdrawVotingTokens { amount: Option<Uint128>, }, WithdrawVotingRewards { poll_id: Option<u64>, }, StakeVotingRewards { poll_id: Option<u64>, }, EndPoll { poll_id: u64, }, ExecutePoll { poll_id: u64, }, SnapshotPoll { poll_id: u64, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] #[allow(clippy::large_enum_variant)] pub enum Cw20HookMsg { /// StakeVotingTokens a user can stake their mirror token to receive rewards /// or do vote on polls StakeVotingTokens {}, /// CreatePoll need to receive deposit from a proposer CreatePoll { title: String, description: String, link: Option<String>, execute_msg: Option<PollExecuteMsg>, admin_action: Option<PollAdminAction>, }, /// Deposit rewards to be distributed among stakers and voters DepositReward {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PollExecuteMsg { pub contract: String, pub msg: Binary, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PollConfig { pub proposal_deposit: Uint128, pub voting_period: u64, pub quorum: Decimal, pub threshold: Decimal, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] #[allow(clippy::large_enum_variant)] pub enum PollAdminAction { /// Updates migration manager owner UpdateOwner { owner: String }, /// Executes a set of migrations. The poll can be executes as soon as it reaches the quorum and threshold ExecuteMigrations { migrations: Vec<(String, u64, Binary)>, }, /// Transfer admin privileges over Mirror contracts to the authorized_addr AuthorizeClaim { authorized_addr: String }, /// Updates Governace contract configuration UpdateConfig { owner: Option<String>, effective_delay: Option<u64>, default_poll_config: Option<PollConfig>, migration_poll_config: Option<PollConfig>, auth_admin_poll_config: Option<PollConfig>, voter_weight: Option<Decimal>, snapshot_period: Option<u64>, admin_manager: Option<String>, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, State {}, Staker { address: String, }, Poll { poll_id: u64, }, Polls { filter: Option<PollStatus>, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, }, Voter { poll_id: u64, address: String, }, Voters { poll_id: u64, start_after: Option<String>, limit: Option<u32>, order_by: Option<OrderBy>, }, Shares { start_after: Option<String>, limit: Option<u32>, order_by: Option<OrderBy>, }, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub mirror_token: String, pub effective_delay: u64, pub default_poll_config: PollConfig, pub migration_poll_config: PollConfig, pub auth_admin_poll_config: PollConfig, pub voter_weight: Decimal, pub snapshot_period: u64, pub admin_manager: String, pub poll_gas_limit: u64, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)] pub struct StateResponse { pub poll_count: u64, pub total_share: Uint128, pub total_deposit: Uint128, pub pending_voting_rewards: Uint128, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct PollResponse { pub id: u64, pub creator: String, pub status: PollStatus, pub end_time: u64, pub title: String, pub description: String, pub link: Option<String>, pub deposit_amount: Uint128, pub execute_data: Option<PollExecuteMsg>, pub yes_votes: Uint128, // balance pub no_votes: Uint128, // balance pub abstain_votes: Uint128, // balance pub total_balance_at_end_poll: Option<Uint128>, pub voters_reward: Uint128, pub staked_amount: Option<Uint128>, pub admin_action: Option<PollAdminAction>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct PollsResponse { pub polls: Vec<PollResponse>, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)] pub struct PollCountResponse { pub poll_count: u64, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct StakerResponse { pub balance: Uint128, pub share: Uint128, pub locked_balance: Vec<(u64, VoterInfo)>, pub withdrawable_polls: Vec<(u64, Uint128)>, pub pending_voting_rewards: Uint128, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct SharesResponseItem { pub staker: String, pub share: Uint128, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct SharesResponse { pub stakers: Vec<SharesResponseItem>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct VotersResponseItem { pub voter: String, pub vote: VoteOption, pub balance: Uint128, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] pub struct VotersResponse { pub voters: Vec<VotersResponseItem>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg { pub migration_poll_config: PollConfig, pub auth_admin_poll_config: PollConfig, pub admin_manager: String, pub poll_gas_limit: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct VoterInfo { pub vote: VoteOption, pub balance: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum PollStatus { InProgress, Passed, Rejected, Executed, Expired, Failed, } impl fmt::Display for PollStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum VoteOption { Yes, No, Abstain, } impl fmt::Display for VoteOption { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { VoteOption::Yes => write!(f, "yes"), VoteOption::No => write!(f, "no"), VoteOption::Abstain => write!(f, "abstain"), } } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/collateral_oracle.rs
packages/mirror_protocol/src/collateral_oracle.rs
use cosmwasm_std::Decimal; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; use terraswap::asset::AssetInfo; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub mint_contract: String, pub base_denom: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, mint_contract: Option<String>, base_denom: Option<String>, }, RegisterCollateralAsset { asset: AssetInfo, price_source: SourceType, multiplier: Decimal, }, RevokeCollateralAsset { asset: AssetInfo, }, UpdateCollateralPriceSource { asset: AssetInfo, price_source: SourceType, }, UpdateCollateralMultiplier { asset: AssetInfo, multiplier: Decimal, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, CollateralPrice { asset: String, timeframe: Option<u64>, }, CollateralAssetInfo { asset: String, }, CollateralAssetInfos {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub mint_contract: String, pub base_denom: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct CollateralPriceResponse { pub asset: String, pub rate: Decimal, pub last_updated: u64, pub multiplier: Decimal, pub is_revoked: bool, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct CollateralInfoResponse { pub asset: String, pub multiplier: Decimal, pub source_type: String, pub is_revoked: bool, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct CollateralInfosResponse { pub collaterals: Vec<CollateralInfoResponse>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg { pub mirror_tefi_oracle_addr: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SourceType { TefiOracle { oracle_addr: String, }, FixedPrice { price: Decimal, }, AmmPair { pair_addr: String, intermediate_denom: Option<String>, }, AnchorMarket { anchor_market_addr: String, }, Native { native_denom: String, }, Lunax { staking_contract_addr: String, }, } impl fmt::Display for SourceType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SourceType::TefiOracle { .. } => write!(f, "tefi_oracle"), SourceType::FixedPrice { .. } => write!(f, "fixed_price"), SourceType::AmmPair { .. } => write!(f, "amm_pair"), SourceType::AnchorMarket { .. } => write!(f, "anchor_market"), SourceType::Native { .. } => write!(f, "native"), SourceType::Lunax { .. } => write!(f, "lunax"), } } }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/oracle.rs
packages/mirror_protocol/src/oracle.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::common::OrderBy; use cosmwasm_std::Decimal; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub base_asset: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, }, /// Used to register new asset or to update feeder RegisterAsset { asset_token: String, feeder: String, }, FeedPrice { prices: Vec<(String, Decimal)>, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, Feeder { asset_token: String, }, Price { base_asset: String, quote_asset: String, }, Prices { start_after: Option<String>, limit: Option<u32>, order_by: Option<OrderBy>, }, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub base_asset: String, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct FeederResponse { pub asset_token: String, pub feeder: String, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PriceResponse { pub rate: Decimal, pub last_updated_base: u64, pub last_updated_quote: u64, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PricesResponseElem { pub asset_token: String, pub price: Decimal, pub last_updated_time: u64, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PricesResponse { pub prices: Vec<PricesResponseElem>, } /// We currently take no arguments for migrations #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {}
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/lib.rs
packages/mirror_protocol/src/lib.rs
pub mod admin_manager; pub mod collateral_oracle; pub mod collector; pub mod common; pub mod community; pub mod factory; pub mod gov; pub mod limit_order; pub mod lock; pub mod mint; pub mod oracle; // deprecated pub mod short_reward; pub mod staking;
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/short_reward.rs
packages/mirror_protocol/src/short_reward.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Decimal; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { ShortRewardWeight { premium_rate: Decimal }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ShortRewardWeightResponse { pub short_reward_weight: Decimal, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/lock.rs
packages/mirror_protocol/src/lock.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Uint128; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub mint_contract: String, pub base_denom: String, pub lockup_period: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, mint_contract: Option<String>, base_denom: Option<String>, lockup_period: Option<u64>, }, LockPositionFundsHook { position_idx: Uint128, receiver: String, }, UnlockPositionFunds { positions_idx: Vec<Uint128>, }, ReleasePositionFunds { position_idx: Uint128, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, PositionLockInfo { position_idx: Uint128 }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub mint_contract: String, pub base_denom: String, pub lockup_period: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PositionLockInfoResponse { pub idx: Uint128, pub receiver: String, pub locked_amount: Uint128, pub unlock_time: u64, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/mint.rs
packages/mirror_protocol/src/mint.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Decimal, Uint128}; use cw20::Cw20ReceiveMsg; use terraswap::asset::{Asset, AssetInfo}; use crate::common::OrderBy; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub oracle: String, pub collector: String, pub collateral_oracle: String, pub staking: String, pub terraswap_factory: String, pub lock: String, pub base_denom: String, pub token_code_id: u64, pub protocol_fee_rate: Decimal, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { Receive(Cw20ReceiveMsg), ////////////////////// /// Owner Operations ////////////////////// /// Update config; only owner is allowed to execute it UpdateConfig { owner: Option<String>, oracle: Option<String>, collector: Option<String>, collateral_oracle: Option<String>, terraswap_factory: Option<String>, lock: Option<String>, token_code_id: Option<u64>, protocol_fee_rate: Option<Decimal>, staking: Option<String>, }, /// Update asset related parameters UpdateAsset { asset_token: String, auction_discount: Option<Decimal>, min_collateral_ratio: Option<Decimal>, ipo_params: Option<IPOParams>, }, /// Generate asset token initialize msg and register required infos except token address RegisterAsset { asset_token: String, auction_discount: Decimal, min_collateral_ratio: Decimal, ipo_params: Option<IPOParams>, }, RegisterMigration { asset_token: String, end_price: Decimal, }, /// Asset feeder is allowed to trigger IPO event on preIPO assets TriggerIPO { asset_token: String, }, ////////////////////// /// User Operations ////////////////////// // Create position to meet collateral ratio OpenPosition { collateral: Asset, asset_info: AssetInfo, collateral_ratio: Decimal, short_params: Option<ShortParams>, }, /// Deposit more collateral Deposit { position_idx: Uint128, collateral: Asset, }, /// Withdraw collateral Withdraw { position_idx: Uint128, collateral: Option<Asset>, }, /// Convert all deposit collateral to asset Mint { position_idx: Uint128, asset: Asset, short_params: Option<ShortParams>, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ShortParams { pub belief_price: Option<Decimal>, pub max_spread: Option<Decimal>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct IPOParams { pub mint_end: u64, pub pre_ipo_price: Decimal, pub min_collateral_ratio_after_ipo: Decimal, pub trigger_addr: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum Cw20HookMsg { // Create position to meet collateral ratio OpenPosition { asset_info: AssetInfo, collateral_ratio: Decimal, short_params: Option<ShortParams>, }, /// Deposit more collateral Deposit { position_idx: Uint128 }, /// Convert specified asset amount and send back to user Burn { position_idx: Uint128 }, /// Buy discounted collateral from the contract with their asset tokens Auction { position_idx: Uint128 }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, AssetConfig { asset_token: String, }, Position { position_idx: Uint128, }, Positions { owner_addr: Option<String>, asset_token: Option<String>, start_after: Option<Uint128>, limit: Option<u32>, order_by: Option<OrderBy>, }, NextPositionIdx {}, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub oracle: String, pub collector: String, pub collateral_oracle: String, pub staking: String, pub terraswap_factory: String, pub lock: String, pub base_denom: String, pub token_code_id: u64, pub protocol_fee_rate: Decimal, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct AssetConfigResponse { pub token: String, pub auction_discount: Decimal, pub min_collateral_ratio: Decimal, pub end_price: Option<Decimal>, pub ipo_params: Option<IPOParams>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PositionResponse { pub idx: Uint128, pub owner: String, pub collateral: Asset, pub asset: Asset, pub is_short: bool, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)] pub struct PositionsResponse { pub positions: Vec<PositionResponse>, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)] pub struct NextPositionIdxResponse { pub next_position_idx: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg { pub tefi_oracle_contract: String, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/admin_manager.rs
packages/mirror_protocol/src/admin_manager.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Binary; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub admin_claim_period: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateOwner { owner: String, }, ExecuteMigrations { migrations: Vec<(String, u64, Binary)>, }, AuthorizeClaim { authorized_addr: String, }, ClaimAdmin { contract: String, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, MigrationRecords { start_after: Option<u64>, // timestamp (seconds) limit: Option<u32>, }, AuthRecords { start_after: Option<u64>, // timestamp (seconds) limit: Option<u32>, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub admin_claim_period: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct AuthRecordResponse { pub address: String, pub start_time: u64, pub end_time: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct AuthRecordsResponse { pub records: Vec<AuthRecordResponse>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrationRecordResponse { pub executor: String, pub time: u64, pub migrations: Vec<MigrationItem>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrationItem { pub contract: String, pub new_code_id: u64, pub msg: Binary, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrationRecordsResponse { pub records: Vec<MigrationRecordResponse>, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/staking.rs
packages/mirror_protocol/src/staking.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Decimal, Uint128}; use cw20::Cw20ReceiveMsg; use terraswap::asset::Asset; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub mirror_token: String, pub mint_contract: String, pub oracle_contract: String, pub terraswap_factory: String, pub base_denom: String, pub premium_min_update_interval: u64, pub short_reward_contract: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { Receive(Cw20ReceiveMsg), //////////////////////// /// Owner operations /// //////////////////////// UpdateConfig { owner: Option<String>, premium_min_update_interval: Option<u64>, short_reward_contract: Option<String>, }, RegisterAsset { asset_token: String, staking_token: String, }, DeprecateStakingToken { asset_token: String, new_staking_token: String, }, //////////////////////// /// User operations /// //////////////////////// Unbond { asset_token: String, amount: Uint128, }, /// Withdraw pending rewards Withdraw { // If the asset token is not given, then all rewards are withdrawn asset_token: Option<String>, }, /// Provides liquidity and automatically stakes the LP tokens AutoStake { assets: [Asset; 2], slippage_tolerance: Option<Decimal>, }, /// Hook to stake the minted LP tokens AutoStakeHook { asset_token: String, staking_token: String, staker_addr: String, prev_staking_token_amount: Uint128, }, ////////////////////////////////// /// Permission-less operations /// ////////////////////////////////// AdjustPremium { asset_tokens: Vec<String>, }, //////////////////////////////// /// Mint contract operations /// //////////////////////////////// IncreaseShortToken { asset_token: String, staker_addr: String, amount: Uint128, }, DecreaseShortToken { asset_token: String, staker_addr: String, amount: Uint128, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum Cw20HookMsg { Bond { asset_token: String }, DepositReward { rewards: Vec<(String, Uint128)> }, } /// We currently take no arguments for migrations #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg { pub tefi_oracle_contract: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, PoolInfo { asset_token: String, }, RewardInfo { staker_addr: String, asset_token: Option<String>, }, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub mirror_token: String, pub mint_contract: String, pub oracle_contract: String, pub terraswap_factory: String, pub base_denom: String, pub premium_min_update_interval: u64, pub short_reward_contract: String, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct PoolInfoResponse { pub asset_token: String, pub staking_token: String, pub total_bond_amount: Uint128, pub total_short_amount: Uint128, pub reward_index: Decimal, pub short_reward_index: Decimal, pub pending_reward: Uint128, pub short_pending_reward: Uint128, pub premium_rate: Decimal, pub short_reward_weight: Decimal, pub premium_updated_time: u64, pub migration_index_snapshot: Option<Decimal>, pub migration_deprecated_staking_token: Option<String>, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct RewardInfoResponse { pub staker_addr: String, pub reward_infos: Vec<RewardInfoResponseItem>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct RewardInfoResponseItem { pub asset_token: String, pub bond_amount: Uint128, pub pending_reward: Uint128, pub is_short: bool, // returns true if the position should be closed to keep receiving rewards // with the new lp token pub should_migrate: Option<bool>, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/limit_order.rs
packages/mirror_protocol/src/limit_order.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Uint128; use cw20::Cw20ReceiveMsg; use terraswap::asset::Asset; use crate::common::OrderBy; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { Receive(Cw20ReceiveMsg), /////////////////////// /// User Operations /// /////////////////////// SubmitOrder { offer_asset: Asset, ask_asset: Asset, }, CancelOrder { order_id: u64, }, /// Arbitrager execute order to get profit ExecuteOrder { execute_asset: Asset, order_id: u64, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum Cw20HookMsg { SubmitOrder { ask_asset: Asset, }, /// Arbitrager execute order to get profit ExecuteOrder { order_id: u64, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Order { order_id: u64, }, Orders { bidder_addr: Option<String>, start_after: Option<u64>, limit: Option<u32>, order_by: Option<OrderBy>, }, LastOrderId {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct OrderResponse { pub order_id: u64, pub bidder_addr: String, pub offer_asset: Asset, pub ask_asset: Asset, pub filled_offer_amount: Uint128, pub filled_ask_amount: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct OrdersResponse { pub orders: Vec<OrderResponse>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LastOrderIdResponse { pub last_order_id: u64, } /// We currently take no arguments for migrations #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {}
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/community.rs
packages/mirror_protocol/src/community.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Uint128; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, // mirror gov contract pub mirror_token: String, // mirror token address pub spend_limit: Uint128, // spend limit per each `spend` request } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, spend_limit: Option<Uint128>, }, Spend { recipient: String, amount: Uint128, }, } /// We currently take no arguments for migrations #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub mirror_token: String, pub spend_limit: Uint128, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/collector.rs
packages/mirror_protocol/src/collector.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub owner: String, pub distribution_contract: String, // collected rewards receiver pub terraswap_factory: String, pub mirror_token: String, pub base_denom: String, // aUST params pub aust_token: String, pub anchor_market: String, // bLuna params pub bluna_token: String, // Lunax params pub lunax_token: String, // when set, use this address instead of querying from terraswap pub mir_ust_pair: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] #[allow(clippy::large_enum_variant)] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, distribution_contract: Option<String>, terraswap_factory: Option<String>, mirror_token: Option<String>, base_denom: Option<String>, aust_token: Option<String>, anchor_market: Option<String>, bluna_token: Option<String>, mir_ust_pair: Option<String>, lunax_token: Option<String>, }, Convert { asset_token: String, }, Distribute {}, /// Internal operation to swap Luna for UST LunaSwapHook {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum MoneyMarketCw20HookMsg { /// Return stable coins to a user /// according to exchange rate RedeemStable {}, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub distribution_contract: String, // collected rewards receiver pub terraswap_factory: String, pub mirror_token: String, pub base_denom: String, pub aust_token: String, pub anchor_market: String, pub bluna_token: String, pub lunax_token: String, pub mir_ust_pair: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg { pub lunax_token: String, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/common.rs
packages/mirror_protocol/src/common.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Order; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum OrderBy { Asc, Desc, } // impl Into<Order> for OrderBy { // fn into(self) -> Order { // if self == OrderBy::Asc { // Order::Ascending // } else { // Order::Descending // } // } // } impl From<OrderBy> for Order { fn from(order_by: OrderBy) -> Order { if order_by == OrderBy::Asc { Order::Ascending } else { Order::Descending } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum Network { Mainnet, Testnet, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
Mirror-Protocol/mirror-contracts
https://github.com/Mirror-Protocol/mirror-contracts/blob/56cc6946b9457293ede6aa0feb296ee1d16f6974/packages/mirror_protocol/src/factory.rs
packages/mirror_protocol/src/factory.rs
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Binary, Decimal, Uint128}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub token_code_id: u64, pub base_denom: String, pub distribution_schedule: Vec<(u64, u64, Uint128)>, // [[start_time, end_time, distribution_amount], [], ...] } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { /////////////////// /// Owner Operations /////////////////// PostInitialize { owner: String, terraswap_factory: String, mirror_token: String, staking_contract: String, oracle_contract: String, mint_contract: String, commission_collector: String, }, UpdateConfig { owner: Option<String>, token_code_id: Option<u64>, distribution_schedule: Option<Vec<(u64, u64, Uint128)>>, // [[start_time, end_time, distribution_amount], [], ...] }, UpdateWeight { asset_token: String, weight: u32, }, Whitelist { /// asset name used to create token contract name: String, /// asset symbol used to create token contract symbol: String, /// oracle proxy that will provide prices for this asset oracle_proxy: String, /// used to create all necessary contract or register asset params: Params, }, PassCommand { contract_addr: String, msg: Binary, }, /// Revoke asset from MIR rewards pool /// and register end_price to mint contract RevokeAsset { asset_token: String, }, /// Migrate asset to new asset by registering /// end_price to mint contract and add /// the new asset to MIR rewards pool MigrateAsset { name: String, symbol: String, oracle_proxy: String, from_token: String, }, /////////////////// /// User Operations /////////////////// Distribute {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, DistributionInfo {}, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct ConfigResponse { pub owner: String, pub mirror_token: String, pub mint_contract: String, pub staking_contract: String, pub commission_collector: String, pub oracle_contract: String, pub terraswap_factory: String, pub token_code_id: u64, pub base_denom: String, pub genesis_time: u64, pub distribution_schedule: Vec<(u64, u64, Uint128)>, } // We define a custom struct for each query response #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct DistributionInfoResponse { pub weights: Vec<(String, u32)>, pub last_distributed: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg { pub tefi_oracle_contract: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct Params { /// Auction discount rate applied to asset mint pub auction_discount: Decimal, /// Minium collateral ratio applied to asset mint pub min_collateral_ratio: Decimal, /// Distribution weight (default is 30, which is 1/10 of MIR distribution weight) pub weight: Option<u32>, /// For pre-IPO assets, time period after asset creation in which minting is enabled pub mint_period: Option<u64>, /// For pre-IPO assets, collateral ratio for the asset after ipo pub min_collateral_ratio_after_ipo: Option<Decimal>, /// For pre-IPO assets, fixed price during minting period pub pre_ipo_price: Option<Decimal>, /// For pre-IPO assets, address authorized to trigger the ipo event pub ipo_trigger_addr: Option<String>, }
rust
Apache-2.0
56cc6946b9457293ede6aa0feb296ee1d16f6974
2026-01-04T20:21:07.037869Z
false
paulstansifer/unseemly
https://github.com/paulstansifer/unseemly/blob/dd1f55be7b09b741a25af954c7a902eeac00a0c2/src/expand.rs
src/expand.rs
use crate::{ ast::Ast, ast_walk::{LazyWalkReses, WalkRule, WalkRule::LiteralLike}, form::Form, name::{n, Name}, runtime::{eval, eval::Value}, walk_mode::{NegativeWalkMode, WalkMode}, }; custom_derive! { #[derive(Copy, Clone, Debug, Reifiable)] pub struct ExpandMacros {} } custom_derive! { #[derive(Copy, Clone, Debug, Reifiable)] pub struct UnusedNegativeExpandMacros {} } impl WalkMode for ExpandMacros { fn name() -> &'static str { "MExpand" } type Elt = Value; type Negated = UnusedNegativeExpandMacros; type AsPositive = ExpandMacros; type AsNegative = UnusedNegativeExpandMacros; type Err = <eval::Eval as WalkMode>::Err; type D = crate::walk_mode::Positive<ExpandMacros>; type ExtraInfo = (); fn get_walk_rule(f: &Form) -> WalkRule<ExpandMacros> { if f.name == n("macro_invocation") { let rule = f.eval.pos().clone(); cust_rc_box!(move |parts| { match rule { WalkRule::Custom(ref ts_fn) => ts_fn(parts.switch_mode::<eval::Eval>()), _ => icp!(), } }) } else { LiteralLike } } fn automatically_extend_env() -> bool { false } // TODO: maybe keep this from being called? fn underspecified(_: Name) -> Value { val!(enum "why is this here?", ) } fn walk_var(name: Name, _parts: &LazyWalkReses<ExpandMacros>) -> Result<Value, Self::Err> { use crate::runtime::reify::Reifiable; Ok(ast!((vr name)).reify()) // Even variables are literal in macro expansion! } } impl WalkMode for UnusedNegativeExpandMacros { fn name() -> &'static str { "XXXXX" } type Elt = Value; type Negated = ExpandMacros; type AsPositive = ExpandMacros; type AsNegative = UnusedNegativeExpandMacros; type Err = <eval::Eval as WalkMode>::Err; type D = crate::walk_mode::Negative<UnusedNegativeExpandMacros>; type ExtraInfo = (); fn get_walk_rule(_: &Form) -> WalkRule<UnusedNegativeExpandMacros> { icp!() } fn automatically_extend_env() -> bool { icp!() } } impl NegativeWalkMode for UnusedNegativeExpandMacros { fn needs_pre_match() -> bool { panic!() } } // I *think* the environment doesn't matter pub fn expand(ast: &Ast) -> Result<Ast, ()> { use crate::runtime::reify::Reifiable; Ok(Ast::reflect(&crate::ast_walk::walk::<ExpandMacros>(ast, &LazyWalkReses::new_empty())?)) } #[test] fn expand_basic_macros() { use crate::{core_macro_forms::macro_invocation, util::assoc::Assoc}; // Quasiquotation doesn't work with `u!`, so we have to use `ast!`: let macro_body_0_args = ast!({"Expr" "quote_expr" : "nt" => (vr "Expr"), "body" => (++ true (,u!({apply : plus [one ; two]})))}); let uqef = crate::core_qq_forms::unquote_form(n("Expr"), true, 1); let uqpf = crate::core_qq_forms::unquote_form(n("Pat"), true, 1); let macro_def_0_args = u!({Syntax scope : [] {literal => [] : {call : DefaultToken} (at just_add_1_and_2)} just_add_1_and_2_macro (,macro_body_0_args.clone()) }); // Full of closures, so hard to compare: assert_m!(eval::eval_top(&macro_def_0_args), Ok(_)); assert_eq!( expand(&u!({ macro_invocation( form_pat!((lit "just_add_1_and_2")), n("just_add_1_and_2_macro"), vec![], eval::Closure { body: macro_body_0_args, params: vec![], env: Assoc::new() }, vec![], ); })), Ok(u!({apply : plus [one ; two]})) ); // A macro that generates a one-adding expression: let macro_body_1_arg = ast!({"Expr" "quote_expr" : "nt" => (vr "Expr"), "body" => (++ true (,u!({apply : plus [one ; { uqef.clone(); (~) e}]})))}); let macro_def_1_arg = u!({Syntax scope : [] {seq => [* ["elt"]] : [{literal => [] : {call : DefaultToken} (at add_1)} ; {named => ["part_name"] : e {call : Expr}}] } add_1_macro (,macro_body_1_arg.clone()) }); // Full of closures, so hard to compare: assert_m!(eval::eval_top(&macro_def_1_arg), Ok(_)); assert_eq!( expand(&u!({ macro_invocation( // duplicates the syntax syntax above form_pat!([(lit "add_1"), (named "e", (call "Expr"))]), n("add_1_macro"), vec![], eval::Closure { body: macro_body_1_arg, params: vec![n("e")], env: Assoc::new() }, vec![], ); five // syntax argument for e })), Ok(u!({apply : plus [one ; five]})) ); // A let macro: let macro_body_let = ast!({"Expr" "quote_expr" : "nt" => (vr "Expr"), "body" => (++ true (,u!( {match : { uqef.clone(); (~) let_val} [{ uqpf.clone(); (~) let_pat } {uqef.clone(); (~) let_body}]})))}); let macro_def_let = u!({Syntax scope : [T; S] {seq => [* ["elt"]] : [{literal => [] : {call : DefaultToken} (at let)} ; {named => ["part_name"] : let_pat {call : Pat}} ; {named => ["part_name"] : let_val {call : Expr}} ; {named => ["part_name"] : let_body {call : Expr}}] } let_macro (,macro_body_let.clone()) }); // Full of closures, so hard to compare: assert_m!(eval::eval_top(&macro_def_let), Ok(_)); assert_eq!( expand(&u!({ macro_invocation( // duplicates the syntax syntax above form_pat!([(lit "let"), (named "let_pat", (call "Pat")), (named "let_val", (call "Expr")), (named "let_body", (call "Expr"))]), n("let_macro"), vec![u!(T), u!(S)], eval::Closure { body: macro_body_let.clone(), params: vec![n("let_val"), n("let_pat"), n("let_body")], env: Assoc::new(), }, vec![], ); x // let_pat five // let_val {apply : times [x ; eight]} // let_body })), Ok(u!({match : five [x {apply : times [x ; eight]}]})) ); // The previous example was unrealistic, since no actual binding took place in the input. // (It works because the binding is actually irrelevant at this stage.) // Once more, with binding: assert_eq!( expand(&u!({ macro_invocation( // duplicates the syntax syntax above form_pat!([(lit "let"), (named "let_pat", (call "Pat")), (named "let_val", (call "Expr")), (named "let_body", (import ["let_pat" = "let_val"], (call "Expr")))]), n("let_macro"), vec![u!(T), u!(S)], eval::Closure { body: macro_body_let, params: vec![n("let_val"), n("let_pat"), n("let_body")], env: Assoc::new(), }, vec![], ); x // let_pat five // let_val (, raw_ast!(ExtendEnv(u!({apply : times [x ; eight]}), beta!(["let_pat" = "let_val"])))) // let_body })), Ok(u!({match : five [x {apply : times [x ; eight]}]})) ); // An n-ary let macro: let dddef = crate::core_qq_forms::dotdotdot_form(n("Expr")); let dddpf = crate::core_qq_forms::dotdotdot_form(n("Pat")); let macro_body_nary_let = ast!({"Expr" "quote_expr" : "nt" => (vr "Expr"), "body" => (++ true (, u!( {match : {tuple_expr : [{dddef.clone() ; [(~ let_val)] { uqef.clone(); (~) let_val}}]} [{Pat tuple_pat : [{dddpf.clone() ; [(~ let_pat)] { uqpf.clone(); (~) let_pat }}]} { uqef.clone(); (~) let_body}]})))}); let macro_def_nary_let = u!({Syntax scope : [T; S] {seq => [* ["elt"]] : [{literal => [] : {call : DefaultToken} (at let)} ; {star => ["body"] : {named => ["part_name"] : let_pat {call : Pat}}} ; {star => ["body"] : {named => ["part_name"] : let_val {call : Expr}}} ; {named => ["part_name"] : let_body {call : Expr}}] } nary_let_macro (,macro_body_nary_let.clone()) }); // Full of closures, so hard to compare: assert_m!(eval::eval_top(&macro_def_nary_let), Ok(_)); assert_eq!( expand(&u!({ macro_invocation( // duplicates the syntax syntax above form_pat!([(lit "let"), (star (named "let_pat", (call "Pat"))), (star (named "let_val", (call "Expr"))), (named "let_body", (call "Expr"))]), n("nary_let_macro"), vec![u!(T), u!(S)], eval::Closure { body: macro_body_nary_let, params: vec![n("let_val"), n("let_pat"), n("let_body")], env: Assoc::new(), }, vec![], ); [x; y] // let_pat [five; seven] // let_val {apply : times [x ; eight]} // let_body })), Ok(u!({match : {tuple_expr : [five; seven]} [{Pat tuple_pat : [x; y]} {apply : times [x; eight]}]})) ); }
rust
MIT
dd1f55be7b09b741a25af954c7a902eeac00a0c2
2026-01-04T20:20:52.848824Z
false
paulstansifer/unseemly
https://github.com/paulstansifer/unseemly/blob/dd1f55be7b09b741a25af954c7a902eeac00a0c2/src/ty_compare.rs
src/ty_compare.rs
use crate::{ ast::*, ast_walk::{ walk, Clo, LazyWalkReses, WalkRule::{self, *}, }, core_forms::find_core_form, form::{Both, Form}, name::*, ty::TyErr, util::assoc::Assoc, walk_mode::WalkMode, }; use std::{cell::RefCell, collections::HashMap, rc::Rc}; // Let me write down an example subtyping hierarchy, to stop myself from getting confused. // ⊤ (any type/dynamic type/"dunno"/∀X.X) // ╱ | | ╲ // Num ∀X Y.(X⇒Y) Nat⇒Int ∀X Y.(X,Y) // | ╱ ╲ ╱ ╲ ╲ // Int ∀Y.(Bool⇒Y) ∀X.(X⇒Bool) Int⇒Int Nat⇒Nat ∀X.(X, Bool) // | ╲ ╱ ╲ ╱ | // Nat Bool⇒Bool Int⇒Nat (Nat,Bool) // ╲ | | ╱ // ⊥ (uninhabited type/panic/"can't happen"/enum{}) // // How do we see if S is a subtype of T? // First, we positively walk S, turning `∀X.(X⇒X)` into `(G23⇒G23)` // (where `G23` is a generated type name), // producing SArbitrary // Then, we negatively walk T, with SArbitrary as context, similarly eliminating `∀`. // We use side-effects to see if generated type names in T can be consistently assigned // to make everything match. // // Is (Int, Nat) <: ∀X. (X, X)? // If so, we could instantiate every type variable at ⊤, eliminating all constraints! // Eliminating ⊤ doesn't prevent (Bool⇒Bool, String⇒String) <: ∀X. (X X), via X=∀Y. Y⇒Y. // I think that this means we need to constrain ∀-originated variables to being equal, // not subtypes. // // Okay, we know that negative positions have the opposite subtyping relationship... // // <digression about something not currently implemented> // // ...weirdly, this kinda suggests that there's an alternative formulation of `∀` // that's more concise, and might play better with our system, // and (for better or worse) can't express certain "exotic" types. // In this forumlation, instead of writing `∀X. …`, // we paste `∀` in front of a negative-position variable: // id: ∀X ⇒ X // map: List<∀X> (X ⇒ ∀Y) ⇒ List<Y> (need `letrec`-style binding!) // boring_map: List<Int> (Int ⇒ ∀Y) ⇒ List<Y> (need `∀` to distinguish binders and refs!) // boring_map2: List<∀X> List<X> (X X ⇒ ∀Y) ⇒ List<Y> // let_macro: "[let :::[ ;[var ⇑ v]; = ;[ expr<∀T> ]; ]::: in ;[expr<∀S> ↓ ...{v = T}...]; ]" // -> expr<S> // // Okay, let's walk through this. Let's suppose that we have some type variables in scope: // is `(A ⇒ B) ⇒ ((∀A ⇒ F) ⇒ D)` a subtype of `(∀EE ⇒ BB) ⇒ (CC ⇒ EE)`? // // It starts as a negative walk of the purported supertype. Destructuring succeeds. // Add ∀ed type variables to an environment. Now `∀X` might as well be `X`. // - is [A]`((A ⇒ F) ⇒ D)` a subtype of [EE]`(CC ⇒ EE)`? Destructuring succeeds. // - is [A]`D` a subtype of [EE]`EE`? Set EE := `D`. // - is [EE]`CC` a subtype of [A]`(A ⇒ F)`? Depends on `CC`. // Assuming CC is `CC_arg ⇒ CC_ret`, we set A := CC_arg. // - is [EE]`(EE ⇒ BB)` a subtype of [A]`(A ⇒ B)`? Destructuring succeeds. // - is [EE]`BB` a subtype of [A]`B`? Depends on the environment. // - is [A]`A` a subtype of [EE]`EE`? Both have already been set, so: // - does `CC_arg` equal `D`? Depends on the environment. // // What if we re-order the side-effects? // ⋮ // - is [A]`A` a subtype of [EE]`EE`? Set A := `A_and_EE` and EE := `A_and_EE`. // (What happens when names escape the scope that defined them??) // ⋮ // - is [A]`D` a subtype of [EE]`EE`? EE is set to `A_and_EE`, so set A_and_EE := `D` // - is [EE]`CC` a subtype of [A]`(A ⇒ F)`? Depends on `CC`. // Assuming CC is `CC_arg ⇒ CC_ret`, does `D` equal `CC_arg`?. // // Note that, if we allowed ∀ed type variables to participate in subtyping, // these two orders would demand opposite relationships between `D` and `CC_arg`. // // // // So, we have this negative/positive distinction. Consider: // Nat (Int => String) => (∀X ⇒ X) // If you count how many negations each type is under, // you get a picture of the inputs and outputs of the type at a high level. // So, the type needs a `Nat` and a `String` and an `X`, and provides an `Int` and an `X` // (The `Int` is doubly-negated; the function promises to provide it to the function it is passed.). // // What about `Nat (∀X => Nat) => X`, assuming that we have access to `transmogrify`? // When we typecheck an invocation of it, we expect to know the exact type of its arguments, // but that exact type might well still be `∀X ⇒ Nat`, // meaning we have no idea what type we'll return, and no `∀`s left to explain the lack of knowledge. // // </digression> // // But let's not do that weird thing just yet. // // The other thing that subtyping has to deal with is `...[T >> T]...`. // /// Follow variable references in `env` and underdeterminednesses in `unif` /// until we hit something that can't move further. /// TODO #28: could this be replaced by `SynthTy`? /// TODO: This doesn't change `env`, and none of its clients care. It should just return `Ast`. pub fn resolve(Clo { it: t, env }: Clo<Ast>, unif: &HashMap<Name, Clo<Ast>>) -> Clo<Ast> { let u_f = underdetermined_form.with(|u_f| u_f.clone()); let resolved = match t.c() { VariableReference(vr) => { match env.find(vr) { // HACK: leave mu-protected variables alone, instead of recurring forever Some(vr_ast) if vr_ast.c() == &VariableReference(*vr) => None, Some(different) => Some(Clo { it: different.clone(), env: env.clone() }), None => None, } } Node(form, parts, _) if form == &find_core_form("Type", "type_apply") => { // Expand defined type applications. // This is sorta similar to the type synthesis for "type_apply", // but it does not recursively process the arguments (which may be underdetermined!). let arg_terms = parts.get_rep_leaf_or_panic(n("arg")); let resolved = resolve( Clo { it: parts.get_leaf_or_panic(&n("type_rator")).clone(), env: env.clone() }, unif, ); match resolved { Clo { it: vr_ast, env } if matches!(vr_ast.c(), VariableReference(_)) => { let rator_vr = match vr_ast.c() { VariableReference(rator_vr) => *rator_vr, _ => icp!(), }; // e.g. `X<int, Y>` underneath `mu X. ...` // Rebuild a type_apply, but evaulate its arguments // This kind of thing is necessary because // we wish to avoid aliasing problems at the type level. // In System F, this is avoided by performing capture-avoiding substitution. use crate::util::mbe::EnvMBE; let mut new__tapp_parts = EnvMBE::new_from_leaves(assoc_n!("type_rator" => ast!((vr rator_vr)))); let mut args = vec![]; for individual__arg_res in arg_terms { args.push(EnvMBE::new_from_leaves( assoc_n!("arg" => individual__arg_res.clone()), )); } new__tapp_parts.add_anon_repeat(args); let res = raw_ast!(Node( find_core_form("Type", "type_apply"), new__tapp_parts, crate::beta::ExportBeta::Nothing )); if res != t { Some(Clo { it: res, env: env }) } else { None } } Clo { it: defined_type, env } => { match defined_type.ty_destructure(find_core_form("Type", "forall_type"), &t) { Err(_) => None, // Broken "type_apply", but let it fail elsewhere Ok(ref got_forall) => { let params = got_forall.get_rep_leaf_or_panic(n("param")); if params.len() != arg_terms.len() { panic!( "Kind error: wrong number of arguments: {} vs {}", params.len(), arg_terms.len() ); } let mut actual_params = Assoc::new(); for (name, arg_term) in params.iter().zip(arg_terms) { actual_params = actual_params.set(name.to_name(), arg_term.clone()); } Some(Clo { it: crate::alpha::substitute( crate::core_forms::strip_ee( got_forall.get_leaf_or_panic(&n("body")), ), &actual_params, ), env: env, }) } } } } } // TODO: This needs to be implemented (unless issue #28 obviates it) // Ast(Node(ref form, ref parts, _)) if form == &find_core_form("Type", "dotdotdot") => { // } Node(ref form, ref parts, _) if form == &u_f => { // underdetermined unif.get(&parts.get_leaf_or_panic(&n("id")).to_name()).cloned() } _ => None, }; resolved.map(|clo: Clo<Ast>| resolve(clo, unif)).unwrap_or(Clo { it: t, env: env }) } thread_local! { // Invariant: `underdetermined_form`s in the HashMap must not form a cycle. pub static unification: RefCell<HashMap<Name, Clo<Ast>>> = RefCell::new(HashMap::<Name, Clo<Ast>>::new()); pub static underdetermined_form : Rc<Form> = Rc::new(Form { name: n("<underdetermined>"), grammar: Rc::new(form_pat!((named "id", atom))), type_compare: Both( // pre-match handle s the negative case; we need to do the positive case manually: cust_rc_box!(|udet_parts| { let id = udet_parts.get_term(n("id")).to_name(); unification.with(|unif| { let unif = unif.borrow(); // TODO: don't use the id in an error message; it's user-hostile: let clo = unif.get(&id).ok_or(TyErr::UnboundName(id))?; canonicalize(&clo.it, clo.env.clone()) }) }), NotWalked), synth_type: Both(NotWalked, NotWalked), eval: Both(NotWalked, NotWalked), quasiquote: Both(NotWalked, NotWalked) }) } custom_derive! { #[derive(Copy, Clone, Debug, Reifiable)] pub struct Canonicalize {} } custom_derive! { #[derive(Copy, Clone, Debug, Reifiable)] pub struct Subtype {} } // TODO #28: Canonicalization is almost the same thing as `SynthTy`. // Try to replace it with `SynthTy` and see what happens. impl WalkMode for Canonicalize { fn name() -> &'static str { "Canon" } type Elt = Ast; type Negated = Subtype; type AsPositive = Canonicalize; type AsNegative = Subtype; type Err = TyErr; type D = crate::walk_mode::Positive<Canonicalize>; type ExtraInfo = (); // Actually, always `LiteralLike`, but need to get the lifetime as long as `f`'s fn get_walk_rule(f: &Form) -> WalkRule<Canonicalize> { f.type_compare.pos().clone() } fn automatically_extend_env() -> bool { true } fn walk_var(n: Name, cnc: &LazyWalkReses<Canonicalize>) -> Result<Ast, TyErr> { match cnc.env.find(&n) { // If it's protected, stop: Some(t) if &VariableReference(n) == t.c() => Ok(t.clone()), Some(t) => canonicalize(t, cnc.env.clone()), None => Ok(ast!((vr n))), // TODO why can this happen? } } // Simply protect the name; don't try to unify it. fn underspecified(nm: Name) -> Ast { ast!((vr nm)) } } fn splice_ddd( ddd_parts: &LazyWalkReses<Subtype>, context_elts: Vec<Ast>, ) -> Result<Option<(Vec<Assoc<Name, Ast>>, Ast)>, <Subtype as WalkMode>::Err> { let ddd_form = crate::core_forms::find("Type", "dotdotdot_type"); let tuple_form = crate::core_forms::find("Type", "tuple"); let undet_form = underdetermined_form.with(|u_f| u_f.clone()); if context_elts.len() == 1 { match context_elts[0].destructure(ddd_form.clone()) { None => {} // False alarm; just a normal single repetition Some(sub_parts) => { match sub_parts.get_leaf_or_panic(&n("body")).destructure(ddd_form) { Some(_) => icp!("TODO: count up nestings of :::[]:::"), None => return Ok(None), // :::[]::: is a subtype of :::[]::: } } } } let drivers: Vec<(Name, Ast)> = unification.with(|unif| { ddd_parts .get_rep_term(n("driver")) .iter() .map(|a: &Ast| { ( a.vr_to_name(), resolve(Clo { it: a.clone(), env: ddd_parts.env.clone() }, &unif.borrow()).it, ) }) .collect() }); let expected_len = context_elts.len(); let mut envs_with_walked_drivers = vec![]; envs_with_walked_drivers.resize_with(expected_len, Assoc::new); // Make sure tuples are the right length, // and force underdetermined types to *be* tuples of the right length. for (name, driver) in drivers { // TODO: Why not use `ty_destructure` here? if let Some(tuple_parts) = driver.destructure(tuple_form.clone()) { let components = tuple_parts.get_rep_leaf_or_panic(n("component")); if components.len() != expected_len { return Err(TyErr::LengthMismatch( components.into_iter().map(|a| a.clone()).collect(), expected_len, )); } for i in 0..expected_len { envs_with_walked_drivers[i] = envs_with_walked_drivers[i].set(name, components[i].clone()); } } else if let Some(undet_parts) = driver.destructure(undet_form.clone()) { unification.with(|unif| { let mut undet_components = vec![]; undet_components .resize_with(expected_len, || Subtype::underspecified(n("ddd_bit"))); unif.borrow_mut().insert(undet_parts.get_leaf_or_panic(&n("id")).to_name(), Clo { it: ast!({"Type" "tuple" : "component" => (,seq undet_components.clone()) }), env: ddd_parts.env.clone(), }); for i in 0..expected_len { envs_with_walked_drivers[i] = envs_with_walked_drivers[i].set(name, undet_components[i].clone()); } }) } else { return Err(TyErr::UnableToDestructure(driver, n("tuple"))); } } Ok(Some((envs_with_walked_drivers, ddd_parts.get_term(n("body"))))) } impl WalkMode for Subtype { fn name() -> &'static str { "SubTy" } type Elt = Ast; type Negated = Canonicalize; type AsPositive = Canonicalize; type AsNegative = Subtype; type Err = TyErr; type D = crate::walk_mode::Negative<Subtype>; type ExtraInfo = (); fn get_walk_rule(f: &Form) -> WalkRule<Subtype> { f.type_compare.neg().clone() } fn automatically_extend_env() -> bool { true } fn underspecified(name: Name) -> Ast { underdetermined_form.with(|u_f| { let new_name = Name::gensym(&format!("{}⚁", name)); ast!({ u_f.clone() ; "id" => (at new_name)}) }) } /// Look up the reference and keep going. fn walk_var(n: Name, cnc: &LazyWalkReses<Subtype>) -> Result<Assoc<Name, Ast>, TyErr> { let lhs: &Ast = cnc.env.find_or_panic(&n); if lhs.c() == &VariableReference(n) { // mu-protected! return if cnc.context_elt().c() == &VariableReference(n) { // mu-protected type variables have to exactly match by name: Ok(Assoc::new()) } else { Err(TyErr::Mismatch(cnc.context_elt().clone(), lhs.clone())) }; } walk::<Subtype>(lhs, cnc) } fn needs__splice_healing() -> bool { true } fn perform_splice_positive( _: &Form, _: &LazyWalkReses<Self>, ) -> Result<Option<(Vec<Assoc<Name, Ast>>, Ast)>, Self::Err> { // If this ever is non-trivial, // we need to respect `extra_env` in `Positive::walk_quasi_literally` in walk_mode.rs Ok(None) } fn perform_splice_negative( f: &Form, parts: &LazyWalkReses<Self>, context_elts: &dyn Fn() -> Vec<Ast>, ) -> Result<Option<(Vec<Assoc<Name, Ast>>, Ast)>, Self::Err> { if f.name != n("dotdotdot_type") { return Ok(None); } splice_ddd(parts, context_elts()) } } impl crate::walk_mode::NegativeWalkMode for Subtype { fn qlit_mismatch_error(got: Ast, expd: Ast) -> Self::Err { TyErr::Mismatch(got, expd) } fn needs_pre_match() -> bool { true } /// Push through all variable references and underdeterminednesses on both sides, /// returning types that are ready to compare, or `None` if they're definitionally equal fn pre_match(lhs_ty: Ast, rhs_ty: Ast, env: &Assoc<Name, Ast>) -> Option<(Clo<Ast>, Clo<Ast>)> { let u_f = underdetermined_form.with(|u_f| u_f.clone()); let (res_lhs, res_rhs) = unification.with(|unif| { // Capture the environment and resolve: let lhs: Clo<Ast> = resolve(Clo { it: lhs_ty, env: env.clone() }, &unif.borrow()); let rhs: Clo<Ast> = resolve(Clo { it: rhs_ty, env: env.clone() }, &unif.borrow()); let lhs_name = lhs.it.ty_destructure(u_f.clone(), &ast!((trivial))).map( // errors get swallowed ↓ |p| p.get_leaf_or_panic(&n("id")).to_name(), ); let rhs_name = rhs .it .ty_destructure(u_f.clone(), &ast!((trivial))) .map(|p| p.get_leaf_or_panic(&n("id")).to_name()); match (lhs_name, rhs_name) { // They are the same underdetermined type; nothing to do: (Ok(l), Ok(r)) if l == r => None, // Make a determination (possibly just merging two underdetermined types): (Ok(l), _) => { unif.borrow_mut().insert(l, rhs); None } (_, Ok(r)) => { unif.borrow_mut().insert(r, lhs); None } // They are (potentially) different. _ => Some((lhs, rhs)), } })?; Some((res_lhs, res_rhs)) } // TODO: should unbound variable references ever be walked at all? Maybe it should panic? } pub fn canonicalize(t: &Ast, env: Assoc<Name, Ast>) -> Result<Ast, TyErr> { walk::<Canonicalize>(t, &LazyWalkReses::<Canonicalize>::new_wrapper(env)) } // `sub` must be a subtype of `sup`. (Note that `sub` becomes the context element!) pub fn is_subtype( sub: &Ast, sup: &Ast, parts: &LazyWalkReses<crate::ty::SynthTy>, ) -> Result<Assoc<Name, Ast>, TyErr> { walk::<Subtype>(sup, &parts.switch_mode::<Subtype>().with_context(sub.clone())) } // `sub` must be a subtype of `sup`. (Note that `sub` becomes the context element!) // Only use this in tests or at the top level; this discards any non-phase-0-environments! pub fn must_subtype( sub: &Ast, sup: &Ast, env: Assoc<Name, Ast>, ) -> Result<Assoc<Name, Ast>, TyErr> { // TODO: I think we should be canonicalizing first... // TODO: they might need different environments? let lwr_env = &LazyWalkReses::<Subtype>::new_wrapper(env).with_context(sub.clone()); walk::<Subtype>(sup, lwr_env) } // TODO: I think we need to route some other things (especially in macros.rs) through this... pub fn must_equal( lhs: &Ast, rhs: &Ast, parts: &LazyWalkReses<crate::ty::SynthTy>, ) -> Result<(), TyErr> { let canon_parts = parts.switch_mode::<Canonicalize>(); if walk::<Canonicalize>(lhs, &canon_parts) == walk::<Canonicalize>(rhs, &canon_parts) { Ok(()) } else { Err(TyErr::Mismatch(lhs.clone(), rhs.clone())) } } #[test] fn basic_subtyping() { use crate::{ty::TyErr::*, util::assoc::Assoc}; let mt_ty_env = Assoc::new(); let int_ty = ast!({ "Type" "Int" : }); let nat_ty = ast!({ "Type" "Nat" : }); let float_ty = ast!({ "Type" "Float" : }); assert_m!(must_subtype(&int_ty, &int_ty, mt_ty_env.clone()), Ok(_)); assert_eq!( must_subtype(&float_ty, &int_ty, mt_ty_env.clone()), Err(Mismatch(float_ty.clone(), int_ty.clone())) ); let id_fn_ty = ast!({ "Type" "forall_type" : "param" => ["t"], "body" => (import [* [forall "param"]] { "Type" "fn" : "param" => [ (vr "t") ], "ret" => (vr "t") })}); let int_to_int_fn_ty = ast!({ "Type" "fn" : "param" => [(, int_ty.clone())], "ret" => (, int_ty.clone())}); assert_m!(must_subtype(&int_to_int_fn_ty, &int_to_int_fn_ty, mt_ty_env.clone()), Ok(_)); assert_m!(must_subtype(&id_fn_ty, &id_fn_ty, mt_ty_env.clone()), Ok(_)); // actually subtype interestingly! assert_m!(must_subtype(&int_to_int_fn_ty, &id_fn_ty, mt_ty_env.clone()), Ok(_)); // TODO: this error spits out generated names to the user without context ) : assert_m!(must_subtype(&id_fn_ty, &int_to_int_fn_ty, mt_ty_env.clone()), Err(Mismatch(_, _))); let parametric_ty_env = assoc_n!( "some_int" => ast!( { "Type" "Int" : }), "convert_to_nat" => ast!({ "Type" "forall_type" : "param" => ["t"], "body" => (import [* [forall "param"]] { "Type" "fn" : "param" => [ (vr "t") ], "ret" => (, nat_ty.clone() ) })}), "identity" => id_fn_ty.clone(), "int_to_int" => int_to_int_fn_ty.clone()); assert_m!( must_subtype(&ast!((vr "int_to_int")), &ast!((vr "identity")), parametric_ty_env.clone()), Ok(_) ); assert_m!( must_subtype(&ast!((vr "identity")), &ast!((vr "int_to_int")), parametric_ty_env.clone()), Err(Mismatch(_, _)) ); fn incomplete_fn_ty() -> Ast { // A function, so we get a fresh underspecified type each time. ast!({ "Type" "fn" : "param" => [ { "Type" "Int" : } ], "ret" => (, Subtype::underspecified(n("<return_type>")) )}) } assert_m!(must_subtype(&incomplete_fn_ty(), &int_to_int_fn_ty, mt_ty_env.clone()), Ok(_)); assert_m!(must_subtype(&incomplete_fn_ty(), &id_fn_ty, mt_ty_env.clone()), Ok(_)); assert_eq!( crate::ty::synth_type( &ast!({"Expr" "apply" : "rator" => (vr "identity"), "rand" => [(vr "some_int")]}), parametric_ty_env.clone() ), Ok(ast!({"Type" "Int" : })) ); // TODO: write a test that relies on the capture-the-environment behavior of `pre_match` } #[test] fn misc_subtyping_problems() { let list_ty = ast!( { "Type" "forall_type" : "param" => ["Datum"], "body" => (import [* [forall "param"]] { "Type" "mu_type" : "param" => [(import [prot "param"] (vr "List"))], "body" => (import [* [prot "param"]] { "Type" "enum" : "name" => [@"c" "Nil", "Cons"], "component" => [@"c" [], [(vr "Datum"), {"Type" "type_apply" : "type_rator" => (vr "List"), "arg" => [(vr "Datum")]} ]]})})}); let int_list_ty = ast!( { "Type" "mu_type" : "param" => [(import [prot "param"] (vr "IntList"))], "body" => (import [* [prot "param"]] { "Type" "enum" : "name" => [@"c" "Nil", "Cons"], "component" => [@"c" [], [{"Type" "Int" :}, (vr "IntList") ]]})}); let bool_list_ty = ast!( { "Type" "mu_type" : "param" => [(import [prot "param"] (vr "FloatList"))], "body" => (import [* [prot "param"]] { "Type" "enum" : "name" => [@"c" "Nil", "Cons"], "component" => [@"c" [], [{"Type" "Float" :}, (vr "FloatList") ]]})}); let ty_env = assoc_n!( "IntList" => int_list_ty.clone(), "FloatList" => bool_list_ty.clone(), "List" => list_ty.clone() ); // Test that canonicalization accepts `underspecified`: assert_m!(canonicalize(&list_ty, ty_env.clone()), Ok(_)); // μ also has binding: assert_m!(must_subtype(&int_list_ty, &int_list_ty, ty_env.clone()), Ok(_)); assert_m!(must_subtype(&int_list_ty, &bool_list_ty, ty_env.clone()), Err(_)); // Don't walk `Atom`s! let basic_enum = ast!({"Type" "enum" : "name" => [@"arm" "Aa", "Bb"], "component" => [@"arm" [{"Type" "Int" :}], []]}); assert_m!(must_subtype(&basic_enum, &basic_enum, crate::util::assoc::Assoc::new()), Ok(_)); let basic_mu = ast!({"Type" "mu_type" : "param" => [(import [prot "param"] (vr "X"))], "body" => (import [* [prot "param"]] (vr "X"))}); let mu_env = assoc_n!("X" => basic_mu.clone()); // Don't diverge on `μ`! assert_m!(must_subtype(&basic_mu, &basic_mu, mu_env), Ok(_)); let id_fn_ty = ast!({ "Type" "forall_type" : "param" => ["t"], "body" => (import [* [forall "param"]] { "Type" "fn" : "param" => [ (vr "t") ], "ret" => (vr "t") })}); let int_ty = ast!({ "Type" "Int" : }); let nat_ty = ast!({ "Type" "Nat" : }); let int_to_int_fn_ty = ast!({ "Type" "fn" : "param" => [(, int_ty.clone())], "ret" => (, int_ty.clone())}); let parametric_ty_env = assoc_n!( "some_int" => ast!( { "Type" "Int" : }), "convert_to_nat" => ast!({ "Type" "forall_type" : "param" => ["t"], "body" => (import [* [forall "param"]] { "Type" "fn" : "param" => [ (vr "t") ], "ret" => (, nat_ty.clone() ) })}), "identity" => id_fn_ty.clone(), "int_to_int" => int_to_int_fn_ty.clone()); assert_m!( must_subtype( &ast!({"Type" "type_apply" : "type_rator" => (vr "identity"), "arg" => [{"Type" "Int" :}]}), &ast!({"Type" "type_apply" : "type_rator" => (vr "identity"), "arg" => [{"Type" "Int" :}]}), parametric_ty_env.clone() ), Ok(_) ); assert_m!( must_subtype( &ast!({"Type" "type_apply" : "type_rator" => (vr "identity"), "arg" => [{"Type" "Int" :}]}), &ast!((vr "identity")), parametric_ty_env.clone() ), Ok(_) ); // Some things that involve mu assert_m!(must_subtype(&ast!((vr "List")), &ast!((vr "List")), ty_env.clone()), Ok(_)); assert_m!( must_subtype( &ast!({"Type" "type_apply" : "type_rator" => (vr "List"), "arg" => [{"Type" "Int" :}]}), &ast!({"Type" "type_apply" : "type_rator" => (vr "List"), "arg" => [{"Type" "Int" :}]}), ty_env.clone() ), Ok(_) ); assert_m!( must_subtype( &ast!({"Type" "type_apply" : "type_rator" => (, ty_env.find_or_panic(&n("List")).clone()), "arg" => [{"Type" "Int" :}]}), &ast!({"Type" "type_apply" : "type_rator" => (vr "List"), "arg" => [{"Type" "Int" :}]}), ty_env.clone() ), Ok(_) ); assert_m!( must_subtype( &ast!({"Type" "mu_type" : "param" => [(import [prot "param"] (vr "List"))], "body" => (import [* [prot "param"]] {"Type" "type_apply": "type_rator" => (vr "List"), "arg" => [{"Type" "Int" :}]})}), &ast!({"Type" "mu_type" : "param" => [(import [prot "param"] (vr "List"))], "body" => (import [* [prot "param"]] {"Type" "type_apply": "type_rator" => (vr "List"), "arg" => [{"Type" "Int" :}]})}), ty_env.clone() ), Ok(_) ); assert_m!( must_subtype( // Reparameterize &ast!((vr "List")), &ast!( { "Type" "forall_type" : "param" => ["Datum2"], "body" => (import [* [forall "param"]] {"Type" "type_apply" : "type_rator" => (vr "List"), "arg" => [(vr "Datum2")]})}), ty_env.clone() ), Ok(_) ); } #[test] fn struct_subtyping() { // Trivial struct subtying: assert_m!( must_subtype( &ast!( { "Type" "struct" : "component_name" => [@"c" "a", "b"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}]}), &ast!( { "Type" "struct" : "component_name" => [@"c" "a", "b"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}]}), Assoc::new() ), Ok(_) ); // Add a component: assert_m!( must_subtype( &ast!( { "Type" "struct" : "component_name" => [@"c" "a", "b"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}]}), &ast!( { "Type" "struct" : "component_name" => [@"c" "a", "b", "c"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}, {"Type" "Float" :}]}), Assoc::new() ), Ok(_) ); // Reorder components: assert_m!( must_subtype( &ast!( { "Type" "struct" : "component_name" => [@"c" "a", "b"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}]}), &ast!( { "Type" "struct" : "component_name" => [@"c" "b", "a"], "component" => [@"c" {"Type" "Nat" :}, {"Type" "Int" :}]}), Assoc::new() ), Ok(_) ); // Scramble: assert_m!( must_subtype( &ast!( { "Type" "struct" : "component_name" => [@"c" "a", "b"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}]}), &ast!( { "Type" "struct" : "component_name" => [@"c" "b", "a"], "component" => [@"c" {"Type" "Int" :}, {"Type" "Nat" :}]}), Assoc::new() ), Err(_) ); } #[test] fn subtype_different_mus() { // testing the Amber rule: // These types are non-contractive, but it doesn't matter for subtyping purposes. let jane_author = ast!({"Type" "mu_type" : "param" => [(import [prot "param"] (vr "CharlotteBrontë"))], "body" => (import [* [prot "param"]] {"Type" "fn" : "param" => [{"Type" "Float" :}], "ret" => (vr "CharlotteBrontë")})}); let jane_psuedonym = ast!({"Type" "mu_type" : "param" => [(import [prot "param"] (vr "CurrerBell"))], "body" => (import [* [prot "param"]] {"Type" "fn" : "param" => [{"Type" "Float" :}], "ret" => (vr "CurrerBell")})}); let wuthering_author = ast!({"Type" "mu_type" : "param" => [(import [prot "param"] (vr "EmilyBrontë"))], "body" => (import [* [prot "param"]] {"Type" "fn" : "param" => [{"Type" "Int" :}], "ret" => (vr "EmilyBrontë")})}); let mu_env = assoc_n!( "CharlotteBrontë" => jane_author.clone(), "CurrerBell" => jane_psuedonym.clone(), "EmilyBrontë" => wuthering_author.clone()); assert_m!(must_subtype(&jane_author, &jane_author, mu_env.clone()), Ok(_)); assert_m!(must_subtype(&jane_author, &jane_psuedonym, mu_env.clone()), Ok(_)); assert_m!(must_subtype(&jane_author, &wuthering_author, mu_env.clone()), Err(_)); } #[test] fn subtype_dotdotdot_type() { let threeple = uty!({tuple : [{Int :}; {Float :}; {Nat :}]}); let dddple = uty!({forall_type : [T] {tuple : [{dotdotdot_type : [T] T}]}});
rust
MIT
dd1f55be7b09b741a25af954c7a902eeac00a0c2
2026-01-04T20:20:52.848824Z
true
paulstansifer/unseemly
https://github.com/paulstansifer/unseemly/blob/dd1f55be7b09b741a25af954c7a902eeac00a0c2/src/ast.rs
src/ast.rs
//! This abstract syntax tree is *really* abstract. //! It makes binding explicit, but everything else about the language is hidden inside `Node`; //! Their meaning comes from `Form`. #![macro_use] use crate::{ beta::{Beta, ExportBeta}, form::Form, name::*, util::mbe::EnvMBE, }; use std::{fmt, rc::Rc}; // TODO: This really ought to be an `Rc` around an `enum` #[derive(Clone, PartialEq)] pub enum AstContents { Trivial, /// Typically, a binder Atom(Name), VariableReference(Name), /// Shift environment to quote more (the `bool` indicates whether it's positive or negative) QuoteMore(Ast, bool), /// Shift environment to quote less (the `u8` indicates the number of steps out) QuoteLess(Ast, u8), /// A meaningful chunk of syntax, governed by a form, containing an environment, /// potentially exporting some names. Node(std::rc::Rc<Form>, EnvMBE<Ast>, ExportBeta), /// For parsing purposes. IncompleteNode(EnvMBE<Ast>), /// For parsing purposes. Shape(Vec<Ast>), /// Variable binding ExtendEnv(Ast, Beta), /// Variable binding, affects all phases. /// This is weird, but needed for marcos, it seems. ExtendEnvPhaseless(Ast, Beta), } #[derive(Clone, PartialEq)] pub struct LocatedAst { /// "contents" pub c: AstContents, pub file_id: usize, pub begin: usize, pub end: usize, } #[derive(Clone)] pub struct Ast(pub Rc<LocatedAst>); // For testing purposes, we want to ignore span information impl PartialEq for Ast { fn eq(&self, other: &Ast) -> bool { self.c() == other.c() } } // Reification macros would totally work for this, // but it's worth having a special case in `Value` in order to make this faster. impl crate::runtime::reify::Reifiable for Ast { fn ty_name() -> Name { n("Ast") } fn reify(&self) -> crate::runtime::eval::Value { crate::runtime::eval::Value::AbstractSyntax(self.clone()) } fn reflect(v: &crate::runtime::eval::Value) -> Ast { extract!((v) crate::runtime::eval::Value::AbstractSyntax = (ref ast) => ast.clone()) } } pub use self::AstContents::*; impl fmt::Debug for Ast { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:#?}", self.c()) } } impl fmt::Debug for AstContents { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Trivial => write!(f, "⨉"), Atom(n) => write!(f, "∘{}∘", n.print()), VariableReference(v) => write!(f, "{}", v.print()), Shape(v) => { write!(f, "(")?; let mut first = true; for elt in v { if !first { write!(f, " ")? } elt.fmt(f)?; first = false; } write!(f, ")") } Node(form, body, export) => { write!(f, "{{ ({}); {:#?}", form.name.sp(), body)?; match *export { crate::beta::ExportBeta::Nothing => {} _ => write!(f, " ⇑{:#?}", export)?, } write!(f, "}}") } QuoteMore(body, pos) => { if *pos { write!(f, "pos``{:#?}``", body) } else { write!(f, "neg``{:#?}``", body) } } QuoteLess(body, depth) => write!(f, ",,({}){:#?},,", depth, body), IncompleteNode(body) => write!(f, "{{ INCOMPLETE; {:#?} }}", body), ExtendEnv(body, beta) => write!(f, "{:#?}↓{:#?}", body, beta), ExtendEnvPhaseless(body, beta) => write!(f, "{:#?}±↓{:#?}", body, beta), } } } // Warning: this assumes the core language! To properly display an `Ast`, you need the `SynEnv`. impl fmt::Display for Ast { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.c()) } } impl fmt::Display for AstContents { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Atom(ref n) => write!(f, "{}", n.print()), VariableReference(ref v) => write!(f, "{}", v.print()), Node(ref form, ref body, _) => { let s = crate::unparse::unparse_mbe( &form.grammar, self, body, &crate::core_forms::get_core_forms(), ); write!(f, "{}", s) } Shape(ref v) => { write!(f, "(")?; let mut first = true; for elt in v { if !first { write!(f, " ")? } elt.fmt(f)?; first = false; } write!(f, ")") } ExtendEnv(ref body, _) => write!(f, "{}↓", body), ExtendEnvPhaseless(ref body, _) => write!(f, "{}±↓", body), QuoteMore(body, _) => { write!(f, "``{}``", body) } QuoteLess(body, _) => write!(f, ",,{},,", body), _ => write!(f, "{:#?}", self), } } } impl Ast { /// "Contents". Ignore location information and get the interesting bits pub fn c(&self) -> &AstContents { &self.0.c } /// Replace the contents. pub fn c_map(&self, f: &dyn Fn(&AstContents) -> AstContents) -> Ast { self.with_c(f(self.c())) } /// Keep the location information, but replace the contents. pub fn with_c(&self, c: AstContents) -> Ast { Ast(Rc::new(LocatedAst { c: c, file_id: self.0.file_id, begin: self.0.begin, end: self.0.end, })) } // TODO: this ought to at least warn if we're losing anything other than `Shape` pub fn flatten(&self) -> EnvMBE<Ast> { match self.c() { Trivial | Atom(_) => EnvMBE::new(), VariableReference(_) => EnvMBE::new(), Shape(ref v) => { let mut accum = EnvMBE::new(); for sub_a in v { accum = accum.combine_overriding(&sub_a.flatten()) } accum } IncompleteNode(ref env) => env.clone(), Node(ref _f, ref _body, ref _export) => { // TODO: think about what should happen when // `Scope` contains a `Scope` without an intervening `Named` panic!("I don't know what to do with {:#?}!", self) } QuoteMore(ref body, _) => body.flatten(), QuoteLess(ref body, _) => body.flatten(), ExtendEnv(ref body, _) | ExtendEnvPhaseless(ref body, _) => body.flatten(), } } // TODO: use `Mode::context_match` whenever possible pub fn destructure( &self, expd_form: std::rc::Rc<Form>, ) -> Option<crate::util::mbe::EnvMBE<Ast>> { if let Node(ref f, ref parts, _) = self.c() { if f == &expd_form { return Some(parts.clone()); } } None } pub fn is_node(&self) -> bool { match self.c() { Node(_, _, _) => true, _ => false, } } // TODO: I think we have a lot of places where we ought to use this function: pub fn node_parts(&self) -> &EnvMBE<Ast> { match self.c() { Node(_, ref body, _) => body, _ => icp!(), } } pub fn maybe_node_parts(&self) -> Option<&EnvMBE<Ast>> { match self.c() { Node(_, ref body, _) => Some(body), _ => None, } } pub fn node_form(&self) -> &Form { match self.c() { Node(ref form, _, _) => form, _ => icp!(), } } pub fn free_vrs(&self) -> Vec<Name> { match self.c() { Trivial | Atom(_) => vec![], VariableReference(v) => vec![*v], Shape(_) | IncompleteNode(_) => unimplemented!("TODO"), QuoteLess(_, _) | QuoteMore(_, _) => unimplemented!("TODO"), // This one is actually encounterable by real-world code // (if a ∀ somehow ends up underneath a `*` in syntax.) // And we need to take a LazyWalkReses to do this right. ExtendEnv(_, _) | ExtendEnvPhaseless(_, _) => unimplemented!("TODO"), Node(_, ref body, _) => body.map_reduce( &|a| a.free_vrs(), &|v0, v1| { let mut res = v0.clone(); res.append(&mut v1.clone()); res }, vec![], ), } } pub fn to_name(&self) -> Name { match self.c() { Atom(n) => *n, _ => icp!("{:#?} is not an atom", self), } } pub fn vr_to_name(&self) -> Name { match self.c() { VariableReference(n) => *n, _ => icp!("{:#?} is not an atom", self), } } pub fn orig_str<'a, 'b>(&'a self, prog: &'b str) -> &'b str { &prog[self.0.begin..self.0.end] } } #[test] fn star_construction() { let env = mbe!( "a" => ["1", "2"]); assert_eq!( ast!( { - "x" => [* env =>("a") env : (, env.get_leaf_or_panic(&n("a")).clone())]} ), ast!( { - "x" => ["1", "2"] }) ); let env = mbe!( "a" => [@"duo" "1", "2"], "b" => [@"duo" "11", "22"]); assert_eq!( ast!( { - "x" => [* env =>("a", "b") env : ((, env.get_leaf_or_panic(&n("b")).clone()) (, env.get_leaf_or_panic(&n("a")).clone()))]} ), ast!( { - "x" => [("11" "1"), ("22" "2")] }) ); } #[test] fn mbe_r_and_r_roundtrip() { use crate::runtime::reify::Reifiable; let mbe1 = mbe!( "a" => [@"duo" "1", "2"], "b" => [@"duo" "11", "22"]); assert_eq!(mbe1, EnvMBE::<Ast>::reflect(&mbe1.reify())); }
rust
MIT
dd1f55be7b09b741a25af954c7a902eeac00a0c2
2026-01-04T20:20:52.848824Z
false
paulstansifer/unseemly
https://github.com/paulstansifer/unseemly/blob/dd1f55be7b09b741a25af954c7a902eeac00a0c2/src/walk_mode.rs
src/walk_mode.rs
use crate::{ alpha::{freshen, freshen_with}, ast::{Ast, AstContents, AstContents::*}, ast_walk::{walk, Clo, LazyWalkReses, OutEnvHandle, WalkRule}, form::Form, name::*, runtime::reify::Reifiable, util::{assoc::Assoc, mbe::EnvMBE}, }; use std::fmt::{Debug, Display}; /// This trait makes a type producable by positive and negative walks. pub trait WalkElt: Clone + Debug + Display + Reifiable + PartialEq { fn from_ast(a: &Ast) -> Self; fn to_ast(&self) -> Ast; } // Abbreviation for Result<…::Out, …> type Res<Mode> = Result<<<Mode as WalkMode>::D as Dir>::Out, <Mode as WalkMode>::Err>; /// This trait exists to walk over `Ast`s in different ways. /// `get_walk_rule` connects `Form`s to actual walk operations. /// /// There are two kinds of walks over `Ast`s: /// * Positive walks produce an element (a value or type, say) from an environment. /// They are for expression-like terms. /// * Negative walks produce an environment from an element. /// They are for pattern-like terms. /// /// Now, the whole environment is actually present in both cases, /// and negative walks can actually use it /// -- the special value they traverse is stored in the environment with a special name -- /// but they conceptually are mostly relying on the special value. pub trait WalkMode: Debug + Copy + Clone + Reifiable { /// The object type for the environment to walk in. type Elt: Clone + Debug + Reifiable + WalkElt; type Err: Debug + Reifiable + Clone; type D: Dir<Mode = Self>; /// The negated version of this walk type Negated: WalkMode< Elt = Self::Elt, Err = Self::Err, ExtraInfo = Self::ExtraInfo, Negated = Self, >; /// If this walk is positive, `Self`; otherwise `Self::Negated` type AsPositive: WalkMode< Elt = Self::Elt, Err = Self::Err, ExtraInfo = Self::ExtraInfo, D = Positive<Self::AsPositive>, >; /// If this walk is positive, `Self::Negated`; otherwise `Self` type AsNegative: NegativeWalkMode + WalkMode< Elt = Self::Elt, Err = Self::Err, ExtraInfo = Self::ExtraInfo, D = Negative<Self::AsNegative>, >; /// Any extra information the walk needs type ExtraInfo: std::default::Default + Reifiable + Clone + Debug; fn get_walk_rule(form: &Form) -> WalkRule<Self> where Self: Sized; /// Should the walker extend the environment based on imports? /// Only `QQ` and `Expand` have this as false; it's not 100% clear what's special about them. /// (This evolved over time; it used to be false for `Eval`, because of lambda). /// It seems like the thing about those modes is /// (a) they don't look at variables, so their environments are irrelevant, /// (b) `SameAs` switching to the negated mode and doing `get_res` doesn't work. /// But what unites those two factors? fn automatically_extend_env() -> bool; /// Do we ever need to treat certain forms as though they were repetitions? fn needs__splice_healing() -> bool { false } /// A little like `get_walk_rule` always returning `Custom` for positive splicing fn perform_splice_positive( _: &Form, _: &LazyWalkReses<Self>, ) -> Result<Option<(Vec<Assoc<Name, Self::Elt>>, Ast)>, Self::Err> { icp!() } /// A little like `get_walk_rule` always returning `Custom` for negative splicing fn perform_splice_negative( _: &Form, _: &LazyWalkReses<Self>, _context_elts: &dyn Fn() -> Vec<Ast>, ) -> Result<Option<(Vec<Assoc<Name, Self::Elt>>, Ast)>, Self::Err> { icp!() } /// Walk over the structure of a node, not its meaning. /// This could be because we're inside a syntax-quote, /// or it could be that we are a form (like written-out types or a literal) /// that acts like a literal. /// Children are not necessarily walked quasiliterally /// -- maybe they're an interpolation of some kind -- /// instead, the mode (=quotation depth) and form together decide what to do. /// If the walk is negative, the result might be MatchFailure fn walk_quasi_literally(expected: Ast, cnc: &LazyWalkReses<Self>) -> Res<Self> { Self::D::walk_quasi_literally(expected, cnc) } // TODO: these seem like a hack... // We need to dynamically do these if it's possible, for `env_from_beta` fn out_as_elt(o: <Self::D as Dir>::Out) -> Self::Elt { Self::D::out_as_elt(o) } fn out_as_env(o: <Self::D as Dir>::Out) -> Assoc<Name, Self::Elt> { Self::D::out_as_env(o) } fn env_as_out(e: Assoc<Name, Self::Elt>) -> <Self::D as Dir>::Out { Self::D::env_as_out(e) } fn walk_var(n: Name, cnc: &LazyWalkReses<Self>) -> Res<Self> { Self::D::walk_var(n, cnc) } fn walk_atom(n: Name, cnc: &LazyWalkReses<Self>) -> Res<Self> { Self::D::walk_atom(n, cnc) } /// Make up a special `Elt` that is currently "underspecified", /// but which can be "unified" with some other `Elt`. /// If that happens, all copies of this `Elt` will act like that other one. /// /// Side-effects under the covers make this work. fn underspecified(_: Name) -> Self::Elt { icp!("no underspecified_elt") } /// We have two environments from negative walks; merge them. /// The handling of duplicate elements is what needs to vary. /// This default handling just arbitrarily picks the last result to win, /// which is probably wrong if it matters, fn neg__env_merge( lhs: &Assoc<Name, Self::Elt>, rhs: &Assoc<Name, Self::Elt>, ) -> Result<Assoc<Name, Self::Elt>, Self::Err> { Ok(lhs.set_assoc(rhs)) } fn name() -> &'static str; } pub trait Dir: Debug + Copy + Clone where Self: std::marker::Sized { type Mode: WalkMode; /// The output of the walking process. /// /// Negated walks produce an environment of Self::Elt, positive walks produce Self::Elt. type Out: Clone + Debug + Reifiable; /// Get ready to destructure a node. /// Includes freshening (including the context_elt, if necessary) /// and and mode-specific leaf-processing fn pre_walk(node: Ast, cnc: LazyWalkReses<Self::Mode>) -> (Ast, LazyWalkReses<Self::Mode>); fn walk_quasi_literally(node: Ast, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode>; /// Look up variable in the environment! fn walk_var(name: Name, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode>; fn walk_atom(name: Name, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode>; fn out_as_elt(out: Self::Out) -> <Self::Mode as WalkMode>::Elt; fn out_as_env(out: Self::Out) -> Assoc<Name, <Self::Mode as WalkMode>::Elt>; fn env_as_out(env: Assoc<Name, <Self::Mode as WalkMode>::Elt>) -> Self::Out; /// For when we hackishly need to execute some code depending on the direction fn is_positive() -> bool; /// If necessary, prepare to smuggle results across more-quoted AST fn oeh_if_negative() -> Option<OutEnvHandle<Self::Mode>>; } #[derive(Copy, Clone, Debug)] pub struct Positive<Mode: WalkMode> { md: Mode, } #[derive(Copy, Clone, Debug)] pub struct Negative<Mode: WalkMode> { md: Mode, } impl<Mode: WalkMode<D = Self>> Dir for Positive<Mode> { type Out = <Self::Mode as WalkMode>::Elt; type Mode = Mode; fn pre_walk(node: Ast, cnc: LazyWalkReses<Self::Mode>) -> (Ast, LazyWalkReses<Self::Mode>) { // TODO: Per issue #49, this ought to be removable. But EXCITING ERRORS happen if we do. (freshen(&node), cnc) // Nothing to do. } /// Turn `a` from an `Ast` into an `Elt` using `::from_ast()`... except: /// * any `Node` it has might be unquotation or dotdotdoting, which escape quotation /// * any `ExtendEnv[Phaseless]` still extends the environment /// * `VariableReference`/`Atom` might need special handling from `walk_var`/`walk_atom`. fn walk_quasi_literally(a: Ast, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode> { // TODO: this needs to handle splicing, like the negative w_q_l does. // (Wait, in what way does it not?!?) match a.c() { Node(f, parts, exports) => { // TODO: This can probably be simplified: // We need something that's like `map`, // but that exposes the "current marchedness" of the `EnvMBE`/`Sky`, // so that references to siblings in the same march group are visible. // Then we can just do `cnc.parts.map__with__current_marchedness`... // For the sake of `ExtendEnv`, we need to march out `cnc`: // betas look at the environment in a marched way. let mut walked = parts .map_marched_against( &mut |p: &Ast, cnc_m: &LazyWalkReses<Self::Mode>| { match p.c() { // Yes, `walk`, not `w_q_l`; // the mode is in charge of figuring things out. Node(_, _, _) | VariableReference(_) | ExtendEnv(_, _) | ExtendEnvPhaseless(_, _) => walk(p, cnc_m), _ => Ok(<Self::Mode as WalkMode>::Elt::from_ast(&p.clone())), } .map(|e| <Self::Mode as WalkMode>::Elt::to_ast(&e)) }, cnc, ) .lift_result()?; // HACK: recognize `Shape` as the output of `core_qq_forms::dotdotdot` (TODO #40?): walked .heal_splices::<()>(&|a| match a.c() { Shape(ref v) => Ok(Some(v.clone())), _ => Ok(None), }) .unwrap(); // Can't error // TODO: it should be a type error (or at least an obvious runtime error) // to put a splice (i.e. a `...[]...`) somewhere it can't be healed. Ok(<Self::Mode as WalkMode>::Elt::from_ast(&a.with_c(Node( f.clone(), walked, exports.clone(), )))) } orig => { // TODO #40: This mess is to push `Shape` down past a wrapper (i.e. `ExtendEnv`), // duplicating the wrapper around each element of `Shape`. // This is all for splicing the result of `dotdotdot` let body = match orig { ExtendEnv(ref b, _) | ExtendEnvPhaseless(ref b, _) | QuoteMore(ref b, _) | QuoteLess(ref b, _) => b, _ => icp!(), }; let sub_result = Mode::Elt::to_ast(&walk(body, cnc)?); fn handle_wrapper<Mode: WalkMode>(orig: &AstContents, a: &Ast) -> AstContents { let a = a.clone(); match orig { // Environment extension is handled at `walk` ExtendEnv(_, beta) => ExtendEnv(a, beta.clone()), ExtendEnvPhaseless(_, beta) => ExtendEnvPhaseless(a, beta.clone()), QuoteMore(_, pos) => QuoteMore(a, *pos), QuoteLess(_, depth) => QuoteLess(a, *depth), _ => icp!(), } } let res: AstContents = match sub_result.c() { Shape(sub_results) => Shape( sub_results .iter() .map(|sub| sub.with_c(handle_wrapper::<Self::Mode>(orig, sub))) .collect(), ), _ => handle_wrapper::<Self::Mode>(orig, &sub_result), }; Ok(Mode::Elt::from_ast(&sub_result.with_c(res))) } } } fn walk_var(n: Name, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode> { Ok(cnc.env.find_or_panic(&n).clone()) } fn walk_atom(_: Name, _: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode> { icp!("Atoms are positively unwalkable"); } fn out_as_elt(o: Self::Out) -> <Self::Mode as WalkMode>::Elt { o } fn out_as_env(_: Self::Out) -> Assoc<Name, <Self::Mode as WalkMode>::Elt> { icp!("out_as_env") } fn env_as_out(_: Assoc<Name, <Self::Mode as WalkMode>::Elt>) -> Self::Out { icp!("env_as_out") } fn oeh_if_negative() -> Option<OutEnvHandle<Mode>> { None } fn is_positive() -> bool { true } } impl<Mode: WalkMode<D = Self> + NegativeWalkMode> Dir for Negative<Mode> { type Out = Assoc<Name, <Self::Mode as WalkMode>::Elt>; type Mode = Mode; fn pre_walk(node: Ast, cnc: LazyWalkReses<Self::Mode>) -> (Ast, LazyWalkReses<Self::Mode>) { if !<Self::Mode as NegativeWalkMode>::needs_pre_match() { return (freshen(&node), cnc); } let node_ast = <Self::Mode as WalkMode>::Elt::from_ast(&node); // `pre_match` brings things together, which we want to do before attempting to co-freshen. match Mode::pre_match(node_ast, cnc.context_elt().clone(), &cnc.env) { Some((l_clo, r_clo)) => { // Closures; we need to unify their environments: let (l, r, new_env) = l_clo.env_merge(&r_clo); let (l_fresh, r_fresh) = freshen_with( &<Self::Mode as WalkMode>::Elt::to_ast(&l), &<Self::Mode as WalkMode>::Elt::to_ast(&r), ); ( l_fresh, cnc.with_environment(new_env) .with_context(<Self::Mode as WalkMode>::Elt::from_ast(&r_fresh)), ) } // HACK: force walking to automatically succeed, avoiding return type muckery None => ( ast!((at negative_ret_val())), cnc.with_context(<Self::Mode as WalkMode>::Elt::from_ast(&ast!((trivial)))), ), } } fn walk_quasi_literally(expected: Ast, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode> { use crate::ast_walk::LazilyWalkedTerm; use std::rc::Rc; let got = <Mode::Elt as WalkElt>::to_ast(&cnc.context_elt().clone()); let parts_actual = Mode::context_match(&expected, &got, cnc.env.clone())?; // Continue the walk on subterms. (`context_match` does the freshening) // TODO: is it possible we need `map_reduce_with_marched_against`? cnc.parts.map_reduce_with( &parts_actual, &|model: &Rc<LazilyWalkedTerm<Mode>>, actual: &Ast| match model.term.c() { Node(_, _, _) | VariableReference(_) | ExtendEnv(_, _) | ExtendEnvPhaseless(_, _) => { if model.extra_env.empty() { walk( &model.term, &cnc.with_context(<Self::Mode as WalkMode>::Elt::from_ast(actual)), ) } else { // TODO: This splicing-related code feels really out-of-place here. // Hopefully a refactor will let us delete this. walk( &model.term, &cnc.with_environment(cnc.env.set_assoc(&model.extra_env)) .with_context(<Self::Mode as WalkMode>::Elt::from_ast(actual)), ) } } _ => Ok(Assoc::new()), }, // Merging two environments is mode-specific: &|result, next| Mode::neg__env_merge(&result?, &next?), Ok(Assoc::new()), ) } fn walk_var(n: Name, _: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode> { icp!("{} is a VarRef, which is negatively unwalkable", n) } /// Bind atom to the context! fn walk_atom(n: Name, cnc: &LazyWalkReses<Self::Mode>) -> Res<Self::Mode> { Ok(Assoc::new().set(n, cnc.context_elt().clone())) } fn out_as_elt(_: Self::Out) -> <Self::Mode as WalkMode>::Elt { icp!("out_as_elt") } fn out_as_env(o: Self::Out) -> Assoc<Name, <Self::Mode as WalkMode>::Elt> { o } fn env_as_out(e: Assoc<Name, <Self::Mode as WalkMode>::Elt>) -> Self::Out { e } fn oeh_if_negative() -> Option<OutEnvHandle<Self::Mode>> { Some(std::rc::Rc::new(std::cell::RefCell::new( Assoc::<Name, <Self::Mode as WalkMode>::Elt>::new(), ))) } fn is_positive() -> bool { false } } pub trait NegativeWalkMode: WalkMode { /// What happens if destructuring fails? fn qlit_mismatch_error(l: Self::Elt, r: Self::Elt) -> Self::Err { panic!("match failure unimplemented: {} vs. {}", l, r) } // HACK: `Value`s can't survive the round-trip to `Ast`, so `pre_match`, as implemented, // causes a panic in that case. So only pre_match if necessary. // HACK: This controls both whether `pre_match` is called, // and whether we `freshen_with` the context_elt (as opposed to just `freshen`ing the value). // If something *can* round-trip to `Ast`, then it needs to be freshened, and `pre_match` fn needs_pre_match() -> bool; /// Before matching, possibly adjust the two `Elt`s to match better. (`None` is auto-match.) /// By default, a no-op. fn pre_match( expected: Self::Elt, got: Self::Elt, env: &Assoc<Name, Self::Elt>, ) -> Option<(Clo<Self::Elt>, Clo<Self::Elt>)> { Some((Clo { it: expected, env: env.clone() }, Clo { it: got, env: env.clone() })) } /// Match the context element against the current node. /// Note that this should come after `pre_match`, /// so any remaining variables will be not be resolved. /// TODO: I should think about whether to use `Ast` or `Elt` during matches in `ast_walk` /// TODO: This should replace crate::ast::destructure /// TODO: Use this more fn context_match( expected: &Ast, got: &Ast, _env: Assoc<Name, Self::Elt>, ) -> Result<EnvMBE<Ast>, <Self as WalkMode>::Err> { // break apart the node, and walk it element-wise match (expected.c(), got.c()) { // `pre_walk` has already freshened for us (&Node(ref f, _, _), &Node(ref f_actual, ref parts_actual, _)) if *f == *f_actual => { Ok(parts_actual.clone()) } _ => { // TODO: wouldn't it be nice to have match failures that // contained useful `diff`-like information for debugging, // when a match was expected to succeed? // (I really like using pattern-matching in unit tests!) Err(Self::qlit_mismatch_error( Self::Elt::from_ast(got), Self::Elt::from_ast(expected), )) } } } } /// `var_to_out`, for positive walks where `Out` == `Elt` pub fn var_lookup<Elt: Debug + Clone>(n: Name, env: &Assoc<Name, Elt>) -> Result<Elt, ()> { Ok((*env.find(&n).unwrap_or_else(|| panic!("Name {:#?} unbound in {:#?}", n, env))).clone()) } /// `var_to_out`, for negative walks where `Out` == `Assoc<Name, Elt>`` pub fn var_bind<Elt: Debug + Clone>( n: Name, env: &Assoc<Name, Elt>, ) -> Result<Assoc<Name, Elt>, ()> { Ok(Assoc::new().set(n, env.find(&negative_ret_val()).unwrap().clone())) }
rust
MIT
dd1f55be7b09b741a25af954c7a902eeac00a0c2
2026-01-04T20:20:52.848824Z
false