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

ref: add batched endpoint for tvl achievement #126

Merged
merged 5 commits into from
Nov 7, 2023
Merged
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
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
starknet = "0.6.0"
starknet-id = { git = "https://github.com/starknet-id/starknet-id.rs.git", branch = "master" }
starknet = { git = "https://github.com/xJonathanLEI/starknet-rs" }
starknet-id = { git = "https://github.com/starknet-id/starknet-id.rs.git" }
axum = "0.6.17"
toml = "0.5.10"
serde = { version = "1.0.152", features = ["derive"] }
Expand Down
88 changes: 88 additions & 0 deletions src/common/get_achievement.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use std::sync::Arc;

use crate::models::AppState;
use crate::models::{AchievementCategoryDocument, UserAchievementsCategory};
use futures::StreamExt;
use mongodb::bson::{doc, from_document};
use starknet::core::types::FieldElement;

pub async fn get_achievement(
state: &Arc<AppState>,
addr: &FieldElement,
category_id: u32,
) -> Result<UserAchievementsCategory, String> {
let achievement_categories = state
.db
.collection::<AchievementCategoryDocument>("achievement_categories");
let pipeline = vec![
doc! {
"$match": {
"id": category_id,
}
},
doc! {
"$lookup": {
"from": "achievements",
"localField": "id",
"foreignField": "category_id",
"as": "achievement"
}
},
doc! {"$unwind": "$achievement" },
doc! {
"$lookup": {
"from": "achieved",
"let": { "achievement_id": "$achievement.id" },
"pipeline": [
{ "$match": {
"$expr": {
"$and": [
{ "$eq": ["$achievement_id", "$$achievement_id"] },
{ "$eq": ["$addr", FieldElement::to_string(&addr)] }
]
}
} }
],
"as": "achieved"
}
},
doc! {
"$project": {
"_id": 0,
"category_id": "$id",
"achievements": {
"id": "$achievement.id",
"completed": { "$ne": [{ "$size": "$achieved" }, 0] },
"verify_type": "$achievement.verify_type",
}
}
},
doc! {
"$group": {
"_id": {
"category_id": "$category_id",
},
"achievements": { "$push": "$achievements" }
}
},
doc! {
"$project": {
"category_id": "$_id.category_id",
"achievements": 1,
"_id": 0
}
},
];

match achievement_categories.aggregate(pipeline, None).await {
Ok(mut cursor) => match cursor.next().await {
Some(Ok(document)) => match from_document::<UserAchievementsCategory>(document) {
Ok(achievement_category) => Ok(achievement_category),
Err(e) => Err(format!("Error deserializing document : {}", e)),
},
Some(Err(e)) => Err(format!("No data found: {}", e)),
None => Err("No data found".to_string()),
},
Err(e) => Err(format!("Error fetching user achievements: {}", e)),
}
}
1 change: 1 addition & 0 deletions src/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod get_achievement;
pub mod has_deployed_time;
pub mod verify_has_nft;
pub mod verify_has_root_domain;
Expand Down
1 change: 1 addition & 0 deletions src/endpoints/achievements/batched/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod verify_tvl_batched;
74 changes: 74 additions & 0 deletions src/endpoints/achievements/batched/verify_tvl_batched.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use std::sync::Arc;

use crate::{
common::get_achievement::get_achievement,
models::{AppState, VerifyAchievementBatchedQuery},
utils::{get_error, to_hex, AchievementsTrait},
};
use axum::{
extract::{Query, State},
http::StatusCode,
response::IntoResponse,
Json,
};
use serde_json::json;
use starknet::core::types::FieldElement;

