Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement automatic on-chain arbitrage #833

Merged
merged 89 commits into from
Nov 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
c1f4c26
wip
maltekliemann Oct 4, 2022
0317c94
wip
maltekliemann Oct 6, 2022
0f0e116
wip
maltekliemann Oct 6, 2022
0b80a79
.
maltekliemann Oct 6, 2022
5f1383c
wip
maltekliemann Oct 7, 2022
5739c8b
wip
maltekliemann Oct 7, 2022
1cfaf6b
wip
maltekliemann Oct 7, 2022
fe8ee05
wip
maltekliemann Oct 7, 2022
f8e7ef0
wip
maltekliemann Oct 7, 2022
067ae74
wip
maltekliemann Oct 9, 2022
8f3a6fa
wip
maltekliemann Oct 9, 2022
e651235
wip
maltekliemann Oct 9, 2022
2161dc1
wip
maltekliemann Oct 9, 2022
afadecc
wip
maltekliemann Oct 9, 2022
7b84e95
wip
maltekliemann Oct 9, 2022
a8b591b
wip
maltekliemann Oct 10, 2022
99beec1
add root tests
maltekliemann Oct 10, 2022
bb2a90c
Add more tests for root
maltekliemann Oct 10, 2022
a5f23f9
Add more tests for root
maltekliemann Oct 10, 2022
332ec8a
clean up
maltekliemann Oct 10, 2022
e6bcfcb
calc_total_spot_price_tests
maltekliemann Oct 10, 2022
82b9fcd
Add more tests
maltekliemann Oct 10, 2022
ee2cec3
wip
maltekliemann Oct 10, 2022
b028447
.
maltekliemann Oct 10, 2022
912e299
.
maltekliemann Oct 10, 2022
54b7faa
.
maltekliemann Oct 10, 2022
d91e024
.
maltekliemann Oct 10, 2022
57956bd
.
maltekliemann Oct 11, 2022
bfafc41
wip
maltekliemann Oct 11, 2022
3dc0400
Remove println
maltekliemann Oct 11, 2022
ea0460f
.
maltekliemann Oct 11, 2022
a30e73e
Merge branch 'main' into mkl-arbitrage
maltekliemann Oct 11, 2022
e3f313c
Remove TODOs
maltekliemann Oct 11, 2022
ac6b77d
.
maltekliemann Oct 12, 2022
d4f9aba
Do dependency injection of `max_iterations`
maltekliemann Oct 12, 2022
86bda4f
Complete benchmarks
maltekliemann Oct 12, 2022
8869a1b
Remove `println!`
maltekliemann Oct 12, 2022
a9b80e6
Clean up benchmarks
maltekliemann Oct 12, 2022
1b8d215
Finish benchmarks
maltekliemann Oct 12, 2022
4775c9e
Reduce size of minimum weight
maltekliemann Oct 12, 2022
d931dde
Merge branch 'main' into mkl-arbitrage
maltekliemann Oct 12, 2022
8f19527
`cargo fmt`
maltekliemann Oct 12, 2022
1aa52f3
Fix clippy issues
maltekliemann Oct 13, 2022
cf1a030
Change `Hasher` of arbitrage cache
maltekliemann Oct 13, 2022
1a9346a
More clippy fixes
maltekliemann Oct 13, 2022
71f32d1
Remove outdated TODO
maltekliemann Oct 14, 2022
d693094
Change hasher of cache
maltekliemann Oct 14, 2022
93d23a5
Remove `MIN_ARBITRAGE_WEIGHT`
maltekliemann Oct 14, 2022
423e311
Correctly mimic buy/sell complete set ops
maltekliemann Oct 14, 2022
f7e39f4
Fix formatting
maltekliemann Oct 14, 2022
e0d3e4a
Add `market_account` to `market-commons`
maltekliemann Oct 14, 2022
fac643c
Fix benchmark
maltekliemann Oct 14, 2022
b87401f
Fix benchmarks some more
maltekliemann Oct 14, 2022
c08905d
Add missing changelog
maltekliemann Oct 15, 2022
2a619b2
Remove `market_account` from `prediction-markets`
maltekliemann Oct 15, 2022
428dfe2
Update changelog
maltekliemann Oct 15, 2022
f23b2d5
Add a better solution for enforcing pool limit
maltekliemann Oct 20, 2022
fe36c49
Revert hasher to `Twox64Concat`
maltekliemann Oct 21, 2022
2519a67
Update zrml/swaps/src/benchmarks.rs
maltekliemann Oct 21, 2022
ac928b0
Merge branch 'main' into mkl-arbitrage
maltekliemann Oct 21, 2022
93fad1b
Merge branch 'mkl-arbitrage' of github.com:zeitgeistpm/zeitgeist into…
maltekliemann Oct 21, 2022
73e538c
Merge branch 'main' into mkl-arbitrage
maltekliemann Oct 21, 2022
f8d3dd0
Fix benchmarks
maltekliemann Oct 21, 2022
7ef6720
Merge branch 'main' into mkl-arbitrage
maltekliemann Oct 21, 2022
799e42d
Add comment explaining a test
maltekliemann Oct 25, 2022
be1411b
Use variable for the base asset
maltekliemann Oct 25, 2022
11f3179
Replace `is_err` with explicit `assert_eq`
maltekliemann Oct 25, 2022
3c66f96
Replace `is_err` with explicit `assert_eq`
maltekliemann Oct 25, 2022
4eb68e9
Remove TODO
maltekliemann Oct 25, 2022
d8c913f
Remove `iteration_count` parameter from benchmarks
maltekliemann Oct 25, 2022
f561e20
`cargo fmt`
maltekliemann Oct 25, 2022
5ffcd40
Fix `WeightInfo` invocation
maltekliemann Oct 25, 2022
57ba9d5
Fix clippy issues
maltekliemann Oct 25, 2022
dacdc7a
Merge branch 'main' into mkl-arbitrage
maltekliemann Oct 26, 2022
baf9667
Update zrml/swaps/src/arbitrage.rs
maltekliemann Oct 26, 2022
7806f21
correct review suggestion comment
Chralt98 Oct 27, 2022
064b2d3
Default to min on low volume domains
maltekliemann Oct 27, 2022
857e2af
Fix doc string formatting
maltekliemann Oct 27, 2022
0a16914
Fix clippy errors
maltekliemann Oct 27, 2022
cc5e0a7
Merge branch 'main' into mkl-arbitrage
maltekliemann Nov 3, 2022
e5c08a8
Merge branch 'main' into mkl-arbitrage
maltekliemann Nov 7, 2022
8e2b003
Merge branch 'main' into mkl-arbitrage
maltekliemann Nov 17, 2022
064d467
Apply suggestions from code review
maltekliemann Nov 17, 2022
4c17ca9
Add module docstrings
maltekliemann Nov 17, 2022
dd335f9
Add missing docstrings
maltekliemann Nov 17, 2022
a199e40
Merge branch 'mkl-arbitrage' of github.com:zeitgeistpm/zeitgeist into…
maltekliemann Nov 17, 2022
e24c62e
Update `zrml_market_commons` mock
maltekliemann Nov 17, 2022
728dc7c
Fix formatting
maltekliemann Nov 17, 2022
8d02820
Ensure that min balance is observed by arbitrage
maltekliemann Nov 17, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/changelog_for_devs.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# v0.3.7

