Skip to content

Commit

Permalink
feat: added GetAssetByAuthority method
Browse files Browse the repository at this point in the history
  • Loading branch information
anamansari062 committed Apr 26, 2024
1 parent ecb7f2f commit f6435e6
Show file tree
Hide file tree
Showing 6 changed files with 192 additions and 25 deletions.
17 changes: 16 additions & 1 deletion src/rpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::config::Config;
use crate::error::Result;
use crate::request_handler::RequestHandler;
use crate::types::types::ApiResponse;
use crate::types::AssetsByOwnerRequest;
use crate::types::{AssetsByOwnerRequest, AssetsByAuthorityRequest};

use reqwest::{Client, Method, Url};
use serde_json::{json, Value};
Expand Down Expand Up @@ -35,4 +35,19 @@ impl RpcClient {

self.handler.send(Method::POST, url, Some(&request_body)).await
}

/// Gets a list of assets of a given authority
pub async fn get_assets_by_authority(&self, request: AssetsByAuthorityRequest) -> Result<ApiResponse> {
let url: String = format!("{}?api-key={}", self.config.endpoints.rpc, self.config.api_key);
let url: Url = Url::parse(&url).expect("Failed to parse URL");

let request_body: Value = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "getAssetsByAuthority",
"params": request
});

self.handler.send(Method::POST, url, Some(&request_body)).await
}
}
2 changes: 1 addition & 1 deletion src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ pub use self::enums::{
AssetSortBy, AssetSortDirection, Context, Interface, OwnershipModel, RoyaltyModel, Scope, UseMethods,
};
pub use self::types::{
ApiResponse, AssetsByOwnerRequest, Attribute, Cluster, CollectionMetadata, Content, File, GetAssetResponse,
ApiResponse, AssetsByOwnerRequest, AssetsByAuthorityRequest, Attribute, Cluster, CollectionMetadata, Content, File, GetAssetResponse,
GetAssetResponseList, HeliusEndpoints, Metadata, Ownership, ResponseType,
};
33 changes: 19 additions & 14 deletions src/types/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ impl HeliusEndpoints {
}
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Default)]
pub struct AssetsByOwnerRequest {
#[serde(rename = "ownerAddress")]
pub owner_address: String,
#[serde(rename = "page")]
pub page: Option<i32>,
pub page: u32,
#[serde(rename = "limit")]
pub limit: Option<i32>,
#[serde(rename = "before")]
Expand All @@ -51,30 +51,35 @@ pub struct AssetsByOwnerRequest {
pub sort_by: Option<AssetSortingRequest>,
}

impl Default for AssetsByOwnerRequest {
fn default() -> Self {
AssetsByOwnerRequest {
owner_address: Default::default(),
page: None,
limit: None,
before: None,
after: None,
display_options: None,
sort_by: None,
}
}
#[derive(Serialize, Deserialize, Default)]
pub struct AssetsByAuthorityRequest{
#[serde(rename = "authorityAddress")]
pub authority_address: String,
pub page: u32,
pub limit: Option<u32>,
pub before: Option<String>,
pub after: Option<String>,
#[serde(rename = "displayOptions")]
pub display_options: Option<DisplayOptions>,
#[serde(rename = "sortBy")]
pub sort_by: Option<AssetSortingRequest>
}

#[derive(Serialize, Deserialize, Debug)]
pub struct DisplayOptions {
#[serde(rename = "showUnverifiedCollections")]
pub show_unverified_collections: Option<bool>,
#[serde(rename = "showCollectionMetadata")]
pub show_collection_metadata: Option<bool>,
#[serde(rename = "showGrandTotal")]
pub show_grand_total: Option<bool>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct AssetSortingRequest {
#[serde(rename = "sortBy")]
pub sort_by: AssetSortBy,
#[serde(rename = "sortDirection")]
pub sort_direction: AssetSortDirection,
}

Expand Down
153 changes: 153 additions & 0 deletions tests/rpc/test_get_assets_by_authority.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use helius_sdk::config::Config;
use helius_sdk::error::HeliusError;
use helius_sdk::rpc_client::RpcClient;
use helius_sdk::types::{
ApiResponse, AssetsByAuthorityRequest, Attribute, Cluster, Content, File, GetAssetResponse, GetAssetResponseList,
HeliusEndpoints, Interface, Metadata, Ownership, OwnershipModel, ResponseType,
};
use helius_sdk::Helius;

use mockito::{self, Server};
use reqwest::Client;
use std::sync::Arc;

#[tokio::test]
async fn test_get_assets_by_authority_success() {
let mut server: Server = Server::new_with_opts_async(mockito::ServerOpts::default()).await;
let url: String = server.url();

let mock_response: ApiResponse = ApiResponse {
jsonrpc: "2.0".to_string(),
result: ResponseType::GetAssetResponseList(GetAssetResponseList {
total: Some(1),
limit: Some(10),
page: Some(1),
items: Some(vec![GetAssetResponse {
interface: Interface::V1NFT,
id: "123".to_string(),
content: Some(Content {
schema: "http://example.com/schema".to_string(),
json_uri: "http://example.com/json".to_string(),
files: Some(vec![File {
uri: Some("http://example.com/file1".to_string()),
mime: Some("image/png".to_string()),
cdn_uri: None,
quality: None,
contexts: None,
}]),
metadata: Metadata {
attributes: Some(vec![Attribute {
value: "blue".to_string(),
trait_type: "color".to_string(),
}]),
description: Some("A description".to_string()),
name: "Item1".to_string(),
symbol: "SYM".to_string(),
},
links: None,
}),
authorities: None,
compression: None,
grouping: None,
royalty: None,
ownership: Ownership {
frozen: false,
delegated: false,
delegate: None,
ownership_model: OwnershipModel::Single,
owner: "OwnerAddress1".to_string(),
},
creators: None,
uses: None,
supply: None,
mutable: false,
burnt: false,
}]),
}),
id: 1,
};

server
.mock("POST", "/?api-key=fake_api_key")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(serde_json::to_string(&mock_response).unwrap())
.create();

let config: Arc<Config> = Arc::new(Config {
api_key: "fake_api_key".to_string(),
cluster: Cluster::Devnet,
endpoints: HeliusEndpoints {
api: url.to_string(),
rpc: url.to_string(),
},
});

let client: Client = Client::new();
let rpc_client: Arc<RpcClient> = Arc::new(RpcClient::new(Arc::new(client.clone()), Arc::clone(&config)).unwrap());
let helius: Helius = Helius {
config,
client,
rpc_client,
};

let request: AssetsByAuthorityRequest = AssetsByAuthorityRequest {
authority_address: "GNPwr9fk9RJbfy9nSKbNiz5NPfc69KVwnizverx6fNze".to_string(),
page: 1,
limit: Some(1),
..Default::default()
};

let response: Result<ApiResponse, HeliusError> = helius.rpc().get_assets_by_authority(request).await;
assert!(response.is_ok(), "The API call failed: {:?}", response.err());

let api_response: ApiResponse = response.unwrap();

if let ResponseType::GetAssetResponseList(list) = api_response.result {
assert_eq!(list.total, Some(1), "Total does not match");
assert!(list.items.is_some(), "Items are missing");
assert_eq!(list.items.unwrap().len(), 1, "Items count does not match");
} else {
panic!("Expected GetAssetResponseList");
}
}

#[tokio::test]
async fn test_get_assets_by_authority_failure() {
let mut server: Server = Server::new_with_opts_async(mockito::ServerOpts::default()).await;
let url: String = server.url();

// Simulate an API failure with status code 500
server
.mock("POST", "/?api-key=fake_api_key")
.with_status(500)
.with_header("content-type", "application/json")
.with_body(r#"{"error": "Internal Server Error"}"#)
.create();

let config: Arc<Config> = Arc::new(Config {
api_key: "fake_api_key".to_string(),
cluster: Cluster::Devnet,
endpoints: HeliusEndpoints {
api: url.to_string(),
rpc: url.to_string(),
},
});

let client: Client = Client::new();
let rpc_client: Arc<RpcClient> = Arc::new(RpcClient::new(Arc::new(client.clone()), Arc::clone(&config)).unwrap());
let helius: Helius = Helius {
config,
client,
rpc_client,
};

let request: AssetsByAuthorityRequest = AssetsByAuthorityRequest {
authority_address: "GNPwr9fk9RJbfy9nSKbNiz5NPfc69KVwnizverx6fNze".to_string(),
page: 1,
..Default::default()
};

let response: Result<ApiResponse, HeliusError> = helius.rpc().get_assets_by_authority(request).await;
assert!(response.is_err(), "Expected an error due to server failure");
}
11 changes: 2 additions & 9 deletions tests/rpc/test_get_assets_by_owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,8 @@ use helius_sdk::Helius;

use mockito::{self, Server};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

#[derive(Serialize, Deserialize, Debug, Default)]
struct MockAssetResponse {
total: u32,
assets: Vec<String>,
}

#[tokio::test]
async fn test_get_assets_by_owner_success() {
let mut server: Server = Server::new_with_opts_async(mockito::ServerOpts::default()).await;
Expand Down Expand Up @@ -100,7 +93,7 @@ async fn test_get_assets_by_owner_success() {

let request: AssetsByOwnerRequest = AssetsByOwnerRequest {
owner_address: "GNPwr9fk9RJbfy9nSKbNiz5NPfc69KVwnizverx6fNze".to_string(),
page: Some(1),
page: 1,
..Default::default()
};

Expand Down Expand Up @@ -149,7 +142,7 @@ async fn test_get_assets_by_owner_failure() {

let request: AssetsByOwnerRequest = AssetsByOwnerRequest {
owner_address: "GNPwr9fk9RJbfy9nSKbNiz5NPfc69KVwnizverx6fNze".to_string(),
page: Some(1),
page: 1,
..Default::default()
};

Expand Down
1 change: 1 addition & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ mod utils {

mod rpc {
mod test_get_assets_by_owner;
mod test_get_assets_by_authority;
}

0 comments on commit f6435e6

Please sign in to comment.