pub async fn handler(
State(state): State<Arc<AppState>>,
Query(query): Query<VerifyAchievementBatchedQuery>,
) -> impl IntoResponse {
let addr = query.addr;
if addr == FieldElement::ZERO {
return get_error("Please connect your wallet first".to_string());
}

let url = format!(
"https://stack.starkendefi.xyz/public/aggregates/{}",
to_hex(addr)
);
let client = reqwest::Client::new();
match client.get(url).send().await {
Ok(response) => match response.json::<serde_json::Value>().await {
Ok(json) => {
if let Some(total_tvl_dollars) = json["total_tvl_dollars"].as_f64() {
if total_tvl_dollars < 100.0 {
return get_error("Your TVL is too low".to_string());
}

match get_achievement(&state, &query.addr, query.category_id).await {
Ok(achievements) => {
let mut achieved: Vec<u32> = vec![];
for achievement in achievements.achievements {
if !achievement.completed
&& (achievement.id == 11 && total_tvl_dollars >= 100.0)
|| (achievement.id == 12 && total_tvl_dollars >= 1000.0)
|| (achievement.id == 13 && total_tvl_dollars >= 10000.0)
{
match state
.upsert_completed_achievement(addr, achievement.id)
.await
{
Ok(_) => {
achieved.push(achievement.id);
}
Err(e) => return get_error(format!("{}", e)),
}
}
}
(StatusCode::OK, Json(json!({ "achieved": achieved }))).into_response()
}
Err(e) => get_error(e),
}
} else {
get_error("total_tvl_dollars not found or not a float".to_string())
}
}
Err(e) => get_error(format!(
"Failed to get JSON response from Starkendefi: {}",
e
)),
},
Err(e) => get_error(format!("Failed to fetch Starkendefi: {}", e)),
}
}
3 changes: 3 additions & 0 deletions src/endpoints/achievements/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub async fn handler(
"category_img_url": "$img_url",
"category_type": "$type",
"category_disabled": "$disabled",
"category_override_verified_type": "$override_verified_type",
"achievements": {
"id": "$achievement.id",
"name": "$achievement.name",
Expand Down Expand Up @@ -91,6 +92,7 @@ pub async fn handler(
"category_img_url": "$category_img_url",
"category_type": "$category_type",
"category_disabled": "$category_disabled",
"category_override_verified_type": "$category_override_verified_type",
},
"achievements": { "$push": "$achievements" }
}
Expand All @@ -103,6 +105,7 @@ pub async fn handler(
"category_img_url": "$_id.category_img_url",
"category_type": "$_id.category_type",
"category_disabled": "$_id.category_disabled",
"category_override_verified_type": "$_id.category_override_verified_type",
"achievements": 1,
"_id": 0
}
Expand Down
1 change: 1 addition & 0 deletions src/endpoints/achievements/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod batched;
pub mod fetch;
pub mod fetch_buildings;
pub mod verify_achieved_quests;
Expand Down
1 change: 0 additions & 1 deletion src/endpoints/achievements/verify_achieved_quests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ pub async fn handler(
match client.get(&url).send().await {
Ok(response) => match response.json::<Vec<u32>>().await {
Ok(quests) => {
println!("quests: {:?}", quests);
if quests.is_empty() {
return get_error("You have not completed any quests.".to_string());
}
Expand Down
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,10 @@ async fn main() {
"/achievements/verify_tvl",
get(endpoints::achievements::verify_tvl::handler),
)
.route(
"/achievements/batched/verify_tvl_batched",
get(endpoints::achievements::batched::verify_tvl_batched::handler),
)
.route(
"/achievements/verify_seniority",
get(endpoints::achievements::verify_seniority::handler),
Expand Down
17 changes: 17 additions & 0 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ pub struct UserAchievements {
category_type: String,
#[serde(default = "default_category_disabled")]
pub category_disabled: bool,
pub category_override_verified_type: Option<String>,
achievements: Vec<UserAchievement>,
}

Expand Down Expand Up @@ -180,3 +181,19 @@ pub_struct!(Deserialize, Debug; DeployedTime {
addr: String,
timestamp: u32,
});

pub_struct!(Deserialize; VerifyAchievementBatchedQuery {
addr: FieldElement,
category_id: u32,
});

pub_struct!(Deserialize, Serialize, Debug; UserAchievementsCategory {
category_id: u32,
achievements: Vec<UserAchievementCategory>,
});

pub_struct!(Deserialize, Serialize, Debug; UserAchievementCategory {
id: u32,
completed: bool,
verify_type: String,
});