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 IssuedOrNative struct #109

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion stellar_rust_sdk/src/accounts/accounts_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ impl AccountsRequest<NoSponsorFilter, NoSignerFilter, NoAssetFilter, NoLiquidity
///
pub fn set_sponsor_filter(
self,
sponsor: impl Into<String>
sponsor: impl Into<String>,
) -> Result<
AccountsRequest<SponsorFilter, NoSignerFilter, NoAssetFilter, NoLiquidityPoolFilter>,
String,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{models::*, BuildQueryParametersExt};
use crate::{models::*, models::prelude::*, BuildQueryParametersExt};
use stellar_rust_sdk_derive::pagination;

/// Represents a request to list all claimable balances from the Stellar Horizon API.
Expand All @@ -17,16 +17,17 @@ use stellar_rust_sdk_derive::pagination;
///
/// # Example
/// ```
/// # use stellar_rs::claimable_balances::all_claimable_balances_request::AllClaimableBalancesRequest;
/// # use stellar_rs::models::{Asset, Order, IssuedAsset};
/// use stellar_rs::claimable_balances::all_claimable_balances_request::AllClaimableBalancesRequest;
/// use stellar_rs::models::{Order, prelude::*};
///
/// let request = AllClaimableBalancesRequest::new()
/// .set_sponsor("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap() // Optional sponsor filter
/// .set_asset(Asset::new().set_issued("USD", "GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap()) // Optional asset filter
/// .set_claimant("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap() // Optional claimant filter
/// .set_cursor(123).unwrap() // Optional cursor for pagination
/// .set_limit(100).unwrap() // Optional limit for response records
/// .set_order(Order::Desc); // Optional order of records
/// .set_sponsor("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap() // optional sponsor filter
/// .set_asset(IssuedOrNative::Issued(AssetData{
/// asset_code: "USDC".to_string(),
/// asset_issuer: "GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7".to_string(),
/// })) // optional asset filter
/// .set_claimant("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7".to_string()).unwrap() // optional claimant filter
/// .set_limit(4).unwrap(); // optional limit for response records
///
/// // Use with HorizonClient::get_all_claimable_balances
/// ```
Expand All @@ -40,7 +41,7 @@ pub struct AllClaimableBalancesRequest {

/// Optional. Indicates issued asset for which claimable balances are being queried.
/// When set, the response will filter claimable balances that hold this specific asset.
asset: Option<Asset<IssuedAsset>>,
asset: Option<IssuedOrNative>,

/// Optional. Represents the account ID of the claimant. If provided, the response will
/// include only claimable balances that are claimable by the specified account.
Expand All @@ -49,9 +50,21 @@ pub struct AllClaimableBalancesRequest {

impl Request for AllClaimableBalancesRequest {
fn get_query_parameters(&self) -> String {
let prefix = "asset=";
let asset = match &self.asset {
Some(IssuedOrNative::Native) => format!("{}native", prefix),
Some(IssuedOrNative::Issued(asset_data)) => {
format!(
"{}{}%3A{}",
prefix, asset_data.asset_code, asset_data.asset_issuer
)
},
None => String::new()
};

vec![
self.sponsor.as_ref().map(|s| format!("sponsor={}", s)),
self.asset.as_ref().map(|a| format!("asset={}", a)),
Some(asset),
self.claimant.as_ref().map(|c| format!("claimant={}", c)),
self.cursor.as_ref().map(|c| format!("cursor={}", c)),
self.limit.as_ref().map(|l| format!("limit={}", l)),
Expand Down Expand Up @@ -81,7 +94,10 @@ impl AllClaimableBalancesRequest {
/// # Arguments
/// * `sponsor` - A Stellar public key of the sponsor whose claimable balances are to be retrieved.
///
pub fn set_sponsor(self, sponsor: impl Into<String>) -> Result<AllClaimableBalancesRequest, String> {
pub fn set_sponsor(
self,
sponsor: impl Into<String>,
) -> Result<AllClaimableBalancesRequest, String> {
let sponsor = sponsor.into();
if let Err(e) = is_public_key(&sponsor) {
return Err(e.to_string());
Expand All @@ -98,7 +114,7 @@ impl AllClaimableBalancesRequest {
/// # Arguments
/// * `asset` - The issued asset to filter claimable balances by asset type.
///
pub fn set_asset(self, asset: Asset<IssuedAsset>) -> AllClaimableBalancesRequest {
pub fn set_asset(self, asset: IssuedOrNative) -> AllClaimableBalancesRequest {
AllClaimableBalancesRequest {
asset: Some(asset),
..self
Expand All @@ -110,7 +126,10 @@ impl AllClaimableBalancesRequest {
/// # Arguments
/// * `claimant` - A Stellar public key of the claimant whose claimable balances are to be retrieved.
///
pub fn set_claimant(self, claimant: impl Into<String>) -> Result<AllClaimableBalancesRequest, String> {
pub fn set_claimant(
self,
claimant: impl Into<String>,
) -> Result<AllClaimableBalancesRequest, String> {
let claimant = claimant.into();
if let Err(e) = is_public_key(&claimant) {
return Err(e.to_string());
Expand Down
33 changes: 24 additions & 9 deletions stellar_rust_sdk/src/claimable_balances/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ pub mod prelude {
mod tests {
use super::parse_epoch;
use super::prelude::*;
use crate::models::prelude::*;
use crate::horizon_client::HorizonClient;
use chrono::DateTime;
use chrono::{TimeZone, Utc};
Expand Down Expand Up @@ -184,20 +185,34 @@ mod tests {
assert_eq!(predicate.is_valid(jan_first_2024), true);
assert_eq!(predicate.is_valid(valid_date), true);
let record = &binding.embedded().records()[0];

assert_eq!(record.id(), ID);

assert_eq!(record.asset(), ASSET);

assert_eq!(record.amount(), AMOUNT);

assert_eq!(record.sponsor(), SPONSOR);

assert_eq!(record.last_modified_ledger(), LAST_MODIFIED_LEDGER);

assert_eq!(record.last_modified_time().to_string(), LAST_MODIFIED_TIME);

assert_eq!(record.flags().clawback_enabled(), CLAWBACK_ENABLED);

// Create request with parameters.
let all_claimable_balances_request =
AllClaimableBalancesRequest::new()
.set_sponsor("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7")
.unwrap()
.set_asset(IssuedOrNative::Issued(AssetData{
asset_code: "USDC".to_string(),
asset_issuer: "GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7".to_string(),
}))
.set_claimant("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7".to_string())
.unwrap()
.set_limit(4)
.unwrap();

let all_claimable_balances_response = horizon_client
.get_all_claimable_balances(&all_claimable_balances_request)
.await;

assert!(all_claimable_balances_response.is_ok()); // only test response status code

}

#[tokio::test]
Expand All @@ -218,8 +233,8 @@ mod tests {
// Initialize horizon client
let horizon_client = HorizonClient::new("https://horizon-testnet.stellar.org").unwrap();

let single_claimable_balance_request = SingleClaimableBalanceRequest::new()
.set_claimable_balance_id(CLAIMABLE_BALANCE_ID);
let single_claimable_balance_request =
SingleClaimableBalanceRequest::new().set_claimable_balance_id(CLAIMABLE_BALANCE_ID);

let single_claimable_balance_response = horizon_client
.get_single_claimable_balance(&single_claimable_balance_request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ mod tests {

#[test]
fn test_single_claimable_balance_request() {
let request =
SingleClaimableBalanceRequest::new().set_claimable_balance_id("00000000");
let request = SingleClaimableBalanceRequest::new().set_claimable_balance_id("00000000");

assert_eq!(request.get_query_parameters(), "00000000");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ impl EffectForTransactionRequest {
/// # Arguments
/// * `liquidity_pool_id` - A `String` value representing the liquidity pool id.
///
pub fn set_transaction_hash(self, transaction_hash: impl Into<String>) -> EffectForTransactionRequest {
pub fn set_transaction_hash(
self,
transaction_hash: impl Into<String>,
) -> EffectForTransactionRequest {
EffectForTransactionRequest {
transaction_hash: Some(transaction_hash.into()),
..self
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::{
models::{prelude::{AssetData, AssetType}, Order, Request},
models::{
prelude::{AssetData, AssetType},
Order, Request,
},
BuildQueryParametersExt,
};
use stellar_rust_sdk_derive::pagination;
Expand Down Expand Up @@ -74,7 +77,7 @@ impl AllLiquidityPoolsRequest {
asset_issuer,
})),
None => {
self.reserves = Some(vec![AssetType::Alphanumeric4(AssetData{
self.reserves = Some(vec![AssetType::Alphanumeric4(AssetData {
asset_code,
asset_issuer,
})])
Expand Down
11 changes: 10 additions & 1 deletion stellar_rust_sdk/src/models/request_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@ pub struct AssetData {
pub asset_issuer: String,
}

/// Represents the asset type of an asset.
/// Represents 1 of the asset types which can be specified in a request.
#[derive(Default, Clone, Debug)]
pub enum IssuedOrNative {
#[default]
Native,
Issued(AssetData),
}

/// Represents 1 of the asset types which can be specified in a request.
/// This type has more specific options to choose from.
#[derive(Default, Clone, PartialEq, Debug)]
pub enum AssetType {
/// A native asset_type type. It holds no value.
Expand Down
59 changes: 44 additions & 15 deletions stellar_rust_sdk/src/offers/all_offers_request.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{models::*, BuildQueryParametersExt};
use crate::{models::prelude::*, models::*, BuildQueryParametersExt};
use stellar_rust_sdk_derive::pagination;

/// Represents a request to list all offers from the Stellar Horizon API.
Expand All @@ -17,16 +17,19 @@ use stellar_rust_sdk_derive::pagination;
/// # Example
/// ```
/// use stellar_rs::offers::all_offers_request::AllOffersRequest;
/// use stellar_rs::models::{Asset, NativeAsset, Order};
/// use stellar_rs::models::{Order, prelude::*};
///
/// let request = AllOffersRequest::new()
/// .set_sponsor("GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5").unwrap() // Optional sponsor filter
/// .set_seller("GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap() // Optional seller filter
/// .set_selling(Asset::new().set_issued("USD", "GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap()) // Optional selling asset filter
/// .set_buying(Asset::new().set_issued("USD", "GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH2BEWFG4BRUY4CKI7").unwrap()) // Optional buying asset filter
/// .set_cursor(123).unwrap() // Optional cursor for pagination
/// .set_limit(100).unwrap() // Optional limit for response records
/// .set_order(Order::Desc); // Optional order of records
/// .set_sponsor("GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5").unwrap() // Optional buyer filter
/// .set_seller("GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4").unwrap() // optional seller filter
/// .set_selling(IssuedOrNative::Issued(AssetData {
/// asset_code: "USDC".to_string(),
/// asset_issuer: "GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4".to_string(),
/// })) // optional selling asset filter
/// .set_buying(IssuedOrNative::Native) // optional buying asset filter
/// .set_cursor(123).unwrap() // optional cursor for pagination
/// .set_limit(100).unwrap() // optional limit for response records
/// .set_order(Order::Desc).unwrap(); // optional order of records
///
/// // Use with HorizonClient::get_all_offers
/// ```
Expand All @@ -42,19 +45,45 @@ pub struct AllOffersRequest {
seller: Option<String>,
/// Optional. Indicates an selling asset for which offers are being queried.
/// When set, the response will filter the offers that hold this specific asset.
selling: Option<Asset<IssuedAsset>>,
selling: Option<IssuedOrNative>,
/// Optional. Indicates a buying asset for which offers are being queried.
/// When set, the response will filter the offers that hold this specific asset.
buying: Option<Asset<IssuedAsset>>,
buying: Option<IssuedOrNative>,
}

impl Request for AllOffersRequest {
fn get_query_parameters(&self) -> String {
// Determine selling assets and form parameters.
let prefix = "selling=";
let selling_asset = match &self.selling {
Some(IssuedOrNative::Native) => format!("{}native", prefix),
Some(IssuedOrNative::Issued(asset_data)) => {
format!(
"{}{}%3A{}",
prefix, asset_data.asset_code, asset_data.asset_issuer
)
},
None => String::new()
};

// Determine buying assets and form parameters.
let prefix = "buying=";
let buying_asset = match &self.buying {
Some(IssuedOrNative::Native) => format!("{}native", prefix),
Some(IssuedOrNative::Issued(asset_data)) => {
format!(
"{}{}%3A{}",
prefix, asset_data.asset_code, asset_data.asset_issuer
)
},
None => String::new()
};

vec![
self.sponsor.as_ref().map(|s| format!("sponsor={}", s)),
self.seller.as_ref().map(|s| format!("seller={}", s)),
self.selling.as_ref().map(|s| format!("selling={}", s)),
self.buying.as_ref().map(|b| format!("buying={}", b)),
Some(selling_asset),
Some(buying_asset),
self.cursor.as_ref().map(|c| format!("cursor={}", c)),
self.limit.as_ref().map(|l| format!("limit={}", l)),
self.order.as_ref().map(|o| format!("order={}", o)),
Expand Down Expand Up @@ -117,7 +146,7 @@ impl AllOffersRequest {
/// # Arguments
/// * `selling` - The selling asset to filter offers by.
///
pub fn set_selling(self, selling: Asset<IssuedAsset>) -> AllOffersRequest {
pub fn set_selling(self, selling: IssuedOrNative) -> AllOffersRequest {
AllOffersRequest {
selling: Some(selling),
..self
Expand All @@ -129,7 +158,7 @@ impl AllOffersRequest {
/// # Arguments
/// * `buying` - The buying asset to filter offers by.
///
pub fn set_buying(self, buying: Asset<IssuedAsset>) -> AllOffersRequest {
pub fn set_buying(self, buying: IssuedOrNative) -> AllOffersRequest {
AllOffersRequest {
buying: Some(buying),
..self
Expand Down
31 changes: 27 additions & 4 deletions stellar_rust_sdk/src/offers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ pub mod prelude {
#[cfg(test)]
pub mod test {
use super::prelude::*;
use crate::{horizon_client::HorizonClient, models::*};
use crate::{horizon_client::HorizonClient,
models::*,
models::prelude::*
};

#[tokio::test]
async fn test_get_single_offer() {
Expand All @@ -109,9 +112,7 @@ pub mod test {

let horizon_client = HorizonClient::new("https://horizon-testnet.stellar.org").unwrap();

let single_offer_request = SingleOfferRequest::new()
.set_offer_id(OFFER_ID)
.unwrap();
let single_offer_request = SingleOfferRequest::new().set_offer_id(OFFER_ID).unwrap();

let single_offer_response = horizon_client.get_single_offer(&single_offer_request).await;

Expand Down Expand Up @@ -210,6 +211,28 @@ pub mod test {
assert_eq!(record.price_decimal(), PRICE);
assert_eq!(record.last_modified_ledger(), LAST_MODIFIED_LEDGER);
assert_eq!(record.last_modified_time(), LAST_MODIFIED_TIME);

// Create a request with parameters.
let all_offers_request = AllOffersRequest::new()
.set_sponsor("GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5")
.unwrap()
.set_seller("GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4")
.unwrap()
.set_selling(IssuedOrNative::Issued(AssetData {
asset_code: "USDC".to_string(),
asset_issuer: "GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4"
.to_string(),
}))
.set_buying(IssuedOrNative::Native)
.set_cursor(123)
.unwrap()
.set_limit(100)
.unwrap()
.set_order(Order::Desc)
.unwrap();

let all_offers_response = horizon_client.get_all_offers(&all_offers_request).await;
assert!(all_offers_response.is_ok()); // only test response status code
}

#[tokio::test]
Expand Down
2 changes: 1 addition & 1 deletion stellar_rust_sdk/src/offers/offers_for_account_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl OffersForAccountRequest<NoOfferAccountId> {

pub fn set_account_id(
self,
account_id: impl Into<String>
account_id: impl Into<String>,
) -> Result<OffersForAccountRequest<OfferAccountId>, String> {
let account_id = account_id.into();
if let Err(e) = is_public_key(&account_id) {
Expand Down
Loading