-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmod.rs
5053 lines (4600 loc) · 183 KB
/
mod.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::sync::Arc;
use std::{collections::HashMap, str::FromStr};
use alloy::primitives::Address;
use application::file::{SpsChangeRequest, StorageProviderChangeVerifier};
use chrono::{DateTime, Local, Utc};
use futures::future;
use octocrab::models::{
pulls::PullRequest,
repos::{Content, ContentItems},
};
use rayon::prelude::*;
use reqwest::Response;
use serde::{Deserialize, Serialize};
use serde_json::from_str;
use crate::{
base64,
config::get_env_var_or_default,
core::application::{
file::Allocations,
gitcoin_interaction::{
get_address_from_signature, verify_on_gitcoin, ExpirableSolStruct, KycApproval,
KycAutoallocationApproval,
},
},
error::LDNError,
external_services::{
filecoin::{get_allowance_for_address, get_multisig_threshold_for_actor},
github::{
github_async_new, CreateMergeRequestData, CreateRefillMergeRequestData, GithubWrapper,
},
},
helpers::{compare_allowance_and_allocation, parse_size_to_bytes, process_amount},
parsers::ParsedIssue,
};
use fplus_database::database::allocation_amounts::get_allocation_quantity_options;
use fplus_database::database::{
self,
allocators::{get_allocator, update_allocator_threshold},
};
use fplus_database::models::applications::Model as ApplicationModel;
use self::application::file::{
AllocationRequest, AllocationRequestType, AppState, ApplicationFile, DeepCompare,
ValidVerifierList, VerifierInput,
};
use crate::core::application::file::Allocation;
use std::collections::HashSet;
pub mod allocator;
pub mod application;
pub mod autoallocator;
#[derive(Deserialize)]
pub struct CreateApplicationInfo {
pub issue_number: String,
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct TriggerSSAInfo {
pub amount: String,
pub amount_type: String,
}
#[derive(Deserialize)]
pub struct BranchDeleteInfo {
pub owner: String,
pub repo: String,
pub branch_name: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct VerifierList(pub Vec<String>);
#[derive(Deserialize, Serialize, Debug)]
pub struct ApplicationProposalApprovalSignerInfo {
pub signing_address: String,
pub created_at: String,
pub message_cids: GrantDataCapCids,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct GrantDataCapCids {
pub message_cid: String,
pub increase_allowance_cid: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct CompleteNewApplicationProposalInfo {
pub signer: ApplicationProposalApprovalSignerInfo,
pub request_id: String,
pub new_allocation_amount: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct StorageProvidersChangeSignerInfo {
pub signing_address: String,
pub max_deviation_cid: Option<String>,
pub allowed_sps_cids: Option<HashMap<String, Vec<String>>>,
pub removed_allowed_sps_cids: Option<HashMap<String, Vec<String>>>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct StorageProvidersChangeProposalInfo {
pub signer: StorageProvidersChangeSignerInfo,
pub allowed_sps: Option<Vec<u64>>,
pub max_deviation: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct StorageProvidersChangeApprovalInfo {
pub signer: StorageProvidersChangeSignerInfo,
pub request_id: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct CompleteNewApplicationApprovalInfo {
pub signer: ApplicationProposalApprovalSignerInfo,
pub request_id: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct MoreInfoNeeded {
pub verifier_message: String,
}
#[derive(Debug)]
pub struct LDNApplication {
github: GithubWrapper,
pub application_id: String,
pub file_sha: String,
pub file_name: String,
pub branch_name: String,
}
#[derive(Deserialize, Debug)]
pub struct RefillInfo {
pub id: String,
pub amount: String,
pub amount_type: String,
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct NotifyRefillInfo {
pub owner: String,
pub repo: String,
pub issue_number: String,
}
#[derive(Deserialize)]
pub struct DcReachedInfo {
pub id: String,
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct ValidationPullRequestData {
pub pr_number: String,
pub user_handle: String,
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct ValidationIssueData {
pub issue_number: String,
pub user_handle: String,
}
#[derive(Deserialize)]
pub struct Allocator {
pub owner: String,
pub repo: String,
pub installation_id: Option<i64>,
pub multisig_address: Option<String>,
pub verifiers_gh_handles: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct ChangedAllocators {
pub files_changed: Vec<String>,
}
#[derive(Deserialize)]
pub struct AllocatorUpdateForceInfo {
pub files: Vec<String>,
pub allocators: Option<Vec<GithubQueryParams>>,
}
#[derive(Deserialize, Debug)]
pub struct LastAutoallocationQueryParams {
pub evm_wallet_address: Address,
}
#[derive(Deserialize)]
pub struct TriggerAutoallocationInfo {
pub message: KycAutoallocationApproval,
pub signature: String,
}
#[derive(Deserialize)]
pub struct GithubQueryParams {
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct ApplicationQueryParams {
pub id: String,
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct CompleteGovernanceReviewInfo {
pub allocation_amount: String,
pub client_contract_address: Option<String>,
}
#[derive(Deserialize)]
pub struct VerifierActionsQueryParams {
pub github_username: String,
pub id: String,
pub owner: String,
pub repo: String,
}
#[derive(Deserialize)]
pub struct SubmitKYCInfo {
pub message: KycApproval,
pub signature: String,
}
#[derive(Debug, Clone)]
pub struct ApplicationFileWithDate {
pub application_file: ApplicationFile,
pub updated_at: DateTime<Utc>,
pub pr_number: u64,
pub sha: String,
pub path: String,
}
#[derive(Debug, Serialize)]
pub struct ApplicationGithubInfo {
pub sha: String,
pub path: String,
}
#[derive(Debug, Serialize)]
pub struct ApplicationWithAllocation {
application_file: ApplicationFile, // Assuming ApplicationFile is the type for app_file
allocation: AllocationObject,
}
#[derive(Debug, Serialize)]
pub struct AllocationObject {
allocation_amount_type: String,
allocation_amount_quantity_options: Vec<String>,
}
impl LDNApplication {
pub async fn single_active(
pr_number: u64,
owner: String,
repo: String,
) -> Result<ApplicationFile, LDNError> {
let gh = github_async_new(owner, repo).await;
let (_, pull_request) = gh.get_pull_request_files(pr_number).await.unwrap();
let pull_request = pull_request.first().unwrap();
let pull_request: Response = reqwest::Client::new()
.get(pull_request.raw_url.to_string())
.send()
.await
.map_err(|e| LDNError::Load(format!("Failed to get pull request files /// {}", e)))?;
let pull_request = pull_request
.text()
.await
.map_err(|e| LDNError::Load(format!("Failed to get pull request files /// {}", e)))?;
if let Ok(app) = serde_json::from_str::<ApplicationFile>(&pull_request) {
Ok(app)
} else {
Err(LDNError::Load(format!(
"Pull Request {} Application file is corrupted or invalid format: {}",
pr_number,
serde_json::from_str::<ApplicationFile>(&pull_request).unwrap_err()
)))
}
}
async fn get_pr_files_and_app(
owner: String,
repo: String,
pr_number: u64,
) -> Result<
Option<(
(u64, Vec<octocrab::models::pulls::FileDiff>),
ApplicationFile,
)>,
LDNError,
> {
let gh = github_async_new(owner, repo).await;
let files = match gh.get_pull_request_files(pr_number).await {
Ok(files) => files,
Err(_) => return Ok(None),
};
let raw_url = match files.1.first() {
Some(f) => f.raw_url.clone(),
None => return Ok(None),
};
let response = reqwest::Client::new().get(raw_url).send().await;
let response = match response {
Ok(response) => response,
Err(_) => return Ok(None),
};
let response = response.text().await;
let response = match response {
Ok(response) => response,
Err(_) => return Ok(None),
};
let app = match ApplicationFile::from_str(&response) {
Ok(app) => app,
Err(e) => {
dbg!(&e);
return Ok(None);
}
};
Ok(Some((files, app)))
}
async fn load_pr_files(
pr: PullRequest,
owner: String,
repo: String,
) -> Result<Option<(String, String, ApplicationFile, PullRequest)>, LDNError> {
let result = Self::get_pr_files_and_app(owner.clone(), repo.clone(), pr.number).await;
if let Some((files, app)) = result? {
Ok(Some((
files.1.first().unwrap().sha.clone(),
files.1.first().unwrap().filename.clone(),
app,
pr.clone(),
)))
} else {
Ok(None)
}
}
async fn get_application_model(
application_id: String,
owner: String,
repo: String,
) -> Result<ApplicationModel, LDNError> {
let app_model_result =
database::applications::get_application(application_id, owner, repo, None).await;
match app_model_result {
Ok(model) => Ok(model),
Err(e) => Err(LDNError::Load(format!("Database error: {}", e))),
}
}
pub async fn load_from_db(
application_id: String,
owner: String,
repo: String,
) -> Result<ApplicationFile, LDNError> {
let app_model =
Self::get_application_model(application_id.clone(), owner.clone(), repo.clone())
.await?;
let app_str = app_model.application.ok_or_else(|| {
LDNError::Load(format!(
"Application {} does not have an application field",
application_id
))
})?;
ApplicationFile::from_str(&app_str)
.map_err(|e| LDNError::Load(format!("Failed to parse application file from DB: {}", e)))
}
pub async fn application_with_allocation_amount(
application_id: String,
owner: String,
repo: String,
) -> Result<ApplicationWithAllocation, LDNError> {
let app_model_result = database::applications::get_application(
application_id.clone(),
owner.clone(),
repo.clone(),
None,
)
.await;
let app_model = match app_model_result {
Ok(model) => model,
Err(e) => return Err(LDNError::Load(format!("Database error: {}", e))),
};
// Check if the application field is present and parse it
let app_str = app_model.application.ok_or_else(|| {
LDNError::Load(format!(
"Application {} does not have an application field",
application_id
))
})?;
let app_file = ApplicationFile::from_str(&app_str).map_err(|e| {
LDNError::Load(format!("Failed to parse application file from DB: {}", e))
})?;
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 allocation_amount_type = db_allocator
.allocation_amount_type
.unwrap_or("".to_string());
let allocation_amount_quantity_options = get_allocation_quantity_options(db_allocator.id)
.await
.unwrap();
Ok(ApplicationWithAllocation {
allocation: {
AllocationObject {
allocation_amount_type,
allocation_amount_quantity_options,
}
},
application_file: app_file,
})
}
pub async fn load(
application_id: String,
owner: String,
repo: String,
) -> Result<Self, LDNError> {
let gh = github_async_new(owner.to_string(), repo.to_string()).await;
let pull_requests = gh.list_pull_requests().await.unwrap();
let pull_requests = future::try_join_all(
pull_requests
.into_iter()
.map(|pr: PullRequest| {
LDNApplication::load_pr_files(pr, owner.clone(), repo.clone())
})
.collect::<Vec<_>>(),
)
.await?;
let result = pull_requests
.par_iter()
.filter(|pr| {
if let Some(r) = pr {
r.2.id.clone() == application_id.clone()
} else {
false
}
})
.collect::<Vec<_>>();
if let Some(Some(r)) = result.first() {
return Ok(Self {
github: gh,
application_id: r.2.id.clone(),
file_sha: r.0.clone(),
file_name: r.1.clone(),
branch_name: r.3.head.ref_field.clone(),
});
}
let app = Self::single_merged(application_id, owner.clone(), repo.clone()).await?;
Ok(Self {
github: gh,
application_id: app.1.id.clone(),
file_sha: app.0.sha.clone(),
file_name: app.0.path.clone(),
branch_name: "main".to_string(),
})
}
pub async fn all_applications() -> Result<Vec<(ApplicationFile, String, String)>, Vec<LDNError>>
{
let db_apps = database::applications::get_applications().await;
let mut all_apps: Vec<(ApplicationFile, String, String)> = Vec::new();
match db_apps {
Ok(apps) => {
for app in apps {
let app_file = match ApplicationFile::from_str(&app.application.unwrap()) {
Ok(app) => app,
Err(_) => {
continue;
}
};
all_apps.push((app_file, app.owner, app.repo));
}
Ok(all_apps)
}
Err(e) => Err(vec![LDNError::Load(format!(
"Failed to retrieve applications from the database /// {}",
e
))]),
}
}
pub async fn active(
owner: String,
repo: String,
filter: Option<String>,
) -> Result<Vec<ApplicationFile>, LDNError> {
// Get all active applications from the database.
let active_apps_result =
database::applications::get_active_applications(Some(owner), Some(repo)).await;
// Handle errors in getting active applications.
let active_apps = match active_apps_result {
Ok(apps) => apps,
Err(e) => return Err(LDNError::Load(format!("Database error: {}", e))),
};
// Filter and convert active applications.
let mut apps: Vec<ApplicationFile> = Vec::new();
for app_model in active_apps {
// If a filter was provided and it doesn't match the application's id, continue to the next iteration.
if let Some(ref filter_id) = filter {
if app_model.application.is_some() && app_model.id != filter_id.as_str() {
continue;
}
}
// Try to deserialize the `application` field to `ApplicationFile`.
if let Some(app_json) = app_model.application {
match from_str::<ApplicationFile>(&app_json) {
Ok(app) => apps.push(app),
//if error, don't push into apps
Err(err) => {
log::error!("Failed to parse application file from DB: {}", err);
}
}
}
}
Ok(apps)
}
pub async fn active_apps_with_last_update(
owner: String,
repo: String,
filter: Option<String>,
) -> Result<Vec<ApplicationFileWithDate>, LDNError> {
let gh = github_async_new(owner.to_string(), repo.to_string()).await;
let mut apps: Vec<ApplicationFileWithDate> = Vec::new();
let pull_requests = gh.list_pull_requests().await.unwrap();
let pull_requests = future::try_join_all(
pull_requests
.into_iter()
.map(|pr: PullRequest| {
LDNApplication::load_pr_files(pr, owner.clone(), repo.clone())
})
.collect::<Vec<_>>(),
)
.await
.unwrap();
for (sha, path, app_file, pr_info) in pull_requests.into_iter().flatten() {
if let Some(updated_at) = pr_info.updated_at {
let app_with_date = ApplicationFileWithDate {
application_file: app_file.clone(),
updated_at,
pr_number: pr_info.number,
sha,
path,
};
if filter.as_ref().map_or(true, |f| &app_file.id == f) {
apps.push(app_with_date);
}
}
}
Ok(apps)
}
pub async fn merged_apps_with_last_update(
owner: String,
repo: String,
filter: Option<String>,
) -> Result<Vec<ApplicationFileWithDate>, LDNError> {
let gh = Arc::new(github_async_new(owner.to_string(), repo.to_string()).await);
let applications_path = "applications";
let mut all_files_result = gh.get_files(applications_path).await.map_err(|e| {
LDNError::Load(format!(
"Failed to retrieve all files from GitHub. Reason: {}",
e
))
})?;
all_files_result
.items
.retain(|item| item.download_url.is_some() && item.name.ends_with(".json"));
let mut application_files_with_date: Vec<ApplicationFileWithDate> = vec![];
for fd in all_files_result.items {
let gh_clone = Arc::clone(&gh);
let result = gh_clone.get_last_modification_date(&fd.path).await;
if let Ok(updated_at) = result {
let map_result = LDNApplication::map_merged(fd).await;
if let Ok(Some((content, app_file))) = map_result {
application_files_with_date.push(ApplicationFileWithDate {
application_file: app_file,
updated_at,
pr_number: 0,
sha: content.sha,
path: content.path,
});
}
} else {
log::warn!("Failed to get last modification date for file: {}", fd.path);
}
}
let filtered_files: Vec<ApplicationFileWithDate> = if let Some(filter_val) = filter {
application_files_with_date
.into_iter()
.filter(|f| f.application_file.id == filter_val)
.collect()
} else {
application_files_with_date
};
Ok(filtered_files)
}
/// Create New Application
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 (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);
let branch_name = LDNPullRequest::application_branch_name(&application_id);
let multisig_address = if parsed_ldn.datacap.custom_multisig == "[X] Use Custom Multisig" {
"true".to_string()
} else {
"false".to_string()
};
match gh.get_file(&file_name, &branch_name).await {
// If the file does not exist, create a new application file
Err(_) => {
log::info!("File not found, creating new application file");
let application_file = ApplicationFile::new(
issue_number.clone(),
multisig_address,
parsed_ldn.version,
parsed_ldn.id.clone(),
parsed_ldn.client.clone(),
parsed_ldn.project,
parsed_ldn.datacap,
)
.await;
let applications = database::applications::get_applications().await.unwrap();
//check if id is in applications vector
let app_model = applications.iter().find(|app| app.id == application_id);
if let Some(app_model) = app_model {
// Add a comment to the GitHub issue
log::info!("Application already exists in the database");
Self::issue_pathway_mismatch_comment(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
Some(app_model.clone()),
)
.await?;
// Return an error as the application already exists
return Err(LDNError::New(
"Pathway mismatch: Application already exists".to_string(),
));
} else {
log::info!("Application does not exist in the database");
// Check the allowance for the address
match get_allowance_for_address(&application_id).await {
Ok(allowance) if allowance != "0" => {
log::info!("Allowance found and is not zero. Value is {}", allowance);
// If allowance is found and is not zero, issue the pathway mismatch comment
Self::issue_pathway_mismatch_comment(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
None,
)
.await?;
return Err(LDNError::New(
"Pathway mismatch: Application has already received datacap"
.to_string(),
));
}
Ok(_) => {
log::info!("Allowance not found or is zero");
}
Err(e) => {
//If error contains "DMOB api", add error label and comment to issue
if e.to_string().contains("DMOB api") {
log::error!("Error getting allowance for address. Unable to access blockchain data");
Self::add_error_label(
issue_number.clone(),
"".to_string(),
info.owner.clone(),
info.repo.clone(),
)
.await?;
Self::add_comment_to_issue(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
"Unable to access blockchain data for your address. Please contact support.".to_string(),
).await?;
return Err(LDNError::New(
"Error getting allowance for address. Unable to access blockchain".to_string(),
));
}
}
}
}
let file_content = match serde_json::to_string_pretty(&application_file) {
Ok(f) => f,
Err(e) => {
Self::add_error_label(
application_file.issue_number.clone(),
"".to_string(),
info.owner.clone(),
info.repo.clone(),
)
.await?;
return Err(LDNError::New(format!(
"Application issue file is corrupted /// {}",
e
)));
}
};
let app_id = parsed_ldn.id.clone();
let file_sha = LDNPullRequest::create_pr_for_new_application(
issue_number.clone(),
parsed_ldn.client.name.clone(),
branch_name.clone(),
LDNPullRequest::application_path(&app_id),
file_content.clone(),
info.owner.clone(),
info.repo.clone(),
)
.await?;
Self::issue_waiting_for_gov_review(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
)
.await?;
Self::update_issue_labels(
application_file.issue_number.clone(),
&[AppState::Submitted.as_str(), "waiting for allocator review"],
info.owner.clone(),
info.repo.clone(),
)
.await?;
match gh.get_pull_request_by_head(&branch_name).await {
Ok(prs) => {
if let Some(pr) = prs.first() {
let number = pr.number;
let issue_number = issue_number.parse::<i64>().map_err(|e| {
LDNError::New(format!(
"Parse issue number: {} to i64 failed. {}",
issue_number, e
))
})?;
database::applications::create_application(
application_id.clone(),
info.owner.clone(),
info.repo.clone(),
number,
issue_number,
file_content,
LDNPullRequest::application_path(&app_id),
)
.await
.map_err(|e| {
LDNError::New(format!(
"Application issue {} cannot create application in DB /// {}",
application_id, e
))
})?;
}
}
Err(e) => log::warn!("Failed to get pull request by head: {}", e),
}
Ok(LDNApplication {
github: gh,
application_id,
file_sha,
file_name,
branch_name,
})
}
// If the file already exists, return an error
Ok(_) => {
let app_model = match Self::get_application_model(
application_id.clone(),
info.owner.clone(),
info.repo.clone(),
)
.await
{
Ok(model) => Some(model),
Err(_) => {
return Err(LDNError::New(
"Original application file not found in db, but GH file exists"
.to_string(),
))
}
};
// Add a comment to the GitHub issue
Self::issue_pathway_mismatch_comment(
issue_number.clone(),
info.owner.clone(),
info.repo.clone(),
Some(app_model.unwrap()),
)
.await?;
// Return an error as the application already exists
Err(LDNError::New(
"Pathway mismatch: Allocator already assigned".to_string(),
))
}
}
}
/// Move application from Governance Review to Proposal
pub async fn complete_governance_review(
&self,
actor: String,
owner: String,
repo: String,
allocation_amount: String,
client_contract_address: Option<String>,
) -> Result<ApplicationFile, LDNError> {
match self.app_state().await {
Ok(s) => match s {
AppState::KYCRequested
| AppState::Submitted
| AppState::AdditionalInfoRequired
| AppState::AdditionalInfoSubmitted => {
let app_file: ApplicationFile = self.file().await?;
let allocation_amount_parsed = process_amount(allocation_amount.clone());
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_parsed.clone()),
)
.await?;
let uuid = uuidv4::uuid::v4();
let request = AllocationRequest::new(
actor.clone(),
uuid,
AllocationRequestType::First,
allocation_amount_parsed,
);
let app_file = app_file.complete_governance_review(
actor.clone(),
request,
client_contract_address.clone(),
);
let file_content = serde_json::to_string_pretty(&app_file).unwrap();
let app_path = &self.file_name.clone();
let app_branch = self.branch_name.clone();
Self::issue_datacap_request_trigger(
app_file.clone(),
owner.clone(),
repo.clone(),
)
.await?;
match LDNPullRequest::add_commit_to(
app_path.to_string(),
app_branch.clone(),
LDNPullRequest::application_move_to_proposal_commit(&actor),
file_content,
self.file_sha.clone(),
owner.clone(),
repo.clone(),
)
.await
{
Some(()) => {
match self.github.get_pull_request_by_head(&app_branch).await {
Ok(prs) => {
if let Some(pr) = prs.first() {
let number = pr.number;
database::applications::update_application(
app_file.id.clone(),
owner.clone(),
repo.clone(),
number,
serde_json::to_string_pretty(&app_file).unwrap(),
Some(app_path.clone()),
None,
client_contract_address,
)
.await
.map_err(|e| {
LDNError::Load(format!(
"Failed to update application: {} /// {}",
app_file.id, e
))
})?;
Self::issue_datacap_allocation_requested(
app_file.clone(),
app_file.get_active_allocation(),
owner.clone(),
repo.clone(),
)
.await?;
Self::update_issue_labels(
app_file.issue_number.clone(),
&[AppState::ReadyToSign.as_str()],
owner.clone(),
repo.clone(),
)
.await?;
Self::issue_ready_to_sign(
app_file.issue_number.clone(),
owner.clone(),
repo.clone(),
)
.await?;
}
}
Err(e) => log::warn!("Failed to get pull request by head: {}", e),
};
Ok(app_file)
}
None => Err(LDNError::New(format!(
"Application issue {} cannot be triggered(1)",
self.application_id
))),
}
}
_ => Err(LDNError::New(format!(
"Application issue {} cannot be triggered(2)",
self.application_id
))),
},
Err(e) => Err(LDNError::New(format!(
"Application issue {} cannot be triggered {}(3)",
self.application_id, e
))),
}