Skip to content

Commit

Permalink
Fix prediction-markets tests, I (#1265)
Browse files Browse the repository at this point in the history
* Test `admin_move_market_to_resolved` with disputed market

* Fix formatting

* Move court integration test to `integration.rs`

* Test that `approve_market` fails in invalid states

* Use `ApproveOrigin` instead of `SUDO`

* Fix formatting

* Use `RejectOrigin` instead of `SUDO`

* Use `CloseMarketEarlyOrigin` instead of `SUDO`

* Use `CloseOrigin` instead of `SUDO`

* Remove `DestroyOrigin`

* Use `RequestEditOrigin` to replace `SUDO`

* Use `ResolveOrigin` to replace `SUDO`

* Fix benchmarks and tests

* Remove solved TODO

* Add `buy_complete_set` tests

* Add missing `close_trusted_market` tests

* Add missing tests for `create_market`

* Fix naming in `benchmarks.rs`

* Apply suggestions from code review

Co-authored-by: Harald Heckmann <[email protected]>

---------

Co-authored-by: Harald Heckmann <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Apr 8, 2024
1 parent 2d0277b commit 45701a6
Show file tree
Hide file tree
Showing 22 changed files with 699 additions and 537 deletions.
7 changes: 0 additions & 7 deletions runtime/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,6 @@ macro_rules! decl_common_types {
EnsureProportionAtLeast<AccountId, AdvisoryCommitteeInstance, 2, 3>,
>;

// At least 100%
type EnsureRootOrAllAdvisoryCommittee = EitherOfDiverse<
EnsureRoot<AccountId>,
EnsureProportionAtLeast<AccountId, AdvisoryCommitteeInstance, 1, 1>,
>;

#[cfg(feature = "std")]
/// The version information used to identify this runtime when compiled natively.
pub fn native_version() -> NativeVersion {
Expand Down Expand Up @@ -1274,7 +1268,6 @@ macro_rules! impl_config_traits {
type CloseEarlyProtectionTimeFramePeriod = CloseEarlyProtectionTimeFramePeriod;
type CloseEarlyProtectionBlockPeriod = CloseEarlyProtectionBlockPeriod;
type CloseEarlyRequestBond = CloseEarlyRequestBond;
type DestroyOrigin = EnsureRootOrAllAdvisoryCommittee;
type DeployPool = NeoSwaps;
type DisputeBond = DisputeBond;
type RuntimeEvent = RuntimeEvent;
Expand Down
1 change: 0 additions & 1 deletion zrml/neo-swaps/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,6 @@ impl zrml_prediction_markets::Config for Runtime {
type Court = Court;
type Currency = Balances;
type DeployPool = DeployPoolNoop;
type DestroyOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type DisputeBond = DisputeBond;
type RuntimeEvent = RuntimeEvent;
type GlobalDisputes = GlobalDisputes;
Expand Down
24 changes: 12 additions & 12 deletions zrml/prediction-markets/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,10 @@ benchmarks! {
).unwrap();
}

let close_origin = T::CloseOrigin::try_successful_origin().unwrap();
let resolve_origin = T::ResolveOrigin::try_successful_origin().unwrap();
let call = Call::<T>::admin_move_market_to_resolved { market_id };
}: {
call.dispatch_bypass_filter(close_origin)?
call.dispatch_bypass_filter(resolve_origin)?
} verify {
assert_last_event::<T>(Event::MarketResolved::<T>(
market_id,
Expand Down Expand Up @@ -316,10 +316,10 @@ benchmarks! {
).unwrap();
}

let close_origin = T::CloseOrigin::try_successful_origin().unwrap();
let resolve_origin = T::ResolveOrigin::try_successful_origin().unwrap();
let call = Call::<T>::admin_move_market_to_resolved { market_id };
}: {
call.dispatch_bypass_filter(close_origin)?
call.dispatch_bypass_filter(resolve_origin)?
} verify {
assert_last_event::<T>(Event::MarketResolved::<T>(
market_id,
Expand Down Expand Up @@ -368,10 +368,10 @@ benchmarks! {
).unwrap();
}

let close_origin = T::CloseOrigin::try_successful_origin().unwrap();
let resolve_origin = T::ResolveOrigin::try_successful_origin().unwrap();
let call = Call::<T>::admin_move_market_to_resolved { market_id };
}: {
call.dispatch_bypass_filter(close_origin)?
call.dispatch_bypass_filter(resolve_origin)?
} verify {
assert_last_event::<T>(Event::MarketResolved::<T>(
market_id,
Expand Down Expand Up @@ -421,10 +421,10 @@ benchmarks! {
).unwrap();
}

let close_origin = T::CloseOrigin::try_successful_origin().unwrap();
let resolve_origin = T::ResolveOrigin::try_successful_origin().unwrap();
let call = Call::<T>::admin_move_market_to_resolved { market_id };
}: {
call.dispatch_bypass_filter(close_origin)?
call.dispatch_bypass_filter(resolve_origin)?
} verify {
assert_last_event::<T>(Event::MarketResolved::<T>(
market_id,
Expand Down Expand Up @@ -456,10 +456,10 @@ benchmarks! {
Some(MarketDisputeMechanism::Court),
)?;

let approve_origin = T::ApproveOrigin::try_successful_origin().unwrap();
let request_edit_origin = T::RequestEditOrigin::try_successful_origin().unwrap();
let edit_reason = vec![0_u8; r as usize];
let call = Call::<T>::request_edit{ market_id, edit_reason };
}: { call.dispatch_bypass_filter(approve_origin)? } verify {}
}: { call.dispatch_bypass_filter(request_edit_origin)? } verify {}

buy_complete_set {
let a in (T::MinCategories::get().into())..T::MaxCategories::get().into();
Expand Down Expand Up @@ -529,10 +529,10 @@ benchmarks! {
.dispatch_bypass_filter(RawOrigin::Signed(caller.clone()).into())?;
let market_id = zrml_market_commons::Pallet::<T>::latest_market_id()?;

let approve_origin = T::ApproveOrigin::try_successful_origin().unwrap();
let request_edit_origin = T::RequestEditOrigin::try_successful_origin().unwrap();
let edit_reason = vec![0_u8; 1024];
Call::<T>::request_edit{ market_id, edit_reason }
.dispatch_bypass_filter(approve_origin)?;
.dispatch_bypass_filter(request_edit_origin)?;

for i in 0..m {
MarketIdsPerCloseTimeFrame::<T>::try_mutate(
Expand Down
3 changes: 0 additions & 3 deletions zrml/prediction-markets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1628,9 +1628,6 @@ mod pallet {
MarketId = MarketIdOf<Self>,
>;

/// The origin that is allowed to destroy markets.
type DestroyOrigin: EnsureOrigin<Self::RuntimeOrigin>;

/// The base amount of currency that must be bonded in order to create a dispute.
#[pallet::constant]
type DisputeBond: Get<BalanceOf<Self>>;
Expand Down
28 changes: 20 additions & 8 deletions zrml/prediction-markets/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ use sp_runtime::{
DispatchError, DispatchResult,
};
use std::cell::RefCell;
#[cfg(feature = "parachain")]
use zeitgeist_primitives::types::XcmAsset;
use zeitgeist_primitives::{
constants::mock::{
AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AssetsAccountDeposit,
Expand All @@ -68,7 +70,6 @@ use zeitgeist_primitives::{
AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest,
CampaignAsset, CampaignAssetClass, CampaignAssetId, Currencies, CustomAsset, CustomAssetId,
Hash, Index, MarketAsset, MarketId, Moment, ResultWithWeightInfo, UncheckedExtrinsicTest,
XcmAsset,
},
};

Expand All @@ -86,6 +87,12 @@ pub const DAVE: AccountIdTest = 3;
pub const EVE: AccountIdTest = 4;
pub const FRED: AccountIdTest = 5;
pub const SUDO: AccountIdTest = 69;
pub const APPROVE_ORIGIN: AccountIdTest = 70;
pub const REJECT_ORIGIN: AccountIdTest = 71;
pub const CLOSE_MARKET_EARLY_ORIGIN: AccountIdTest = 72;
pub const CLOSE_ORIGIN: AccountIdTest = 73;
pub const REQUEST_EDIT_ORIGIN: AccountIdTest = 74;
pub const RESOLVE_ORIGIN: AccountIdTest = 75;

pub const INITIAL_BALANCE: u128 = 1_000 * BASE;

Expand Down Expand Up @@ -191,6 +198,12 @@ impl DeployPoolMock {

ord_parameter_types! {
pub const Sudo: AccountIdTest = SUDO;
pub const ApproveOrigin: AccountIdTest = APPROVE_ORIGIN;
pub const RejectOrigin: AccountIdTest = REJECT_ORIGIN;
pub const CloseMarketEarlyOrigin: AccountIdTest = CLOSE_MARKET_EARLY_ORIGIN;
pub const CloseOrigin: AccountIdTest = CLOSE_ORIGIN;
pub const RequestEditOrigin: AccountIdTest = REQUEST_EDIT_ORIGIN;
pub const ResolveOrigin: AccountIdTest = RESOLVE_ORIGIN;
}
parameter_types! {
pub const AdvisoryBond: Balance = 11 * CENT;
Expand Down Expand Up @@ -235,23 +248,22 @@ construct_runtime!(
impl crate::Config for Runtime {
type AdvisoryBond = AdvisoryBond;
type AdvisoryBondSlashPercentage = AdvisoryBondSlashPercentage;
type ApproveOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type ApproveOrigin = EnsureSignedBy<ApproveOrigin, AccountIdTest>;
type AssetCreator = AssetRouter;
type AssetDestroyer = AssetRouter;
type AssetManager = AssetManager;
#[cfg(feature = "parachain")]
type AssetRegistry = MockRegistry;
type Authorized = Authorized;
type CloseEarlyDisputeBond = CloseEarlyDisputeBond;
type CloseMarketEarlyOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type CloseMarketEarlyOrigin = EnsureSignedBy<CloseMarketEarlyOrigin, AccountIdTest>;
type CloseEarlyProtectionTimeFramePeriod = CloseEarlyProtectionTimeFramePeriod;
type CloseEarlyProtectionBlockPeriod = CloseEarlyProtectionBlockPeriod;
type CloseEarlyRequestBond = CloseEarlyRequestBond;
type CloseOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type CloseOrigin = EnsureSignedBy<CloseOrigin, AccountIdTest>;
type Currency = Balances;
type MaxCreatorFee = MaxCreatorFee;
type Court = Court;
type DestroyOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type DeployPool = DeployPoolMock;
type DisputeBond = DisputeBond;
type RuntimeEvent = RuntimeEvent;
Expand All @@ -274,9 +286,9 @@ impl crate::Config for Runtime {
type PalletId = PmPalletId;
type CloseEarlyBlockPeriod = CloseEarlyBlockPeriod;
type CloseEarlyTimeFramePeriod = CloseEarlyTimeFramePeriod;
type RejectOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type RequestEditOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type ResolveOrigin = EnsureSignedBy<Sudo, AccountIdTest>;
type RejectOrigin = EnsureSignedBy<RejectOrigin, AccountIdTest>;
type RequestEditOrigin = EnsureSignedBy<RequestEditOrigin, AccountIdTest>;
type ResolveOrigin = EnsureSignedBy<ResolveOrigin, AccountIdTest>;
type SimpleDisputes = SimpleDisputes;
type Slash = Treasury;
type ValidityBond = ValidityBond;
Expand Down
19 changes: 14 additions & 5 deletions zrml/prediction-markets/src/tests/admin_move_market_to_closed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn admin_move_market_to_closed_successfully_closes_market_and_sets_end_blocknumb
run_blocks(3);
let market_id = 0;
assert_ok!(PredictionMarkets::admin_move_market_to_closed(
RuntimeOrigin::signed(SUDO),
RuntimeOrigin::signed(CloseOrigin::get()),
market_id
));
let market = MarketCommons::market(&market_id).unwrap();
Expand Down Expand Up @@ -81,7 +81,7 @@ fn admin_move_market_to_closed_successfully_closes_market_and_sets_end_timestamp
run_blocks(shift_blocks);

assert_ok!(PredictionMarkets::admin_move_market_to_closed(
RuntimeOrigin::signed(SUDO),
RuntimeOrigin::signed(CloseOrigin::get()),
market_id
));
let market = MarketCommons::market(&market_id).unwrap();
Expand All @@ -97,7 +97,10 @@ fn admin_move_market_to_closed_successfully_closes_market_and_sets_end_timestamp
fn admin_move_market_to_closed_fails_if_market_does_not_exist() {
ExtBuilder::default().build().execute_with(|| {
assert_noop!(
PredictionMarkets::admin_move_market_to_closed(RuntimeOrigin::signed(SUDO), 0),
PredictionMarkets::admin_move_market_to_closed(
RuntimeOrigin::signed(CloseOrigin::get()),
0
),
zrml_market_commons::Error::<Runtime>::MarketDoesNotExist
);
});
Expand All @@ -122,7 +125,10 @@ fn admin_move_market_to_closed_fails_if_market_is_not_active(market_status: Mark
Ok(())
}));
assert_noop!(
PredictionMarkets::admin_move_market_to_closed(RuntimeOrigin::signed(SUDO), market_id),
PredictionMarkets::admin_move_market_to_closed(
RuntimeOrigin::signed(CloseOrigin::get()),
market_id
),
Error::<Runtime>::MarketIsNotActive,
);
});
Expand Down Expand Up @@ -158,7 +164,10 @@ fn admin_move_market_to_closed_correctly_clears_auto_close_blocks() {
Some(MarketDisputeMechanism::SimpleDisputes),
ScoringRule::Lmsr,
));
assert_ok!(PredictionMarkets::admin_move_market_to_closed(RuntimeOrigin::signed(SUDO), 0));
assert_ok!(PredictionMarkets::admin_move_market_to_closed(
RuntimeOrigin::signed(CloseOrigin::get()),
0
));

let auto_close = MarketIdsPerCloseBlock::<Runtime>::get(66).into_inner();
assert_eq!(auto_close, vec![1]);
Expand Down
77 changes: 74 additions & 3 deletions zrml/prediction-markets/src/tests/admin_move_market_to_resolved.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ fn admin_move_market_to_resolved_resolves_reported_market() {
outcome_report.clone()
));
assert_ok!(PredictionMarkets::admin_move_market_to_resolved(
RuntimeOrigin::signed(SUDO),
RuntimeOrigin::signed(ResolveOrigin::get()),
market_id
));

Expand Down Expand Up @@ -94,7 +94,78 @@ fn admin_move_market_to_resolved_resolves_reported_market() {
});
}

// TODO(#1239) resolves disputed market
#[test]
fn admin_move_market_to_resolved_resolves_disputed_market() {
// NOTE: Bonds are always in ZTG, irrespective of base_asset.
let test = |base_asset: BaseAsset| {
let end = 33;
simple_create_categorical_market(
base_asset,
MarketCreation::Permissionless,
0..end,
ScoringRule::Lmsr,
);
let market_id = 0;

// Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check
// that the correct bonds are unreserved!
assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT));
assert_ok!(Balances::reserve_named(
&PredictionMarkets::reserve_id(),
&ALICE,
SENTINEL_AMOUNT
));
let balance_free_before = Balances::free_balance(ALICE);
let balance_reserved_before =
Balances::reserved_balance_named(&PredictionMarkets::reserve_id(), &ALICE);

let market = MarketCommons::market(&0).unwrap();
let grace_period = end + market.deadlines.grace_period;
run_to_block(grace_period + 1);
let category = 1;
let outcome_report = OutcomeReport::Categorical(category);
assert_ok!(PredictionMarkets::report(
RuntimeOrigin::signed(BOB),
market_id,
OutcomeReport::Categorical(0),
));
assert_ok!(PredictionMarkets::dispute(RuntimeOrigin::signed(CHARLIE), market_id));
assert_ok!(Authorized::authorize_market_outcome(
RuntimeOrigin::signed(AuthorizedDisputeResolutionUser::get()),
market_id,
outcome_report.clone(),
));
assert_ok!(PredictionMarkets::admin_move_market_to_resolved(
RuntimeOrigin::signed(ResolveOrigin::get()),
market_id
));

let market = MarketCommons::market(&market_id).unwrap();
assert_eq!(market.status, MarketStatus::Resolved);
assert_eq!(market.resolved_outcome.unwrap(), outcome_report);
System::assert_last_event(
Event::MarketResolved(market_id, MarketStatus::Resolved, outcome_report).into(),
);

assert_eq!(
Balances::reserved_balance_named(&PredictionMarkets::reserve_id(), &ALICE),
balance_reserved_before
- <Runtime as Config>::OracleBond::get()
- <Runtime as Config>::ValidityBond::get()
);
assert_eq!(
Balances::free_balance(ALICE),
balance_free_before + <Runtime as Config>::ValidityBond::get()
);
};
ExtBuilder::default().build().execute_with(|| {
test(BaseAsset::Ztg);
});
#[cfg(feature = "parachain")]
ExtBuilder::default().build().execute_with(|| {
test(BaseAsset::ForeignAsset(100));
});
}

#[test_case(MarketStatus::Active)]
#[test_case(MarketStatus::Closed)]
Expand All @@ -116,7 +187,7 @@ fn admin_move_market_to_resolved_fails_if_market_is_not_reported_or_disputed(
}));
assert_noop!(
PredictionMarkets::admin_move_market_to_resolved(
RuntimeOrigin::signed(SUDO),
RuntimeOrigin::signed(ResolveOrigin::get()),
market_id,
),
Error::<Runtime>::InvalidMarketStatus,
Expand Down
Loading

0 comments on commit 45701a6

Please sign in to comment.