Skip to content

Commit

Permalink
fix: use Uint256 & Decimal256 to be able to work with 18 decimals
Browse files Browse the repository at this point in the history
  • Loading branch information
nseguias committed Jul 31, 2024
1 parent 5403df5 commit d7c3dd7
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 62 deletions.
3 changes: 1 addition & 2 deletions contracts/injective-auction-pool/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ pub fn execute(
} => executions::try_bid(deps, env, info, auction_round, basket_value),
ExecuteMsg::JoinPool {
auction_round,
basket_value,
} => executions::join_pool(deps, env, info, auction_round, basket_value),
} => executions::join_pool(deps, env, info, auction_round),
ExecuteMsg::ExitPool {} => executions::exit_pool(deps, env, info),
ExecuteMsg::SettleAuction {
auction_round,
Expand Down
32 changes: 10 additions & 22 deletions contracts/injective-auction-pool/src/executions.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use cosmwasm_std::{
attr, coins, to_json_binary, BankMsg, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Response,
Uint128, WasmMsg,
attr, coins, BankMsg, CosmosMsg, Decimal, Decimal256, DepsMut, Env, MessageInfo, Response,
Uint128, Uint256,
};
use injective_auction::auction_pool::ExecuteMsg::TryBid;
use injective_std::types::cosmos::base::v1beta1::Coin;
use injective_std::types::injective::auction::v1beta1::MsgBid;

Expand Down Expand Up @@ -107,7 +106,6 @@ pub(crate) fn join_pool(
env: Env,
info: MessageInfo,
auction_round: u64,
basket_value: Uint128,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
let amount = cw_utils::must_pay(&info, &config.native_denom)?;
Expand All @@ -132,7 +130,7 @@ pub(crate) fn join_pool(
amount,
));

// send the minted lp token to the user
// send the minted lp token to the user address
let lp_denom = format!("factory/{}/auction.{}", env.contract.address, lp_subdenom);
messages.push(
BankMsg::Send {
Expand All @@ -146,16 +144,6 @@ pub(crate) fn join_pool(
BIDDING_BALANCE
.update::<_, ContractError>(deps.storage, |balance| Ok(balance.checked_add(amount)?))?;

// try to bid on the auction if possible
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: env.contract.address.to_string(),
msg: to_json_binary(&TryBid {
auction_round,
basket_value,
})?,
funds: vec![],
}));

Ok(Response::default().add_messages(messages).add_attributes(vec![
("action", "join_pool".to_string()),
("auction_round", auction_round.to_string()),
Expand Down Expand Up @@ -232,7 +220,6 @@ pub(crate) fn try_bid(

let current_auction_round_response = query_current_auction(deps.as_ref())?;
let current_auction_round = current_auction_round_response.auction_round;
//.ok_or(ContractError::CurrentAuctionQueryError)?;

// prevents the contract from bidding on the wrong auction round
if auction_round != current_auction_round.u64() {
Expand All @@ -255,22 +242,23 @@ pub(crate) fn try_bid(
let minimum_allowed_bid = current_auction_round_response
.highest_bid_amount
.to_string()
// .unwrap_or(0.to_string())
.parse::<Decimal>()?
.checked_mul((Decimal::one().checked_add(config.min_next_bid_increment_rate))?)?
.parse::<Decimal256>()?
.checked_mul((Decimal256::one().checked_add(config.min_next_bid_increment_rate.into()))?)?
.to_uint_ceil()
.checked_add(Uint128::one())?;
.checked_add(Uint256::one())?;

// prevents the contract from bidding if the minimum allowed bid is higher than bidding balance
let bidding_balance: Uint128 = BIDDING_BALANCE.load(deps.storage)?;
if minimum_allowed_bid > bidding_balance {
if minimum_allowed_bid > bidding_balance.into() {
return Ok(Response::default()
.add_attribute("action", "did_not_bid")
.add_attribute("reason", "minimum_allowed_bid_is_higher_than_bidding_balance"));
}

// prevents the contract from bidding if the returns are not high enough
if basket_value * (Decimal::one() - config.min_return) < minimum_allowed_bid {
if Uint256::from(basket_value) * (Decimal256::one() - Decimal256::from(config.min_return))
< minimum_allowed_bid
{
return Ok(Response::default()
.add_attribute("action", "did_not_bid")
.add_attribute("reason", "basket_value_is_not_worth_bidding_for"));
Expand Down
4 changes: 2 additions & 2 deletions contracts/injective-auction-pool/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,8 @@ pub(crate) fn validate_percentage(percentage: Decimal) -> Result<Decimal, Contra
/// Queries the current auction
pub(crate) fn query_current_auction(
deps: Deps,
) -> StdResult<crate::state::QueryCurrentAuctionBasketResponse> {
let current_auction_basket_response: crate::state::QueryCurrentAuctionBasketResponse =
) -> StdResult<crate::state::CurrentAuctionBasketResponse> {
let current_auction_basket_response: crate::state::CurrentAuctionBasketResponse =
deps.querier.query(&QueryRequest::Stargate {
path: "/injective.auction.v1beta1.Query/CurrentAuctionBasket".to_string(),
data: [].into(),
Expand Down
2 changes: 1 addition & 1 deletion contracts/injective-auction-pool/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub const FUNDS_LOCKED: Item<bool> = Item::new("funds_locked");

#[cw_serde]
#[serde(rename_all = "camelCase")]
pub struct QueryCurrentAuctionBasketResponse {
pub struct CurrentAuctionBasketResponse {
pub amount: Vec<Coin>,
pub auction_round: Uint64,
pub auction_closing_time: Int64,
Expand Down
46 changes: 21 additions & 25 deletions contracts/injective-auction-pool/src/tests/unit_tests.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::marker::PhantomData;
use std::{marker::PhantomData, str::FromStr};

use cosmwasm_std::{
attr, coin, coins, from_json,
testing::{mock_env, mock_info, BankQuerier, MockApi, MockStorage, MOCK_CONTRACT_ADDR},
to_json_binary, Addr, BankMsg, Binary, CodeInfoResponse, ContractResult as CwContractResult,
CosmosMsg, Decimal, Empty, Env, HexBinary, Int64, MemoryStorage, MessageInfo, OwnedDeps,
Querier, QuerierResult, QueryRequest, Uint128, Uint64, WasmMsg, WasmQuery,
CosmosMsg, Decimal, Decimal256, Empty, Env, HexBinary, Int64, MemoryStorage, MessageInfo,
OwnedDeps, Querier, QuerierResult, QueryRequest, Uint128, Uint256, Uint64, WasmQuery,
};
use cw_ownable::Ownership;
use injective_auction::auction_pool::{
Expand Down Expand Up @@ -44,7 +44,7 @@ impl Querier for AuctionQuerier {
} => match path.as_str() {
"/injective.auction.v1beta1.Query/CurrentAuctionBasket" => {
Ok(CwContractResult::Ok(
to_json_binary(&crate::state::QueryCurrentAuctionBasketResponse {
to_json_binary(&crate::state::CurrentAuctionBasketResponse {
amount: vec![cosmwasm_std::Coin {
denom: "uatom".to_string(),
amount: Uint128::new(10000u128),
Expand Down Expand Up @@ -337,7 +337,6 @@ pub fn join_pool_works() {
let info = mock_info("robinho", &coins(100, "native_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
};
let res = execute(deps.as_mut().branch(), env.clone(), info, msg).unwrap();

Expand All @@ -361,20 +360,6 @@ pub fn join_pool_works() {
.into()
);

// contract calls try_bid on itself
assert_eq!(
res.messages[2].msg,
CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: MOCK_CONTRACT_ADDR.to_string(),
msg: to_json_binary(&ExecuteMsg::TryBid {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
})
.unwrap(),
funds: vec![],
})
);

// checking attributes are fine
assert_eq!(
res.attributes,
Expand All @@ -398,7 +383,6 @@ fn join_pool_fails() {
let info = mock_info("robinho", &coins(100, "wrong_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
};
let res = execute(deps.as_mut().branch(), env.clone(), info, msg.clone()).unwrap_err();
assert_eq!(
Expand All @@ -422,7 +406,6 @@ fn join_pool_fails() {
let info = mock_info("robinho", &coins(100, "native_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 2,
basket_value: Uint128::from(10_000u128),
};
let res = execute(deps.as_mut().branch(), env.clone(), info, msg.clone()).unwrap_err();
assert_eq!(
Expand All @@ -441,7 +424,6 @@ fn exit_pool_works() {
let info = mock_info("robinho", &coins(100, "native_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
};
let _ = execute(deps.as_mut().branch(), env.clone(), info, msg).unwrap();

Expand Down Expand Up @@ -482,7 +464,6 @@ fn exit_pool_fails() {
let info = mock_info("robinho", &coins(100, "native_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
};
let _ = execute(deps.as_mut().branch(), env.clone(), info.clone(), msg).unwrap();

Expand Down Expand Up @@ -554,7 +535,6 @@ fn try_bid_works() {
let info = mock_info("robinho", &coins(30_000, "native_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
};
let _ = execute(deps.as_mut().branch(), env.clone(), info, msg).unwrap();

Expand Down Expand Up @@ -631,7 +611,6 @@ fn try_bid_fails() {
let info = mock_info("robinho", &coins(30_000, "native_denom"));
let msg = ExecuteMsg::JoinPool {
auction_round: 1,
basket_value: Uint128::from(10_000u128),
};
let _ = execute(deps.as_mut().branch(), env.clone(), info, msg).unwrap();

Expand Down Expand Up @@ -819,3 +798,20 @@ fn try_bid_fails() {
// // funds should be released
// assert!(!FUNDS_LOCKED.load(deps.as_ref().storage).unwrap());
// }

#[test]
fn testing_math() {
let minimum_allowed_bid = 7_212_340_000_000_000_000_000_u128
.to_string()
.parse::<Decimal256>()
.unwrap()
.checked_mul(
Decimal256::one().checked_add(Decimal256::from_str("0.0005").unwrap()).unwrap(),
)
.unwrap()
.to_uint_ceil()
.checked_add(Uint256::one())
.unwrap();

println!("{:?}", minimum_allowed_bid);
}
31 changes: 23 additions & 8 deletions deploy/02-testnet-auction.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ export FROM=auction-test
export FROM_ADDR=inj12nn88vtuf893cpfkke23dszpr5uccqj2zqukt6
export TREASURE=8127

just optimize

injectived tx wasm store ./artifacts/injective_auction_pool.wasm --from ${FROM} --yes --gas-prices "160000000inj" --gas-adjustment 1.3 --gas auto

tx=BF46482DC0C034F186BC554E64A46B01A19F7D5E02DE16389E5AD76F355FA35C
tx=95376ED78346B509E2226649CC1BEBDBFC827E1E4DDB4ADA8D279DD9D0858E14

export AUCTION=$(injectived query tx ${tx} |jq -e -r ' .events[] | select(.type=="cosmwasm.wasm.v1.EventCodeStored").attributes[] | select(.key=="code_id").value ' | tr -d '"')
echo $AUCTION
export AUCTION=11699
export AUCTION=11745

## create the test denom
export FEE_AMT=$(injectived query tokenfactory params|jq -r '.params.denom_creation_fee[0].amount')
Expand All @@ -37,16 +39,29 @@ injectived tx wasm instantiate $AUCTION ${INIT_MSG} \
--amount ${FEE_AMT}inj \
--from $FROM --yes --gas-prices "160000000inj" --gas-adjustment 1.3 --gas auto

^^ following is failing
#tx_auction=A175DE3FF1F399E79B5BD616046C54BAE9CA5AAACE67A9E453C71189014FE145
tx_auction=8E651410ACF16145CCB10F99F6C4B9989E3068665DA5C07564A4616E34D84F50
tx_auction=576DE92111628B290A9E174C31F742B7D5CFB21160A8ECED2320749DCF590BF7

export AUCTION_CONTRACT=$(injectived query tx $tx_auction|jq -r '.events[]| select(.type=="cosmwasm.wasm.v1.EventContractInstantiated").attributes[] |select(.key=="contract_address").value '|tr -d '"')
echo $AUCTION_CONTRACT
#export AUCTION_CONTRACT=inj1r467s95lrzf005pw4x6grzhhtnmw9lx93lcpek
# export AUCTION_CONTRACT=inj1r467s95lrzf005pw4x6grzhhtnmw9lx93lcpek
# export AUCTION_CONTRACT=inj1s9dzsqrrq09z46ye7ffa9fldg3dt0e2cvx6yla
# export AUCTION_CONTRACT=inj1ghtvh6juxudspvrh9tdlz0p4d4u6k8xxd6jkgx
# export AUCTION_CONTRACT=inj1kar690fes35rm0dx5zcjwt5pjhtvcf572w3ffe

injectived query wasm cs smart $AUCTION_CONTRACT '{"query_current_auction_basket":{}}'
injectived query wasm cs smart $AUCTION_CONTRACT '{"current_auction_basket":{}}'
injectived query wasm cs smart $AUCTION_CONTRACT '{"whitelisted_addresses":{}}'
injectived query wasm cs smart $AUCTION_CONTRACT '{"funds_locked":{}}'
injectived query wasm cs smart $AUCTION_CONTRACT '{"bidding_balance":{}}'
injectived query wasm cs smart $AUCTION_CONTRACT '{"bidding_balance":{}}'

# add address to whitelist
injectived tx wasm execute $AUCTION_CONTRACT '{"update_white_listed_addresses":{"add":["inj12nn88vtuf893cpfkke23dszpr5uccqj2zqukt6"], "remove":[]}}' --from inj1cdugmt5t0mgfsmfc99eyhe4fzps0937ae0jgqh --yes --gas-prices "160000000inj" --gas-adjustment 1.3 --gas auto --node https://testnet.sentry.tm.injective.network:443 --output json --chain-id injective-888 | jq

# join pool with 1inj
injectived tx wasm execute $AUCTION_CONTRACT '{"join_pool":{"auction_round":108, "basket_value":"1000"}}' \
--from inj1cdugmt5t0mgfsmfc99eyhe4fzps0937ae0jgqh --yes --gas-prices "160000000inj" --gas-adjustment 1.3 --gas auto \
--node https://testnet.sentry.tm.injective.network:443 --output json --chain-id injective-888 --amount 1000000000000000000inj | jq

# try bid
injectived tx wasm execute $AUCTION_CONTRACT '{"try_bid":{"auction_round":108, "basket_value":"1000"}}' \
--from inj1cdugmt5t0mgfsmfc99eyhe4fzps0937ae0jgqh --yes --gas-prices "160000000inj" --gas-adjustment 1.3 --gas auto \
--node https://testnet.sentry.tm.injective.network:443 --output json --chain-id injective-888 | jq
2 changes: 0 additions & 2 deletions packages/injective_auction/src/auction_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ pub enum ExecuteMsg {
JoinPool {
/// The auction round to join
auction_round: u64,
/// The value in native denom of all assets being auctioned
basket_value: Uint128,
},
/// Can be called by the user before T-1 day from auction's end to exit the auction.
ExitPool {},
Expand Down

0 comments on commit d7c3dd7

Please sign in to comment.