Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeHartnell authored and Jake Hartnell committed Mar 26, 2024
1 parent f05541b commit 988cf5d
Show file tree
Hide file tree
Showing 6 changed files with 163 additions and 145 deletions.
70 changes: 43 additions & 27 deletions contracts/external/cw-abc/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
use crate::abc::{CommonsPhase, CurveFn, MinMax};
use crate::contract::CwAbcResult;
use crate::ContractError;
use cosmwasm_std::{
coins, ensure, Addr, BankMsg, Decimal as StdDecimal, DepsMut, Env, MessageInfo, QuerierWrapper,
Response, StdError, StdResult, Storage, Uint128,
coins, ensure, to_binary, Addr, BankMsg, Coin, CosmosMsg, Decimal as StdDecimal, DepsMut, Env,
MessageInfo, QuerierWrapper, Response, StdError, StdResult, Storage, Uint128, WasmMsg,
};
use cw_tokenfactory_issuer::msg::ExecuteMsg as IssuerExecuteMsg;
use cw_utils::must_pay;
use std::collections::HashSet;
use std::ops::Deref;
use token_bindings::{TokenFactoryMsg, TokenFactoryQuery};

use crate::abc::{CommonsPhase, CurveFn, MinMax};
use crate::contract::CwAbcResult;
use crate::state::{
CURVE_STATE, DONATIONS, HATCHERS, HATCHER_ALLOWLIST, PHASE, PHASE_CONFIG, SUPPLY_DENOM,
TOKEN_ISSUER_CONTRACT,
};
use crate::ContractError;

