Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple feats #186

Merged
merged 7 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 10 additions & 2 deletions fplus-http-server/src/router/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use fplus_lib::core::allocator::generate_github_app_jwt;
use fplus_lib::core::{allocator::{
create_allocator_repo, force_update_allocators, is_allocator_repo_created, process_allocator_file, update_single_installation_id_logic, validate_amount_type_and_options
}, AllocatorUpdateForceInfo, AllocatorUpdateInfo, ChangedAllocators, InstallationIdUpdateInfo};
use fplus_lib::helpers::process_amount;
use reqwest::Client;

/**
Expand Down Expand Up @@ -42,15 +43,20 @@ pub async fn create_from_json(files: web::Json<ChangedAllocators>) -> actix_web:
log::info!("Starting allocator creation on: {}", file_name);

match process_allocator_file(file_name).await {
Ok(model) => {
Ok(mut model) => {
let mut quantity_options: Vec<String>;
if let Some(allocation_amount) = model.application.allocation_amount.clone() {
if allocation_amount.amount_type.clone() == None || allocation_amount.quantity_options.clone() == None {
error_response = Some(HttpResponse::BadRequest().body("Amount type and quantity options are required"));
break;
}

let amount_type = allocation_amount.amount_type.clone().unwrap().to_lowercase(); // Assuming you still want to unwrap here
let quantity_options = allocation_amount.quantity_options.unwrap(); // Assuming unwrap is desired
quantity_options = allocation_amount.quantity_options.unwrap(); // Assuming unwrap is desired

for option in quantity_options.iter_mut() {
*option = process_amount(option.clone());
}

match validate_amount_type_and_options(&amount_type, &quantity_options) {
Ok(()) => println!("Options are valid"),
Expand All @@ -59,6 +65,8 @@ pub async fn create_from_json(files: web::Json<ChangedAllocators>) -> actix_web:
break;
}
}

model.application.allocation_amount.as_mut().unwrap().quantity_options = Some(quantity_options);
}

let verifiers_gh_handles = if model.application.verifiers_gh_handles.is_empty() {
Expand Down
3 changes: 2 additions & 1 deletion fplus-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ log = "0.4.20"
once_cell = "1.19.0"
fplus-database = { path = "../fplus-database", version = "1.8.3"}
pem = "1.0"
anyhow = "1.0"
anyhow = "1.0"
regex = "1.0"
1 change: 1 addition & 0 deletions fplus-lib/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub fn default_env_vars() -> &'static HashMap<&'static str, &'static str> {
m.insert("BACKEND_URL", "https://fp-core.dp04sa0tdc6pk.us-east-1.cs.amazonlightsail.com");
m.insert("FILPLUS_ENV", "staging");
m.insert("GLIF_NODE_URL", "http://electric-publicly-adder.ngrok-free.app/rpc/v0");
m.insert("ISSUE_TEMPLATE_VERSION", "1.3");

m
})
Expand Down
8 changes: 0 additions & 8 deletions fplus-lib/src/core/application/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,6 @@ pub enum StorageProviders {

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Project {
#[serde(rename = "Project Id")]
pub project_id: String,
#[serde(rename = "Brief history of your project and organization")]
pub history: String,
#[serde(rename = "Is this project associated with other projects/ecosystem stakeholders?")]
Expand Down Expand Up @@ -404,9 +402,6 @@ pub trait DeepCompare {
impl DeepCompare for ApplicationFile {
fn compare(&self, other: &Self) -> Vec<String> {
let mut differences = Vec::new();
if self.version != other.version {
differences.push(format!("Version: {} vs {}", self.version, other.version));
}
if self.id != other.id {
differences.push(format!("ID: {} vs {}", self.id, other.id));
}
Expand Down Expand Up @@ -483,9 +478,6 @@ impl DeepCompare for Datacap {
impl DeepCompare for Project {
fn compare(&self, other: &Self) -> Vec<String> {
let mut differences = Vec::new();
if self.project_id != other.project_id {
differences.push(format!("Project ID: {} vs {}", self.project_id, other.project_id));
}
if self.history != other.history {
differences.push(format!("Brief history of your project and organization: {} vs {}", self.history, other.history));
}
Expand Down
1 change: 0 additions & 1 deletion fplus-lib/src/core/application/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ pub mod client;
pub mod datacap;
pub mod file;
pub mod lifecycle;
pub mod project;

impl file::ApplicationFile {
pub async fn new(
Expand Down
40 changes: 0 additions & 40 deletions fplus-lib/src/core/application/project.rs

This file was deleted.

83 changes: 78 additions & 5 deletions fplus-lib/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
blockchain::BlockchainData, filecoin::get_multisig_threshold_for_actor, github::{
github_async_new, CreateMergeRequestData, CreateRefillMergeRequestData, GithubWrapper,
}
}, parsers::ParsedIssue
}, helpers::{compare_allowance_and_allocation, process_amount}, parsers::ParsedIssue
};
use fplus_database::database::allocation_amounts::get_allocation_quantity_options;
use fplus_database::database::{
Expand Down Expand Up @@ -593,12 +593,15 @@ impl LDNApplication {
pub async fn new_from_issue(info: CreateApplicationInfo) -> Result<Self, LDNError> {
let issue_number = info.issue_number;
let gh = github_async_new(info.owner.to_string(), info.repo.to_string()).await;
let (parsed_ldn, _) = LDNApplication::parse_application_issue(
let (mut parsed_ldn, _) = LDNApplication::parse_application_issue(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
)
.await?;

parsed_ldn.datacap.total_requested_amount = process_amount(parsed_ldn.datacap.total_requested_amount.clone());
parsed_ldn.datacap.weekly_allocation = process_amount(parsed_ldn.datacap.weekly_allocation.clone());

let application_id = parsed_ldn.id.clone();
let file_name = LDNPullRequest::application_path(&application_id);
Expand Down Expand Up @@ -814,13 +817,27 @@ impl LDNApplication {
Ok(s) => match s {
AppState::Submitted | AppState::AdditionalInfoRequired | AppState::AdditionalInfoSubmitted => {
let app_file: ApplicationFile = self.file().await?;

let db_allocator = match get_allocator(&owner, &repo).await {
Ok(allocator) => allocator.unwrap(),
Err(err) => {
return Err(LDNError::New(format!("Database: get_allocator: {}", err)));
}
};
let db_multisig_address = db_allocator.multisig_address.unwrap();
Self::check_and_handle_allowance(
&db_multisig_address.clone(),
Some(allocation_amount.clone()),
).await?;

let uuid = uuidv4::uuid::v4();
let request = AllocationRequest::new(
actor.clone(),
uuid,
AllocationRequestType::First,
allocation_amount,
);

let app_file = app_file.complete_governance_review(actor.clone(), request);
let file_content = serde_json::to_string_pretty(&app_file).unwrap();
let app_path = &self.file_name.clone();
Expand Down Expand Up @@ -967,6 +984,11 @@ impl LDNApplication {
app_lifecycle,
);
if new_allocation_amount.is_some() && app_file.allocation.0.len() > 1 {
Self::check_and_handle_allowance(
&db_multisig_address.clone(),
new_allocation_amount.clone(),
).await?;

let _ = app_file.adjust_active_allocation_amount(new_allocation_amount.unwrap().clone());
}

Expand Down Expand Up @@ -1107,7 +1129,16 @@ impl LDNApplication {
));
}

// Check the allowance for the address

if new_allocation_amount.is_some() && app_file.allocation.0.len() > 1 {
let db_multisig_address = db_allocator.multisig_address.unwrap();

Self::check_and_handle_allowance(
&db_multisig_address.clone(),
new_allocation_amount.clone(),
).await?;

let _ = app_file.adjust_active_allocation_amount(new_allocation_amount.unwrap().clone());
}

Expand Down Expand Up @@ -2382,7 +2413,7 @@ impl LDNApplication {
pub async fn update_from_issue(info: CreateApplicationInfo) -> Result<Self, LDNError> {
// Get the PR number from the issue number.
let issue_number = info.issue_number.clone();
let (parsed_ldn, _) = LDNApplication::parse_application_issue(
let (mut parsed_ldn, _) = LDNApplication::parse_application_issue(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
Expand Down Expand Up @@ -2412,6 +2443,9 @@ impl LDNApplication {

}
};

parsed_ldn.datacap.total_requested_amount = process_amount(parsed_ldn.datacap.total_requested_amount.clone());
parsed_ldn.datacap.weekly_allocation = process_amount(parsed_ldn.datacap.weekly_allocation.clone());

//Application was granted. Create a new PR with the updated application file, as if it was a new application
if application_model.pr_number == 0 {
Expand Down Expand Up @@ -2521,6 +2555,40 @@ impl LDNApplication {
}
}

async fn check_and_handle_allowance(
db_multisig_address: &str,
new_allocation_amount: Option<String>,
) -> Result<(), LDNError> {
let blockchain = BlockchainData::new();
match blockchain.get_allowance_for_address("f24siazyti3akorqyvi33rvlq3i73j23rwohdamuy").await {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leave this as it is just for testing purposes. We need to remove it when tagging into prod

Ok(allowance) if allowance != "0" => {
log::info!("Allowance found and is not zero. Value is {}", allowance);
match compare_allowance_and_allocation(&allowance, new_allocation_amount) {
Some(result) => {
if result {
println!("Allowance is sufficient.");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's remove prints on tagging

Ok(())
} else {
println!("Allowance is not sufficient.");
Err(LDNError::New("Multisig address has less allowance than the new allocation amount".to_string()))
}
},
None => {
println!("Error parsing sizes.");
Err(LDNError::New("Error parsing sizes".to_string()))
},
}
},
Ok(_) => {
Err(LDNError::New("Multisig address has no remaining allowance".to_string()))
},
Err(e) => {
log::error!("Failed to retrieve allowance: {:?}", e);
Err(LDNError::New("Failed to retrieve allowance".to_string()))
}
}
}

pub async fn create_pr_from_issue_modification(parsed_ldn: ParsedIssue, application_model: ApplicationModel) -> Result<Self, LDNError> {
let merged_application = ApplicationFile::from_str(&application_model.application.unwrap())
.map_err(|e| LDNError::Load(format!("Failed to parse application file from DB: {}", e))).unwrap();
Expand Down Expand Up @@ -3483,9 +3551,11 @@ impl LDNPullRequest {
));
})?;

let issue_link = format!("https://github.com/{}/{}/issues/{}", owner, repo, application_id);

let (_pr, file_sha) = gh
.create_merge_request(CreateMergeRequestData {
application_id: application_id.clone(),
issue_link,
branch_name: app_branch_name,
file_name,
owner_name,
Expand Down Expand Up @@ -3526,9 +3596,12 @@ impl LDNPullRequest {
application_id, e
));
})?;

let issue_link = format!("https://github.com/{}/{}/issues/{}", owner, repo, application_id);

let pr = match gh
.create_refill_merge_request(CreateRefillMergeRequestData {
application_id: application_id.clone(),
issue_link,
owner_name,
file_name: file_name.clone(),
file_sha: file_sha.clone(),
Expand Down
7 changes: 6 additions & 1 deletion fplus-lib/src/external_services/blockchain.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const BASE_URL: &str = "https://api.filplus.d.interplanetary.one/public/api";
extern crate regex;

/// BlockchainData is a client for the Fil+ blockchain data API.
pub struct BlockchainData {
Expand Down Expand Up @@ -94,6 +95,10 @@ impl BlockchainData {
let allowance = json["allowance"].as_str().unwrap_or("");
Ok(allowance.to_string())
}
Some("verifier") => {
let allowance = json["allowance"].as_str().unwrap_or("");
Ok(allowance.to_string())
}
Some("error") => {
let message = json["message"].as_str().unwrap_or("");
Err(BlockchainDataError::Err(message.to_string()))
Expand All @@ -109,4 +114,4 @@ impl BlockchainData {
fn build_url(&self, path: &str) -> String {
format!("{}/{}", self.base_url, path)
}
}
}
12 changes: 6 additions & 6 deletions fplus-lib/src/external_services/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ struct GithubParams {

#[derive(Debug)]
pub struct CreateRefillMergeRequestData {
pub application_id: String,
pub issue_link: String,
pub owner_name: String,
pub ref_request: Request<String>,
pub file_content: String,
Expand All @@ -57,7 +57,7 @@ pub struct CreateRefillMergeRequestData {

#[derive(Debug)]
pub struct CreateMergeRequestData {
pub application_id: String,
pub issue_link: String,
pub owner_name: String,
pub ref_request: Request<String>,
pub file_content: String,
Expand Down Expand Up @@ -605,7 +605,7 @@ impl GithubWrapper {
data: CreateRefillMergeRequestData,
) -> Result<(PullRequest, String), OctocrabError> {
let CreateRefillMergeRequestData {
application_id: _,
issue_link,
ref_request,
owner_name,
file_content,
Expand All @@ -621,7 +621,7 @@ impl GithubWrapper {
.create_pull_request(
&format!("Datacap for {}", owner_name),
&branch_name,
&format!(""),
&format!("{}", issue_link),
)
.await?;

Expand All @@ -633,7 +633,7 @@ impl GithubWrapper {
data: CreateMergeRequestData,
) -> Result<(PullRequest, String), OctocrabError> {
let CreateMergeRequestData {
application_id: _,
issue_link,
ref_request,
owner_name,
file_content,
Expand All @@ -650,7 +650,7 @@ impl GithubWrapper {
.create_pull_request(
&format!("Datacap for {}", owner_name),
&branch_name,
&format!(""),
&format!("{}", issue_link),
)
.await?;

Expand Down
Loading
Loading