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
//! # Deip Module
//! A module for managing digital assets.
//!
//! - [`multisig::Config`](./trait.Config.html)
//! - [`Call`](./enum.Call.html)
//!
//! ## Overview
//!
//! This module contains functionality for managing different types of digital assets. 
//!
//! It provides a hierarchy to simply operate digital assets in the real world. 
//! The module contains entities Project and  Content of the Project with belongs to multi Account aka Team. 
//!
//! Besides, the Module provides Proof of share functionality. Proof of Share is a term we 
//! use for a special cryptographic proof that a sender actually sent, and the receiver 
//! has actually received an encrypted payload and a key to decrypt it. Please refer to the attached image.
//! Includes entities like NDA and NDA Access Request.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! * `add_domain` - Add cryptographic hash of DomainId
//! * `create_project` - Create Project belongs to Account (Team)
//! * [`create_investment_opportunity`](./enum.Call.html#variant.create_investment_opportunity)
//! * [`invest`](./enum.Call.html#variant.invest)
//! * `update_project` - Update Project info
//! * `create_project_content` - Create Project Content (Digital Asset)
//! * `create_project_nda` - Create NDA contract between sides
//! * `create_nda_content_access_request` - Some side request access to the data of contract
//! * `fulfill_nda_content_access_request` - Granter fulfill access request to the data
//! * `reject_nda_content_access_request` - Granter reject access request to the data
//! * `create_review` - Create Review
//!
//! [`Call`]: ./enum.Call.html
//! [`Config`]: ./trait.Config.html

#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{
    codec::{Decode, Encode}, ensure,
    decl_module, decl_storage, decl_event, decl_error, 
    StorageMap,
    dispatch::{ DispatchResult, Parameter },
    storage::{ IterableStorageMap, IterableStorageDoubleMap },
    traits::{Currency, ReservableCurrency}
};
use frame_system::{ self as system, ensure_signed };
use sp_std::vec::Vec;
use sp_runtime::{ RuntimeDebug, traits::Member };
pub use sp_core::{ H160, H256 };
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

mod project_token_sale;
use project_token_sale::{Id as InvestmentId,
    Status as ProjectTokenSaleStatus,
    Info as ProjectTokenSale,
    TokenInfo as ProjectTokenSaleTokenInfo};

mod project_token_sale_contribution;
use project_token_sale_contribution::{Contribution as ProjectTokenSaleContribution};

/// A maximum number of Domains. When domains reaches this number, no new domains can be added.
pub const MAX_DOMAINS: u32 = 100;

/// Possible statuses of Project inherited from Project Content type
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub enum ProjectContentType {
    Announcement,
    FinalResult,
    MilestoneArticle,
    MilestoneBook,
    MilestoneChapter,
    MilestoneCode,
    MilestoneConferencePaper,
    MilestoneCoverPage,
    MilestoneData,
    MilestoneExperimentFindings,
    MilestoneMethod,
    MilestoneNegativeResults,
    MilestonePatent,
    MilestonePoster,
    MilestonePreprint,
    MilestonePresentation,
    MilestoneRawData,
    MilestoneResearchProposal,
    MilestoneTechnicalReport,
    MilestoneThesis,
}


impl Default for ProjectContentType {
    fn default() -> ProjectContentType { ProjectContentType::Announcement }
}

/// Configuration trait. Pallet depends on frame_system and pallet_timestamp. 
pub trait Config: frame_system::Config + pallet_timestamp::Config {
    /// The overarching event type.
    type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
    
    type DeipAccountId: Into<Self::AccountId> + Parameter + Member;

    type Currency: ReservableCurrency<Self::AccountId>;
}

/// Unique Project ID reference
pub type ProjectId = H160;
/// Unique DomainId reference
pub type DomainId = H160;
/// Unique Project Contnt reference 
pub type ProjectContentId = H160;
/// Unique NDA reference 
pub type NdaId = H160;
/// Unique NdaAccess Request reference 
pub type NdaAccessRequestId = H160;
/// Unique Review reference 
pub type ReviewId = H160;

pub type ProjectOf<T> = Project<<T as system::Config>::Hash, <T as system::Config>::AccountId>;
pub type ReviewOf<T> = Review<<T as system::Config>::Hash, <T as system::Config>::AccountId>;
pub type NdaOf<T> = Nda<<T as system::Config>::Hash, <T as system::Config>::AccountId, <T as pallet_timestamp::Config>::Moment>;
pub type NdaAccessRequestOf<T> = NdaAccessRequest<<T as system::Config>::Hash, <T as system::Config>::AccountId>;
pub type ProjectContentOf<T> = ProjectContent<<T as system::Config>::Hash, <T as system::Config>::AccountId>;
pub type ProjectTokenSaleOf<T> = ProjectTokenSale<<T as pallet_timestamp::Config>::Moment, BalanceOf<T>>;
pub type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as system::Config>::AccountId>>::Balance;
pub type ProjectTokenSaleContributionOf<T> = ProjectTokenSaleContribution<<T as system::Config>::AccountId, BalanceOf<T>, <T as pallet_timestamp::Config>::Moment>;

