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

Fetch cat in all situations #210

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
76 changes: 5 additions & 71 deletions crates/sage-wallet/src/queues/cat_queue.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
use std::time::Duration;

use chia::protocol::Bytes32;
use sage_database::{CatRow, Database};
use serde::Deserialize;
use tokio::{
sync::mpsc,
time::{sleep, timeout},
};
use tokio::{sync::mpsc, time::sleep};
use tracing::info;

use crate::{SyncEvent, WalletError};

#[derive(Deserialize)]
struct Response {
assets: Vec<AssetData>,
}

#[derive(Deserialize, Clone)]
struct AssetData {
name: Option<String>,
code: Option<String>,
description: Option<String>,
}
use crate::{try_lookup_cat, SyncEvent, WalletError};

#[derive(Debug)]
pub struct CatQueue {
Expand Down Expand Up @@ -56,44 +39,15 @@ impl CatQueue {
asset_id
);

let asset = match timeout(Duration::from_secs(10), lookup_cat(asset_id, self.testnet)).await
{
Ok(Ok(response)) => response.assets.first().cloned().unwrap_or(AssetData {
name: None,
code: None,
description: None,
}),
Ok(Err(error)) => {
info!("Failed to fetch CAT: {:?}", error);
AssetData {
name: None,
code: None,
description: None,
}
}
Err(_) => {
info!("Timeout fetching CAT");
AssetData {
name: None,
code: None,
description: None,
}
}
};

let dexie_image_base_url = if self.testnet {
"https://icons-testnet.dexie.space"
} else {
"https://icons.dexie.space"
};
let asset = try_lookup_cat(asset_id, self.testnet).await;

self.db
.update_cat(CatRow {
asset_id,
name: asset.name,
ticker: asset.code,
ticker: asset.ticker,
description: asset.description,
icon: Some(format!("{dexie_image_base_url}/{asset_id}.webp")),
icon: asset.icon_url,
visible: true,
fetched: true,
})
Expand All @@ -104,23 +58,3 @@ impl CatQueue {
Ok(())
}
}

async fn lookup_cat(asset_id: Bytes32, testnet: bool) -> Result<Response, WalletError> {
let dexie_base_url = if testnet {
"https://api-testnet.dexie.space/v1"
} else {
"https://api.dexie.space/v1"
};

let response = timeout(
Duration::from_secs(10),
reqwest::get(format!(
"{dexie_base_url}/assets?page_size=25&page=1&type=all&code={asset_id}"
)),
)
.await??
.json::<Response>()
.await?;

Ok(response)
}
2 changes: 2 additions & 0 deletions crates/sage-wallet/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
mod fetch_nft_did;
mod fetch_nft_offer_details;
mod fetch_uri;
mod lookup_cat;
mod offchain_metadata;
mod submit;

pub use fetch_nft_did::*;
pub use fetch_nft_offer_details::*;
pub use fetch_uri::*;
pub use lookup_cat::*;
pub use offchain_metadata::*;
pub use submit::*;
79 changes: 79 additions & 0 deletions crates/sage-wallet/src/utils/lookup_cat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use std::time::Duration;

use chia::protocol::Bytes32;
use serde::Deserialize;
use tokio::time::timeout;
use tracing::info;

use crate::WalletError;

#[derive(Debug, Default, Clone)]
pub struct FetchedCatDetails {
pub name: Option<String>,
pub ticker: Option<String>,
pub description: Option<String>,
pub icon_url: Option<String>,
}

