Skip to content

Commit

Permalink
fix after merge
Browse files Browse the repository at this point in the history
  • Loading branch information
Chralt98 committed Aug 22, 2023
1 parent d1b437d commit 77b8825
Show file tree
Hide file tree
Showing 8 changed files with 1,046 additions and 936 deletions.
1,728 changes: 962 additions & 766 deletions Cargo.lock

Large diffs are not rendered by default.

71 changes: 41 additions & 30 deletions zrml/court/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2298,39 +2298,50 @@ mod pallet {
Error::<T>::MarketDoesNotHaveCourtMechanism
);

let court_id = <MarketIdToCourtId<T>>::get(market_id)
.ok_or(Error::<T>::MarketIdToCourtIdNotFound)?;

let court = <Courts<T>>::get(court_id).ok_or(Error::<T>::CourtNotFound)?;
// oracle outcome is added by pm-pallet
let mut gd_outcomes: Vec<GlobalDisputeItem<Self::AccountId, Self::Balance>> =
Vec::new();

let report = market.report.as_ref().ok_or(Error::<T>::MarketReportNotFound)?;
let oracle_outcome = &report.outcome;
let mut appeals_len = 0u32;
let mut draws_len = 0u32;

let appeals_len = court.appeals.len() as u32;

let gd_outcomes = court
.appeals
.iter()
.filter_map(|a| {
match a.appealed_vote_item.clone().into_outcome() {
// oracle outcome is added by pm pallet
Some(outcome) if outcome != *oracle_outcome => Some(GlobalDisputeItem {
outcome,
// we have no better global dispute outcome owner
owner: Self::treasury_account_id(),
// initial vote amount
initial_vote_amount: <BalanceOf<T>>::zero(),
}),
_ => None,
}
})
.collect::<Vec<GlobalDisputeItem<Self::AccountId, Self::Balance>>>();
// None case can happen if no dispute could be created,
// because there is not enough juror and delegator stake,
// in this case allow a global dispute
if let Some(court_id) = <MarketIdToCourtId<T>>::get(market_id) {
let court = <Courts<T>>::get(court_id).ok_or(Error::<T>::CourtNotFound)?;

appeals_len = court.appeals.len() as u32;

let report = market.report.as_ref().ok_or(Error::<T>::MarketReportNotFound)?;
let oracle_outcome = &report.outcome;

gd_outcomes = court
.appeals
.iter()
.filter_map(|a| {
match a.appealed_vote_item.clone().into_outcome() {
// oracle outcome is added by pm pallet
Some(outcome) if outcome != *oracle_outcome => {
Some(GlobalDisputeItem {
outcome,
// we have no better global dispute outcome owner
owner: Self::treasury_account_id(),
// initial vote amount
initial_vote_amount: <BalanceOf<T>>::zero(),
})
}
_ => None,
}
})
.collect::<Vec<GlobalDisputeItem<Self::AccountId, Self::Balance>>>();

let old_draws = SelectedDraws::<T>::get(court_id);
let draws_len = old_draws.len() as u32;
Self::unlock_participants_from_last_draw(court_id, old_draws);
<SelectedDraws<T>>::remove(court_id);
<Courts<T>>::remove(court_id);
let old_draws = SelectedDraws::<T>::get(court_id);
draws_len = old_draws.len() as u32;
Self::unlock_participants_from_last_draw(court_id, old_draws);
<SelectedDraws<T>>::remove(court_id);
<Courts<T>>::remove(court_id);
}