- Added on-chain arbitrage. See
[ZIP-1](https://hackmd.io/@1ypDLjlbQ_e2Gp_1EW7kkg/BksyTQc-o) for details. When
a pool is arbitraged, we emit one of the following events:
`ArbitrageMintSell(pool_id, amount)`, `ArbitrageBuyBurn(pool_id, amount)` or
`ArbitrageSkipped(pool_id)`. The latter can be safely ignored by the indexer.
The `amount` parameter signifies the amount of funds moved into or out of the
prize pool (mint-sell/buy-burn resp.) and the amount of full sets
minted/burned. Note that in addition to these events, the low-level
`tokens.Deposited` and `tokens.Transfer` events are also emitted.
- Added new pallet: GlobalDisputes. Dispatchable calls are:
- `add_vote_outcome` - Add voting outcome to a global dispute in exchange for
a constant fee. Errors if the voting outcome already exists or if the global
Expand Down
2 changes: 1 addition & 1 deletion runtime/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,7 @@ macro_rules! impl_config_traits {
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down Expand Up @@ -1026,7 +1027,6 @@ macro_rules! impl_config_traits {
type LiquidityMining = NoopLiquidityMining;
// type LiquidityMining = LiquidityMining;
type MarketCommons = MarketCommons;
type MarketId = MarketId;
type MinAssets = MinAssets;
type MaxAssets = MaxAssets;
type MaxInRatio = MaxInRatio;
Expand Down
5 changes: 4 additions & 1 deletion zrml/authorized/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
};
use zeitgeist_primitives::{
constants::mock::{AuthorizedPalletId, BlockHashCount, MaxReserves, MinimumPeriod, BASE},
constants::mock::{
AuthorizedPalletId, BlockHashCount, MaxReserves, MinimumPeriod, PmPalletId, BASE,
},
types::{
AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment,
UncheckedExtrinsicTest,
Expand Down Expand Up @@ -106,6 +108,7 @@ impl pallet_balances::Config for Runtime {
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down
5 changes: 3 additions & 2 deletions zrml/court/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use sp_runtime::{
};
use zeitgeist_primitives::{
constants::mock::{
BlockHashCount, CourtCaseDuration, CourtPalletId, MaxReserves, MinimumPeriod, StakeWeight,
BASE,
BlockHashCount, CourtCaseDuration, CourtPalletId, MaxReserves, MinimumPeriod, PmPalletId,
StakeWeight, BASE,
},
types::{
AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment,
Expand Down Expand Up @@ -114,6 +114,7 @@ impl pallet_randomness_collective_flip::Config for Runtime {}
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down
3 changes: 2 additions & 1 deletion zrml/global-disputes/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use sp_runtime::{
use zeitgeist_primitives::{
constants::mock::{
BlockHashCount, GlobalDisputeLockId, GlobalDisputesPalletId, MaxReserves,
MinOutcomeVoteAmount, MinimumPeriod, RemoveKeysLimit, VotingOutcomeFee, BASE,
MinOutcomeVoteAmount, MinimumPeriod, PmPalletId, RemoveKeysLimit, VotingOutcomeFee, BASE,
},
types::{
AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment,
Expand Down Expand Up @@ -124,6 +124,7 @@ impl pallet_timestamp::Config for Runtime {
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down
3 changes: 2 additions & 1 deletion zrml/liquidity-mining/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use sp_runtime::{
use zeitgeist_primitives::{
constants::mock::{
BlockHashCount, ExistentialDeposit, LiquidityMiningPalletId, MaxLocks, MaxReserves,
MinimumPeriod, BASE,
MinimumPeriod, PmPalletId, BASE,
},
types::{
AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment,
Expand Down Expand Up @@ -105,6 +105,7 @@ impl pallet_balances::Config for Runtime {
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down
23 changes: 19 additions & 4 deletions zrml/market-commons/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ mod pallet {
ensure,
pallet_prelude::{StorageMap, StorageValue, ValueQuery},
storage::PrefixIterator,
traits::{Hooks, NamedReservableCurrency, StorageVersion, Time},
Blake2_128Concat, Parameter,
traits::{Get, Hooks, NamedReservableCurrency, StorageVersion, Time},
Blake2_128Concat, PalletId, Parameter,
};
use parity_scale_codec::MaxEncodedLen;
use sp_runtime::{
traits::{AtLeast32Bit, CheckedAdd, MaybeSerializeDeserialize, Member, Saturating},
ArithmeticError, DispatchError,
traits::{
AccountIdConversion, AtLeast32Bit, CheckedAdd, MaybeSerializeDeserialize, Member,
Saturating,
},
ArithmeticError, DispatchError, SaturatedConversion,
};
use zeitgeist_primitives::types::{Market, PoolId};

Expand Down Expand Up @@ -71,6 +74,11 @@ mod pallet {
+ Member
+ Parameter;

// TODO(#837): Remove when on-chain arbitrage is removed!
/// The prefix used to calculate the prize pool accounts.
#[pallet::constant]
type PredictionMarketsPalletId: Get<PalletId>;

/// Time tracker
type Timestamp: Time<Moment = u64>;
}
Expand Down Expand Up @@ -182,6 +190,13 @@ mod pallet {
Ok(())
}

// TODO(#837): Remove when on-chain arbitrage is removed!
#[inline]
fn market_account(market_id: Self::MarketId) -> Self::AccountId {
T::PredictionMarketsPalletId::get()
.into_sub_account_truncating(market_id.saturated_into::<u128>())
}

// MarketPool

fn insert_market_pool(market_id: Self::MarketId, pool_id: PoolId) -> DispatchResult {
Expand Down
3 changes: 3 additions & 0 deletions zrml/market-commons/src/market_commons_pallet_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ pub trait MarketCommonsPalletApi {
/// Removes a market from the storage.
fn remove_market(market_id: &Self::MarketId) -> DispatchResult;

/// Return the account id of a market's prize pool.
fn market_account(market_id: Self::MarketId) -> Self::AccountId;

// MarketPool

/// Connects a pool identified by `pool_id` to a market identified by `market_id`.
Expand Down
3 changes: 2 additions & 1 deletion zrml/market-commons/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
};
use zeitgeist_primitives::{
constants::mock::{BlockHashCount, MaxReserves, MinimumPeriod},
constants::mock::{BlockHashCount, MaxReserves, MinimumPeriod, PmPalletId},
types::{
AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment,
UncheckedExtrinsicTest,
Expand All @@ -48,6 +48,7 @@ construct_runtime!(
impl crate::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down
19 changes: 7 additions & 12 deletions zrml/prediction-markets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ mod pallet {
use orml_traits::{MultiCurrency, NamedMultiReservableCurrency};
use sp_arithmetic::per_things::{Perbill, Percent};
use sp_runtime::{
traits::{AccountIdConversion, CheckedDiv, Saturating, Zero},
traits::{CheckedDiv, Saturating, Zero},
DispatchError, DispatchResult, SaturatedConversion,
};
use zeitgeist_primitives::{
Expand Down Expand Up @@ -125,7 +125,7 @@ mod pallet {
let market = T::MarketCommons::market(&market_id)?;
ensure!(market.scoring_rule == ScoringRule::CPMM, Error::<T>::InvalidScoringRule);
let market_status = market.status;
let market_account = Self::market_account(market_id);
let market_account = T::MarketCommons::market_account(market_id);

// Slash outstanding bonds; see
// https://github.com/zeitgeistpm/runtime-audit-1/issues/34#issuecomment-1120187097 for
Expand Down Expand Up @@ -637,7 +637,7 @@ mod pallet {
}

let market_id = T::MarketCommons::push_market(market.clone())?;
let market_account = Self::market_account(market_id);
let market_account = T::MarketCommons::market_account(market_id);
let mut extra_weight = 0;

if market.status == MarketStatus::CollectingSubsidy {
Expand Down Expand Up @@ -912,7 +912,7 @@ mod pallet {
let sender = ensure_signed(origin)?;

let market = T::MarketCommons::market(&market_id)?;
let market_account = Self::market_account(market_id);
let market_account = T::MarketCommons::market_account(market_id);

ensure!(market.status == MarketStatus::Resolved, Error::<T>::MarketIsNotResolved);

Expand Down Expand Up @@ -1189,7 +1189,7 @@ mod pallet {
ensure!(market.scoring_rule == ScoringRule::CPMM, Error::<T>::InvalidScoringRule);
Self::ensure_market_is_active(&market)?;

let market_account = Self::market_account(market_id);
let market_account = T::MarketCommons::market_account(market_id);
ensure!(
T::AssetManager::free_balance(Asset::Ztg, &market_account) >= amount,
"Market account does not have sufficient reserves.",
Expand Down Expand Up @@ -1870,11 +1870,6 @@ mod pallet {
}
}

#[inline]
pub(crate) fn market_account(market_id: MarketIdOf<T>) -> T::AccountId {
T::PalletId::get().into_sub_account_truncating(market_id.saturated_into::<u128>())
}

fn insert_auto_close(market_id: &MarketIdOf<T>) -> Result<u32, DispatchError> {
let market = T::MarketCommons::market(market_id)?;

Expand Down Expand Up @@ -2008,7 +2003,7 @@ mod pallet {
ensure!(market.scoring_rule == ScoringRule::CPMM, Error::<T>::InvalidScoringRule);
Self::ensure_market_is_active(&market)?;

let market_account = Self::market_account(market_id);
let market_account = T::MarketCommons::market_account(market_id);
T::AssetManager::transfer(Asset::Ztg, &who, &market_account, amount)?;

let assets = Self::outcome_assets(market_id, &market);
Expand Down Expand Up @@ -2729,7 +2724,7 @@ mod pallet {
} else {
return Ok(T::DbWeight::get().reads(1));
};
let market_account = Self::market_account(*market_id);
let market_account = T::MarketCommons::market_account(*market_id);
let weight = T::Swaps::clean_up_pool(
&market.market_type,
pool_id,
Expand Down
2 changes: 1 addition & 1 deletion zrml/prediction-markets/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ impl zrml_liquidity_mining::Config for Runtime {
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down Expand Up @@ -331,7 +332,6 @@ impl zrml_swaps::Config for Runtime {
type FixedTypeS = <Runtime as zrml_rikiddo::Config>::FixedTypeS;
type LiquidityMining = LiquidityMining;
type MarketCommons = MarketCommons;
type MarketId = MarketId;
type MaxAssets = MaxAssets;
type MaxInRatio = MaxInRatio;
type MaxOutRatio = MaxOutRatio;
Expand Down
8 changes: 4 additions & 4 deletions zrml/prediction-markets/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ fn admin_destroy_market_correctly_cleans_up_accounts() {
let market_id = 0;
let pool_id = 0;
let pool_account = Swaps::pool_account_id(&pool_id);
let market_account = PredictionMarkets::market_account(market_id);
let market_account = MarketCommons::market_account(market_id);
let alice_ztg_before = AssetManager::free_balance(Asset::Ztg, &ALICE);
assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0));
assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &pool_account), 0);
Expand Down Expand Up @@ -824,7 +824,7 @@ fn create_categorical_market_deposits_the_correct_event() {
simple_create_categorical_market(MarketCreation::Permissionless, 1..2, ScoringRule::CPMM);
let market_id = 0;
let market = MarketCommons::market(&market_id).unwrap();
let market_account = PredictionMarkets::market_account(market_id);
let market_account = MarketCommons::market_account(market_id);
System::assert_last_event(Event::MarketCreated(0, market_account, market).into());
});
}
Expand All @@ -836,7 +836,7 @@ fn create_scalar_market_deposits_the_correct_event() {
simple_create_scalar_market(MarketCreation::Permissionless, 1..2, ScoringRule::CPMM);
let market_id = 0;
let market = MarketCommons::market(&market_id).unwrap();
let market_account = PredictionMarkets::market_account(market_id);
let market_account = MarketCommons::market_account(market_id);
System::assert_last_event(Event::MarketCreated(0, market_account, market).into());
});
}
Expand Down Expand Up @@ -1530,7 +1530,7 @@ fn it_allows_to_buy_a_complete_set() {
let bal = Balances::free_balance(&BOB);
assert_eq!(bal, 1_000 * BASE - CENT);

let market_account = PredictionMarkets::market_account(0);
let market_account = MarketCommons::market_account(0);
let market_bal = Balances::free_balance(market_account);
assert_eq!(market_bal, CENT);
System::assert_last_event(Event::BoughtCompleteSet(0, CENT, BOB).into());
Expand Down
5 changes: 4 additions & 1 deletion zrml/simple-disputes/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
};
use zeitgeist_primitives::{
constants::mock::{BlockHashCount, MaxReserves, MinimumPeriod, SimpleDisputesPalletId},
constants::mock::{
BlockHashCount, MaxReserves, MinimumPeriod, PmPalletId, SimpleDisputesPalletId,
},
types::{
AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment,
UncheckedExtrinsicTest,
Expand Down Expand Up @@ -94,6 +96,7 @@ impl pallet_balances::Config for Runtime {
impl zrml_market_commons::Config for Runtime {
type Currency = Balances;
type MarketId = MarketId;
type PredictionMarketsPalletId = PmPalletId;
type Timestamp = Timestamp;
}

Expand Down
Loading