#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub enum InvestmentOpportunity<Moment, Balance> {
    ProjectTokenSale {
        /// a moment when the sale starts. Must be later than current moment.
        start_time: Moment,
        /// a moment when the sale ends. Must be later than `start_time`.
        end_time: Moment,
        /// amount of units to raise. This must be greater or equal to `ExistentialDeposit`
        /// (see [frame_support::traits::Currency] for details).
        soft_cap: Balance,
        /// amount upper limit of units to raise. Must be greater or equal to `soft_cap`.
        hard_cap: Balance,
        /// specifies how many tokens of the project are intended to sale.
        security_tokens_on_sale: u64,
    },
}

/// Review 
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct Review<Hash, AccountId> {
    /// Reference for external world and uniques control 
    external_id: ReviewId,
    /// Reference to the Team 
    author: AccountId,
    /// Hash of content
    content: Hash,
    /// List of Domains aka tags Project matches
    domains: Vec<DomainId>,
    /// Model number by which the evaluation is carried out
    assessment_model: u32,
    /// percent in "50.00 %" format
    weight: Vec<u8>,
    /// Reference to Project Content
    project_content_external_id: ProjectContentId,
}

/// PPossible project domains
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct Domain {
    /// Reference for external world and uniques control 
    pub external_id: DomainId,
}

/// Core entity of pallet. Everything connected to Project. 
/// Only Account (Team) stand before Project in hierarchy.
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct Project<Hash, AccountId> {
    /// Determine visible project or not 
    is_private: bool,
    /// Reference for external world and uniques control 
    external_id: ProjectId,
    /// Reference to the Team 
    team_id: AccountId,
    /// Hash of Project description
    description: Hash,
    /// List of Domains aka tags Project matches
    domains: Vec<DomainId>,
}

/// Digital asset. Contains information of content and authors of Digital asset.
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct ProjectContent<Hash, AccountId> {
    /// Reference for external world and uniques control 
    external_id: ProjectContentId,
    /// Reference to the Project 
    project_external_id: ProjectId,
    /// Reference to the Team
    team_id: AccountId,
    /// Type of content. Determine status of Project
    content_type: ProjectContentType,
    /// Hash of the content ddescription
    description: Hash,
    /// Hast of digital asset
    content: Hash,
    /// Authors of Digital asset
    authors: Vec<AccountId>,
    /// List of References to other digital assets whith will be used in current digital asset.
    references: Option<Vec<ProjectContentId>>
    
}

/// NDA contract between parties. Usually about dislocating or not dislocating some confidential info
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct Nda<Hash, AccountId, Moment>  {
    /// Reference to Multisig Account with involved parties
    contract_creator: AccountId,
    /// Reference for external world and uniques control 
    external_id: NdaId,
    /// Unix Timestamp. Exparation date of contract
    end_date: Moment,
    /// Unix Timestamp. Entry into force of the contract
    start_date: Option<Moment>,
    /// Hash of the contract
    contract_hash: Hash,
    /// Involved Parties
    parties: Vec<AccountId>,
    /// Involved Projects 
    projects: Vec<ProjectId>,
}

/// Statuses of NDA access requests
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
enum NdaAccessRequestStatus {
    Pending,
    Fulfilled,
    Rejected,
}


impl Default for NdaAccessRequestStatus {
    fn default() -> NdaAccessRequestStatus { NdaAccessRequestStatus::Pending }
}

/// NDA access request. One of the partice may decide to request to receive 
/// some info included into contract. Holder should fulfill or reject this request. 
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)]
pub struct NdaAccessRequest<Hash, AccountId>  {
    /// Reference for external world and uniques control 
    external_id: NdaAccessRequestId,
    /// Reference to NDA 
    nda_external_id: NdaId,
    /// Reference to Requester (creator of this request)
    requester: AccountId,
    /// Payload witch need to be decrypted
    encrypted_payload_hash: Hash,
    /// IV of encrypted payload
    encrypted_payload_iv: Vec<u8>,
    /// Execution status
    status: NdaAccessRequestStatus,
    /// Reference to access granter if approved
    grantor: Option<AccountId>,
    /// Ecrypted key witch can decrypt payload
    encrypted_payload_encryption_key: Option<Vec<u8>>,
    /// Proof that requester has access to the encrypted data with his key 
    proof_of_encrypted_payload_encryption_key: Option<Vec<u8>>,
}

