-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathlib.rs
More file actions
2047 lines (1790 loc) · 65.2 KB
/
Copy pathlib.rs
File metadata and controls
2047 lines (1790 loc) · 65.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::all)]
#![allow(unused)]
//! TeachLink Smart Contract
//!
//! A comprehensive Soroban smart contract for the TeachLink decentralized
//! knowledge-sharing platform on the Stellar network.
//!
//! # Overview
//!
//! TeachLink provides the following core features:
//!
//! - **Cross-Chain Bridge**: Bridge tokens between Stellar and other blockchains
//! - **Advanced BFT Consensus**: Byzantine Fault Tolerant validator consensus
//! - **Validator Slashing**: Economic penalties for malicious validators
//! - **Multi-Chain Support**: Support for multiple blockchain networks
//! - **Liquidity Optimization**: AMM and dynamic fee pricing
//! - **Message Passing**: Guaranteed cross-chain message delivery
//! - **Emergency Controls**: Circuit breaker and pause mechanisms
//! - **Atomic Swaps**: Cross-chain token exchanges
//! - **Audit & Compliance**: Comprehensive logging and reporting
//! - **Token Rewards**: Incentivize learning and contributions with token rewards
//! - **Multi-Sig Escrow**: Secure payments with multi-signature escrow and arbitration
//! - **Content Tokenization**: Mint NFTs representing educational content ownership
//! - **Provenance Tracking**: Full chain-of-custody for content tokens
//! - **User Reputation**: Track user participation, completion rates, and contribution quality
//! - **Credit Scoring**: Calculate user credit scores based on courses and contributions
//!
//! # Contract Modules
//!
//! | Module | Description |
//! |--------|-------------|
//! | [`bridge`] | Cross-chain token bridging with validator consensus |
//! | [`bft_consensus`] | Byzantine Fault Tolerant consensus mechanism |
//! | [`slashing`] | Validator slashing and reward mechanisms |
//! | [`multichain`] | Multi-chain support and asset management |
//! | [`liquidity`] | Bridge liquidity pools and AMM |
//! | [`message_passing`] | Cross-chain message passing |
//! | [`emergency`] | Emergency pause and circuit breaker |
//! | [`audit`] | Audit trail and compliance reporting |
//! | [`atomic_swap`] | Cross-chain atomic swaps |
//! | [`analytics`] | Bridge monitoring and analytics |
//! | [`performance`] | Performance caching (bridge summary, TTL, invalidation) |
//! | [`reporting`] | Advanced analytics, report templates, dashboards, and alerting |
//! | [`backup`] | Backup scheduling, integrity verification, disaster recovery, and RTO audit |
//! | [`rewards`] | Reward pool management and distribution |
//! | [`escrow`] | Multi-signature escrow with dispute resolution |
//! | [`tokenization`] | Educational content NFT minting and management |
//! | [`provenance`] | Ownership history tracking for content tokens |
//! | [`reputation`] | User reputation scoring system |
//! | [`score`] | Credit score calculation from activities |
//!
//! # Quick Start
//!
//! ```ignore
//! // Initialize the contract
//! TeachLinkBridge::initialize(env, token, admin, min_validators, fee_recipient);
//!
//! // Register a validator with BFT consensus
//! TeachLinkBridge::register_validator(env, validator, stake);
//!
//! // Add a supported chain
//! TeachLinkBridge::add_supported_chain_config(env, chain_id, chain_name, bridge_address);
//!
//! // Bridge tokens with advanced features
//! let nonce = TeachLinkBridge::bridge_out(env, from, amount, destination_chain, destination_address);
//!
//! // Create atomic swap
//! let swap_id = TeachLinkBridge::initiate_atomic_swap(env, params);
//! ```
//!
//! # Authorization
//!
//! Most state-changing functions require authorization:
//! - Admin functions require the admin address
//! - User functions require the user's address
//! - Validator functions require validator authorization
//! - Escrow functions require appropriate party authorization
#![no_std]
#![allow(clippy::unreadable_literal)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::trivially_copy_pass_by_ref)]
#![allow(clippy::needless_borrow)]
use soroban_sdk::{contract, contractimpl, Address, Bytes, Env, Map, String, Symbol, Vec};
mod access_control;
mod access_logger;
mod analytics;
mod arbitration;
mod assessment;
mod atomic_swap;
mod audit;
mod auto_scaling;
mod backup;
mod bft_consensus;
mod bridge;
mod bulk_limits;
mod config;
mod dos_protection;
mod emergency;
mod errors;
mod escrow_analytics;
mod event_query;
mod feature_flags;
mod safe_stats;
// TODO: Fix event_tests module compilation errors (pre-existing issue)
// mod event_tests;
mod events;
mod insurance;
mod interface_versioning;
mod ledger_time;
mod liquidity;
mod message_passing;
mod mobile_platform;
mod multichain;
mod network_recovery;
mod notification;
mod notification_events_basic;
// TODO: Fix notification_tests module (pre-existing issue - tests fail with AlreadyInitialized)
// mod notification_tests;
mod notification_types;
mod performance;
mod property_based_tests;
mod provenance;
mod rate_limiting;
mod recommendation;
mod reentrancy;
mod reporting;
mod repository;
mod reputation;
mod rewards;
mod score;
mod slashing;
mod storage;
mod sustainability;
mod tokenization;
mod types;
mod upgrade;
mod validation;
// TODO: Fix validation_tests compilation errors (pre-existing issue)
// mod validation_tests;
pub use validation::{
AddressValidator, BridgeValidator, BytesValidator, CrossChainValidator, EscrowValidator,
InputSanitizer, NumberValidator, RewardsValidator, StringValidator, ValidationError,
ValidationResult,
};
pub use crate::types::{
ColorBlindMode, ComponentConfig, DeviceInfo, FeedbackCategory, FocusStyle, FontSize,
LayoutDensity, MobileAccessibilitySettings, MobilePreferences, MobileProfile, NetworkType,
OnboardingStage, OnboardingStatus, ThemePreference, UserFeedback, VideoQuality,
};
pub use assessment::{
Assessment, AssessmentSettings, AssessmentSubmission, Question, QuestionType,
};
pub use errors::{
AccessLogError, BridgeError, EscrowError, GovernanceError, MobilePlatformError, RewardsError,
ScoreError, TokenizationError,
};
pub use repository::{
BridgeRepository, EscrowAggregateRepository, GenericCounterRepository, GenericMapRepository,
SingleValueRepository, StorageError,
};
pub use types::{
// access logging / audit types
AccessLogEntry,
AccessOutcome,
AlertConditionType,
AlertRule,
ArbitratorProfile,
AtomicSwap,
AuditQuery,
AuditRecord,
BackupManifest,
BackupSchedule,
BridgeMetrics,
BridgeProposal,
BridgeTransaction,
CachedBridgeSummary,
ChainConfig,
ChainMetrics,
ComplianceReport,
ConsensusState,
ContentMetadata,
ContentToken,
ContentTokenParameters,
ContentType,
ContractSemVer,
ContributionType,
CrossChainMessage,
CrossChainPacket,
DashboardAnalytics,
DeprecatedFunction,
DeprecationPolicy,
DisputeOutcome,
EmergencyState,
Escrow,
EscrowMetrics,
EscrowParameters,
EscrowRole,
EscrowSigner,
EscrowStatus,
FeatureFlag,
FeatureStatus,
InterfaceVersionStatus,
LiquidityPool,
MigrationPath,
MultiChainAsset,
NotificationChannel,
NotificationContent,
NotificationPreference,
NotificationSchedule,
NotificationTemplate,
NotificationTracking,
OperationType,
PacketStatus,
ProposalStatus,
ProvenanceRecord,
RecoveryRecord,
ReportComment,
ReportSchedule,
ReportSnapshot,
ReportTemplate,
ReportType,
ReportUsage,
RewardRate,
RewardType,
RolloutStrategy,
RtoTier,
SlashingReason,
SlashingRecord,
SwapStatus,
TransferType,
UserNotificationSettings,
UserReputation,
UserReward,
ValidatorInfo,
ValidatorReward,
ValidatorSignature,
VisualizationDataPoint,
};
/// TeachLink main contract.
///
/// This contract provides entry points for all TeachLink functionality
/// including bridging, rewards, escrow, tokenization, and reputation.
#[contract]
pub struct TeachLinkBridge;
#[contractimpl]
impl TeachLinkBridge {
/// Initialize the bridge contract
pub fn initialize(
env: Env,
token: Address,
admin: Address,
min_validators: u32,
fee_recipient: Address,
) -> Result<(), BridgeError> {
bridge::Bridge::initialize(&env, token, admin.clone(), min_validators, fee_recipient)?;
interface_versioning::InterfaceVersioning::initialize(&env);
upgrade::ContractUpgrader::initialize(&env, admin.clone())?;
Ok(())
}
/// Bridge tokens out to another chain (lock/burn tokens on Stellar)
pub fn bridge_out(
env: Env,
from: Address,
amount: i128,
destination_chain: u32,
destination_address: Bytes,
) -> Result<u64, BridgeError> {
bridge::Bridge::bridge_out(&env, from, amount, destination_chain, destination_address)
}
/// Complete a bridge transaction (mint/release tokens on Stellar)
pub fn complete_bridge(
env: Env,
message: CrossChainMessage,
validator_signatures: Vec<Address>,
) -> Result<(), BridgeError> {
bridge::Bridge::complete_bridge(&env, message, validator_signatures)
}
/// Cancel a bridge transaction and refund locked tokens
pub fn cancel_bridge(env: Env, nonce: u64) -> Result<(), BridgeError> {
bridge::Bridge::cancel_bridge(&env, nonce)
}
pub fn mark_bridge_failed(env: Env, nonce: u64, reason: Bytes) -> Result<(), BridgeError> {
bridge::Bridge::mark_bridge_failed(&env, nonce, reason)
}
pub fn retry_bridge(env: Env, nonce: u64) -> Result<u32, BridgeError> {
bridge::Bridge::retry_bridge(&env, nonce)
}
pub fn refund_bridge_transaction(env: Env, nonce: u64) -> Result<(), BridgeError> {
bridge::Bridge::refund_bridge_transaction(&env, nonce)
}
// ========== Admin Functions ==========
/// Add a validator (admin only)
pub fn add_validator(env: Env, validator: Address) -> Result<(), BridgeError> {
bridge::Bridge::add_validator(&env, validator)
}
/// Remove a validator (admin only)
pub fn remove_validator(env: Env, validator: Address) -> Result<(), BridgeError> {
bridge::Bridge::remove_validator(&env, validator)
}
/// Add a supported destination chain (admin only)
pub fn add_supported_chain(env: Env, chain_id: u32) -> Result<(), BridgeError> {
bridge::Bridge::add_supported_chain(&env, chain_id)
}
/// Remove a supported destination chain (admin only)
pub fn remove_supported_chain(env: Env, chain_id: u32) -> Result<(), BridgeError> {
bridge::Bridge::remove_supported_chain(&env, chain_id)
}
/// Set bridge fee (admin only)
pub fn set_bridge_fee(env: Env, fee: i128) -> Result<(), BridgeError> {
bridge::Bridge::set_bridge_fee(&env, fee)
}
/// Set fee recipient (admin only)
pub fn set_fee_recipient(env: Env, fee_recipient: Address) -> Result<(), BridgeError> {
bridge::Bridge::set_fee_recipient(&env, fee_recipient)
}
/// Set minimum validators (admin only)
pub fn set_min_validators(env: Env, min_validators: u32) -> Result<(), BridgeError> {
bridge::Bridge::set_min_validators(&env, min_validators)
}
// ========== View Functions ==========
/// Get full interface version status (current and minimum compatible version)
pub fn get_interface_version_status(env: Env) -> InterfaceVersionStatus {
interface_versioning::InterfaceVersioning::get_interface_version_status(&env)
}
/// Get current interface semantic version
pub fn get_interface_version(env: Env) -> ContractSemVer {
interface_versioning::InterfaceVersioning::get_interface_version(&env)
}
/// Get minimum supported interface semantic version
pub fn get_min_compat_interface_version(env: Env) -> ContractSemVer {
interface_versioning::InterfaceVersioning::get_minimum_compatible_interface_version(&env)
}
/// Update current and minimum compatible interface versions (admin only)
pub fn set_interface_version(
env: Env,
current: ContractSemVer,
minimum_compatible: ContractSemVer,
) -> Result<(), BridgeError> {
interface_versioning::InterfaceVersioning::set_interface_versions(
&env,
current,
minimum_compatible,
)
}
/// Validate whether a client interface version is compatible
pub fn is_interface_compatible(env: Env, client_version: ContractSemVer) -> bool {
interface_versioning::InterfaceVersioning::is_interface_compatible(&env, client_version)
}
/// Assert interface compatibility and return an explicit error if incompatible
pub fn assert_interface_compatible(
env: Env,
client_version: ContractSemVer,
) -> Result<(), BridgeError> {
interface_versioning::InterfaceVersioning::assert_interface_compatible(&env, client_version)
}
/// Check if upgrading from one version to another is backward compatible
pub fn is_backward_compatible(from: ContractSemVer, to: ContractSemVer) -> bool {
interface_versioning::InterfaceVersioning::is_backward_compatible(&from, &to)
}
/// Register a function as deprecated (admin only)
pub fn deprecate_function(
env: Env,
caller: Address,
function_name: Symbol,
deprecated_in: ContractSemVer,
removal_in: ContractSemVer,
replacement: Option<Symbol>,
reason: Bytes,
) -> Result<(), BridgeError> {
interface_versioning::InterfaceVersioning::deprecate_function(
&env,
caller,
function_name,
deprecated_in,
removal_in,
replacement,
reason,
)
}
/// Get deprecation info for a specific function
pub fn get_deprecation(env: Env, function_name: Symbol) -> Option<DeprecatedFunction> {
interface_versioning::InterfaceVersioning::get_deprecation(&env, function_name)
}
/// Get the full deprecation policy (current version + all deprecated functions)
pub fn get_deprecation_policy(env: Env) -> DeprecationPolicy {
interface_versioning::InterfaceVersioning::get_deprecation_policy(&env)
}
/// Register a migration path between two versions (admin only)
pub fn register_migration_path(
env: Env,
caller: Address,
from_version: ContractSemVer,
to_version: ContractSemVer,
description: Bytes,
breaking_changes: Vec<Bytes>,
migration_steps: Vec<Bytes>,
) -> Result<(), BridgeError> {
interface_versioning::InterfaceVersioning::register_migration_path(
&env,
caller,
from_version,
to_version,
description,
breaking_changes,
migration_steps,
)
}
/// Get the migration path between two specific versions
pub fn get_migration_path(
env: Env,
from_version: ContractSemVer,
to_version: ContractSemVer,
) -> Option<MigrationPath> {
interface_versioning::InterfaceVersioning::get_migration_path(
&env,
from_version,
to_version,
)
}
/// Get all registered migration paths
pub fn get_all_migration_paths(env: Env) -> Vec<MigrationPath> {
interface_versioning::InterfaceVersioning::get_all_migration_paths(&env)
}
/// Get the full version upgrade history
pub fn get_version_history(env: Env) -> Vec<ContractSemVer> {
interface_versioning::InterfaceVersioning::get_version_history(&env)
}
/// Get the bridge transaction by nonce
pub fn get_bridge_transaction(env: Env, nonce: u64) -> Option<BridgeTransaction> {
bridge::Bridge::get_bridge_transaction(&env, nonce)
}
/// Check if a chain is 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
pub fn is_validator(env: Env, address: Address) -> bool {
bridge::Bridge::is_validator(&env, address)
}
/// Get the current nonce
pub fn get_nonce(env: Env) -> u64 {
bridge::Bridge::get_nonce(&env)
}
/// Get the bridge fee
pub fn get_bridge_fee(env: Env) -> i128 {
bridge::Bridge::get_bridge_fee(&env)
}
/// Get the token address
pub fn get_token(env: Env) -> Result<Address, BridgeError> {
Ok(bridge::Bridge::get_token(&env))
}
/// Get the admin address
pub fn get_admin(env: Env) -> Result<Address, BridgeError> {
Ok(bridge::Bridge::get_admin(&env))
}
// ========== BFT Consensus Functions ==========
/// Register a validator with stake for BFT consensus
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
pub fn unregister_validator(env: Env, validator: Address) -> Result<(), BridgeError> {
bft_consensus::BFTConsensus::unregister_validator(&env, validator)
}
/// Create a bridge proposal for BFT consensus
pub fn create_bridge_proposal(
env: Env,
message: CrossChainMessage,
) -> Result<u64, BridgeError> {
bft_consensus::BFTConsensus::create_proposal(&env, message)
}
/// Vote on a bridge 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
pub fn get_validator_info(env: Env, validator: Address) -> Option<ValidatorInfo> {
bft_consensus::BFTConsensus::get_validator_info(&env, validator)
}
/// Get consensus state
pub fn get_consensus_state(env: Env) -> ConsensusState {
bft_consensus::BFTConsensus::get_consensus_state(&env)
}
/// Get proposal by ID
pub fn get_proposal(env: Env, proposal_id: u64) -> Option<BridgeProposal> {
bft_consensus::BFTConsensus::get_proposal(&env, proposal_id)
}
/// Check if consensus is reached for a proposal
pub fn is_consensus_reached(env: Env, proposal_id: u64) -> bool {
bft_consensus::BFTConsensus::is_consensus_reached(&env, proposal_id)
}
/// Rotate validators: deactivate those with low reputation or insufficient stake.
/// Returns the number of validators rotated out.
pub fn rotate_validators(env: Env) -> Result<u32, BridgeError> {
bft_consensus::BFTConsensus::rotate_validators(&env)
}
/// Trigger rotation if the current consensus round is at an epoch boundary.
pub fn maybe_rotate_validators(env: Env) -> Result<bool, BridgeError> {
bft_consensus::BFTConsensus::maybe_rotate(&env)
}
// ========== Auto-Scaling & Load Management Functions ==========
/// Initialize auto-scaling configuration (admin only)
pub fn initialize_auto_scaling(env: Env, admin: Address) -> Result<(), BridgeError> {
auto_scaling::AutoScaler::initialize(&env, &admin)
}
/// Get current system load level
pub fn get_load_level(env: Env) -> crate::types::LoadLevel {
auto_scaling::AutoScaler::get_current_load_level(&env)
}
/// Calculate optimal batch size based on current load
pub fn get_optimal_batch_size(env: Env) -> u32 {
auto_scaling::AutoScaler::calculate_optimal_batch_size(&env)
}
/// Check if an operation should be shed based on priority and load
pub fn should_shed_operation(env: Env, priority: u32) -> bool {
auto_scaling::AutoScaler::should_shed_operation(&env, priority)
}
/// Update load metrics with recent operation data
pub fn update_load_metrics(
env: Env,
operations_processed: u64,
operations_shed: u64,
current_gas_usage: u64,
) -> Result<(), BridgeError> {
auto_scaling::AutoScaler::update_load_metrics(
&env,
operations_processed,
operations_shed,
current_gas_usage,
)
}
/// Determine if an operation should be queued based on priority
pub fn should_queue_operation(env: Env, priority: u32) -> bool {
auto_scaling::AutoScaler::should_queue_operation(&env, priority)
}
/// Get gas allocation for an operation based on load and priority
pub fn allocate_gas_budget(env: Env, priority: u32, base_gas: u64) -> u64 {
auto_scaling::AutoScaler::allocate_gas_budget(&env, priority, base_gas)
}
/// Trigger emergency scaling (admin only)
pub fn trigger_emergency_scaling(env: Env, admin: Address) -> Result<(), BridgeError> {
admin.require_auth();
auto_scaling::AutoScaler::emergency_scaling(&env)
}
/// Reset scaling configuration to defaults (admin only)
pub fn reset_auto_scaling(env: Env, admin: Address) -> Result<(), BridgeError> {
auto_scaling::AutoScaler::reset_scaling(&env, &admin)
}
// ========== Slashing and Rewards Functions ==========
/// Deposit stake for a validator
pub fn deposit_stake(env: Env, validator: Address, amount: i128) -> Result<(), BridgeError> {
slashing::SlashingManager::deposit_stake(&env, validator, amount)
}
/// 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
pub fn slash_validator(
env: Env,
validator: Address,
reason: types::SlashingReason,
evidence: Bytes,
slasher: Address,
) -> Result<i128, BridgeError> {
slashing::SlashingManager::slash_validator(&env, validator, reason, evidence, slasher)
}
/// Reward a 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
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
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
pub fn add_supported_chain_config(
env: Env,
chain_id: u32,
chain_name: Bytes,
bridge_contract_address: Bytes,
confirmation_blocks: u32,
gas_price: u64,
) -> Result<(), BridgeError> {
multichain::MultiChainManager::add_chain(
&env,
chain_id,
chain_name,
bridge_contract_address,
confirmation_blocks,
gas_price,
)
}
/// Update chain configuration
pub fn update_chain_config(
env: Env,
chain_id: u32,
is_active: bool,
confirmation_blocks: Option<u32>,
gas_price: Option<u64>,
) -> Result<(), BridgeError> {
multichain::MultiChainManager::update_chain(
&env,
chain_id,
is_active,
confirmation_blocks,
gas_price,
)
}
/// Register a multi-chain asset
pub fn register_multi_chain_asset(
env: Env,
asset_id: Bytes,
stellar_token: Address,
chain_configs: Map<u32, types::ChainAssetInfo>,
) -> Result<u64, BridgeError> {
multichain::MultiChainManager::register_asset(&env, asset_id, stellar_token, chain_configs)
}
/// Get chain configuration
pub fn get_chain_config(env: Env, chain_id: u32) -> Option<ChainConfig> {
multichain::MultiChainManager::get_chain_config(&env, chain_id)
}
/// Check if chain is active
pub fn is_chain_active(env: Env, chain_id: u32) -> bool {
multichain::MultiChainManager::is_chain_active(&env, chain_id)
}
/// Get supported chains
pub fn get_supported_chains(env: Env) -> Vec<u32> {
multichain::MultiChainManager::get_supported_chains(&env)
}
// ========== Liquidity and AMM Functions ==========
/// Initialize liquidity pool for a chain
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
pub fn add_liquidity(
env: Env,
provider: Address,
chain_id: u32,
amount: i128,
) -> Result<u32, BridgeError> {
liquidity::LiquidityManager::add_liquidity(&env, provider, chain_id, amount)
}
/// Remove liquidity from a pool
pub fn remove_liquidity(
env: Env,
provider: Address,
chain_id: u32,
amount: i128,
) -> Result<i128, BridgeError> {
liquidity::LiquidityManager::remove_liquidity(&env, provider, chain_id, amount)
}
/// Calculate dynamic bridge fee
pub fn calculate_bridge_fee(
env: Env,
chain_id: u32,
amount: i128,
user_volume_24h: i128,
) -> Result<i128, BridgeError> {
liquidity::LiquidityManager::calculate_bridge_fee(&env, chain_id, amount, user_volume_24h)
}
/// Update fee structure
pub fn update_fee_structure(
env: Env,
base_fee: i128,
dynamic_multiplier: u32,
volume_discount_tiers: Map<u32, u32>,
) -> Result<(), BridgeError> {
liquidity::LiquidityManager::update_fee_structure(
&env,
base_fee,
dynamic_multiplier,
volume_discount_tiers,
)
}
/// Get available liquidity for a chain
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
pub fn send_cross_chain_packet(
env: Env,
source_chain: u32,
destination_chain: u32,
sender: Bytes,
recipient: Bytes,
payload: Bytes,
timeout: Option<u64>,
) -> Result<u64, BridgeError> {
message_passing::MessagePassing::send_packet(
&env,
source_chain,
destination_chain,
sender,
recipient,
payload,
timeout,
)
}
/// Mark a cross-chain packet as delivered
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
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
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
pub fn check_cross_chain_timeouts(env: Env) -> Result<Vec<u64>, BridgeError> {
message_passing::MessagePassing::check_timeouts(&env)
}
/// Get packet by ID
pub fn get_packet(env: Env, packet_id: u64) -> Option<CrossChainPacket> {
message_passing::MessagePassing::get_packet(&env, packet_id)
}
/// Get packet receipt
pub fn get_packet_receipt(env: Env, packet_id: u64) -> Option<types::MessageReceipt> {
message_passing::MessagePassing::get_receipt(&env, packet_id)
}
/// 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
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
pub fn pause_bridge(env: Env, pauser: Address, reason: Bytes) -> Result<(), BridgeError> {
emergency::EmergencyManager::pause_bridge(&env, pauser, reason)
}
/// Resume the bridge
pub fn resume_bridge(env: Env, resumer: Address) -> Result<(), BridgeError> {
emergency::EmergencyManager::resume_bridge(&env, resumer)
}
/// Pause specific chains
pub fn pause_chains(
env: Env,
pauser: Address,
chain_ids: Vec<u32>,
reason: Bytes,
) -> Result<(), BridgeError> {
emergency::EmergencyManager::pause_chains(&env, pauser, chain_ids, reason)
}
/// Resume specific chains
pub fn resume_chains(
env: Env,
resumer: Address,
chain_ids: Vec<u32>,
) -> Result<(), BridgeError> {
emergency::EmergencyManager::resume_chains(&env, resumer, chain_ids)
}
/// Initialize circuit breaker for a chain
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
pub fn is_bridge_paused(env: Env) -> bool {
emergency::EmergencyManager::is_bridge_paused(&env)
}
/// Check if a chain is paused
pub fn is_chain_paused(env: Env, chain_id: u32) -> bool {
emergency::EmergencyManager::is_chain_paused(&env, chain_id)
}
/// 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
pub fn create_audit_record(
env: Env,
operation_type: types::OperationType,
operator: Address,
details: Bytes,
tx_hash: Bytes,
) -> Result<u64, BridgeError> {
audit::AuditManager::create_audit_record(&env, operation_type, operator, details, tx_hash)
}
/// Get audit record by ID
pub fn get_audit_record(env: Env, record_id: u64) -> Option<AuditRecord> {
audit::AuditManager::get_audit_record(&env, record_id)
}
/// Generate compliance report
pub fn generate_compliance_report(
env: Env,
period_start: u64,
period_end: u64,
) -> Result<u64, BridgeError> {
audit::AuditManager::generate_compliance_report(&env, period_start, period_end)
}
/// Get compliance report
pub fn get_compliance_report(env: Env, report_id: u64) -> Option<ComplianceReport> {
audit::AuditManager::get_compliance_report(&env, report_id)
}
// ========== Atomic Swap Functions ==========
/// Initiate an 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<u64, BridgeError> {
atomic_swap::AtomicSwapManager::initiate_swap(
&env,
initiator,
initiator_token,
initiator_amount,
counterparty,
counterparty_token,
counterparty_amount,
hashlock,
timelock,
)
}
/// Accept and complete an 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)
}