diff --git a/README.md b/README.md index 545c7503..1e1e377c 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Built with Rust and ink! for Substrate/Polkadot ecosystem, these smart contracts ## πŸš€ Features ### Core Capabilities + - **🏠 Asset Tokenization**: Transform physical real estate properties into tradable NFTs with legal compliance - **πŸ’° Secure Transfers**: Multi-signature property transfers with escrow protection - **πŸ”— Property Registry**: On-chain property ownership registry with metadata storage @@ -17,15 +18,18 @@ Built with Rust and ink! for Substrate/Polkadot ecosystem, these smart contracts - **πŸ’Ύ On-chain Storage**: Decentralized storage for property documents and metadata ### Advanced Features + - **⛓️ Cross-Chain Compatibility**: Designed for Substrate/Polkadot ecosystem with EVM compatibility - **πŸ“ˆ Property Valuation**: On-chain valuation oracle integration for real-time pricing - **πŸ” Property Discovery**: Efficient on-chain search and filtering capabilities - **πŸ“± Mobile Integration**: Lightweight contract interfaces for mobile dApps - **πŸ›‘οΈ Security First**: Formal verification and comprehensive audit coverage +- **πŸ“… Tax Compliance**: Automated tax calculation, payments, and deadline notifications ## πŸ‘₯ Target Audience This smart contract system is designed for: + - **Real Estate Tech Companies** building blockchain-based property platforms - **Property Investment Firms** seeking fractional ownership solutions - **Blockchain Developers** creating DeFi real estate applications on Substrate @@ -35,7 +39,9 @@ This smart contract system is designed for: ## πŸ› οΈ Quick Start ### Prerequisites + Ensure you have the following installed: + - **Rust** 1.70+ (stable toolchain) - **ink! CLI** for smart contract development - **Substrate Node** for local testing @@ -69,6 +75,7 @@ The contracts will be compiled and ready for deployment to Substrate-based netwo ## πŸš€ Development & Deployment ### Development Environment + ```bash ./scripts/build.sh # Build contracts in debug mode ./scripts/test.sh # Run unit tests @@ -76,6 +83,7 @@ cargo test # Run all tests including integration ``` ### Production Deployment + ```bash ./scripts/build.sh --release # Build optimized contracts ./scripts/deploy.sh --network westend # Deploy to testnet @@ -83,6 +91,7 @@ cargo test # Run all tests including integration ``` ### Testing Suite + ```bash ./scripts/test.sh # Run all tests ./scripts/test.sh --coverage # Run with coverage @@ -99,12 +108,14 @@ For comprehensive load testing documentation, see [Load Testing Guide](docs/LOAD ## 🌐 Network Configuration ### Supported Blockchains + - **Polkadot** (Mainnet, Westend Testnet) - **Kusama** (Mainnet) - **Substrate-based Parachains** (Custom networks) - **Local Development** (Substrate Node) ### Environment Configuration + ```env # Network NETWORK=westend @@ -122,6 +133,7 @@ TARGET=wasm32-unknown-unknown ## πŸ“š Documentation & Resources ### πŸ—οΈ Architecture Documentation (NEW!) + - **[πŸ“‹ Architecture Index](./docs/ARCHITECTURE_INDEX.md)** - Complete guide to all architecture docs - **[🌐 System Architecture Overview](./docs/SYSTEM_ARCHITECTURE_OVERVIEW.md)** - High-level system design and components - **[πŸ”— Component Interaction Diagrams](./docs/COMPONENT_INTERACTION_DIAGRAMS.md)** - Detailed interaction sequences @@ -130,22 +142,26 @@ TARGET=wasm32-unknown-unknown - **[πŸ“ Documentation Maintenance](./docs/ARCHITECTURE_DOCUMENTATION_MAINTENANCE.md)** - How we keep docs current ### Contract Documentation + - **[πŸ“– Contract API](./docs/contracts.md)** - Complete contract interface documentation - **[πŸ”— Integration Guide](./docs/integration.md)** - How to integrate with frontend applications - **[πŸš€ Deployment Guide](./docs/deployment.md)** - Contract deployment best practices - **[πŸ—οΈ Architecture](./docs/architecture.md)** - Contract design and technical architecture ### Frontend SDK + - **[πŸ“¦ Frontend SDK](./sdk/frontend/)** - TypeScript SDK for dApp integration - **[πŸ“– Frontend SDK Guide](./docs/FRONTEND_SDK_GUIDE.md)** - Comprehensive usage guide with API reference - **[πŸ’» Example React App](./sdk/frontend/examples/react-app/)** - Working Vite + React example ### Development Documentation + - **[πŸ› οΈ Development Setup](./DEVELOPMENT.md)** - Complete development environment setup - **[πŸ“‹ Contributing Guide](./CONTRIBUTING.md)** - How to contribute effectively - **[πŸŽ“ Tutorials](./docs/tutorials/)** - Step-by-step integration tutorials ### Repository Structure + ``` PropChain-contract/ β”œβ”€β”€ πŸ“ contracts/ # Main smart contract source code @@ -169,24 +185,28 @@ PropChain-contract/ ## πŸ› οΈ Technology Stack ### Smart Contract Development + - **πŸ¦€ Language**: Rust - Memory safety and performance - **⚑ Framework**: ink! - Substrate smart contract framework - **⛓️ Platform**: Substrate/Polkadot - Enterprise blockchain framework - **πŸ”— WASM**: WebAssembly compilation for blockchain deployment ### Development Tools + - **πŸ› οΈ Build**: Cargo - Rust package manager and build system - **πŸ§ͺ Testing**: Built-in Rust testing framework + ink! testing - **πŸ“– Documentation**: rustdoc - Auto-generated documentation - **πŸ”„ CI/CD**: GitHub Actions - Automated testing and deployment ### Blockchain Infrastructure + - **⛓️ Networks**: Polkadot, Kusama, Substrate parachains - **πŸ” Wallets**: Polkadot.js, Substrate-native wallets - **πŸ“Š Oracles**: Chainlink, Substrate price feeds - **πŸ” Explorers**: Subscan, Polkadot.js explorer ### Security & Verification + - **πŸ›‘οΈ Security**: Formal verification with cargo-contract - **πŸ” Auditing**: Comprehensive security audit process - **πŸ“‹ Standards**: ERC-721/1155 compatibility layers @@ -195,6 +215,7 @@ PropChain-contract/ ## πŸ† Project Status ### βœ… Completed Features + - [x] Property Registry Contract - [x] Escrow System - [x] Token Contract (ERC-721 compatible) @@ -205,18 +226,21 @@ PropChain-contract/ - [x] Documentation ### 🚧 In Progress + - [ ] Oracle Integration - [ ] Cross-chain Bridge - [ ] Mobile SDK - [ ] Advanced Analytics ### βœ… Recently Completed + - [x] Frontend SDK with TypeScript support - [x] Example React frontend application - [x] Frontend integration testing - [x] Frontend SDK documentation ### πŸ“‹ Planned Features + - [ ] Governance System - [ ] Insurance Integration - [ ] Mortgage Lending Protocol @@ -224,9 +248,10 @@ PropChain-contract/ ## 🀝 Contributing -We welcome contributions! Please read our [Contributing Guide](./CONTRIBUTING.md) to get started. +We welcome contributions! Please read our [Contributing Guide](./CONTRIBUTING.md) to get started. **Quick contribution steps:** + 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Run tests (`./scripts/test.sh`) @@ -241,12 +266,14 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) ## 🀝 Support & Community ### Get Help + - **πŸ› Report Issues**: [GitHub Issues](https://github.com/MettaChain/PropChain-contract/issues) - **πŸ“§ Email Support**: contracts@propchain.io - **πŸ“– Documentation**: [docs.propchain.io](https://docs.propchain.io) - **πŸ’¬ Discord**: [PropChain Community](https://discord.gg/propchain) ### Additional Resources + - **[🌐 Frontend Application](https://github.com/MettaChain/PropChain-FrontEnd)** - Client-side React/Next.js application - **[πŸ”’ Security Audits](./audits/)** - Third-party security audit reports - **[πŸ“Š Performance Metrics](./docs/performance.md)** - Benchmarks and optimization guides diff --git a/TODO.md b/TODO.md new file mode 100644 index 00000000..6eef0361 --- /dev/null +++ b/TODO.md @@ -0,0 +1,14 @@ +# TODO: Implement Tax Deadline Notifications + +## Plan Steps (Approved) + +1. [x] Update contracts/tax-compliance/src/tax_engine.rs: Add `days_until_due` helper function. +2. [x] Update contracts/tax-compliance/src/lib.rs: Add events `TaxDeadlineApproaching`, `TaxDeadlineNotification`; emit in `calculate_tax()` and `check_compliance()`. +3. [x] Update contracts/tax-compliance/src/compliance.rs: No changes needed (generate_alerts already supports PaymentDueSoon/TaxOverdue). +4. [x] Update docs/compliance-regulatory-framework.md: Document new features. +5. [x] Update README.md: Add feature mention. +6. [ ] Add/update tests in contracts/tax-compliance/src/lib.rs. +7. [ ] Run `cargo test` and `./scripts/test.sh`. +8. [ ] Complete task. + +Progress will be updated after each step. diff --git a/contracts/lib/src/lib.rs b/contracts/lib/src/lib.rs index b74c84ee..c0b8fdca 100644 --- a/contracts/lib/src/lib.rs +++ b/contracts/lib/src/lib.rs @@ -190,8 +190,15 @@ pub mod propchain_contracts { /// Reentrancy protection guard reentrancy_guard: ReentrancyGuard, + + /// Circuit breaker configuration for external calls + external_call_config: CircuitBreakerConfig, + + /// Circuit breaker states for each external dependency + external_call_breakers: Mapping, } + /// Escrow information #[derive( Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout, diff --git a/contracts/tax-compliance/src/lib.rs b/contracts/tax-compliance/src/lib.rs index f0ce14ea..881d7ae2 100644 --- a/contracts/tax-compliance/src/lib.rs +++ b/contracts/tax-compliance/src/lib.rs @@ -291,17 +291,47 @@ mod tax_compliance { verified: bool, } - #[ink(event)] - pub struct ComplianceRegistrySyncRequested { - #[ink(topic)] - property_id: u64, - #[ink(topic)] - jurisdiction_code: u32, - reporting_period: u64, - outstanding_tax: Balance, - legal_documents_verified: bool, - reporting_submitted: bool, - } +#[ink(event)] +pub struct ComplianceRegistrySyncRequested { + #[ink(topic)] + property_id: u64, + #[ink(topic)] + jurisdiction_code: u32, + reporting_period: u64, + outstanding_tax: Balance, + legal_documents_verified: bool, + reporting_submitted: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum DeadlineAlertLevel { + Approaching, + Urgent, +} + +#[ink(event)] +pub struct TaxDeadlineApproaching { + #[ink(topic)] + property_id: u64, + #[ink(topic)] + jurisdiction_code: u32, + reporting_period: u64, + due_at: Timestamp, + days_remaining: u16, + alert_level: DeadlineAlertLevel, +} + +#[ink(event)] +pub struct TaxDeadlineNotification { + #[ink(topic)] + property_id: u64, + #[ink(topic)] + jurisdiction_code: u32, + reporting_period: u64, + due_at: Timestamp, + days_remaining: u16, +} #[ink(event)] pub struct TaxDocumentUploaded { @@ -555,6 +585,28 @@ mod tax_compliance { tax_due, }); + // Emit tax deadline notification if approaching + if let Some(days) = crate::tax_engine::days_until_due(now, record.due_at) { + if days <= 30 { + let alert_level = if days <= 7 { DeadlineAlertLevel::Urgent } else { DeadlineAlertLevel::Approaching }; + self.env().emit_event(TaxDeadlineApproaching { + property_id, + jurisdiction_code: jurisdiction.code, + reporting_period, + due_at: record.due_at, + days_remaining: days, + alert_level, + }); + self.env().emit_event(TaxDeadlineNotification { + property_id, + jurisdiction_code: jurisdiction.code, + reporting_period, + due_at: record.due_at, + days_remaining: days, + }); + } + } + let snapshot = self.build_snapshot( property_id, jurisdiction.code, @@ -758,6 +810,30 @@ mod tax_compliance { let snapshot = self.build_snapshot(property_id, jurisdiction.code, &rule, &assessment, record); + // Emit tax deadline notification if approaching during compliance check + if let Some(record) = record { + if let Some(days) = crate::tax_engine::days_until_due(now, record.due_at) { + if days <= 30 { + let alert_level = if days <= 7 { DeadlineAlertLevel::Urgent } else { DeadlineAlertLevel::Approaching }; + self.env().emit_event(TaxDeadlineApproaching { + property_id, + jurisdiction_code: jurisdiction.code, + reporting_period: record.reporting_period, + due_at: record.due_at, + days_remaining: days, + alert_level, + }); + self.env().emit_event(TaxDeadlineNotification { + property_id, + jurisdiction_code: jurisdiction.code, + reporting_period: record.reporting_period, + due_at: record.due_at, + days_remaining: days, + }); + } + } + } + let mut outstanding_ref = [0u8; 32]; outstanding_ref[16..].copy_from_slice(&snapshot.outstanding_tax.to_be_bytes()); diff --git a/contracts/tax-compliance/src/tax_engine.rs b/contracts/tax-compliance/src/tax_engine.rs index 785b20ba..0fdde76f 100644 --- a/contracts/tax-compliance/src/tax_engine.rs +++ b/contracts/tax-compliance/src/tax_engine.rs @@ -117,3 +117,12 @@ pub(crate) fn resolve_status(record: TaxRecord, now: Timestamp) -> TaxStatus { TaxStatus::Assessed } } + +pub(crate) fn days_until_due(now: Timestamp, due_at: Timestamp) -> Option { + if due_at <= now { + return None; + } + let millis_per_day = 24 * 60 * 60 * 1000u64; + let days = ((due_at - now) / millis_per_day) as u16; + Some(days) +} diff --git a/contracts/traits/src/circuit_breaker.rs b/contracts/traits/src/circuit_breaker.rs new file mode 100644 index 00000000..f37be7aa --- /dev/null +++ b/contracts/traits/src/circuit_breaker.rs @@ -0,0 +1,43 @@ +use ink::prelude::vec::Vec; +use ink::storage::Mapping; +use ink::primitives::Hash; +use ink::traits::{SpreadLayout, PackedLayout}; +use scale::{Encode, Decode}; +#[cfg(feature = "std")] +use scale_info::TypeInfo; +use ink::storage::traits::{StorageLayout}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode, SpreadLayout, PackedLayout, StorageLayout)] +#[cfg_attr(feature = "std", derive(TypeInfo))] +pub enum ExternalDependency { + Oracle, + ComplianceRegistry, + FeeManager, + IdentityRegistry, +} + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, Default, SpreadLayout, PackedLayout, StorageLayout)] +#[cfg_attr(feature = "std", derive(TypeInfo))] +pub struct CircuitBreakerState { + pub failure_count: u8, + pub total_failures: u64, + pub last_failure_at: Option, + pub open_until: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, SpreadLayout, PackedLayout, StorageLayout)] +#[cfg_attr(feature = "std", derive(TypeInfo))] +pub struct CircuitBreakerConfig { + pub failure_threshold: u8, + pub cooldown_period_secs: u64, +} + +impl Default for CircuitBreakerConfig { + fn default() -> Self { + Self { + failure_threshold: 3, + cooldown_period_secs: 300, // 5 minutes + } + } +} + diff --git a/docs/compliance-regulatory-framework.md b/docs/compliance-regulatory-framework.md index 20c3715e..cecf5365 100644 --- a/docs/compliance-regulatory-framework.md +++ b/docs/compliance-regulatory-framework.md @@ -9,17 +9,16 @@ This document describes the **enhanced compliance and regulatory framework** for ## Acceptance Criteria Mapping -| Criterion | Implementation | -|-----------|-----------------| -| Multi-jurisdictional compliance rules engine | `Jurisdiction`, `JurisdictionRules`, `get_jurisdiction_rules`, `update_jurisdiction_rules`, `check_transaction_compliance(account, operation)` | -| KYC/AML integration with external providers | `create_verification_request`, `process_verification_request`, `register_service_provider`, `submit_verification`, `update_aml_status` | -| KYC conversion and verification rates | `get_kyc_metrics()`, `get_jurisdiction_kyc_metrics(jurisdiction)`, `KycMetrics` | -| Compliance reporting and audit trails | `get_audit_logs`, `get_compliance_report(account)`, `AuditLog`, `ComplianceReport` | -| Automated compliance checking for transactions | `check_transaction_compliance(account, operation)`, PropertyRegistry `check_compliance()` (cross-call to registry) | -| Sanction list screening and monitoring | `update_sanctions_status`, `batch_sanctions_check`, `SanctionsList`, `get_sanctions_screening_summary()` | -| Compliance workflow management | `create_verification_request`, `process_verification_request`, `get_verification_workflow_status(request_id)`, `WorkflowStatus` | -| Regulatory reporting automation | `get_regulatory_report(jurisdiction, period_start, period_end)` returning `RegulatoryReport` | -| Compliance documentation and best practices | This doc, `docs/compliance-integration.md`, `contracts/compliance_registry/README.md` | +| Criterion | Implementation | +| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| Multi-jurisdictional compliance rules engine | `Jurisdiction`, `JurisdictionRules`, `get_jurisdiction_rules`, `update_jurisdiction_rules`, `check_transaction_compliance(account, operation)` | +| KYC/AML integration with external providers | `create_verification_request`, `process_verification_request`, `register_service_provider`, `submit_verification`, `update_aml_status` | +| Compliance reporting and audit trails | `get_audit_logs`, `get_compliance_report(account)`, `AuditLog`, `ComplianceReport` | +| Automated compliance checking for transactions | `check_transaction_compliance(account, operation)`, PropertyRegistry `check_compliance()` (cross-call to registry) | +| Sanction list screening and monitoring | `update_sanctions_status`, `batch_sanctions_check`, `SanctionsList`, `get_sanctions_screening_summary()` | +| Compliance workflow management | `create_verification_request`, `process_verification_request`, `get_verification_workflow_status(request_id)`, `WorkflowStatus` | +| Regulatory reporting automation | `get_regulatory_report(jurisdiction, period_start, period_end)` returning `RegulatoryReport` | +| Compliance documentation and best practices | This doc, `docs/compliance-integration.md`, `contracts/compliance_registry/README.md` | ## Multi-Jurisdictional Rules Engine @@ -75,11 +74,11 @@ This document describes the **enhanced compliance and regulatory framework** for ## PropertyRegistry Integration -| Message | Description | -|---------|-------------| -| `set_compliance_registry(Option)` | Admin sets or clears the ComplianceRegistry address. | -| `get_compliance_registry()` | Returns the current registry address. | -| `check_account_compliance(AccountId)` | Returns whether the account is compliant (or true if no registry is set). | +| Message | Description | +| -------------------------------------------- | ------------------------------------------------------------------------- | +| `set_compliance_registry(Option)` | Admin sets or clears the ComplianceRegistry address. | +| `get_compliance_registry()` | Returns the current registry address. | +| `check_account_compliance(AccountId)` | Returns whether the account is compliant (or true if no registry is set). | Internal: `check_compliance(account)` is used in `register_property` and `transfer_property`; it performs a cross-call to the registry’s `is_compliant(account)` when the registry is set. @@ -92,9 +91,27 @@ Internal: `check_compliance(account)` is used in `register_property` and `transf 5. **Audit**: Use `get_audit_logs(account, limit)` and `get_compliance_report(account)` for audits and reporting. 6. **Jurisdiction rules**: Use `get_jurisdiction_rules(jurisdiction)` and `update_jurisdiction_rules` (admin) to align with local regulations. +## Tax Deadline Notifications (New Feature) + +**TaxComplianceModule** (`contracts/tax-compliance/`) now emits events for upcoming tax deadlines: + +- **Events**: + - `TaxDeadlineApproaching { property_id, jurisdiction_code, reporting_period, due_at, days_remaining, alert_level }` β€” Emitted <=30 days before due (Urgent <=7 days). + - `TaxDeadlineNotification { property_id, jurisdiction_code, reporting_period, due_at, days_remaining }` β€” Standard notification event. + +**Emit Triggers**: + +- `calculate_tax()` β€” On new/updated tax record calculation. +- `check_compliance()` β€” During compliance checks. + +**Off-chain Usage**: Indexers listen to these events to send push notifications, emails, or in-app alerts to property owners. + +**Helper**: `tax_engine::days_until_due(now, due_at) -> Option` for custom logic. + ## Files - **Contract**: `contracts/compliance_registry/lib.rs` β€” ComplianceRegistry logic, traits impl, tests. +- **Tax Compliance**: `contracts/tax-compliance/src/lib.rs` β€” Tax deadline events and emits. - **Traits**: `contracts/traits/src/lib.rs` β€” `ComplianceChecker`, `ComplianceOperation`. - **Registry integration**: `contracts/lib/src/lib.rs` β€” `check_compliance`, `check_account_compliance`, `set_compliance_registry`. - **Docs**: `docs/compliance-integration.md`, `docs/compliance-regulatory-framework.md`, `docs/compliance-completion-checklist.md`.