decl_event! {
    /// Events type.
    pub enum Event<T> 
    where 
        AccountId = <T as frame_system::Config>::AccountId,
        Project = ProjectOf<T>,
        Review = ReviewOf<T>,
        ProjectTokenSale = ProjectTokenSaleOf<T>,
    {
        // ==== Projects ====

        /// Event emitted when a project has been created. [BelongsTo, Project]
        ProjectCreated(AccountId, Project),
        /// Event emitted when a project is removed by the owner. [BelongsTo, Project]
        ProjectRemoved(AccountId, Project),
        /// Event emitted when a project is removed by the owner. [BelongsTo, ProjectId]
        ProjectUpdated(AccountId, ProjectId),

        // ==== Project Content ====
       
        /// Event emitted when a project contnet has been created. [BelongsTo, ProjectContentId]
        ProjectContnetCreated(AccountId, ProjectContentId),

        // ==== NDA ====
       
        /// Event emitted when a NDA has been created. [BelongsTo, NdaId]
        NdaCreated(AccountId, NdaId),
        /// Event emitted when a NDA Access request has been created. [BelongsTo, NdaAccessRequestId]
        NdaAccessRequestCreated(AccountId, NdaAccessRequestId),
        //  /// Event emitted when a NDA Access request has been fulfilled. [BelongsTo, NdaAccessRequestId]
        NdaAccessRequestFulfilled(AccountId, NdaAccessRequestId),
        //  /// Event emitted when a NDA Access request has been rejected. [BelongsTo, NdaAccessRequestId]
        NdaAccessRequestRejected(AccountId, NdaAccessRequestId),

        /// Added a domain. [Creator, DomainId]
		DomainAdded(AccountId, DomainId),

        /// Event emitted when a review has been created. [BelongsTo, Review]
        ReviewCreated(AccountId, Review),

        /// Event emitted when a token sale for project has been created.
        ProjectTokenSaleCreated(ProjectId, ProjectTokenSale),
        /// Event emitted when a token sale for project has been activated.
        ProjectTokenSaleActivated(ProjectId, InvestmentId),
        /// Event emitted when a token sale for project has finished.
        ProjectTokenSaleFinished(ProjectId, InvestmentId),
        /// Event emitted when a token sale for project has expired.
        ProjectTokenSaleExpired(ProjectId, InvestmentId),
        /// Event emitted when DAO contributed to the project token sale
        ProjectTokenSaleContributed(InvestmentId, AccountId),
    }
}

// Errors inform users that something went wrong.
decl_error! {
    pub enum Error for Module<T: Config> {
        // ==== Projects ====
        
        /// The project does not exist.
        NoSuchProject,
        /// The project is created by another account, so caller can't remove it.
        NotProjectOwner,
        /// Cannot add domain into the porject because this domain not exists
        DomainNotExists,
        /// Cannot add a project because a project with this ID is already a exists
		ProjectAlreadyExists,

        // ==== Project Content ====
       
        /// Cannot add a project content because a project content with this ID is already a exists.
        ProjectContentAlreadyExists,
        /// Project does not belong to the team.
        ProjectNotBelongToTeam,
        /// The project content does not exist.
        NoSuchProjectContent,
        /// The Reference does not exist.
        NoSuchReference, 
        /// Cannot add a project content because a project with this ID is already a finished
		ProjectAlreadyFinished,


        // ==== Domains ====
        
        /// Cannot add another domain because the limit is already reached
        DomianLimitReached,
        /// Cannot add domain because this domain is already a exists
        DomainAlreadyExists,

        // ==== NDA ====
        
        /// Cannot add a NDA because a NDA with this ID is already a exists.
        NdaAlreadyExists,
        /// Nda Access Request with this ID is  already a exists.
        NdaAccessRequestAlreadyExists,
        /// The NDA with this ID does not exist.
        NoSuchNda,
        /// The NDA Access Request with this ID does not exist.
        NoSuchNdaAccessRequest,
        /// The start of the contract has not yet arrived, so contract can't be fulfilled or rejected
        NdaContractIsNotActiveYet,
        /// NDA start date must be later or equal current moment
        NdaStartDateMustBeLaterOrEqualCurrentMoment,
        /// NDA end date must be later current moment
        NdaEndDateMustBeLaterCurrentMoment,
        /// NDA start date must be less than end date
        NdaStartDateMustBeLessThanEndDate,
        /// Team of all projects must specified as party
        TeamOfAllProjectsMustSpecifiedAsParty,
        /// Nda access request already finalized
        NdaAccessRequestAlreadyFinalized,

        /// Cannot add a review because a review with this ID is already a exists
        ReviewAlreadyExists,
        
        // ==== General =====

        /// Access Forbiten
        NoPermission,

        // Project token sale errors
        TokenSaleStartTimeMustBeLaterOrEqualCurrentMoment,
        TokenSaleEndTimeMustBeLaterStartTime,
        TokenSaleSoftCapMustBeGreaterOrEqualMinimum,
        TokenSaleHardCapShouldBeGreaterOrEqualSoftCap,
        TokenSaleScheduledAlready,
        TokenSaleAlreadyExists,
        TokenSaleBalanceIsNotEnough,
        TokenSaleProjectReservedOverflow,

        // Possible errors when DAO tries to contribute to a project token sale
        ContributionProjectTokenSaleNotFound,
        ContributionProjectTokenSaleNotActive,
        ContributionNotEnoughFunds,
    }
}

