Skip to content

Commit

Permalink
fix: call multiaddr BlockChainInfo API to query balance for BTC, add …
Browse files Browse the repository at this point in the history
…new ts-tests for it with bumped vc-jsonschema version
  • Loading branch information
higherordertech authored and higherordertech committed May 1, 2024
1 parent b0b7a90 commit 2556fd1
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 28 deletions.
6 changes: 4 additions & 2 deletions tee-worker/litentry/core/credentials/src/credential_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ pub fn get_schema_url(assertion: &Assertion) -> String {

Assertion::LITStaking => format!("{BASE_URL}/17-token-holding-amount/1-1-0.json"),

Assertion::TokenHoldingAmount(_) | Assertion::EVMAmountHolding(_) =>
format!("{BASE_URL}/21-evm-holding-amount/1-1-0.json"),
Assertion::EVMAmountHolding(_) => format!("{BASE_URL}/21-evm-holding-amount/1-1-0.json"),

Assertion::BRC20AmountHolder =>
format!("{BASE_URL}/20-token-holding-amount-list/1-1-0.json"),
Expand All @@ -104,6 +103,9 @@ pub fn get_schema_url(assertion: &Assertion) -> String {

Assertion::PlatformUser(_) => format!("{BASE_URL}/24-platform-user/1-1-0.json"),

Assertion::TokenHoldingAmount(_) =>
format!("{BASE_URL}/25-token-holding-amount/1-1-0.json"),

Assertion::NftHolder(_) => format!("{BASE_URL}/26-nft-holder/1-1-0.json"),
}
}
63 changes: 63 additions & 0 deletions tee-worker/litentry/core/data-providers/src/blockchain_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,35 @@ impl<'a> RestPath<ReqPath<'a>> for GetSingleAddressResponse {
}
}

#[derive(Serialize, Deserialize, Debug)]
pub struct GetMultiAddressesResponse {
pub wallet: GetMultiAddressesResponseWallet,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct GetMultiAddressesResponseWallet {
pub final_balance: u128,
}

impl<'a> RestPath<ReqPath<'a>> for GetMultiAddressesResponse {
fn get_path(path: ReqPath) -> Result<String, HttpError> {
Ok(path.path.into())
}
}

// https://www.blockchain.com/explorer/api/blockchain_api
pub trait BlockChainInfoDataApi {
fn get_single_address(
&mut self,
address: String,
fail_fast: bool,
) -> Result<GetSingleAddressResponse, Error>;

fn get_multi_addresses(
&mut self,
addresses: Vec<String>,
fail_fast: bool,
) -> Result<GetMultiAddressesResponse, Error>;
}

impl BlockChainInfoDataApi for BlockChainInfoClient {
Expand All @@ -130,6 +153,30 @@ impl BlockChainInfoDataApi for BlockChainInfoClient {
},
}
}

fn get_multi_addresses(
&mut self,
addresses: Vec<String>,
fail_fast: bool,
) -> Result<GetMultiAddressesResponse, Error> {
let query: Vec<(String, String)> =
vec![("active".to_string(), addresses.join("|")), ("n".to_string(), "0".into())];

let params = BlockChainInfoRequest { path: "multiaddr".into(), query: Some(query) };

debug!("get_multi_addresses, params: {:?}", params);

match self.get::<GetMultiAddressesResponse>(params, fail_fast) {
Ok(resp) => {
debug!("get_multi_addresses, response: {:?}", resp);
Ok(resp)
},
Err(e) => {
debug!("get_multi_addresses, error: {:?}", e);
Err(e)
},
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -163,4 +210,20 @@ mod tests {
.unwrap();
assert_eq!(response.final_balance, 0);
}

#[test]
fn does_get_multi_addresses_works() {
let config = init();
let mut client = BlockChainInfoClient::new(&config);
let response = client
.get_multi_addresses(
vec![
"bc1pgr5fw4p9gl9me0vzjklnlnap669caxc0gsk4j62gff2qktlw6naqm4m3d0".into(),
"bc1qxhmdufsvnuaaaer4ynz88fspdsxq2h9e9cetdj".into(),
],
true,
)
.unwrap();
assert_eq!(response.wallet.final_balance, 185123167511);
}
}
20 changes: 18 additions & 2 deletions tee-worker/litentry/core/mock-server/src/blockchain_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@

use std::collections::HashMap;

use lc_data_providers::blockchain_info::GetSingleAddressResponse;
use lc_data_providers::blockchain_info::{
GetMultiAddressesResponse, GetMultiAddressesResponseWallet, GetSingleAddressResponse,
};

use warp::{http::Response, Filter};

pub(crate) fn query() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
pub(crate) fn query_rawaddr(
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::get()
.and(warp::path!("blockchain_info" / "rawaddr" / String))
.and(warp::query::<HashMap<String, String>>())
Expand All @@ -35,3 +38,16 @@ pub(crate) fn query() -> impl Filter<Extract = impl warp::Reply, Error = warp::R
}
})
}

