diff --git a/Cargo.toml b/Cargo.toml index 7554e289..35d5aae5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,8 +6,8 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -starknet = "0.6.0" -starknet-id = { git = "https://github.com/starknet-id/starknet-id.rs.git", branch = "master" } +starknet = { git = "https://github.com/xJonathanLEI/starknet-rs" } +starknet-id = { git = "https://github.com/starknet-id/starknet-id.rs.git" } axum = "0.6.17" toml = "0.5.10" serde = { version = "1.0.152", features = ["derive"] } diff --git a/config.template.toml b/config.template.toml index 8ecb5461..4d3137e1 100644 --- a/config.template.toml +++ b/config.template.toml @@ -32,6 +32,9 @@ api_key_user = "xxxxxx" api_key_claimed_mission = "xxxxxx" [quests.element] api_key = "xxxxxx" +[quests.nostra] +utils_contract = "0xXXXXXXXXXXXX" +pairs = ["0xXXXXXXXXXXXX"] [twitter] oauth2_clientid = "xxxxxx" @@ -795,4 +798,45 @@ options = [ "To verify that a user is a real human and a single person", "To confirm the user's location" ] +correct_answers = [*] + +[quizzes.nostra] +name = "Nostra Quiz" +desc = "Take part in our Quiz to test your knowledge about Nostra, and you'll have a chance to win an exclusive LaFamiglia Rose NFT as your reward." +intro = "Starknet Quest Quiz Rounds, a quiz series designed to make Starknet ecosystem knowledge accessible and enjoyable for all. Test your understanding of the workings of Nostra, enjoy the experience, and earn an exclusive NFT reward by testing your knowledge about Starknet Ecosystem projects!" + +[[quizzes.nostra.questions]] +kind = "text_choice" +layout = "default" +question = "Which network is Nostra built on?" +options = [ + "Scroll", + "Starknet", + "Binance Smart Chain", + "zkSync" +] +correct_answers = [*] + +[[quizzes.nostra.questions]] +kind = "text_choice" +layout = "default" +question = "How many sub-accounts can a user open on Nostra?" +options = [ + "10", + "100", + "255", + "Unlimited" +] +correct_answers = [*] + +[[quizzes.nostra.questions]] +kind = "text_choice" +layout = "default" +question = "What is the minimum borrow amount for USDC on Nostra?" +options = [ + "500 USDC", + "100 USDC.", + "3000 USDC.", + "There is no minimum amount" +] correct_answers = [*] \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 2d07b633..c88a3ba3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -62,6 +62,7 @@ pub_struct!(Clone, Deserialize; Quests { myswap: Contract, braavos: Braavos, element: Element, + nostra: Pairs, }); pub_struct!(Clone, Deserialize; Twitter { diff --git a/src/endpoints/quests/mod.rs b/src/endpoints/quests/mod.rs index 41f45016..658df1f7 100644 --- a/src/endpoints/quests/mod.rs +++ b/src/endpoints/quests/mod.rs @@ -8,6 +8,7 @@ pub mod focustree; pub mod jediswap; pub mod morphine; pub mod myswap; +pub mod nostra; pub mod orbiter; pub mod sithswap; pub mod starknet; diff --git a/src/endpoints/quests/nostra/claimable.rs b/src/endpoints/quests/nostra/claimable.rs new file mode 100644 index 00000000..f1ea8d89 --- /dev/null +++ b/src/endpoints/quests/nostra/claimable.rs @@ -0,0 +1,101 @@ +use crate::models::{AppState, CompletedTaskDocument, Reward, RewardResponse}; +use crate::utils::{get_error, get_nft}; +use axum::{ + extract::{Query, State}, + http::StatusCode, + response::IntoResponse, + Json, +}; +use futures::StreamExt; +use mongodb::bson::doc; +use serde::Deserialize; +use starknet::{ + core::types::FieldElement, + signers::{LocalWallet, SigningKey}, +}; +use std::sync::Arc; + +const QUEST_ID: u32 = 20; +const TASK_IDS: &[u32] = &[79, 80, 81]; +const LAST_TASK: u32 = TASK_IDS[2]; +const NFT_LEVEL: u32 = 27; + +#[derive(Deserialize)] +pub struct ClaimableQuery { + addr: FieldElement, +} + +pub async fn handler( + State(state): State>, + Query(query): Query, +) -> impl IntoResponse { + let collection = state + .db + .collection::("completed_tasks"); + + let pipeline = vec![ + doc! { + "$match": { + "address": &query.addr.to_string(), + "task_id": { "$in": TASK_IDS }, + }, + }, + doc! { + "$lookup": { + "from": "tasks", + "localField": "task_id", + "foreignField": "id", + "as": "task", + }, + }, + doc! { + "$match": { + "task.quest_id": QUEST_ID, + }, + }, + doc! { + "$group": { + "_id": "$address", + "completed_tasks": { "$push": "$task_id" }, + }, + }, + doc! { + "$match": { + "completed_tasks": { "$all": TASK_IDS }, + }, + }, + ]; + + let completed_tasks = collection.aggregate(pipeline, None).await; + match completed_tasks { + Ok(mut tasks_cursor) => { + if tasks_cursor.next().await.is_none() { + return get_error("User hasn't completed all tasks".into()); + } + + let signer = LocalWallet::from(SigningKey::from_secret_scalar( + state.conf.nft_contract.private_key, + )); + + let mut rewards = vec![]; + + let Ok((token_id, sig)) = get_nft(QUEST_ID, LAST_TASK, &query.addr, NFT_LEVEL, &signer).await else { + return get_error("Signature failed".into()); + }; + + rewards.push(Reward { + task_id: LAST_TASK, + nft_contract: state.conf.nft_contract.address.clone(), + token_id: token_id.to_string(), + sig: (sig.r, sig.s), + }); + + if rewards.is_empty() { + get_error("No rewards found for this user".into()) + } else { + (StatusCode::OK, Json(RewardResponse { rewards })).into_response() + } + } + Err(_) => get_error("Error querying rewards".into()), + } +} diff --git a/src/endpoints/quests/nostra/discord_fw_callback.rs b/src/endpoints/quests/nostra/discord_fw_callback.rs new file mode 100644 index 00000000..c5576ec3 --- /dev/null +++ b/src/endpoints/quests/nostra/discord_fw_callback.rs @@ -0,0 +1,145 @@ +use std::sync::Arc; + +use crate::utils::CompletedTasksTrait; +use crate::{ + models::AppState, + utils::{get_error_redirect, success_redirect}, +}; +use axum::{ + extract::{Query, State}, + response::IntoResponse, +}; +use mongodb::bson::doc; +use reqwest::header::AUTHORIZATION; +use serde::Deserialize; +use starknet::core::types::FieldElement; + +#[derive(Deserialize)] +pub struct DiscordOAuthCallbackQuery { + code: String, + state: FieldElement, +} + +#[derive(Deserialize, Debug)] +pub struct Guild { + id: String, + #[allow(dead_code)] + name: String, +} + +pub async fn handler( + State(state): State>, + Query(query): Query, +) -> impl IntoResponse { + let quest_id = 20; + let task_id = 80; + let guild_id = "1002209435868987463"; + let authorization_code = &query.code; + let error_redirect_uri = format!( + "{}/quest/{}?task_id={}&res=false", + state.conf.variables.app_link, quest_id, task_id + ); + + // Exchange the authorization code for an access token + let params = [ + ("client_id", &state.conf.discord.oauth2_clientid), + ("client_secret", &state.conf.discord.oauth2_secret), + ("code", &authorization_code.to_string()), + ( + "redirect_uri", + &format!( + "{}/quests/nostra/discord_fw_callback", + state.conf.variables.api_link + ), + ), + ("grant_type", &"authorization_code".to_string()), + ]; + let access_token = match exchange_authorization_code(params).await { + Ok(token) => token, + Err(e) => { + return get_error_redirect( + error_redirect_uri, + format!("Failed to exchange authorization code: {}", e), + ); + } + }; + + // Get user guild information + let client = reqwest::Client::new(); + let response_result = client + .get("https://discord.com/api/users/@me/guilds") + .header(AUTHORIZATION, format!("Bearer {}", access_token)) + .send() + .await; + let response: Vec = match response_result { + Ok(response) => { + let json_result = response.json().await; + match json_result { + Ok(json) => json, + Err(e) => { + return get_error_redirect( + error_redirect_uri, + format!( + "Failed to get JSON response while fetching user info: {}", + e + ), + ); + } + } + } + Err(e) => { + return get_error_redirect( + error_redirect_uri, + format!("Failed to send request to get user info: {}", e), + ); + } + }; + + for guild in response { + if guild.id == guild_id { + match state.upsert_completed_task(query.state, task_id).await { + Ok(_) => { + let redirect_uri = format!( + "{}/quest/{}?task_id={}&res=true", + state.conf.variables.app_link, quest_id, task_id + ); + return success_redirect(redirect_uri); + } + Err(e) => return get_error_redirect(error_redirect_uri, format!("{}", e)), + } + } + } + + get_error_redirect( + error_redirect_uri, + "You're not part of Nostra's Discord server".to_string(), + ) +} + +async fn exchange_authorization_code( + params: [(&str, &String); 5], +) -> Result> { + let client = reqwest::Client::new(); + let res = client + .post("https://discord.com/api/oauth2/token") + .form(¶ms) + .send() + .await?; + let json: serde_json::Value = res.json().await?; + match json["access_token"].as_str() { + Some(s) => Ok(s.to_string()), + None => { + println!( + "Failed to get 'access_token' from JSON response : {:?}", + json + ); + Err(Box::new(std::io::Error::new( + std::io::ErrorKind::Other, + format!( + "Failed to get 'access_token' from JSON response : {:?}", + json + ), + ))) + } + } +} diff --git a/src/endpoints/quests/nostra/mod.rs b/src/endpoints/quests/nostra/mod.rs new file mode 100644 index 00000000..57eade9b --- /dev/null +++ b/src/endpoints/quests/nostra/mod.rs @@ -0,0 +1,3 @@ +pub mod claimable; +pub mod discord_fw_callback; +pub mod verify_added_liquidity; diff --git a/src/endpoints/quests/nostra/verify_added_liquidity.rs b/src/endpoints/quests/nostra/verify_added_liquidity.rs new file mode 100644 index 00000000..b1611449 --- /dev/null +++ b/src/endpoints/quests/nostra/verify_added_liquidity.rs @@ -0,0 +1,55 @@ +use std::sync::Arc; + +use crate::{ + models::{AppState, VerifyQuery}, + utils::{get_error, CompletedTasksTrait}, +}; +use axum::{ + extract::{Query, State}, + http::StatusCode, + response::IntoResponse, + Json, +}; +use serde_json::json; +use starknet::{ + core::types::{BlockId, BlockTag, FieldElement, FunctionCall}, + macros::selector, + providers::Provider, +}; + +pub async fn handler( + State(state): State>, + Query(query): Query, +) -> impl IntoResponse { + let task_id = 81; + let addr = &query.addr; + let mut calldata = vec![addr.clone(), state.conf.quests.nostra.pairs.len().into()]; + calldata.append(&mut state.conf.quests.nostra.pairs.clone()); + + // get starkname from address + let call_result = state + .provider + .call( + FunctionCall { + contract_address: state.conf.quests.nostra.utils_contract, + entry_point_selector: selector!("sum_balances"), + calldata, + }, + BlockId::Tag(BlockTag::Latest), + ) + .await; + + match call_result { + Ok(result) => { + if result[0] == FieldElement::ZERO { + get_error("You didn't deposit liquidity.".to_string()) + } else { + match state.upsert_completed_task(query.addr, task_id).await { + Ok(_) => (StatusCode::OK, Json(json!({"res": true}))).into_response(), + Err(e) => get_error(format!("{}", e)), + } + } + } + Err(e) => get_error(format!("{}", e)), + } +} diff --git a/src/endpoints/quests/uri.rs b/src/endpoints/quests/uri.rs index 8a31c0a2..2da5a957 100644 --- a/src/endpoints/quests/uri.rs +++ b/src/endpoints/quests/uri.rs @@ -307,6 +307,17 @@ pub async fn handler( }), ) .into_response(), + + Some(27) => ( + StatusCode::OK, + Json(TokenURI { + name: "Nostra - LaFamiglia Rose".into(), + description: "A Nostra - LaFamiglia Rose NFT won for successfully finishing the Quest".into(), + image: format!("{}/nostra/rose.webp", state.conf.variables.app_link), + attributes: None, + }), + ) + .into_response(), _ => get_error("Error, this level is not correct".into()), } diff --git a/src/endpoints/quests/verify_quiz.rs b/src/endpoints/quests/verify_quiz.rs index edcb2e03..59ccfbe4 100644 --- a/src/endpoints/quests/verify_quiz.rs +++ b/src/endpoints/quests/verify_quiz.rs @@ -27,6 +27,7 @@ fn get_task_id(quiz_name: &str) -> Option { "element" => Some(64), "briq" => Some(67), "element_starknetid" => Some(73), + "nostra" => Some(79), _ => None, } } diff --git a/src/main.rs b/src/main.rs index b8c41816..df953457 100644 --- a/src/main.rs +++ b/src/main.rs @@ -342,6 +342,18 @@ async fn main() { "/quests/element/starknetid/claimable", get(endpoints::quests::element::starknetid::claimable::handler), ) + .route( + "/quests/nostra/claimable", + get(endpoints::quests::nostra::claimable::handler), + ) + .route( + "/quests/nostra/discord_fw_callback", + get(endpoints::quests::nostra::discord_fw_callback::handler), + ) + .route( + "/quests/nostra/verify_added_liquidity", + get(endpoints::quests::nostra::verify_added_liquidity::handler), + ) .route( "/achievements/verify_default", get(endpoints::achievements::verify_default::handler),