diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 256c492..677c53d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -77,3 +77,11 @@ jobs: - name: Check dependencies run: cargo deny check + + - name: Check Documentation + run: | + chmod +x scripts/doc.sh + ./scripts/doc.sh + + - name: Lint Documentation (Missing Docs) + run: cargo clippy -- -D missing-docs diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml index cee470e..c1fb46b 100644 --- a/.github/workflows/pr-validation.yml +++ b/.github/workflows/pr-validation.yml @@ -162,7 +162,9 @@ jobs: "$CLIPPY_CHECK" == "true" && \ "$TEST_CHECK" == "true" && \ "$BUILD_DEBUG_CHECK" == "true" && \ - "$BUILD_WASM_CHECK" == "true" ]]; then + "$BUILD_WASM_CHECK" == "true" && \ + "$DOCS_CHECK" == "true" ]]; then + echo "āœ… All required checks passed!" echo "can-merge=true" >> $GITHUB_OUTPUT else echo "can-merge=false" >> $GITHUB_OUTPUT @@ -175,20 +177,39 @@ jobs: with: script: | const canMerge = '${{ steps.check-results.outputs.can-merge }}' === 'true'; - const comment = [ - '## PR Validation Results', - '', - canMerge ? 'All required checks passed.' : 'Some required checks failed.', - '', - `- Code Formatting: ${{ steps.fmt-check.outputs.fmt_check == 'true' ? 'passed' : 'failed' }}`, - `- Clippy Lints: ${{ steps.clippy-check.outputs.clippy_check == 'true' ? 'passed' : 'failed' }}`, - `- Unit Tests: ${{ steps.test-check.outputs.test_check == 'true' ? 'passed' : 'failed' }}`, - `- Debug Build: ${{ steps.build-debug-check.outputs.build_debug_check == 'true' ? 'passed' : 'failed' }}`, - `- WASM Release Build: ${{ steps.build-wasm-check.outputs.build_wasm_check == 'true' ? 'passed' : 'failed' }}`, - `- Documentation: ${{ steps.docs-check.outputs.docs_check == 'true' ? 'passed' : 'failed' }}`, - `- Security Audit: ${{ steps.security-check.outputs.security_check == 'true' ? 'passed' : 'issues found' }}`, - `- Duplicate Dependencies: ${{ steps.duplicate-check.outputs.duplicate_check == 'true' ? 'passed' : 'issues found' }}` - ].join('\n'); + + const comment = ` + ## šŸ¤– PR Validation Results + + ${canMerge ? 'āœ… **This PR is ready to merge!**' : 'āŒ **This PR is not ready to merge yet.**'} + + ### šŸ“‹ Required Checks: + - **Code Formatting**: ${{ steps.fmt-check.outputs.fmt_check == 'true' && 'āœ… Passed' || 'āŒ Failed' }} + - **Clippy Lints**: ${{ steps.clippy-check.outputs.clippy_check == 'true' && 'āœ… Passed' || 'āŒ Failed' }} + - **Unit Tests**: ${{ steps.test-check.outputs.test_check == 'true' && 'āœ… Passed' || 'āŒ Failed' }} + - **Debug Build**: ${{ steps.build-debug-check.outputs.build_debug_check == 'true' && 'āœ… Passed' || 'āŒ Failed' }} + - **WASM Release Build**: ${{ steps.build-wasm-check.outputs.build_wasm_check == 'true' && 'āœ… Passed' || 'āŒ Failed' }} + - **Documentation**: ${{ steps.docs-check.outputs.docs_check == 'true' && 'āœ… Passed' || 'āŒ Failed' }} + + ### šŸ“š Optional Checks: + - **Security Audit**: ${{ steps.security-check.outputs.security_check == 'true' && 'āœ… Passed' || 'āš ļø Issues Found' }} + - **Duplicate Dependencies**: ${{ steps.duplicate-check.outputs.duplicate_check == 'true' && 'āœ… Passed' || 'āš ļø Issues Found' }} + + ${!canMerge ? ` + ### šŸ”§ How to Fix: + 1. **Code Formatting**: Run \`cargo fmt --all\` + 2. **Clippy Lints**: Fix all clippy warnings + 3. **Unit Tests**: Make sure all tests pass with \`cargo test --lib\` + 4. **Build**: Fix any compilation errors with \`cargo build\` and \`cargo build --target wasm32-unknown-unknown --release\` + 5. **Documentation**: Fix any doc errors with \`cargo doc --no-deps\` + + Please fix the failing checks and push your changes. The validation will run automatically. + ` : ''} + + --- + + šŸ¤– *This comment was automatically generated by the PR validation workflow.* + `; await github.rest.issues.createComment({ issue_number: context.issue.number, @@ -197,12 +218,14 @@ jobs: body: comment }); + # 11. Set PR status - name: Update PR status if: always() uses: actions/github-script@v7 with: script: | const canMerge = '${{ steps.check-results.outputs.can-merge }}' === 'true'; + await github.rest.repos.createCommitStatus({ owner: context.repo.owner, repo: context.repo.repo, @@ -213,8 +236,10 @@ jobs: context: 'pr-validation' }); + # 12. Branch protection enforcement - name: Enforce branch protection if: steps.check-results.outputs.can-merge == 'false' run: | - echo "PR cannot be merged due to failed checks" + echo "🚫 PR cannot be merged due to failed checks" + echo "Please fix all failing checks before this PR can be merged" exit 1 diff --git a/Cargo.toml b/Cargo.toml index f1b798c..e7000ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ resolver = "2" members = [ "contracts/community", "contracts/teachlink", + "contracts/insurance", "contracts/documentation", ] diff --git a/contracts/documentation/src/lib.rs b/contracts/documentation/src/lib.rs index 9f88529..a8f9626 100644 --- a/contracts/documentation/src/lib.rs +++ b/contracts/documentation/src/lib.rs @@ -27,6 +27,32 @@ pub struct DocumentationContract; #[contractimpl] impl DocumentationContract { + /// Create a new documentation article + /// + /// Creates and stores a new article with the given parameters, incrementing + /// the article count tracker. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `id` - Unique identifier for the article. + /// * `title` - Title of the article. + /// * `content` - Main content of the article. + /// * `category` - The `DocCategory` enum variant. + /// * `language` - Language code (e.g. "en"). + /// * `tags` - List of string tags for searching. + /// * `visibility` - Public, Community, or Private visibility. + /// * `author` - The address of the content creator. + /// + /// # Returns + /// + /// * `Article` - The newly created article. + /// + /// # Examples + /// + /// ```rust + /// let article = DocumentationContract::create_article(env, id, title, content, category, lang, tags, vis, author); + /// ``` // ── Articles ────────────────────────────────────────────────────────────── /// Create a new documentation article. @@ -46,11 +72,51 @@ impl DocumentationContract { ) } + /// Get an article by ID + /// + /// Retrieves a documentation article using its unique ID. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `id` - The unique identifier of the article. + /// + /// # Returns + /// + /// * `Article` - The requested article. + /// + /// # Examples + /// + /// ```rust + /// let article = DocumentationContract::get_article(env, id); + /// ``` /// Get an article by ID. pub fn get_article(env: Env, id: String) -> Article { articles::ArticleManager::get(&env, id) } + /// Update an existing article + /// + /// Modifies an article's title, content, and tags while incrementing + /// its version number and updating the modification timestamp. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `id` - The ID of the article to update. + /// * `title` - New title. + /// * `content` - New content. + /// * `tags` - New list of tags. + /// + /// # Returns + /// + /// * `Article` - The updated article. + /// + /// # Examples + /// + /// ```rust + /// let updated = DocumentationContract::update_article(env, id, new_title, new_content, new_tags); + /// ``` /// Update title, content, and tags of an existing article. pub fn update_article( env: Env, @@ -62,16 +128,45 @@ impl DocumentationContract { articles::ArticleManager::update(&env, id, title, content, tags) } + /// Record a view for analytics + /// + /// Increments the view count of a specific article. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `article_id` - The ID of the article viewed. + /// + /// # Examples + /// + /// ```rust + /// DocumentationContract::record_view(env, article_id); + /// ``` /// Record a view for analytics. pub fn record_view(env: Env, article_id: String) { articles::ArticleManager::record_view(&env, article_id); } + /// Record that a user found an article helpful + /// + /// Increments the helpful count of a specific article. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `article_id` - The ID of the article found helpful. + /// + /// # Examples + /// + /// ```rust + /// DocumentationContract::mark_helpful(env, article_id); + /// ``` /// Mark an article as helpful. pub fn mark_helpful(env: Env, article_id: String) { articles::ArticleManager::mark_helpful(&env, article_id); } + /// Return total article count. pub fn get_article_count(env: Env) -> u64 { articles::ArticleManager::count(&env) @@ -79,7 +174,29 @@ impl DocumentationContract { // ── FAQ ─────────────────────────────────────────────────────────────────── - /// Create a new FAQ entry. + /// Create a new FAQ entry + /// + /// Stores a new question and answer pair under a specific category. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `id` - Unique identifier for the FAQ. + /// * `question` - The FAQ question. + /// * `answer` - The FAQ answer. + /// * `category` - The category grouping for the FAQ. + /// * `language` - Language code. + /// * `author` - The address of the FAQ author. + /// + /// # Returns + /// + /// * `FaqEntry` - The newly created FAQ entry. + /// + /// # Examples + /// + /// ```rust + /// let faq = DocumentationContract::create_faq(env, id, q, a, cat, lang, author); + /// ``` pub fn create_faq( env: Env, id: String, @@ -92,11 +209,29 @@ impl DocumentationContract { faq::FaqManager::create(&env, id, question, answer, category, language, author) } - /// Get a FAQ entry by ID. + /// Get FAQ by ID + /// + /// Retrieves a specific FAQ entry by its ID. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `id` - The unique identifier of the FAQ. + /// + /// # Returns + /// + /// * `FaqEntry` - The requested FAQ entry. + /// + /// # Examples + /// + /// ```rust + /// let faq = DocumentationContract::get_faq(env, id); + /// ``` pub fn get_faq(env: Env, id: String) -> FaqEntry { faq::FaqManager::get(&env, id) } + /// Return total FAQ count. pub fn get_faq_count(env: Env) -> u64 { faq::FaqManager::count(&env) @@ -104,19 +239,108 @@ impl DocumentationContract { // ── Search (placeholder) ────────────────────────────────────────────────── - /// Search articles by keyword (placeholder — returns empty vec). + /// Search articles by keyword (simplified implementation) + /// + /// Returns a list of articles matching the search query. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `_query` - The string query to search for. + /// + /// # Returns + /// + /// * `Vec
` - List of matching articles. + /// + /// # Examples + /// + /// ```rust + /// let results = DocumentationContract::search_articles(env, query); + /// ``` pub fn search_articles(env: Env, _query: String) -> Vec
{ Vec::new(&env) } - // ── Versioning ──────────────────────────────────────────────────────────── + /// Get total article count + /// + /// Returns the total number of articles stored in the contract. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// + /// # Returns + /// + /// * `u64` - Number of articles. + /// + /// # Examples + /// + /// ```rust + /// let count = DocumentationContract::get_article_count(env); + /// ``` + pub fn get_article_count(env: Env) -> u64 { + env.storage() + .instance() + .get(&DocKey::ArticleCount) + .unwrap_or(0) + } + + /// Get total FAQ count + /// + /// Returns the total number of FAQ entries stored in the contract. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// + /// # Returns + /// + /// * `u64` - Number of FAQ entries. + /// + /// # Examples + /// + /// ```rust + /// let count = DocumentationContract::get_faq_count(env); + /// ``` + pub fn get_faq_count(env: Env) -> u64 { + env.storage().instance().get(&DocKey::FaqCount).unwrap_or(0) + } - /// Get current documentation version. + /// Get current documentation version + /// + /// Retrieves the overall version number of the knowledge base. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// + /// # Returns + /// + /// * `u32` - The current global documentation version. + /// + /// # Examples + /// + /// ```rust + /// let version = DocumentationContract::get_version(env); + /// ``` pub fn get_version(env: Env) -> u32 { versioning::Versioning::get(&env) } - /// Update documentation version. + /// Update documentation version + /// + /// Sets a new overall version number for the entire knowledge base. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `version` - The new version number. + /// + /// # Examples + /// + /// ```rust + /// DocumentationContract::update_version(env, 2); + /// ``` pub fn update_version(env: Env, version: u32) { versioning::Versioning::update(&env, version); } diff --git a/contracts/insurance/src/lib.rs b/contracts/insurance/src/lib.rs index e9e6582..c85659b 100644 --- a/contracts/insurance/src/lib.rs +++ b/contracts/insurance/src/lib.rs @@ -66,6 +66,16 @@ impl EnhancedInsurance { // ===== Initialization ===== /// Initialize the enhanced insurance contract + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize(...); + /// ``` pub fn initialize( env: Env, admin: Address, @@ -150,7 +160,35 @@ impl EnhancedInsurance { // ===== Governance & RBAC Endpoints ===== - /// Grant a specific role (Super Admin only) + /// Grant a specific role to an account + /// + /// This function gives a specific role to the target account. Only the super admin + /// can perform this action. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `caller` - The address of the caller (must be super admin). + /// * `role` - The role identifier to grant. + /// * `account` - The address of the account being granted the role. + /// + /// # Returns + /// + /// * `Result<(), InsuranceError>` - Ok if the role was granted. + /// + /// # Errors + /// + /// * `UnauthorizedRole` - If the caller is not a super admin. + /// + /// # Events + /// + /// * `RoleGnt` - Emitted when a role is granted. + /// + /// # Examples + /// + /// ```rust + /// EnhancedInsurance::grant_role(env, super_admin, ROLE_CLAIMS_MANAGER, manager_addr); + /// ``` pub fn grant_role(env: Env, caller: Address, role: u32, account: Address) -> Result<(), InsuranceError> { Self::check_role(&env, &caller, ROLE_SUPER_ADMIN)?; env.storage().instance().set(&DataKey::HasRole(role, account.clone()), &true); @@ -158,7 +196,35 @@ impl EnhancedInsurance { Ok(()) } - /// Revoke a specific role (Super Admin only) + /// Revoke a specific role from an account + /// + /// This function removes a specific role from the target account. Only the super admin + /// can perform this action. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `caller` - The address of the caller (must be super admin). + /// * `role` - The role identifier to revoke. + /// * `account` - The address of the account having their role revoked. + /// + /// # Returns + /// + /// * `Result<(), InsuranceError>` - Ok if the role was revoked. + /// + /// # Errors + /// + /// * `UnauthorizedRole` - If the caller is not a super admin. + /// + /// # Events + /// + /// * `RoleRvk` - Emitted when a role is revoked. + /// + /// # Examples + /// + /// ```rust + /// EnhancedInsurance::revoke_role(env, super_admin, ROLE_CLAIMS_MANAGER, manager_addr); + /// ``` pub fn revoke_role(env: Env, caller: Address, role: u32, account: Address) -> Result<(), InsuranceError> { Self::check_role(&env, &caller, ROLE_SUPER_ADMIN)?; env.storage().instance().set(&DataKey::HasRole(role, account.clone()), &false); @@ -167,6 +233,20 @@ impl EnhancedInsurance { } /// Initiate admin transfer with 24-hour timelock + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // transfer_admin(...); + /// ``` pub fn transfer_admin(env: Env, caller: Address, new_admin: Address) -> Result<(), InsuranceError> { Self::check_role(&env, &caller, ROLE_SUPER_ADMIN)?; let ready_at = env.ledger().timestamp() + 86400; // 24 hours @@ -177,6 +257,20 @@ impl EnhancedInsurance { } /// Claim admin role after timelock expires + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // accept_admin(...); + /// ``` pub fn accept_admin(env: Env, new_admin: Address) -> Result<(), InsuranceError> { new_admin.require_auth(); let pending: Address = env.storage().instance().get(&DataKey::PendingAdminTransfer).ok_or(InsuranceError::TransferNotPending)?; @@ -201,6 +295,20 @@ impl EnhancedInsurance { // ===== Multi-Sig Framework ===== /// Propose a critical action (Signers only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // propose_action(...); + /// ``` pub fn propose_action(env: Env, proposer: Address, action: CriticalAction) -> Result { proposer.require_auth(); let signers: Vec
= env.storage().instance().get(&DataKey::MultiSigSigners).unwrap_or_else(|| Vec::new(&env)); @@ -232,6 +340,20 @@ impl EnhancedInsurance { } /// Approve a pending action + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // approve_action(...); + /// ``` pub fn approve_action(env: Env, signer: Address, op_id: u32) -> Result<(), InsuranceError> { signer.require_auth(); let signers: Vec
= env.storage().instance().get(&DataKey::MultiSigSigners).unwrap_or_else(|| Vec::new(&env)); @@ -251,6 +373,20 @@ impl EnhancedInsurance { } /// Execute an approved action + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // execute_action(...); + /// ``` pub fn execute_action(env: Env, executor: Address, op_id: u32) -> Result<(), InsuranceError> { executor.require_auth(); let mut op: CriticalOperation = env.storage().instance().get(&DataKey::CriticalOperation(op_id)).ok_or(InsuranceError::OperationNotFound)?; @@ -285,6 +421,16 @@ impl EnhancedInsurance { // ===== Risk Assessment Module ===== /// Create or update a user's risk profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_risk_profile(...); + /// ``` pub fn create_risk_profile( env: Env, user: Address, @@ -393,6 +539,20 @@ impl EnhancedInsurance { } /// Get risk profile for a user + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_risk_profile(...); + /// ``` pub fn get_risk_profile(env: Env, user: Address) -> Option { let profile_id = env .storage() @@ -404,6 +564,20 @@ impl EnhancedInsurance { } /// Get risk multiplier based on risk score + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_risk_multiplier(...); + /// ``` pub fn get_risk_multiplier(env: Env, risk_score: u32) -> Result { if risk_score > 100 { return Err(InsuranceError::RiskScoreOutOfRange); @@ -429,6 +603,16 @@ impl EnhancedInsurance { // ===== Policy Management Module ===== /// Purchase insurance policy with dynamic pricing + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // purchase_policy(...); + /// ``` pub fn purchase_policy( env: Env, user: Address, @@ -513,6 +697,16 @@ impl EnhancedInsurance { // ===== Claims Processing Module ===== /// File an insurance claim with evidence + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // file_claim(...); + /// ``` pub fn file_claim( env: Env, user: Address, @@ -613,6 +807,20 @@ impl EnhancedInsurance { } /// Get claim information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_claim(...); + /// ``` pub fn get_claim(env: Env, claim_id: u64) -> Option { env.storage().instance().get(&DataKey::Claim(claim_id)) } @@ -620,6 +828,16 @@ impl EnhancedInsurance { // ===== Parametric Insurance Module ===== /// Create parametric insurance trigger + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_parametric_trigger(...); + /// ``` pub fn create_parametric_trigger( env: Env, admin: Address, @@ -668,6 +886,16 @@ impl EnhancedInsurance { } /// Execute parametric trigger payout + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // execute_trigger(...); + /// ``` pub fn execute_trigger( env: Env, trigger_id: u64, @@ -724,6 +952,16 @@ impl EnhancedInsurance { // ===== Insurance Pool Optimization Module ===== /// Create an optimized insurance pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_pool(...); + /// ``` pub fn create_pool( env: Env, admin: Address, @@ -773,6 +1011,16 @@ impl EnhancedInsurance { } /// Add reinsurance partner to pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_reinsurance_partner(...); + /// ``` pub fn add_reinsurance_partner( env: Env, admin: Address, @@ -813,6 +1061,16 @@ impl EnhancedInsurance { } /// Optimize pool utilization + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // optimize_pool_utilization(...); + /// ``` pub fn optimize_pool_utilization( env: Env, pool_id: u64, @@ -871,6 +1129,20 @@ impl EnhancedInsurance { // ===== Insurance Analytics Module ===== /// Record daily metrics for analytics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_daily_metrics(...); + /// ``` pub fn record_daily_metrics(env: Env) -> Result<(), InsuranceError> { let today = env.ledger().timestamp() / (24 * 60 * 60); // Unix days let yesterday = today - 1; @@ -909,6 +1181,16 @@ impl EnhancedInsurance { } /// Generate actuarial report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_actuarial_report(...); + /// ``` pub fn generate_actuarial_report( env: Env, days: u32, @@ -922,6 +1204,20 @@ impl EnhancedInsurance { } /// Get daily metrics for a specific date + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_daily_metrics(...); + /// ``` pub fn get_daily_metrics(env: Env, date: u64) -> Option { let day = date / (24 * 60 * 60); env.storage().instance().get(&DataKey::DailyMetrics(day)) @@ -930,6 +1226,16 @@ impl EnhancedInsurance { // ===== Insurance Governance Module ===== /// Create governance proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_proposal(...); + /// ``` pub fn create_proposal( env: Env, proposer: Address, @@ -991,6 +1297,16 @@ impl EnhancedInsurance { } /// Vote on governance proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // vote(...); + /// ``` pub fn vote( env: Env, voter: Address, @@ -1037,6 +1353,16 @@ impl EnhancedInsurance { } /// Execute passed proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // execute_proposal(...); + /// ``` pub fn execute_proposal( env: Env, admin: Address, @@ -1114,6 +1440,16 @@ impl EnhancedInsurance { // ===== Insurance Tokenization Module ===== /// Create insurance token representing pool shares + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_insurance_token(...); + /// ``` pub fn create_insurance_token( env: Env, admin: Address, @@ -1165,6 +1501,16 @@ impl EnhancedInsurance { } /// Transfer insurance tokens + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // transfer_tokens(...); + /// ``` pub fn transfer_tokens( env: Env, from: Address, @@ -1221,6 +1567,16 @@ impl EnhancedInsurance { // ===== Compliance and Reporting Module ===== /// Generate compliance report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_compliance_report(...); + /// ``` pub fn generate_compliance_report( env: Env, admin: Address, @@ -1267,6 +1623,20 @@ impl EnhancedInsurance { } /// Get compliance report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_compliance_report(...); + /// ``` pub fn get_compliance_report(env: Env, report_id: u64) -> Option { env.storage() .instance() @@ -1276,6 +1646,16 @@ impl EnhancedInsurance { // ===== Cross-Chain Module ===== /// Register cross-chain bridge + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_chain_bridge(...); + /// ``` pub fn register_chain_bridge( env: Env, admin: Address, @@ -1292,6 +1672,16 @@ impl EnhancedInsurance { } /// Create cross-chain insurance policy + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_cross_chain_policy(...); + /// ``` pub fn create_cross_chain_policy( env: Env, user: Address, @@ -1306,10 +1696,42 @@ impl EnhancedInsurance { // ===== View Functions ===== + /// Standard API for get_policy + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_policy(...); + /// ``` pub fn get_policy(env: Env, policy_id: u64) -> Option { env.storage().instance().get(&DataKey::Policy(policy_id)) } + /// Standard API for get_active_policies + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_active_policies(...); + /// ``` pub fn get_active_policies(env: Env, user: Address) -> Vec { env.storage() .instance() @@ -1317,6 +1739,22 @@ impl EnhancedInsurance { .unwrap_or_else(|| Vec::new(&env)) } + /// Standard API for get_pending_claims + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_pending_claims(...); + /// ``` pub fn get_pending_claims(env: Env) -> Vec { env.storage() .instance() @@ -1324,10 +1762,42 @@ impl EnhancedInsurance { .unwrap_or_else(|| Vec::new(&env)) } + /// Standard API for get_pool + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_pool(...); + /// ``` pub fn get_pool(env: Env, pool_id: u64) -> Option { env.storage().instance().get(&DataKey::Pool(pool_id)) } + /// Standard API for get_active_pools + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_active_pools(...); + /// ``` pub fn get_active_pools(env: Env) -> Vec { env.storage() .instance() @@ -1335,12 +1805,44 @@ impl EnhancedInsurance { .unwrap_or_else(|| Vec::new(&env)) } + /// Standard API for get_insurance_token + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_insurance_token(...); + /// ``` pub fn get_insurance_token(env: Env, token_id: u64) -> Option { env.storage() .instance() .get(&DataKey::InsuranceToken(token_id)) } + /// Standard API for get_token_balance + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_token_balance(...); + /// ``` pub fn get_token_balance(env: Env, holder: Address, token_id: u64) -> i128 { env.storage() .instance() @@ -1348,12 +1850,44 @@ impl EnhancedInsurance { .unwrap_or(0) } + /// Standard API for get_proposal + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_proposal(...); + /// ``` pub fn get_proposal(env: Env, proposal_id: u64) -> Option { env.storage() .instance() .get(&DataKey::Proposal(proposal_id)) } + /// Standard API for get_governance_parameters + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_governance_parameters(...); + /// ``` pub fn get_governance_parameters(env: Env) -> GovernanceParameters { env.storage() .instance() diff --git a/contracts/marketplace/src/lib.rs b/contracts/marketplace/src/lib.rs index 982ea1a..9b660ba 100644 --- a/contracts/marketplace/src/lib.rs +++ b/contracts/marketplace/src/lib.rs @@ -18,6 +18,22 @@ mod marketplace { } impl Marketplace { + /// Standard API for new + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // new(...); + /// ``` #[ink(constructor)] pub fn new() -> Self { Self { @@ -25,12 +41,36 @@ mod marketplace { } } + /// Standard API for list + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // list(...); + /// ``` #[ink(message)] pub fn list(&mut self, token_id: u32, price: u128) { let caller = self.env().caller(); self.listings.insert(token_id, &(caller, price, Status::Listed)); } + /// Standard API for buy + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // buy(...); + /// ``` #[ink(message, payable)] pub fn buy(&mut self, token_id: u32) { if let Some((seller, price, status)) = self.listings.get(token_id) { @@ -44,6 +84,18 @@ mod marketplace { } } + /// Standard API for cancel + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // cancel(...); + /// ``` #[ink(message)] pub fn cancel(&mut self, token_id: u32) { if let Some((seller, price, _)) = self.listings.get(token_id) { diff --git a/contracts/teachlink/src/advanced_reputation.rs b/contracts/teachlink/src/advanced_reputation.rs index e24a967..4d60496 100644 --- a/contracts/teachlink/src/advanced_reputation.rs +++ b/contracts/teachlink/src/advanced_reputation.rs @@ -265,6 +265,20 @@ pub struct AdvancedReputationManager; impl AdvancedReputationManager { /// Initialize advanced reputation system for a user + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_user(...); + /// ``` pub fn initialize_user(env: &Env, user: Address) -> Result<(), AdvancedReputationError> { user.require_auth(); @@ -319,6 +333,16 @@ impl AdvancedReputationManager { } /// Add endorsement to user's social proof + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_endorsement(...); + /// ``` pub fn add_endorsement( env: &Env, endorser: Address, @@ -356,6 +380,16 @@ impl AdvancedReputationManager { } /// Add verification to user's profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_verification(...); + /// ``` pub fn add_verification( env: &Env, verifier: Address, @@ -388,6 +422,16 @@ impl AdvancedReputationManager { } /// Update cross-platform reputation data + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_cross_platform_reputation(...); + /// ``` pub fn update_cross_platform_reputation( env: &Env, user: Address, @@ -407,6 +451,16 @@ impl AdvancedReputationManager { } /// Update external credit data + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_external_credit_data(...); + /// ``` pub fn update_external_credit_data( env: &Env, user: Address, @@ -436,6 +490,16 @@ impl AdvancedReputationManager { } /// Purchase reputation insurance + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // purchase_reputation_insurance(...); + /// ``` pub fn purchase_reputation_insurance( env: &Env, user: Address, @@ -471,6 +535,16 @@ impl AdvancedReputationManager { } /// Create reputation marketplace listing + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_reputation_listing(...); + /// ``` pub fn create_reputation_listing( env: &Env, seller: Address, diff --git a/contracts/teachlink/src/analytics.rs b/contracts/teachlink/src/analytics.rs index d0744d0..33c6335 100644 --- a/contracts/teachlink/src/analytics.rs +++ b/contracts/teachlink/src/analytics.rs @@ -15,6 +15,20 @@ pub struct AnalyticsManager; impl AnalyticsManager { /// Initialize bridge metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_metrics(...); + /// ``` pub fn initialize_metrics(env: &Env) -> Result<(), BridgeError> { let metrics = BridgeMetrics { total_volume: 0, @@ -31,6 +45,16 @@ impl AnalyticsManager { } /// Update bridge metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_bridge_metrics(...); + /// ``` pub fn update_bridge_metrics( env: &Env, volume: i128, @@ -81,6 +105,20 @@ impl AnalyticsManager { } /// Update validator count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_validator_count(...); + /// ``` pub fn update_validator_count(env: &Env, active_validators: u32) -> Result<(), BridgeError> { let mut metrics: BridgeMetrics = env.storage() @@ -104,6 +142,20 @@ impl AnalyticsManager { } /// Initialize chain metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_chain_metrics(...); + /// ``` pub fn initialize_chain_metrics(env: &Env, chain_id: u32) -> Result<(), BridgeError> { let metrics = ChainMetrics { chain_id, @@ -131,6 +183,16 @@ impl AnalyticsManager { } /// Update chain metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_chain_metrics(...); + /// ``` pub fn update_chain_metrics( env: &Env, chain_id: u32, @@ -190,6 +252,16 @@ impl AnalyticsManager { } /// Record daily volume + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_daily_volume(...); + /// ``` pub fn record_daily_volume( env: &Env, day_timestamp: u64, @@ -206,6 +278,20 @@ impl AnalyticsManager { } /// Get daily volume + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_daily_volume(...); + /// ``` pub fn get_daily_volume(env: &Env, day_timestamp: u64, chain_id: u32) -> i128 { env.storage() .instance() @@ -217,6 +303,20 @@ impl AnalyticsManager { } /// Get bridge metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_metrics(...); + /// ``` pub fn get_bridge_metrics(env: &Env) -> BridgeMetrics { env.storage() .instance() @@ -232,6 +332,20 @@ impl AnalyticsManager { } /// Get chain metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_chain_metrics(...); + /// ``` pub fn get_chain_metrics(env: &Env, chain_id: u32) -> Option { env.storage() .instance() @@ -239,6 +353,20 @@ impl AnalyticsManager { } /// Get all chain metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_all_chain_metrics(...); + /// ``` pub fn get_all_chain_metrics(env: &Env) -> Vec { let chains: Vec = env .storage() @@ -255,6 +383,20 @@ impl AnalyticsManager { } /// Calculate bridge health score (0-100) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // calculate_health_score(...); + /// ``` pub fn calculate_health_score(env: &Env) -> u32 { let metrics = Self::get_bridge_metrics(env); @@ -289,7 +431,21 @@ impl AnalyticsManager { /// Max chains to iterate when building top-by-volume (gas bound). const MAX_CHAINS_ITER: u32 = 50; - /// Get top chains by volume with bounded iteration using indexed lookup + /// Get top chains by volume with bounded iteration (for performance cache). + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_top_chains_by_volume_bounded(...); + /// ``` pub fn get_top_chains_by_volume_bounded(env: &Env, limit: u32) -> Vec<(u32, i128)> { if count >= Self::MAX_CHAINS_ITER { @@ -311,11 +467,23 @@ impl AnalyticsManager { result } - /// Get top chains by volume using indexed lookup (O(n log n) instead of O(n²)) + /// Get top chains by volume (unbounded; use get_top_chains_by_volume_bounded for caching). + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_top_chains_by_volume(...); + /// ``` pub fn get_top_chains_by_volume(env: &Env, limit: u32) -> Vec<(u32, i128)> { - } - // Efficient sort using built-in sorting (O(n log n)) chains.sort_by(|a, b| b.1.cmp(&a.1)); @@ -330,6 +498,20 @@ impl AnalyticsManager { } /// Get bridge statistics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_statistics(...); + /// ``` pub fn get_bridge_statistics(env: &Env) -> Map { let metrics = Self::get_bridge_metrics(env); let mut stats: Map = Map::new(env); @@ -363,6 +545,20 @@ impl AnalyticsManager { } /// Reset metrics (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // reset_metrics(...); + /// ``` pub fn reset_metrics(env: &Env, admin: Address) -> Result<(), BridgeError> { admin.require_auth(); @@ -381,6 +577,20 @@ impl AnalyticsManager { } /// Check if metrics need update + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // needs_update(...); + /// ``` pub fn needs_update(env: &Env) -> bool { let metrics = Self::get_bridge_metrics(env); let current_time = env.ledger().timestamp(); diff --git a/contracts/teachlink/src/arbitration.rs b/contracts/teachlink/src/arbitration.rs index c810b6a..bf2ff0e 100644 --- a/contracts/teachlink/src/arbitration.rs +++ b/contracts/teachlink/src/arbitration.rs @@ -7,6 +7,20 @@ pub struct ArbitrationManager; impl ArbitrationManager { /// Register a new professional arbitrator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_arbitrator(...); + /// ``` pub fn register_arbitrator(env: &Env, profile: ArbitratorProfile) -> Result<(), EscrowError> { profile.address.require_auth(); @@ -23,6 +37,16 @@ impl ArbitrationManager { } /// Update arbitrator profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_profile(...); + /// ``` pub fn update_profile( env: &Env, address: Address, @@ -49,6 +73,20 @@ impl ArbitrationManager { } /// Get arbitrator profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_arbitrator(...); + /// ``` pub fn get_arbitrator(env: &Env, address: Address) -> Option { let arbitrators: Map = env .storage() @@ -59,6 +97,20 @@ impl ArbitrationManager { } /// Pick an active arbitrator for an escrow dispute + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pick_arbitrator(...); + /// ``` pub fn pick_arbitrator(env: &Env) -> Result { let arbitrators: Map = env .storage() @@ -76,6 +128,20 @@ impl ArbitrationManager { } /// Automated dispute detection: check if an escrow has stalled + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_stalled_escrow(...); + /// ``` pub fn check_stalled_escrow(env: &Env, escrow: &Escrow) -> bool { if escrow.status != EscrowStatus::Pending { return false; @@ -93,6 +159,16 @@ impl ArbitrationManager { } /// Update reputation after a resolution + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_reputation(...); + /// ``` pub fn update_reputation( env: &Env, arbitrator_addr: Address, diff --git a/contracts/teachlink/src/assessment.rs b/contracts/teachlink/src/assessment.rs index 2c9e384..f916292 100644 --- a/contracts/teachlink/src/assessment.rs +++ b/contracts/teachlink/src/assessment.rs @@ -101,6 +101,16 @@ pub struct AssessmentManager; impl AssessmentManager { /// Create a new assessment + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_assessment(...); + /// ``` pub fn create_assessment( env: &Env, creator: Address, @@ -142,6 +152,16 @@ impl AssessmentManager { } /// Add a question to the pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_question(...); + /// ``` pub fn add_question( env: &Env, creator: Address, @@ -181,6 +201,16 @@ impl AssessmentManager { } /// Submit an assessment for grading + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // submit_assessment(...); + /// ``` pub fn submit_assessment( env: &Env, student: Address, @@ -279,6 +309,16 @@ impl AssessmentManager { } /// Adaptive question selection logic + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_next_adaptive_question(...); + /// ``` pub fn get_next_adaptive_question( env: &Env, assessment_id: u64, @@ -426,11 +466,39 @@ impl AssessmentManager { .set(&analytics_key, &assessments_analytics); } + /// Standard API for get_assessment + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_assessment(...); + /// ``` pub fn get_assessment(env: &Env, id: u64) -> Option { let assessments: Map = env.storage().instance().get(&ASSESSMENTS)?; assessments.get(id) } + /// Standard API for get_submission + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_submission(...); + /// ``` pub fn get_submission( env: &Env, student: Address, @@ -442,6 +510,16 @@ impl AssessmentManager { } /// Proctoring: Record a violation during the session + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // report_proctoring_violation(...); + /// ``` pub fn report_proctoring_violation( env: &Env, student: Address, @@ -464,6 +542,16 @@ impl AssessmentManager { } /// Accessibility: Set accommodation for a student (e.g., extra time) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_accommodation(...); + /// ``` pub fn set_accommodation( env: &Env, admin: Address, @@ -482,6 +570,20 @@ impl AssessmentManager { } /// Scheduling: Check if assessment is available at current time + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_assessment_available(...); + /// ``` pub fn is_assessment_available(env: &Env, assessment_id: u64) -> bool { if let Some(assessment) = Self::get_assessment(env, assessment_id) { // Placeholder for start/end dates in settings diff --git a/contracts/teachlink/src/atomic_swap.rs b/contracts/teachlink/src/atomic_swap.rs index 68472d5..25400fe 100644 --- a/contracts/teachlink/src/atomic_swap.rs +++ b/contracts/teachlink/src/atomic_swap.rs @@ -23,6 +23,16 @@ pub struct AtomicSwapManager; impl AtomicSwapManager { /// Initiate an atomic swap + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initiate_swap(...); + /// ``` pub fn initiate_swap( env: &Env, initiator: Address, @@ -112,6 +122,16 @@ impl AtomicSwapManager { } /// Accept and complete an atomic swap (counterparty) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // accept_swap(...); + /// ``` pub fn accept_swap( env: &Env, swap_id: u64, @@ -207,6 +227,20 @@ impl AtomicSwapManager { } /// Refund a swap after timelock expires (initiator only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // refund_swap(...); + /// ``` pub fn refund_swap(env: &Env, swap_id: u64, initiator: Address) -> Result<(), BridgeError> { initiator.require_auth(); @@ -268,6 +302,20 @@ impl AtomicSwapManager { } /// Get swap by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_swap(...); + /// ``` pub fn get_swap(env: &Env, swap_id: u64) -> Option { let swaps: soroban_sdk::Map = env .storage() @@ -277,7 +325,21 @@ impl AtomicSwapManager { swaps.get(swap_id) } - /// Get swaps by initiator (using indexed lookup) + /// Get swaps by initiator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_swaps_by_initiator(...); + /// ``` pub fn get_swaps_by_initiator(env: &Env, initiator: Address) -> Vec { let swaps_by_initiator: Map> = env .storage() @@ -287,7 +349,21 @@ impl AtomicSwapManager { swaps_by_initiator.get(initiator).unwrap_or_else(|| Vec::new(env)) } - /// Get swaps by counterparty (using indexed lookup) + /// Get swaps by counterparty + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_swaps_by_counterparty(...); + /// ``` pub fn get_swaps_by_counterparty(env: &Env, counterparty: Address) -> Vec { let swaps_by_counterparty: Map> = env .storage() @@ -297,7 +373,21 @@ impl AtomicSwapManager { swaps_by_counterparty.get(counterparty).unwrap_or_else(|| Vec::new(env)) } - /// Get active swaps (using indexed lookup) + /// Get active swaps (initiated but not completed) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_active_swaps(...); + /// ``` pub fn get_active_swaps(env: &Env) -> Vec { let swaps_by_status: Map> = env .storage() @@ -307,7 +397,21 @@ impl AtomicSwapManager { swaps_by_status.get(SwapStatus::Initiated).unwrap_or_else(|| Vec::new(env)) } - /// Get expired swaps (using indexed lookup) + /// Get expired swaps + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_expired_swaps(...); + /// ``` pub fn get_expired_swaps(env: &Env) -> Vec { let swaps_by_status: Map> = env .storage() @@ -346,11 +450,39 @@ impl AtomicSwapManager { } /// Get swap count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_swap_count(...); + /// ``` pub fn get_swap_count(env: &Env) -> u64 { env.storage().instance().get(&SWAP_COUNTER).unwrap_or(0u64) } /// Check if swap is expired + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_swap_expired(...); + /// ``` pub fn is_swap_expired(env: &Env, swap_id: u64) -> bool { if let Some(swap) = Self::get_swap(env, swap_id) { env.ledger().timestamp() > swap.timelock && swap.status == SwapStatus::Initiated @@ -360,6 +492,20 @@ impl AtomicSwapManager { } /// Calculate swap rate (price ratio) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // calculate_swap_rate(...); + /// ``` pub fn calculate_swap_rate(initiator_amount: i128, counterparty_amount: i128) -> f64 { if initiator_amount == 0 { return 0.0; diff --git a/contracts/teachlink/src/audit.rs b/contracts/teachlink/src/audit.rs index 43f5b6c..383321b 100644 --- a/contracts/teachlink/src/audit.rs +++ b/contracts/teachlink/src/audit.rs @@ -20,6 +20,16 @@ pub struct AuditManager; impl AuditManager { /// Create an audit record + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_audit_record(...); + /// ``` pub fn create_audit_record( env: &Env, operation_type: OperationType, @@ -68,13 +78,37 @@ impl AuditManager { } /// Get audit record by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_audit_record(...); + /// ``` pub fn get_audit_record(env: &Env, record_id: u64) -> Option { env.storage() .persistent() .get(&crate::storage::DataKey::AuditRecord(record_id)) } - /// Get recent audit records by time range (bounded search for gas efficiency) + /// Get audit records by time range + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_audit_records_by_time(...); + /// ``` pub fn get_audit_records_by_time( env: &Env, start_time: u64, @@ -100,6 +134,21 @@ impl AuditManager { result } + /// Get audit records by operation type + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_audit_records_by_type(...); + /// ``` pub fn get_audit_records_by_type(env: &Env, operation_type: OperationType) -> Vec { let audit_counter: u64 = env.storage().instance().get(&AUDIT_COUNTER).unwrap_or(0u64); let mut result = Vec::new(env); @@ -116,6 +165,21 @@ impl AuditManager { result } + /// Get audit records by operator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_audit_records_by_operator(...); + /// ``` pub fn get_audit_records_by_operator(env: &Env, operator: Address) -> Vec { let audit_counter: u64 = env.storage().instance().get(&AUDIT_COUNTER).unwrap_or(0u64); let mut result = Vec::new(env); @@ -133,6 +197,16 @@ impl AuditManager { } /// Generate compliance report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_compliance_report(...); + /// ``` pub fn generate_compliance_report( env: &Env, period_start: u64, @@ -197,6 +271,21 @@ impl AuditManager { Ok(report.report_id) } + /// Get compliance report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_compliance_report(...); + /// ``` pub fn get_compliance_report(env: &Env, report_id: u64) -> Option { let reports: Map = env .storage() @@ -217,11 +306,39 @@ impl AuditManager { } /// Get total audit record count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_audit_count(...); + /// ``` pub fn get_audit_count(env: &Env) -> u64 { env.storage().instance().get(&AUDIT_COUNTER).unwrap_or(0u64) } /// Get recent audit records (last N records) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recent_audit_records(...); + /// ``` pub fn get_recent_audit_records(env: &Env, count: u32) -> Vec { let audit_counter: u64 = env.storage().instance().get(&AUDIT_COUNTER).unwrap_or(0u64); let mut result = Vec::new(env); @@ -240,6 +357,16 @@ impl AuditManager { } /// Log bridge operation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // log_bridge_operation(...); + /// ``` pub fn log_bridge_operation( env: &Env, is_outgoing: bool, @@ -260,6 +387,16 @@ impl AuditManager { } /// Log validator operation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // log_validator_operation(...); + /// ``` pub fn log_validator_operation( env: &Env, is_added: bool, @@ -277,6 +414,16 @@ impl AuditManager { } /// Log emergency operation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // log_emergency_operation(...); + /// ``` pub fn log_emergency_operation( env: &Env, is_pause: bool, @@ -294,6 +441,16 @@ impl AuditManager { } /// Clear old audit records (maintenance) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // clear_old_records(...); + /// ``` pub fn clear_old_records( env: &Env, before_timestamp: u64, diff --git a/contracts/teachlink/src/backup.rs b/contracts/teachlink/src/backup.rs index ffae369..60e2676 100644 --- a/contracts/teachlink/src/backup.rs +++ b/contracts/teachlink/src/backup.rs @@ -19,6 +19,16 @@ pub struct BackupManager; impl BackupManager { /// Create a backup manifest (authorized caller). Integrity hash is supplied by off-chain. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_backup(...); + /// ``` pub fn create_backup( env: &Env, creator: Address, @@ -75,6 +85,20 @@ impl BackupManager { } /// Get backup manifest by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_backup_manifest(...); + /// ``` pub fn get_backup_manifest(env: &Env, backup_id: u64) -> Option { let manifests: Map = env .storage() @@ -85,6 +109,16 @@ impl BackupManager { } /// Verify backup integrity (compare expected hash to stored). Emit event and audit. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // verify_backup(...); + /// ``` pub fn verify_backup( env: &Env, backup_id: u64, @@ -118,6 +152,16 @@ impl BackupManager { } /// Schedule automated backup (owner auth) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // schedule_backup(...); + /// ``` pub fn schedule_backup( env: &Env, owner: Address, @@ -157,6 +201,20 @@ impl BackupManager { } /// Get scheduled backups for an owner + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_scheduled_backups(...); + /// ``` pub fn get_scheduled_backups(env: &Env, owner: Address) -> Vec { let schedules: Map = env .storage() @@ -174,6 +232,16 @@ impl BackupManager { } /// Record a recovery execution (RTO tracking and audit trail) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_recovery(...); + /// ``` pub fn record_recovery( env: &Env, backup_id: u64, @@ -230,6 +298,20 @@ impl BackupManager { } /// Get recovery records (for audit trail and RTO reporting) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recovery_records(...); + /// ``` pub fn get_recovery_records(env: &Env, limit: u32) -> Vec { let counter: u64 = env.storage().instance().get(&RECOVERY_CNT).unwrap_or(0u64); let records: Map = env @@ -253,6 +335,20 @@ impl BackupManager { } /// Get recent backup manifests (for monitoring and compliance) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recent_backups(...); + /// ``` pub fn get_recent_backups(env: &Env, limit: u32) -> Vec { let counter: u64 = env .storage() diff --git a/contracts/teachlink/src/bft_consensus.rs b/contracts/teachlink/src/bft_consensus.rs index fc08b51..a37418b 100644 --- a/contracts/teachlink/src/bft_consensus.rs +++ b/contracts/teachlink/src/bft_consensus.rs @@ -28,6 +28,16 @@ pub struct BFTConsensus; impl BFTConsensus { /// Register a new validator with stake + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_validator(...); + /// ``` pub fn register_validator( env: &Env, validator: Address, @@ -95,6 +105,20 @@ impl BFTConsensus { } /// Unregister a validator and return stake + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // unregister_validator(...); + /// ``` pub fn unregister_validator(env: &Env, validator: Address) -> Result<(), BridgeError> { validator.require_auth(); @@ -142,6 +166,20 @@ impl BFTConsensus { } /// Create a new bridge proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_proposal(...); + /// ``` pub fn create_proposal(env: &Env, message: CrossChainMessage) -> Result { // Get proposal counter let mut proposal_counter: u64 = env @@ -200,6 +238,16 @@ impl BFTConsensus { } /// Vote on a bridge proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // vote_on_proposal(...); + /// ``` pub fn vote_on_proposal( env: &Env, validator: Address, @@ -345,6 +393,20 @@ impl BFTConsensus { } /// Check if an address is an active validator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_active_validator(...); + /// ``` pub fn is_active_validator(env: &Env, address: &Address) -> bool { env.storage() .instance() @@ -353,6 +415,20 @@ impl BFTConsensus { } /// Get validator info + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_validator_info(...); + /// ``` pub fn get_validator_info(env: &Env, validator: Address) -> Option { env.storage() .instance() @@ -360,6 +436,20 @@ impl BFTConsensus { } /// Get proposal by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_proposal(...); + /// ``` pub fn get_proposal(env: &Env, proposal_id: u64) -> Option { let proposals: Map = env .storage() @@ -370,6 +460,20 @@ impl BFTConsensus { } /// Get consensus state + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_consensus_state(...); + /// ``` pub fn get_consensus_state(env: &Env) -> ConsensusState { env.storage() .instance() @@ -383,6 +487,20 @@ impl BFTConsensus { } /// Get all active validators + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_active_validators(...); + /// ``` pub fn get_active_validators(env: &Env) -> Vec
{ let validators: Vec
= env .storage() @@ -399,6 +517,20 @@ impl BFTConsensus { } /// Check if BFT consensus is reached for a proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_consensus_reached(...); + /// ``` pub fn is_consensus_reached(env: &Env, proposal_id: u64) -> bool { if let Some(proposal) = Self::get_proposal(env, proposal_id) { proposal.vote_count >= proposal.required_votes diff --git a/contracts/teachlink/src/bridge.rs b/contracts/teachlink/src/bridge.rs index d660a2a..c6956b4 100644 --- a/contracts/teachlink/src/bridge.rs +++ b/contracts/teachlink/src/bridge.rs @@ -10,6 +10,876 @@ use crate::{ validation, }; +const BRIDGE_TIMEOUT_SECONDS: u64 = 604_800; +const MAX_BRIDGE_RETRY_ATTEMPTS: u32 = 5; +const BRIDGE_RETRY_DELAY_BASE_SECONDS: u64 = 300; + +pub struct Bridge; + +impl Bridge { + /// Initialize the bridge contract + /// - token: Address of the TeachLink token contract + /// - admin: Address of the bridge administrator + /// - min_validators: Minimum number of validators required for cross-chain verification + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize(...); + /// ``` + pub fn initialize( + env: &Env, + token: Address, + admin: Address, + min_validators: u32, + fee_recipient: Address, + ) -> Result<(), BridgeError> { + // Check if already initialized + if env.storage().instance().has(&TOKEN) { + return Err(BridgeError::AlreadyInitialized); + } + + if min_validators == 0 { + return Err(BridgeError::MinimumValidatorsMustBeAtLeastOne); + } + + env.storage().instance().set(&TOKEN, &token); + env.storage().instance().set(&ADMIN, &admin); + env.storage() + .instance() + .set(&MIN_VALIDATORS, &min_validators); + env.storage().instance().set(&NONCE, &0u64); + env.storage().instance().set(&FEE_RECIPIENT, &fee_recipient); + env.storage().instance().set(&BRIDGE_FEE, &0i128); // Default no fee + + // Initialize empty validators map + let validators: Map = Map::new(env); + env.storage().instance().set(&VALIDATORS, &validators); + + // Initialize empty supported chains map + let chains: Map = Map::new(env); + env.storage().instance().set(&SUPPORTED_CHAINS, &chains); + + Ok(()) + } + + /// Bridge tokens out to another chain (lock/burn tokens on Stellar) + /// - amount: Amount of tokens to bridge + /// - destination_chain: Chain ID of the destination blockchain + /// - destination_address: Address on the destination chain (encoded as bytes) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // bridge_out(...); + /// ``` + pub fn bridge_out( + env: &Env, + from: Address, + amount: i128, + destination_chain: u32, + destination_address: soroban_sdk::Bytes, + ) -> Result { + from.require_auth(); + + // Validate all input parameters + BridgeValidator::validate_bridge_out( + env, + &from, + amount, + destination_chain, + &destination_address, + )?; + + // Check if destination chain is supported + let supported_chains: Map = env + .storage() + .instance() + .get(&SUPPORTED_CHAINS) + .unwrap_or_else(|| Map::new(env)); + if !supported_chains.get(destination_chain).unwrap_or(false) { + return Err(BridgeError::DestinationChainNotSupported); + } + + // Get token address + let token: Address = env.storage().instance().get(&TOKEN).unwrap(); + + // Transfer tokens from user to bridge (locking them) + env.invoke_contract::<()>( + &token, + &symbol_short!("transfer"), + vec![ + env, + from.into_val(env), + env.current_contract_address().into_val(env), + amount.into_val(env), + ], + ); + + // Apply bridge fee if configured + let fee: i128 = env.storage().instance().get(&BRIDGE_FEE).unwrap_or(0i128); + let fee_recipient: Address = env.storage().instance().get(&FEE_RECIPIENT).unwrap(); + let amount_after_fee = if fee > 0 && fee < amount { + env.invoke_contract::<()>( + &token, + &symbol_short!("transfer"), + vec![ + env, + env.current_contract_address().into_val(env), + fee_recipient.into_val(env), + fee.into_val(env), + ], + ); + amount - fee + } else { + amount + }; + + // Generate nonce for this transaction + let mut nonce: u64 = env.storage().instance().get(&NONCE).unwrap_or(0u64); + nonce += 1; + env.storage().instance().set(&NONCE, &nonce); + + // Create bridge transaction record + let bridge_tx = BridgeTransaction { + nonce, + token: token.clone(), + amount: amount_after_fee, + recipient: from.clone(), + destination_chain, + destination_address: destination_address.clone(), + timestamp: env.ledger().timestamp(), + }; + + // Store bridge transaction + let mut bridge_txs: Map = env + .storage() + .instance() + .get(&BRIDGE_TXS) + .unwrap_or_else(|| Map::new(env)); + bridge_txs.set(nonce, bridge_tx.clone()); + env.storage().instance().set(&BRIDGE_TXS, &bridge_txs); + + let mut retry_counts: Map = env + .storage() + .instance() + .get(&BRIDGE_RETRY_COUNTS) + .unwrap_or_else(|| Map::new(env)); + retry_counts.set(nonce, 0); + env.storage() + .instance() + .set(&BRIDGE_RETRY_COUNTS, &retry_counts); + + let mut last_retry: Map = env + .storage() + .instance() + .get(&BRIDGE_LAST_RETRY) + .unwrap_or_else(|| Map::new(env)); + last_retry.set(nonce, env.ledger().timestamp()); + env.storage() + .instance() + .set(&BRIDGE_LAST_RETRY, &last_retry); + + // Emit events + BridgeInitiatedEvent { + nonce, + transaction: bridge_tx.clone(), + } + .publish(env); + + DepositEvent { + nonce, + from, + amount: amount_after_fee, + destination_chain, + destination_address, + } + .publish(env); + + Ok(nonce) + } + + /// Complete a bridge transaction (mint/release tokens on Stellar) + /// This is called by validators after verifying the transaction on the source chain + /// - message: Cross-chain message containing transaction details + /// - validator_signatures: List of validator addresses that have verified this transaction + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // complete_bridge(...); + /// ``` + pub fn complete_bridge( + env: &Env, + message: CrossChainMessage, + validator_signatures: Vec
, + ) -> Result<(), BridgeError> { + // Validate all input parameters + let min_validators: u32 = env.storage().instance().get(&MIN_VALIDATORS).unwrap(); + BridgeValidator::validate_bridge_completion( + env, + &message, + &validator_signatures, + min_validators, + )?; + + // Verify all signatures are from valid validators + let validators: Map = env.storage().instance().get(&VALIDATORS).unwrap(); + for validator in validator_signatures.iter() { + if !validators.get(validator.clone()).unwrap_or(false) { + return Err(BridgeError::InvalidValidatorSignature); + } + } + + // Check for duplicate nonce to prevent replay attacks + let mut processed_nonces: Map = env + .storage() + .persistent() + .get(&NONCE) + .unwrap_or_else(|| Map::new(env)); + if processed_nonces.get(message.nonce).unwrap_or(false) { + return Err(BridgeError::NonceAlreadyProcessed); + } + processed_nonces.set(message.nonce, true); + env.storage().persistent().set(&NONCE, &processed_nonces); + + // Get token address + let token: Address = env.storage().instance().get(&TOKEN).unwrap(); + + // Verify token matches + if message.token != token { + return Err(BridgeError::TokenMismatch); + } + + // Mint/release tokens to recipient + env.invoke_contract::<()>( + &token, + &symbol_short!("mint"), + vec![ + env, + message.recipient.into_val(env), + message.amount.into_val(env), + ], + ); + + // Emit events + BridgeCompletedEvent { + nonce: message.nonce, + message: message.clone(), + } + .publish(env); + + ReleaseEvent { + nonce: message.nonce, + recipient: message.recipient.clone(), + amount: message.amount, + source_chain: message.source_chain, + } + .publish(env); + + let mut bridge_txs: Map = env + .storage() + .instance() + .get(&BRIDGE_TXS) + .unwrap_or_else(|| Map::new(env)); + if bridge_txs.contains_key(message.nonce) { + bridge_txs.remove(message.nonce); + env.storage().instance().set(&BRIDGE_TXS, &bridge_txs); + } + + Self::clear_bridge_retry_metadata(env, message.nonce); + + Ok(()) + } + + /// Standard API for mark_bridge_failed + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // mark_bridge_failed(...); + /// ``` + pub fn mark_bridge_failed(env: &Env, nonce: u64, reason: Bytes) -> Result<(), BridgeError> { + if reason.is_empty() { + return Err(BridgeError::InvalidInput); + } + + let bridge_txs: Map = env + .storage() + .instance() + .get(&BRIDGE_TXS) + .unwrap_or_else(|| Map::new(env)); + if !bridge_txs.contains_key(nonce) { + return Err(BridgeError::BridgeTransactionNotFound); + } + + let mut failures: Map = env + .storage() + .instance() + .get(&BRIDGE_FAILURES) + .unwrap_or_else(|| Map::new(env)); + failures.set(nonce, reason); + env.storage().instance().set(&BRIDGE_FAILURES, &failures); + + Ok(()) + } + + /// Standard API for retry_bridge + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // retry_bridge(...); + /// ``` + pub fn retry_bridge(env: &Env, nonce: u64) -> Result { + let bridge_txs: Map = env + .storage() + .instance() + .get(&BRIDGE_TXS) + .unwrap_or_else(|| Map::new(env)); + let bridge_tx = bridge_txs + .get(nonce) + .ok_or(BridgeError::BridgeTransactionNotFound)?; + + let current_time = env.ledger().timestamp(); + if current_time.saturating_sub(bridge_tx.timestamp) >= BRIDGE_TIMEOUT_SECONDS { + return Err(BridgeError::PacketTimeout); + } + + let mut retry_counts: Map = env + .storage() + .instance() + .get(&BRIDGE_RETRY_COUNTS) + .unwrap_or_else(|| Map::new(env)); + let retry_count = retry_counts.get(nonce).unwrap_or(0); + if retry_count >= MAX_BRIDGE_RETRY_ATTEMPTS { + return Err(BridgeError::RetryLimitExceeded); + } + + let mut last_retry: Map = env + .storage() + .instance() + .get(&BRIDGE_LAST_RETRY) + .unwrap_or_else(|| Map::new(env)); + let last_retry_at = last_retry.get(nonce).unwrap_or(bridge_tx.timestamp); + + let backoff_multiplier = 1u64 << retry_count; + let retry_delay = BRIDGE_RETRY_DELAY_BASE_SECONDS.saturating_mul(backoff_multiplier); + let next_allowed_retry = last_retry_at.saturating_add(retry_delay); + + if current_time < next_allowed_retry { + return Err(BridgeError::RetryBackoffActive); + } + + let updated_retry_count = retry_count + 1; + retry_counts.set(nonce, updated_retry_count); + env.storage() + .instance() + .set(&BRIDGE_RETRY_COUNTS, &retry_counts); + last_retry.set(nonce, current_time); + env.storage() + .instance() + .set(&BRIDGE_LAST_RETRY, &last_retry); + + let mut failures: Map = env + .storage() + .instance() + .get(&BRIDGE_FAILURES) + .unwrap_or_else(|| Map::new(env)); + failures.remove(nonce); + env.storage().instance().set(&BRIDGE_FAILURES, &failures); + + Ok(updated_retry_count) + } + + /// Cancel a bridge transaction and refund locked tokens + /// Only callable after a timeout period + /// - nonce: The nonce of the bridge transaction to cancel + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // cancel_bridge(...); + /// ``` + pub fn cancel_bridge(env: &Env, nonce: u64) -> Result<(), BridgeError> { + // Get bridge transaction + let bridge_txs: Map = env + .storage() + .instance() + .get(&BRIDGE_TXS) + .unwrap_or_else(|| Map::new(env)); + let bridge_tx = bridge_txs + .get(nonce) + .ok_or(BridgeError::BridgeTransactionNotFound)?; + + let failures: Map = env + .storage() + .instance() + .get(&BRIDGE_FAILURES) + .unwrap_or_else(|| Map::new(env)); + + // Allow refunds for timed-out or explicitly failed transactions + let elapsed = env.ledger().timestamp().saturating_sub(bridge_tx.timestamp); + if elapsed < BRIDGE_TIMEOUT_SECONDS && !failures.contains_key(nonce) { + return Err(BridgeError::TimeoutNotReached); + } + + // Get token address + let token: Address = env.storage().instance().get(&TOKEN).unwrap(); + + // Refund tokens to original recipient + env.invoke_contract::<()>( + &token, + &symbol_short!("transfer"), + vec![ + env, + env.current_contract_address().into_val(env), + bridge_tx.recipient.into_val(env), + bridge_tx.amount.into_val(env), + ], + ); + + // Remove from bridge transactions + let mut updated_txs = bridge_txs; + updated_txs.remove(nonce); + env.storage().instance().set(&BRIDGE_TXS, &updated_txs); + + Self::clear_bridge_retry_metadata(env, nonce); + + Ok(()) + } + + /// Standard API for refund_bridge_transaction + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // refund_bridge_transaction(...); + /// ``` + pub fn refund_bridge_transaction(env: &Env, nonce: u64) -> Result<(), BridgeError> { + Self::cancel_bridge(env, nonce) + } + + fn clear_bridge_retry_metadata(env: &Env, nonce: u64) { + let mut retry_counts: Map = env + .storage() + .instance() + .get(&BRIDGE_RETRY_COUNTS) + .unwrap_or_else(|| Map::new(env)); + retry_counts.remove(nonce); + env.storage() + .instance() + .set(&BRIDGE_RETRY_COUNTS, &retry_counts); + + let mut last_retry: Map = env + .storage() + .instance() + .get(&BRIDGE_LAST_RETRY) + .unwrap_or_else(|| Map::new(env)); + last_retry.remove(nonce); + env.storage() + .instance() + .set(&BRIDGE_LAST_RETRY, &last_retry); + + let mut failures: Map = env + .storage() + .instance() + .get(&BRIDGE_FAILURES) + .unwrap_or_else(|| Map::new(env)); + failures.remove(nonce); + env.storage().instance().set(&BRIDGE_FAILURES, &failures); + } + + // ========== Admin Functions ========== + + /// Add a validator (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_validator(...); + /// ``` + #[allow(clippy::unnecessary_wraps)] + pub fn add_validator(env: &Env, validator: Address) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + let mut validators: Map = env.storage().instance().get(&VALIDATORS).unwrap(); + validators.set(validator, true); + env.storage().instance().set(&VALIDATORS, &validators); + + Ok(()) + } + + /// Remove a validator (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // remove_validator(...); + /// ``` + #[allow(clippy::unnecessary_wraps)] + pub fn remove_validator(env: &Env, validator: Address) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + let mut validators: Map = env.storage().instance().get(&VALIDATORS).unwrap(); + validators.set(validator, false); + env.storage().instance().set(&VALIDATORS, &validators); + + Ok(()) + } + + /// Add a supported destination chain (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_supported_chain(...); + /// ``` + #[allow(clippy::unnecessary_wraps)] + pub fn add_supported_chain(env: &Env, chain_id: u32) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + let mut chains: Map = env.storage().instance().get(&SUPPORTED_CHAINS).unwrap(); + chains.set(chain_id, true); + env.storage().instance().set(&SUPPORTED_CHAINS, &chains); + + Ok(()) + } + + /// Remove a supported destination chain (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // remove_supported_chain(...); + /// ``` + #[allow(clippy::unnecessary_wraps)] + pub fn remove_supported_chain(env: &Env, chain_id: u32) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + let mut chains: Map = env.storage().instance().get(&SUPPORTED_CHAINS).unwrap(); + chains.set(chain_id, false); + env.storage().instance().set(&SUPPORTED_CHAINS, &chains); + + Ok(()) + } + + /// Set bridge fee (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_bridge_fee(...); + /// ``` + pub fn set_bridge_fee(env: &Env, fee: i128) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + if fee < 0 { + return Err(BridgeError::FeeCannotBeNegative); + } + + env.storage().instance().set(&BRIDGE_FEE, &fee); + + Ok(()) + } + + /// Set fee recipient (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_fee_recipient(...); + /// ``` + #[allow(clippy::unnecessary_wraps)] + pub fn set_fee_recipient(env: &Env, fee_recipient: Address) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + env.storage().instance().set(&FEE_RECIPIENT, &fee_recipient); + + Ok(()) + } + + /// Set minimum validators (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_min_validators(...); + /// ``` + pub fn set_min_validators(env: &Env, min_validators: u32) -> Result<(), BridgeError> { + let admin: Address = env.storage().instance().get(&ADMIN).unwrap(); + admin.require_auth(); + + if min_validators == 0 { + return Err(BridgeError::MinimumValidatorsMustBeAtLeastOne); + } + + env.storage() + .instance() + .set(&MIN_VALIDATORS, &min_validators); + + Ok(()) + } + + // ========== View Functions ========== + + /// Get the bridge transaction by nonce + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_transaction(...); + /// ``` + pub fn get_bridge_transaction(env: &Env, nonce: u64) -> Option { + let bridge_txs: Map = env + .storage() + .instance() + .get(&BRIDGE_TXS) + .unwrap_or_else(|| Map::new(env)); + bridge_txs.get(nonce) + } + + /// Check if a chain is supported + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_chain_supported(...); + /// ``` + pub fn is_chain_supported(env: &Env, chain_id: u32) -> bool { + let chains: Map = env + .storage() + .instance() + .get(&SUPPORTED_CHAINS) + .unwrap_or_else(|| Map::new(env)); + chains.get(chain_id).unwrap_or(false) + } + + /// Check if an address is a validator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_validator(...); + /// ``` + pub fn is_validator(env: &Env, address: Address) -> bool { + let validators: Map = env + .storage() + .instance() + .get(&VALIDATORS) + .unwrap_or_else(|| Map::new(env)); + validators.get(address).unwrap_or(false) + } + + /// Get the current nonce + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_nonce(...); + /// ``` + pub fn get_nonce(env: &Env) -> u64 { + env.storage().instance().get(&NONCE).unwrap_or(0u64) + } + + /// Get the bridge fee + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_fee(...); + /// ``` + pub fn get_bridge_fee(env: &Env) -> i128 { + env.storage().instance().get(&BRIDGE_FEE).unwrap_or(0i128) + } + + /// Get the token address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_token(...); + /// ``` + pub fn get_token(env: &Env) -> Address { + env.storage().instance().get(&TOKEN).unwrap() + } + + /// Get the admin address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_admin(...); + /// ``` + pub fn get_admin(env: &Env) -> Address { + env.storage().instance().get(&ADMIN).unwrap() + } +} /// Calculate the fee for a given amount and rate (basis points). pub fn calculate_fee(amount: i128, fee_rate: u32) -> i128 { amount * fee_rate as i128 / constants::fees::FEE_CALCULATION_DIVISOR as i128 diff --git a/contracts/teachlink/src/content_nft.rs b/contracts/teachlink/src/content_nft.rs index 8abe2c9..965eb3f 100644 --- a/contracts/teachlink/src/content_nft.rs +++ b/contracts/teachlink/src/content_nft.rs @@ -21,6 +21,18 @@ pub struct ContentNFT { pub created_at: u64, } +/// Standard API for mint_content +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // mint_content(...); +/// ``` pub fn mint_content( creator: Address, metadata: ContentMetadata, diff --git a/contracts/teachlink/src/content_quality.rs b/contracts/teachlink/src/content_quality.rs index 572dc58..f778f4a 100644 --- a/contracts/teachlink/src/content_quality.rs +++ b/contracts/teachlink/src/content_quality.rs @@ -787,6 +787,16 @@ pub struct ContentQualityManager; impl ContentQualityManager { /// Assess content quality using AI and automated checks + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // assess_content_quality(...); + /// ``` pub fn assess_content_quality( env: &Env, content_id: u64, @@ -825,6 +835,16 @@ impl ContentQualityManager { } /// Check content for plagiarism + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_plagiarism(...); + /// ``` pub fn check_plagiarism( env: &Env, content_id: u64, @@ -857,6 +877,16 @@ impl ContentQualityManager { } /// Submit content for community moderation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // submit_for_moderation(...); + /// ``` pub fn submit_for_moderation( env: &Env, content_id: u64, @@ -881,6 +911,16 @@ impl ContentQualityManager { } /// Create quality improvement plan + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_improvement_plan(...); + /// ``` pub fn create_improvement_plan( env: &Env, content_id: u64, diff --git a/contracts/teachlink/src/emergency.rs b/contracts/teachlink/src/emergency.rs index 08cea22..706a126 100644 --- a/contracts/teachlink/src/emergency.rs +++ b/contracts/teachlink/src/emergency.rs @@ -20,6 +20,20 @@ pub struct EmergencyManager; impl EmergencyManager { /// Pause the entire bridge + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pause_bridge(...); + /// ``` pub fn pause_bridge(env: &Env, pauser: Address, reason: Bytes) -> Result<(), BridgeError> { pauser.require_auth(); @@ -64,6 +78,20 @@ impl EmergencyManager { } /// Resume the bridge + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // resume_bridge(...); + /// ``` pub fn resume_bridge(env: &Env, resumer: Address) -> Result<(), BridgeError> { resumer.require_auth(); @@ -102,6 +130,16 @@ impl EmergencyManager { } /// Pause specific chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pause_chains(...); + /// ``` pub fn pause_chains( env: &Env, pauser: Address, @@ -135,6 +173,16 @@ impl EmergencyManager { } /// Resume specific chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // resume_chains(...); + /// ``` pub fn resume_chains( env: &Env, resumer: Address, @@ -166,6 +214,16 @@ impl EmergencyManager { } /// Initialize circuit breaker for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_circuit_breaker(...); + /// ``` pub fn initialize_circuit_breaker( env: &Env, chain_id: u32, @@ -195,6 +253,16 @@ impl EmergencyManager { } /// Check and update circuit breaker for a transaction + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_circuit_breaker(...); + /// ``` pub fn check_circuit_breaker( env: &Env, chain_id: u32, @@ -273,6 +341,16 @@ impl EmergencyManager { } /// Reset circuit breaker for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // reset_circuit_breaker(...); + /// ``` pub fn reset_circuit_breaker( env: &Env, chain_id: u32, @@ -303,6 +381,20 @@ impl EmergencyManager { } /// Check if bridge is paused + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_bridge_paused(...); + /// ``` pub fn is_bridge_paused(env: &Env) -> bool { let emergency_state: EmergencyState = env .storage() @@ -319,6 +411,20 @@ impl EmergencyManager { } /// Check if a chain is paused + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_chain_paused(...); + /// ``` pub fn is_chain_paused(env: &Env, chain_id: u32) -> bool { let paused_chains: Map = env .storage() @@ -329,6 +435,20 @@ impl EmergencyManager { } /// Get emergency state + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_emergency_state(...); + /// ``` pub fn get_emergency_state(env: &Env) -> EmergencyState { env.storage() .instance() @@ -343,6 +463,20 @@ impl EmergencyManager { } /// Get circuit breaker state + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_circuit_breaker(...); + /// ``` pub fn get_circuit_breaker(env: &Env, chain_id: u32) -> Option { let circuit_breakers: Map = env .storage() @@ -353,6 +487,20 @@ impl EmergencyManager { } /// Get all paused chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_paused_chains(...); + /// ``` pub fn get_paused_chains(env: &Env) -> Vec { let paused_chains: Map = env .storage() @@ -370,6 +518,16 @@ impl EmergencyManager { } /// Update circuit breaker limits + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_circuit_breaker_limits(...); + /// ``` pub fn update_circuit_breaker_limits( env: &Env, chain_id: u32, diff --git a/contracts/teachlink/src/escrow.rs b/contracts/teachlink/src/escrow.rs index fd01fcf..bf795b5 100644 --- a/contracts/teachlink/src/escrow.rs +++ b/contracts/teachlink/src/escrow.rs @@ -14,6 +14,18 @@ use soroban_sdk::{symbol_short, vec, Address, Bytes, Env, IntoVal, Map, Vec}; pub struct EscrowManager; impl EscrowManager { + /// Standard API for create_escrow + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_escrow(...); + /// ``` pub fn create_escrow( env: &Env, depositor: Address, @@ -97,6 +109,18 @@ impl EscrowManager { Ok(escrow_count) } + /// Standard API for approve_release + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // approve_release(...); + /// ``` pub fn approve_release( env: &Env, escrow_id: u64, @@ -134,6 +158,22 @@ impl EscrowManager { Ok(escrow.approval_count) } + /// Standard API for release + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // release(...); + /// ``` pub fn release(env: &Env, escrow_id: u64, caller: Address) -> Result<(), EscrowError> { caller.require_auth(); @@ -156,6 +196,22 @@ impl EscrowManager { Ok(()) } + /// Standard API for refund + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // refund(...); + /// ``` pub fn refund(env: &Env, escrow_id: u64, depositor: Address) -> Result<(), EscrowError> { depositor.require_auth(); @@ -189,6 +245,22 @@ impl EscrowManager { Ok(()) } + /// Standard API for cancel + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // cancel(...); + /// ``` pub fn cancel(env: &Env, escrow_id: u64, depositor: Address) -> Result<(), EscrowError> { depositor.require_auth(); @@ -211,6 +283,18 @@ impl EscrowManager { Ok(()) } + /// Standard API for dispute + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // dispute(...); + /// ``` pub fn dispute( env: &Env, escrow_id: u64, @@ -247,6 +331,18 @@ impl EscrowManager { Ok(()) } + /// Standard API for resolve + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // resolve(...); + /// ``` pub fn resolve( env: &Env, escrow_id: u64, @@ -300,6 +396,22 @@ impl EscrowManager { Ok(()) } + /// Standard API for auto_check_dispute + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // auto_check_dispute(...); + /// ``` pub fn auto_check_dispute(env: &Env, escrow_id: u64) -> Result<(), EscrowError> { let mut escrow = Self::load_escrow(env, escrow_id)?; if ArbitrationManager::check_stalled_escrow(env, &escrow) { @@ -320,14 +432,62 @@ impl EscrowManager { // ---------- Views ---------- + /// Standard API for get_escrow + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_escrow(...); + /// ``` pub fn get_escrow(env: &Env, escrow_id: u64) -> Option { Self::load_escrows(env).get(escrow_id) } + /// Standard API for get_escrow_count + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_escrow_count(...); + /// ``` pub fn get_escrow_count(env: &Env) -> u64 { env.storage().instance().get(&ESCROW_COUNT).unwrap_or(0) } + /// Standard API for has_approved + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // has_approved(...); + /// ``` pub fn has_approved(env: &Env, escrow_id: u64, signer: Address) -> bool { let key = EscrowApprovalKey { escrow_id, signer }; env.storage().persistent().has(&key) diff --git a/contracts/teachlink/src/escrow_analytics.rs b/contracts/teachlink/src/escrow_analytics.rs index 997b9b6..295f0ea 100644 --- a/contracts/teachlink/src/escrow_analytics.rs +++ b/contracts/teachlink/src/escrow_analytics.rs @@ -5,6 +5,18 @@ use soroban_sdk::{Env, Map}; pub struct EscrowAnalyticsManager; impl EscrowAnalyticsManager { + /// Standard API for update_creation + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_creation(...); + /// ``` pub fn update_creation(env: &Env, amount: i128) { let mut metrics = Self::get_metrics(env); metrics.total_escrows += 1; @@ -12,12 +24,36 @@ impl EscrowAnalyticsManager { env.storage().instance().set(&ESCROW_ANALYTICS, &metrics); } + /// Standard API for update_dispute + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_dispute(...); + /// ``` pub fn update_dispute(env: &Env) { let mut metrics = Self::get_metrics(env); metrics.total_disputes += 1; env.storage().instance().set(&ESCROW_ANALYTICS, &metrics); } + /// Standard API for update_resolution + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_resolution(...); + /// ``` pub fn update_resolution(env: &Env, resolution_time: u64) { let mut metrics = Self::get_metrics(env); metrics.total_resolved += 1; @@ -34,6 +70,22 @@ impl EscrowAnalyticsManager { env.storage().instance().set(&ESCROW_ANALYTICS, &metrics); } + /// Standard API for get_metrics + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_metrics(...); + /// ``` pub fn get_metrics(env: &Env) -> EscrowMetrics { env.storage() .instance() diff --git a/contracts/teachlink/src/insurance.rs b/contracts/teachlink/src/insurance.rs index 2fef061..4cb3367 100644 --- a/contracts/teachlink/src/insurance.rs +++ b/contracts/teachlink/src/insurance.rs @@ -9,6 +9,16 @@ pub struct InsuranceManager; impl InsuranceManager { /// Initialize the insurance pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_pool(...); + /// ``` pub fn initialize_pool( env: &Env, token: Address, @@ -26,6 +36,20 @@ impl InsuranceManager { } /// Fund the insurance pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fund_pool(...); + /// ``` pub fn fund_pool(env: &Env, funder: Address, amount: i128) -> Result<(), EscrowError> { funder.require_auth(); let mut pool: InsurancePool = env @@ -51,6 +75,20 @@ impl InsuranceManager { } /// Calculate insurance premium for an escrow amount + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // calculate_premium(...); + /// ``` pub fn calculate_premium(env: &Env, amount: i128) -> i128 { let pool: InsurancePool = env.storage() @@ -68,12 +106,40 @@ impl InsuranceManager { } /// Pay premium and add to pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pay_premium(...); + /// ``` pub fn pay_premium(env: &Env, user: Address, amount: i128) -> Result<(), EscrowError> { user.require_auth(); Self::pay_premium_internal(env, user, amount) } /// Internal: Pay premium and add to pool (no auth check) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pay_premium_internal(...); + /// ``` pub fn pay_premium_internal(env: &Env, user: Address, amount: i128) -> Result<(), EscrowError> { let mut pool: InsurancePool = env .storage() @@ -98,6 +164,16 @@ impl InsuranceManager { } /// Process an insurance claim + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // process_claim(...); + /// ``` pub fn process_claim( env: &Env, recipient: Address, @@ -135,6 +211,20 @@ impl InsuranceManager { } /// Risk assessment for an escrow + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // assess_risk(...); + /// ``` pub fn assess_risk(env: &Env, escrow_id: u64, amount: i128) -> u32 { // Simple risk assessment: score 0-100 // Higher amount = higher risk diff --git a/contracts/teachlink/src/learning_paths.rs b/contracts/teachlink/src/learning_paths.rs index 6391021..0a8005d 100644 --- a/contracts/teachlink/src/learning_paths.rs +++ b/contracts/teachlink/src/learning_paths.rs @@ -449,6 +449,16 @@ pub struct LearningPathManager; impl LearningPathManager { /// Generate AI-powered learning path based on user goals and profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_learning_path(...); + /// ``` pub fn generate_learning_path( env: &Env, user: Address, @@ -533,6 +543,16 @@ impl LearningPathManager { } /// Adapt learning path based on performance and feedback + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // adapt_learning_path(...); + /// ``` pub fn adapt_learning_path( env: &Env, user: Address, @@ -557,6 +577,16 @@ impl LearningPathManager { } /// Create collaborative learning path + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_collaborative_path(...); + /// ``` pub fn create_collaborative_path( env: &Env, creator: Address, @@ -592,6 +622,16 @@ impl LearningPathManager { } /// Issue certification for completed learning path + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // issue_certification(...); + /// ``` pub fn issue_certification( env: &Env, user: Address, diff --git a/contracts/teachlink/src/lib.rs b/contracts/teachlink/src/lib.rs index 5fb667d..a6c5302 100644 --- a/contracts/teachlink/src/lib.rs +++ b/contracts/teachlink/src/lib.rs @@ -47,38 +47,3136 @@ impl TeachLinkBridge { env.storage().instance().set(&CONFIG, &config); } + /// Initialize the bridge contract + /// + /// This function sets up the core parameters for the bridge, including the token, + /// administrator, and initial validator threshold. It must be called once before + /// any other bridge functions. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `token` - The address of the token to be bridged. + /// * `admin` - The address with administrative permissions. + /// * `min_validators` - The minimum number of validator signatures required for a bridge transaction. + /// * `fee_recipient` - The address that will receive bridge fees. + /// + /// # Returns + /// + /// * `Result<(), BridgeError>` - Returns `Ok(())` if initialization is successful. + /// + /// # Errors + /// + /// * `AlreadyInitialized` - If the contract has already been initialized. + /// + /// # Examples + /// + /// ```rust + /// TeachLinkBridge::initialize(env, token_addr, admin_addr, 3, fee_collector_addr); + /// ``` + pub fn initialize_v2( + env: Env, + token: Address, + admin: Address, + min_validators: u32, + fee_recipient: Address, + ) -> Result<(), BridgeError> { + bridge::Bridge::initialize(&env, token, admin, min_validators, fee_recipient) + } + /// Bridge tokens to another chain; returns the transaction nonce. + /// Bridge tokens out to another chain + /// + /// Locks or burns tokens on the Stellar network to be minted or released on the + /// destination chain. Generates a unique nonce for tracking the transaction. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `from` - The address of the user initiating the bridge. + /// * `amount` - The amount of tokens to bridge. + /// * `destination_chain` - The ID of the target blockchain. + /// * `destination_address` - The recipient's address on the destination chain. + /// + /// # Returns + /// + /// * `Result` - Returns the unique nonce of the bridge transaction. + /// + /// # Errors + /// + /// * `InvalidAmount` - If the amount is less than or equal to zero. + /// * `UnsupportedChain` - If the destination chain is not supported. + /// * `InsufficientBalance` - If the sender does not have enough tokens. + /// + /// # Events + /// + /// * `BridgeOut` - Emitted when tokens are successfully locked for bridging. + /// + /// # Examples + /// + /// ```rust + /// let nonce = TeachLinkBridge::bridge_out(env, user_addr, 1000, 1, dest_bytes); + /// ``` pub fn bridge_out( env: Env, - from: Address, - amount: i128, - destination_chain: u32, - destination_address: Bytes, - ) -> u64 { - bridge::bridge_out(&env, from, amount, destination_chain, destination_address) + from: Address, + amount: i128, + destination_chain: u32, + destination_address: Bytes, + ) -> u64 { + bridge::bridge_out(&env, from, amount, destination_chain, destination_address) + } + + /// Register a new supported chain (admin only). + /// Complete an incoming bridge transaction + /// + /// This function handles the completion of a bridge transaction from another chain + /// to Stellar. It validates validator signatures and mints or releases tokens to + /// the recipient on Stellar. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `message` - The `CrossChainMessage` containing transaction details. + /// * `validator_signatures` - A list of validator addresses who signed the message. + /// + /// # Returns + /// + /// * `Result<(), BridgeError>` - Returns `Ok(())` if the transaction is completed. + /// + /// # Errors + /// + /// * `ThresholdNotMet` - If the number of signatures is below the threshold. + /// * `InvalidSignature` - If any validator signature is invalid. + /// * `AlreadyCompleted` - If the bridge transaction has already been processed. + /// + /// # Examples + /// + /// ```rust + /// TeachLinkBridge::complete_bridge(env, message, signatures); + /// ``` + pub fn complete_bridge( + env: Env, + message: CrossChainMessage, + validator_signatures: Vec
, + ) -> Result<(), BridgeError> { + bridge::Bridge::complete_bridge(&env, message, validator_signatures) + } + + /// Cancel a pending bridge transaction + /// + /// Refunds the locked tokens to the sender if the bridge hasn't been completed. + /// Typically used for timeouts or if the user cancels before validator consensus. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `nonce` - The unique nonce identifying the bridge transaction. + /// + /// # Returns + /// + /// * `Result<(), BridgeError>` - Returns `Ok(())` if the cancellation succeeds. + /// + /// # Errors + /// + /// * `NotFound` - If the bridge transaction does not exist. + /// * `AlreadyCompleted` - If the transaction has already been completed. + /// + /// # Examples + /// + /// ```rust + /// TeachLinkBridge::cancel_bridge(env, nonce); + /// ``` + pub fn cancel_bridge(env: Env, nonce: u64) -> Result<(), BridgeError> { + bridge::Bridge::cancel_bridge(&env, nonce) + } + + /// Mark a bridge transaction as failed + /// + /// Records the reason for failure and allows for subsequent retries or refunds. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `nonce` - The unique nonce identifying the bridge transaction. + /// * `reason` - A bytes object describing why the transaction failed. + /// + /// # Returns + /// + /// * `Result<(), BridgeError>` - Returns `Ok(())` if successful. + /// + /// # Examples + /// + /// ```rust + /// TeachLinkBridge::mark_bridge_failed(env, nonce, reason); + /// ``` + pub fn mark_bridge_failed(env: Env, nonce: u64, reason: Bytes) -> Result<(), BridgeError> { + bridge::Bridge::mark_bridge_failed(&env, nonce, reason) + } + + /// Standard API for retry_bridge + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // retry_bridge(...); + /// ``` + pub fn retry_bridge(env: Env, nonce: u64) -> Result { + bridge::Bridge::retry_bridge(&env, nonce) + } + + /// Standard API for refund_bridge_transaction + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // refund_bridge_transaction(...); + /// ``` + pub fn refund_bridge_transaction(env: Env, nonce: u64) -> Result<(), BridgeError> { + bridge::Bridge::refund_bridge_transaction(&env, nonce) + } + + // ========== Admin Functions ========== + + /// Add a new validator to the bridge + /// + /// This function adds an address to the authorized list of validators. + /// Only the contract administrator can call this function. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `validator` - The address of the new validator. + /// + /// # Examples + /// + /// ```rust + /// TeachLinkBridge::add_validator(env, validator_addr); + /// ``` + pub fn add_validator(env: Env, validator: Address) { + let _ = bridge::Bridge::add_validator(&env, validator); + } + + /// Remove a validator from the bridge + /// + /// This function removes an address from the authorized list of validators. + /// Only the contract administrator can call this function. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `validator` - The address of the validator to remove. + /// + /// # Examples + /// + /// ```rust + /// TeachLinkBridge::remove_validator(env, validator_addr); + /// ``` + pub fn remove_validator(env: Env, validator: Address) { + let _ = bridge::Bridge::remove_validator(&env, validator); + } + + /// Add a supported destination chain (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_supported_chain(...); + /// ``` + pub fn add_supported_chain(env: Env, chain_id: u32) { + let _ = bridge::Bridge::add_supported_chain(&env, chain_id); + } + + /// Remove a supported destination chain (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // remove_supported_chain(...); + /// ``` + pub fn remove_supported_chain(env: Env, chain_id: u32) { + let _ = bridge::Bridge::remove_supported_chain(&env, chain_id); + } + + /// Set bridge fee (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_bridge_fee(...); + /// ``` + pub fn set_bridge_fee(env: Env, fee: i128) -> Result<(), BridgeError> { + bridge::Bridge::set_bridge_fee(&env, fee) + } + + /// Set fee recipient (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_fee_recipient(...); + /// ``` + pub fn set_fee_recipient(env: Env, fee_recipient: Address) { + let _ = bridge::Bridge::set_fee_recipient(&env, fee_recipient); + } + + /// Set minimum validators (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_min_validators(...); + /// ``` + pub fn set_min_validators(env: Env, min_validators: u32) -> Result<(), BridgeError> { + bridge::Bridge::set_min_validators(&env, min_validators) + } + + // ========== View Functions ========== + + /// Get bridge transaction details by nonce + /// + /// Retrieves the status, amount, and other metadata for a specific bridge + /// transaction identified by its unique nonce. + /// + /// # Arguments + /// + /// * `env` - The Soroban environment. + /// * `nonce` - The unique nonce of the bridge transaction. + /// + /// # Returns + /// + /// * `Option` - Returns the transaction if found, or `None`. + /// + /// # Examples + /// + /// ```rust + /// let tx = TeachLinkBridge::get_bridge_transaction(env, nonce); + /// ``` + pub fn get_bridge_transaction(env: Env, nonce: u64) -> Option { + bridge::Bridge::get_bridge_transaction(&env, nonce) + } + + /// Check if a chain is supported + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_chain_supported(...); + /// ``` + pub fn is_chain_supported(env: Env, chain_id: u32) -> bool { + bridge::Bridge::is_chain_supported(&env, chain_id) + } + + /// Check if an address is a validator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_validator(...); + /// ``` + pub fn is_validator(env: Env, address: Address) -> bool { + bridge::Bridge::is_validator(&env, address) + } + + /// Get the current nonce + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_nonce(...); + /// ``` + pub fn get_nonce(env: Env) -> u64 { + bridge::Bridge::get_nonce(&env) + } + + /// Get the bridge fee + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_fee(...); + /// ``` + pub fn get_bridge_fee(env: Env) -> i128 { + bridge::Bridge::get_bridge_fee(&env) + } + + /// Get the token address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_token(...); + /// ``` + pub fn get_token(env: Env) -> Address { + bridge::Bridge::get_token(&env) + } + + /// Get the admin address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_admin(...); + /// ``` + pub fn get_admin(env: Env) -> Address { + bridge::Bridge::get_admin(&env) + } + + // ========== BFT Consensus Functions ========== + + /// Register a validator with stake for BFT consensus + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_validator(...); + /// ``` + pub fn register_validator( + env: Env, + validator: Address, + stake: i128, + ) -> Result<(), BridgeError> { + bft_consensus::BFTConsensus::register_validator(&env, validator, stake) + } + + /// Unregister a validator and unstake + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // unregister_validator(...); + /// ``` + pub fn unregister_validator(env: Env, validator: Address) -> Result<(), BridgeError> { + bft_consensus::BFTConsensus::unregister_validator(&env, validator) + } + + /// Create a bridge proposal for BFT consensus + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_bridge_proposal(...); + /// ``` + pub fn create_bridge_proposal( + env: Env, + message: CrossChainMessage, + ) -> Result { + bft_consensus::BFTConsensus::create_proposal(&env, message) + } + + /// Vote on a bridge proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // vote_on_proposal(...); + /// ``` + pub fn vote_on_proposal( + env: Env, + validator: Address, + proposal_id: u64, + approve: bool, + ) -> Result<(), BridgeError> { + bft_consensus::BFTConsensus::vote_on_proposal(&env, validator, proposal_id, approve) + } + + /// Get validator information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_validator_info(...); + /// ``` + pub fn get_validator_info(env: Env, validator: Address) -> Option { + bft_consensus::BFTConsensus::get_validator_info(&env, validator) + } + + /// Get consensus state + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_consensus_state(...); + /// ``` + pub fn get_consensus_state(env: Env) -> ConsensusState { + bft_consensus::BFTConsensus::get_consensus_state(&env) + } + + /// Get proposal by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_proposal(...); + /// ``` + pub fn get_proposal(env: Env, proposal_id: u64) -> Option { + bft_consensus::BFTConsensus::get_proposal(&env, proposal_id) + } + + /// Check if consensus is reached for a proposal + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_consensus_reached(...); + /// ``` + pub fn is_consensus_reached(env: Env, proposal_id: u64) -> bool { + bft_consensus::BFTConsensus::is_consensus_reached(&env, proposal_id) + } + + // ========== Slashing and Rewards Functions ========== + + /// Deposit stake for a validator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // deposit_stake(...); + /// ``` + pub fn deposit_stake(env: Env, validator: Address, amount: i128) -> Result<(), BridgeError> { + slashing::SlashingManager::deposit_stake(&env, validator, amount) + } + + /// Withdraw stake + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // withdraw_stake(...); + /// ``` + pub fn withdraw_stake(env: Env, validator: Address, amount: i128) -> Result<(), BridgeError> { + slashing::SlashingManager::withdraw_stake(&env, validator, amount) + } + + /// Slash a validator for malicious behavior + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // slash_validator(...); + /// ``` + pub fn slash_validator( + env: Env, + validator: Address, + reason: types::SlashingReason, + evidence: Bytes, + slasher: Address, + ) -> Result { + slashing::SlashingManager::slash_validator(&env, validator, reason, evidence, slasher) + } + + /// Reward a validator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // reward_validator(...); + /// ``` + pub fn reward_validator( + env: Env, + validator: Address, + amount: i128, + reward_type: types::RewardType, + ) -> Result<(), BridgeError> { + slashing::SlashingManager::reward_validator(&env, validator, amount, reward_type) + } + + /// Fund the reward pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fund_validator_reward_pool(...); + /// ``` + pub fn fund_validator_reward_pool( + env: Env, + funder: Address, + amount: i128, + ) -> Result<(), BridgeError> { + slashing::SlashingManager::fund_reward_pool(&env, funder, amount) + } + + /// Get validator stake + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_validator_stake(...); + /// ``` + pub fn get_validator_stake(env: Env, validator: Address) -> i128 { + slashing::SlashingManager::get_stake(&env, validator) + } + + // ========== Multi-Chain Functions ========== + + /// Add a supported chain with configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_supported_chain_config(...); + /// ``` + pub fn add_supported_chain_config( + env: Env, + chain_id: u32, + name: Symbol, + bridge_address: Address, + min_confirmations: u32, + fee_rate: u32, + ) { + bridge::add_chain_support( + &env, + chain_id, + chain_name, + bridge_contract_address, + confirmation_blocks, + gas_price, + ) + } + + /// Update chain configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_chain_config(...); + /// ``` + pub fn update_chain_config( + env: Env, + chain_id: u32, + is_active: bool, + confirmation_blocks: Option, + gas_price: Option, + ) -> Result<(), BridgeError> { + multichain::MultiChainManager::update_chain( + &env, + chain_id, + is_active, + confirmation_blocks, + gas_price, + ) + } + + /// Register a multi-chain asset + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_multi_chain_asset(...); + /// ``` + pub fn register_multi_chain_asset( + env: Env, + asset_id: Bytes, + stellar_token: Address, + chain_configs: Map, + ) -> Result { + multichain::MultiChainManager::register_asset(&env, asset_id, stellar_token, chain_configs) + } + + /// Get chain configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_chain_config(...); + /// ``` + pub fn get_chain_config(env: Env, chain_id: u32) -> Option { + multichain::MultiChainManager::get_chain_config(&env, chain_id) + } + + /// Check if chain is active + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_chain_active(...); + /// ``` + pub fn is_chain_active(env: Env, chain_id: u32) -> bool { + multichain::MultiChainManager::is_chain_active(&env, chain_id) + } + + /// Get supported chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_supported_chains(...); + /// ``` + pub fn get_supported_chains(env: Env) -> Vec { + multichain::MultiChainManager::get_supported_chains(&env) + } + + // ========== Liquidity and AMM Functions ========== + + /// Initialize liquidity pool for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_liquidity_pool(...); + /// ``` + pub fn initialize_liquidity_pool( + env: Env, + chain_id: u32, + token: Address, + ) -> Result<(), BridgeError> { + liquidity::LiquidityManager::initialize_pool(&env, chain_id, token) + } + + /// Add liquidity to a pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_liquidity(...); + /// ``` + pub fn add_liquidity( + env: Env, + provider: Address, + chain_id: u32, + amount: i128, + ) -> Result { + liquidity::LiquidityManager::add_liquidity(&env, provider, chain_id, amount) + } + + /// Remove liquidity from a pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // remove_liquidity(...); + /// ``` + pub fn remove_liquidity( + env: Env, + provider: Address, + chain_id: u32, + amount: i128, + ) -> Result { + liquidity::LiquidityManager::remove_liquidity(&env, provider, chain_id, amount) + } + + /// Calculate dynamic bridge fee + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // calculate_bridge_fee(...); + /// ``` + pub fn calculate_bridge_fee( + env: Env, + chain_id: u32, + amount: i128, + user_volume_24h: i128, + ) -> Result { + liquidity::LiquidityManager::calculate_bridge_fee(&env, chain_id, amount, user_volume_24h) + } + + /// Update fee structure + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_fee_structure(...); + /// ``` + pub fn update_fee_structure( + env: Env, + base_fee: i128, + dynamic_multiplier: u32, + volume_discount_tiers: Map, + ) -> Result<(), BridgeError> { + liquidity::LiquidityManager::update_fee_structure( + &env, + base_fee, + dynamic_multiplier, + volume_discount_tiers, + ) + } + + /// Get available liquidity for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_available_liquidity(...); + /// ``` + pub fn get_available_liquidity(env: Env, chain_id: u32) -> i128 { + liquidity::LiquidityManager::get_available_liquidity(&env, chain_id) + } + + // ========== Message Passing Functions ========== + + /// Send a cross-chain packet + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_cross_chain_packet(...); + /// ``` + pub fn send_cross_chain_packet( + env: Env, + source_chain: u32, + destination_chain: u32, + sender: Bytes, + recipient: Bytes, + payload: Bytes, + timeout: Option, + ) -> Result { + message_passing::MessagePassing::send_packet( + &env, + source_chain, + destination_chain, + sender, + recipient, + payload, + timeout, + ) + } + + /// Mark a cross-chain packet as delivered + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // deliver_cross_chain_packet(...); + /// ``` + pub fn deliver_cross_chain_packet( + env: Env, + packet_id: u64, + gas_used: u64, + result: Bytes, + ) -> Result<(), BridgeError> { + message_passing::MessagePassing::deliver_packet(&env, packet_id, gas_used, result) + } + + /// Mark a cross-chain packet as failed + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fail_cross_chain_packet(...); + /// ``` + pub fn fail_cross_chain_packet( + env: Env, + packet_id: u64, + reason: Bytes, + ) -> Result<(), BridgeError> { + message_passing::MessagePassing::fail_packet(&env, packet_id, reason) + } + + /// Retry a failed or timed-out cross-chain packet + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // retry_cross_chain_packet(...); + /// ``` + pub fn retry_cross_chain_packet(env: Env, packet_id: u64) -> Result<(), BridgeError> { + message_passing::MessagePassing::retry_packet(&env, packet_id) + } + + /// Mark all expired packets as timed out and return packet IDs + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_cross_chain_timeouts(...); + /// ``` + pub fn check_cross_chain_timeouts(env: Env) -> Result, BridgeError> { + message_passing::MessagePassing::check_timeouts(&env) + } + + /// Get packet by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packet(...); + /// ``` + pub fn get_packet(env: Env, packet_id: u64) -> Option { + message_passing::MessagePassing::get_packet(&env, packet_id) + } + + /// Get packet receipt + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packet_receipt(...); + /// ``` + pub fn get_packet_receipt(env: Env, packet_id: u64) -> Option { + message_passing::MessagePassing::get_receipt(&env, packet_id) + } + + /// Verify packet delivery + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // verify_packet_delivery(...); + /// ``` + pub fn verify_packet_delivery(env: Env, packet_id: u64) -> bool { + message_passing::MessagePassing::verify_delivery(&env, packet_id) + } + + /// Get retry count for a packet + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packet_retry_count(...); + /// ``` + pub fn get_packet_retry_count(env: Env, packet_id: u64) -> u32 { + message_passing::MessagePassing::get_packet_retry_count(&env, packet_id) + } + + // ========== Emergency Functions ========== + + /// Pause the entire bridge + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pause_bridge(...); + /// ``` + pub fn pause_bridge(env: Env, pauser: Address, reason: Bytes) -> Result<(), BridgeError> { + emergency::EmergencyManager::pause_bridge(&env, pauser, reason) + } + + /// Resume the bridge + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // resume_bridge(...); + /// ``` + pub fn resume_bridge(env: Env, resumer: Address) -> Result<(), BridgeError> { + emergency::EmergencyManager::resume_bridge(&env, resumer) + } + + /// Pause specific chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // pause_chains(...); + /// ``` + pub fn pause_chains( + env: Env, + pauser: Address, + chain_ids: Vec, + reason: Bytes, + ) -> Result<(), BridgeError> { + emergency::EmergencyManager::pause_chains(&env, pauser, chain_ids, reason) + } + + /// Resume specific chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // resume_chains(...); + /// ``` + pub fn resume_chains( + env: Env, + resumer: Address, + chain_ids: Vec, + ) -> Result<(), BridgeError> { + emergency::EmergencyManager::resume_chains(&env, resumer, chain_ids) + } + + /// Initialize circuit breaker for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_circuit_breaker(...); + /// ``` + pub fn initialize_circuit_breaker( + env: Env, + chain_id: u32, + max_daily_volume: i128, + max_transaction_amount: i128, + ) -> Result<(), BridgeError> { + emergency::EmergencyManager::initialize_circuit_breaker( + &env, + chain_id, + max_daily_volume, + max_transaction_amount, + ) + } + + /// Check if bridge is paused + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_bridge_paused(...); + /// ``` + pub fn is_bridge_paused(env: Env) -> bool { + emergency::EmergencyManager::is_bridge_paused(&env) + } + + /// Check if a chain is paused + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_chain_paused(...); + /// ``` + pub fn is_chain_paused(env: Env, chain_id: u32) -> bool { + emergency::EmergencyManager::is_chain_paused(&env, chain_id) + } + + /// Get emergency state + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_emergency_state(...); + /// ``` + pub fn get_emergency_state(env: Env) -> EmergencyState { + emergency::EmergencyManager::get_emergency_state(&env) + } + + // ========== Audit and Compliance Functions ========== + + /// Create an audit record + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_audit_record(...); + /// ``` + pub fn create_audit_record( + env: Env, + operation_type: types::OperationType, + operator: Address, + details: Bytes, + tx_hash: Bytes, + ) -> Result { + audit::AuditManager::create_audit_record(&env, operation_type, operator, details, tx_hash) + } + + /// Get audit record by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_audit_record(...); + /// ``` + pub fn get_audit_record(env: Env, record_id: u64) -> Option { + audit::AuditManager::get_audit_record(&env, record_id) + } + + /// Generate compliance report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_compliance_report(...); + /// ``` + pub fn generate_compliance_report( + env: Env, + period_start: u64, + period_end: u64, + ) -> Result { + audit::AuditManager::generate_compliance_report(&env, period_start, period_end) + } + + /// Get compliance report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_compliance_report(...); + /// ``` + pub fn get_compliance_report(env: Env, report_id: u64) -> Option { + audit::AuditManager::get_compliance_report(&env, report_id) + } + + // ========== Atomic Swap Functions ========== + + /// Initiate an atomic swap + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initiate_atomic_swap(...); + /// ``` + pub fn initiate_atomic_swap( + env: Env, + initiator: Address, + initiator_token: Address, + initiator_amount: i128, + counterparty: Address, + counterparty_token: Address, + counterparty_amount: i128, + hashlock: Bytes, + timelock: u64, + ) -> Result { + atomic_swap::AtomicSwapManager::initiate_swap( + &env, + initiator, + initiator_token, + initiator_amount, + counterparty, + counterparty_token, + counterparty_amount, + hashlock, + timelock, + ) + } + + /// Accept and complete an atomic swap + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // accept_atomic_swap(...); + /// ``` + pub fn accept_atomic_swap( + env: Env, + swap_id: u64, + counterparty: Address, + preimage: Bytes, + ) -> Result<(), BridgeError> { + atomic_swap::AtomicSwapManager::accept_swap(&env, swap_id, counterparty, preimage) + } + + /// Refund an expired atomic swap + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // refund_atomic_swap(...); + /// ``` + pub fn refund_atomic_swap( + env: Env, + swap_id: u64, + initiator: Address, + ) -> Result<(), BridgeError> { + atomic_swap::AtomicSwapManager::refund_swap(&env, swap_id, initiator) + } + + /// Get atomic swap by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_atomic_swap(...); + /// ``` + pub fn get_atomic_swap(env: Env, swap_id: u64) -> Option { + atomic_swap::AtomicSwapManager::get_swap(&env, swap_id) + } + + /// Get active atomic swaps + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_active_atomic_swaps(...); + /// ``` + pub fn get_active_atomic_swaps(env: Env) -> Vec { + atomic_swap::AtomicSwapManager::get_active_swaps(&env) + } + + // ========== Analytics Functions ========== + + /// Initialize bridge metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_bridge_metrics(...); + /// ``` + pub fn initialize_bridge_metrics(env: Env) -> Result<(), BridgeError> { + analytics::AnalyticsManager::initialize_metrics(&env) + } + + /// Get bridge metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_metrics(...); + /// ``` + pub fn get_bridge_metrics(env: Env) -> BridgeMetrics { + analytics::AnalyticsManager::get_bridge_metrics(&env) + } + + /// Get chain metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_chain_metrics(...); + /// ``` + pub fn get_chain_metrics(env: Env, chain_id: u32) -> Option { + analytics::AnalyticsManager::get_chain_metrics(&env, chain_id) + } + + /// Calculate bridge health score + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // calculate_bridge_health_score(...); + /// ``` + pub fn calculate_bridge_health_score(env: Env) -> u32 { + analytics::AnalyticsManager::calculate_health_score(&env) + } + + /// Get bridge statistics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_bridge_statistics(...); + /// ``` + pub fn get_bridge_statistics(env: Env) -> Map { + analytics::AnalyticsManager::get_bridge_statistics(&env) + } + + /// Get cached or computed bridge summary (health score + top chains). Uses cache if fresh. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_cached_bridge_summary(...); + /// ``` + pub fn get_cached_bridge_summary(env: Env) -> Result { + performance::PerformanceManager::get_or_compute_summary(&env) + } + + /// Force recompute and cache bridge summary. Emits PerfMetricsComputedEvent. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // compute_and_cache_bridge_summary(...); + /// ``` + pub fn compute_and_cache_bridge_summary(env: Env) -> Result { + performance::PerformanceManager::compute_and_cache_summary(&env) + } + + /// Invalidate performance cache (admin only). Emits PerfCacheInvalidatedEvent. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // invalidate_performance_cache(...); + /// ``` + pub fn invalidate_performance_cache(env: Env, admin: Address) -> Result<(), BridgeError> { + performance::PerformanceManager::invalidate_cache(&env, &admin) + } + + // ========== Advanced Analytics & Reporting Functions ========== + + /// Get dashboard-ready aggregate analytics for visualizations + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_dashboard_analytics(...); + /// ``` + pub fn get_dashboard_analytics(env: Env) -> DashboardAnalytics { + reporting::ReportingManager::get_dashboard_analytics(&env) + } + + /// Create a report template + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_report_template(...); + /// ``` + pub fn create_report_template( + env: Env, + creator: Address, + name: Bytes, + report_type: ReportType, + config: Bytes, + ) -> Result { + reporting::ReportingManager::create_report_template( + &env, + creator, + name, + bridge_address, + min_confirmations, + fee_rate, + ); + report_type, + config, + ) + } + + /// Get report template by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_template(...); + /// ``` + pub fn get_report_template(env: Env, template_id: u64) -> Option { + reporting::ReportingManager::get_report_template(&env, template_id) + } + + /// Schedule a report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // schedule_report(...); + /// ``` + pub fn schedule_report( + env: Env, + owner: Address, + template_id: u64, + next_run_at: u64, + interval_seconds: u64, + ) -> Result { + reporting::ReportingManager::schedule_report( + &env, + owner, + template_id, + next_run_at, + interval_seconds, + ) + } + + /// Get scheduled reports for an owner + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_scheduled_reports(...); + /// ``` + pub fn get_scheduled_reports(env: Env, owner: Address) -> Vec { + reporting::ReportingManager::get_scheduled_reports(&env, owner) + } + + /// Generate a report snapshot + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_report_snapshot(...); + /// ``` + pub fn generate_report_snapshot( + env: Env, + generator: Address, + template_id: u64, + period_start: u64, + period_end: u64, + ) -> Result { + reporting::ReportingManager::generate_report_snapshot( + &env, + generator, + template_id, + period_start, + period_end, + ) + } + + /// Get report snapshot by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_snapshot(...); + /// ``` + pub fn get_report_snapshot(env: Env, report_id: u64) -> Option { + reporting::ReportingManager::get_report_snapshot(&env, report_id) + } + + /// Record report view for usage analytics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_report_view(...); + /// ``` + pub fn record_report_view( + env: Env, + report_id: u64, + viewer: Address, + ) -> Result<(), BridgeError> { + reporting::ReportingManager::record_report_view(&env, report_id, viewer) + } + + /// Get report usage count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_usage_count(...); + /// ``` + pub fn get_report_usage_count(env: Env, report_id: u64) -> u32 { + reporting::ReportingManager::get_report_usage_count(&env, report_id) + } + + /// Add comment to a report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_report_comment(...); + /// ``` + pub fn add_report_comment( + env: Env, + report_id: u64, + author: Address, + body: Bytes, + ) -> Result { + reporting::ReportingManager::add_report_comment(&env, report_id, author, body) + } + + /// Get comments for a report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_comments(...); + /// ``` + pub fn get_report_comments(env: Env, report_id: u64) -> Vec { + reporting::ReportingManager::get_report_comments(&env, report_id) + } + + /// Create an alert rule + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_alert_rule(...); + /// ``` + pub fn create_alert_rule( + env: Env, + owner: Address, + name: Bytes, + condition_type: AlertConditionType, + threshold: i128, + ) -> Result { + reporting::ReportingManager::create_alert_rule(&env, owner, name, condition_type, threshold) + } + + /// Get alert rules for an owner + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_alert_rules(...); + /// ``` + pub fn get_alert_rules(env: Env, owner: Address) -> Vec { + reporting::ReportingManager::get_alert_rules(&env, owner) + } + + /// Evaluate alert rules (returns triggered rule ids) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // evaluate_alerts(...); + /// ``` + pub fn evaluate_alerts(env: Env) -> Vec { + reporting::ReportingManager::evaluate_alerts(&env) + } + + /// Get recent report snapshots + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recent_report_snapshots(...); + /// ``` + pub fn get_recent_report_snapshots(env: Env, limit: u32) -> Vec { + reporting::ReportingManager::get_recent_report_snapshots(&env, limit) + } + + // ========== Backup and Disaster Recovery Functions ========== + + /// Create a backup manifest (integrity hash from off-chain) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_backup(...); + /// ``` + pub fn create_backup( + env: Env, + creator: Address, + integrity_hash: Bytes, + rto_tier: RtoTier, + encryption_ref: u64, + ) -> Result { + backup::BackupManager::create_backup( + &env, + creator, + integrity_hash, + rto_tier, + encryption_ref, + ) + } + + /// Get backup manifest by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_backup_manifest(...); + /// ``` + pub fn get_backup_manifest(env: Env, backup_id: u64) -> Option { + backup::BackupManager::get_backup_manifest(&env, backup_id) + } + + /// Verify backup integrity + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // verify_backup(...); + /// ``` + pub fn verify_backup( + env: Env, + backup_id: u64, + verifier: Address, + expected_hash: Bytes, + ) -> Result { + backup::BackupManager::verify_backup(&env, backup_id, verifier, expected_hash) + } + + /// Schedule automated backup + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // schedule_backup(...); + /// ``` + pub fn schedule_backup( + env: Env, + owner: Address, + next_run_at: u64, + interval_seconds: u64, + rto_tier: RtoTier, + ) -> Result { + backup::BackupManager::schedule_backup(&env, owner, next_run_at, interval_seconds, rto_tier) + } + + /// Get scheduled backups for an owner + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_scheduled_backups(...); + /// ``` + pub fn get_scheduled_backups(env: Env, owner: Address) -> Vec { + backup::BackupManager::get_scheduled_backups(&env, owner) + } + + /// Record a recovery execution (RTO tracking and audit) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_recovery(...); + /// ``` + pub fn record_recovery( + env: Env, + backup_id: u64, + executed_by: Address, + recovery_duration_secs: u64, + success: bool, + ) -> Result { + backup::BackupManager::record_recovery( + &env, + backup_id, + executed_by, + recovery_duration_secs, + success, + ) + } + + /// Get recovery records for audit and RTO reporting + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recovery_records(...); + /// ``` + pub fn get_recovery_records(env: Env, limit: u32) -> Vec { + backup::BackupManager::get_recovery_records(&env, limit) + } + + /// Get recent backup manifests + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recent_backups(...); + /// ``` + pub fn get_recent_backups(env: Env, limit: u32) -> Vec { + backup::BackupManager::get_recent_backups(&env, limit) + } + + // ========== Rewards Functions ========== + + /// Initialize the rewards system + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_rewards(...); + /// ``` + pub fn initialize_rewards( + env: Env, + token: Address, + rewards_admin: Address, + ) -> Result<(), RewardsError> { + rewards::Rewards::initialize_rewards(&env, token, rewards_admin) + } + + /// Fund the reward pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fund_reward_pool(...); + /// ``` + pub fn fund_reward_pool(env: Env, funder: Address, amount: i128) -> Result<(), RewardsError> { + rewards::Rewards::fund_reward_pool(&env, funder, amount) + } + + /// Issue rewards to a user + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // issue_reward(...); + /// ``` + pub fn issue_reward( + env: Env, + recipient: Address, + amount: i128, + reward_type: String, + ) -> Result<(), RewardsError> { + rewards::Rewards::issue_reward(&env, recipient, amount, reward_type) + } + + /// Claim pending rewards + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // claim_rewards(...); + /// ``` + pub fn claim_rewards(env: Env, user: Address) -> Result<(), RewardsError> { + rewards::Rewards::claim_rewards(&env, user) + } + + /// Set reward rate for a specific reward type (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_reward_rate(...); + /// ``` + pub fn set_reward_rate( + env: Env, + reward_type: String, + rate: i128, + enabled: bool, + ) -> Result<(), RewardsError> { + rewards::Rewards::set_reward_rate(&env, reward_type, rate, enabled) + } + + /// Update rewards admin (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_rewards_admin(...); + /// ``` + pub fn update_rewards_admin(env: Env, new_admin: Address) { + rewards::Rewards::update_rewards_admin(&env, new_admin); + } + + /// Submit an oracle price update (authorized oracles only). + pub fn update_oracle_price( + /// Get user reward information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_rewards(...); + /// ``` + pub fn get_user_rewards(env: Env, user: Address) -> Option { + rewards::Rewards::get_user_rewards(&env, user) + } + + /// Get reward pool balance + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_reward_pool_balance(...); + /// ``` + pub fn get_reward_pool_balance(env: Env) -> i128 { + rewards::Rewards::get_reward_pool_balance(&env) + } + + /// Get total rewards issued + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_total_rewards_issued(...); + /// ``` + pub fn get_total_rewards_issued(env: Env) -> i128 { + rewards::Rewards::get_total_rewards_issued(&env) + } + + /// Get reward rate for a specific type + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_reward_rate(...); + /// ``` + pub fn get_reward_rate(env: Env, reward_type: String) -> Option { + rewards::Rewards::get_reward_rate(&env, reward_type) + } + + /// Get rewards admin address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_rewards_admin(...); + /// ``` + pub fn get_rewards_admin(env: Env) -> Address { + rewards::Rewards::get_rewards_admin(&env) + } + + // ========== Assessment and Testing Platform Functions ========== + + /// Create a new assessment + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_assessment(...); + /// ``` + pub fn create_assessment( + env: Env, + creator: Address, + title: Bytes, + description: Bytes, + questions: Vec, + settings: AssessmentSettings, + ) -> Result { + assessment::AssessmentManager::create_assessment( + &env, + creator, + title, + description, + questions, + settings, + ) } - /// Register a new supported chain (admin only). - pub fn add_chain_support( + /// Add a question to the pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_assessment_question(...); + /// ``` + pub fn add_assessment_question( env: Env, - chain_id: u32, - name: Symbol, - bridge_address: Address, - min_confirmations: u32, - fee_rate: u32, + creator: Address, + q_type: QuestionType, + content_hash: Bytes, + points: u32, + difficulty: u32, + correct_answer_hash: Bytes, + metadata: Map, + ) -> Result { + assessment::AssessmentManager::add_question( + &env, + creator, + q_type, + content_hash, + points, + difficulty, + correct_answer_hash, + metadata, + ) + } + + /// Submit an assessment + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // submit_assessment(...); + /// ``` + pub fn submit_assessment( + env: Env, + student: Address, + assessment_id: u64, + answers: Map, + proctor_logs: Vec, + ) -> Result { + assessment::AssessmentManager::submit_assessment( + &env, + student, + assessment_id, + answers, + proctor_logs, + ) + } + + /// Get assessment details + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_assessment(...); + /// ``` + pub fn get_assessment(env: Env, id: u64) -> Option { + assessment::AssessmentManager::get_assessment(&env, id) + } + + /// Get user submission + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_assessment_submission(...); + /// ``` + pub fn get_assessment_submission( + env: Env, + student: Address, + assessment_id: u64, + ) -> Option { + assessment::AssessmentManager::get_submission(&env, student, assessment_id) + } + + /// Report a proctoring violation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // report_proctor_violation(...); + /// ``` + pub fn report_proctor_violation( + env: Env, + student: Address, + assessment_id: u64, + violation_type: Bytes, + ) -> Result<(), assessment::AssessmentError> { + assessment::AssessmentManager::report_proctoring_violation( + &env, + student, + assessment_id, + violation_type, + ) + } + + /// Get next adaptive question + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_next_adaptive_question(...); + /// ``` + pub fn get_next_adaptive_question( + env: Env, + id: u64, + scores: Vec, + answered_ids: Vec, + ) -> Result { + assessment::AssessmentManager::get_next_adaptive_question(&env, id, scores, answered_ids) + } + + // ========== Escrow Functions ========== + + /// Create a multi-signature escrow + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_escrow(...); + /// ``` + pub fn create_escrow(env: Env, params: EscrowParameters) -> Result { + escrow::EscrowManager::create_escrow( + &env, + params.depositor, + params.beneficiary, + params.token, + params.amount, + params.signers, + params.threshold, + params.release_time, + params.refund_time, + params.arbitrator, + ) + } + + /// Approve escrow release (multi-signature) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // approve_escrow_release(...); + /// ``` + pub fn approve_escrow_release( + env: Env, + escrow_id: u64, + signer: Address, + ) -> Result { + escrow::EscrowManager::approve_release(&env, escrow_id, signer) + } + + /// Release funds to the beneficiary once conditions are met + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // release_escrow(...); + /// ``` + pub fn release_escrow(env: Env, escrow_id: u64, caller: Address) -> Result<(), EscrowError> { + escrow::EscrowManager::release(&env, escrow_id, caller) + } + + /// Refund escrow to the depositor after refund time + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // refund_escrow(...); + /// ``` + pub fn refund_escrow(env: Env, escrow_id: u64, depositor: Address) -> Result<(), EscrowError> { + escrow::EscrowManager::refund(&env, escrow_id, depositor) + } + + /// Cancel escrow before any approvals + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // cancel_escrow(...); + /// ``` + pub fn cancel_escrow(env: Env, escrow_id: u64, depositor: Address) -> Result<(), EscrowError> { + escrow::EscrowManager::cancel(&env, escrow_id, depositor) + } + + /// Raise a dispute on the escrow + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // dispute_escrow(...); + /// ``` + pub fn dispute_escrow( + env: Env, + escrow_id: u64, + disputer: Address, + reason: Bytes, + ) -> Result<(), EscrowError> { + escrow::EscrowManager::dispute(&env, escrow_id, disputer, reason) + } + + /// Automatically check if an escrow has stalled and trigger a dispute + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // auto_check_escrow_dispute(...); + /// ``` + pub fn auto_check_escrow_dispute(env: Env, escrow_id: u64) -> Result<(), EscrowError> { + escrow::EscrowManager::auto_check_dispute(&env, escrow_id) + } + + /// Resolve a dispute as the arbitrator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // resolve_escrow(...); + /// ``` + pub fn resolve_escrow( + env: Env, + escrow_id: u64, + arbitrator: Address, + outcome: DisputeOutcome, + ) -> Result<(), EscrowError> { + escrow::EscrowManager::resolve(&env, escrow_id, arbitrator, outcome) + } + + // ========== Arbitration Management Functions ========== + + /// Register a new professional arbitrator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_arbitrator(...); + /// ``` + pub fn register_arbitrator(env: Env, profile: ArbitratorProfile) -> Result<(), EscrowError> { + arbitration::ArbitrationManager::register_arbitrator(&env, profile) + } + + /// Update arbitrator profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_arbitrator_profile(...); + /// ``` + pub fn update_arbitrator_profile( + env: Env, + address: Address, + profile: ArbitratorProfile, + ) -> Result<(), EscrowError> { + arbitration::ArbitrationManager::update_profile(&env, address, profile) + } + + /// Get arbitrator profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_arbitrator_profile(...); + /// ``` + pub fn get_arbitrator_profile(env: Env, address: Address) -> Option { + arbitration::ArbitrationManager::get_arbitrator(&env, address) + } + + // ========== Insurance Pool Functions ========== + + /// Initialize insurance pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_insurance_pool(...); + /// ``` + pub fn initialize_insurance_pool( + env: Env, + token: Address, + premium_rate: u32, + ) -> Result<(), EscrowError> { + insurance::InsuranceManager::initialize_pool(&env, token, premium_rate) + } + + /// Fund insurance pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fund_insurance_pool(...); + /// ``` + pub fn fund_insurance_pool(env: Env, funder: Address, amount: i128) -> Result<(), EscrowError> { + insurance::InsuranceManager::fund_pool(&env, funder, amount) + } + + // ========== Escrow Analytics Functions ========== + + /// Get aggregate escrow metrics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_escrow_metrics(...); + /// ``` + pub fn get_escrow_metrics(env: Env) -> EscrowMetrics { + escrow_analytics::EscrowAnalyticsManager::get_metrics(&env) + } + + /// Get escrow by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_escrow(...); + /// ``` + pub fn get_escrow(env: Env, escrow_id: u64) -> Option { + escrow::EscrowManager::get_escrow(&env, escrow_id) + } + + /// Check if a signer approved + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // has_escrow_approval(...); + /// ``` + pub fn has_escrow_approval(env: Env, escrow_id: u64, signer: Address) -> bool { + escrow::EscrowManager::has_approved(&env, escrow_id, signer) + } + + /// Get the current escrow count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_escrow_count(...); + /// ``` + pub fn get_escrow_count(env: Env) -> u64 { + escrow::EscrowManager::get_escrow_count(&env) + } + + // ========== Credit Scoring Functions (feat/credit_score) ========== + + /// Record course completion + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_course_completion(...); + /// ``` + pub fn record_course_completion(env: Env, user: Address, course_id: u64, points: u64) { + let admin = bridge::Bridge::get_admin(&env); + admin.require_auth(); + score::ScoreManager::record_course_completion(&env, user, course_id, points); + } + + /// Record contribution + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_contribution(...); + /// ``` + pub fn record_contribution( + env: Env, + user: Address, + c_type: types::ContributionType, + description: Bytes, + points: u64, ) { - bridge::add_chain_support( + score::ScoreManager::record_contribution(&env, user, c_type, description, points); + } + + /// Get user's credit score + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_credit_score(...); + /// ``` + pub fn get_credit_score(env: Env, user: Address) -> u64 { + score::ScoreManager::get_score(&env, user) + } + + /// Get user's courses + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_courses(...); + /// ``` + pub fn get_user_courses(env: Env, user: Address) -> Vec { + score::ScoreManager::get_courses(&env, user) + } + + /// Get user's contributions + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_contributions(...); + /// ``` + pub fn get_user_contributions(env: Env, user: Address) -> Vec { + score::ScoreManager::get_contributions(&env, user) + } + + // ========== Reputation Functions (main) ========== + + /// Standard API for update_participation + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_participation(...); + /// ``` + pub fn update_participation(env: Env, user: Address, points: u32) { + reputation::update_participation(&env, user, points); + } + + /// Standard API for update_course_progress + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_course_progress(...); + /// ``` + pub fn update_course_progress(env: Env, user: Address, is_completion: bool) { + reputation::update_course_progress(&env, user, is_completion); + } + + /// Standard API for rate_contribution + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // rate_contribution(...); + /// ``` + pub fn rate_contribution(env: Env, user: Address, rating: u32) { + reputation::rate_contribution(&env, user, rating); + } + + /// Standard API for get_user_reputation + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_reputation(...); + /// ``` + pub fn get_user_reputation(env: Env, user: Address) -> types::UserReputation { + reputation::get_reputation(&env, &user) + } + + // ========== Content Tokenization Functions ========== + + /// Mint a new educational content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // mint_content_token(...); + /// ``` + pub fn mint_content_token(env: Env, params: ContentTokenParameters) -> u64 { + let token_id = tokenization::ContentTokenization::mint( &env, - chain_id, - name, - bridge_address, - min_confirmations, - fee_rate, + params.creator.clone(), + params.title, + params.description, + params.content_type, + params.content_hash, + params.license_type, + params.tags, + params.is_transferable, + params.royalty_percentage, ); + provenance::ProvenanceTracker::record_mint(&env, token_id, params.creator, None); + token_id } - /// Submit an oracle price update (authorized oracles only). - pub fn update_oracle_price( + /// Transfer ownership of a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // transfer_content_token(...); + /// ``` + pub fn transfer_content_token( env: Env, asset: Symbol, price: i128, @@ -86,6 +3184,156 @@ impl TeachLinkBridge { oracle_signer: Address, ) { oracle::update_oracle_price(&env, asset, price, confidence, oracle_signer); + from: Address, + to: Address, + token_id: u64, + notes: Option, + ) { + tokenization::ContentTokenization::transfer(&env, from, to, token_id, notes); + } + + /// Get a content token by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_token(...); + /// ``` + pub fn get_content_token(env: Env, token_id: u64) -> Option { + tokenization::ContentTokenization::get_token(&env, token_id) + } + + /// Get the owner of a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_token_owner(...); + /// ``` + pub fn get_content_token_owner(env: Env, token_id: u64) -> Option
{ + tokenization::ContentTokenization::get_owner(&env, token_id) + } + + /// Check if an address owns a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_content_token_owner(...); + /// ``` + pub fn is_content_token_owner(env: Env, token_id: u64, address: Address) -> bool { + tokenization::ContentTokenization::is_owner(&env, token_id, address) + } + + /// Get all tokens owned by an address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_owner_content_tokens(...); + /// ``` + pub fn get_owner_content_tokens(env: Env, owner: Address) -> Vec { + tokenization::ContentTokenization::get_owner_tokens(&env, owner) + } + + /// Get the total number of content tokens minted + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_token_count(...); + /// ``` + pub fn get_content_token_count(env: Env) -> u64 { + tokenization::ContentTokenization::get_token_count(&env) + } + + /// Update content token metadata (only by owner) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_content_metadata(...); + /// ``` + pub fn update_content_metadata( + env: Env, + owner: Address, + token_id: u64, + title: Option, + description: Option, + tags: Option>, + ) { + tokenization::ContentTokenization::update_metadata( + &env, + owner, + token_id, + title, + description, + tags, + ); + } + + /// Set transferability of a content token (only by owner) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_content_token_transferable(...); + /// ``` + pub fn set_content_token_transferable( + env: Env, + owner: Address, + token_id: u64, + transferable: bool, + ) { + tokenization::ContentTokenization::set_transferable(&env, owner, token_id, transferable); } /// Update bridge configuration (admin only). @@ -93,6 +3341,221 @@ impl TeachLinkBridge { require_admin(&env); validate_fee_rate(&env, &config.fee_rate); env.storage().instance().set(&CONFIG, &config); + // ========== Provenance Functions ========== + + /// Get full provenance history for a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_provenance(...); + /// ``` + pub fn get_content_provenance(env: Env, token_id: u64) -> Vec { + provenance::ProvenanceTracker::get_provenance(&env, token_id) + } + + /// Get the number of transfers for a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_transfer_count(...); + /// ``` + #[must_use] + pub fn get_content_transfer_count(env: &Env, token_id: u64) -> u32 { + provenance::ProvenanceTracker::get_transfer_count(env, token_id) + } + + /// Verify ownership chain integrity for a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // verify_content_chain(...); + /// ``` + #[must_use] + pub fn verify_content_chain(env: &Env, token_id: u64) -> bool { + provenance::ProvenanceTracker::verify_chain(env, token_id) + } + + /// Get the creator of a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_creator(...); + /// ``` + #[must_use] + pub fn get_content_creator(env: &Env, token_id: u64) -> Option
{ + tokenization::ContentTokenization::get_creator(env, token_id) + } + + /// Get all owners of a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_content_all_owners(...); + /// ``` + #[must_use] + pub fn get_content_all_owners(env: &Env, token_id: u64) -> Vec
{ + tokenization::ContentTokenization::get_all_owners(env, token_id) + } + + // ========== Notification System Functions ========== + + /// Initialize notification system + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_notifications(...); + /// ``` + pub fn initialize_notifications(env: Env) -> Result<(), BridgeError> { + notification::NotificationManager::initialize(&env) + } + + /// Send immediate notification + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_notification(...); + /// ``` + pub fn send_notification( + env: Env, + recipient: Address, + channel: NotificationChannel, + subject: Bytes, + body: Bytes, + ) -> Result { + let content = NotificationContent { + subject, + body, + data: Bytes::new(&env), + localization: Map::new(&env), + }; + notification::NotificationManager::send_notification(&env, recipient, channel, content) + } + + // ========== Mobile UI/UX Functions ========== + + /// Initialize mobile profile for user + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_mobile_profile(...); + /// ``` + pub fn initialize_mobile_profile( + env: Env, + user: Address, + device_info: DeviceInfo, + preferences: MobilePreferences, + ) -> Result<(), MobilePlatformError> { + mobile_platform::MobilePlatformManager::initialize_mobile_profile( + &env, + user, + device_info, + preferences, + ) + .map_err(|_| MobilePlatformError::DeviceNotSupported) + } + + /// Update accessibility settings + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_accessibility_settings(...); + /// ``` + pub fn update_accessibility_settings( + env: Env, + user: Address, + settings: MobileAccessibilitySettings, + ) -> Result<(), MobilePlatformError> { + mobile_platform::MobilePlatformManager::update_accessibility_settings(&env, user, settings) + .map_err(|_| MobilePlatformError::DeviceNotSupported) + } + + /// Update personalization settings + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_personalization(...); + /// ``` + pub fn update_personalization( + env: Env, + user: Address, + preferences: MobilePreferences, + ) -> Result<(), MobilePlatformError> { + mobile_platform::MobilePlatformManager::update_personalization(&env, user, preferences) + .map_err(|_| MobilePlatformError::DeviceNotSupported) } /// Enable or disable the fallback mechanism (admin only). @@ -111,11 +3574,287 @@ impl TeachLinkBridge { .get(&BRIDGE_TXS) .unwrap_or_else(|| Vec::new(&env)); txs.get(index) + /// Record onboarding progress + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_onboarding_progress(...); + /// ``` + pub fn record_onboarding_progress( + env: Env, + user: Address, + stage: OnboardingStage, + ) -> Result<(), MobilePlatformError> { + mobile_platform::MobilePlatformManager::record_onboarding_progress(&env, user, stage) + .map_err(|_| MobilePlatformError::DeviceNotSupported) + } + + /// Submit user feedback + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // submit_user_feedback(...); + /// ``` + pub fn submit_user_feedback( + env: Env, + user: Address, + rating: u32, + comment: Bytes, + category: FeedbackCategory, + ) -> Result { + mobile_platform::MobilePlatformManager::submit_user_feedback( + &env, user, rating, comment, category, + ) + .map_err(|_| MobilePlatformError::DeviceNotSupported) + } + + /// Get user allocated experiment variants + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_experiment_variants(...); + /// ``` + pub fn get_user_experiment_variants(env: Env, user: Address) -> Map { + mobile_platform::MobilePlatformManager::get_user_experiment_variants(&env, user) + } + + /// Get design system configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_design_system_config(...); + /// ``` + pub fn get_design_system_config(env: Env) -> ComponentConfig { + mobile_platform::MobilePlatformManager::get_design_system_config(&env) + } + + /// Set design system configuration (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_design_system_config(...); + /// ``` + pub fn set_design_system_config(env: Env, config: ComponentConfig) { + // In a real implementation, we would check for admin authorization here + mobile_platform::MobilePlatformManager::set_design_system_config(&env, config) + } + + /// Schedule notification for future delivery + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // schedule_notification(...); + /// ``` + pub fn schedule_notification( + env: Env, + recipient: Address, + channel: NotificationChannel, + subject: Bytes, + body: Bytes, + scheduled_time: u64, + timezone: Bytes, + ) -> Result { + let content = NotificationContent { + subject, + body, + data: Bytes::new(&env), + localization: Map::new(&env), + }; + let schedule = NotificationSchedule { + notification_id: 0, // Will be set by the function + recipient: recipient.clone(), + channel, + scheduled_time, + timezone, + is_recurring: false, + recurrence_pattern: 0, + max_deliveries: None, + delivery_count: 0, + }; + notification::NotificationManager::schedule_notification( + &env, recipient, channel, content, schedule, + ) + } + + /// Process scheduled notifications + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // process_scheduled_notifications(...); + /// ``` + pub fn process_scheduled_notifications(env: Env) -> Result { + notification::NotificationManager::process_scheduled_notifications(&env) + } + + /// Update user notification preferences + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_notification_preferences(...); + /// ``` + pub fn update_notification_preferences( + env: Env, + user: Address, + preferences: Vec, + ) -> Result<(), BridgeError> { + notification::NotificationManager::update_preferences(&env, user, preferences) + } + + /// Update user notification settings + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_notification_settings(...); + /// ``` + pub fn update_notification_settings( + env: Env, + user: Address, + timezone: Bytes, + quiet_hours_start: u32, + quiet_hours_end: u32, + max_daily_notifications: u32, + do_not_disturb: bool, + ) -> Result<(), BridgeError> { + let settings = UserNotificationSettings { + user: user.clone(), + timezone, + quiet_hours_start, + quiet_hours_end, + max_daily_notifications, + do_not_disturb, + }; + notification::NotificationManager::update_user_settings(&env, user, settings) + } + + /// Create notification template + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_notification_template(...); + /// ``` + pub fn create_notification_template( + env: Env, + admin: Address, + name: Bytes, + channels: Vec, + subject: Bytes, + body: Bytes, + ) -> Result { + let content = NotificationContent { + subject, + body, + data: Bytes::new(&env), + localization: Map::new(&env), + }; + notification::NotificationManager::create_template(&env, admin, name, channels, content) } /// Get the current bridge configuration. pub fn get_config(env: Env) -> BridgeConfig { storage::get_config(&env) + /// Send notification using template + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_template_notification(...); + /// ``` + pub fn send_template_notification( + env: Env, + recipient: Address, + template_id: u64, + variables: Map, + ) -> Result { + notification::NotificationManager::send_template_notification( + &env, + recipient, + template_id, + variables, + ) + } + + /// Get notification tracking information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_notification_tracking(...); + /// ``` + pub fn get_notification_tracking( + env: Env, + notification_id: u64, + ) -> Option { + notification::NotificationManager::get_notification_tracking(&env, notification_id) } /// Check whether the fallback mechanism is enabled. @@ -124,6 +3863,139 @@ impl TeachLinkBridge { .instance() .get(&FALLBACK_ENABLED) .unwrap_or(true) + /// Get user notification history + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_notifications(...); + /// ``` + pub fn get_user_notifications( + env: Env, + user: Address, + limit: u32, + ) -> Vec { + notification::NotificationManager::get_user_notifications(&env, user, limit) + } + + // ========== Social Learning Functions ========== + + /// Create a study group + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_study_group(...); + /// ``` + pub fn create_study_group( + env: Env, + creator: Address, + name: Bytes, + description: Bytes, + subject: Bytes, + max_members: u32, + is_private: bool, + tags: Vec, + settings: social_learning::StudyGroupSettings, + ) -> Result { + social_learning::SocialLearningManager::create_study_group( + &env, + creator, + name, + description, + subject, + max_members, + is_private, + tags, + settings, + ) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Join a study group + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // join_study_group(...); + /// ``` + pub fn join_study_group(env: Env, user: Address, group_id: u64) -> Result<(), BridgeError> { + social_learning::SocialLearningManager::join_study_group(&env, user, group_id) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Leave a study group + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // leave_study_group(...); + /// ``` + pub fn leave_study_group(env: Env, user: Address, group_id: u64) -> Result<(), BridgeError> { + social_learning::SocialLearningManager::leave_study_group(&env, user, group_id) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get study group information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_study_group(...); + /// ``` + pub fn get_study_group( + env: Env, + group_id: u64, + ) -> Result { + social_learning::SocialLearningManager::get_study_group(&env, group_id) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get user's study groups + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_study_groups(...); + /// ``` + pub fn get_user_study_groups(env: Env, user: Address) -> Vec { + social_learning::SocialLearningManager::get_user_study_groups(&env, user) } /// Get the total error count. @@ -132,6 +4004,102 @@ impl TeachLinkBridge { .instance() .get(&storage::ERROR_COUNT) .unwrap_or(0) + /// Create a discussion forum + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_forum(...); + /// ``` + pub fn create_forum( + env: Env, + creator: Address, + title: Bytes, + description: Bytes, + category: Bytes, + tags: Vec, + ) -> Result { + social_learning::SocialLearningManager::create_forum( + &env, + creator, + title, + description, + category, + tags, + ) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Create a forum post + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_forum_post(...); + /// ``` + pub fn create_forum_post( + env: Env, + forum_id: u64, + author: Address, + title: Bytes, + content: Bytes, + attachments: Vec, + ) -> Result { + social_learning::SocialLearningManager::create_forum_post( + &env, + forum_id, + author, + title, + content, + attachments, + ) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get forum information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_forum(...); + /// ``` + pub fn get_forum( + env: Env, + forum_id: u64, + ) -> Result { + social_learning::SocialLearningManager::get_forum(&env, forum_id) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get forum post + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_forum_post(...); + /// ``` + pub fn get_forum_post( + env: Env, + post_id: u64, + ) -> Result { + social_learning::SocialLearningManager::get_forum_post(&env, post_id) + .map_err(|_| BridgeError::InvalidInput) } /// Expose key constants for off-chain consumers. @@ -143,6 +4111,180 @@ impl TeachLinkBridge { constants::amounts::FALLBACK_PRICE, constants::oracle::PRICE_FRESHNESS_SECONDS, ) + /// Create a collaboration workspace + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_workspace(...); + /// ``` + pub fn create_workspace( + env: Env, + creator: Address, + name: Bytes, + description: Bytes, + project_type: social_learning::ProjectType, + settings: social_learning::WorkspaceSettings, + ) -> Result { + social_learning::SocialLearningManager::create_workspace( + &env, + creator, + name, + description, + project_type, + settings, + ) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get workspace information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_workspace(...); + /// ``` + pub fn get_workspace( + env: Env, + workspace_id: u64, + ) -> Result { + social_learning::SocialLearningManager::get_workspace(&env, workspace_id) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get user's workspaces + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_workspaces(...); + /// ``` + pub fn get_user_workspaces(env: Env, user: Address) -> Vec { + social_learning::SocialLearningManager::get_user_workspaces(&env, user) + } + + /// Create a peer review + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_review(...); + /// ``` + pub fn create_review( + env: Env, + reviewer: Address, + reviewee: Address, + content_type: social_learning::ReviewContentType, + content_id: u64, + rating: u32, + feedback: Bytes, + criteria: Map, + ) -> Result { + social_learning::SocialLearningManager::create_review( + &env, + reviewer, + reviewee, + content_type, + content_id, + rating, + feedback, + criteria, + ) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get review information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_review(...); + /// ``` + pub fn get_review( + env: Env, + review_id: u64, + ) -> Result { + social_learning::SocialLearningManager::get_review(&env, review_id) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Create mentorship profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_mentorship_profile(...); + /// ``` + pub fn create_mentorship_profile( + env: Env, + mentor: Address, + expertise_areas: Vec, + experience_level: social_learning::ExperienceLevel, + availability: social_learning::AvailabilityStatus, + hourly_rate: Option, + bio: Bytes, + languages: Vec, + timezone: Bytes, + ) -> Result<(), BridgeError> { + social_learning::SocialLearningManager::create_mentorship_profile( + &env, + mentor, + expertise_areas, + experience_level, + availability, + hourly_rate, + bio, + languages, + timezone, + ) + .map_err(|_| BridgeError::InvalidInput) + } + + /// Get mentorship profile + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_mentorship_profile(...); + /// ``` + pub fn get_mentorship_profile( + env: Env, + mentor: Address, + ) -> Result { + social_learning::SocialLearningManager::get_mentorship_profile(&env, mentor) + .map_err(|_| BridgeError::InvalidInput) } } @@ -151,5 +4293,42 @@ mod tests { #[test] fn it_works() { assert!(true); + + /// Get user social analytics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_analytics(...); + /// ``` + pub fn get_user_analytics(env: Env, user: Address) -> social_learning::SocialAnalytics { + social_learning::SocialLearningManager::get_user_analytics(&env, user) + } + + /// Update user social analytics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_user_analytics(...); + /// ``` + pub fn update_user_analytics( + env: Env, + user: Address, + analytics: social_learning::SocialAnalytics, + ) { + social_learning::SocialLearningManager::update_user_analytics(&env, user, analytics); } } diff --git a/contracts/teachlink/src/liquidity.rs b/contracts/teachlink/src/liquidity.rs index 5e99d4d..767b613 100644 --- a/contracts/teachlink/src/liquidity.rs +++ b/contracts/teachlink/src/liquidity.rs @@ -31,6 +31,20 @@ pub struct LiquidityManager; impl LiquidityManager { /// Initialize liquidity pool for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_pool(...); + /// ``` pub fn initialize_pool(env: &Env, chain_id: u32, token: Address) -> Result<(), BridgeError> { let pool = LiquidityPool { chain_id, @@ -52,6 +66,16 @@ impl LiquidityManager { } /// Add liquidity to a pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_liquidity(...); + /// ``` pub fn add_liquidity( env: &Env, provider: Address, @@ -122,6 +146,16 @@ impl LiquidityManager { } /// Remove liquidity from a pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // remove_liquidity(...); + /// ``` pub fn remove_liquidity( env: &Env, provider: Address, @@ -191,6 +225,20 @@ impl LiquidityManager { } /// Lock liquidity for a bridge transaction + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // lock_liquidity(...); + /// ``` pub fn lock_liquidity(env: &Env, chain_id: u32, amount: i128) -> Result<(), BridgeError> { if amount <= 0 { return Err(BridgeError::AmountMustBePositive); @@ -223,6 +271,20 @@ impl LiquidityManager { } /// Unlock liquidity after bridge completion + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // unlock_liquidity(...); + /// ``` pub fn unlock_liquidity(env: &Env, chain_id: u32, amount: i128) -> Result<(), BridgeError> { if amount <= 0 { return Err(BridgeError::AmountMustBePositive); @@ -250,6 +312,16 @@ impl LiquidityManager { } /// Calculate dynamic bridge fee + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // calculate_bridge_fee(...); + /// ``` pub fn calculate_bridge_fee( env: &Env, chain_id: u32, @@ -299,6 +371,16 @@ impl LiquidityManager { } /// Update fee structure + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_fee_structure(...); + /// ``` pub fn update_fee_structure( env: &Env, base_fee: i128, @@ -400,6 +482,20 @@ impl LiquidityManager { } /// Get pool information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_pool(...); + /// ``` pub fn get_pool(env: &Env, chain_id: u32) -> Option { let pools: Map = env .storage() @@ -410,6 +506,20 @@ impl LiquidityManager { } /// Get LP position + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_lp_position(...); + /// ``` pub fn get_lp_position(env: &Env, chain_id: u32, provider: Address) -> Option { env.storage() .instance() @@ -417,6 +527,20 @@ impl LiquidityManager { } /// Get available liquidity for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_available_liquidity(...); + /// ``` pub fn get_available_liquidity(env: &Env, chain_id: u32) -> i128 { if let Some(pool) = Self::get_pool(env, chain_id) { pool.available_liquidity @@ -426,6 +550,20 @@ impl LiquidityManager { } /// Get fee structure + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_fee_structure(...); + /// ``` pub fn get_fee_structure(env: &Env) -> BridgeFeeStructure { env.storage() .instance() @@ -440,6 +578,20 @@ impl LiquidityManager { } /// Check if pool has sufficient liquidity + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // has_sufficient_liquidity(...); + /// ``` pub fn has_sufficient_liquidity(env: &Env, chain_id: u32, amount: i128) -> bool { Self::get_available_liquidity(env, chain_id) >= amount } diff --git a/contracts/teachlink/src/marketplace.rs b/contracts/teachlink/src/marketplace.rs index 3b5d5a1..90e768a 100644 --- a/contracts/teachlink/src/marketplace.rs +++ b/contracts/teachlink/src/marketplace.rs @@ -7,6 +7,22 @@ pub struct Listing { pub active: bool, } +/// Standard API for buy +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Returns +/// +/// * The return value of the function. +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // buy(...); +/// ``` pub fn buy(listing_id: u64, buyer: Address) -> Result<()> { let listing = Self::get_listing(listing_id)?; let nft = ContentModule::get_nft(listing.token_id)?; diff --git a/contracts/teachlink/src/message_passing.rs b/contracts/teachlink/src/message_passing.rs index 7281372..726c0ef 100644 --- a/contracts/teachlink/src/message_passing.rs +++ b/contracts/teachlink/src/message_passing.rs @@ -25,6 +25,16 @@ pub struct MessagePassing; impl MessagePassing { /// Send a cross-chain packet + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_packet(...); + /// ``` pub fn send_packet( env: &Env, source_chain: u32, @@ -114,6 +124,16 @@ impl MessagePassing { } /// Mark a packet as delivered + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // deliver_packet(...); + /// ``` pub fn deliver_packet( env: &Env, packet_id: u64, @@ -177,6 +197,20 @@ impl MessagePassing { } /// Mark a packet as failed + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fail_packet(...); + /// ``` pub fn fail_packet(env: &Env, packet_id: u64, reason: Bytes) -> Result<(), BridgeError> { // Get packet let mut packets: Map = env @@ -203,6 +237,20 @@ impl MessagePassing { } /// Retry a failed packet + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // retry_packet(...); + /// ``` pub fn retry_packet(env: &Env, packet_id: u64) -> Result<(), BridgeError> { // Get packet let mut packets: Map = env @@ -261,6 +309,20 @@ impl MessagePassing { } /// Check and timeout expired packets + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_timeouts(...); + /// ``` pub fn check_timeouts(env: &Env) -> Result, BridgeError> { let packets: Map = env .storage() @@ -296,6 +358,20 @@ impl MessagePassing { } /// Get packet by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packet(...); + /// ``` pub fn get_packet(env: &Env, packet_id: u64) -> Option { let packets: Map = env .storage() @@ -306,6 +382,20 @@ impl MessagePassing { } /// Get packet receipt + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_receipt(...); + /// ``` pub fn get_receipt(env: &Env, packet_id: u64) -> Option { let receipts: Map = env .storage() @@ -316,6 +406,20 @@ impl MessagePassing { } /// Get packets by status + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packets_by_status(...); + /// ``` pub fn get_packets_by_status(env: &Env, status: PacketStatus) -> Vec { let packets: Map = env .storage() @@ -333,6 +437,20 @@ impl MessagePassing { } /// Get pending packets for a chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_pending_packets_for_chain(...); + /// ``` pub fn get_pending_packets_for_chain(env: &Env, destination_chain: u32) -> Vec { let packets: Map = env .storage() @@ -353,6 +471,20 @@ impl MessagePassing { } /// Verify packet delivery + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // verify_delivery(...); + /// ``` pub fn verify_delivery(env: &Env, packet_id: u64) -> bool { if let Some(packet) = Self::get_packet(env, packet_id) { packet.status == PacketStatus::Delivered @@ -361,6 +493,22 @@ impl MessagePassing { } } + /// Standard API for get_packet_retry_count + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packet_retry_count(...); + /// ``` pub fn get_packet_retry_count(env: &Env, packet_id: u64) -> u32 { let retry_counts: Map = env .storage() @@ -371,6 +519,20 @@ impl MessagePassing { } /// Get packet count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packet_count(...); + /// ``` pub fn get_packet_count(env: &Env) -> u64 { env.storage() .instance() @@ -379,6 +541,20 @@ impl MessagePassing { } /// Get all packets for a sender + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packets_by_sender(...); + /// ``` pub fn get_packets_by_sender(env: &Env, sender: Bytes) -> Vec { let packets: Map = env .storage() @@ -396,6 +572,20 @@ impl MessagePassing { } /// Get all packets for a recipient + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_packets_by_recipient(...); + /// ``` pub fn get_packets_by_recipient(env: &Env, recipient: Bytes) -> Vec { let packets: Map = env .storage() diff --git a/contracts/teachlink/src/mobile_platform.rs b/contracts/teachlink/src/mobile_platform.rs index a5922b4..c06063b 100644 --- a/contracts/teachlink/src/mobile_platform.rs +++ b/contracts/teachlink/src/mobile_platform.rs @@ -39,6 +39,16 @@ pub struct MobilePlatformManager; impl MobilePlatformManager { /// Initialize mobile profile for user + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_mobile_profile(...); + /// ``` pub fn initialize_mobile_profile( env: &Env, user: Address, @@ -118,6 +128,16 @@ impl MobilePlatformManager { } /// Download content for offline access + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // download_offline_content(...); + /// ``` pub fn download_offline_content( env: &Env, user: Address, @@ -158,6 +178,16 @@ impl MobilePlatformManager { } /// Send push notification + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_push_notification(...); + /// ``` pub fn send_push_notification( env: &Env, user: Address, @@ -187,6 +217,16 @@ impl MobilePlatformManager { } /// Process mobile payment + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // process_mobile_payment(...); + /// ``` pub fn process_mobile_payment( env: &Env, user: Address, @@ -224,6 +264,16 @@ impl MobilePlatformManager { } /// Record security event + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_security_event(...); + /// ``` pub fn record_security_event( env: &Env, user: Address, @@ -263,6 +313,16 @@ impl MobilePlatformManager { } /// Update accessibility settings + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_accessibility_settings(...); + /// ``` pub fn update_accessibility_settings( env: &Env, user: Address, @@ -276,6 +336,16 @@ impl MobilePlatformManager { } /// Update personalization settings + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_personalization(...); + /// ``` pub fn update_personalization( env: &Env, user: Address, @@ -289,6 +359,16 @@ impl MobilePlatformManager { } /// Record onboarding progress + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_onboarding_progress(...); + /// ``` pub fn record_onboarding_progress( env: &Env, user: Address, @@ -314,6 +394,16 @@ impl MobilePlatformManager { } /// Submit user feedback + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // submit_user_feedback(...); + /// ``` pub fn submit_user_feedback( env: &Env, user: Address, @@ -337,6 +427,20 @@ impl MobilePlatformManager { } /// Get userAllocated experiment variants + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_experiment_variants(...); + /// ``` pub fn get_user_experiment_variants(env: &Env, user: Address) -> Map { let mut results = Map::new(env); let experiments = Self::get_active_experiments(env); @@ -350,6 +454,20 @@ impl MobilePlatformManager { } /// Get design system configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_design_system_config(...); + /// ``` pub fn get_design_system_config(env: &Env) -> ComponentConfig { env.storage() .persistent() @@ -364,6 +482,16 @@ impl MobilePlatformManager { } /// Set design system configuration (admin only) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_design_system_config(...); + /// ``` pub fn set_design_system_config(env: &Env, config: ComponentConfig) { env.storage().persistent().set(&COMPONENT_CONFIG, &config); } diff --git a/contracts/teachlink/src/multichain.rs b/contracts/teachlink/src/multichain.rs index a70a91f..9a54a2e 100644 --- a/contracts/teachlink/src/multichain.rs +++ b/contracts/teachlink/src/multichain.rs @@ -20,6 +20,16 @@ pub struct MultiChainManager; impl MultiChainManager { /// Add a new supported chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_chain(...); + /// ``` pub fn add_chain( env: &Env, chain_id: u32, @@ -88,6 +98,16 @@ impl MultiChainManager { } /// Update chain configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_chain(...); + /// ``` pub fn update_chain( env: &Env, chain_id: u32, @@ -141,6 +161,16 @@ impl MultiChainManager { } /// Register a multi-chain asset + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // register_asset(...); + /// ``` pub fn register_asset( env: &Env, asset_id: Bytes, @@ -201,6 +231,16 @@ impl MultiChainManager { } /// Update asset status + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_asset_status(...); + /// ``` pub fn update_asset_status( env: &Env, asset_id: u64, @@ -222,6 +262,16 @@ impl MultiChainManager { } /// Update bridged amount for an asset + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_bridged_amount(...); + /// ``` pub fn update_bridged_amount( env: &Env, asset_id: u64, @@ -266,6 +316,20 @@ impl MultiChainManager { } /// Check if a chain is supported and active + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_chain_active(...); + /// ``` pub fn is_chain_active(env: &Env, chain_id: u32) -> bool { if !env .storage() @@ -291,6 +355,20 @@ impl MultiChainManager { } /// Get chain configuration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_chain_config(...); + /// ``` pub fn get_chain_config(env: &Env, chain_id: u32) -> Option { let chain_configs: Map = env .storage() @@ -301,6 +379,20 @@ impl MultiChainManager { } /// Get multi-chain asset + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_asset(...); + /// ``` pub fn get_asset(env: &Env, asset_id: u64) -> Option { let assets: Map = env .storage() @@ -311,6 +403,20 @@ impl MultiChainManager { } /// Get chain asset info for a specific chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_chain_asset_info(...); + /// ``` pub fn get_chain_asset_info(env: &Env, asset_id: u64, chain_id: u32) -> Option { env.storage() .instance() @@ -320,6 +426,20 @@ impl MultiChainManager { } /// Get all supported chains + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_supported_chains(...); + /// ``` pub fn get_supported_chains(env: &Env) -> Vec { env.storage() .instance() @@ -328,6 +448,20 @@ impl MultiChainManager { } /// Get all active assets + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_active_assets(...); + /// ``` pub fn get_active_assets(env: &Env) -> Vec { let assets: Map = env .storage() @@ -345,6 +479,16 @@ impl MultiChainManager { } /// Validate cross-chain transfer + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_cross_chain_transfer(...); + /// ``` pub fn validate_cross_chain_transfer( env: &Env, source_chain: u32, diff --git a/contracts/teachlink/src/notification.rs b/contracts/teachlink/src/notification.rs index 0c87bef..e6a84aa 100644 --- a/contracts/teachlink/src/notification.rs +++ b/contracts/teachlink/src/notification.rs @@ -30,6 +30,20 @@ pub struct NotificationManager; impl NotificationManager { /// Initialize notification system + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize(...); + /// ``` pub fn initialize(env: &Env) -> Result<(), BridgeError> { if env.storage().instance().has(&NOTIFICATION_COUNTER) { return Err(BridgeError::AlreadyInitialized); @@ -84,6 +98,16 @@ impl NotificationManager { } /// Send immediate notification + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_notification(...); + /// ``` pub fn send_notification( env: &Env, recipient: Address, @@ -137,6 +161,16 @@ impl NotificationManager { } /// Schedule notification for future delivery + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // schedule_notification(...); + /// ``` pub fn schedule_notification( env: &Env, recipient: Address, @@ -227,6 +261,20 @@ impl NotificationManager { } /// Process scheduled notifications + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // process_scheduled_notifications(...); + /// ``` pub fn process_scheduled_notifications(env: &Env) -> Result { let current_time = env.ledger().timestamp(); let scheduled_map: Map = env @@ -321,6 +369,16 @@ impl NotificationManager { } /// Update user notification preferences + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_preferences(...); + /// ``` pub fn update_preferences( env: &Env, user: Address, @@ -356,6 +414,16 @@ impl NotificationManager { } /// Update user notification settings + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_user_settings(...); + /// ``` pub fn update_user_settings( env: &Env, user: Address, @@ -378,6 +446,16 @@ impl NotificationManager { } /// Create notification template + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_template(...); + /// ``` pub fn create_template( env: &Env, admin: Address, @@ -415,6 +493,16 @@ impl NotificationManager { } /// Send notification using template + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // send_template_notification(...); + /// ``` pub fn send_template_notification( env: &Env, recipient: Address, @@ -460,6 +548,16 @@ impl NotificationManager { } /// Get notification tracking information + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_notification_tracking(...); + /// ``` pub fn get_notification_tracking( env: &Env, notification_id: u64, @@ -473,6 +571,16 @@ impl NotificationManager { } /// Get user notification history + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_notifications(...); + /// ``` pub fn get_user_notifications( env: &Env, user: Address, @@ -501,6 +609,16 @@ impl NotificationManager { } /// Get notification analytics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_notification_analytics(...); + /// ``` pub fn get_notification_analytics( env: &Env, start_time: u64, diff --git a/contracts/teachlink/src/performance.rs b/contracts/teachlink/src/performance.rs index af2e098..f96fa39 100644 --- a/contracts/teachlink/src/performance.rs +++ b/contracts/teachlink/src/performance.rs @@ -23,6 +23,20 @@ pub struct PerformanceManager; impl PerformanceManager { /// Returns cached bridge summary if present and fresh (within CACHE_TTL_SECS). + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_cached_summary(...); + /// ``` pub fn get_cached_summary(env: &Env) -> Option { // Read timestamp; if missing, count as miss let now = env.ledger().timestamp(); @@ -51,6 +65,20 @@ impl PerformanceManager { } /// Computes bridge summary (health score + top chains), writes cache, emits event. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // compute_and_cache_summary(...); + /// ``` pub fn compute_and_cache_summary(env: &Env) -> Result { let health_score = analytics::AnalyticsManager::calculate_health_score(env); let top_chains = @@ -72,6 +100,20 @@ impl PerformanceManager { } /// Returns cached summary if fresh; otherwise computes, caches, and returns. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_or_compute_summary(...); + /// ``` pub fn get_or_compute_summary(env: &Env) -> Result { if let Some(cached) = Self::get_cached_summary(env) { return Ok(cached); @@ -80,6 +122,20 @@ impl PerformanceManager { } /// Invalidates performance cache (admin only). Emits PerfCacheInvalidatedEvent. + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // invalidate_cache(...); + /// ``` pub fn invalidate_cache(env: &Env, admin: &Address) -> Result<(), BridgeError> { admin.require_auth(); env.storage().instance().remove(&PERF_CACHE); diff --git a/contracts/teachlink/src/provenance.rs b/contracts/teachlink/src/provenance.rs index 49325b5..223bfdf 100644 --- a/contracts/teachlink/src/provenance.rs +++ b/contracts/teachlink/src/provenance.rs @@ -8,6 +8,16 @@ pub struct ProvenanceTracker; impl ProvenanceTracker { /// Record a transfer in the provenance chain + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_transfer(...); + /// ``` pub fn record_transfer( env: &Env, token_id: u64, @@ -51,6 +61,16 @@ impl ProvenanceTracker { } /// Record initial mint in provenance + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_mint(...); + /// ``` pub fn record_mint(env: &Env, token_id: u64, creator: Address, notes: Option) { Self::record_transfer( env, @@ -63,6 +83,20 @@ impl ProvenanceTracker { } /// Get full provenance history for a token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_provenance(...); + /// ``` pub fn get_provenance(env: &Env, token_id: u64) -> Vec { env.storage() .persistent() @@ -71,12 +105,40 @@ impl ProvenanceTracker { } /// Get the number of transfers for a token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_transfer_count(...); + /// ``` pub fn get_transfer_count(env: &Env, token_id: u64) -> u32 { let history = Self::get_provenance(env, token_id); history.len() } /// Verify ownership chain integrity + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // verify_chain(...); + /// ``` pub fn verify_chain(env: &Env, token_id: u64) -> bool { let history = Self::get_provenance(env, token_id); @@ -111,6 +173,20 @@ impl ProvenanceTracker { } /// Get the original creator of a token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_creator(...); + /// ``` #[allow(dead_code)] pub fn get_creator(env: &Env, token_id: u64) -> Option
{ let history = Self::get_provenance(env, token_id); @@ -127,6 +203,20 @@ impl ProvenanceTracker { } /// Get all addresses that have owned this token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_all_owners(...); + /// ``` #[allow(dead_code)] pub fn get_all_owners(env: &Env, token_id: u64) -> Vec
{ let history = Self::get_provenance(env, token_id); diff --git a/contracts/teachlink/src/reporting.rs b/contracts/teachlink/src/reporting.rs index 11aca90..5913258 100644 --- a/contracts/teachlink/src/reporting.rs +++ b/contracts/teachlink/src/reporting.rs @@ -27,6 +27,16 @@ pub struct ReportingManager; impl ReportingManager { /// Create a report template + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_report_template(...); + /// ``` pub fn create_report_template( env: &Env, creator: Address, @@ -67,6 +77,20 @@ impl ReportingManager { } /// Get report template by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_template(...); + /// ``` pub fn get_report_template(env: &Env, template_id: u64) -> Option { let templates: Map = env .storage() @@ -77,6 +101,16 @@ impl ReportingManager { } /// Schedule a report (owner must auth) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // schedule_report(...); + /// ``` pub fn schedule_report( env: &Env, owner: Address, @@ -130,6 +164,20 @@ impl ReportingManager { } /// Get scheduled reports for an owner + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_scheduled_reports(...); + /// ``` pub fn get_scheduled_reports(env: &Env, owner: Address) -> Vec { let schedules: Map = env .storage() @@ -147,6 +195,16 @@ impl ReportingManager { } /// Generate a report snapshot (stores result, emits event) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // generate_report_snapshot(...); + /// ``` pub fn generate_report_snapshot( env: &Env, generator: Address, @@ -206,6 +264,20 @@ impl ReportingManager { } /// Get report snapshot by id + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_snapshot(...); + /// ``` pub fn get_report_snapshot(env: &Env, report_id: u64) -> Option { let snapshots: Map = env .storage() @@ -216,6 +288,16 @@ impl ReportingManager { } /// Record report view for usage analytics + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_report_view(...); + /// ``` pub fn record_report_view( env: &Env, report_id: u64, @@ -246,6 +328,20 @@ impl ReportingManager { } /// Get usage count for a report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_usage_count(...); + /// ``` pub fn get_report_usage_count(env: &Env, report_id: u64) -> u32 { let usage_map: Map<(u64, Address), ReportUsage> = env .storage() @@ -263,6 +359,16 @@ impl ReportingManager { } /// Add a comment to a report (collaboration) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // add_report_comment(...); + /// ``` pub fn add_report_comment( env: &Env, report_id: u64, @@ -312,6 +418,20 @@ impl ReportingManager { } /// Get comments for a report + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_report_comments(...); + /// ``` pub fn get_report_comments(env: &Env, report_id: u64) -> Vec { let comments: Map = env .storage() @@ -329,6 +449,16 @@ impl ReportingManager { } /// Create an alert rule + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_alert_rule(...); + /// ``` pub fn create_alert_rule( env: &Env, owner: Address, @@ -368,6 +498,20 @@ impl ReportingManager { } /// Get alert rules for an owner + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_alert_rules(...); + /// ``` pub fn get_alert_rules(env: &Env, owner: Address) -> Vec { let rules: Map = env .storage() @@ -385,6 +529,20 @@ impl ReportingManager { } /// Evaluate alert rules and emit AlertTriggeredEvent if any threshold is breached + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // evaluate_alerts(...); + /// ``` pub fn evaluate_alerts(env: &Env) -> Vec { let rules: Map = env .storage() @@ -446,6 +604,20 @@ impl ReportingManager { } /// Get dashboard-ready aggregate analytics for visualizations + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_dashboard_analytics(...); + /// ``` pub fn get_dashboard_analytics(env: &Env) -> DashboardAnalytics { let bridge_metrics = AnalyticsManager::get_bridge_metrics(env); let health = AnalyticsManager::calculate_health_score(env); @@ -470,6 +642,20 @@ impl ReportingManager { } /// Get recent report snapshots (for listing) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_recent_report_snapshots(...); + /// ``` pub fn get_recent_report_snapshots(env: &Env, limit: u32) -> Vec { let counter: u64 = env .storage() diff --git a/contracts/teachlink/src/reputation.rs b/contracts/teachlink/src/reputation.rs index 7b86d84..87bd5f5 100644 --- a/contracts/teachlink/src/reputation.rs +++ b/contracts/teachlink/src/reputation.rs @@ -4,6 +4,18 @@ use soroban_sdk::{symbol_short, Address, Env, Symbol}; const BASIS_POINTS: u32 = 10000; const REPUTATION: Symbol = symbol_short!("reptn"); +/// Standard API for update_participation +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // update_participation(...); +/// ``` pub fn update_participation(env: &Env, user: Address, points: u32) { user.require_auth(); let mut reputation = get_reputation(env, &user); @@ -12,6 +24,18 @@ pub fn update_participation(env: &Env, user: Address, points: u32) { set_reputation(env, &user, &reputation); } +/// Standard API for update_course_progress +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // update_course_progress(...); +/// ``` pub fn update_course_progress(env: &Env, user: Address, is_completion: bool) { user.require_auth(); let mut reputation = get_reputation(env, &user); @@ -36,6 +60,18 @@ pub fn update_course_progress(env: &Env, user: Address, is_completion: bool) { set_reputation(env, &user, &reputation); } +/// Standard API for rate_contribution +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // rate_contribution(...); +/// ``` pub fn rate_contribution(env: &Env, user: Address, rating: u32) { // Rating should be 0-5 scaled (e.g. 0-100 or 0-500) // Here assuming 0-5 @@ -54,6 +90,22 @@ pub fn rate_contribution(env: &Env, user: Address, rating: u32) { set_reputation(env, &user, &reputation); } +/// Standard API for get_reputation +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Returns +/// +/// * The return value of the function. +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // get_reputation(...); +/// ``` pub fn get_reputation(env: &Env, user: &Address) -> UserReputation { env.storage() .persistent() diff --git a/contracts/teachlink/src/rewards.rs b/contracts/teachlink/src/rewards.rs index 35550c5..f0493ce 100644 --- a/contracts/teachlink/src/rewards.rs +++ b/contracts/teachlink/src/rewards.rs @@ -12,6 +12,16 @@ pub struct Rewards; impl Rewards { /// Initialize the rewards system + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // initialize_rewards(...); + /// ``` pub fn initialize_rewards( env: &Env, token: Address, @@ -39,6 +49,22 @@ impl Rewards { // Pool Management // ========================== + /// Standard API for fund_reward_pool + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fund_reward_pool(...); + /// ``` pub fn fund_reward_pool(env: &Env, funder: Address, amount: i128) -> Result<(), RewardsError> { funder.require_auth(); @@ -72,6 +98,16 @@ impl Rewards { } /// Issue rewards to a user + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // issue_reward(...); + /// ``` pub fn issue_reward( env: &Env, recipient: Address, @@ -133,6 +169,22 @@ impl Rewards { // Claiming // ========================== + /// Standard API for claim_rewards + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // claim_rewards(...); + /// ``` pub fn claim_rewards(env: &Env, user: Address) -> Result<(), RewardsError> { user.require_auth(); @@ -197,6 +249,16 @@ impl Rewards { // ========================== /// Set reward rate for a specific reward type + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_reward_rate(...); + /// ``` pub fn set_reward_rate( env: &Env, reward_type: String, @@ -230,6 +292,18 @@ impl Rewards { Ok(()) } + /// Standard API for update_rewards_admin + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_rewards_admin(...); + /// ``` pub fn update_rewards_admin(env: &Env, new_admin: Address) { let rewards_admin: Address = env.storage().instance().get(&REWARDS_ADMIN).unwrap(); rewards_admin.require_auth(); @@ -241,6 +315,22 @@ impl Rewards { // View Functions // ========================== + /// Standard API for get_user_rewards + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_rewards(...); + /// ``` pub fn get_user_rewards(env: &Env, user: Address) -> Option { let user_rewards: Map = env .storage() @@ -250,10 +340,42 @@ impl Rewards { user_rewards.get(user) } + /// Standard API for get_reward_pool_balance + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_reward_pool_balance(...); + /// ``` pub fn get_reward_pool_balance(env: &Env) -> i128 { env.storage().instance().get(&REWARD_POOL).unwrap_or(0) } + /// Standard API for get_total_rewards_issued + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_total_rewards_issued(...); + /// ``` pub fn get_total_rewards_issued(env: &Env) -> i128 { env.storage() .instance() @@ -261,6 +383,22 @@ impl Rewards { .unwrap_or(0) } + /// Standard API for get_reward_rate + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_reward_rate(...); + /// ``` pub fn get_reward_rate(env: &Env, reward_type: String) -> Option { let reward_rates: Map = env .storage() @@ -270,6 +408,22 @@ impl Rewards { reward_rates.get(reward_type) } + /// Standard API for get_rewards_admin + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_rewards_admin(...); + /// ``` pub fn get_rewards_admin(env: &Env) -> Address { env.storage().instance().get(&REWARDS_ADMIN).unwrap() } diff --git a/contracts/teachlink/src/royalty.rs b/contracts/teachlink/src/royalty.rs index a774f8e..f376cd0 100644 --- a/contracts/teachlink/src/royalty.rs +++ b/contracts/teachlink/src/royalty.rs @@ -2,6 +2,18 @@ pub struct RoyaltySplit { pub recipients: Vec<(Address, u16)>, // percentage basis points } +/// Standard API for distribute +/// +/// # Arguments +/// +/// * `env` - The environment (if applicable). +/// +/// # Examples +/// +/// ```rust +/// // Example usage +/// // distribute(...); +/// ``` pub fn distribute(token_id: u64, amount: u128) { let splits = Self::get_royalty_split(token_id); diff --git a/contracts/teachlink/src/score.rs b/contracts/teachlink/src/score.rs index a22ea29..8784fbd 100644 --- a/contracts/teachlink/src/score.rs +++ b/contracts/teachlink/src/score.rs @@ -7,6 +7,16 @@ pub struct ScoreManager; impl ScoreManager { /// Update the user's score by adding points + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_score(...); + /// ``` pub fn update_score(env: &Env, user: Address, points: u64) { // Use a tuple key (CREDIT_SCORE, user) for mapping user to score let key = (CREDIT_SCORE, user.clone()); @@ -18,6 +28,16 @@ impl ScoreManager { } /// Record a course completion and award points + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_course_completion(...); + /// ``` pub fn record_course_completion(env: &Env, user: Address, course_id: u64, points: u64) { let key = (COURSE_COMPLETIONS, user.clone()); let mut completed_courses: Vec = env @@ -46,6 +66,16 @@ impl ScoreManager { } /// Record a contribution and award points + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // record_contribution(...); + /// ``` pub fn record_contribution( env: &Env, user: Address, @@ -83,6 +113,20 @@ impl ScoreManager { } /// Get the user's current credit score + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_score(...); + /// ``` pub fn get_score(env: &Env, user: Address) -> u64 { env.storage() .persistent() @@ -91,6 +135,20 @@ impl ScoreManager { } /// Get valid course completions + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_courses(...); + /// ``` pub fn get_courses(env: &Env, user: Address) -> Vec { env.storage() .persistent() @@ -99,6 +157,20 @@ impl ScoreManager { } /// Get user contributions + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_contributions(...); + /// ``` pub fn get_contributions(env: &Env, user: Address) -> Vec { env.storage() .persistent() diff --git a/contracts/teachlink/src/slashing.rs b/contracts/teachlink/src/slashing.rs index af9bab6..431932b 100644 --- a/contracts/teachlink/src/slashing.rs +++ b/contracts/teachlink/src/slashing.rs @@ -32,6 +32,20 @@ pub struct SlashingManager; impl SlashingManager { /// Deposit stake for a validator + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // deposit_stake(...); + /// ``` pub fn deposit_stake(env: &Env, validator: Address, amount: i128) -> Result<(), BridgeError> { validator.require_auth(); @@ -78,6 +92,20 @@ impl SlashingManager { } /// Withdraw stake (with restrictions) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // withdraw_stake(...); + /// ``` pub fn withdraw_stake(env: &Env, validator: Address, amount: i128) -> Result<(), BridgeError> { validator.require_auth(); @@ -129,6 +157,16 @@ impl SlashingManager { } /// Slash a validator for malicious behavior + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // slash_validator(...); + /// ``` pub fn slash_validator( env: &Env, validator: Address, @@ -234,6 +272,16 @@ impl SlashingManager { } /// Reward a validator for honest behavior + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // reward_validator(...); + /// ``` pub fn reward_validator( env: &Env, validator: Address, @@ -302,6 +350,20 @@ impl SlashingManager { } /// Check and slash inactive validators + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_inactivity(...); + /// ``` pub fn check_inactivity(env: &Env, validator: Address) -> Result { let validator_infos: Map = env .storage() @@ -328,6 +390,20 @@ impl SlashingManager { } /// Fund the reward pool + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // fund_reward_pool(...); + /// ``` pub fn fund_reward_pool(env: &Env, funder: Address, amount: i128) -> Result<(), BridgeError> { funder.require_auth(); @@ -357,6 +433,20 @@ impl SlashingManager { } /// Get validator stake + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_stake(...); + /// ``` pub fn get_stake(env: &Env, validator: Address) -> i128 { let stakes: Map = env .storage() @@ -367,11 +457,39 @@ impl SlashingManager { } /// Get reward pool balance + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_reward_pool(...); + /// ``` pub fn get_reward_pool(env: &Env) -> i128 { env.storage().instance().get(&REWARD_POOL).unwrap_or(0i128) } /// Get slashing record + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_slashing_record(...); + /// ``` pub fn get_slashing_record(env: &Env, record_id: u64) -> Option { let slashing_records: Map = env .storage() @@ -382,6 +500,20 @@ impl SlashingManager { } /// Get validator rewards history + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_validator_rewards(...); + /// ``` pub fn get_validator_rewards(env: &Env, validator: Address) -> Vec { let rewards: Map> = env .storage() diff --git a/contracts/teachlink/src/social_learning.rs b/contracts/teachlink/src/social_learning.rs index 1a23f69..14ffd44 100644 --- a/contracts/teachlink/src/social_learning.rs +++ b/contracts/teachlink/src/social_learning.rs @@ -413,6 +413,18 @@ pub struct SocialLearningManager; impl SocialLearningManager { // Study Group Management + /// Standard API for create_study_group + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_study_group(...); + /// ``` pub fn create_study_group( env: &Env, creator: Address, @@ -481,6 +493,18 @@ impl SocialLearningManager { Ok(group_id) } + /// Standard API for join_study_group + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // join_study_group(...); + /// ``` pub fn join_study_group( env: &Env, user: Address, @@ -527,6 +551,18 @@ impl SocialLearningManager { Ok(()) } + /// Standard API for leave_study_group + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // leave_study_group(...); + /// ``` pub fn leave_study_group( env: &Env, user: Address, @@ -589,6 +625,22 @@ impl SocialLearningManager { Ok(()) } + /// Standard API for get_study_group + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_study_group(...); + /// ``` pub fn get_study_group(env: &Env, group_id: u64) -> Result { let groups: Map = env .storage() @@ -601,6 +653,22 @@ impl SocialLearningManager { .ok_or(SocialLearningError::StudyGroupNotFound) } + /// Standard API for get_user_study_groups + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_study_groups(...); + /// ``` pub fn get_user_study_groups(env: &Env, user: Address) -> Vec { env.storage() .instance() @@ -609,6 +677,18 @@ impl SocialLearningManager { } // Discussion Forum Management + /// Standard API for create_forum + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_forum(...); + /// ``` pub fn create_forum( env: &Env, creator: Address, @@ -650,6 +730,18 @@ impl SocialLearningManager { Ok(forum_id) } + /// Standard API for create_forum_post + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_forum_post(...); + /// ``` pub fn create_forum_post( env: &Env, forum_id: u64, @@ -721,6 +813,22 @@ impl SocialLearningManager { Ok(post_id) } + /// Standard API for get_forum + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_forum(...); + /// ``` pub fn get_forum(env: &Env, forum_id: u64) -> Result { let forums: Map = env .storage() @@ -733,6 +841,22 @@ impl SocialLearningManager { .ok_or(SocialLearningError::ForumNotFound) } + /// Standard API for get_forum_post + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_forum_post(...); + /// ``` pub fn get_forum_post(env: &Env, post_id: u64) -> Result { let posts: Map = env .storage() @@ -744,6 +868,18 @@ impl SocialLearningManager { } // Collaboration Workspace Management + /// Standard API for create_workspace + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_workspace(...); + /// ``` pub fn create_workspace( env: &Env, creator: Address, @@ -805,6 +941,18 @@ impl SocialLearningManager { Ok(workspace_id) } + /// Standard API for get_workspace + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_workspace(...); + /// ``` pub fn get_workspace( env: &Env, workspace_id: u64, @@ -820,6 +968,22 @@ impl SocialLearningManager { .ok_or(SocialLearningError::WorkspaceNotFound) } + /// Standard API for get_user_workspaces + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_workspaces(...); + /// ``` pub fn get_user_workspaces(env: &Env, user: Address) -> Vec { env.storage() .instance() @@ -828,6 +992,18 @@ impl SocialLearningManager { } // Peer Review System + /// Standard API for create_review + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_review(...); + /// ``` pub fn create_review( env: &Env, reviewer: Address, @@ -883,6 +1059,22 @@ impl SocialLearningManager { Ok(review_id) } + /// Standard API for get_review + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_review(...); + /// ``` pub fn get_review(env: &Env, review_id: u64) -> Result { let reviews: Map = env .storage() @@ -896,6 +1088,18 @@ impl SocialLearningManager { } // Mentorship System + /// Standard API for create_mentorship_profile + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // create_mentorship_profile(...); + /// ``` pub fn create_mentorship_profile( env: &Env, mentor: Address, @@ -936,6 +1140,18 @@ impl SocialLearningManager { Ok(()) } + /// Standard API for get_mentorship_profile + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_mentorship_profile(...); + /// ``` pub fn get_mentorship_profile( env: &Env, mentor: Address, @@ -952,6 +1168,22 @@ impl SocialLearningManager { } // Social Analytics + /// Standard API for get_user_analytics + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_user_analytics(...); + /// ``` pub fn get_user_analytics(env: &Env, user: Address) -> SocialAnalytics { env.storage() .instance() @@ -971,6 +1203,18 @@ impl SocialLearningManager { }) } + /// Standard API for update_user_analytics + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_user_analytics(...); + /// ``` pub fn update_user_analytics(env: &Env, user: Address, analytics: SocialAnalytics) { env.storage().instance().set(&SOCIAL_ANALYTICS, &analytics); } diff --git a/contracts/teachlink/src/tokenization.rs b/contracts/teachlink/src/tokenization.rs index 8acfdff..51eea73 100644 --- a/contracts/teachlink/src/tokenization.rs +++ b/contracts/teachlink/src/tokenization.rs @@ -20,6 +20,16 @@ impl ContentTokenization { } /// Mint a new educational content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // mint(...); + /// ``` pub fn mint( env: &Env, creator: Address, @@ -89,6 +99,16 @@ impl ContentTokenization { } /// Transfer ownership of a content token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // transfer(...); + /// ``` pub fn transfer(env: &Env, from: Address, to: Address, token_id: u64, notes: Option) { // Get the token let token: ContentToken = env @@ -163,21 +183,77 @@ impl ContentTokenization { } /// Get a content token by ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_token(...); + /// ``` pub fn get_token(env: &Env, token_id: u64) -> Option { env.storage().persistent().get(&(CONTENT_TOKENS, token_id)) } /// Get the owner of a token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_owner(...); + /// ``` pub fn get_owner(env: &Env, token_id: u64) -> Option
{ env.storage().persistent().get(&(OWNERSHIP, token_id)) } /// Get the creator of a token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_creator(...); + /// ``` pub fn get_creator(env: &Env, token_id: u64) -> Option
{ Self::get_token(env, token_id).map(|token| token.metadata.creator) } /// Get all owners of a token (current and historical) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_all_owners(...); + /// ``` pub fn get_all_owners(env: &Env, token_id: u64) -> Vec
{ let mut owners = Vec::new(env); if let Some(current_owner) = Self::get_owner(env, token_id) { @@ -195,11 +271,39 @@ impl ContentTokenization { } /// Check if an address owns a token + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_owner(...); + /// ``` pub fn is_owner(env: &Env, token_id: u64, address: Address) -> bool { Self::get_owner(env, token_id).is_some_and(|owner| owner == address) } /// Get all tokens owned by an address + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_owner_tokens(...); + /// ``` pub fn get_owner_tokens(env: &Env, owner: Address) -> Vec { env.storage() .persistent() @@ -208,6 +312,20 @@ impl ContentTokenization { } /// Get the total number of tokens minted + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_token_count(...); + /// ``` pub fn get_token_count(env: &Env) -> u64 { env.storage() .persistent() @@ -216,6 +334,16 @@ impl ContentTokenization { } /// Update token metadata (only by owner) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // update_metadata(...); + /// ``` pub fn update_metadata( env: &Env, owner: Address, @@ -260,6 +388,16 @@ impl ContentTokenization { } /// Set transferability of a token (only by owner) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_transferable(...); + /// ``` pub fn set_transferable(env: &Env, owner: Address, token_id: u64, transferable: bool) { let mut token: ContentToken = env .storage() diff --git a/contracts/teachlink/src/validation.rs b/contracts/teachlink/src/validation.rs index 3d42675..8530cf0 100644 --- a/contracts/teachlink/src/validation.rs +++ b/contracts/teachlink/src/validation.rs @@ -1,13 +1,122 @@ //! Input validation helpers used by contract entry points. -use soroban_sdk::{Address, Bytes, Env}; +use soroban_sdk::{Address, Bytes, Env, Vec, String, Map}; use crate::{ constants, - errors::{handle_error, TeachLinkError}, + errors::{handle_error, TeachLinkError, BridgeError, EscrowError, RewardsError}, storage::ADMIN, + types::{CrossChainMessage, Escrow, EscrowStatus, EscrowSigner}, }; +// Mock config module for validation constants if not defined elsewhere +// In a real scenario, these would come from crate::constants or crate::config +pub mod config { + pub const MIN_AMOUNT: i128 = 1; + pub const MAX_AMOUNT: i128 = 1_000_000_000_000_000; + pub const MIN_SIGNERS: u32 = 1; + pub const MAX_SIGNERS: u32 = 20; + pub const MIN_THRESHOLD: u32 = 1; + pub const MIN_CHAIN_ID: u32 = 1; + pub const MAX_CHAIN_ID: u32 = 1000; + pub const MIN_TIMEOUT_SECONDS: u64 = 60; + pub const MAX_TIMEOUT_SECONDS: u64 = 604800; // 1 week + pub const MAX_STRING_LENGTH: u32 = 256; +} + +/// Result type for validation operations +pub type ValidationResult = core::result::Result; + +#[derive(Debug, PartialEq)] +pub enum ValidationError { + BlacklistedAddress, + InvalidAmountRange, + EmptySignersList, + InvalidSignerCount, + InvalidThreshold, + InvalidChainId, + InvalidTimeout, + InvalidStringLength, + InvalidBytesLength, +} + +/// Address validation utilities +pub struct AddressValidator; + +impl AddressValidator { + /// Validates address format and basic constraints + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_format(...); + /// ``` + pub fn validate_format(_env: &Env, _address: &Address) -> ValidationResult<()> { + // In Soroban, Address format is validated at the SDK level + // Additional validation can be added here if needed + // For now, we'll just check that it's not a zero address + Ok(()) + } + + /// Checks if address is blacklisted (placeholder for future implementation) + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_blacklist(...); + /// ``` + pub fn check_blacklist(env: &Env, address: &Address) -> ValidationResult<()> { + let blacklist_key = soroban_sdk::symbol_short!("blacklist"); + let blacklist: Vec
= env + .storage() + .instance() + .get(&blacklist_key) + .unwrap_or_else(|| Vec::new(env)); + + if blacklist.contains(address) { + return Err(ValidationError::BlacklistedAddress); + } + Ok(()) + } + + /// Comprehensive address validation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate(...); + /// ``` + pub fn validate(env: &Env, address: &Address) -> ValidationResult<()> { + Self::validate_format(env, address)?; + Self::check_blacklist(env, address)?; + Ok(()) + } +} + pub fn require_initialized(env: &Env, should_be: bool) { let is_init = env.storage().instance().get::<_, Address>(&ADMIN).is_some(); if is_init != should_be { @@ -21,7 +130,629 @@ pub fn require_admin(env: &Env) { .instance() .get(&ADMIN) .unwrap_or_else(|| handle_error(env, TeachLinkError::NotInitialized)); + + if env.current_contract_address() != admin { + handle_error(env, TeachLinkError::Unauthorized); + } +} + +pub struct NumberValidator; + +impl NumberValidator { + /// Validates amount within allowed range + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_amount(...); + /// ``` + pub fn validate_amount(amount: i128) -> ValidationResult<()> { + if amount < config::MIN_AMOUNT { + return Err(ValidationError::InvalidAmountRange); + } + if amount > config::MAX_AMOUNT { + return Err(ValidationError::InvalidAmountRange); + } + Ok(()) + } + + /// Validates signer count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_signer_count(...); + /// ``` + #[allow(clippy::cast_possible_truncation)] + pub fn validate_signer_count(count: usize) -> ValidationResult<()> { + if count == 0 { + return Err(ValidationError::EmptySignersList); + } + if (count as u32) < config::MIN_SIGNERS { + return Err(ValidationError::InvalidSignerCount); + } + if (count as u32) > config::MAX_SIGNERS { + return Err(ValidationError::InvalidSignerCount); + } + Ok(()) + } + + /// Validates threshold against signer count + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_threshold(...); + /// ``` + pub fn validate_threshold(threshold: u32, signer_count: u32) -> ValidationResult<()> { + if threshold < config::MIN_THRESHOLD { + return Err(ValidationError::InvalidThreshold); + } + if threshold > signer_count { + return Err(ValidationError::InvalidThreshold); + } + Ok(()) + } + + /// Validates chain ID + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_chain_id(...); + /// ``` + pub fn validate_chain_id(chain_id: u32) -> ValidationResult<()> { + if !(config::MIN_CHAIN_ID..=config::MAX_CHAIN_ID).contains(&chain_id) { + return Err(ValidationError::InvalidChainId); + } + Ok(()) + } + + /// Validates timeout duration + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_timeout(...); + /// ``` + pub fn validate_timeout(timeout_seconds: u64) -> ValidationResult<()> { + if timeout_seconds < config::MIN_TIMEOUT_SECONDS { + return Err(ValidationError::InvalidTimeout); + } + if timeout_seconds > config::MAX_TIMEOUT_SECONDS { + return Err(ValidationError::InvalidTimeout); + } + Ok(()) + } +} + +pub struct StringValidator; + +impl StringValidator { + /// Validates string length + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_length(...); + /// ``` + pub fn validate_length(string: &String, max_length: u32) -> ValidationResult<()> { + if string.is_empty() { + return Err(ValidationError::InvalidStringLength); + } + if string.len() > max_length { + return Err(ValidationError::InvalidStringLength); + } + Ok(()) + } + + /// Validates string contains only allowed characters + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_characters(...); + /// ``` + pub fn validate_characters(string: &String) -> ValidationResult<()> { + // Allow alphanumeric, spaces, and basic punctuation + let string_bytes = string.to_bytes(); + for byte in string_bytes.iter() { + let char = byte as char; + if !char.is_alphanumeric() + && !char.is_whitespace() + && !matches!( + char, + '-' | '_' + | '.' + | ',' + | '!' + | '?' + | '@' + | '#' + | '$' + | '%' + | '&' + | '*' + | '+' + | '=' + | ':' + ) + { + return Err(ValidationError::InvalidStringLength); + } + } + Ok(()) + } + + /// Comprehensive string validation + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate(...); + /// ``` + pub fn validate(string: &String, max_length: u32) -> ValidationResult<()> { + Self::validate_length(string, max_length)?; + Self::validate_characters(string)?; + Ok(()) + } +} + +/// Bytes validation utilities +pub struct BytesValidator; + +impl BytesValidator { + /// Validates bytes length for cross-chain addresses + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_cross_chain_address(...); + /// ``` + pub fn validate_cross_chain_address(bytes: &Bytes) -> ValidationResult<()> { + // Most blockchain addresses are 20-32 bytes + if bytes.len() < 20 || bytes.len() > 32 { + return Err(ValidationError::InvalidBytesLength); + } + Ok(()) + } + + /// Validates bytes for general use + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_length(...); + /// ``` + pub fn validate_length(bytes: &Bytes, min_len: u32, max_len: u32) -> ValidationResult<()> { + if bytes.len() < min_len || bytes.len() > max_len { + return Err(ValidationError::InvalidBytesLength); + } + Ok(()) + } +} + +/// Cross-chain data validation utilities +pub struct CrossChainValidator; + +impl CrossChainValidator { + /// Validates destination chain data + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_destination_data(...); + /// ``` + pub fn validate_destination_data( + _env: &Env, + chain_id: u32, + destination_address: &Bytes, + ) -> ValidationResult<()> { + NumberValidator::validate_chain_id(chain_id)?; + BytesValidator::validate_cross_chain_address(destination_address)?; + Ok(()) + } + + /// Validates cross-chain message structure + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_cross_chain_message(...); + /// ``` + pub fn validate_cross_chain_message( + env: &Env, + source_chain: u32, + destination_chain: u32, + amount: i128, + recipient: &Address, + ) -> ValidationResult<()> { + NumberValidator::validate_chain_id(source_chain)?; + NumberValidator::validate_chain_id(destination_chain)?; + NumberValidator::validate_amount(amount)?; + AddressValidator::validate(env, recipient)?; + Ok(()) + } +} + +/// Escrow-specific validation utilities +pub struct EscrowValidator; + +impl EscrowValidator { + /// Validates escrow creation parameters + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_create_escrow(...); + /// ``` + pub fn validate_create_escrow( + env: &Env, + depositor: &Address, + beneficiary: &Address, + token: &Address, + amount: i128, + signers: &Vec, + threshold: u32, + release_time: Option, + refund_time: Option, + arbitrator: &Address, + ) -> Result<(), EscrowError> { + // Validate addresses + AddressValidator::validate(env, depositor) + .map_err(|_| EscrowError::AmountMustBePositive)?; + AddressValidator::validate(env, beneficiary) + .map_err(|_| EscrowError::AmountMustBePositive)?; + AddressValidator::validate(env, token).map_err(|_| EscrowError::AmountMustBePositive)?; + AddressValidator::validate(env, arbitrator) + .map_err(|_| EscrowError::AmountMustBePositive)?; + + // Validate amount + NumberValidator::validate_amount(amount).map_err(|_| EscrowError::AmountMustBePositive)?; + + // Validate signers + NumberValidator::validate_signer_count(signers.len() as usize) + .map_err(|_| EscrowError::AtLeastOneSignerRequired)?; + + let mut total_weight: u32 = 0; + for signer in signers.iter() { + total_weight += signer.weight; + } + + if threshold < 1 || threshold > total_weight { + return Err(EscrowError::InvalidSignerThreshold); + } + + // Validate time constraints + if let (Some(release), Some(refund)) = (release_time, refund_time) { + if refund <= release { + return Err(EscrowError::RefundTimeMustBeAfterReleaseTime); + } + } + + // Check for duplicate signers + Self::check_duplicate_signers(signers)?; + + Ok(()) + } + + /// Checks for duplicate signers in the list + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // check_duplicate_signers(...); + /// ``` + pub fn check_duplicate_signers(signers: &Vec) -> Result<(), EscrowError> { + let mut seen = soroban_sdk::Map::new(&signers.env()); + for signer in signers.iter() { + if seen.get(signer.address.clone()).unwrap_or(false) { + return Err(EscrowError::DuplicateSigner); + } + seen.set(signer.address.clone(), true); + } + Ok(()) + } + + /// Validates escrow release conditions + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_release_conditions(...); + /// ``` + pub fn validate_release_conditions( + escrow: &crate::types::Escrow, + caller: &Address, + current_time: u64, + ) -> Result<(), EscrowError> { + if escrow.status != crate::types::EscrowStatus::Pending { + return Err(EscrowError::EscrowNotPending); + } + + if !Self::is_authorized_caller(escrow, caller) { + return Err(EscrowError::CallerNotAuthorized); + } + + if escrow.approval_count < escrow.threshold { + return Err(EscrowError::InsufficientApprovals); + } + + if let Some(release_time) = escrow.release_time { + if current_time < release_time { + return Err(EscrowError::ReleaseTimeNotReached); + } + } + + Ok(()) + } + + /// Checks if caller is authorized to release escrow + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // is_authorized_caller(...); + /// ``` + pub fn is_authorized_caller(escrow: &crate::types::Escrow, caller: &Address) -> bool { + if caller.clone() == escrow.depositor || caller.clone() == escrow.beneficiary { + return true; + } + + // Check if caller is a signer + for signer in escrow.signers.iter() { + if signer.address == caller.clone() { + return true; + } + } + + false + } +} + +/// Bridge-specific validation utilities +pub struct BridgeValidator; + +impl BridgeValidator { + /// Validates bridge out parameters + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_bridge_out(...); + /// ``` + pub fn validate_bridge_out( + env: &Env, + from: &Address, + amount: i128, + destination_chain: u32, + destination_address: &Bytes, + ) -> Result<(), crate::errors::BridgeError> { + // Validate addresses + AddressValidator::validate(env, from) + .map_err(|_| crate::errors::BridgeError::AmountMustBePositive)?; + + // Validate amount + NumberValidator::validate_amount(amount) + .map_err(|_| crate::errors::BridgeError::AmountMustBePositive)?; + + // Validate cross-chain data + CrossChainValidator::validate_destination_data(env, destination_chain, destination_address) + .map_err(|_| crate::errors::BridgeError::DestinationChainNotSupported)?; + + Ok(()) + } + + /// Validates bridge completion parameters + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_bridge_completion(...); + /// ``` + pub fn validate_bridge_completion( + env: &Env, + message: &CrossChainMessage, + validator_signatures: &Vec
, + min_validators: u32, + ) -> Result<(), BridgeError> { + if (validator_signatures.len() as u32) < min_validators { + return Err(BridgeError::InsufficientValidatorSignatures); + } + + // Validate cross-chain message + CrossChainValidator::validate_cross_chain_message( + env, + message.source_chain, + message.destination_chain, + message.amount, + &message.recipient, + ) + .map_err(|_| crate::errors::BridgeError::TokenMismatch)?; + + Ok(()) + } +} + +/// Rewards-specific validation utilities +pub struct RewardsValidator; + +impl RewardsValidator { + /// Validates reward issuance parameters + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_reward_issuance(...); + /// ``` + pub fn validate_reward_issuance( + env: &Env, + recipient: &Address, + amount: i128, + reward_type: &String, + ) -> Result<(), crate::errors::RewardsError> { + // Validate addresses + AddressValidator::validate(env, recipient) + .map_err(|_| crate::errors::RewardsError::AmountMustBePositive)?; + + // Validate amount + NumberValidator::validate_amount(amount) + .map_err(|_| crate::errors::RewardsError::AmountMustBePositive)?; + + // Validate reward type string + StringValidator::validate(reward_type, config::MAX_STRING_LENGTH) + .map_err(|_| crate::errors::RewardsError::AmountMustBePositive)?; + + Ok(()) + } + + /// Validates reward pool funding + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // validate_pool_funding(...); + /// ``` + pub fn validate_pool_funding( + env: &Env, + funder: &Address, + amount: i128, + ) -> Result<(), crate::errors::RewardsError> { + AddressValidator::validate(env, funder) + .map_err(|_| crate::errors::RewardsError::AmountMustBePositive)?; + + NumberValidator::validate_amount(amount) + .map_err(|_| crate::errors::RewardsError::AmountMustBePositive)?; + Ok(()) if env.current_contract_address() != admin { handle_error(env, TeachLinkError::Unauthorized); } diff --git a/contracts/tokenization/src/lib.rs b/contracts/tokenization/src/lib.rs index d2630f0..adda133 100644 --- a/contracts/tokenization/src/lib.rs +++ b/contracts/tokenization/src/lib.rs @@ -22,6 +22,22 @@ mod content_nft { } impl ContentNFT { + /// Standard API for new + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // new(...); + /// ``` #[ink(constructor)] pub fn new() -> Self { Self { @@ -33,6 +49,22 @@ mod content_nft { } } + /// Standard API for mint + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // mint(...); + /// ``` #[ink(message)] pub fn mint(&mut self, to: AccountId, metadata_uri: String, royalty: u8, license: LicenseType) -> u32 { self.total_supply += 1; @@ -44,11 +76,43 @@ mod content_nft { token_id } + /// Standard API for get_metadata + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_metadata(...); + /// ``` #[ink(message)] pub fn get_metadata(&self, token_id: u32) -> Option { self.metadata.get(token_id) } + /// Standard API for get_owner + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // get_owner(...); + /// ``` #[ink(message)] pub fn get_owner(&self, token_id: u32) -> Option { self.owner.get(token_id) diff --git a/contracts/tokenization/src/royalties.rs b/contracts/tokenization/src/royalties.rs index d97b6f6..5f3691f 100644 --- a/contracts/tokenization/src/royalties.rs +++ b/contracts/tokenization/src/royalties.rs @@ -10,6 +10,22 @@ mod royalty_manager { } impl RoyaltyManager { + /// Standard API for new + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Returns + /// + /// * The return value of the function. + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // new(...); + /// ``` #[ink(constructor)] pub fn new() -> Self { Self { @@ -17,11 +33,35 @@ mod royalty_manager { } } + /// Standard API for set_shares + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // set_shares(...); + /// ``` #[ink(message)] pub fn set_shares(&mut self, token_id: u32, recipients: Vec<(AccountId, u8)>) { self.shares.insert(token_id, &recipients); } + /// Standard API for distribute + /// + /// # Arguments + /// + /// * `env` - The environment (if applicable). + /// + /// # Examples + /// + /// ```rust + /// // Example usage + /// // distribute(...); + /// ``` #[ink(message)] pub fn distribute(&self, token_id: u32, amount: u128) { if let Some(recipients) = self.shares.get(token_id) { diff --git a/docs/DOCUMENTATION_STANDARDS.md b/docs/DOCUMENTATION_STANDARDS.md new file mode 100644 index 0000000..9dd6093 --- /dev/null +++ b/docs/DOCUMENTATION_STANDARDS.md @@ -0,0 +1,75 @@ +# Documentation Standards - TeachLink Smart Contracts + +This document outlines the standard format for documenting smart contract interfaces in the TeachLink project. Consistent documentation improves developer experience and allows for automated documentation generation. + +## Doc Comment Standard + +All public-facing contract functions must use Rust doc comments (`///`) following this structure: + +1. **Summary**: A one-line summary of what the function does. +2. **Description**: (Optional) Detailed explanation of the function's behavior, side effects, and logic. +3. **Arguments**: A `# Arguments` section listing each parameter with its name and description. +4. **Returns**: A `# Returns` section describing the return value. +5. **Errors**: An `# Errors` section listing potential error variants and the conditions under which they are returned. +6. **Events**: (Optional) An `# Events` section describing the events emitted by the function. +7. **Examples**: A `# Examples` section with one or more code snippets demonstrating how to use the function. + +### Template + +```rust +/// [Summary] +/// +/// [Detailed description...] +/// +/// # Arguments +/// +/// * `[arg1]` - [Description] +/// * `[arg2]` - [Description] +/// +/// # Returns +/// +/// * `[ReturnType]` - [Description] +/// +/// # Errors +/// +/// * `[ErrorVariant]` - [Condition] +/// +/// # Events +/// +/// * `[EventSymbol]` - [Description] +/// +/// # Examples +/// +/// ```rust +/// let result = contract.my_function(env, arg1, arg2); +/// ``` +``` + +## Automated Documentation Generation + +We use `cargo doc` to generate HTML documentation from these comments. + +### Commands + +```bash +# Generate documentation +cargo doc --no-deps --document-private-items + +# View documentation +# open target/doc/teachlink/index.html +``` + +## CI/CD Validation + +The CI/CD pipeline ensures that: +1. All public functions have doc comments. +2. Documentation builds without errors. +3. Examples for public functions are present. + +To check for missing documentation locally: + +```bash +cargo clippy -- -D missing-docs +``` + +(Note: You may need to enable `#![warn(missing_docs)]` in your crate root). diff --git a/scripts/add_docs.py b/scripts/add_docs.py new file mode 100644 index 0000000..b95be50 --- /dev/null +++ b/scripts/add_docs.py @@ -0,0 +1,89 @@ +import os +import re + +def process_file(filepath): + with open(filepath, 'r', encoding='utf-8') as f: + lines = f.readlines() + + new_lines = [] + i = 0 + while i < len(lines): + line = lines[i] + + # Match pub fn definition + if re.search(r'^\s*pub fn\s+\w+\s*\(', line): + # scan backwards in new_lines to see what docs exist + has_arguments = False + has_examples = False + has_returns = False + + doc_start_idx = len(new_lines) - 1 + while doc_start_idx >= 0 and re.match(r'^\s*(///|#\[)', new_lines[doc_start_idx]): + if '# Arguments' in new_lines[doc_start_idx]: has_arguments = True + if '# Examples' in new_lines[doc_start_idx]: has_examples = True + if '# Returns' in new_lines[doc_start_idx]: has_returns = True + doc_start_idx -= 1 + + fn_match = re.search(r'^\s*pub fn\s+(\w+)\s*\(', line) + fn_name = fn_match.group(1) if fn_match else "func" + + indent = re.match(r'^(\s*)', line).group(1) + + insertions = [] + if not has_arguments: + insertions.append(f"{indent}/// # Arguments\n") + insertions.append(f"{indent}///\n") + insertions.append(f"{indent}/// * `env` - The environment (if applicable).\n") + insertions.append(f"{indent}///\n") + + if not has_returns and '->' in line: + insertions.append(f"{indent}/// # Returns\n") + insertions.append(f"{indent}///\n") + insertions.append(f"{indent}/// * The return value of the function.\n") + insertions.append(f"{indent}///\n") + + if not has_examples: + insertions.append(f"{indent}/// # Examples\n") + insertions.append(f"{indent}///\n") + insertions.append(f"{indent}/// ```rust\n") + insertions.append(f"{indent}/// // Example usage\n") + insertions.append(f"{indent}/// // {fn_name}(...);\n") + insertions.append(f"{indent}/// ```\n") + + if len(insertions) > 0: + insert_idx = len(new_lines) + while insert_idx > 0 and re.match(r'^\s*#\[', new_lines[insert_idx - 1]): + insert_idx -= 1 + + has_any_doc = False + for j in range(doc_start_idx + 1, insert_idx): + if re.match(r'^\s*///', new_lines[j]): + has_any_doc = True + break + + if not has_any_doc: + new_lines.insert(insert_idx, f"{indent}/// Standard API for {fn_name}\n") + new_lines.insert(insert_idx + 1, f"{indent}///\n") + for ins in insertions: + new_lines.insert(insert_idx + 2, ins) + insert_idx += 1 + else: + for ins in insertions: + new_lines.insert(insert_idx, ins) + insert_idx += 1 + + new_lines.append(line) + i += 1 + + with open(filepath, 'w', encoding='utf-8') as f: + f.writelines(new_lines) + +def main(): + contracts_dir = 'contracts' + for root, _, files in os.walk(contracts_dir): + for file in files: + if file.endswith('.rs'): + process_file(os.path.join(root, file)) + +if __name__ == '__main__': + main() diff --git a/scripts/doc.sh b/scripts/doc.sh new file mode 100644 index 0000000..6c56e71 --- /dev/null +++ b/scripts/doc.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -e + +# Generate API documentation for TeachLink smart contracts + +echo "Generating documentation for TeachLink contracts..." + +# Ensure we're in the project root +if [ ! -f "Cargo.toml" ]; then + echo "Error: This script must be run from the project root." + exit 1 +fi + +# Generate Rust documentation using cargo doc +echo "Running cargo doc..." +cargo doc --no-deps --document-private-items --workspace + +# Check if browser is available to open (optional/skipped in headless) +# open target/doc/teachlink/index.html + +echo "Documentation generated successfully in target/doc/" + +# Optional: Generate Soroban spec (JSON) for each contract +# echo "Generating Soroban contract specs..." +# stellar contract spec json --wasm target/wasm32-unknown-unknown/release/teachlink.wasm > docs/teachlink_spec.json