Skip to content

Commit a9f2eef

Browse files
committed
add runtime api
1 parent f851f55 commit a9f2eef

File tree

5 files changed

+47
-39
lines changed

5 files changed

+47
-39
lines changed

pallets/hybrid-orderbook/ops/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ pub mod pallet {
156156
let pool_id = T::PoolLocator::pool_id(&asset1, &asset2)
157157
.map_err(|_| Error::<T>::InvalidAssetPair)?;
158158
let info = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolNotFound)?;
159+
let metadata = PoolMetadata::<T>::get(&pool_id).ok_or(Error::<T>::PoolNotFound)?;
159160

160161
let (prior_account, new_account) =
161162
Self::addresses(&pool_id).ok_or(Error::<T>::InvalidAssetPair)?;
@@ -165,7 +166,7 @@ pub mod pallet {
165166
// Assets that must be transferred to the new account id.
166167
let balance1 = T::Assets::total_balance(asset1.clone(), &prior_account);
167168
let balance2 = T::Assets::total_balance(asset2.clone(), &prior_account);
168-
let lp_balance = T::PoolAssets::total_balance(info.lp_token(), &prior_account);
169+
let lp_balance = T::PoolAssets::total_balance(metadata.lp_token(), &prior_account);
169170

170171
ensure!(!balance1.is_zero(), Error::<T>::ZeroBalance);
171172
ensure!(!balance2.is_zero(), Error::<T>::ZeroBalance);

pallets/hybrid-orderbook/src/lib.rs

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -237,18 +237,6 @@ pub mod pallet {
237237
#[pallet::storage]
238238
pub type NextPoolAssetId<T: Config> = StorageValue<_, T::PoolAssetId, OptionQuery>;
239239

240-
/// Stores the `Hold` assets for limit order
241-
#[pallet::storage]
242-
pub type FrozenAssets<T: Config> = StorageDoubleMap<
243-
_,
244-
Twox64Concat,
245-
T::AccountId,
246-
Twox64Concat,
247-
T::AssetKind,
248-
T::Unit,
249-
OptionQuery,
250-
>;
251-
252240
// Pallet's events.
253241
#[pallet::event]
254242
#[pallet::generate_deposit(pub(super) fn deposit_event)]
@@ -530,9 +518,10 @@ pub mod pallet {
530518
T::PoolAssets::touch(lp_token.clone(), &pool_account, &sender)?
531519
};
532520

533-
let pool = Pool::<T>::new(lp_token.clone(), taker_fee_rate, tick_size, lot_size);
534-
Pools::<T>::insert(pool_id.clone(), pool);
535-
521+
Pools::<T>::insert(
522+
pool_id.clone(),
523+
Pool::<T>::new(lp_token.clone(), taker_fee_rate, tick_size, lot_size),
524+
);
536525
Self::deposit_event(Event::PoolCreated {
537526
creator: sender,
538527
pool_id,
@@ -942,15 +931,11 @@ pub mod pallet {
942931
// quote asset would be released.
943932
let released = if is_bid { q } else { p * q };
944933
// 1. Release the frozen asset
945-
FrozenAssets::<T>::try_mutate(
946-
&owner,
934+
T::AssetsFreezer::decrease_frozen(
947935
asset1.clone(),
948-
|maybe_balance| -> DispatchResult {
949-
let mut new = maybe_balance.take().ok_or(Error::<T>::NoOps)?;
950-
new = new.saturating_sub(released);
951-
*maybe_balance = Some(new);
952-
Ok(())
953-
},
936+
&FreezeReason::LimitOrder.into(),
937+
&owner,
938+
released,
954939
)?;
955940
// 2. Transfer assets between orderer and owner of limit order
956941
let (transfer1, transfer2) = if is_bid { (q, released) } else { (released, q) };
@@ -1294,7 +1279,7 @@ pub mod pallet {
12941279
/// Pool price
12951280
///
12961281
/// 1 * quote_reserve / base_reserve
1297-
pub(crate) fn pool_price(
1282+
pub fn pool_price(
12981283
base_asset: &T::AssetKind,
12991284
quote_asset: &T::AssetKind,
13001285
) -> Result<T::Unit, Error<T>> {
@@ -2002,7 +1987,7 @@ pub mod pallet {
20021987
sp_api::decl_runtime_apis! {
20031988
/// This runtime api allows people to query the size of the liquidity pools
20041989
/// and quote prices for swaps.
2005-
pub trait AssetConversionApi<Balance, AssetId>
1990+
pub trait HybridOrderbookApi<Balance, AssetId>
20061991
where
20071992
Balance: frame_support::traits::tokens::Balance + MaybeDisplay,
20081993
AssetId: Codec,
@@ -2031,6 +2016,9 @@ sp_api::decl_runtime_apis! {
20312016

20322017
/// Returns the size of the liquidity pool for the given asset pair.
20332018
fn get_reserves(asset1: AssetId, asset2: AssetId) -> Option<(Balance, Balance)>;
2019+
2020+
/// Returns the price of the given asset pair.
2021+
fn get_pool_price(base: AssetId, quote: AssetId) -> Option<Balance>;
20342022
}
20352023
}
20362024

pallets/hybrid-orderbook/src/types.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,13 @@ impl OrderbookOrderId for OrderId {
9898

9999
fn new(is_bid: bool) -> Self {
100100
if is_bid {
101-
Self::start_ask_id()
102-
} else {
103101
Self::start_bid_id()
102+
} else {
103+
Self::start_ask_id()
104104
}
105105
}
106106

107-
fn checked_increase(&self, is_bid: bool) -> Option<Self> {
107+
fn checked_increase(&self) -> Option<Self> {
108108
self.increase_by_one()
109109
}
110110

@@ -188,7 +188,7 @@ pub trait OrderbookOrderId:
188188
/// Create new instance of `OrderId`
189189
fn new(is_bid: bool) -> Self;
190190
/// Increase `OrderId` by 1. Return `None`, if overflow
191-
fn checked_increase(&self, is_bid: bool) -> Option<Self>;
191+
fn checked_increase(&self) -> Option<Self>;
192192
/// Check whether it is id of `bid` order
193193
fn is_bid(&self) -> bool;
194194
}
@@ -283,7 +283,7 @@ impl<Quantity, Account: Clone, BlockNumber> Order<Quantity, Account, BlockNumber
283283
#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]
284284
#[scale_info(skip_type_params(T))]
285285
pub struct Pool<T: Config> {
286-
/// Liquidity pool asset
286+
/// Id of lp token
287287
pub lp_token: T::PoolAssetId,
288288
/// The orderbook of the bid.
289289
pub bids: T::OrderBook,
@@ -340,13 +340,13 @@ impl<T: Config> Pool<T> {
340340

341341
pub fn next_bid_order_id(&mut self) -> Result<OrderId, Error<T>> {
342342
let next = self.next_bid_order_id.clone();
343-
self.next_bid_order_id = next.checked_increase(true).ok_or(Error::<T>::Overflow)?;
343+
self.next_bid_order_id = next.checked_increase().ok_or(Error::<T>::Overflow)?;
344344
Ok(next)
345345
}
346346

347347
pub fn next_ask_order_id(&mut self) -> Result<OrderId, Error<T>> {
348348
let next = self.next_ask_order_id.clone();
349-
self.next_ask_order_id = next.checked_increase(false).ok_or(Error::<T>::Overflow)?;
349+
self.next_ask_order_id = next.checked_increase().ok_or(Error::<T>::Overflow)?;
350350
Ok(next)
351351
}
352352

runtime/src/apis.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
use alloc::vec::Vec;
2828
use frame_support::{
2929
genesis_builder_helper::{build_state, get_preset},
30+
traits::fungible::NativeOrWithId,
3031
weights::Weight,
3132
};
3233
use pallet_aura::Authorities;
@@ -42,9 +43,9 @@ use sp_version::RuntimeVersion;
4243

4344
// Local module imports
4445
use super::{
45-
AccountId, Balance, Block, ConsensusHook, Executive, InherentDataExt, Nonce, ParachainSystem,
46-
Runtime, RuntimeCall, RuntimeGenesisConfig, SessionKeys, System, TransactionPayment,
47-
SLOT_DURATION, VERSION,
46+
AccountId, Balance, Block, ConsensusHook, Executive, HybridOrderbook, InherentDataExt, Nonce,
47+
ParachainSystem, Runtime, RuntimeCall, RuntimeGenesisConfig, SessionKeys, System,
48+
TransactionPayment, SLOT_DURATION, VERSION,
4849
};
4950

5051
// we move some impls outside so we can easily use them with `docify`.
@@ -210,6 +211,24 @@ impl_runtime_apis! {
210211
}
211212
}
212213

214+
impl pallet_hybrid_orderbook::HybridOrderbookApi<Block, Balance, NativeOrWithId<u32>> for Runtime {
215+
fn quote_price_exact_tokens_for_tokens(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>, amount: Balance, include_fee: bool) -> Option<Balance> {
216+
HybridOrderbook::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee)
217+
}
218+
219+
fn quote_price_tokens_for_exact_tokens(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>, amount: Balance, include_fee: bool) -> Option<Balance> {
220+
HybridOrderbook::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee)
221+
}
222+
223+
fn get_reserves(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>) -> Option<(Balance, Balance)> {
224+
HybridOrderbook::get_reserves(&asset1, &asset2).ok()
225+
}
226+
227+
fn get_pool_price(base: NativeOrWithId<u32>, quote: NativeOrWithId<u32>) -> Option<Balance> {
228+
HybridOrderbook::pool_price(&base, &quote).ok()
229+
}
230+
}
231+
213232
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
214233
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
215234
ParachainSystem::collect_collation_info(header)

runtime/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ extern crate alloc;
1616
use alloc::vec::Vec;
1717
use smallvec::smallvec;
1818
use sp_runtime::{
19-
create_runtime_str, generic, impl_opaque_keys,
19+
generic, impl_opaque_keys,
2020
traits::{BlakeTwo256, IdentifyAccount, Verify},
2121
MultiSignature,
2222
};
@@ -159,8 +159,8 @@ impl_opaque_keys! {
159159

160160
#[sp_version::runtime_version]
161161
pub const VERSION: RuntimeVersion = RuntimeVersion {
162-
spec_name: create_runtime_str!("warpx-runtime"),
163-
impl_name: create_runtime_str!("warpx-runtime"),
162+
spec_name: alloc::borrow::Cow::Borrowed("warpx-runtime"),
163+
impl_name: alloc::borrow::Cow::Borrowed("warpx-runtime"),
164164
authoring_version: 1,
165165
spec_version: 1,
166166
impl_version: 0,

0 commit comments

Comments
 (0)