-
Notifications
You must be signed in to change notification settings - Fork 27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add rango quest #148
Merged
Merged
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ceca3fd
feat: add rango quest
ayushtom cea0b47
feat: add discord task
ayushtom e96016b
feat: add rango
ayushtom 083508e
feat: add rango exchange nft
ayushtom e436d25
Merge branch 'master' into ayush/rango
ayushtom 8d857a9
feat: add quiz template
ayushtom 834cb68
chore: remove merge brackets
ayushtom 189f0a9
feat: change nft name
ayushtom fffaed8
chore: rmeove unnec changes
ayushtom 6e20b6b
chore: resolve pr comments
ayushtom 113bcc8
chore: remo warnings
ayushtom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,3 +17,4 @@ pub mod tribe; | |
pub mod uri; | ||
pub mod verify_quiz; | ||
pub mod zklend; | ||
pub mod rango; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
use std::sync::Arc; | ||
|
||
use crate::models::EmailQuery; | ||
use crate::utils::{CompletedTasksTrait}; | ||
use crate::{models::AppState, utils::get_error}; | ||
use axum::{ | ||
extract::{Query, State}, | ||
http::StatusCode, | ||
response::IntoResponse, | ||
Json, | ||
}; | ||
use serde_json::json; | ||
|
||
pub async fn handler( | ||
State(state): State<Arc<AppState>>, | ||
Query(query): Query<EmailQuery>, | ||
) -> impl IntoResponse { | ||
let task_id = 92; | ||
|
||
let res = make_rango_request(&state.conf.rango.api_endpoint, &state.conf.rango.api_key).await; | ||
let response = match res { | ||
Ok(response) => response, | ||
Err(e) => return get_error(format!("{}", e)), | ||
}; | ||
|
||
if let Some(data_response) = response.get("data") { | ||
if let Some(result) = response.get("result") { | ||
if result.as_bool().unwrap() { | ||
return 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)), | ||
}; | ||
} else { | ||
get_error("User has not completed the task".to_string()) | ||
} | ||
} else { | ||
get_error("User has not completed the task".to_string()) | ||
} | ||
} else { | ||
get_error("User has not completed the task".to_string()) | ||
} | ||
} | ||
|
||
async fn make_rango_request(endpoint: &str, apiKey: &str) -> Result<serde_json::Value, String> { | ||
let client = reqwest::Client::new(); | ||
match client.get(endpoint).header("apiKey", apiKey).send().await { | ||
Ok(response) => match response.json::<serde_json::Value>().await { | ||
Ok(json) => { | ||
if let Some(res) = json.get("res") { | ||
if res.as_bool().unwrap() { | ||
return Ok(json!({"res": true})); | ||
} | ||
} | ||
Err(format!("Failed to get JSON response: {}", json)) | ||
fricoben marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
Err(e) => Err(format!("Failed to get JSON response: {}", e)), | ||
}, | ||
Err(e) => Err(format!("Failed to send request: {}", e)), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 = 23; | ||
const TASK_IDS: &[u32] = &[92, 93, 94, 95]; | ||
const LAST_TASK: u32 = TASK_IDS[3]; | ||
const NFT_LEVEL: u32 = 30; | ||
|
||
#[derive(Deserialize)] | ||
pub struct ClaimableQuery { | ||
addr: FieldElement, | ||
} | ||
|
||
pub async fn handler( | ||
State(state): State<Arc<AppState>>, | ||
Query(query): Query<ClaimableQuery>, | ||
) -> impl IntoResponse { | ||
let collection = state | ||
.db | ||
.collection::<CompletedTaskDocument>("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()), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 TwitterOAuthCallbackQuery { | ||
code: String, | ||
state: FieldElement, | ||
} | ||
|
||
#[derive(Deserialize)] | ||
pub struct Guild { | ||
id: String, | ||
#[allow(dead_code)] | ||
name: String, | ||
} | ||
|
||
pub async fn handler( | ||
State(state): State<Arc<AppState>>, | ||
Query(query): Query<TwitterOAuthCallbackQuery>, | ||
) -> impl IntoResponse { | ||
let quest_id = 23; | ||
let task_id = 94; | ||
let guild_id = "1079299393712300112"; | ||
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/rango/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<Guild> = 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 Rango's Discord server".to_string(), | ||
) | ||
} | ||
|
||
async fn exchange_authorization_code( | ||
params: [(&str, &String); 5], | ||
) -> Result<String, Box<dyn std::error::Error>> { | ||
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 | ||
), | ||
))) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
pub mod verify_twitter_fw; | ||
pub mod discord_fw_callback; | ||
pub mod check_trade; | ||
pub mod claimable; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Try to avoid repeating the same statement. You can try to use
return
inside the last if and return get_error "user hasn ot completed the tasks" only at the end. Will be easier if we want to modify it.