let res = ResultWithWeightInfo {
result: gd_outcomes,
Expand Down
19 changes: 2 additions & 17 deletions zrml/global-disputes/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ pub type InitialItemOf<T> = crate::types::InitialItem<AccountIdOf<T>, BalanceOf<
#[frame_support::pallet]
mod pallet {
use crate::{types::*, weights::WeightInfoZeitgeist, GlobalDisputesPalletApi, InitialItemOf};
use alloc::collections::BTreeSet;
use core::marker::PhantomData;
use frame_support::{
ensure, log,
Expand Down Expand Up @@ -221,8 +220,6 @@ mod pallet {
pub enum Error<T> {
/// Sender tried to vote with an amount below a defined minimum.
AmountTooLow,
/// To start a global dispute, at least two outcomes are required.
AtLeastTwoUniqueOutcomesRequired,
/// The global dispute status is invalid for this operation.
InvalidGlobalDisputeStatus,
/// Sender does not have enough funds for the vote on an outcome.
Expand Down Expand Up @@ -332,11 +329,12 @@ mod pallet {
///
/// Complexity: `O(n)`,
/// where `n` is the number of all existing outcomes for a global dispute.
#[frame_support::transactional]
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::refund_vote_fees(
T::RemoveKeysLimit::get(),
T::MaxOwners::get(),
))]
#[frame_support::transactional]
pub fn refund_vote_fees(
origin: OriginFor<T>,
#[pallet::compact] market_id: MarketIdOf<T>,
Expand Down Expand Up @@ -815,19 +813,6 @@ mod pallet {
Error::<T>::GlobalDisputeAlreadyExists
);

let mut outcome_set = BTreeSet::new();
// insert returns true if the outcome is already present
let outcome_count = initial_items
.iter()
// insert returns true if the outcome was not already present (unqiue)
.filter(|item| outcome_set.insert(item.outcome.clone()))
.take(2) // Limit the iterator to at most two unique outcomes
.count();

if outcome_count < 2 {
return Err(Error::<T>::AtLeastTwoUniqueOutcomesRequired.into());
}

for InitialItem { outcome, owner, amount } in initial_items {
ensure!(market.matches_outcome_report(outcome), Error::<T>::OutcomeMismatch);

Expand Down
12 changes: 2 additions & 10 deletions zrml/global-disputes/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use frame_support::{
pallet_prelude::{DispatchError, Weight},
parameter_types,
traits::Everything,
BoundedVec,
};
use sp_runtime::{
testing::Header,
Expand All @@ -37,8 +36,8 @@ use zeitgeist_primitives::{
},
traits::DisputeResolutionApi,
types::{
AccountIdTest, Asset, Balance, BlockNumber, BlockTest, Hash, Index, Market, MarketDispute,
MarketId, Moment, UncheckedExtrinsicTest,
AccountIdTest, Asset, Balance, BlockNumber, BlockTest, Hash, Index, Market, MarketId,
Moment, UncheckedExtrinsicTest,
},
};

Expand Down Expand Up @@ -72,7 +71,6 @@ impl DisputeResolutionApi for NoopResolution {
type Balance = Balance;
type BlockNumber = BlockNumber;
type MarketId = MarketId;
type MaxDisputes = u32;
type Moment = Moment;

fn resolve(
Expand Down Expand Up @@ -102,12 +100,6 @@ impl DisputeResolutionApi for NoopResolution {
fn remove_auto_resolve(_market_id: &Self::MarketId, _resolve_at: Self::BlockNumber) -> u32 {
0u32
}

fn get_disputes(
_market_id: &Self::MarketId,
) -> BoundedVec<MarketDispute<Self::AccountId, Self::BlockNumber>, Self::MaxDisputes> {
Default::default()
}
}

parameter_types! {
Expand Down
39 changes: 0 additions & 39 deletions zrml/global-disputes/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,45 +220,6 @@ fn start_global_dispute_fails_if_outcome_mismatch() {
});
}

#[test]
fn start_global_dispute_fails_if_less_than_two_outcomes() {
ExtBuilder::default().build().execute_with(|| {
let market_id = 0u128;
let market = market_mock::<Runtime>();
Markets::<Runtime>::insert(market_id, market);

let initial_items = vec![InitialItem {
outcome: OutcomeReport::Scalar(0),
owner: ALICE,
amount: SETUP_AMOUNT,
}];
assert_eq!(
GlobalDisputes::start_global_dispute(&market_id, initial_items.as_slice()),
Err(Error::<Runtime>::AtLeastTwoUniqueOutcomesRequired.into())
);
});
}

#[test]
fn start_global_dispute_fails_if_not_two_unique_outcomes() {
ExtBuilder::default().build().execute_with(|| {
let market_id = 0u128;
let market = market_mock::<Runtime>();
Markets::<Runtime>::insert(market_id, market);

// three times the same outcome => not at least two unique outcomes
let initial_items = vec![
InitialItem { outcome: OutcomeReport::Scalar(0), owner: ALICE, amount: SETUP_AMOUNT },
InitialItem { outcome: OutcomeReport::Scalar(0), owner: BOB, amount: SETUP_AMOUNT },
InitialItem { outcome: OutcomeReport::Scalar(0), owner: CHARLIE, amount: SETUP_AMOUNT },
];
assert_eq!(
GlobalDisputes::start_global_dispute(&market_id, initial_items.as_slice()),
Err(Error::<Runtime>::AtLeastTwoUniqueOutcomesRequired.into())
);
});
}

#[test]
fn start_global_dispute_fails_if_already_exists() {
ExtBuilder::default().build().execute_with(|| {
Expand Down
1 change: 0 additions & 1 deletion zrml/prediction-markets/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ use zeitgeist_primitives::{
},
};
use zrml_authorized::Pallet as AuthorizedPallet;
#[cfg(feature = "with-global-disputes")]
use zrml_global_disputes::GlobalDisputesPalletApi;
use zrml_market_commons::MarketCommonsPalletApi;

Expand Down
16 changes: 13 additions & 3 deletions zrml/prediction-markets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ mod pallet {
pub type CacheSize = ConstU32<64>;
pub type EditReason<T> = BoundedVec<u8, <T as Config>::MaxEditReasonLen>;
pub type RejectReason<T> = BoundedVec<u8, <T as Config>::MaxRejectReasonLen>;
#[cfg(feature = "with-global-disputes")]
type InitialItemOf<T> = InitialItem<<T as frame_system::Config>::AccountId, BalanceOf<T>>;

macro_rules! impl_unreserve_bond {
Expand Down Expand Up @@ -344,7 +343,6 @@ mod pallet {
MarketIdsForEdit::<T>::remove(market_id);
}

#[cfg(feature = "with-global-disputes")]
if T::GlobalDisputes::is_active(&market_id) {
T::GlobalDisputes::destroy_global_dispute(&market_id)?;
}
Expand Down Expand Up @@ -1453,7 +1451,10 @@ mod pallet {
ensure_signed(origin)?;

let market = <zrml_market_commons::Pallet<T>>::market(&market_id)?;
ensure!(market.status == MarketStatus::Disputed, Error::<T>::InvalidMarketStatus);
ensure!(
matches!(market.status, MarketStatus::Disputed | MarketStatus::Reported),
Error::<T>::InvalidMarketStatus
);

ensure!(
matches!(market.dispute_mechanism, MarketDisputeMechanism::Court),
Expand Down Expand Up @@ -1514,6 +1515,15 @@ mod pallet {
// ignore first of tuple because we always have max disputes
let (_, ids_len_2) = Self::clear_auto_resolve(&market_id)?;

if market.status == MarketStatus::Reported {
// this is the case that a dispute can not be initiated,
// because court has not enough juror and delegator stake (dispute errors)
<zrml_market_commons::Pallet<T>>::mutate_market(&market_id, |m| {
m.status = MarketStatus::Disputed;
Ok(())
})?;
}

// global disputes uses DisputeResolution API to control its resolution
let ids_len_1 =
T::GlobalDisputes::start_global_dispute(&market_id, initial_items.as_slice())?;
Expand Down
96 changes: 26 additions & 70 deletions zrml/prediction-markets/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ use zeitgeist_primitives::{
Moment, MultiHash, OutcomeReport, PoolStatus, ScalarPosition, ScoringRule,
},
};
use zrml_global_disputes::GlobalDisputesPalletApi;
use zrml_global_disputes::{
types::{OutcomeInfo, Possession},
GlobalDisputesPalletApi, Outcomes, PossessionOf,
};
use zrml_market_commons::MarketCommonsPalletApi;
use zrml_swaps::Pools;
const LIQUIDITY: u128 = 100 * BASE;
Expand Down Expand Up @@ -3447,7 +3450,6 @@ fn it_appeals_a_court_market_to_global_dispute() {
OutcomeReport::Categorical(0)
));

let dispute_block = report_at;
assert_ok!(PredictionMarkets::dispute(RuntimeOrigin::signed(CHARLIE), market_id,));

for _ in 0..(MaxAppeals::get() - 1) {
Expand All @@ -3472,87 +3474,41 @@ fn it_appeals_a_court_market_to_global_dispute() {
CError::<Runtime>::MaxAppealsReached
);

assert!(!GlobalDisputes::is_started(&market_id));
assert!(!GlobalDisputes::does_exist(&market_id));

assert_ok!(PredictionMarkets::start_global_dispute(RuntimeOrigin::signed(BOB), market_id));

let now = <frame_system::Pallet<Runtime>>::block_number();

assert!(GlobalDisputes::is_started(&market_id));
assert!(GlobalDisputes::does_exist(&market_id));
System::assert_last_event(Event::GlobalDisputeStarted(market_id).into());

#[cfg(feature = "with-global-disputes")]
{
use zrml_global_disputes::{
types::{OutcomeInfo, Possession},
GlobalDisputesPalletApi, Outcomes, PossessionOf,
};

let now = <frame_system::Pallet<Runtime>>::block_number();
assert_ok!(PredictionMarkets::start_global_dispute(
RuntimeOrigin::signed(CHARLIE),
market_id
));

// report check
let possession: PossessionOf<Runtime> = Possession::Shared {
owners: frame_support::BoundedVec::try_from(vec![BOB]).unwrap(),
};
let outcome_info = OutcomeInfo { outcome_sum: Zero::zero(), possession };
assert_eq!(
Outcomes::<Runtime>::get(market_id, &OutcomeReport::Categorical(0)).unwrap(),
outcome_info
);
let possession: PossessionOf<Runtime> = Possession::Shared {
owners: frame_support::BoundedVec::try_from(vec![CHARLIE]).unwrap(),
};
for i in 1..=<Runtime as Config>::MaxDisputes::get() {
let dispute_bond = crate::default_dispute_bond::<Runtime>((i - 1).into());
let outcome_info =
OutcomeInfo { outcome_sum: dispute_bond, possession: possession.clone() };
assert_eq!(
Outcomes::<Runtime>::get(
market_id,
&OutcomeReport::Categorical(i.saturated_into())
)
.unwrap(),
outcome_info
);
}

// remove_last_dispute_from_market_ids_per_dispute_block works
let removable_market_ids = MarketIdsPerDisputeBlock::<Runtime>::get(dispute_block);
assert_eq!(removable_market_ids.len(), 0);

let add_outcome_end = now + GlobalDisputes::get_add_outcome_period();
let vote_end = add_outcome_end + GlobalDisputes::get_vote_period();
let market_ids = MarketIdsPerDisputeBlock::<Runtime>::get(vote_end);
assert_eq!(market_ids, vec![market_id]);
assert!(GlobalDisputes::is_active(&market_id));
System::assert_last_event(Event::GlobalDisputeStarted(market_id).into());

assert_noop!(
PredictionMarkets::start_global_dispute(RuntimeOrigin::signed(CHARLIE), market_id),
Error::<Runtime>::GlobalDisputeExistsAlready
);
}

// remove_last_dispute_from_market_ids_per_dispute_block works
let removable_market_ids = MarketIdsPerDisputeBlock::<Runtime>::get(dispute_block);
assert_eq!(removable_market_ids.len(), 0);

let market_ids = MarketIdsPerDisputeBlock::<Runtime>::get(
now + <Runtime as Config>::GlobalDisputePeriod::get(),
// report check
let possession: PossessionOf<Runtime> =
Possession::Shared { owners: frame_support::BoundedVec::try_from(vec![BOB]).unwrap() };
let outcome_info = OutcomeInfo { outcome_sum: Zero::zero(), possession };
assert_eq!(
Outcomes::<Runtime>::get(market_id, &OutcomeReport::Categorical(0)).unwrap(),
outcome_info
);

let add_outcome_end = now + GlobalDisputes::get_add_outcome_period();
let vote_end = add_outcome_end + GlobalDisputes::get_vote_period();
let market_ids = MarketIdsPerDisputeBlock::<Runtime>::get(vote_end);
assert_eq!(market_ids, vec![market_id]);
assert!(GlobalDisputes::is_started(&market_id));
System::assert_last_event(Event::GlobalDisputeStarted(market_id).into());
assert!(GlobalDisputes::is_active(&market_id));

assert_noop!(
PredictionMarkets::start_global_dispute(RuntimeOrigin::signed(CHARLIE), market_id),
Error::<Runtime>::GlobalDisputeAlreadyStarted
Error::<Runtime>::GlobalDisputeExistsAlready
);
}
};
ExtBuilder::default().build().execute_with(|| {
test(Asset::Ztg);
});
#[cfg(feature = "parachain")]
ExtBuilder::default().build().execute_with(|| {
test(Asset::ForeignAsset(100));
});
}

Expand Down

0 comments on commit 77b8825

Please sign in to comment.