-
Notifications
You must be signed in to change notification settings - Fork 0
/
eligibility.rs
143 lines (117 loc) · 5.34 KB
/
eligibility.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use crate::{
data_objects::{
dto::PersistentCampaignDto,
query_param::Eligibility,
response::{self, EligibilityResponse, GeneralErrorResponse},
},
services::ipfs::download_from_ipfs,
WebResult,
};
use merkle_tree_rs::standard::{LeafType, StandardMerkleTree, StandardMerkleTreeData};
use serde_json::json;
use std::{collections::HashMap, str};
use url::Url;
use vercel_runtime as Vercel;
use warp::Filter;
/// Eligibility request common handler. It downloads data from IPFS and determines if an address is eligible for an
/// airstream campaign.
pub async fn handler(eligibility: Eligibility) -> response::R {
let ipfs_data = download_from_ipfs::<PersistentCampaignDto>(&eligibility.cid).await;
if ipfs_data.is_err() {
let response_json = json!(GeneralErrorResponse {
message: "There was a problem processing your request: Bad CID provided".to_string(),
});
return response::internal_server_error(response_json);
}
let ipfs_data = ipfs_data.unwrap();
let recipient_index =
ipfs_data.recipients.iter().position(|r| r.address.to_lowercase() == eligibility.address.to_lowercase());
if recipient_index.is_none() {
let response_json = json!(GeneralErrorResponse {
message: String::from("The provided address is not eligible for this campaign"),
});
return response::bad_request(response_json);
}
let recipient_index = recipient_index.unwrap();
let tree_data: StandardMerkleTreeData = serde_json::from_str(&ipfs_data.merkle_tree).unwrap();
let tree = StandardMerkleTree::load(tree_data);
let proof = tree.get_proof(LeafType::Number(recipient_index));
let response_json = json!(&EligibilityResponse {
index: recipient_index,
proof,
address: ipfs_data.recipients[recipient_index].address.clone(),
amount: ipfs_data.recipients[recipient_index].amount.clone(),
});
response::ok(response_json)
}
/// Warp specific handler for the eligibility endpoint
pub async fn handler_to_warp(eligibility: Eligibility) -> WebResult<impl warp::Reply> {
let result = handler(eligibility).await;
Ok(response::to_warp(result))
}
/// Vercel specific handler for the create eligibility
pub async fn handler_to_vercel(req: Vercel::Request) -> Result<Vercel::Response<Vercel::Body>, Vercel::Error> {
// ------------------------------------------------------------
// Extract query parameters from the URL: address, cid
// ------------------------------------------------------------
let url = Url::parse(&req.uri().to_string()).unwrap();
let query: HashMap<String, String> = url.query_pairs().into_owned().collect();
// ------------------------------------------------------------
//Format arguments for the generic handler
// ------------------------------------------------------------
let fallback = String::from("");
let params = Eligibility {
address: query.get("address").unwrap_or(&fallback).clone(),
cid: query.get("cid").unwrap_or(&fallback).clone(),
};
let result = handler(params).await;
response::to_vercel(result)
}
/// Bind the route with the handler for the Warp handler.
pub fn build_route() -> impl warp::Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("api" / "eligibility")
.and(warp::get())
.and(warp::query::query::<Eligibility>())
.and_then(handler_to_warp)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::async_test::{setup_env_vars, SERVER};
#[tokio::test]
async fn handler_success_response() {
let mut server = SERVER.lock().await;
setup_env_vars(&server);
let mock = server
.mock("GET", "/valid_cid?pinataGatewayToken=mock_pinata_access_token")
.with_status(200)
.with_body(r#"{"root": "root", "total_amount": "10", "number_of_recipients": 1, "merkle_tree":"{\"format\":\"standard-v1\",\"tree\":[\"0x23bb7a869a407bc69b27975acff039dfe6a6abe5e3da626e98623d70137eb320\"],\"values\":[{\"value\":[\"0\",\"0x9ad7cad4f10d0c3f875b8a2fd292590490c9f491\",\"5000\"],\"tree_index\":0}],\"leaf_encoding\":[\"uint\",\"address\",\"uint256\"]}", "recipients": [{ "address": "0x0x9ad7CAD4F10D0c3f875b8a2fd292590490c9f491", "amount": "10"}]}"#)
.create();
let validity = Eligibility {
cid: "valid_cid".to_string(),
address: "0x0x9ad7CAD4F10D0c3f875b8a2fd292590490c9f491".to_string(),
};
let response = handler(validity).await;
assert_eq!(response.status, warp::http::StatusCode::OK.as_u16());
mock.assert();
drop(server);
}
#[tokio::test]
async fn handler_error_response() {
let mut server = SERVER.lock().await;
setup_env_vars(&server);
let mock = server
.mock("GET", "/invalid_cid?pinataGatewayToken=mock_pinata_access_token")
.with_status(500)
.with_body(r#"{"message": "Bad request"}"#)
.create();
let validity = Eligibility {
cid: "invalid_cid".to_string(),
address: "0x0x9ad7CAD4F10D0c3f875b8a2fd292590490c9f491".to_string(),
};
let response = handler(validity).await;
assert_eq!(response.status, warp::http::StatusCode::INTERNAL_SERVER_ERROR.as_u16());
mock.assert();
drop(server);
}
}