forked from MettaChain/PropChain-contract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2767 lines (2458 loc) · 100 KB
/
Copy pathlib.rs
File metadata and controls
2767 lines (2458 loc) · 100 KB
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
#![allow(clippy::clone_on_copy)] // fires inside ink! generated storage code
#![cfg_attr(not(feature = "std"), no_std, no_main)]
#![allow(
clippy::needless_borrows_for_generic_args,
clippy::too_many_arguments,
clippy::upper_case_acronyms,
dead_code
)]
use propchain_traits::{ComplianceChecker, *};
#[ink::contract]
pub mod compliance_registry {
use ink::prelude::vec::Vec;
use ink::storage::Mapping;
use propchain_traits::ComplianceOperation;
use super::*;
/// Represents the verification status of a user
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum VerificationStatus {
NotVerified,
Pending,
Verified,
Rejected,
Expired,
}
/// Supported jurisdictions
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum Jurisdiction {
US,
EU,
UK,
Singapore,
UAE,
Other,
}
/// Supported operations that can be enabled/disabled per jurisdiction
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum AllowedOperation {
Transfer,
ListForSale,
Purchase,
CreateEscrow,
ReleaseEscrow,
BridgeTransfer,
UpdateMetadata,
RegisterProperty,
}
/// Matrix of allowed operations for a jurisdiction
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode, Default)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct OperationsMatrix {
pub transfer: bool,
pub list_for_sale: bool,
pub purchase: bool,
pub create_escrow: bool,
pub release_escrow: bool,
pub bridge_transfer: bool,
pub update_metadata: bool,
pub register_property: bool,
}
/// Token jurisdiction configuration
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct TokenJurisdictionConfig {
pub jurisdiction: Jurisdiction,
pub operations: OperationsMatrix,
pub is_active: bool,
}
/// Risk level assessment
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum RiskLevel {
Low,
Medium,
High,
Prohibited,
}
/// Document verification types
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum DocumentType {
Passport,
NationalId,
DriverLicense,
BirthCertificate,
ProofOfAddress,
CorporateDocument,
}
/// Biometric authentication methods
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum BiometricMethod {
None,
Fingerprint,
FaceRecognition,
VoiceRecognition,
IrisScan,
MultiFactor,
}
/// Sanctions list sources
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum SanctionsList {
UN,
OFAC,
EU,
UK,
Singapore,
UAE,
Multiple,
}
/// GDPR consent status
#[derive(Debug, PartialEq, Eq, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum ConsentStatus {
NotGiven,
Given,
Withdrawn,
Expired,
}
/// AML risk factors
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct AMLRiskFactors {
pub pep_status: bool, // Politically Exposed Person
pub high_risk_country: bool,
pub suspicious_transaction_pattern: bool,
pub large_transaction_volume: bool,
pub source_of_funds_verified: bool,
}
/// Jurisdiction-specific compliance requirements
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct JurisdictionRules {
pub requires_kyc: bool,
pub requires_aml: bool,
pub requires_sanctions_check: bool,
pub minimum_verification_level: u8, // 1-5 scale
pub data_retention_days: u32,
pub requires_biometric: bool,
}
/// User compliance data (stored on-chain)
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct ComplianceData {
pub status: VerificationStatus,
pub jurisdiction: Jurisdiction,
pub risk_level: RiskLevel,
pub verification_timestamp: Timestamp,
pub expiry_timestamp: Timestamp,
pub kyc_hash: [u8; 32],
pub aml_checked: bool,
pub sanctions_checked: bool,
// Enhanced KYC fields
pub document_type: DocumentType,
pub biometric_method: BiometricMethod,
pub risk_score: u8, // 0-100 risk score
// Enhanced AML fields
pub aml_risk_factors: AMLRiskFactors,
pub sanctions_list_checked: SanctionsList,
// Privacy and GDPR
pub gdpr_consent: ConsentStatus,
pub data_encrypted: bool,
pub consent_timestamp: Timestamp,
pub data_retention_until: Timestamp,
}
/// Tax-specific compliance status reported by the tax compliance module
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct TaxComplianceStatus {
pub jurisdiction_code: u32,
pub reporting_period: u64,
pub last_checked_at: Timestamp,
pub last_payment_at: Timestamp,
pub outstanding_tax: Balance,
pub reporting_submitted: bool,
pub legal_documents_verified: bool,
pub clearance_expiry: Timestamp,
pub violation_count: u32,
}
/// Compliance audit log entry
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct AuditLog {
pub account: AccountId,
pub action: u8, // 0=verification, 1=aml_check, 2=sanctions_check, 3=consent_update, etc.
pub timestamp: Timestamp,
pub verifier: AccountId,
}
/// Verification request for off-chain processing
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct VerificationRequest {
pub account: AccountId,
pub jurisdiction: Jurisdiction,
pub document_hash: [u8; 32], // Hash of document for verification
pub biometric_hash: [u8; 32], // Hash of biometric data
pub request_timestamp: Timestamp,
pub request_id: u64,
pub status: VerificationStatus,
}
/// Integration service provider information
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct ServiceProvider {
pub provider_id: AccountId,
pub service_type: u8, // 0=KYC, 1=AML, 2=Sanctions, 3=All
pub is_active: bool,
pub last_update: Timestamp,
}
#[ink(storage)]
pub struct ComplianceRegistry {
/// Contract owner (admin)
owner: AccountId,
/// Authorized verifiers who can update compliance status
verifiers: Mapping<AccountId, bool>,
/// User compliance data
compliance_data: Mapping<AccountId, ComplianceData>,
/// Jurisdiction-specific requirements
jurisdiction_rules: Mapping<Jurisdiction, JurisdictionRules>,
/// Compliance audit log (indexed by account and log number)
audit_logs: Mapping<(AccountId, u64), AuditLog>,
/// Audit log counters per account
audit_log_count: Mapping<AccountId, u64>,
/// Data retention policies (days per jurisdiction)
retention_policies: Mapping<Jurisdiction, u32>,
/// Encryption keys mapping (hash of encrypted data location)
encrypted_data_hashes: Mapping<AccountId, [u8; 32]>,
/// Pending verification requests (for off-chain processing)
verification_requests: Mapping<u64, VerificationRequest>,
/// Request counter
request_counter: u64,
/// Service providers registry
service_providers: Mapping<AccountId, ServiceProvider>,
/// Account to pending request mapping
account_requests: Mapping<AccountId, u64>,
/// ZK compliance contract address (optional)
zk_compliance_contract: Option<AccountId>,
/// Authorized tax compliance modules
tax_modules: Mapping<AccountId, bool>,
/// Optional tax compliance state per account
tax_compliance_status: Mapping<AccountId, TaxComplianceStatus>,
/// Global KYC funnel metrics
kyc_metrics: KycMetrics,
/// KYC funnel metrics scoped by jurisdiction
jurisdiction_kyc_metrics: Mapping<Jurisdiction, KycMetrics>,
/// Merkle root of the sanctions list for on-chain verification
sanctions_list_merkle_root: [u8; 32],
/// Cache of screening results per account
screening_cache: Mapping<AccountId, ScreeningResult>,
/// TTL for cached screening results in seconds
screening_cache_ttl: u64,
/// Per-token jurisdiction configuration: tokenId -> TokenJurisdictionConfig
token_jurisdictions: Mapping<u64, TokenJurisdictionConfig>,
/// Operations matrix for each jurisdiction (default rules)
jurisdiction_operations: Mapping<Jurisdiction, OperationsMatrix>,
}
/// Errors
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
/// Caller is not authorized
NotAuthorized,
/// User is not verified
NotVerified,
/// Verification has expired
VerificationExpired,
/// User has high risk level
HighRisk,
/// Jurisdiction is prohibited
ProhibitedJurisdiction,
/// User already verified
AlreadyVerified,
/// Consent not given
ConsentNotGiven,
/// Data retention period expired
DataRetentionExpired,
/// Invalid risk score
InvalidRiskScore,
/// Invalid document type
InvalidDocumentType,
/// Jurisdiction not supported
JurisdictionNotSupported,
/// Sanctions check failed
SanctionsCheckFailed,
/// Operation not allowed for this token's jurisdiction
OperationNotAllowed,
/// Token not found in jurisdiction registry
TokenNotFound,
/// Invalid operation specified
InvalidOperation,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::NotAuthorized => write!(f, "Caller is not authorized"),
Error::NotVerified => write!(f, "User is not verified"),
Error::VerificationExpired => write!(f, "Verification has expired"),
Error::HighRisk => write!(f, "User has high risk level"),
Error::ProhibitedJurisdiction => write!(f, "Jurisdiction is prohibited"),
Error::AlreadyVerified => write!(f, "User already verified"),
Error::ConsentNotGiven => write!(f, "Consent not given"),
Error::DataRetentionExpired => write!(f, "Data retention period expired"),
Error::InvalidRiskScore => write!(f, "Invalid risk score"),
Error::InvalidDocumentType => write!(f, "Invalid document type"),
Error::JurisdictionNotSupported => write!(f, "Jurisdiction not supported"),
Error::SanctionsCheckFailed => write!(f, "Sanctions check failed"),
Error::OperationNotAllowed => {
write!(f, "Operation not allowed for this token's jurisdiction")
}
Error::TokenNotFound => write!(f, "Token not found in jurisdiction registry"),
Error::InvalidOperation => write!(f, "Invalid operation specified"),
}
}
}
impl ContractError for Error {
fn error_code(&self) -> u32 {
match self {
Error::NotAuthorized => {
propchain_traits::errors::compliance_codes::COMPLIANCE_UNAUTHORIZED
}
Error::NotVerified => {
propchain_traits::errors::compliance_codes::COMPLIANCE_NOT_VERIFIED
}
Error::VerificationExpired => {
propchain_traits::errors::compliance_codes::COMPLIANCE_EXPIRED
}
Error::HighRisk => {
propchain_traits::errors::compliance_codes::COMPLIANCE_HIGH_RISK
}
Error::ProhibitedJurisdiction => {
propchain_traits::errors::compliance_codes::COMPLIANCE_PROHIBITED_JURISDICTION
}
Error::AlreadyVerified => {
propchain_traits::errors::compliance_codes::COMPLIANCE_ALREADY_VERIFIED
}
Error::ConsentNotGiven => {
propchain_traits::errors::compliance_codes::COMPLIANCE_CONSENT_NOT_GIVEN
}
Error::DataRetentionExpired => {
propchain_traits::errors::compliance_codes::COMPLIANCE_DATA_RETENTION_EXPIRED
}
Error::InvalidRiskScore => {
propchain_traits::errors::compliance_codes::COMPLIANCE_INVALID_RISK_SCORE
}
Error::InvalidDocumentType => {
propchain_traits::errors::compliance_codes::COMPLIANCE_INVALID_DOCUMENT_TYPE
}
Error::JurisdictionNotSupported => {
propchain_traits::errors::compliance_codes::COMPLIANCE_JURISDICTION_NOT_SUPPORTED
}
Error::SanctionsCheckFailed => {
propchain_traits::errors::compliance_codes::COMPLIANCE_SANCTIONS_CHECK_FAILED
}
Error::OperationNotAllowed => {
propchain_traits::errors::compliance_codes::COMPLIANCE_SANCTIONS_CHECK_FAILED + 1
}
Error::TokenNotFound => {
propchain_traits::errors::compliance_codes::COMPLIANCE_SANCTIONS_CHECK_FAILED + 2
}
Error::InvalidOperation => {
propchain_traits::errors::compliance_codes::COMPLIANCE_SANCTIONS_CHECK_FAILED + 3
}
}
}
fn error_description(&self) -> &'static str {
match self {
Error::NotAuthorized => {
"Caller does not have permission to perform this compliance operation"
}
Error::NotVerified => "The user has not completed verification",
Error::VerificationExpired => {
"The user's verification has expired and needs renewal"
}
Error::HighRisk => "The user has been assessed as high risk and is not permitted",
Error::ProhibitedJurisdiction => {
"The user's jurisdiction is prohibited from this operation"
}
Error::AlreadyVerified => "The user is already verified and cannot be re-verified",
Error::ConsentNotGiven => "The user has not provided the required consent",
Error::DataRetentionExpired => {
"The data retention period for this record has expired"
}
Error::InvalidRiskScore => {
"The risk score provided is invalid or out of acceptable range"
}
Error::InvalidDocumentType => "The document type is invalid or not accepted",
Error::JurisdictionNotSupported => {
"The specified jurisdiction is not currently supported"
}
Error::SanctionsCheckFailed => "The account has failed sanctions screening",
Error::OperationNotAllowed => {
"The requested operation is not allowed for this token's jurisdiction"
}
Error::TokenNotFound => {
"The specified token ID was not found in the jurisdiction registry"
}
Error::InvalidOperation => "The specified operation is invalid or not recognized",
}
}
fn error_category(&self) -> ErrorCategory {
ErrorCategory::Compliance
}
fn error_i18n_key(&self) -> &'static str {
match self {
Error::NotAuthorized => "compliance.unauthorized",
Error::NotVerified => "compliance.not_verified",
Error::VerificationExpired => "compliance.verification_expired",
Error::HighRisk => "compliance.high_risk",
Error::ProhibitedJurisdiction => "compliance.prohibited_jurisdiction",
Error::AlreadyVerified => "compliance.already_verified",
Error::ConsentNotGiven => "compliance.consent_not_given",
Error::DataRetentionExpired => "compliance.data_retention_expired",
Error::InvalidRiskScore => "compliance.invalid_risk_score",
Error::InvalidDocumentType => "compliance.invalid_document_type",
Error::JurisdictionNotSupported => "compliance.jurisdiction_not_supported",
Error::SanctionsCheckFailed => "compliance.sanctions_check_failed",
Error::OperationNotAllowed => "compliance.operation_not_allowed",
Error::TokenNotFound => "compliance.token_not_found",
Error::InvalidOperation => "compliance.invalid_operation",
}
}
}
pub type Result<T> = core::result::Result<T, Error>;
/// Events
#[ink(event)]
pub struct VerificationUpdated {
#[ink(topic)]
account: AccountId,
status: VerificationStatus,
timestamp: Timestamp,
}
#[ink(event)]
pub struct ComplianceCheckPerformed {
#[ink(topic)]
account: AccountId,
passed: bool,
timestamp: Timestamp,
}
#[ink(event)]
pub struct ConsentUpdated {
#[ink(topic)]
account: AccountId,
consent_status: ConsentStatus,
timestamp: Timestamp,
}
#[ink(event)]
pub struct DataRetentionExpired {
#[ink(topic)]
account: AccountId,
timestamp: Timestamp,
}
#[ink(event)]
pub struct AuditLogCreated {
#[ink(topic)]
account: AccountId,
action: u8,
timestamp: Timestamp,
}
#[ink(event)]
pub struct VerificationRequestCreated {
#[ink(topic)]
account: AccountId,
#[ink(topic)]
request_id: u64,
jurisdiction: Jurisdiction,
timestamp: Timestamp,
}
#[ink(event)]
pub struct ServiceProviderRegistered {
#[ink(topic)]
provider: AccountId,
service_type: u8,
timestamp: Timestamp,
}
#[ink(event)]
pub struct TaxComplianceStatusUpdated {
#[ink(topic)]
account: AccountId,
jurisdiction_code: u32,
outstanding_tax: Balance,
timestamp: Timestamp,
}
#[ink(event)]
pub struct AddressFlagged {
#[ink(topic)]
account: AccountId,
status: ScreeningStatus,
matched_lists: Vec<SanctionsList>,
timestamp: u64,
}
#[ink(event)]
pub struct SanctionsListUpdated {
merkle_root: [u8; 32],
updated_by: AccountId,
timestamp: u64,
}
#[ink(event)]
pub struct TokenJurisdictionUpdated {
#[ink(topic)]
token_id: u64,
jurisdiction: Jurisdiction,
is_active: bool,
timestamp: Timestamp,
}
#[ink(event)]
pub struct JurisdictionOperationsUpdated {
#[ink(topic)]
jurisdiction: Jurisdiction,
timestamp: Timestamp,
}
/// Compliance report for an account (audit trail and reporting - Issue #45)
#[derive(Debug, Clone, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct ComplianceReport {
pub account: AccountId,
pub is_compliant: bool,
pub jurisdiction: Jurisdiction,
pub status: VerificationStatus,
pub risk_level: RiskLevel,
pub kyc_verified: bool,
pub aml_checked: bool,
pub sanctions_checked: bool,
pub audit_log_count: u64,
pub last_audit_timestamp: Timestamp,
pub verification_expiry: Timestamp,
pub tax_compliant: bool,
pub outstanding_tax: Balance,
}
/// Verification workflow status (workflow management - Issue #45)
#[derive(Debug, Clone, Copy, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum WorkflowStatus {
Pending,
InProgress,
Verified,
Rejected,
Expired,
}
/// Regulatory report summary for a jurisdiction and period (reporting automation - Issue #45)
#[derive(Debug, Clone, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct RegulatoryReport {
pub jurisdiction: Jurisdiction,
pub period_start: Timestamp,
pub period_end: Timestamp,
pub verifications_count: u64,
pub compliant_accounts: u64,
pub aml_checks_count: u64,
pub sanctions_checks_count: u64,
}
/// KYC funnel metrics used to track conversion and verification rates.
#[derive(Debug, Clone, Copy, Default, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct KycMetrics {
pub requests_created: u64,
pub pending_requests: u64,
pub verification_attempts: u64,
pub successful_verifications: u64,
pub failed_verifications: u64,
pub converted_requests: u64,
pub conversion_rate_bips: u32,
pub verification_rate_bips: u32,
}
/// Sanctions screening summary (sanction list monitoring - Issue #45)
#[derive(Debug, Clone, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct SanctionsScreeningSummary {
pub total_screened: u64,
pub passed: u64,
pub failed: u64,
pub lists_checked: Vec<u8>,
}
/// Screening result for an address
#[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct ScreeningResult {
pub account: AccountId,
pub status: ScreeningStatus,
pub matched_lists: Vec<SanctionsList>,
pub match_details: String,
pub screened_at: u64,
pub expires_at: u64,
}
/// Screening status
#[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum ScreeningStatus {
Cleared,
Flagged,
Blocked,
}
impl Default for ComplianceRegistry {
fn default() -> Self {
Self::new()
}
}
impl ComplianceRegistry {
/// Constructor
#[ink(constructor)]
pub fn new() -> Self {
let caller = Self::env().caller();
let mut verifiers = Mapping::default();
verifiers.insert(caller, &true);
let mut registry = Self {
owner: caller,
verifiers,
compliance_data: Mapping::default(),
jurisdiction_rules: Mapping::default(),
audit_logs: Mapping::default(),
audit_log_count: Mapping::default(),
retention_policies: Mapping::default(),
encrypted_data_hashes: Mapping::default(),
verification_requests: Mapping::default(),
request_counter: 0,
service_providers: Mapping::default(),
account_requests: Mapping::default(),
zk_compliance_contract: None,
tax_modules: Mapping::default(),
tax_compliance_status: Mapping::default(),
kyc_metrics: KycMetrics::default(),
jurisdiction_kyc_metrics: Mapping::default(),
sanctions_list_merkle_root: [0u8; 32],
screening_cache: Mapping::default(),
screening_cache_ttl: 3600,
token_jurisdictions: Mapping::default(),
jurisdiction_operations: Mapping::default(),
};
// Initialize default jurisdiction rules
registry.init_default_jurisdiction_rules();
// Initialize default jurisdiction operations matrices
registry.init_default_jurisdiction_operations();
registry
}
/// Initialize default jurisdiction-specific rules
fn init_default_jurisdiction_rules(&mut self) {
// US rules
self.jurisdiction_rules.insert(
&Jurisdiction::US,
&JurisdictionRules {
requires_kyc: true,
requires_aml: true,
requires_sanctions_check: true,
minimum_verification_level: 3,
data_retention_days: 2555, // 7 years
requires_biometric: false,
},
);
// EU rules (GDPR compliant)
self.jurisdiction_rules.insert(
&Jurisdiction::EU,
&JurisdictionRules {
requires_kyc: true,
requires_aml: true,
requires_sanctions_check: true,
minimum_verification_level: 3,
data_retention_days: 1095, // 3 years (GDPR)
requires_biometric: false,
},
);
// UK rules
self.jurisdiction_rules.insert(
&Jurisdiction::UK,
&JurisdictionRules {
requires_kyc: true,
requires_aml: true,
requires_sanctions_check: true,
minimum_verification_level: 3,
data_retention_days: 1825, // 5 years
requires_biometric: false,
},
);
// Singapore rules
self.jurisdiction_rules.insert(
&Jurisdiction::Singapore,
&JurisdictionRules {
requires_kyc: true,
requires_aml: true,
requires_sanctions_check: true,
minimum_verification_level: 4,
data_retention_days: 1825, // 5 years
requires_biometric: true,
},
);
// UAE rules
self.jurisdiction_rules.insert(
&Jurisdiction::UAE,
&JurisdictionRules {
requires_kyc: true,
requires_aml: true,
requires_sanctions_check: true,
minimum_verification_level: 4,
data_retention_days: 1825, // 5 years
requires_biometric: true,
},
);
}
/// Initialize default operation matrices for each jurisdiction
fn init_default_jurisdiction_operations(&mut self) {
// US: Most operations allowed except bridge transfers by default
self.jurisdiction_operations.insert(
&Jurisdiction::US,
&OperationsMatrix {
transfer: true,
list_for_sale: true,
purchase: true,
create_escrow: true,
release_escrow: true,
bridge_transfer: false, // Restrict cross-chain in US
update_metadata: true,
register_property: true,
},
);
// EU: All operations allowed with full compliance
self.jurisdiction_operations.insert(
&Jurisdiction::EU,
&OperationsMatrix {
transfer: true,
list_for_sale: true,
purchase: true,
create_escrow: true,
release_escrow: true,
bridge_transfer: true,
update_metadata: true,
register_property: true,
},
);
// UK: Similar to EU
self.jurisdiction_operations.insert(
&Jurisdiction::UK,
&OperationsMatrix {
transfer: true,
list_for_sale: true,
purchase: true,
create_escrow: true,
release_escrow: true,
bridge_transfer: true,
update_metadata: true,
register_property: true,
},
);
// Singapore: Bridge transfers restricted but others allowed
self.jurisdiction_operations.insert(
&Jurisdiction::Singapore,
&OperationsMatrix {
transfer: true,
list_for_sale: true,
purchase: true,
create_escrow: true,
release_escrow: true,
bridge_transfer: false, // MAS regulations restrict cross-chain
update_metadata: true,
register_property: true,
},
);
// UAE: Similar to Singapore
self.jurisdiction_operations.insert(
&Jurisdiction::UAE,
&OperationsMatrix {
transfer: true,
list_for_sale: true,
purchase: true,
create_escrow: true,
release_escrow: true,
bridge_transfer: false,
update_metadata: true,
register_property: true,
},
);
// Other jurisdictions: Conservative defaults
self.jurisdiction_operations.insert(
&Jurisdiction::Other,
&OperationsMatrix {
transfer: true,
list_for_sale: true,
purchase: true,
create_escrow: true,
release_escrow: true,
bridge_transfer: false,
update_metadata: true,
register_property: true,
},
);
}
/// Add authorized verifier (KYC service)
#[ink(message)]
pub fn add_verifier(&mut self, verifier: AccountId) -> Result<()> {
self.ensure_owner()?;
self.verifiers.insert(verifier, &true);
Ok(())
}
/// Submit KYC verification with enhanced document and biometric info
#[ink(message)]
pub fn submit_verification(
&mut self,
account: AccountId,
jurisdiction: Jurisdiction,
kyc_hash: [u8; 32],
risk_level: RiskLevel,
document_type: DocumentType,
biometric_method: BiometricMethod,
risk_score: u8,
) -> Result<()> {
self.ensure_verifier()?;
let result = self.submit_verification_internal(
account,
jurisdiction,
kyc_hash,
risk_level,
document_type,
biometric_method,
risk_score,
);
if result.is_err() {
self.record_kyc_verification_attempt(jurisdiction, false, false);
}
result
}
fn submit_verification_internal(
&mut self,
account: AccountId,
jurisdiction: Jurisdiction,
kyc_hash: [u8; 32],
risk_level: RiskLevel,
document_type: DocumentType,
biometric_method: BiometricMethod,
risk_score: u8,
) -> Result<()> {
if risk_score > 100 {
return Err(Error::InvalidRiskScore);
}
// Check jurisdiction rules
let rules = self
.jurisdiction_rules
.get(jurisdiction)
.ok_or(Error::JurisdictionNotSupported)?;
// Validate minimum verification level
let verification_level =
self.calculate_verification_level(document_type, biometric_method, risk_score);
if verification_level < rules.minimum_verification_level {
return Err(Error::NotVerified);
}
let now = self.env().block_timestamp();
let expiry = now + (365 * 24 * 60 * 60 * 1000); // 1 year validity
let retention_days = rules.data_retention_days as u64;
let retention_until = now + (retention_days * 24 * 60 * 60 * 1000);
let compliance = ComplianceData {
status: VerificationStatus::Verified,
jurisdiction,
risk_level,
verification_timestamp: now,
expiry_timestamp: expiry,
kyc_hash,
aml_checked: false, // Will be set separately