decl_storage! {
    trait Store for Module<T: Config> as Deip {
        /// Map from ProjectID to Project Info
        ProjectMap get(fn project): map hasher(identity) ProjectId => ProjectOf<T>;
        /// Project list, guarantees uniquest and provides Project listing
        Projects get(fn projects): Vec<(ProjectId, T::AccountId)>;

        ProjectTokens: map hasher(identity) ProjectId => ProjectTokenSaleTokenInfo;

        ProjectTokenSaleMap get(fn project_token_sale): map hasher(identity) InvestmentId => ProjectTokenSaleOf<T>;
        ProjectTokenSaleByProjectIdStatus get(fn token_sales): Vec<(ProjectId, ProjectTokenSaleStatus, InvestmentId)>;
        /// Index for fast lookup a token sale by its end time
        ProjectTokenSaleEndTimes: Vec<(T::Moment, InvestmentId)>;

        /// Contains contributions to project token sales from DAOs
        ProjectTokenSaleContributions: map hasher(identity) InvestmentId => Vec<(T::AccountId, ProjectTokenSaleContributionOf<T>)>;

        /// temporary object that holds information about how many project's tokens
        /// belong to the user
        OwnedProjectTokens: double_map hasher(blake2_128_concat) T::AccountId, hasher(identity) ProjectId => u64;

        /// Map to Project Content Info
        ProjectContentMap get(fn project_content_entity): double_map hasher(identity) ProjectId, hasher(identity) ProjectContentId => ProjectContentOf<T>;
        /// Project Content list, guarantees uniquest and provides Project Conent listing
        ProjectsContent get(fn project_content_list): Vec<(ProjectContentId, ProjectId, T::AccountId)>;

        /// NDA list, guarantees uniquest and provides NDA listing
        Ndas get(fn nda_list): Vec<(ProjectId, T::AccountId)>;
        /// Map to NDA Info
        NdaMap get(fn nda): map hasher(identity) NdaId => NdaOf<T>;
        
        /// NDA Access Requests list, guarantees uniquest and provides NDA Access Requests listing
        NdaAccessRequests get(fn nda_requests): Vec<(NdaAccessRequestId, NdaId, T::AccountId)>;
        /// Map to NDA Access Requests Info
        NdaAccessRequestMap get(fn nda_request): map hasher(identity) NdaAccessRequestId => NdaAccessRequestOf<T>;

        /// Map from ReviewID to Review Info
        ReviewMap get(fn review): map hasher(identity) ReviewId => ReviewOf<T>;
        /// Review list, guarantees uniquest and provides Review listing
        Reviews get(fn reviews): Vec<(ReviewId, T::AccountId)>;

        // The set of all Domains.
        Domains get(fn domains) config(): map hasher(blake2_128_concat) DomainId => Domain;
        // The total number of domains stored in the map.
        // Because the map does not store its size, we must store it separately
        DomainCount get(fn domain_count) config(): u32;
    }
}

// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
decl_module! {
    pub struct Module<T: Config> for enum Call where origin: T::Origin {
        // Errors must be initialized if they are used by the pallet.
        type Error = Error<T>;

        // Events must be initialized if they are used by the pallet.
        fn deposit_event() = default;
       
        /// Allow a user to create project.
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `project`: [Project](./struct.Project.html) to be created.
        #[weight = 10_000]
        fn create_project(origin,
            is_private: bool,
            external_id: ProjectId,
            team_id: T::DeipAccountId,
            description: T::Hash,
            domains: Vec<DomainId>
        ) {
            // Check that the extrinsic was signed and get the signer.
            // This function will return an error if the extrinsic is not signed.
            // https://substrate.dev/docs/en/knowledgebase/runtime/origin
            let account = ensure_signed(origin)?;
            
            let project = ProjectOf::<T> {
                is_private,
                external_id,
                team_id: team_id.into(),
                description,
                domains
            };
            
            for domain in &project.domains {
                ensure!(Domains::contains_key(&domain), Error::<T>::DomainNotExists);
            }

            let mut projects = Projects::<T>::get();

            // We don't want to add duplicate projects, so we check whether the potential new
			// project is already present in the list. Because the list is always ordered, we can
			// leverage the binary search which makes this check O(log n).
			match projects.binary_search_by_key(&project.external_id, |&(a,_)| a) {
				// If the search succeeds, the project is already a exists, so just return
				Ok(_) => return Err(Error::<T>::ProjectAlreadyExists.into()),
				// If the search fails, the project is not a exists and we learned the index where
				// they should be inserted
				Err(index) => {
					projects.insert(index, (project.external_id, project.team_id.clone()));
					Projects::<T>::put(projects);
				}
			};

            // Store the projects related to account
            ProjectMap::<T>::insert(project.external_id, project.clone());
            ProjectTokens::insert(project.external_id, ProjectTokenSaleTokenInfo{ total: 100_000u64, reserved: 0u64 });

            // Emit an event that the project was created.
            Self::deposit_event(RawEvent::ProjectCreated(account, project));
        }

        /// Allows DAO to create an investment opportunity.
        ///
        /// The origin for this call must be _Signed_.
        ///
        /// - `external_id`: id of the sale. Must be unique.
        /// - `project_id`: id of the project which tokens are intended to sale.
        /// - `investment_type`: specifies type of created investment opportunity. For possible
        /// variants and details see [`InvestmentOpportunity`].
        #[weight = 10_000]
        fn create_investment_opportunity(origin,
            external_id: InvestmentId,
            project_id: ProjectId,
            investment_type: InvestmentOpportunity<T::Moment, BalanceOf<T>>,
        ) -> DispatchResult {
            let account = ensure_signed(origin)?;

            match investment_type {
                InvestmentOpportunity::ProjectTokenSale{
                    start_time,
                    end_time,
                    soft_cap,
                    hard_cap,
                    security_tokens_on_sale,
                } => Self::create_project_token_sale_impl(account, external_id, project_id, start_time, end_time, soft_cap, hard_cap, security_tokens_on_sale)
            }
        }

        /// Allows DAO to invest to an opportunity.
        ///
        /// The origin for this call must be _Signed_.
        ///
        /// - `id`: identifier of the investment opportunity
        /// - `amount`: amount of units to invest. The account should have enough funds on
        ///     the balance. This amount is reserved until the investment finished or expired
        /// (see [frame_support::traits::ReservableCurrency] for details).
        #[weight = 10_000]
        fn invest(origin,
            id: InvestmentId,
            amount: BalanceOf<T>
        ) -> DispatchResult {
            let account = ensure_signed(origin)?;
            Self::contribute_to_project_token_sale_impl(account, id, amount)
        }

        /// Allow a user to update project.
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `project_id`: [Project]((./struct.Project.html)) identifier (external_id) to be updated
        /// - `description`: Optional. Hash of description
        /// - `is_private`: Optional.  Determine visible project or not 
        #[weight = 10_000]
        fn update_project(origin, project_id: ProjectId, description: Option<T::Hash>, is_private: Option<bool>) -> DispatchResult {
            // Check that the extrinsic was signed and get the signer.
            // This function will return an error if the extrinsic is not signed.
            // https://substrate.dev/docs/en/knowledgebase/runtime/origin
            let account = ensure_signed(origin)?;

            ProjectMap::<T>::mutate_exists(project_id, |maybe_project| -> DispatchResult {
                let project = maybe_project.as_mut().ok_or(Error::<T>::NoSuchProject)?;

                ensure!(project.team_id == account, Error::<T>::NoPermission);

                // TODO make sure that we don't lose first 2 bytes of the hash
                if let Some(value) = description  {
                    project.description = value;
                }

                if let Some(value) = is_private  {
                    project.is_private = value;
                }
                
                Ok(())
            })?;

            // Emit an event that the project was updated.
            Self::deposit_event(RawEvent::ProjectUpdated(account, project_id));

            Ok(())
        }

        /// Allow a user to create project content.
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `content`: [Content](./struct.ProjectContent.html) to be created
        #[weight = 10_000]
        fn create_project_content(origin,
            external_id: ProjectContentId,
            project_external_id: ProjectId,
            team_id: T::DeipAccountId,
            content_type: ProjectContentType,
            description: T::Hash,
            content: T::Hash,
            authors: Vec<T::DeipAccountId>,
            references: Option<Vec<ProjectContentId>>
        ) {
            let account = ensure_signed(origin)?;
            
            let content = ProjectContentOf::<T> {
                external_id,
                project_external_id,
                team_id: team_id.into(),
                content_type,
                description,
                content,
                authors: authors.into_iter().map(Into::into).collect(),
                references
            };

            let mut project_content = ProjectsContent::<T>::get();

            let index_to_insert_content = project_content.binary_search_by_key(&content.external_id, |&(a,_, _)| a)
                .err().ok_or(Error::<T>::ProjectContentAlreadyExists)?;

            let project = ProjectMap::<T>::get(content.project_external_id);

            ensure!(!project.external_id.is_zero(), Error::<T>::NoSuchProject);
            ensure!(project.team_id == content.team_id, Error::<T>::ProjectNotBelongToTeam);
            ensure!(!Self::is_project_finished(&project.external_id), Error::<T>::ProjectAlreadyFinished);


            if let Some(references) = &content.references {
                let is_all_references_exists = references
                    .iter()
                    .all(|&reference| project_content.binary_search_by_key(&reference,|&(id,_, _)| id).is_ok());

                ensure!(is_all_references_exists, Error::<T>::NoSuchReference);
            }

            project_content.insert(index_to_insert_content, (content.external_id, content.project_external_id,  content.team_id.clone()));
            ProjectsContent::<T>::put(project_content);

            // Store the content
            ProjectContentMap::<T>::insert(project.external_id, content.external_id, content.clone());

            // Emit an event that the content was created.
            Self::deposit_event(RawEvent::ProjectContnetCreated(account, content.external_id));
        }

        /// Allow a user to create [NDA](./struct.Nda.html).
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `end_date`: Unix Timestamp. Exparation date of contract
        /// - `contract_hash`: Hash of the contract
        /// - `maybe_start_date`: Optional. Unix Timestamp. Entry into force of the contract
        /// - `parties`: List of involved Parties
        /// - `projects`: List of involved Projects
        #[weight = 10_000]
        fn create_project_nda(origin,  
            external_id: NdaId,
            end_date: T::Moment,
            contract_hash: T::Hash,
            maybe_start_date: Option<T::Moment>,
            parties: Vec<T::DeipAccountId>,
            projects: Vec<ProjectId>
        ) {
            let mut projects = projects;
            projects.dedup();
            let contract_creator = ensure_signed(origin)?;
            let timestamp = pallet_timestamp::Module::<T>::get();

            ensure!(end_date > timestamp, Error::<T>::NdaEndDateMustBeLaterCurrentMoment);

            if let Some(start_date) = maybe_start_date {
                ensure!(start_date >= timestamp, Error::<T>::NdaStartDateMustBeLaterOrEqualCurrentMoment);
                ensure!(end_date > start_date, Error::<T>::NdaStartDateMustBeLessThanEndDate);
            }
            
            let parties: Vec<T::AccountId> = parties.into_iter().map(Into::into).collect();
            
            projects.iter()
                .try_for_each(|id| -> DispatchResult {
                    let project = ProjectMap::<T>::get(id);

                    ensure!(!project.external_id.is_zero(), Error::<T>::NoSuchProject);
                    ensure!(parties.contains(&project.team_id), Error::<T>::TeamOfAllProjectsMustSpecifiedAsParty);

                    Ok(())
                })?;

            let mut nda_list = Ndas::<T>::get();

            let index_to_insert_nda = nda_list.binary_search_by_key(&external_id, |&(external_id, ..)| external_id)
                .err().ok_or(Error::<T>::NdaAlreadyExists)?;
            
               
            let nda = Nda {
                contract_creator: contract_creator.clone(),
                external_id,
                end_date,
                start_date: maybe_start_date,
                contract_hash,
                parties,
                projects
            };
            
            nda_list.insert(index_to_insert_nda, (nda.external_id, contract_creator.clone()));
            Ndas::<T>::put(nda_list);

            NdaMap::<T>::insert(nda.external_id, nda);

            // Emit an event that the NDA was created.
            Self::deposit_event(RawEvent::NdaCreated(contract_creator, external_id));

        }

        /// Create [request](./struct.NdaAccessRequest.html) to access NDA content
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `external_id`: Reference for external world and uniques control 
        /// - `nda_external_id`: Reference to NDA 
        /// - `encrypted_payload_hash`: Payload witch need to be decrypted
        /// - `encrypted_payload_iv`: IV of encrypted payload
        #[weight = 10_000]
        fn create_nda_content_access_request(
            origin, 
            external_id: NdaAccessRequestId,
            nda_external_id: NdaId,
            encrypted_payload_hash: T::Hash,
            encrypted_payload_iv: Vec<u8>,
        ) {
            let account = ensure_signed(origin)?;
            let timestamp = pallet_timestamp::Module::<T>::get();

            let nda = NdaMap::<T>::get(nda_external_id);
            
            ensure!(!nda.external_id.is_zero(), Error::<T>::NoSuchNda);
            ensure!(nda.start_date <= Some(timestamp), Error::<T>::NdaContractIsNotActiveYet);

            let mut nda_requests = NdaAccessRequests::<T>::get();

            let index_to_insert_nda_request = nda_requests.binary_search_by_key(&external_id, |&(external_id, ..)| external_id)
                .err().ok_or(Error::<T>::NdaAccessRequestAlreadyExists)?;
            
            let nda_request = NdaAccessRequest {
                external_id,
                nda_external_id, 

                requester: account.clone(),
                encrypted_payload_hash,
                encrypted_payload_iv,
                status: NdaAccessRequestStatus::Pending,
                grantor: None,
                encrypted_payload_encryption_key: None,
                proof_of_encrypted_payload_encryption_key: None,
            };
            nda_requests.insert(index_to_insert_nda_request, (external_id, nda_external_id, account.clone()));
            NdaAccessRequests::<T>::put(nda_requests);

            NdaAccessRequestMap::<T>::insert(nda_request.external_id, nda_request);

            // Emit an event that the NDA was created.
            Self::deposit_event(RawEvent::NdaAccessRequestCreated(account, external_id));
            

        }
        
        /// Fulfill NDA access request
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `external_id`: Reference for external world and uniques control 
        /// - `encrypted_payload_encryption_key`: Ecrypted key witch can decrypt payload
        /// - `proof_of_encrypted_payload_encryption_key`: Proof that requester has access to the encrypted data with his key 
        #[weight = 10_000]
        fn fulfill_nda_content_access_request(
            origin, 
            external_id: NdaAccessRequestId,
            encrypted_payload_encryption_key: Vec<u8>,
            proof_of_encrypted_payload_encryption_key: Vec<u8>,
        ) {
            let account = ensure_signed(origin)?;

            NdaAccessRequestMap::<T>::mutate_exists(external_id, |maybe_nda_access_request| -> DispatchResult {
                let mut nda_access_request = maybe_nda_access_request.as_mut().ok_or(Error::<T>::NoSuchNdaAccessRequest)?;

                ensure!(nda_access_request.status == NdaAccessRequestStatus::Pending, Error::<T>::NdaAccessRequestAlreadyFinalized);
                ensure!(NdaMap::<T>::contains_key(nda_access_request.nda_external_id), Error::<T>::NoSuchNda);

                nda_access_request.status = NdaAccessRequestStatus::Fulfilled;
                nda_access_request.grantor = Some(account.clone());
                nda_access_request.encrypted_payload_encryption_key = Some(encrypted_payload_encryption_key);
                nda_access_request.proof_of_encrypted_payload_encryption_key = Some(proof_of_encrypted_payload_encryption_key);

                Ok(())
            })?;

            // Emit an event that the NDA was fulfilled.
            Self::deposit_event(RawEvent::NdaAccessRequestFulfilled(account, external_id));

        }

        /// Reject NDA access request
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `external_id`: Reference for external world and uniques control 
         #[weight = 10_000]
         fn reject_nda_content_access_request(
             origin, 
             external_id: NdaAccessRequestId,
         ) {
             let account = ensure_signed(origin)?;
 
             NdaAccessRequestMap::<T>::mutate_exists(external_id, |maybe_nda_access_request| -> DispatchResult {
                let mut nda_access_request = maybe_nda_access_request.as_mut().ok_or(Error::<T>::NoSuchNdaAccessRequest)?;
                
                
                ensure!(nda_access_request.status == NdaAccessRequestStatus::Pending, Error::<T>::NdaAccessRequestAlreadyFinalized);
                ensure!(NdaMap::<T>::contains_key(nda_access_request.nda_external_id), Error::<T>::NoSuchNda);
 
                nda_access_request.status = NdaAccessRequestStatus::Rejected;
                 
                Ok(())
             })?;
 
             // Emit an event that the NDA was rejected.
             Self::deposit_event(RawEvent::NdaAccessRequestRejected(account, external_id));
 
        }

        /// Allow a user to create review.
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `review`: [Review](./struct.Review.html) to be created
        #[weight = 10_000]
        fn create_review(origin,
            external_id: ReviewId,
            author: T::DeipAccountId,
            content: T::Hash,
            domains: Vec<DomainId>,
            assessment_model: u32,
            weight: Vec<u8>,
            project_content_external_id: ProjectContentId,
        ) {
            let account = ensure_signed(origin)?;
            
            let review = ReviewOf::<T> {
                external_id,
                author: author.into(),
                content,
                domains,
                assessment_model,
                weight,
                project_content_external_id
            };

            let mut reviews = Reviews::<T>::get();

            let index_to_insert_review = reviews.binary_search_by_key(&review.external_id, |&(a,_)| a)
                .err().ok_or(Error::<T>::ReviewAlreadyExists)?;

            ProjectsContent::<T>::get().iter().find(|(id, ..)| id == &review.project_content_external_id)
                .ok_or(Error::<T>::NoSuchProjectContent)?;
            
            for domain in &review.domains {
                ensure!(Domains::contains_key(&domain), Error::<T>::DomainNotExists);
            }

            reviews.insert(index_to_insert_review, (review.external_id,  review.author.clone()));
            Reviews::<T>::put(reviews);

            // Store the content
            ReviewMap::<T>::insert(review.external_id, review.clone());

            // Emit an event that the content was created.
            Self::deposit_event(RawEvent::ReviewCreated(account, review));
        }


        
        /// Allow a user to create domains.
        ///
		/// The origin for this call must be _Signed_. 
        ///
		/// - `project`: [Domain](./struct.Domain.html) to be created.
        #[weight = 10_000]
        fn add_domain(origin, domain: Domain) {
            let account = ensure_signed(origin)?;
        
            let domain_count = DomainCount::get();
            ensure!(domain_count < MAX_DOMAINS, Error::<T>::DomianLimitReached);

            let external_id = domain.external_id;
        
            // We don't want to add duplicate domains, so we check whether the potential new
            // domain is already present in the list. Because the domains is stored as a hash
            // map this check is constant time O(1)
            ensure!(!Domains::contains_key(&external_id), Error::<T>::DomainAlreadyExists);

           
            
            // Insert the new domin and emit the event
            Domains::insert(&external_id, domain);
            DomainCount::put(domain_count + 1); // overflow check not necessary because of maximum
            
            Self::deposit_event(RawEvent::DomainAdded(account, external_id));
        }

        // TODO: temporarily disabled since more appropriate approach
        // should be used (for example, Off-Chain Workers)
        // fn on_finalize() {
        //     Self::process_project_token_sales();
        // }
    }
}

