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

Impl RPCs to access Swap APIs #890

Merged
merged 6 commits into from
Dec 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
28 changes: 28 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ members = [
"runtimes/mainnet",
"runtimes/parachain",
"rpc/assets",
"rpc/swap",
"rpc/assets/runtime-api",
"pallets/pdex-migration",
"pallets/ocex",
Expand Down Expand Up @@ -69,6 +70,7 @@ default-members = [
"pallets/thea-executor",
"pallets/rewards/rpc",
"pallets/rewards/rpc/runtime-api",
"rpc/swap",
]

[workspace.dependencies]
Expand Down
2 changes: 2 additions & 0 deletions nodes/mainnet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ polkadex-client = { path = "../../client" }

thea = { path = "../../pallets/thea" }
pallet-ocex-lmp = { path = "../../pallets/ocex" }
swap-rpc = { path = "../../rpc/swap" }
# Substrate dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
Expand Down Expand Up @@ -80,6 +81,7 @@ sc-statement-store = { git = "https://github.com/paritytech/polkadot-sdk", branc
sp-statement-store = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-network-statement = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
pallet-asset-conversion-tx-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
pallet-asset-conversion = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
#Primitives
polkadex-primitives = { path = "../../primitives/polkadex" }
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
Expand Down
6 changes: 4 additions & 2 deletions nodes/mainnet/src/node_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use pallet_rewards_rpc::PolkadexRewardsRpc;
use grandpa::{
FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,
};
use polkadex_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index};
use polkadex_primitives::{AccountId, AssetId, Balance, Block, BlockNumber, Hash, Index};
use rpc_assets::{PolkadexAssetHandlerRpc, PolkadexAssetHandlerRpcApiServer};
use sc_client_api::{AuxStore, BlockchainEvents};
use sc_consensus_babe::BabeWorkerHandle;
Expand All @@ -53,6 +53,7 @@ use sp_consensus::SelectChain;
use sp_consensus_babe::BabeApi;
use sp_keystore::KeystorePtr;
use std::sync::Arc;
use swap_rpc::{PolkadexSwapRpc, PolkadexSwapRpcApiServer};

/// Extra dependencies for BABE.
pub struct BabeDeps {
Expand Down Expand Up @@ -122,6 +123,7 @@ where
C::Api: rpc_assets::PolkadexAssetHandlerRuntimeApi<Block, AccountId, Hash>,
C::Api: pallet_rewards_rpc::PolkadexRewardsRuntimeApi<Block, AccountId, Hash>,
C::Api: pallet_ocex_rpc::PolkadexOcexRuntimeApi<Block, AccountId, Hash>,
C::Api: pallet_asset_conversion::AssetConversionApi<Block, Balance, u128, AssetId>,
C: BlockchainEvents<Block>,
{
use pallet_ocex_rpc::PolkadexOcexRpcApiServer;
Expand Down Expand Up @@ -177,7 +179,7 @@ where
SyncState::new(chain_spec, client.clone(), shared_authority_set, babe_worker_handle)?
.into_rpc(),
)?;

io.merge(PolkadexSwapRpc::new(client.clone()).into_rpc())?;
// io.merge(StateMigration::new(client.clone(), backend, deny_unsafe).into_rpc())?;
io.merge(PolkadexAssetHandlerRpc::new(client.clone()).into_rpc())?;
io.merge(PolkadexRewardsRpc::new(client.clone()).into_rpc())?;
Expand Down
4 changes: 2 additions & 2 deletions pallets/liquidity/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ benchmarks! {
call.dispatch_bypass_filter(origin.clone())?;

//existential deposit
T::NativeCurrency::deposit_creating(
let _ = T::NativeCurrency::deposit_creating(
&main_account.clone(),
(10 * UNIT_BALANCE).saturated_into(),
);
Expand Down Expand Up @@ -104,7 +104,7 @@ benchmarks! {
call.dispatch_bypass_filter(origin.clone())?;

//existential deposit
T::NativeCurrency::deposit_creating(
let _ = T::NativeCurrency::deposit_creating(
&main_account.clone(),
(10 * UNIT_BALANCE).saturated_into(),
);
Expand Down
8 changes: 4 additions & 4 deletions pallets/rewards/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,13 @@ benchmarks! {
let pallet_id_account = pallet_rewards::<T>::get_pallet_account();

//set balance for pallet account
T::NativeCurrency::deposit_creating(
let _ = T::NativeCurrency::deposit_creating(
&pallet_id_account,
(10000000 * UNIT_BALANCE).saturated_into(),
);

//set existential balance for alice
T::NativeCurrency::deposit_creating(
let _ = T::NativeCurrency::deposit_creating(
&alice_account,
(10000000 * UNIT_BALANCE).saturated_into(),
);
Expand Down Expand Up @@ -111,13 +111,13 @@ benchmarks! {
let pallet_id_account = pallet_rewards::<T>::get_pallet_account();

//set balance for pallet account
T::NativeCurrency::deposit_creating(
let _ = T::NativeCurrency::deposit_creating(
&pallet_id_account,
(10000000 * UNIT_BALANCE).saturated_into(),
);

//set existential balance for alice
T::NativeCurrency::deposit_creating(
let _ = T::NativeCurrency::deposit_creating(
&alice_account,
(10000000 * UNIT_BALANCE).saturated_into(),
);
Expand Down
26 changes: 26 additions & 0 deletions rpc/swap/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "swap-rpc"
version = "5.4.1"
edition = "2021"

[dependencies]
tokio = { workspace = true }
serde = { workspace = true, default-features = true }
parity-scale-codec = { workspace = true, features = ["derive"] }
jsonrpsee = { workspace = true, features = ["client-core", "server", "macros"] }
sp-rpc = { workspace = true }
sp-blockchain = { workspace = true }
sp-api = { workspace = true }
sp-runtime = { workspace = true }
sp-core = { workspace = true }
orderbook-primitives = { path = "../../primitives/orderbook" }
serde_json = { workspace = true, default-features = true }
polkadex-primitives = { workspace = true }
sc-rpc-api = { workspace = true, default-features = true }
sc-rpc = { workspace = true, default-features = true }
sp-offchain = { workspace = true, default-features = true }
parking_lot = { workspace = true }
pallet-asset-conversion = { workspace = true, default-features = true }
hash-db = { workspace = true }
trie-db = { workspace = true }
sp-trie = { workspace = true }
131 changes: 131 additions & 0 deletions rpc/swap/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// This file is part of Polkadex.
//
// Copyright (c) 2023 Polkadex oü.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! This crate provides an RPC methods for OCEX pallet - balances state and onchain/offchain
//! recovery data.

use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
proc_macros::rpc,
tracing::log,
types::error::{CallError, ErrorObject},
};
pub use pallet_asset_conversion::AssetConversionApi;
use polkadex_primitives::AssetId;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::traits::Block as BlockT;
use std::sync::Arc;

const RUNTIME_ERROR: i32 = 1;

#[rpc(client, server)]
pub trait PolkadexSwapRpcApi<BlockHash> {
#[method(name = "tx_quotePriceExactTokensForTokens")]
async fn quote_price_exact_tokens_for_tokens(
&self,
asset_id1: String,
asset_id2: String,
amount: u128,
include_fee: bool,
) -> RpcResult<Option<u128>>;

#[method(name = "tx_quotePriceTokensForExactTokens")]
async fn quote_price_tokens_for_exact_tokens(
&self,
asset_id1: String,
asset_id2: String,
amount: u128,
include_fee: bool,
) -> RpcResult<Option<u128>>;
}

/// A structure that represents the Polkadex OCEX pallet RPC, which allows querying
/// individual balances and recovery state data.
///
/// # Type Parameters
///
/// * `Client`: The client API used to interact with the Substrate runtime.
/// * `Block`: The block type of the Substrate.
pub struct PolkadexSwapRpc<Client, Block> {
/// An `Arc` reference to the client API for accessing runtime functionality.
client: Arc<Client>,
/// A marker for the `Block` type parameter, used to ensure the struct
/// is covariant with respect to the block type.
_marker: std::marker::PhantomData<Block>,
}

impl<Client, Block> PolkadexSwapRpc<Client, Block> {
pub fn new(client: Arc<Client>) -> Self {
Self { client, _marker: Default::default() }
}
}

#[async_trait]
impl<Client, Block> PolkadexSwapRpcApiServer<<Block as BlockT>::Hash>
for PolkadexSwapRpc<Client, Block>
where
Block: BlockT,
Client: ProvideRuntimeApi<Block> + Send + Sync + 'static + HeaderBackend<Block>,
Client::Api: pallet_asset_conversion::AssetConversionApi<Block, u128, u128, AssetId>,
{
async fn quote_price_exact_tokens_for_tokens(
&self,
asset_id1: String,
asset_id2: String,
amount: u128,
include_fee: bool,
) -> RpcResult<Option<u128>> {
let api = self.client.runtime_api();
let at = self.client.info().best_hash;
let asset_id1: AssetId =
AssetId::try_from(asset_id1).map_err(runtime_error_into_rpc_err)?;
let asset_id2: AssetId =
AssetId::try_from(asset_id2).map_err(runtime_error_into_rpc_err)?;
let runtime_api_result = api
.quote_price_exact_tokens_for_tokens(at, asset_id1, asset_id2, amount, include_fee)
.map_err(runtime_error_into_rpc_err)?;
Ok(runtime_api_result)
}

async fn quote_price_tokens_for_exact_tokens(
&self,
asset_id1: String,
asset_id2: String,
amount: u128,
include_fee: bool,
) -> RpcResult<Option<u128>> {
let api = self.client.runtime_api();
let at = self.client.info().best_hash;
let asset_id1: AssetId =
AssetId::try_from(asset_id1).map_err(runtime_error_into_rpc_err)?;
let asset_id2: AssetId =
AssetId::try_from(asset_id2).map_err(runtime_error_into_rpc_err)?;
let runtime_api_result = api
.quote_price_tokens_for_exact_tokens(at, asset_id1, asset_id2, amount, include_fee)
.map_err(runtime_error_into_rpc_err)?;
Ok(runtime_api_result)
}
}

/// Converts a runtime trap into an RPC error.
fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> JsonRpseeError {
log::error!(target:"ocex","runtime rpc error: {:?} ",err);
CallError::Custom(ErrorObject::owned(RUNTIME_ERROR, "Runtime error", Some(format!("{err:?}"))))
.into()
}