From e036ab66d5e1ff19d2b6704aca8eecb5033ce42b Mon Sep 17 00:00:00 2001 From: Oshioke-Salaki Date: Mon, 26 Aug 2024 12:49:51 +0100 Subject: [PATCH 1/2] feat: logger impl --- Cargo.toml | 2 + config.template.toml | 9 + src/common/mod.rs | 2 +- src/common/verify_has_root_domain.rs | 15 +- .../verify_has_root_or_braavos_domain.rs | 15 +- src/common/verify_quiz.rs | 4 +- src/config.rs | 15 ++ .../batched/verify_tvl_batched.rs | 5 +- src/endpoints/achievements/claim/mod.rs | 2 +- .../achievements/claim/quests_achievement.rs | 5 +- src/endpoints/achievements/fetch.rs | 5 +- src/endpoints/achievements/fetch_buildings.rs | 5 +- src/endpoints/achievements/mod.rs | 4 +- .../achievements/verify_achieved_quests.rs | 5 +- src/endpoints/achievements/verify_avnu.rs | 5 +- src/endpoints/achievements/verify_briq.rs | 5 +- src/endpoints/achievements/verify_default.rs | 5 +- .../achievements/verify_has_domain.rs | 4 +- src/endpoints/achievements/verify_quests.rs | 5 +- .../achievements/verify_seniority.rs | 5 +- src/endpoints/achievements/verify_tvl.rs | 5 +- src/endpoints/admin/balance/create_balance.rs | 5 +- src/endpoints/admin/balance/update_balance.rs | 5 +- src/endpoints/admin/custom/create_custom.rs | 5 +- src/endpoints/admin/custom/mod.rs | 2 +- src/endpoints/admin/custom/update_custom.rs | 21 +-- src/endpoints/admin/delete_task.rs | 21 ++- src/endpoints/admin/discord/create_discord.rs | 5 +- src/endpoints/admin/discord/mod.rs | 2 +- src/endpoints/admin/discord/update_discord.rs | 23 +-- src/endpoints/admin/domain/create_domain.rs | 5 +- src/endpoints/admin/domain/mod.rs | 2 +- src/endpoints/admin/domain/update_domain.rs | 27 ++- src/endpoints/admin/nft_uri/create_uri.rs | 24 +-- src/endpoints/admin/nft_uri/get_nft_uri.rs | 11 +- src/endpoints/admin/nft_uri/mod.rs | 2 +- src/endpoints/admin/nft_uri/update_uri.rs | 15 +- src/endpoints/admin/quest/create_quest.rs | 11 +- src/endpoints/admin/quest/get_quest.rs | 27 ++- src/endpoints/admin/quest/get_quests.rs | 5 +- src/endpoints/admin/quest/mod.rs | 4 +- src/endpoints/admin/quest/update_quest.rs | 24 +-- .../admin/quest_boost/create_boost.rs | 30 ++-- src/endpoints/admin/quest_boost/mod.rs | 2 +- .../admin/quest_boost/update_boost.rs | 5 +- src/endpoints/admin/quiz/create_question.rs | 10 +- src/endpoints/admin/quiz/create_quiz.rs | 5 +- src/endpoints/admin/quiz/get_quiz.rs | 19 +-- src/endpoints/admin/quiz/mod.rs | 6 +- src/endpoints/admin/quiz/update_question.rs | 5 +- src/endpoints/admin/quiz/update_quiz.rs | 30 ++-- .../admin/twitter/create_twitter_fw.rs | 5 +- .../admin/twitter/create_twitter_rw.rs | 5 +- src/endpoints/admin/twitter/mod.rs | 2 +- .../admin/twitter/update_twitter_fw.rs | 17 +- .../admin/twitter/update_twitter_rw.rs | 21 +-- src/endpoints/admin/user/mod.rs | 2 +- src/endpoints/analytics/get_quest_activity.rs | 5 +- .../analytics/get_quest_participation.rs | 5 +- .../analytics/get_unique_visitors.rs | 5 +- src/endpoints/analytics/mod.rs | 2 +- .../discover/defi/get_alt_protocol_stats.rs | 9 +- .../discover/defi/get_derivatives_stats.rs | 9 +- src/endpoints/discover/defi/get_lend_stats.rs | 9 +- src/endpoints/discover/defi/get_pair_stats.rs | 9 +- src/endpoints/discover/defi/mod.rs | 6 +- src/endpoints/discover/mod.rs | 2 +- src/endpoints/get_quiz.rs | 5 +- src/endpoints/leaderboard/get_ranking.rs | 19 +-- src/endpoints/leaderboard/get_static_info.rs | 5 +- src/endpoints/leaderboard/mod.rs | 2 +- src/endpoints/mod.rs | 8 +- src/endpoints/quest_boost/get_claim_params.rs | 10 +- .../quest_boost/get_completed_boosts.rs | 5 +- .../quest_boost/get_pending_claims.rs | 11 +- .../quests/avnu/discord_fw_callback.rs | 8 +- src/endpoints/quests/bountive/mod.rs | 4 +- .../quests/braavos/carbonable/mod.rs | 4 +- src/endpoints/quests/braavos/mod.rs | 6 +- src/endpoints/quests/braavos/pyramid/mod.rs | 4 +- src/endpoints/quests/braavos/realms/mod.rs | 2 +- .../braavos/starknetid/verify_has_mission.rs | 8 +- src/endpoints/quests/braavos/zklend/mod.rs | 4 +- src/endpoints/quests/discord_fw_callback.rs | 6 +- .../quests/ekubo/discord_fw_callback.rs | 8 +- src/endpoints/quests/ekubo/mod.rs | 2 +- .../engagement/discord_fw_callback.rs | 8 +- .../quests/focustree/engagement/mod.rs | 2 +- .../quests/focustree/introduction/mod.rs | 2 +- src/endpoints/quests/focustree/mod.rs | 2 +- src/endpoints/quests/haiko/mod.rs | 2 +- .../quests/hashstack/discord_fw_callback.rs | 8 +- src/endpoints/quests/hashstack/mod.rs | 2 +- .../quests/influence/discord_fw_callback.rs | 8 +- src/endpoints/quests/influence/mod.rs | 2 +- .../quests/myswap/discord_fw_callback.rs | 8 +- .../quests/nimbora/discord_fw_callback.rs | 8 +- .../liquidity_quest/discord_fw_callback.rs | 8 +- src/endpoints/quests/nostra/mod.rs | 2 +- .../quests/nostra/staking_quest/mod.rs | 2 +- src/endpoints/quests/rango/mod.rs | 2 +- .../rango/quest1/discord_fw_callback.rs | 8 +- src/endpoints/quests/rango/quest1/mod.rs | 2 +- .../rango/quest2/discord_fw_callback.rs | 8 +- src/endpoints/quests/rango/quest2/mod.rs | 2 +- src/endpoints/quests/rhino/mod.rs | 6 +- src/endpoints/quests/sithswap/mod.rs | 2 +- src/endpoints/quests/sithswap/quest2/mod.rs | 2 +- src/endpoints/quests/verify_balance.rs | 8 +- src/logger.rs | 157 ++++++++++++++++++ src/main.rs | 46 ++++- src/models.rs | 3 +- src/utils.rs | 9 +- 113 files changed, 563 insertions(+), 475 deletions(-) create mode 100644 src/logger.rs diff --git a/Cargo.toml b/Cargo.toml index 2b613676..20ba303b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,8 @@ edition = "2021" [dependencies] starknet = { git = "https://github.com/xJonathanLEI/starknet-rs", rev = "c974e5cb42e8d8344cee910b76005ec46b4dd3ed" } starknet-id = { git = "https://github.com/starknet-id/starknet-id.rs.git", rev = "2b30c2453b96789a628c86d2edebb1023fa2e77d" } +serde_derive = "1.0.183" +env_logger = "0.10.0" axum_auto_routes = { git = "https://github.com/Th0rgal/axum_auto_routes.git", rev = "f9e1d2083e887cd264642359c4aa851938da6f09" } axum = "0.6.17" toml = "0.5.10" diff --git a/config.template.toml b/config.template.toml index 2d6cf92f..2f44b075 100644 --- a/config.template.toml +++ b/config.template.toml @@ -9,6 +9,15 @@ connection_string = "xxxxxx" secret_key = "secret_key" expiry_duration = 0 +[watchtower] +endpoint = "https://api.watchtower.starknet.id/service/add_message" +app_id = "XXXXXXXXXXXXXXXXX" +token = "XXXXXXXXXXXXXXXXX" +[watchtower.types] +info = "goerli/info" +warning = "goerli/warning" +severe = "goerli/severe" + [discover] pairs_api_endpoint = "XXXXXXXX" lending_api_endpoint = "XXXXXXXX" diff --git a/src/common/mod.rs b/src/common/mod.rs index 00e03f52..e6ce6f50 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -3,4 +3,4 @@ pub mod has_deployed_time; pub mod verify_has_nft; pub mod verify_has_root_domain; pub mod verify_has_root_or_braavos_domain; -pub mod verify_quiz; \ No newline at end of file +pub mod verify_quiz; diff --git a/src/common/verify_has_root_domain.rs b/src/common/verify_has_root_domain.rs index def70174..3bb27e91 100644 --- a/src/common/verify_has_root_domain.rs +++ b/src/common/verify_has_root_domain.rs @@ -45,16 +45,17 @@ pub async fn execute_has_root_domain( FunctionCall { contract_address: state.conf.starknetid_contracts.naming_contract, entry_point_selector: selector!("domain_to_expiry"), - calldata: vec![ FieldElement::ONE, result[1] ], + calldata: vec![FieldElement::ONE, result[1]], }, BlockId::Tag(BlockTag::Latest), ) - .await else { - return get_error("error querying expiry".to_string()) - }; - let Ok(expiry) : Result = expiry_result[0].try_into() else { - return get_error("error reading expiry".to_string()) - }; + .await + else { + return get_error("error querying expiry".to_string()); + }; + let Ok(expiry): Result = expiry_result[0].try_into() else { + return get_error("error reading expiry".to_string()); + }; let now = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => n.as_secs(), Err(_) => return get_error("system time before UNIX EPOCH".to_string()), diff --git a/src/common/verify_has_root_or_braavos_domain.rs b/src/common/verify_has_root_or_braavos_domain.rs index 7480d972..c84c7e5e 100644 --- a/src/common/verify_has_root_or_braavos_domain.rs +++ b/src/common/verify_has_root_or_braavos_domain.rs @@ -46,16 +46,17 @@ pub async fn verify_has_root_or_braavos_domain( FunctionCall { contract_address: state.conf.starknetid_contracts.naming_contract, entry_point_selector: selector!("domain_to_expiry"), - calldata: vec![ FieldElement::ONE, result[1] ], + calldata: vec![FieldElement::ONE, result[1]], }, BlockId::Tag(BlockTag::Latest), ) - .await else { - return get_error("error querying expiry".to_string()) - }; - let Ok(expiry) : Result = expiry_result[0].try_into() else { - return get_error("error reading expiry".to_string()) - }; + .await + else { + return get_error("error querying expiry".to_string()); + }; + let Ok(expiry): Result = expiry_result[0].try_into() else { + return get_error("error reading expiry".to_string()); + }; let now = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => n.as_secs(), Err(_) => return get_error("system time before UNIX EPOCH".to_string()), diff --git a/src/common/verify_quiz.rs b/src/common/verify_quiz.rs index dc1df3d6..b8f30be4 100644 --- a/src/common/verify_quiz.rs +++ b/src/common/verify_quiz.rs @@ -1,9 +1,9 @@ +use crate::config::{Quiz, QuizQuestionType}; +use crate::models::QuizInsertDocument; use futures::StreamExt; use mongodb::bson::{doc, from_document}; use mongodb::Database; -use crate::config::{Quiz, QuizQuestionType}; use starknet::core::types::FieldElement; -use crate::models::QuizInsertDocument; fn match_vectors(vector1: &Vec, vector2: &Vec) -> bool { // Check if vectors have the same length diff --git a/src/config.rs b/src/config.rs index f550a129..814e5ea8 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,6 +4,20 @@ use std::collections::HashMap; use std::env; use std::fs; +pub_struct!(Clone, Deserialize; Watchtower { + enabled : bool, + endpoint: String, + app_id: String, + token: String, + types: WatchtowerTypes, +}); + +pub_struct!(Clone, Deserialize; WatchtowerTypes { + info: String, + warning: String, + severe: String, +}); + pub_struct!(Clone, Deserialize; Server { port: u16 }); pub_struct!(Clone, Deserialize; Database { @@ -193,6 +207,7 @@ pub_struct!(Clone, Deserialize; Config { discord: Discord, starkscan: Starkscan, achievements: Achievements, + watchtower: Watchtower, quest_boost: QuestBoost, rhino: PublicApi, rango: Api, diff --git a/src/endpoints/achievements/batched/verify_tvl_batched.rs b/src/endpoints/achievements/batched/verify_tvl_batched.rs index 0b036d42..88a5d23f 100644 --- a/src/endpoints/achievements/batched/verify_tvl_batched.rs +++ b/src/endpoints/achievements/batched/verify_tvl_batched.rs @@ -15,10 +15,7 @@ use axum_auto_routes::route; use serde_json::json; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/batched/verify_tvl_batched" -)] +#[route(get, "/achievements/batched/verify_tvl_batched")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/claim/mod.rs b/src/endpoints/achievements/claim/mod.rs index db5e013f..73519106 100644 --- a/src/endpoints/achievements/claim/mod.rs +++ b/src/endpoints/achievements/claim/mod.rs @@ -1 +1 @@ -pub mod quests_achievement; \ No newline at end of file +pub mod quests_achievement; diff --git a/src/endpoints/achievements/claim/quests_achievement.rs b/src/endpoints/achievements/claim/quests_achievement.rs index d9e088b0..5dffa345 100644 --- a/src/endpoints/achievements/claim/quests_achievement.rs +++ b/src/endpoints/achievements/claim/quests_achievement.rs @@ -27,10 +27,7 @@ fn get_number_of_quests(id: u32) -> u32 { }; } -#[route( - get, - "/achievements/claim/quest_achievement" -)] +#[route(get, "/achievements/claim/quest_achievement")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/fetch.rs b/src/endpoints/achievements/fetch.rs index 273da747..ae29abf1 100644 --- a/src/endpoints/achievements/fetch.rs +++ b/src/endpoints/achievements/fetch.rs @@ -15,10 +15,7 @@ use futures::stream::StreamExt; use mongodb::bson::{doc, from_document}; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/fetch" -)] +#[route(get, "/achievements/fetch")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/fetch_buildings.rs b/src/endpoints/achievements/fetch_buildings.rs index 3ac35b33..e0a5911f 100644 --- a/src/endpoints/achievements/fetch_buildings.rs +++ b/src/endpoints/achievements/fetch_buildings.rs @@ -14,10 +14,7 @@ use axum_auto_routes::route; use futures::stream::StreamExt; use mongodb::bson::{doc, from_document}; -#[route( - get, - "/achievements/fetch_buildings" -)] +#[route(get, "/achievements/fetch_buildings")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/mod.rs b/src/endpoints/achievements/mod.rs index 8c87a695..48a3292d 100644 --- a/src/endpoints/achievements/mod.rs +++ b/src/endpoints/achievements/mod.rs @@ -1,4 +1,5 @@ pub mod batched; +pub mod claim; pub mod fetch; pub mod fetch_buildings; pub mod verify_achieved_quests; @@ -6,8 +7,7 @@ pub mod verify_avnu; pub mod verify_briq; pub mod verify_default; pub mod verify_has_domain; +pub mod verify_quests; pub mod verify_seniority; pub mod verify_tvl; pub mod verify_whitelisted; -pub mod verify_quests; -pub mod claim; \ No newline at end of file diff --git a/src/endpoints/achievements/verify_achieved_quests.rs b/src/endpoints/achievements/verify_achieved_quests.rs index d3bd4847..60d30d77 100644 --- a/src/endpoints/achievements/verify_achieved_quests.rs +++ b/src/endpoints/achievements/verify_achieved_quests.rs @@ -14,10 +14,7 @@ use axum_auto_routes::route; use serde_json::json; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/verify_achieved_quests" -)] +#[route(get, "/achievements/verify_achieved_quests")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_avnu.rs b/src/endpoints/achievements/verify_avnu.rs index 1663baad..db30a5e8 100644 --- a/src/endpoints/achievements/verify_avnu.rs +++ b/src/endpoints/achievements/verify_avnu.rs @@ -14,10 +14,7 @@ use axum_auto_routes::route; use serde_json::json; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/verify_avnu" -)] +#[route(get, "/achievements/verify_avnu")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_briq.rs b/src/endpoints/achievements/verify_briq.rs index 14d14074..f73d3aaa 100644 --- a/src/endpoints/achievements/verify_briq.rs +++ b/src/endpoints/achievements/verify_briq.rs @@ -16,10 +16,7 @@ use mongodb::bson::doc; use serde_json::json; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/verify_briq" -)] +#[route(get, "/achievements/verify_briq")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_default.rs b/src/endpoints/achievements/verify_default.rs index 80ee1129..259962b0 100644 --- a/src/endpoints/achievements/verify_default.rs +++ b/src/endpoints/achievements/verify_default.rs @@ -42,10 +42,7 @@ fn get_args(config: Config, achievement_id: u32) -> Result<(FieldElement, u32, N } } -#[route( - get, - "/achievements/verify_default" -)] +#[route(get, "/achievements/verify_default")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_has_domain.rs b/src/endpoints/achievements/verify_has_domain.rs index 773a95e2..5a7dc70d 100644 --- a/src/endpoints/achievements/verify_has_domain.rs +++ b/src/endpoints/achievements/verify_has_domain.rs @@ -20,9 +20,7 @@ use std::{ time::{SystemTime, UNIX_EPOCH}, }; -#[route( - get, - "/achievements/verify_has_domain")] +#[route(get, "/achievements/verify_has_domain")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_quests.rs b/src/endpoints/achievements/verify_quests.rs index fb53cf6c..d3934fb0 100644 --- a/src/endpoints/achievements/verify_quests.rs +++ b/src/endpoints/achievements/verify_quests.rs @@ -28,10 +28,7 @@ fn get_number_of_quests(id: u32) -> u32 { }; } -#[route( - get, - "/achievements/verify_quests" -)] +#[route(get, "/achievements/verify_quests")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_seniority.rs b/src/endpoints/achievements/verify_seniority.rs index 628f7966..036c8272 100644 --- a/src/endpoints/achievements/verify_seniority.rs +++ b/src/endpoints/achievements/verify_seniority.rs @@ -16,10 +16,7 @@ use chrono::{NaiveDateTime, Utc}; use serde_json::json; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/verify_seniority" -)] +#[route(get, "/achievements/verify_seniority")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/achievements/verify_tvl.rs b/src/endpoints/achievements/verify_tvl.rs index f8d25dc7..6883bb53 100644 --- a/src/endpoints/achievements/verify_tvl.rs +++ b/src/endpoints/achievements/verify_tvl.rs @@ -14,10 +14,7 @@ use axum_auto_routes::route; use serde_json::json; use starknet::core::types::FieldElement; -#[route( - get, - "/achievements/verify_tvl" -)] +#[route(get, "/achievements/verify_tvl")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/admin/balance/create_balance.rs b/src/endpoints/admin/balance/create_balance.rs index 547ac83f..14198b15 100644 --- a/src/endpoints/admin/balance/create_balance.rs +++ b/src/endpoints/admin/balance/create_balance.rs @@ -26,10 +26,7 @@ pub_struct!(Deserialize; CreateBalance { cta: String, }); -#[route( - post, - "/admin/tasks/balance/create" -)] +#[route(post, "/admin/tasks/balance/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/balance/update_balance.rs b/src/endpoints/admin/balance/update_balance.rs index e2e913b8..2b44bfd2 100644 --- a/src/endpoints/admin/balance/update_balance.rs +++ b/src/endpoints/admin/balance/update_balance.rs @@ -30,10 +30,7 @@ fn field_element_to_bson(fe: &FieldElement) -> mongodb::bson::Bson { mongodb::bson::Bson::String(fe.to_string()) } -#[route( - post, - "/admin/tasks/balance/update" -)] +#[route(post, "/admin/tasks/balance/update")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/custom/create_custom.rs b/src/endpoints/admin/custom/create_custom.rs index 0f7b8b71..743ad885 100644 --- a/src/endpoints/admin/custom/create_custom.rs +++ b/src/endpoints/admin/custom/create_custom.rs @@ -24,10 +24,7 @@ pub_struct!(Deserialize; CreateCustom { api: String, }); -#[route( - post, - "/admin/tasks/custom/create" -)] +#[route(post, "/admin/tasks/custom/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/custom/mod.rs b/src/endpoints/admin/custom/mod.rs index 04726dc9..2367e5a0 100644 --- a/src/endpoints/admin/custom/mod.rs +++ b/src/endpoints/admin/custom/mod.rs @@ -1,2 +1,2 @@ pub mod create_custom; -pub mod update_custom; \ No newline at end of file +pub mod update_custom; diff --git a/src/endpoints/admin/custom/update_custom.rs b/src/endpoints/admin/custom/update_custom.rs index 4897429b..c5f21c7a 100644 --- a/src/endpoints/admin/custom/update_custom.rs +++ b/src/endpoints/admin/custom/update_custom.rs @@ -1,19 +1,18 @@ -use crate::models::{QuestTaskDocument,JWTClaims}; +use crate::models::{JWTClaims, QuestTaskDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use crate::utils::verify_task_auth; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - pub_struct!(Deserialize; CreateCustom { id: i64, @@ -35,8 +34,8 @@ pub async fn handler( let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("tasks"); - let res= verify_task_auth(user,&collection,&(body.id as i32)).await; - if !res{ + let res = verify_task_auth(user, &collection, &(body.id as i32)).await; + if !res { return get_error("Error updating tasks".to_string()); } @@ -74,12 +73,8 @@ pub async fn handler( "$set": update_doc }; - // insert document to boost collection - return match collection - .find_one_and_update(filter, update, None) - .await - { + return match collection.find_one_and_update(filter, update, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "Task updated successfully"})).into_response(), diff --git a/src/endpoints/admin/delete_task.rs b/src/endpoints/admin/delete_task.rs index 2b6d046f..ed04b8c4 100644 --- a/src/endpoints/admin/delete_task.rs +++ b/src/endpoints/admin/delete_task.rs @@ -1,19 +1,18 @@ +use crate::models::{JWTClaims, QuestTaskDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; +use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use serde::Deserialize; -use crate::models::{QuestTaskDocument,JWTClaims}; -use axum::http::HeaderMap; -use crate::utils::verify_task_auth; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - pub_struct!(Deserialize; DeleteTask { id: i32, @@ -27,8 +26,8 @@ pub async fn handler( ) -> impl IntoResponse { let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("tasks"); - let res= verify_task_auth(user, &collection,&body.id).await; - if !res{ + let res = verify_task_auth(user, &collection, &body.id).await; + if !res { return get_error("Error updating tasks".to_string()); } @@ -36,7 +35,7 @@ pub async fn handler( let filter = doc! { "id": &body.id, }; - return match &collection.delete_one(filter.clone(), None).await{ + return match &collection.delete_one(filter.clone(), None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "deleted successfully"})), @@ -45,5 +44,5 @@ pub async fn handler( Err(_) => { return get_error("Task does not exist".to_string()); } - } + }; } diff --git a/src/endpoints/admin/discord/create_discord.rs b/src/endpoints/admin/discord/create_discord.rs index 6405ae08..8f1da307 100644 --- a/src/endpoints/admin/discord/create_discord.rs +++ b/src/endpoints/admin/discord/create_discord.rs @@ -23,10 +23,7 @@ pub_struct!(Deserialize; CreateCustom { guild_id: String, }); -#[route( - post, - "/admin/tasks/discord/create" -)] +#[route(post, "/admin/tasks/discord/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/discord/mod.rs b/src/endpoints/admin/discord/mod.rs index 1d7340b7..4a8c366c 100644 --- a/src/endpoints/admin/discord/mod.rs +++ b/src/endpoints/admin/discord/mod.rs @@ -1,2 +1,2 @@ pub mod create_discord; -pub mod update_discord; \ No newline at end of file +pub mod update_discord; diff --git a/src/endpoints/admin/discord/update_discord.rs b/src/endpoints/admin/discord/update_discord.rs index 5d2c94ee..68304b7a 100644 --- a/src/endpoints/admin/discord/update_discord.rs +++ b/src/endpoints/admin/discord/update_discord.rs @@ -1,19 +1,18 @@ -use crate::models::{QuestTaskDocument,JWTClaims}; +use crate::models::{JWTClaims, QuestTaskDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use crate::utils::verify_task_auth; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - pub_struct!(Deserialize; CreateCustom { id: i64, @@ -29,11 +28,11 @@ pub async fn handler( headers: HeaderMap, body: Json, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("tasks"); - let res= verify_task_auth(user, &collection,&(body.id as i32)).await; - if !res{ + let res = verify_task_auth(user, &collection, &(body.id as i32)).await; + if !res { return get_error("Error updating tasks".to_string()); } @@ -62,12 +61,8 @@ pub async fn handler( "$set": update_doc }; - // insert document to boost collection - return match collection - .find_one_and_update(filter, update, None) - .await - { + return match collection.find_one_and_update(filter, update, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "Task updated successfully"})).into_response(), diff --git a/src/endpoints/admin/domain/create_domain.rs b/src/endpoints/admin/domain/create_domain.rs index 9c8fef73..78fadea9 100644 --- a/src/endpoints/admin/domain/create_domain.rs +++ b/src/endpoints/admin/domain/create_domain.rs @@ -21,10 +21,7 @@ pub_struct!(Deserialize; CreateTwitterFw { quest_id: i64, }); -#[route( - post, - "/admin/tasks/domain/create" -)] +#[route(post, "/admin/tasks/domain/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/domain/mod.rs b/src/endpoints/admin/domain/mod.rs index 849ddd1a..df88f4b4 100644 --- a/src/endpoints/admin/domain/mod.rs +++ b/src/endpoints/admin/domain/mod.rs @@ -1,2 +1,2 @@ pub mod create_domain; -pub mod update_domain; \ No newline at end of file +pub mod update_domain; diff --git a/src/endpoints/admin/domain/update_domain.rs b/src/endpoints/admin/domain/update_domain.rs index 20bc0dc1..9848fcc0 100644 --- a/src/endpoints/admin/domain/update_domain.rs +++ b/src/endpoints/admin/domain/update_domain.rs @@ -1,19 +1,18 @@ +use crate::models::{JWTClaims, QuestTaskDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; +use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use serde::Deserialize; -use crate::models::{QuestTaskDocument,JWTClaims}; -use crate::utils::verify_task_auth; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - pub_struct!(Deserialize; CreateTwitterFw { name: Option, @@ -27,16 +26,14 @@ pub async fn handler( headers: HeaderMap, body: Json, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("tasks"); - - let res= verify_task_auth(user, &collection,&body.id).await; - if !res{ + let res = verify_task_auth(user, &collection, &body.id).await; + if !res { return get_error("Error updating tasks".to_string()); } - // filter to get existing quest let filter = doc! { "id": &body.id, @@ -56,12 +53,8 @@ pub async fn handler( "$set": update_doc }; - // insert document to boost collection - return match collection - .find_one_and_update(filter, update, None) - .await - { + return match collection.find_one_and_update(filter, update, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "Task updated successfully"})).into_response(), diff --git a/src/endpoints/admin/nft_uri/create_uri.rs b/src/endpoints/admin/nft_uri/create_uri.rs index da369f67..1742c1c1 100644 --- a/src/endpoints/admin/nft_uri/create_uri.rs +++ b/src/endpoints/admin/nft_uri/create_uri.rs @@ -1,20 +1,19 @@ -use crate::models::{NFTUri,JWTClaims, QuestDocument}; +use crate::models::{JWTClaims, NFTUri, QuestDocument}; +use crate::utils::verify_quest_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; use mongodb::options::FindOneOptions; use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; -use axum::http::HeaderMap; -use crate::utils::verify_quest_auth; - pub_struct!(Deserialize; CreateCustom { quest_id: i64, @@ -34,8 +33,7 @@ pub async fn handler( let quests_collection = state.db.collection::("quests"); - - let res= verify_quest_auth(user, &quests_collection, &(body.quest_id as i64)).await; + let res = verify_quest_auth(user, &quests_collection, &(body.quest_id as i64)).await; if !res { return get_error("Error creating task".to_string()); }; @@ -55,19 +53,13 @@ pub async fn handler( name: body.name.clone(), description: body.desc.clone(), image: body.image.clone(), - quest_id : body.quest_id.clone() as i64, + quest_id: body.quest_id.clone() as i64, id: next_id, attributes: None, }; // insert document to boost collection - return match collection - .insert_one( - new_document, - None, - ) - .await - { + return match collection.insert_one(new_document, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "Uri created successfully"})).into_response(), diff --git a/src/endpoints/admin/nft_uri/get_nft_uri.rs b/src/endpoints/admin/nft_uri/get_nft_uri.rs index 00e68928..0c2abf5d 100644 --- a/src/endpoints/admin/nft_uri/get_nft_uri.rs +++ b/src/endpoints/admin/nft_uri/get_nft_uri.rs @@ -1,8 +1,5 @@ use crate::models::NFTUri; -use crate::{ - models::{AppState}, - utils::get_error, -}; +use crate::{models::AppState, utils::get_error}; use axum::{ extract::{Query, State}, http::StatusCode, @@ -14,16 +11,12 @@ use mongodb::bson::doc; use serde::Deserialize; use std::sync::Arc; - #[derive(Deserialize)] pub struct GetQuestsQuery { id: i64, } -#[route( - get, - "/admin/nft_uri/get_nft_uri" -)] +#[route(get, "/admin/nft_uri/get_nft_uri")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/admin/nft_uri/mod.rs b/src/endpoints/admin/nft_uri/mod.rs index 3c6a81f4..09b19cd1 100644 --- a/src/endpoints/admin/nft_uri/mod.rs +++ b/src/endpoints/admin/nft_uri/mod.rs @@ -1,3 +1,3 @@ pub mod create_uri; +pub mod get_nft_uri; pub mod update_uri; -pub mod get_nft_uri; \ No newline at end of file diff --git a/src/endpoints/admin/nft_uri/update_uri.rs b/src/endpoints/admin/nft_uri/update_uri.rs index b9a348c9..4a11fb68 100644 --- a/src/endpoints/admin/nft_uri/update_uri.rs +++ b/src/endpoints/admin/nft_uri/update_uri.rs @@ -1,18 +1,17 @@ -use crate::models::{NFTUri,JWTClaims}; +use crate::models::{JWTClaims, NFTUri}; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - pub_struct!(Deserialize; CreateCustom { id: i64, @@ -52,12 +51,8 @@ pub async fn handler( "$set": update_doc }; - // insert document to boost collection - return match collection - .find_one_and_update(filter, update, None) - .await - { + return match collection.find_one_and_update(filter, update, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "Task updated successfully"})).into_response(), diff --git a/src/endpoints/admin/quest/create_quest.rs b/src/endpoints/admin/quest/create_quest.rs index e5d7f887..e78185be 100644 --- a/src/endpoints/admin/quest/create_quest.rs +++ b/src/endpoints/admin/quest/create_quest.rs @@ -29,10 +29,7 @@ pub_struct!(Deserialize; CreateQuestQuery { issuer: Option, }); -#[route( -post, -"/admin/quest/create" -)] +#[route(post, "/admin/quest/create")] pub async fn handler( State(state): State>, headers: HeaderMap, @@ -59,10 +56,10 @@ pub async fn handler( let issuer = match user == "super_user" { true => { - let result_issuer=(&body.issuer).as_ref().unwrap(); + let result_issuer = (&body.issuer).as_ref().unwrap(); result_issuer - }, - false => &user + } + false => &user, }; let mut new_document = doc! { diff --git a/src/endpoints/admin/quest/get_quest.rs b/src/endpoints/admin/quest/get_quest.rs index f54ffc2f..283a89a3 100644 --- a/src/endpoints/admin/quest/get_quest.rs +++ b/src/endpoints/admin/quest/get_quest.rs @@ -1,7 +1,8 @@ use crate::{ - models::{AppState, QuestDocument,JWTClaims}, + models::{AppState, JWTClaims, QuestDocument}, utils::get_error, }; +use axum::http::HeaderMap; use axum::{ extract::{Query, State}, http::StatusCode, @@ -9,28 +10,23 @@ use axum::{ }; use axum_auto_routes::route; use futures::StreamExt; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use mongodb::bson::doc; use serde::Deserialize; use std::sync::Arc; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - #[derive(Deserialize)] pub struct GetQuestsQuery { id: i32, } -#[route( - get, - "/admin/quest/get_quest" -)] +#[route(get, "/admin/quest/get_quest")] pub async fn handler( State(state): State>, Query(query): Query, headers: HeaderMap, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("quests"); let mut pipeline = vec![ doc! { @@ -76,11 +72,14 @@ pub async fn handler( ]; if user != "super_user" { - pipeline.insert(1, doc! { - "$match": doc! { - "issuer": user, - } - }); + pipeline.insert( + 1, + doc! { + "$match": doc! { + "issuer": user, + } + }, + ); } match collection.aggregate(pipeline, None).await { diff --git a/src/endpoints/admin/quest/get_quests.rs b/src/endpoints/admin/quest/get_quests.rs index 1e1d961e..b981cc72 100644 --- a/src/endpoints/admin/quest/get_quests.rs +++ b/src/endpoints/admin/quest/get_quests.rs @@ -14,10 +14,7 @@ use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use mongodb::bson::{doc, from_document}; use std::sync::Arc; -#[route( - get, - "/admin/quest/get_quests" -)] +#[route(get, "/admin/quest/get_quests")] pub async fn handler(State(state): State>, headers: HeaderMap) -> impl IntoResponse { let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()); let mut pipeline = vec![]; diff --git a/src/endpoints/admin/quest/mod.rs b/src/endpoints/admin/quest/mod.rs index b6d34a69..7d39ec14 100644 --- a/src/endpoints/admin/quest/mod.rs +++ b/src/endpoints/admin/quest/mod.rs @@ -1,5 +1,5 @@ pub mod create_quest; -pub mod update_quest; +mod get_quest; pub mod get_quests; pub mod get_tasks; -mod get_quest; \ No newline at end of file +pub mod update_quest; diff --git a/src/endpoints/admin/quest/update_quest.rs b/src/endpoints/admin/quest/update_quest.rs index dbc3aca4..627b5555 100644 --- a/src/endpoints/admin/quest/update_quest.rs +++ b/src/endpoints/admin/quest/update_quest.rs @@ -1,19 +1,17 @@ -use crate::models::{QuestDocument,JWTClaims}; +use crate::models::{JWTClaims, QuestDocument}; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use mongodb::bson::{doc, Document}; +use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use serde::Deserialize; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - - pub_struct!(Deserialize; UpdateQuestQuery { id: i32, @@ -37,7 +35,7 @@ pub async fn handler( headers: HeaderMap, body: Json, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("quests"); // filter to get existing quest @@ -84,9 +82,9 @@ pub async fn handler( if let Some(rewards_img) = &body.rewards_img { update_doc.insert("rewards_img", rewards_img); let nft_reward = doc! { - "img": &body.rewards_img.clone(), - "level": 1, - }; + "img": &body.rewards_img.clone(), + "level": 1, + }; update_doc.insert("rewards_nfts", vec![nft_reward]); } if let Some(rewards_title) = &body.rewards_title { @@ -99,16 +97,12 @@ pub async fn handler( update_doc.insert("title_card", title_card); } - // update quest query let update = doc! { "$set": update_doc }; - return match collection - .find_one_and_update(filter, update, None) - .await - { + return match collection.find_one_and_update(filter, update, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "updated successfully"})), diff --git a/src/endpoints/admin/quest_boost/create_boost.rs b/src/endpoints/admin/quest_boost/create_boost.rs index c8cea914..1cd40a1c 100644 --- a/src/endpoints/admin/quest_boost/create_boost.rs +++ b/src/endpoints/admin/quest_boost/create_boost.rs @@ -1,20 +1,19 @@ -use crate::models::{BoostTable, QuestDocument,JWTClaims}; +use crate::models::{BoostTable, JWTClaims, QuestDocument}; +use crate::utils::verify_quest_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; use mongodb::options::FindOneOptions; use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use axum::http::HeaderMap; -use crate::utils::verify_quest_auth; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - #[derive(Deserialize)] pub struct CreateBoostQuery { @@ -29,21 +28,17 @@ pub struct CreateBoostQuery { img_url: String, } -#[route( - post, - "/admin/quest_boost/create_boost" -)] +#[route(post, "/admin/quest_boost/create_boost")] pub async fn handler( State(state): State>, headers: HeaderMap, body: Json, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("boosts"); let quests_collection = state.db.collection::("quests"); - - let res= verify_quest_auth(user, &quests_collection, &(body.quest_id as i64)).await; + let res = verify_quest_auth(user, &quests_collection, &(body.quest_id as i64)).await; if !res { return get_error("Error creating boost".to_string()); }; @@ -63,21 +58,18 @@ pub async fn handler( name: body.name.clone(), amount: body.amount.clone(), token_decimals: body.token_decimals.clone(), - token:body.token.clone(), + token: body.token.clone(), expiry: body.expiry.clone(), num_of_winners: body.num_of_winners.clone(), quests: vec![body.quest_id.clone()], id: next_id, hidden: body.hidden.clone(), img_url: body.img_url.clone(), - winner:None, + winner: None, }; // insert document to boost collection - return match collection - .insert_one(new_document, None) - .await - { + return match collection.insert_one(new_document, None).await { Ok(_) => ( StatusCode::OK, Json(json!({"message": "Boost created successfully"})).into_response(), diff --git a/src/endpoints/admin/quest_boost/mod.rs b/src/endpoints/admin/quest_boost/mod.rs index 0831f03c..5b1910ad 100644 --- a/src/endpoints/admin/quest_boost/mod.rs +++ b/src/endpoints/admin/quest_boost/mod.rs @@ -1,2 +1,2 @@ +pub mod create_boost; pub mod update_boost; -pub mod create_boost; \ No newline at end of file diff --git a/src/endpoints/admin/quest_boost/update_boost.rs b/src/endpoints/admin/quest_boost/update_boost.rs index 92dc074e..fea7eac2 100644 --- a/src/endpoints/admin/quest_boost/update_boost.rs +++ b/src/endpoints/admin/quest_boost/update_boost.rs @@ -27,10 +27,7 @@ pub_struct!(Deserialize; UpdateBoostQuery { hidden: Option, }); -#[route( -post, -"/admin/quest_boost/update_boost" -)] +#[route(post, "/admin/quest_boost/update_boost")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/quiz/create_question.rs b/src/endpoints/admin/quiz/create_question.rs index a1c50410..2fdd0dde 100644 --- a/src/endpoints/admin/quiz/create_question.rs +++ b/src/endpoints/admin/quiz/create_question.rs @@ -1,4 +1,6 @@ -use crate::models::{JWTClaims, QuestDocument, QuestTaskDocument, QuizInsertDocument, QuizQuestionDocument}; +use crate::models::{ + JWTClaims, QuestDocument, QuestTaskDocument, QuizInsertDocument, QuizQuestionDocument, +}; use crate::utils::verify_quest_auth; use crate::{models::AppState, utils::get_error}; use axum::http::HeaderMap; @@ -22,10 +24,7 @@ pub_struct!(Deserialize; CreateQuizQuestion { correct_answers: Vec, }); -#[route( - post, - "/admin/tasks/quiz/question/create" -)] +#[route(post, "/admin/tasks/quiz/question/create")] pub async fn handler( State(state): State>, headers: HeaderMap, @@ -39,7 +38,6 @@ pub async fn handler( let quests_collection = state.db.collection::("quests"); let tasks_collection = state.db.collection::("tasks"); - let pipeline = doc! { "quiz_name": &body.quiz_id, }; diff --git a/src/endpoints/admin/quiz/create_quiz.rs b/src/endpoints/admin/quiz/create_quiz.rs index 7e7a50b0..9e8f64e8 100644 --- a/src/endpoints/admin/quiz/create_quiz.rs +++ b/src/endpoints/admin/quiz/create_quiz.rs @@ -24,10 +24,7 @@ pub_struct!(Deserialize; CreateQuiz { quest_id: i64, }); -#[route( - post, - "/admin/tasks/quiz/create" -)] +#[route(post, "/admin/tasks/quiz/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/quiz/get_quiz.rs b/src/endpoints/admin/quiz/get_quiz.rs index e505fe54..b0e95a70 100644 --- a/src/endpoints/admin/quiz/get_quiz.rs +++ b/src/endpoints/admin/quiz/get_quiz.rs @@ -1,8 +1,6 @@ -use crate::models::{QuizInsertDocument,JWTClaims}; -use crate::{ - models::{AppState}, - utils::get_error, -}; +use crate::models::{JWTClaims, QuizInsertDocument}; +use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::{Query, State}, http::StatusCode, @@ -10,26 +8,21 @@ use axum::{ }; use axum_auto_routes::route; use futures::StreamExt; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use mongodb::bson::doc; use serde::Deserialize; use std::sync::Arc; -use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; -use axum::http::HeaderMap; - #[derive(Deserialize)] pub struct GetQuestsQuery { id: i64, } -#[route( - get, - "/admin/quiz/get_quiz" -)] +#[route(get, "/admin/quiz/get_quiz")] pub async fn handler( State(state): State>, Query(query): Query, - headers: HeaderMap + headers: HeaderMap, ) -> impl IntoResponse { let _user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()); let collection = state.db.collection::("quizzes"); diff --git a/src/endpoints/admin/quiz/mod.rs b/src/endpoints/admin/quiz/mod.rs index 8def435c..566f55e8 100644 --- a/src/endpoints/admin/quiz/mod.rs +++ b/src/endpoints/admin/quiz/mod.rs @@ -1,5 +1,5 @@ -pub mod create_quiz; pub mod create_question; -pub mod update_quiz; +pub mod create_quiz; +pub mod get_quiz; pub mod update_question; -pub mod get_quiz; \ No newline at end of file +pub mod update_quiz; diff --git a/src/endpoints/admin/quiz/update_question.rs b/src/endpoints/admin/quiz/update_question.rs index b05ad61c..684e152e 100644 --- a/src/endpoints/admin/quiz/update_question.rs +++ b/src/endpoints/admin/quiz/update_question.rs @@ -25,10 +25,7 @@ pub_struct!(Deserialize; UpdateQuiz { correct_answers: Option>, }); -#[route( - post, - "/admin/tasks/quiz/question/update" -)] +#[route(post, "/admin/tasks/quiz/question/update")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/quiz/update_quiz.rs b/src/endpoints/admin/quiz/update_quiz.rs index 0b4c7478..b2db5e96 100644 --- a/src/endpoints/admin/quiz/update_quiz.rs +++ b/src/endpoints/admin/quiz/update_quiz.rs @@ -1,21 +1,20 @@ +use crate::models::{JWTClaims, QuestTaskDocument, QuizInsertDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use mongodb::bson::{doc}; -use mongodb::options::{FindOneAndUpdateOptions}; -use serde_json::json; -use std::sync::Arc; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +use mongodb::bson::doc; use mongodb::bson::Document; +use mongodb::options::FindOneAndUpdateOptions; use serde::Deserialize; -use crate::models::{QuestTaskDocument, JWTClaims, QuizInsertDocument}; -use axum::http::HeaderMap; -use crate::utils::verify_task_auth; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - +use serde_json::json; +use std::sync::Arc; pub_struct!(Deserialize; UpdateQuiz { id:u32, @@ -33,13 +32,12 @@ pub async fn handler( headers: HeaderMap, body: Json, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let tasks_collection = state.db.collection::("tasks"); let quiz_collection = state.db.collection::("quizzes"); - - let res= verify_task_auth(user, &tasks_collection,&(body.id as i32)).await; - if !res{ + let res = verify_task_auth(user, &tasks_collection, &(body.id as i32)).await; + if !res { return get_error("Error updating tasks".to_string()); } @@ -47,7 +45,10 @@ pub async fn handler( let filter = doc! { "id": &body.quiz_id, }; - let existing_quiz = &quiz_collection.find_one(filter.clone(), None).await.unwrap(); + let existing_quiz = &quiz_collection + .find_one(filter.clone(), None) + .await + .unwrap(); // create a quiz if it does not exist if existing_quiz.is_none() { @@ -83,7 +84,6 @@ pub async fn handler( Err(_e) => get_error("error updating task".to_string()), }; - let mut update_doc = Document::new(); if let Some(name) = &body.name { diff --git a/src/endpoints/admin/twitter/create_twitter_fw.rs b/src/endpoints/admin/twitter/create_twitter_fw.rs index 4d61ef93..0f60caf6 100644 --- a/src/endpoints/admin/twitter/create_twitter_fw.rs +++ b/src/endpoints/admin/twitter/create_twitter_fw.rs @@ -22,10 +22,7 @@ pub_struct!(Deserialize; CreateTwitterFw { quest_id: i64, }); -#[route( - post, - "/admin/tasks/twitter_fw/create" -)] +#[route(post, "/admin/tasks/twitter_fw/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/twitter/create_twitter_rw.rs b/src/endpoints/admin/twitter/create_twitter_rw.rs index 7832f8fa..3e3d071d 100644 --- a/src/endpoints/admin/twitter/create_twitter_rw.rs +++ b/src/endpoints/admin/twitter/create_twitter_rw.rs @@ -22,10 +22,7 @@ pub_struct!(Deserialize; CreateTwitterRw { quest_id: i64, }); -#[route( - post, - "/admin/tasks/twitter_rw/create" -)] +#[route(post, "/admin/tasks/twitter_rw/create")] pub async fn handler( State(state): State>, headers: HeaderMap, diff --git a/src/endpoints/admin/twitter/mod.rs b/src/endpoints/admin/twitter/mod.rs index afeabf69..0452090c 100644 --- a/src/endpoints/admin/twitter/mod.rs +++ b/src/endpoints/admin/twitter/mod.rs @@ -1,4 +1,4 @@ pub mod create_twitter_fw; pub mod create_twitter_rw; pub mod update_twitter_fw; -pub mod update_twitter_rw; \ No newline at end of file +pub mod update_twitter_rw; diff --git a/src/endpoints/admin/twitter/update_twitter_fw.rs b/src/endpoints/admin/twitter/update_twitter_fw.rs index 670cb8ae..e4db13b3 100644 --- a/src/endpoints/admin/twitter/update_twitter_fw.rs +++ b/src/endpoints/admin/twitter/update_twitter_fw.rs @@ -1,19 +1,19 @@ -use crate::models::{QuestTaskDocument,JWTClaims}; +use crate::models::{JWTClaims, QuestTaskDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use mongodb::bson::{doc, Document}; use mongodb::options::FindOneAndUpdateOptions; use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use crate::utils::verify_task_auth; -use axum::http::HeaderMap; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; pub_struct!(Deserialize; UpdateTwitterFw { name: Option, @@ -22,10 +22,7 @@ pub_struct!(Deserialize; UpdateTwitterFw { id: i32, }); -#[route( -post, -"/admin/tasks/twitter_fw/update" -)] +#[route(post, "/admin/tasks/twitter_fw/update")] pub async fn handler( State(state): State>, headers: HeaderMap, @@ -35,8 +32,8 @@ pub async fn handler( let collection = state.db.collection::("tasks"); - let res= verify_task_auth(user, &collection,&body.id).await; - if !res{ + let res = verify_task_auth(user, &collection, &body.id).await; + if !res { return get_error("Error updating tasks".to_string()); } diff --git a/src/endpoints/admin/twitter/update_twitter_rw.rs b/src/endpoints/admin/twitter/update_twitter_rw.rs index a7007146..b3088e0c 100644 --- a/src/endpoints/admin/twitter/update_twitter_rw.rs +++ b/src/endpoints/admin/twitter/update_twitter_rw.rs @@ -1,20 +1,19 @@ +use crate::models::{JWTClaims, QuestTaskDocument}; +use crate::utils::verify_task_auth; use crate::{models::AppState, utils::get_error}; +use axum::http::HeaderMap; use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Json}, }; use axum_auto_routes::route; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use mongodb::bson::{doc, Document}; -use mongodb::options::{FindOneAndUpdateOptions}; +use mongodb::options::FindOneAndUpdateOptions; +use serde::Deserialize; use serde_json::json; use std::sync::Arc; -use serde::Deserialize; -use crate::models::{QuestTaskDocument,JWTClaims}; -use axum::http::HeaderMap; -use crate::utils::verify_task_auth; -use jsonwebtoken::{Validation,Algorithm,decode,DecodingKey}; - pub_struct!(Deserialize; UpdateTwitterRw { name: Option, @@ -29,16 +28,14 @@ pub async fn handler( headers: HeaderMap, body: Json, ) -> impl IntoResponse { - let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; + let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String; let collection = state.db.collection::("tasks"); - - let res= verify_task_auth(user, &collection,&body.id).await; - if !res{ + let res = verify_task_auth(user, &collection, &body.id).await; + if !res { return get_error("Error updating tasks".to_string()); } - // filter to get existing boost let filter = doc! { "id": &body.id, diff --git a/src/endpoints/admin/user/mod.rs b/src/endpoints/admin/user/mod.rs index ec60cd9f..8ea6fc47 100644 --- a/src/endpoints/admin/user/mod.rs +++ b/src/endpoints/admin/user/mod.rs @@ -1 +1 @@ -pub mod create_user; \ No newline at end of file +pub mod create_user; diff --git a/src/endpoints/analytics/get_quest_activity.rs b/src/endpoints/analytics/get_quest_activity.rs index 00bc1124..3dbc71b8 100644 --- a/src/endpoints/analytics/get_quest_activity.rs +++ b/src/endpoints/analytics/get_quest_activity.rs @@ -16,10 +16,7 @@ pub struct GetQuestsQuery { id: u32, } -#[route( -get, -"/analytics/get_quest_activity" -)] +#[route(get, "/analytics/get_quest_activity")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/analytics/get_quest_participation.rs b/src/endpoints/analytics/get_quest_participation.rs index ed3d9fd5..e842fa41 100644 --- a/src/endpoints/analytics/get_quest_participation.rs +++ b/src/endpoints/analytics/get_quest_participation.rs @@ -16,10 +16,7 @@ pub struct GetQuestsQuery { id: u32, } -#[route( - get, - "/analytics/get_quest_participation" -)] +#[route(get, "/analytics/get_quest_participation")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/analytics/get_unique_visitors.rs b/src/endpoints/analytics/get_unique_visitors.rs index 1730d421..16e6b9c7 100644 --- a/src/endpoints/analytics/get_unique_visitors.rs +++ b/src/endpoints/analytics/get_unique_visitors.rs @@ -16,10 +16,7 @@ pub struct GetQuestsQuery { id: u32, } -#[route( -get, -"/analytics/get_unique_visitors" -)] +#[route(get, "/analytics/get_unique_visitors")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/analytics/mod.rs b/src/endpoints/analytics/mod.rs index e809e03e..f6c01233 100644 --- a/src/endpoints/analytics/mod.rs +++ b/src/endpoints/analytics/mod.rs @@ -1,3 +1,3 @@ pub mod get_quest_activity; pub mod get_quest_participation; -pub mod get_unique_visitors; \ No newline at end of file +pub mod get_unique_visitors; diff --git a/src/endpoints/discover/defi/get_alt_protocol_stats.rs b/src/endpoints/discover/defi/get_alt_protocol_stats.rs index 23bcb0ca..253db58a 100644 --- a/src/endpoints/discover/defi/get_alt_protocol_stats.rs +++ b/src/endpoints/discover/defi/get_alt_protocol_stats.rs @@ -1,7 +1,4 @@ -use crate::{ - models::{AppState}, - utils::get_error, -}; +use crate::{models::AppState, utils::get_error}; use axum::{ extract::State, http::StatusCode, @@ -9,9 +6,9 @@ use axum::{ }; use axum_auto_routes::route; use mongodb::bson::doc; +use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; -use serde_json::Value; #[route(get, "/discover/defi/get_alt_protocol_stats")] pub async fn handler(State(state): State>) -> impl IntoResponse { @@ -46,7 +43,7 @@ pub async fn handler(State(state): State>) -> impl IntoResponse { return (StatusCode::OK, Json(new_map)).into_response(); } Err(_) => get_error(format!("Try again later")), - } + }, Err(_) => get_error(format!("Try again later")), }; diff --git a/src/endpoints/discover/defi/get_derivatives_stats.rs b/src/endpoints/discover/defi/get_derivatives_stats.rs index 0ed6e369..1bf5f977 100644 --- a/src/endpoints/discover/defi/get_derivatives_stats.rs +++ b/src/endpoints/discover/defi/get_derivatives_stats.rs @@ -1,7 +1,4 @@ -use crate::{ - models::{AppState}, - utils::get_error, -}; +use crate::{models::AppState, utils::get_error}; use axum::{ extract::State, http::StatusCode, @@ -9,9 +6,9 @@ use axum::{ }; use axum_auto_routes::route; use mongodb::bson::doc; +use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; -use serde_json::Value; #[route(get, "/discover/defi/get_derivatives_stats")] pub async fn handler(State(state): State>) -> impl IntoResponse { @@ -38,7 +35,7 @@ pub async fn handler(State(state): State>) -> impl IntoResponse { return (StatusCode::OK, Json(new_map)).into_response(); } Err(_) => get_error(format!("Try again later")), - } + }, Err(_) => get_error(format!("Try again later")), }; diff --git a/src/endpoints/discover/defi/get_lend_stats.rs b/src/endpoints/discover/defi/get_lend_stats.rs index eb23ae3d..81df0644 100644 --- a/src/endpoints/discover/defi/get_lend_stats.rs +++ b/src/endpoints/discover/defi/get_lend_stats.rs @@ -1,7 +1,4 @@ -use crate::{ - models::{AppState}, - utils::get_error, -}; +use crate::{models::AppState, utils::get_error}; use axum::{ extract::State, http::StatusCode, @@ -9,9 +6,9 @@ use axum::{ }; use axum_auto_routes::route; use mongodb::bson::doc; +use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; -use serde_json::Value; #[route(get, "/discover/defi/get_lend_stats")] pub async fn handler(State(state): State>) -> impl IntoResponse { @@ -46,7 +43,7 @@ pub async fn handler(State(state): State>) -> impl IntoResponse { return (StatusCode::OK, Json(new_map)).into_response(); } Err(_) => get_error(format!("Try again later")), - } + }, Err(_) => get_error(format!("Try again later")), }; diff --git a/src/endpoints/discover/defi/get_pair_stats.rs b/src/endpoints/discover/defi/get_pair_stats.rs index 7e79dc49..9c34083e 100644 --- a/src/endpoints/discover/defi/get_pair_stats.rs +++ b/src/endpoints/discover/defi/get_pair_stats.rs @@ -1,7 +1,4 @@ -use crate::{ - models::{AppState}, - utils::get_error, -}; +use crate::{models::AppState, utils::get_error}; use axum::{ extract::State, http::StatusCode, @@ -9,9 +6,9 @@ use axum::{ }; use axum_auto_routes::route; use mongodb::bson::doc; +use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; -use serde_json::Value; #[route(get, "/discover/defi/get_pair_stats")] pub async fn handler(State(state): State>) -> impl IntoResponse { @@ -46,7 +43,7 @@ pub async fn handler(State(state): State>) -> impl IntoResponse { return (StatusCode::OK, Json(new_map)).into_response(); } Err(_) => get_error(format!("Try again later")), - } + }, Err(_) => get_error(format!("Try again later")), }; diff --git a/src/endpoints/discover/defi/mod.rs b/src/endpoints/discover/defi/mod.rs index c635a4f1..6d7803b8 100644 --- a/src/endpoints/discover/defi/mod.rs +++ b/src/endpoints/discover/defi/mod.rs @@ -1,4 +1,4 @@ -pub mod get_pair_stats; -pub mod get_lend_stats; +pub mod get_alt_protocol_stats; pub mod get_derivatives_stats; -pub mod get_alt_protocol_stats; \ No newline at end of file +pub mod get_lend_stats; +pub mod get_pair_stats; diff --git a/src/endpoints/discover/mod.rs b/src/endpoints/discover/mod.rs index e5a7941d..a406628f 100644 --- a/src/endpoints/discover/mod.rs +++ b/src/endpoints/discover/mod.rs @@ -1 +1 @@ -pub mod defi; \ No newline at end of file +pub mod defi; diff --git a/src/endpoints/get_quiz.rs b/src/endpoints/get_quiz.rs index f8e0a6e9..9cc77928 100644 --- a/src/endpoints/get_quiz.rs +++ b/src/endpoints/get_quiz.rs @@ -5,9 +5,9 @@ use axum::{ response::{IntoResponse, Json}, }; use axum_auto_routes::route; -use futures::{StreamExt}; +use futures::StreamExt; use mongodb::bson::{doc, Document}; -use serde::{Deserialize}; +use serde::Deserialize; use starknet::core::types::FieldElement; use std::sync::Arc; @@ -20,7 +20,6 @@ pub struct GetQuizQuery { addr: FieldElement, } - #[route(get, "/get_quiz")] pub async fn handler( State(state): State>, diff --git a/src/endpoints/leaderboard/get_ranking.rs b/src/endpoints/leaderboard/get_ranking.rs index 0fae00b8..7a21dbed 100644 --- a/src/endpoints/leaderboard/get_ranking.rs +++ b/src/endpoints/leaderboard/get_ranking.rs @@ -235,27 +235,16 @@ pub struct GetCompletedQuestsQuery { duration: String, } -#[route( - get, - "/leaderboard/get_ranking" -)] +#[route(get, "/leaderboard/get_ranking")] pub async fn handler( State(state): State>, Query(query): Query, ) -> impl IntoResponse { - - // check value of duration and set time_gap accordingly using match and respective timestamp let time_gap = match query.duration.as_str() { - "week" => { - get_timestamp_from_days(7) - } - "month" => { - get_timestamp_from_days(30) - } - "all" => { - 0 - } + "week" => get_timestamp_from_days(7), + "month" => get_timestamp_from_days(30), + "all" => 0, _ => { return get_error("Invalid duration".to_string()); } diff --git a/src/endpoints/leaderboard/get_static_info.rs b/src/endpoints/leaderboard/get_static_info.rs index a9901f15..8e6fa5ce 100644 --- a/src/endpoints/leaderboard/get_static_info.rs +++ b/src/endpoints/leaderboard/get_static_info.rs @@ -34,10 +34,7 @@ pub struct GetLeaderboardInfoQuery { duration: String, } -#[route( - get, - "/leaderboard/get_static_info" -)] +#[route(get, "/leaderboard/get_static_info")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/leaderboard/mod.rs b/src/endpoints/leaderboard/mod.rs index b0d78038..6b8c0306 100644 --- a/src/endpoints/leaderboard/mod.rs +++ b/src/endpoints/leaderboard/mod.rs @@ -1,2 +1,2 @@ +pub mod get_ranking; pub mod get_static_info; -pub mod get_ranking; \ No newline at end of file diff --git a/src/endpoints/mod.rs b/src/endpoints/mod.rs index 0fc6f2eb..08822929 100644 --- a/src/endpoints/mod.rs +++ b/src/endpoints/mod.rs @@ -1,4 +1,8 @@ pub mod achievements; +pub mod admin; +pub mod analytics; +pub mod discover; +pub mod get_boosted_quests; pub mod get_completed_quests; pub mod get_deployed_time; pub mod get_quest; @@ -12,8 +16,4 @@ pub mod has_completed_quest; pub mod leaderboard; pub mod quest_boost; pub mod quests; -pub mod get_boosted_quests; -pub mod analytics; pub mod unique_page_visit; -pub mod admin; -pub mod discover; \ No newline at end of file diff --git a/src/endpoints/quest_boost/get_claim_params.rs b/src/endpoints/quest_boost/get_claim_params.rs index 5f16f8d5..c738b895 100644 --- a/src/endpoints/quest_boost/get_claim_params.rs +++ b/src/endpoints/quest_boost/get_claim_params.rs @@ -22,10 +22,7 @@ pub struct GetClaimBoostQuery { addr: FieldElement, } -#[route( - get, - "/boost/get_claim_params" -)] +#[route(get, "/boost/get_claim_params")] pub async fn handler( State(state): State>, Query(query): Query, @@ -46,10 +43,11 @@ pub async fn handler( let boost: Document = res.unwrap(); let num_of_winners = boost.get("num_of_winners").unwrap().as_i32().unwrap(); let decimals = boost.get("token_decimals").unwrap().as_i32().unwrap(); - let amount: u128 = boost.get("amount").unwrap().as_i32().unwrap() as u128 * 10u128.pow(decimals as u32); + let amount: u128 = + boost.get("amount").unwrap().as_i32().unwrap() as u128 * 10u128.pow(decimals as u32); let modified_amount = amount / num_of_winners as u128; let token = boost.get("token").unwrap().as_str().unwrap(); - + let winner_list = boost.get("winner").unwrap().as_array().unwrap(); let bson_value: Bson = Bson::String(address.clone()); diff --git a/src/endpoints/quest_boost/get_completed_boosts.rs b/src/endpoints/quest_boost/get_completed_boosts.rs index 0ab37027..62a9619e 100644 --- a/src/endpoints/quest_boost/get_completed_boosts.rs +++ b/src/endpoints/quest_boost/get_completed_boosts.rs @@ -19,10 +19,7 @@ pub struct GetCompletedQuestsQuery { addr: FieldElement, } -#[route( - get, - "/boost/get_completed_boosts" -)] +#[route(get, "/boost/get_completed_boosts")] pub async fn handler( State(state): State>, Query(query): Query, diff --git a/src/endpoints/quest_boost/get_pending_claims.rs b/src/endpoints/quest_boost/get_pending_claims.rs index 0a1f760b..a137fabd 100644 --- a/src/endpoints/quest_boost/get_pending_claims.rs +++ b/src/endpoints/quest_boost/get_pending_claims.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use crate::utils::to_hex; use crate::{ models::{AppState, QuestDocument}, @@ -20,14 +22,13 @@ pub struct GetQuestsQuery { addr: FieldElement, } -#[route( - get, - "/boost/get_pending_claims" -)] +#[route(get, "/boost/get_pending_claims")] pub async fn handler( State(state): State>, Query(query): Query, ) -> impl IntoResponse { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let address = to_hex(query.addr); let collection = state.db.collection::("boosts"); let pipeline = [ @@ -114,7 +115,7 @@ pub async fn handler( return (StatusCode::OK, Json(res)).into_response(); } Err(e) => { - println!("Error querying claims: {}", e); + logger.info(format!("Error querying claims: {}", e)); get_error("Error querying claims".to_string()) } } diff --git a/src/endpoints/quests/avnu/discord_fw_callback.rs b/src/endpoints/quests/avnu/discord_fw_callback.rs index b18f55b5..a3ad7491 100644 --- a/src/endpoints/quests/avnu/discord_fw_callback.rs +++ b/src/endpoints/quests/avnu/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/bountive/mod.rs b/src/endpoints/quests/bountive/mod.rs index 80e5c8bb..7032666a 100644 --- a/src/endpoints/quests/bountive/mod.rs +++ b/src/endpoints/quests/bountive/mod.rs @@ -1,4 +1,4 @@ +pub mod claimable; +pub mod verify_deposit; pub mod verify_twitter_fw; pub mod verify_twitter_rt; -pub mod verify_deposit; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/braavos/carbonable/mod.rs b/src/endpoints/quests/braavos/carbonable/mod.rs index 79f2451a..34cc778b 100644 --- a/src/endpoints/quests/braavos/carbonable/mod.rs +++ b/src/endpoints/quests/braavos/carbonable/mod.rs @@ -1,6 +1,6 @@ +pub mod claimable; +pub mod verify_deposit; pub mod verify_has_domain; pub mod verify_twitter_fw_braavos; pub mod verify_twitter_fw_carbonable; pub mod verify_twitter_rt; -pub mod verify_deposit; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/braavos/mod.rs b/src/endpoints/quests/braavos/mod.rs index 09d9b5dc..a924aa7a 100644 --- a/src/endpoints/quests/braavos/mod.rs +++ b/src/endpoints/quests/braavos/mod.rs @@ -1,8 +1,8 @@ pub mod avnu; +pub mod carbonable; pub mod myswap; +pub mod pyramid; +pub mod realms; pub mod starknetid; pub mod wallet; -pub mod pyramid; pub mod zklend; -pub mod realms; -pub mod carbonable; diff --git a/src/endpoints/quests/braavos/pyramid/mod.rs b/src/endpoints/quests/braavos/pyramid/mod.rs index 01850705..4f1bb9b8 100644 --- a/src/endpoints/quests/braavos/pyramid/mod.rs +++ b/src/endpoints/quests/braavos/pyramid/mod.rs @@ -1,6 +1,6 @@ +pub mod claimable; +pub mod verify_buy_or_list; pub mod verify_has_domain; pub mod verify_twitter_fw_braavos; pub mod verify_twitter_fw_pyramid; pub mod verify_twitter_rt; -pub mod verify_buy_or_list; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/braavos/realms/mod.rs b/src/endpoints/quests/braavos/realms/mod.rs index f22aeccc..08febda1 100644 --- a/src/endpoints/quests/braavos/realms/mod.rs +++ b/src/endpoints/quests/braavos/realms/mod.rs @@ -1,6 +1,6 @@ pub mod claimable; pub mod verify_has_domain; pub mod verify_has_played; -pub mod verify_twitter_fw_realms; pub mod verify_twitter_fw_braavos; +pub mod verify_twitter_fw_realms; pub mod verify_twitter_rt; diff --git a/src/endpoints/quests/braavos/starknetid/verify_has_mission.rs b/src/endpoints/quests/braavos/starknetid/verify_has_mission.rs index 64b96921..c795465e 100644 --- a/src/endpoints/quests/braavos/starknetid/verify_has_mission.rs +++ b/src/endpoints/quests/braavos/starknetid/verify_has_mission.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use crate::{ models::AppState, utils::{get_error, get_error_redirect, success_redirect, CompletedTasksTrait}, @@ -199,6 +201,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -209,10 +213,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/braavos/zklend/mod.rs b/src/endpoints/quests/braavos/zklend/mod.rs index dbfec14d..1eb4a8cf 100644 --- a/src/endpoints/quests/braavos/zklend/mod.rs +++ b/src/endpoints/quests/braavos/zklend/mod.rs @@ -1,6 +1,6 @@ +pub mod claimable; +pub mod verify_added_liquidity; pub mod verify_has_domain; pub mod verify_twitter_fw_braavos; pub mod verify_twitter_fw_zklend; pub mod verify_twitter_rt; -pub mod verify_added_liquidity; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/discord_fw_callback.rs b/src/endpoints/quests/discord_fw_callback.rs index ff6e69e3..80eed6ae 100644 --- a/src/endpoints/quests/discord_fw_callback.rs +++ b/src/endpoints/quests/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::models::QuestTaskDocument; @@ -34,6 +36,8 @@ pub async fn handler( State(state): State>, Query(query): Query, ) -> impl IntoResponse { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); // the state is in format => "address+quest_id+task_id" let state_split = query.state.split('+').collect::>(); let quest_id = state_split[1].parse::().unwrap(); @@ -115,7 +119,7 @@ pub async fn handler( for guild in response { if guild.id == guild_id { - print!("Checking guild: {:?}", guild); + logger.info(format!("Checking guild: {:?}", guild)); match state.upsert_completed_task(addr, task_id).await { Ok(_) => { let redirect_uri = format!( diff --git a/src/endpoints/quests/ekubo/discord_fw_callback.rs b/src/endpoints/quests/ekubo/discord_fw_callback.rs index b5e41e23..bef349bd 100644 --- a/src/endpoints/quests/ekubo/discord_fw_callback.rs +++ b/src/endpoints/quests/ekubo/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/ekubo/mod.rs b/src/endpoints/quests/ekubo/mod.rs index 2e450cc6..57eade9b 100644 --- a/src/endpoints/quests/ekubo/mod.rs +++ b/src/endpoints/quests/ekubo/mod.rs @@ -1,3 +1,3 @@ pub mod claimable; pub mod discord_fw_callback; -pub mod verify_added_liquidity; \ No newline at end of file +pub mod verify_added_liquidity; diff --git a/src/endpoints/quests/focustree/engagement/discord_fw_callback.rs b/src/endpoints/quests/focustree/engagement/discord_fw_callback.rs index 847b9004..b41cd120 100644 --- a/src/endpoints/quests/focustree/engagement/discord_fw_callback.rs +++ b/src/endpoints/quests/focustree/engagement/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/focustree/engagement/mod.rs b/src/endpoints/quests/focustree/engagement/mod.rs index 620ad0a1..8de7b0db 100644 --- a/src/endpoints/quests/focustree/engagement/mod.rs +++ b/src/endpoints/quests/focustree/engagement/mod.rs @@ -1,2 +1,2 @@ pub mod discord_fw_callback; -pub mod verify_twitter_rt; \ No newline at end of file +pub mod verify_twitter_rt; diff --git a/src/endpoints/quests/focustree/introduction/mod.rs b/src/endpoints/quests/focustree/introduction/mod.rs index 833b55d5..4861397e 100644 --- a/src/endpoints/quests/focustree/introduction/mod.rs +++ b/src/endpoints/quests/focustree/introduction/mod.rs @@ -1,3 +1,3 @@ pub mod claimable; pub mod verify_twitter_fw; -pub mod verify_twitter_rt; \ No newline at end of file +pub mod verify_twitter_rt; diff --git a/src/endpoints/quests/focustree/mod.rs b/src/endpoints/quests/focustree/mod.rs index 1cc5ce78..ddfa854f 100644 --- a/src/endpoints/quests/focustree/mod.rs +++ b/src/endpoints/quests/focustree/mod.rs @@ -1,2 +1,2 @@ -pub mod introduction; pub mod engagement; +pub mod introduction; diff --git a/src/endpoints/quests/haiko/mod.rs b/src/endpoints/quests/haiko/mod.rs index 26278749..9c2d3d63 100644 --- a/src/endpoints/quests/haiko/mod.rs +++ b/src/endpoints/quests/haiko/mod.rs @@ -1,4 +1,4 @@ +pub mod claimable; pub mod verify_deposit; pub mod verify_twitter_fw; pub mod verify_twitter_rw; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/hashstack/discord_fw_callback.rs b/src/endpoints/quests/hashstack/discord_fw_callback.rs index 20e91ee9..6eb5d685 100644 --- a/src/endpoints/quests/hashstack/discord_fw_callback.rs +++ b/src/endpoints/quests/hashstack/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -122,6 +124,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 6], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -132,10 +136,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/hashstack/mod.rs b/src/endpoints/quests/hashstack/mod.rs index 3eedf6d3..21e6ea7d 100644 --- a/src/endpoints/quests/hashstack/mod.rs +++ b/src/endpoints/quests/hashstack/mod.rs @@ -1,6 +1,6 @@ pub mod claimable; pub mod discord_fw_callback; +pub mod verify_deposit; pub mod verify_has_domain; pub mod verify_twitter_fw_hashstack; pub mod verify_twitter_rw; -pub mod verify_deposit; \ No newline at end of file diff --git a/src/endpoints/quests/influence/discord_fw_callback.rs b/src/endpoints/quests/influence/discord_fw_callback.rs index b1e0731f..4cb09256 100644 --- a/src/endpoints/quests/influence/discord_fw_callback.rs +++ b/src/endpoints/quests/influence/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -122,6 +124,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 6], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -132,10 +136,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/influence/mod.rs b/src/endpoints/quests/influence/mod.rs index fed40de5..7eadb3c3 100644 --- a/src/endpoints/quests/influence/mod.rs +++ b/src/endpoints/quests/influence/mod.rs @@ -1,5 +1,5 @@ +pub mod claimable; pub mod discord_fw_callback; pub mod verify_twitter_fw; pub mod verify_twitter_rw; pub mod verify_twitter_rw_2; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/myswap/discord_fw_callback.rs b/src/endpoints/quests/myswap/discord_fw_callback.rs index 238acab9..6fe131f2 100644 --- a/src/endpoints/quests/myswap/discord_fw_callback.rs +++ b/src/endpoints/quests/myswap/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/nimbora/discord_fw_callback.rs b/src/endpoints/quests/nimbora/discord_fw_callback.rs index 9682e3ce..fb470697 100644 --- a/src/endpoints/quests/nimbora/discord_fw_callback.rs +++ b/src/endpoints/quests/nimbora/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -123,6 +125,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 6], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -133,10 +137,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/nostra/liquidity_quest/discord_fw_callback.rs b/src/endpoints/quests/nostra/liquidity_quest/discord_fw_callback.rs index 6b16b3fa..f835772a 100644 --- a/src/endpoints/quests/nostra/liquidity_quest/discord_fw_callback.rs +++ b/src/endpoints/quests/nostra/liquidity_quest/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/nostra/mod.rs b/src/endpoints/quests/nostra/mod.rs index 0de6c9b1..a41ba93b 100644 --- a/src/endpoints/quests/nostra/mod.rs +++ b/src/endpoints/quests/nostra/mod.rs @@ -1,2 +1,2 @@ pub mod liquidity_quest; -pub mod staking_quest; \ No newline at end of file +pub mod staking_quest; diff --git a/src/endpoints/quests/nostra/staking_quest/mod.rs b/src/endpoints/quests/nostra/staking_quest/mod.rs index 934bddc0..3bf138cf 100644 --- a/src/endpoints/quests/nostra/staking_quest/mod.rs +++ b/src/endpoints/quests/nostra/staking_quest/mod.rs @@ -1,3 +1,3 @@ pub mod claimable; -pub mod verify_twitter_tw; pub mod verify_stake; +pub mod verify_twitter_tw; diff --git a/src/endpoints/quests/rango/mod.rs b/src/endpoints/quests/rango/mod.rs index 51892a08..f5418bf7 100644 --- a/src/endpoints/quests/rango/mod.rs +++ b/src/endpoints/quests/rango/mod.rs @@ -1,2 +1,2 @@ pub mod quest1; -pub mod quest2; \ No newline at end of file +pub mod quest2; diff --git a/src/endpoints/quests/rango/quest1/discord_fw_callback.rs b/src/endpoints/quests/rango/quest1/discord_fw_callback.rs index e69e6c36..44f99bd9 100644 --- a/src/endpoints/quests/rango/quest1/discord_fw_callback.rs +++ b/src/endpoints/quests/rango/quest1/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/rango/quest1/mod.rs b/src/endpoints/quests/rango/quest1/mod.rs index 7d2a4c2e..25b51beb 100644 --- a/src/endpoints/quests/rango/quest1/mod.rs +++ b/src/endpoints/quests/rango/quest1/mod.rs @@ -1,4 +1,4 @@ pub mod check_trade; pub mod claimable; pub mod discord_fw_callback; -pub mod verify_twitter_fw; \ No newline at end of file +pub mod verify_twitter_fw; diff --git a/src/endpoints/quests/rango/quest2/discord_fw_callback.rs b/src/endpoints/quests/rango/quest2/discord_fw_callback.rs index 1c59db12..4dc6a7f7 100644 --- a/src/endpoints/quests/rango/quest2/discord_fw_callback.rs +++ b/src/endpoints/quests/rango/quest2/discord_fw_callback.rs @@ -1,3 +1,5 @@ +use crate::config; +use crate::logger::Logger; use std::sync::Arc; use crate::utils::CompletedTasksTrait; @@ -121,6 +123,8 @@ pub async fn handler( async fn exchange_authorization_code( params: [(&str, &String); 5], ) -> Result> { + let conf = config::load(); + let logger = Logger::new(&conf.watchtower); let client = reqwest::Client::new(); let res = client .post("https://discord.com/api/oauth2/token") @@ -131,10 +135,10 @@ async fn exchange_authorization_code( match json["access_token"].as_str() { Some(s) => Ok(s.to_string()), None => { - println!( + logger.info(format!( "Failed to get 'access_token' from JSON response : {:?}", json - ); + )); Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!( diff --git a/src/endpoints/quests/rango/quest2/mod.rs b/src/endpoints/quests/rango/quest2/mod.rs index 54e68fa9..d551e7e8 100644 --- a/src/endpoints/quests/rango/quest2/mod.rs +++ b/src/endpoints/quests/rango/quest2/mod.rs @@ -2,4 +2,4 @@ pub mod check_trade; pub mod claimable; pub mod discord_fw_callback; pub mod verify_twitter_fw; -pub mod verify_twitter_rw; \ No newline at end of file +pub mod verify_twitter_rw; diff --git a/src/endpoints/quests/rhino/mod.rs b/src/endpoints/quests/rhino/mod.rs index 9f7af890..1a528dbb 100644 --- a/src/endpoints/quests/rhino/mod.rs +++ b/src/endpoints/quests/rhino/mod.rs @@ -1,4 +1,4 @@ -pub mod verify_twitter_fw; -pub mod claimable; pub mod check_bridge; -pub mod verify_twitter_rw; \ No newline at end of file +pub mod claimable; +pub mod verify_twitter_fw; +pub mod verify_twitter_rw; diff --git a/src/endpoints/quests/sithswap/mod.rs b/src/endpoints/quests/sithswap/mod.rs index 27f02e0b..f5418bf7 100644 --- a/src/endpoints/quests/sithswap/mod.rs +++ b/src/endpoints/quests/sithswap/mod.rs @@ -1,2 +1,2 @@ +pub mod quest1; pub mod quest2; -pub mod quest1; \ No newline at end of file diff --git a/src/endpoints/quests/sithswap/quest2/mod.rs b/src/endpoints/quests/sithswap/quest2/mod.rs index 6d3690d7..cf01de14 100644 --- a/src/endpoints/quests/sithswap/quest2/mod.rs +++ b/src/endpoints/quests/sithswap/quest2/mod.rs @@ -1,5 +1,5 @@ +pub mod claimable; pub mod verify_deposit; pub mod verify_has_domain; pub mod verify_twitter_fw; pub mod verify_twitter_rw; -pub mod claimable; \ No newline at end of file diff --git a/src/endpoints/quests/verify_balance.rs b/src/endpoints/quests/verify_balance.rs index 752666ce..65df8014 100644 --- a/src/endpoints/quests/verify_balance.rs +++ b/src/endpoints/quests/verify_balance.rs @@ -62,10 +62,10 @@ pub async fn handler( ) .await; - let required_amount = task.total_amount.unwrap_or_else(|| - FieldElement::from_dec_str("3000000000000000").unwrap() - ); - + let required_amount = task + .total_amount + .unwrap_or_else(|| FieldElement::from_dec_str("3000000000000000").unwrap()); + match call_result { Ok(result) => { // if result[0] < FieldElement::from_dec_str("3000000000000000").unwrap() { diff --git a/src/logger.rs b/src/logger.rs new file mode 100644 index 00000000..973609f8 --- /dev/null +++ b/src/logger.rs @@ -0,0 +1,157 @@ +use chrono::Utc; +use reqwest; +use serde_derive::Serialize; +use std::borrow::Cow; +use std::sync::Arc; + +use crate::config::Watchtower; + +// Logger structure +pub struct Logger { + enabled: bool, + config: Arc, + client: Arc, +} + +// Enum for log types +#[derive(Clone)] +pub enum LogType { + Info, + Warning, + Severe, +} + +#[derive(Serialize)] +struct LogData<'a> { + token: &'a str, + log: LogPayload<'a>, +} + +#[derive(Serialize)] +struct LogPayload<'a> { + app_id: &'a str, + r#type: &'a str, + message: Cow<'a, str>, + timestamp: i64, +} + +impl Logger { + pub fn new(config: &Watchtower) -> Self { + env_logger::init(); + Logger { + enabled: config.enabled, + config: Arc::new(config.clone()), + client: Arc::new(reqwest::Client::new()), + } + } + + async fn post_log(&self, log_type: LogType, message: Cow<'static, str>) { + let config = Arc::clone(&self.config); + let client = Arc::clone(&self.client); + + let message_owned = message.into_owned(); + + let data = LogData { + token: &config.token, + log: LogPayload { + app_id: &config.app_id, + r#type: match log_type { + LogType::Info => &config.types.info, + LogType::Warning => &config.types.warning, + LogType::Severe => &config.types.severe, + }, + message: Cow::Owned(message_owned), + timestamp: Utc::now().timestamp_millis(), + }, + }; + + let response = client.post(&config.endpoint).json(&data).send().await; + + match response { + Ok(res) if res.status().is_success() => (), + Ok(res) => eprintln!( + "Failed to post log: {:?}", + res.text().await.unwrap_or_default() + ), + Err(err) => eprintln!("Failed to post log: {:?}", err), + } + } + + pub async fn async_info(&self, message: S) + where + S: Into> + std::fmt::Display + Send + 'static, + { + println!("INFO: {}", &message); + if self.config.enabled { + self.post_log(LogType::Info, message.into()).await; + } + } + + pub async fn async_warning(&self, message: S) + where + S: Into> + std::fmt::Display + Send + 'static, + { + println!("WARNING: {}", &message); + if self.config.enabled { + self.post_log(LogType::Warning, message.into()).await; + } + } + + pub async fn async_severe(&self, message: S) + where + S: Into> + std::fmt::Display + Send + 'static, + { + println!("SEVERE: {}", &message); + if self.config.enabled { + self.post_log(LogType::Severe, message.into()).await; + } + } + + pub fn info(&self, message: S) + where + S: Into> + std::fmt::Display + Send + 'static, + { + let logger_clone = self.clone(); + tokio::spawn(async move { + logger_clone.async_info(message).await; + }); + } + + pub fn warning(&self, message: S) + where + S: Into> + std::fmt::Display + Send + 'static, + { + let logger_clone = self.clone(); + tokio::spawn(async move { + logger_clone.async_warning(message).await; + }); + } + + pub fn severe(&self, message: S) + where + S: Into> + std::fmt::Display + Send + 'static, + { + let logger_clone = self.clone(); + tokio::spawn(async move { + logger_clone.async_severe(message).await; + }); + } + + #[allow(dead_code)] + pub fn local(&self, message: S) + where + S: Into> + std::fmt::Display, + { + println!("{}", &message); + } +} + +impl Clone for Logger { + fn clone(&self) -> Self { + Logger { + enabled: self.enabled, + config: Arc::clone(&self.config), + client: Arc::clone(&self.client), + } + } +} diff --git a/src/main.rs b/src/main.rs index 7bf38ef9..94aeb7d3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,32 +3,55 @@ mod utils; mod common; mod config; mod endpoints; +mod logger; mod models; +use crate::utils::{add_leaderboard_table, run_boosts_raffle}; use axum::{http::StatusCode, Router}; use axum_auto_routes::route; use mongodb::{bson::doc, options::ClientOptions, Client}; use reqwest::Url; +use serde_derive::Serialize; use starknet::providers::{jsonrpc::HttpTransport, JsonRpcClient}; -use std::sync::Arc; +use std::{borrow::Cow, sync::Arc}; use std::{net::SocketAddr, sync::Mutex}; -use utils::WithState; -use crate::utils::{add_leaderboard_table, run_boosts_raffle}; use tower_http::cors::{Any, CorsLayer}; +use utils::WithState; lazy_static::lazy_static! { pub static ref ROUTE_REGISTRY: Mutex>> = Mutex::new(Vec::new()); } +#[derive(Serialize)] +struct LogData<'a> { + token: &'a str, + log: LogPayload<'a>, +} + +#[derive(Serialize)] +struct LogPayload<'a> { + app_id: &'a str, + r#type: &'a str, + message: Cow<'a, str>, + timestamp: i64, +} + #[tokio::main] async fn main() { - println!("quest_server: starting v{}", env!("CARGO_PKG_VERSION")); let conf = config::load(); + let logger = logger::Logger::new(&conf.watchtower); + + logger.info(format!( + "quest_server: starting v{}", + env!("CARGO_PKG_VERSION") + )); + let client_options = ClientOptions::parse(&conf.database.connection_string) .await .unwrap(); let shared_state = Arc::new(models::AppState { + logger: logger.clone(), conf: conf.clone(), provider: JsonRpcClient::new(HttpTransport::new( Url::parse(&conf.variables.rpc_url).unwrap(), @@ -43,14 +66,18 @@ async fn main() { .await .is_err() { - println!("error: unable to connect to database"); + logger.async_severe("Unable to connect to database").await; return; } else { - println!("database: connected"); + logger.info("Connected to database"); } let db_instance = shared_state.db.clone(); - run_boosts_raffle(&db_instance, conf.quest_boost.update_interval); + run_boosts_raffle( + &db_instance, + conf.quest_boost.update_interval, + logger.clone(), + ); add_leaderboard_table(&shared_state.db).await; let cors = CorsLayer::new().allow_headers(Any).allow_origin(Any); @@ -65,7 +92,10 @@ async fn main() { .layer(cors); let addr = SocketAddr::from(([0, 0, 0, 0], conf.server.port)); - println!("server: listening on http://0.0.0.0:{}", conf.server.port); + logger.info(format!( + "server: listening on http://0.0.0.0:{}", + conf.server.port + )); axum::Server::bind(&addr) .serve(app.into_make_service_with_connect_info::()) .await diff --git a/src/models.rs b/src/models.rs index 2ce9ac89..ed80cbad 100644 --- a/src/models.rs +++ b/src/models.rs @@ -6,13 +6,14 @@ use starknet::{ providers::{jsonrpc::HttpTransport, JsonRpcClient}, }; -use crate::config::Config; use crate::endpoints::quests::uri::Attribute; +use crate::{config::Config, logger::Logger}; pub_struct!(;AppState { conf: Config, provider: JsonRpcClient, db: Database, + logger: Logger, }); pub_struct!(Debug, Serialize, Deserialize; NFTItem { diff --git a/src/utils.rs b/src/utils.rs index 2a1f230b..4be3e523 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,3 +1,4 @@ +use crate::logger::Logger; use crate::models::{ AchievementDocument, AppState, BoostTable, CompletedTasks, LeaderboardTable, QuestDocument, QuestTaskDocument, UserExperience, @@ -531,6 +532,7 @@ pub async fn fetch_and_update_boosts_winner( boost_collection: Collection, completed_tasks_collection: Collection, interval: u64, + logger: Logger, ) { loop { let pipeline = vec![doc! { @@ -711,25 +713,26 @@ pub async fn fetch_and_update_boosts_winner( .unwrap(); } None => { - println!("No winners found"); + logger.info("No winners found"); } } } } - Err(_err) => println!("{}", _err), + Err(_err) => logger.info(_err.to_string()), }; sleep(Duration::from_secs(interval)).await; } } -pub fn run_boosts_raffle(db: &Database, interval: u64) { +pub fn run_boosts_raffle(db: &Database, interval: u64, logger: Logger) { let boost_collection = db.collection::("boosts"); let completed_tasks_collection = db.collection::("completed_tasks"); tokio::spawn(fetch_and_update_boosts_winner( boost_collection, completed_tasks_collection, interval, + logger, )); } From e94e777602b50831677aed2266a36b30727398a2 Mon Sep 17 00:00:00 2001 From: Oshioke-Salaki Date: Mon, 26 Aug 2024 21:32:17 +0100 Subject: [PATCH 2/2] chore: update config --- config.template.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/config.template.toml b/config.template.toml index 2f44b075..f75ea94b 100644 --- a/config.template.toml +++ b/config.template.toml @@ -13,6 +13,7 @@ expiry_duration = 0 endpoint = "https://api.watchtower.starknet.id/service/add_message" app_id = "XXXXXXXXXXXXXXXXX" token = "XXXXXXXXXXXXXXXXX" +enabled = true [watchtower.types] info = "goerli/info" warning = "goerli/warning"