pub async fn lookup_cat(
asset_id: Bytes32,
testnet: bool,
) -> Result<FetchedCatDetails, WalletError> {
#[derive(Deserialize)]
struct Response {
assets: Vec<AssetData>,
}

#[derive(Deserialize, Clone)]
struct AssetData {
name: Option<String>,
code: Option<String>,
description: Option<String>,
}

let dexie_base_url = if testnet {
"https://api-testnet.dexie.space/v1"
} else {
"https://api.dexie.space/v1"
};

let dexie_image_base_url = if testnet {
"https://icons-testnet.dexie.space"
} else {
"https://icons.dexie.space"
};

let mut response = reqwest::get(format!(
"{dexie_base_url}/assets?page_size=25&page=1&type=all&code={asset_id}"
))
.await?
.json::<Response>()
.await?;

if response.assets.is_empty() {
return Ok(FetchedCatDetails::default());
}

let asset = response.assets.remove(0);

Ok(FetchedCatDetails {
name: asset.name,
ticker: asset.code,
description: asset.description,
icon_url: Some(format!("{dexie_image_base_url}/{asset_id}.webp")),
})
}

pub async fn try_lookup_cat(asset_id: Bytes32, testnet: bool) -> FetchedCatDetails {
match timeout(Duration::from_secs(10), lookup_cat(asset_id, testnet)).await {
Ok(Ok(asset)) => asset,
Ok(Err(error)) => {
info!("Failed to fetch CAT: {:?}", error);
FetchedCatDetails::default()
}
Err(_) => {
info!("Timeout fetching CAT");
FetchedCatDetails::default()
}
}
}
48 changes: 32 additions & 16 deletions crates/sage/src/endpoints/offers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use sage_api::{
use sage_database::{OfferCatRow, OfferNftRow, OfferRow, OfferStatus, OfferXchRow};
use sage_wallet::{
calculate_royalties, fetch_nft_offer_details, insert_transaction, lookup_from_uris_with_hash,
parse_locked_coins, parse_offer_payments, MakerSide, NftRoyaltyInfo, SyncCommand, TakerSide,
Transaction, Wallet,
parse_locked_coins, parse_offer_payments, try_lookup_cat, FetchedCatDetails, MakerSide,
NftRoyaltyInfo, SyncCommand, TakerSide, Transaction, Wallet,
};
use tracing::{debug, warn};

Expand Down Expand Up @@ -253,19 +253,27 @@ impl Sage {
let mut nft_rows = Vec::new();

for (asset_id, amount) in maker_amounts.cats {
let info = wallet.db.cat(asset_id).await?;
let name = info.as_ref().and_then(|info| info.name.clone());
let ticker = info.as_ref().and_then(|info| info.ticker.clone());
let icon = info.as_ref().and_then(|info| info.icon.clone());
let cat = wallet.db.cat(asset_id).await?;

let details = if let Some(cat) = cat {
FetchedCatDetails {
name: cat.name,
ticker: cat.ticker,
description: cat.description,
icon_url: cat.icon,
}
} else {
try_lookup_cat(asset_id, self.config.network.network_id != "mainnet").await
};

cat_rows.push(OfferCatRow {
offer_id,
requested: false,
asset_id,
amount,
name: name.clone(),
ticker: ticker.clone(),
icon: icon.clone(),
name: details.name,
ticker: details.ticker,
icon: details.icon_url,
royalty: maker_royalties.cats.get(&asset_id).copied().unwrap_or(0),
});
}
Expand Down Expand Up @@ -330,19 +338,27 @@ impl Sage {
}

for (asset_id, amount) in taker_amounts.cats {
let info = wallet.db.cat(asset_id).await?;
let name = info.as_ref().and_then(|info| info.name.clone());
let ticker = info.as_ref().and_then(|info| info.ticker.clone());
let icon = info.as_ref().and_then(|info| info.icon.clone());
let cat = wallet.db.cat(asset_id).await?;

let details = if let Some(cat) = cat {
FetchedCatDetails {
name: cat.name,
ticker: cat.ticker,
description: cat.description,
icon_url: cat.icon,
}
} else {
try_lookup_cat(asset_id, self.config.network.network_id != "mainnet").await
};

cat_rows.push(OfferCatRow {
offer_id,
requested: true,
asset_id,
amount,
name: name.clone(),
ticker: ticker.clone(),
icon: icon.clone(),
name: details.name,
ticker: details.ticker,
icon: details.icon_url,
royalty: taker_royalties.cats.get(&asset_id).copied().unwrap_or(0),
});
}
Expand Down
22 changes: 18 additions & 4 deletions crates/sage/src/utils/confirmation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ use sage_api::{
TransactionOutput, TransactionSummary,
};
use sage_database::Database;
use sage_wallet::{compute_nft_info, ChildKind, CoinKind, Data, Transaction};
use sage_wallet::{
compute_nft_info, try_lookup_cat, ChildKind, CoinKind, Data, FetchedCatDetails, Transaction,
};

use crate::{Error, Result, Sage};

Expand Down Expand Up @@ -54,11 +56,23 @@ impl Sage {
p2_puzzle_hash,
} => {
let cat = wallet.db.cat(asset_id).await?;

let details = if let Some(cat) = cat {
FetchedCatDetails {
name: cat.name,
ticker: cat.ticker,
description: cat.description,
icon_url: cat.icon,
}
} else {
try_lookup_cat(asset_id, self.config.network.network_id != "mainnet").await
};

let kind = AssetKind::Cat {
asset_id: hex::encode(asset_id),
name: cat.as_ref().and_then(|cat| cat.name.clone()),
ticker: cat.as_ref().and_then(|cat| cat.ticker.clone()),
icon_url: cat.as_ref().and_then(|cat| cat.icon.clone()),
name: details.name,
ticker: details.ticker,
icon_url: details.icon_url,
};
(kind, p2_puzzle_hash)
}
Expand Down
36 changes: 29 additions & 7 deletions crates/sage/src/utils/offer_summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use indexmap::IndexMap;
use sage_api::{Amount, OfferAssets, OfferCat, OfferNft, OfferSummary, OfferXch};
use sage_wallet::{
calculate_royalties, lookup_from_uris_with_hash, parse_locked_coins, parse_offer_payments,
NftRoyaltyInfo,
try_lookup_cat, FetchedCatDetails, NftRoyaltyInfo,
};

use crate::{Result, Sage};
Expand Down Expand Up @@ -68,14 +68,25 @@ impl Sage {
for (asset_id, amount) in maker_amounts.cats {
let cat = wallet.db.cat(asset_id).await?;

let details = if let Some(cat) = cat {
FetchedCatDetails {
name: cat.name,
ticker: cat.ticker,
description: cat.description,
icon_url: cat.icon,
}
} else {
try_lookup_cat(asset_id, self.config.network.network_id != "mainnet").await
};

maker.cats.insert(
hex::encode(asset_id),
OfferCat {
amount: Amount::u64(amount),
royalty: Amount::u64(maker_royalties.cats.get(&asset_id).copied().unwrap_or(0)),
name: cat.as_ref().and_then(|cat| cat.name.clone()),
ticker: cat.as_ref().and_then(|cat| cat.ticker.clone()),
icon_url: cat.as_ref().and_then(|cat| cat.icon.clone()),
name: details.name,
ticker: details.ticker,
icon_url: details.icon_url,
},
);
}
Expand Down Expand Up @@ -144,14 +155,25 @@ impl Sage {
for (asset_id, amount) in taker_amounts.cats {
let cat = wallet.db.cat(asset_id).await?;

let details = if let Some(cat) = cat {
FetchedCatDetails {
name: cat.name,
ticker: cat.ticker,
description: cat.description,
icon_url: cat.icon,
}
} else {
try_lookup_cat(asset_id, self.config.network.network_id != "mainnet").await
};

taker.cats.insert(
hex::encode(asset_id),
OfferCat {
amount: Amount::u64(amount),
royalty: Amount::u64(taker_royalties.cats.get(&asset_id).copied().unwrap_or(0)),
name: cat.as_ref().and_then(|cat| cat.name.clone()),
ticker: cat.as_ref().and_then(|cat| cat.ticker.clone()),
icon_url: cat.as_ref().and_then(|cat| cat.icon.clone()),
name: details.name,
ticker: details.ticker,
icon_url: details.icon_url,
},
);
}
Expand Down
Loading