Skip to content

Commit

Permalink
Feature/0.6assets rpc (paritytech#259)
Browse files Browse the repository at this point in the history
* provide withdrawallog and state

* 0.6 all assets rpc

* provide withdrawal depost list rpc interface

* change listing to online in assets rpc

* fix compile err

* do not remove revoke token in asset_list
  • Loading branch information
Aton authored Jan 31, 2019
1 parent 0d946b6 commit c814bf3
Show file tree
Hide file tree
Showing 11 changed files with 238 additions and 169 deletions.
4 changes: 4 additions & 0 deletions rpc/src/chainx/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ error_chain! {
description("not yet implemented"),
display("Method Not Implemented"),
}
ChainErr {
description("Not has this chain id"),
display("Not has this chain id"),
}
/// Get certlist failed
CertNameErr {
description("Get cert name list failed"),
Expand Down
103 changes: 44 additions & 59 deletions rpc/src/chainx/impl_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,34 +61,28 @@ where

fn assets(&self, page_index: u32, page_size: u32) -> Result<Option<PageData<TotalAssetInfo>>> {
let b = self.best_number()?;
let tokens: Result<Vec<Token>> = self
let assets: Result<Vec<(Asset, bool)>> = self
.client
.runtime_api()
.valid_assets(&b)
.all_assets(&b)
.map_err(|e| e.into());
let tokens = tokens?;
let assets = assets?;

let state = self.best_state()?;

let mut assets = Vec::new();
let mut all_assets = Vec::new();

for token in tokens.into_iter() {
for (asset, valid) in assets.into_iter() {
let mut bmap = BTreeMap::<AssetType, Balance>::from_iter(
xassets::AssetType::iterator().map(|t| (*t, Zero::zero())),
);

let key = <xassets::TotalAssetBalance<Runtime>>::key_for(token.as_ref());
let key = <xassets::TotalAssetBalance<Runtime>>::key_for(asset.token().as_ref());
if let Some(info) = Self::pickout::<CodecBTreeMap<AssetType, Balance>>(&state, &key)? {
bmap.extend(info.0.iter());
}

let asset = match Self::get_asset(&state, &token)? {
Some(info) => info,
None => unreachable!("should not reach this branch, the token info must be exists"),
};

// PCX free balance
if token.as_slice() == xassets::Module::<Runtime>::TOKEN {
if asset.token().as_slice() == xassets::Module::<Runtime>::TOKEN {
let key = <balances::TotalIssuance<Runtime>>::key();
let total_issue = Self::pickout::<Balance>(&state, &key)?.unwrap_or(Zero::zero());
let other_total: Balance = bmap
Expand All @@ -99,7 +93,7 @@ where
bmap.insert(xassets::AssetType::Free, free_issue);
}
let mut trustee_addr = String::default();
if token.as_slice() == xbitcoin::Module::<Runtime>::TOKEN {
if asset.token().as_slice() == xbitcoin::Module::<Runtime>::TOKEN {
let key = <xaccounts::TrusteeAddress<Runtime>>::key_for(xassets::Chain::Bitcoin);
match Self::pickout::<xaccounts::TrusteeAddressPair>(&state, &key)? {
Some(a) => {
Expand All @@ -111,14 +105,15 @@ where
};
}

assets.push(TotalAssetInfo::new(
all_assets.push(TotalAssetInfo::new(
asset,
valid,
trustee_addr,
CodecBTreeMap(bmap),
));
}

into_pagedata(assets, page_index, page_size)
into_pagedata(all_assets, page_index, page_size)
}

fn verify_addr(&self, token: String, addr: String, memo: String) -> Result<Option<String>> {
Expand Down Expand Up @@ -160,62 +155,52 @@ where
.map_err(|e| e.into())
}

fn withdrawal_list(
fn deposit_list(
&self,
chain: String,
page_index: u32,
page_size: u32,
) -> Result<Option<PageData<ApplicationWrapper>>> {
let mut v = vec![];
) -> Result<Option<PageData<DepositLog>>> {
let c = serde_json::from_str::<Chain>(chain.as_str()).map_err(|_| ChainErr)?;

let best_number = self.best_number()?;
let state = self.best_state()?;
for c in xassets::Chain::iterator() {
let list: Result<Vec<xrecords::Application<AccountId, Balance, Timestamp>>> = self
.client
.runtime_api()
.withdrawal_list_of(&best_number, *c)
.map_err(|e| e.into());

let list = list?;
let applications = Self::get_applications_with_state(&state, list)?;
v.extend(applications);
match c {
Chain::Bitcoin => {
let list = vec![];
// let list: Result<Vec<xrecords::Application<AccountId, Balance, Timestamp>>> = self
// .client
// .runtime_api()
// .withdrawal_list(&best_number, *c)
// .map_err(|e| e.into());
into_pagedata(list, page_index, page_size)
}
_ => return Ok(None),
}

into_pagedata(v, page_index, page_size)
}

fn withdrawal_list_of(
fn withdrawal_list(
&self,
who: AccountId,
chain: String,
page_index: u32,
page_size: u32,
) -> Result<Option<PageData<ApplicationWrapper>>> {
let mut v = vec![];
let b = self.best_number()?;
for c in xassets::Chain::iterator() {
let list: Result<Vec<xrecords::Application<AccountId, Balance, Timestamp>>> = self
.client
.runtime_api()
.withdrawal_list_of(&b, *c)
.map_err(|e| e.into());
let list = list?;
v.extend(list);
}

// let mut handle = BTreeMap::<Chain, Vec<u32>>::new();
// // btc
// let key = xbitcoin::TxProposal::<Runtime>::key();
// let ids = match Self::pickout::<xbitcoin::CandidateTx>(&state, &key)? {
// Some(candidate_tx) => candidate_tx.outs,
// None => vec![],
// };
// handle.insert(Chain::Bitcoin, ids);

let v = v.into_iter().filter(|r| r.applicant() == who).collect();
) -> Result<Option<PageData<WithdrawalLog>>> {
let c = serde_json::from_str::<Chain>(chain.as_str()).map_err(|_| ChainErr)?;

let best_number = self.best_number()?;
let state = self.best_state()?;
let applications = Self::get_applications_with_state(&state, v)?;

into_pagedata(applications, page_index, page_size)
match c {
Chain::Bitcoin => {
let list = vec![];
// let list: Result<Vec<xrecords::Application<AccountId, Balance, Timestamp>>> = self
// .client
// .runtime_api()
// .withdrawal_list(&best_number, *c)
// .map_err(|e| e.into());
into_pagedata(list, page_index, page_size)
}
_ => return Ok(None),
}
}

fn nomination_records(
Expand Down
116 changes: 59 additions & 57 deletions rpc/src/chainx/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use xr_primitives::generic::b58;
use xaccounts::{self, IntentionProps};
use xassets::{self, Asset, AssetType, Chain, Token};
use xbitcoin::{self, BestIndex, BlockHeaderFor, BlockHeaderInfo, IrrBlock, TxFor, TxInfo};
use xrecords::{self, Application};
use xrecords::{self, Application, types::{DepositLog as DL, WithdrawalLog as WL}};
use xspot::def::{OrderPair, OrderPairID, ID};
use xspot::{HandicapT, OrderT};
use xstaking::{self, IntentionProfs};
Expand All @@ -43,14 +43,16 @@ pub mod types;

use self::error::Result;
use self::types::{
ApplicationWrapper, AssetInfo, DepositInfo, IntentionInfo, NominationRecord, PageData,
PairInfo, PseduIntentionInfo, PseduNominationRecord, QuotationsList, TotalAssetInfo,
WithdrawalState,
AssetInfo, DepositInfo, IntentionInfo, NominationRecord, PageData, PairInfo,
PseduIntentionInfo, PseduNominationRecord, QuotationsList, TotalAssetInfo,
};
use chainx::error::ErrorKind::{OrderPairIDErr, PageIndexErr, PageSizeErr, QuotationssPieceErr};
use chainx::error::ErrorKind::*;

const MAX_PAGE_SIZE: u32 = 100;

type WithdrawalLog = WL<AccountId, Balance, Timestamp>;
type DepositLog = DL<AccountId, Balance, Timestamp>;

build_rpc_trait! {
/// ChainX API
pub trait ChainXApi<Number, AccountId, Balance, BlockNumber> where SignedBlock: Serialize, {
Expand All @@ -71,11 +73,11 @@ build_rpc_trait! {
#[rpc(name = "chainx_getMinimalWithdrawalValueByToken")]
fn minimal_withdrawal_value(&self, String) -> Result<Option<Balance>>;

#[rpc(name = "chainx_getWithdrawalList")]
fn withdrawal_list(&self, u32, u32) -> Result<Option<PageData<ApplicationWrapper>>>;
#[rpc(name = "chainx_getDepositList")]
fn deposit_list(&self, String, u32, u32) -> Result<Option<PageData<DepositLog>>>;

#[rpc(name = "chainx_getWithdrawalListByAccount")]
fn withdrawal_list_of(&self, AccountId, u32, u32) -> Result<Option<PageData<ApplicationWrapper>>>;
#[rpc(name = "chainx_getWithdrawalList")]
fn withdrawal_list(&self, String, u32, u32) -> Result<Option<PageData<WithdrawalLog>>>;

#[rpc(name = "chainx_getNominationRecords")]
fn nomination_records(&self, AccountId) -> Result<Option<Vec<(AccountId, NominationRecord)>>>;
Expand Down Expand Up @@ -173,52 +175,52 @@ where
.unwrap_or(None))
}

fn get_asset(
state: &<B as client::backend::Backend<Block, Blake2Hasher>>::State,
token: &Token,
) -> Result<Option<Asset>> {
let key = <xassets::AssetInfo<Runtime>>::key_for(token);
match Self::pickout::<(Asset, bool, BlockNumber)>(&state, &key)? {
Some((info, _, _)) => Ok(Some(info)),
None => Ok(None),
}
}

fn get_applications_with_state(
state: &<B as client::backend::Backend<Block, Blake2Hasher>>::State,
v: Vec<Application<AccountId, Balance, Timestamp>>,
) -> Result<Vec<ApplicationWrapper>> {
// todo change to runtime?
let mut handle = BTreeMap::<Chain, Vec<u32>>::new();
// btc
let key = xbitcoin::TxProposal::<Runtime>::key();
let ids = match Self::pickout::<xbitcoin::CandidateTx>(&state, &key)? {
Some(candidate_tx) => candidate_tx.outs,
None => vec![],
};
handle.insert(Chain::Bitcoin, ids);

let mut applications = vec![];
for appl in v {
let index = appl.id();
let token = appl.token();

let state = if let Some(info) = Self::get_asset(state, &token)? {
match handle.get(&info.chain()) {
Some(list) => {
if list.contains(&index) {
WithdrawalState::Signing
} else {
WithdrawalState::Applying
}
}
None => WithdrawalState::Unknown,
}
} else {
unreachable!("should not reach this branch, the token info must be exists");
};
applications.push(ApplicationWrapper::new(appl, state));
}
Ok(applications)
}
// fn get_asset(
// state: &<B as client::backend::Backend<Block, Blake2Hasher>>::State,
// token: &Token,
// ) -> Result<Option<Asset>> {
// let key = <xassets::AssetInfo<Runtime>>::key_for(token);
// match Self::pickout::<(Asset, bool, BlockNumber)>(&state, &key)? {
// Some((info, _, _)) => Ok(Some(info)),
// None => Ok(None),
// }
// }

// fn get_applications_with_state(
// state: &<B as client::backend::Backend<Block, Blake2Hasher>>::State,
// v: Vec<Application<AccountId, Balance, Timestamp>>,
// ) -> Result<Vec<ApplicationWrapper>> {
// // todo change to runtime?
// let mut handle = BTreeMap::<Chain, Vec<u32>>::new();
// // btc
// let key = xbitcoin::TxProposal::<Runtime>::key();
// let ids = match Self::pickout::<xbitcoin::CandidateTx>(&state, &key)? {
// Some(candidate_tx) => candidate_tx.outs,
// None => vec![],
// };
// handle.insert(Chain::Bitcoin, ids);
//
// let mut applications = vec![];
// for appl in v {
// let index = appl.id();
// let token = appl.token();
//
// let state = if let Some(info) = Self::get_asset(state, &token)? {
// match handle.get(&info.chain()) {
// Some(list) => {
// if list.contains(&index) {
// WithdrawalState::Signing
// } else {
// WithdrawalState::Applying
// }
// }
// None => WithdrawalState::Unknown,
// }
// } else {
// unreachable!("should not reach this branch, the token info must be exists");
// };
// applications.push(ApplicationWrapper::new(appl, state));
// }
// Ok(applications)
// }
}
Loading

0 comments on commit c814bf3

Please sign in to comment.