pub(crate) fn query_multiaddr(
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::get()
.and(warp::path!("blockchain_info" / "multiaddr"))
.and(warp::query::<HashMap<String, String>>())
.map(move |_| {
let body = GetMultiAddressesResponse {
wallet: GetMultiAddressesResponseWallet { final_balance: 185123167511 },
};
Response::builder().body(serde_json::to_string(&body).unwrap())
})
}
3 changes: 2 additions & 1 deletion tee-worker/litentry/core/mock-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ pub fn run(port: u16) -> Result<String, RecvError> {
.or(karat_dao::query())
.or(moralis::query())
.or(moralis::query_solana())
.or(blockchain_info::query())
.or(blockchain_info::query_rawaddr())
.or(blockchain_info::query_multiaddr())
.or(achainable::query())
.or(litentry_archive::query_user_joined_evm_campaign())
.or(vip3::query_user_sbt_level())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ extern crate sgx_tstd as std;

use core::result::Result;

use lc_common::{
abort_strategy::{loop_with_abort_strategy, AbortStrategy, LoopControls},
web3_token::TokenDecimals,
};
use lc_common::web3_token::TokenDecimals;
use lc_data_providers::blockchain_info::{BlockChainInfoClient, BlockChainInfoDataApi};

use crate::*;
Expand All @@ -36,25 +33,13 @@ pub fn get_balance(
addresses: Vec<(Web3Network, String)>,
data_provider_config: &DataProviderConfig,
) -> Result<f64, Error> {
let mut total_balance = 0_f64;

loop_with_abort_strategy(
addresses,
|(network, address)| {
let decimals = Web3TokenType::Btc.get_decimals(*network);
let mut client = BlockChainInfoClient::new(data_provider_config);

match client.get_single_address(address.clone(), false) {
Ok(response) => {
total_balance +=
calculate_balance_with_decimals(response.final_balance, decimals);
Ok(LoopControls::Continue)
},
Err(err) => Err(err.into_error_detail()),
}
},
AbortStrategy::FailFast::<fn(&_) -> bool>,
)?;
let decimals = Web3TokenType::Btc.get_decimals(addresses[0].0);
let mut client = BlockChainInfoClient::new(data_provider_config);
let address_vec: Vec<String> = addresses.into_iter().map(|(_, address)| address).collect();
let response = client
.get_multi_addresses(address_vec, false)
.map_err(|err| err.into_error_detail())?;
let total_balance = calculate_balance_with_decimals(response.wallet.final_balance, decimals);

Ok(total_balance)
}
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ export const mockAssertions = [
TokenHoldingAmount: 'TRX',
},
},
{
description: 'The amount of BTC you are holding',
assertion: {
TokenHoldingAmount: 'BTC',
},
},

{
description: 'The amount of LIT you are staking',
Expand Down

0 comments on commit 2556fd1

Please sign in to comment.