impl<T: Config> Module<T> {
	fn is_project_finished(project_id: &ProjectId) -> bool {
		ProjectContentMap::<T>::iter_prefix_values(project_id)
            .any(|x| x.content_type == ProjectContentType::FinalResult)
	}
    pub fn get_projects() -> Vec<(ProjectId, T::AccountId)>{
        Self::projects()
    }
    pub fn get_project(project_id: &ProjectId) -> ProjectOf<T> {
        ProjectMap::<T>::get(project_id)
    }
    pub fn get_domains() -> Vec<Domain> {
        <Domains as IterableStorageMap<DomainId, Domain>>::iter()
            .map(|(_id, domain)| domain)
            .collect()
    }
    pub fn get_domain(domain_id: &DomainId) -> Domain {
        Domains::get(domain_id)
    }
    pub fn get_project_content_list(content_ids: &Option<Vec<ProjectContentId>>) -> Vec<ProjectContentOf<T>>{
        <ProjectContentMap<T> as IterableStorageDoubleMap<ProjectId, ProjectContentId, ProjectContentOf<T>>>::iter()
            .filter(|(_project_id, project_content_id, ..)| {                
                match content_ids {
                    Some(ids) => ids.contains(&project_content_id),
                    _ => true
                }
            })
            .map(|(_project_id, _project_content_id, content)| content)
            .collect()
    }
    pub fn get_project_content(project_id: &ProjectId, project_content_id: &ProjectContentId) -> ProjectContentOf<T> {
        ProjectContentMap::<T>::get(project_id, project_content_id)
    }
    pub fn get_nda_list() -> Vec<NdaOf<T>>{
        <NdaMap<T> as IterableStorageMap<NdaId, NdaOf<T>>>::iter()
            .map(|(_id, nda)| nda)
            .collect()
    }
    pub fn get_nda(nda_id: &NdaId) -> NdaOf<T> {
        NdaMap::<T>::get(nda_id)
    }
    pub fn get_reviews() -> Vec<ReviewOf<T>>{
        <ReviewMap<T> as IterableStorageMap<ReviewId, ReviewOf<T>>>::iter()
            .map(|(_id, review)| review)
            .collect()
    }
    pub fn get_review(review_id: &ReviewId) -> ReviewOf<T> {
        ReviewMap::<T>::get(review_id)
    }
}