pub fn execute_buy(
deps: DepsMut<TokenFactoryQuery>,
Expand Down Expand Up @@ -64,7 +66,16 @@ pub fn execute_buy(
curve_state.supply = new_supply;
CURVE_STATE.save(deps.storage, &curve_state)?;

let mint_msg = mint_supply_msg(deps.storage, minted, &info.sender)?;
// Mint tokens for sender by calling mint on the cw-tokenfactory-issuer contract
let issuer_addr = TOKEN_ISSUER_CONTRACT.load(deps.storage)?;
let mint_msg = WasmMsg::Execute {
contract_addr: issuer_addr.to_string(),
msg: to_binary(&IssuerExecuteMsg::Mint {
to_address: info.sender.to_string(),
amount: minted,
})?,
funds: vec![],
};

Ok(Response::new()
.add_message(mint_msg)
Expand All @@ -75,21 +86,6 @@ pub fn execute_buy(
.add_attribute("supply", minted))
}

/// Build a message to mint the supply token to the sender
fn mint_supply_msg(
storage: &dyn Storage,
minted: Uint128,
minter: &Addr,
) -> CwAbcResult<TokenFactoryMsg> {
let denom = SUPPLY_DENOM.load(storage)?;
// mint supply token
Ok(TokenFactoryMsg::mint_contract_tokens(
denom,
minted,
minter.to_string(),
))
}

/// Return the reserved and funded amounts based on the payment and the allocation ratio
fn calculate_reserved_and_funded(
payment: Uint128,
Expand Down Expand Up @@ -128,9 +124,29 @@ pub fn execute_sell(

let supply_denom = SUPPLY_DENOM.load(deps.storage)?;
let burn_amount = must_pay(&info, &supply_denom)?;

let issuer_addr = TOKEN_ISSUER_CONTRACT.load(deps.storage)?;

// Burn the sent supply tokens
let burn_msg =
TokenFactoryMsg::burn_contract_tokens(supply_denom, burn_amount, burner.to_string());
let burn_msgs: Vec<CosmosMsg<TokenFactoryMsg>> = vec![
// Send tokens to the issuer contract to be burned
CosmosMsg::<TokenFactoryMsg>::Bank(BankMsg::Send {
to_address: issuer_addr.to_string().clone(),
amount: vec![Coin {
amount: burn_amount,
denom: supply_denom,
}],
}),
// Execute burn on the cw-tokenfactory-issuer contract
CosmosMsg::<TokenFactoryMsg>::Wasm(WasmMsg::Execute {
contract_addr: issuer_addr.to_string(),
msg: to_binary(&IssuerExecuteMsg::Mint {
to_address: info.sender.to_string(),
amount: burn_amount,
})?,
funds: vec![],
}),
];

let taxed_amount = calculate_exit_tax(deps.storage, burn_amount)?;

Expand All @@ -156,14 +172,14 @@ pub fn execute_sell(
.map_err(StdError::overflow)?;

// Now send the tokens to the sender
let msg = BankMsg::Send {
let msg_send = BankMsg::Send {
to_address: burner.to_string(),
amount: coins(released_reserve.u128(), curve_state.reserve_denom),
};

Ok(Response::new()
.add_message(msg)
.add_message(burn_msg)
Ok(Response::<TokenFactoryMsg>::new()
.add_messages(burn_msgs)
.add_message(msg_send)
.add_attribute("action", "burn")
.add_attribute("from", burner)
.add_attribute("amount", burn_amount)
Expand Down
7 changes: 2 additions & 5 deletions contracts/external/cw-abc/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,8 @@ pub fn do_query(
to_binary(&queries::query_hatchers(deps, start_after, limit)?)
}
QueryMsg::Ownership {} => to_binary(&cw_ownable::get_ownership(deps.storage)?),
// TODO get token contract
// QueryMsg::GetDenom {
// creator_address,
// subdenom,
// } => to_binary(&get_denom(deps, creator_address, subdenom)),
QueryMsg::Denom {} => to_binary(&queries::get_denom(deps)?),
QueryMsg::TokenContract {} => to_binary(&TOKEN_ISSUER_CONTRACT.load(deps.storage)?),
}
}

Expand Down
100 changes: 2 additions & 98 deletions contracts/external/cw-abc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,103 +14,7 @@ pub mod state;
#[cfg(feature = "test-tube")]
mod testtube;

pub use crate::error::ContractError;

// TODO do we still want these?
#[cfg(test)]
pub(crate) mod testing {
use crate::abc::{
ClosedConfig, CommonsPhaseConfig, CurveType, HatchConfig, MinMax, OpenConfig, ReserveToken,
SupplyToken,
};
use crate::msg::InstantiateMsg;
use cosmwasm_std::{
testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage},
Decimal, OwnedDeps, Uint128,
};

use crate::contract;
use crate::contract::CwAbcResult;
use cosmwasm_std::DepsMut;
use std::marker::PhantomData;
use token_bindings::{Metadata, TokenFactoryQuery};

pub(crate) mod prelude {
pub use super::{
default_instantiate_msg, default_supply_metadata, mock_tf_dependencies, TEST_CREATOR,
TEST_RESERVE_DENOM, TEST_SUPPLY_DENOM, _TEST_BUYER, _TEST_INVESTOR,
};
pub use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
pub use speculoos::prelude::*;
}

pub const TEST_RESERVE_DENOM: &str = "satoshi";
pub const TEST_CREATOR: &str = "creator";
pub const _TEST_INVESTOR: &str = "investor";
pub const _TEST_BUYER: &str = "buyer";
mod testing;

pub const TEST_SUPPLY_DENOM: &str = "subdenom";

pub fn default_supply_metadata() -> Metadata {
Metadata {
name: Some("Bonded".to_string()),
symbol: Some("EPOXY".to_string()),
description: None,
denom_units: vec![],
base: None,
display: None,
}
}

pub fn default_instantiate_msg(
decimals: u8,
reserve_decimals: u8,
curve_type: CurveType,
) -> InstantiateMsg {
InstantiateMsg {
supply: SupplyToken {
subdenom: TEST_SUPPLY_DENOM.to_string(),
metadata: default_supply_metadata(),
decimals,
},
reserve: ReserveToken {
denom: TEST_RESERVE_DENOM.to_string(),
decimals: reserve_decimals,
},
phase_config: CommonsPhaseConfig {
hatch: HatchConfig {
initial_raise: MinMax {
min: Uint128::one(),
max: Uint128::from(1000000u128),
},
initial_price: Uint128::one(),
initial_allocation_ratio: Decimal::percent(10u64),
exit_tax: Decimal::zero(),
},
open: OpenConfig {
allocation_percentage: Decimal::percent(10u64),
exit_tax: Decimal::percent(10u64),
},
closed: ClosedConfig {},
},
hatcher_allowlist: None,
curve_type,
}
}

pub fn mock_init(deps: DepsMut<TokenFactoryQuery>, init_msg: InstantiateMsg) -> CwAbcResult {
let info = mock_info(TEST_CREATOR, &[]);
let env = mock_env();
contract::instantiate(deps, env, info, init_msg)
}

pub fn mock_tf_dependencies(
) -> OwnedDeps<MockStorage, MockApi, MockQuerier<TokenFactoryQuery>, TokenFactoryQuery> {
OwnedDeps {
storage: MockStorage::default(),
api: MockApi::default(),
querier: MockQuerier::<TokenFactoryQuery>::new(&[]),
custom_query_type: PhantomData::<TokenFactoryQuery>,
}
}
}
pub use crate::error::ContractError;
11 changes: 11 additions & 0 deletions contracts/external/cw-abc/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ pub enum QueryMsg {
start_after: Option<String>,
limit: Option<u32>,
},
/// Returns Token Factory Denom for the supply
#[returns(DenomResponse)]
Denom {},
/// Returns the address of the cw-tokenfactory-issuer contract
#[returns(::cosmwasm_std::Addr)]
TokenContract {},
}

#[cw_serde]
Expand All @@ -105,6 +111,11 @@ pub struct CurveInfoResponse {
pub reserve_denom: String,
}

#[cw_serde]
pub struct DenomResponse {
pub denom: String,
}

#[cw_serde]
pub struct HatcherAllowlistResponse {
/// Hatcher allowlist
Expand Down
25 changes: 10 additions & 15 deletions contracts/external/cw-abc/src/queries.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use crate::abc::CurveFn;
use crate::msg::{
CommonsPhaseConfigResponse, CurveInfoResponse, DonationsResponse, HatchersResponse,
CommonsPhaseConfigResponse, CurveInfoResponse, DenomResponse, DonationsResponse,
HatchersResponse,
};
use crate::state::{
CurveState, CURVE_STATE, DONATIONS, HATCHERS, PHASE, PHASE_CONFIG, SUPPLY_DENOM,
};
use crate::state::{CurveState, CURVE_STATE, DONATIONS, HATCHERS, PHASE, PHASE_CONFIG};
use cosmwasm_std::{Deps, Order, QuerierWrapper, StdResult};
use std::ops::Deref;
use token_bindings::TokenFactoryQuery;
Expand Down Expand Up @@ -43,19 +46,11 @@ pub fn query_phase_config(deps: Deps<TokenFactoryQuery>) -> StdResult<CommonsPha
})
}

// // TODO, maybe we don't need this
// pub fn get_denom(
// deps: Deps<TokenFactoryQuery>,
// creator_addr: String,
// subdenom: String,
// ) -> GetDenomResponse {
// let querier = TokenQuerier::new(&deps.querier);
// let response = querier.full_denom(creator_addr, subdenom).unwrap();

// GetDenomResponse {
// denom: response.denom,
// }
// }
/// Returns information about the supply Denom
pub fn get_denom(deps: Deps<TokenFactoryQuery>) -> StdResult<DenomResponse> {
let denom = SUPPLY_DENOM.load(deps.storage)?;
Ok(DenomResponse { denom })
}

pub fn query_donations(
deps: Deps<TokenFactoryQuery>,
Expand Down
95 changes: 95 additions & 0 deletions contracts/external/cw-abc/src/testing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
use crate::abc::{
ClosedConfig, CommonsPhaseConfig, CurveType, HatchConfig, MinMax, OpenConfig, ReserveToken,
SupplyToken,
};
use crate::msg::InstantiateMsg;
use cosmwasm_std::{
testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage},
Decimal, OwnedDeps, Uint128,
};

use crate::contract;
use crate::contract::CwAbcResult;
use cosmwasm_std::DepsMut;
use std::marker::PhantomData;
use token_bindings::{Metadata, TokenFactoryQuery};

pub(crate) mod prelude {
pub use super::{
default_instantiate_msg, default_supply_metadata, mock_tf_dependencies, TEST_CREATOR,
TEST_RESERVE_DENOM, TEST_SUPPLY_DENOM, _TEST_BUYER, _TEST_INVESTOR,
};
pub use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
pub use speculoos::prelude::*;
}

pub const TEST_RESERVE_DENOM: &str = "satoshi";
pub const TEST_CREATOR: &str = "creator";
pub const _TEST_INVESTOR: &str = "investor";
pub const _TEST_BUYER: &str = "buyer";

pub const TEST_SUPPLY_DENOM: &str = "subdenom";

pub fn default_supply_metadata() -> Metadata {
Metadata {
name: Some("Bonded".to_string()),
symbol: Some("EPOXY".to_string()),
description: None,
denom_units: vec![],
base: None,
display: None,
}
}

pub fn default_instantiate_msg(
decimals: u8,
reserve_decimals: u8,
curve_type: CurveType,
) -> InstantiateMsg {
InstantiateMsg {
token_issuer_code_id: 1,
supply: SupplyToken {
subdenom: TEST_SUPPLY_DENOM.to_string(),
metadata: Some(default_supply_metadata()),
decimals,
},
reserve: ReserveToken {
denom: TEST_RESERVE_DENOM.to_string(),
decimals: reserve_decimals,
},
phase_config: CommonsPhaseConfig {
hatch: HatchConfig {
initial_raise: MinMax {
min: Uint128::one(),
max: Uint128::from(1000000u128),
},
initial_price: Uint128::one(),
initial_allocation_ratio: Decimal::percent(10u64),
exit_tax: Decimal::zero(),
},
open: OpenConfig {
allocation_percentage: Decimal::percent(10u64),
exit_tax: Decimal::percent(10u64),
},
closed: ClosedConfig {},
},
hatcher_allowlist: None,
curve_type,
}
}

pub fn mock_init(deps: DepsMut<TokenFactoryQuery>, init_msg: InstantiateMsg) -> CwAbcResult {
let info = mock_info(TEST_CREATOR, &[]);
let env = mock_env();
contract::instantiate(deps, env, info, init_msg)
}

pub fn mock_tf_dependencies(
) -> OwnedDeps<MockStorage, MockApi, MockQuerier<TokenFactoryQuery>, TokenFactoryQuery> {
OwnedDeps {
storage: MockStorage::default(),
api: MockApi::default(),
querier: MockQuerier::<TokenFactoryQuery>::new(&[]),
custom_query_type: PhantomData::<TokenFactoryQuery>,
}
}

0 comments on commit 988cf5d

Please sign in to comment.