forked from MettaChain/PropChain-contract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1048 lines (901 loc) · 37.4 KB
/
Copy pathlib.rs
File metadata and controls
1048 lines (901 loc) · 37.4 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
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(unexpected_cfgs)]
use ink::prelude::string::String;
use ink::storage::Mapping;
use propchain_traits::*;
#[cfg(not(feature = "std"))]
use scale_info::prelude::vec::Vec;
#[ink::contract]
mod bridge {
use super::*;
use propchain_traits::{non_reentrant, ReentrancyError, ReentrancyGuard};
include!("errors.rs");
impl From<ReentrancyError> for Error {
fn from(_: ReentrancyError) -> Self {
Error::ReentrantCall
}
}
/// Bridge contract for cross-chain property token transfers
#[ink(storage)]
pub struct PropertyBridge {
/// Bridge configuration
config: BridgeConfig,
/// Multi-signature bridge requests
bridge_requests: Mapping<u64, MultisigBridgeRequest>,
/// Bridge transaction history
bridge_history: Mapping<AccountId, Vec<BridgeTransaction>>,
/// Chain-specific information
chain_info: Mapping<ChainId, ChainBridgeInfo>,
/// Transaction verification records
verified_transactions: Mapping<Hash, bool>,
/// Cross-chain DEX settlement intents tracked by the bridge
cross_chain_trades: Mapping<u64, CrossChainTradeIntent>,
/// Bridge operators
bridge_operators: Vec<AccountId>,
/// Registered validators for multi-signature cross-chain transactions.
/// Only accounts in this set may sign bridge requests (issue #203).
validators: Vec<AccountId>,
/// Request counter
request_counter: u64,
/// Transaction counter
transaction_counter: u64,
/// Cross-chain trade settlement counter
cross_chain_trade_counter: u64,
/// Admin account
admin: AccountId,
/// Registered ECDSA public keys for optional cryptographic signature verification
operator_public_keys: Mapping<AccountId, [u8; 33]>,
/// Pending admin key rotation request
pending_admin_rotation: Option<propchain_traits::KeyRotationRequest>,
/// Account daily bridge request count for rate limiting
account_daily_requests: Mapping<AccountId, u64>,
/// Account last reset day for rate limiting
account_last_reset_day: Mapping<AccountId, u64>,
/// Chain daily volume for rate limiting
chain_daily_volume: Mapping<ChainId, u128>,
/// Chain last reset day for rate limiting
chain_last_reset_day: Mapping<ChainId, u64>,
/// Reentrancy protection
reentrancy_guard: ReentrancyGuard,
}
/// Events for bridge operations
#[ink(event)]
pub struct BridgeRequestCreated {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
#[ink(topic)]
pub source_chain: ChainId,
#[ink(topic)]
pub destination_chain: ChainId,
#[ink(topic)]
pub requester: AccountId,
}
#[ink(event)]
pub struct BridgeRequestSigned {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub signer: AccountId,
pub signatures_collected: u8,
pub signatures_required: u8,
}
#[ink(event)]
pub struct BridgeExecuted {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
#[ink(topic)]
pub transaction_hash: Hash,
}
#[ink(event)]
pub struct BridgeFailed {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
pub error: String,
}
#[ink(event)]
pub struct BridgeRecovered {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub recovery_action: RecoveryAction,
}
/// Emitted when a bridge transaction is atomically rolled back (#201).
#[ink(event)]
pub struct BridgeRolledBack {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
/// Original sender whose funds are now unlocked.
pub requester: AccountId,
/// Human-readable rollback reason for audit trail.
pub reason: String,
/// Block number at which the rollback was executed.
pub rolled_back_at: u32,
}
impl PropertyBridge {
/// Creates a new PropertyBridge contract
#[ink(constructor)]
pub fn new(
supported_chains: Vec<ChainId>,
min_signatures: u8,
max_signatures: u8,
default_timeout: u64,
gas_limit: u64,
) -> Self {
let caller = Self::env().caller();
let config = BridgeConfig {
supported_chains: supported_chains.clone(),
min_signatures_required: min_signatures,
max_signatures_required: max_signatures,
default_timeout_blocks: default_timeout,
gas_limit_per_bridge: gas_limit,
emergency_pause: false,
metadata_preservation: true,
rate_limit_enabled: true,
max_requests_per_day: 10,
max_value_per_day: 1_000_000_000_000_000_000,
};
// Initialize chain info for supported chains
let mut bridge = Self {
config,
bridge_requests: Mapping::default(),
bridge_history: Mapping::default(),
chain_info: Mapping::default(),
verified_transactions: Mapping::default(),
cross_chain_trades: Mapping::default(),
bridge_operators: vec![caller],
validators: Vec::new(),
request_counter: 0,
transaction_counter: 0,
cross_chain_trade_counter: 0,
admin: caller,
operator_public_keys: Mapping::default(),
pending_admin_rotation: None,
account_daily_requests: Mapping::default(),
account_last_reset_day: Mapping::default(),
chain_daily_volume: Mapping::default(),
chain_last_reset_day: Mapping::default(),
reentrancy_guard: ReentrancyGuard::new(),
};
// Set up default chain information
for chain_id in supported_chains {
let chain_info = ChainBridgeInfo {
chain_id,
chain_name: format!("Chain-{}", chain_id),
bridge_contract_address: None,
is_active: true,
gas_multiplier: propchain_traits::constants::DEFAULT_GAS_MULTIPLIER,
confirmation_blocks: propchain_traits::constants::DEFAULT_CONFIRMATION_BLOCKS,
supported_tokens: Vec::new(),
chain_daily_limit: 10_000_000_000_000_000_000, // Example large default
};
bridge.chain_info.insert(chain_id, &chain_info);
}
bridge
}
/// Initiates a bridge request with multi-signature requirement
#[ink(message)]
pub fn initiate_bridge_multisig(
&mut self,
token_id: TokenId,
destination_chain: ChainId,
recipient: AccountId,
required_signatures: u8,
timeout_blocks: Option<u64>,
metadata: PropertyMetadata,
) -> Result<u64, Error> {
let caller = self.env().caller();
// Check if bridge is paused
if self.config.emergency_pause {
return Err(Error::BridgePaused);
}
// Validate destination chain
if !self.config.supported_chains.contains(&destination_chain) {
return Err(Error::InvalidChain);
}
// Validate signature requirements
if required_signatures < self.config.min_signatures_required
|| required_signatures > self.config.max_signatures_required
{
return Err(Error::InsufficientSignatures);
}
// Check if caller is authorized (token owner or approved operator)
if !self.is_authorized_for_token(caller, token_id) {
return Err(Error::Unauthorized);
}
// Enforce rate limiting
// For NFT bridge, we count requests but value is 0 here since NFT value isn't strictly defined by amount.
self.check_and_update_rate_limits(caller, destination_chain, 0, true)?;
// Create bridge request
self.request_counter += 1;
let request_id = self.request_counter;
let current_block = u64::from(self.env().block_number());
let expires_at = timeout_blocks.map(|blocks| current_block + blocks);
let request = MultisigBridgeRequest {
request_id,
token_id,
source_chain: self.get_current_chain_id(),
destination_chain,
sender: caller,
recipient,
required_signatures,
signatures: Vec::new(),
created_at: current_block,
expires_at,
status: BridgeOperationStatus::Pending,
metadata,
};
self.bridge_requests.insert(request_id, &request);
self.env().emit_event(BridgeRequestCreated {
request_id,
token_id,
source_chain: request.source_chain,
destination_chain,
requester: caller,
});
Ok(request_id)
}
/// Signs a bridge request
#[ink(message)]
pub fn sign_bridge_request(&mut self, request_id: u64, approve: bool) -> Result<(), Error> {
let caller = self.env().caller();
// Check if caller is a registered validator (issue #203: only validators may sign)
if !self.validators.contains(&caller) {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Check if request has expired
if let Some(expires_at) = request.expires_at {
if u64::from(self.env().block_number()) > expires_at {
return Err(Error::RequestExpired);
}
}
// Check if already signed
if request.signatures.contains(&caller) {
return Err(Error::AlreadySigned);
}
// Add signature
request.signatures.push(caller);
// Update status based on approval and signatures collected
if !approve {
request.status = BridgeOperationStatus::Failed;
} else if request.signatures.len() >= request.required_signatures as usize {
request.status = BridgeOperationStatus::Locked;
}
self.bridge_requests.insert(request_id, &request);
self.env().emit_event(BridgeRequestSigned {
request_id,
signer: caller,
signatures_collected: request.signatures.len() as u8,
signatures_required: request.required_signatures,
});
Ok(())
}
/// Register an ECDSA public key for cryptographic signature verification.
#[ink(message)]
pub fn register_operator_public_key(&mut self, public_key: [u8; 33]) -> Result<(), Error> {
let caller = self.env().caller();
if !self.bridge_operators.contains(&caller) {
return Err(Error::Unauthorized);
}
self.operator_public_keys.insert(caller, &public_key);
Ok(())
}
/// Sign a bridge request with optional ECDSA cryptographic signature verification.
#[ink(message)]
pub fn sign_bridge_request_with_signature(
&mut self,
request_id: u64,
approve: bool,
signed_approval: Option<propchain_traits::SignedApproval>,
) -> Result<(), Error> {
let caller = self.env().caller();
if let Some(ref approval) = signed_approval {
let expected_key = self
.operator_public_keys
.get(caller)
.ok_or(Error::Unauthorized)?;
propchain_traits::crypto::verify_signed_approval(approval, &expected_key)
.map_err(|_| Error::Unauthorized)?;
let expected_hash = propchain_traits::crypto::hash_encoded(&(
request_id,
approve,
caller,
self.env().block_number(),
));
if approval.message_hash != <[u8; 32]>::from(expected_hash) {
return Err(Error::Unauthorized);
}
}
self.sign_bridge_request(request_id, approve)
}
/// Executes a bridge request after collecting required signatures
#[ink(message)]
pub fn execute_bridge(&mut self, request_id: u64) -> Result<(), Error> {
non_reentrant!(self, {
let caller = self.env().caller();
// Check if caller is a bridge operator
if !self.bridge_operators.contains(&caller) {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Check if request is ready for execution
if request.status != BridgeOperationStatus::Locked {
return Err(Error::InvalidRequest);
}
// Check if enough signatures are collected
if request.signatures.len() < request.required_signatures as usize {
return Err(Error::InsufficientSignatures);
}
// Generate transaction hash
let transaction_hash = self.generate_transaction_hash(&request);
// Create bridge transaction record
self.transaction_counter += 1;
let transaction = BridgeTransaction {
transaction_id: self.transaction_counter,
token_id: request.token_id,
source_chain: request.source_chain,
destination_chain: request.destination_chain,
sender: request.sender,
recipient: request.recipient,
transaction_hash,
timestamp: self.env().block_timestamp(),
gas_used: self.estimate_gas_usage(&request),
status: BridgeOperationStatus::InTransit,
metadata: request.metadata.clone(),
};
// Update request status
request.status = BridgeOperationStatus::Completed;
self.bridge_requests.insert(request_id, &request);
// Store transaction verification
self.verified_transactions.insert(transaction_hash, &true);
// Add to bridge history
let mut history = self.bridge_history.get(request.sender).unwrap_or_default();
history.push(transaction.clone());
self.bridge_history.insert(request.sender, &history);
self.env().emit_event(BridgeExecuted {
request_id,
token_id: request.token_id,
transaction_hash,
});
Ok(())
})
}
/// Recovers from a failed bridge operation
#[ink(message)]
pub fn recover_failed_bridge(
&mut self,
request_id: u64,
recovery_action: RecoveryAction,
) -> Result<(), Error> {
non_reentrant!(self, {
let caller = self.env().caller();
// Only admin can recover failed bridges
if caller != self.admin {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Check if request is in a failed state
if !matches!(
request.status,
BridgeOperationStatus::Failed | BridgeOperationStatus::Expired
) {
return Err(Error::InvalidRequest);
}
// Execute recovery action
match recovery_action {
RecoveryAction::UnlockToken => {
// Logic to unlock the token would be implemented here
// This would typically call back to the property token contract
}
RecoveryAction::RefundGas => {
// Logic to refund gas costs would be implemented here
}
RecoveryAction::RetryBridge => {
// Reset request to pending for retry
request.status = BridgeOperationStatus::Pending;
request.signatures.clear();
}
RecoveryAction::CancelBridge => {
// Mark as cancelled
request.status = BridgeOperationStatus::Failed;
}
}
self.bridge_requests.insert(request_id, &request);
self.env().emit_event(BridgeRecovered {
request_id,
recovery_action,
});
Ok(())
})
}
// ── #201: Transaction rollback mechanism ─────────────────────────────────
/// Rollback a failed or expired bridge transaction (#201).
///
/// This provides a structured, atomic rollback path for bridge requests that
/// got stuck in `Failed`, `Expired`, or `InTransit` states. Unlike the more
/// general `recover_failed_bridge`, a rollback:
///
/// 1. Resets the request to `Recovering` (prevents concurrent rollbacks).
/// 2. Clears all collected signatures so the request cannot be accidentally
/// re-executed.
/// 3. Marks the request as `Failed` (terminal rollback state).
/// 4. Records the rollback block number for audit.
/// 5. Emits a `BridgeRolledBack` event for off-chain indexers.
///
/// Only the bridge admin may trigger a rollback.
#[ink(message)]
pub fn rollback_bridge_transaction(
&mut self,
request_id: u64,
reason: String,
) -> Result<(), Error> {
non_reentrant!(self, {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Only rollback requests that are in a non-terminal, non-completed state
match request.status {
BridgeOperationStatus::Completed => {
// Completed requests cannot be rolled back — funds already moved
return Err(Error::InvalidRequest);
}
BridgeOperationStatus::None => {
return Err(Error::InvalidRequest);
}
_ => {}
}
// Step 1: mark as Recovering to prevent concurrent rollbacks
request.status = BridgeOperationStatus::Recovering;
self.bridge_requests.insert(request_id, &request);
// Step 2: clear signatures so the request cannot be re-executed
request.signatures.clear();
// Step 3: mark as Failed (terminal rollback state)
request.status = BridgeOperationStatus::Failed;
self.bridge_requests.insert(request_id, &request);
// Step 4 + 5: emit structured rollback event for indexers
self.env().emit_event(BridgeRolledBack {
request_id,
token_id: request.token_id,
requester: request.sender,
reason,
rolled_back_at: self.env().block_number(),
});
Ok(())
})
}
/// Gets gas estimation for a bridge operation
#[ink(message)]
pub fn estimate_bridge_gas(
&self,
_token_id: TokenId,
destination_chain: ChainId,
) -> Result<u64, Error> {
let chain_info = self
.chain_info
.get(destination_chain)
.ok_or(Error::InvalidChain)?;
if !chain_info.is_active {
return Err(Error::InvalidChain);
}
let base_gas = propchain_traits::constants::BRIDGE_BASE_GAS;
let multiplier = u64::from(chain_info.gas_multiplier);
let confirmation_blocks = u64::from(chain_info.confirmation_blocks);
let adjusted_base = base_gas.saturating_mul(multiplier) / 100;
let confirmation_overhead = adjusted_base.saturating_mul(confirmation_blocks) / 100;
let estimated = adjusted_base.saturating_add(confirmation_overhead);
Ok(estimated.min(self.config.gas_limit_per_bridge))
}
/// Monitors bridge status
#[ink(message)]
pub fn monitor_bridge_status(&self, request_id: u64) -> Option<BridgeMonitoringInfo> {
let request = self.bridge_requests.get(request_id)?;
Some(BridgeMonitoringInfo {
bridge_request_id: request.request_id,
token_id: request.token_id,
source_chain: request.source_chain,
destination_chain: request.destination_chain,
status: request.status,
created_at: request.created_at,
expires_at: request.expires_at,
signatures_collected: request.signatures.len() as u8,
signatures_required: request.required_signatures,
error_message: None,
})
}
/// Verifies a bridge transaction
#[ink(message)]
pub fn verify_bridge_transaction(
&self,
transaction_hash: Hash,
_source_chain: ChainId,
) -> bool {
self.verified_transactions
.get(transaction_hash)
.unwrap_or(false)
}
/// Gets bridge history for an account
#[ink(message)]
pub fn get_bridge_history(&self, account: AccountId) -> Vec<BridgeTransaction> {
self.bridge_history.get(account).unwrap_or_default()
}
/// Quotes bridge fees for a DEX settlement.
#[ink(message)]
pub fn quote_cross_chain_trade(
&self,
destination_chain: ChainId,
amount_in: u128,
) -> Result<BridgeFeeQuote, Error> {
let chain_info = self
.chain_info
.get(destination_chain)
.ok_or(Error::InvalidChain)?;
let gas_estimate = self.estimate_bridge_gas(0, destination_chain)?;
let protocol_fee = amount_in / 200;
// Convert gas usage into an amount-based fee so totals stay in token units.
let gas_fee = if self.config.gas_limit_per_bridge == 0 {
0
} else {
let gas_ratio_bps = (u128::from(gas_estimate).saturating_mul(10_000))
/ u128::from(self.config.gas_limit_per_bridge);
let chain_risk_bps = u128::from(chain_info.confirmation_blocks).saturating_mul(10);
let adjusted_bps = gas_ratio_bps.saturating_add(chain_risk_bps).min(2_500);
amount_in.saturating_mul(adjusted_bps) / 10_000
};
Ok(BridgeFeeQuote {
destination_chain,
gas_estimate,
protocol_fee,
total_fee: protocol_fee.saturating_add(gas_fee),
})
}
/// Registers a cross-chain DEX trade intent on the bridge.
#[ink(message)]
pub fn register_cross_chain_trade(
&mut self,
pair_id: u64,
order_id: Option<u64>,
destination_chain: ChainId,
recipient: AccountId,
amount_in: u128,
min_amount_out: u128,
) -> Result<u64, Error> {
if self.config.emergency_pause {
return Err(Error::BridgePaused);
}
if !self.config.supported_chains.contains(&destination_chain) {
return Err(Error::InvalidChain);
}
// Enforce rate limiting
// For cross-chain trades, we track the volume (amount_in) but don't count it as an NFT request.
self.check_and_update_rate_limits(
self.env().caller(),
destination_chain,
amount_in,
false,
)?;
self.cross_chain_trade_counter += 1;
let trade_id = self.cross_chain_trade_counter;
let quote = self.quote_cross_chain_trade(destination_chain, amount_in)?;
let intent = CrossChainTradeIntent {
trade_id,
pair_id,
order_id,
source_chain: self.get_current_chain_id(),
destination_chain,
trader: self.env().caller(),
recipient,
amount_in,
min_amount_out,
bridge_request_id: None,
bridge_fee_quote: quote,
status: CrossChainTradeStatus::Pending,
created_at: self.env().block_timestamp(),
};
self.cross_chain_trades.insert(trade_id, &intent);
Ok(trade_id)
}
/// Attaches a bridge request to a pending cross-chain trade.
#[ink(message)]
pub fn attach_bridge_request_to_trade(
&mut self,
trade_id: u64,
bridge_request_id: u64,
) -> Result<(), Error> {
let caller = self.env().caller();
let mut trade = self
.cross_chain_trades
.get(trade_id)
.ok_or(Error::InvalidRequest)?;
if caller != trade.trader && caller != self.admin {
return Err(Error::Unauthorized);
}
trade.bridge_request_id = Some(bridge_request_id);
trade.status = CrossChainTradeStatus::BridgeRequested;
self.cross_chain_trades.insert(trade_id, &trade);
Ok(())
}
/// Marks a cross-chain trade settlement as complete.
#[ink(message)]
pub fn settle_cross_chain_trade(&mut self, trade_id: u64) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin && !self.bridge_operators.contains(&caller) {
return Err(Error::Unauthorized);
}
let mut trade = self
.cross_chain_trades
.get(trade_id)
.ok_or(Error::InvalidRequest)?;
trade.status = CrossChainTradeStatus::Settled;
self.cross_chain_trades.insert(trade_id, &trade);
Ok(())
}
/// Gets a cross-chain trade settlement intent.
#[ink(message)]
pub fn get_cross_chain_trade(&self, trade_id: u64) -> Option<CrossChainTradeIntent> {
self.cross_chain_trades.get(trade_id)
}
/// Adds a bridge operator
#[ink(message)]
pub fn add_bridge_operator(&mut self, operator: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
if !self.bridge_operators.contains(&operator) {
self.bridge_operators.push(operator);
}
Ok(())
}
/// Removes a bridge operator
#[ink(message)]
pub fn remove_bridge_operator(&mut self, operator: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.bridge_operators.retain(|op| op != &operator);
Ok(())
}
/// Checks if an account is a bridge operator
#[ink(message)]
pub fn is_bridge_operator(&self, account: AccountId) -> bool {
self.bridge_operators.contains(&account)
}
/// Gets all bridge operators
#[ink(message)]
pub fn get_bridge_operators(&self) -> Vec<AccountId> {
self.bridge_operators.clone()
}
/// Adds a validator (admin only). Only validators may sign bridge requests (issue #203).
#[ink(message)]
pub fn add_validator(&mut self, validator: AccountId) -> Result<(), Error> {
if self.env().caller() != self.admin {
return Err(Error::Unauthorized);
}
if !self.validators.contains(&validator) {
self.validators.push(validator);
}
Ok(())
}
/// Removes a validator (admin only).
#[ink(message)]
pub fn remove_validator(&mut self, validator: AccountId) -> Result<(), Error> {
if self.env().caller() != self.admin {
return Err(Error::Unauthorized);
}
self.validators.retain(|v| v != &validator);
Ok(())
}
/// Returns all registered validators.
#[ink(message)]
pub fn get_validators(&self) -> Vec<AccountId> {
self.validators.clone()
}
/// Returns whether an account is a registered validator.
#[ink(message)]
pub fn is_validator(&self, account: AccountId) -> bool {
self.validators.contains(&account)
}
/// Updates bridge configuration (admin only)
#[ink(message)]
pub fn update_config(&mut self, config: BridgeConfig) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.config = config;
Ok(())
}
/// Gets current bridge configuration
#[ink(message)]
pub fn get_config(&self) -> BridgeConfig {
self.config.clone()
}
/// Pauses or unpauses the bridge (admin only)
#[ink(message)]
pub fn set_emergency_pause(&mut self, paused: bool) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.config.emergency_pause = paused;
Ok(())
}
/// Gets chain information
#[ink(message)]
pub fn get_chain_info(&self, chain_id: ChainId) -> Option<ChainBridgeInfo> {
self.chain_info.get(chain_id)
}
/// Updates chain information (admin only)
#[ink(message)]
pub fn update_chain_info(
&mut self,
chain_id: ChainId,
info: ChainBridgeInfo,
) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.chain_info.insert(chain_id, &info);
Ok(())
}
/// Request a two-step admin rotation with cooldown.
#[ink(message)]
pub fn request_admin_rotation(&mut self, new_admin: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
let block = self.env().block_number();
let effective_at =
block.saturating_add(propchain_traits::constants::KEY_ROTATION_COOLDOWN_BLOCKS);
self.pending_admin_rotation = Some(propchain_traits::KeyRotationRequest {
old_account: caller,
new_account: new_admin,
requested_at: block,
effective_at,
confirmed: false,
});
Ok(())
}
/// Confirm a pending admin rotation after cooldown.
#[ink(message)]
pub fn confirm_admin_rotation(&mut self) -> Result<(), Error> {
let caller = self.env().caller();
let block = self.env().block_number();
let request = self
.pending_admin_rotation
.as_ref()
.ok_or(Error::InvalidRequest)?;
if request.new_account != caller {
return Err(Error::Unauthorized);
}
if block < request.effective_at {
return Err(Error::InvalidRequest);
}
let expiry = request
.effective_at
.saturating_add(propchain_traits::constants::KEY_ROTATION_EXPIRY_BLOCKS);
if block > expiry {
self.pending_admin_rotation = None;
return Err(Error::RequestExpired);
}
self.admin = caller;
self.pending_admin_rotation = None;
Ok(())
}
/// Cancel a pending admin rotation.
#[ink(message)]
pub fn cancel_admin_rotation(&mut self) -> Result<(), Error> {
let caller = self.env().caller();
let request = self
.pending_admin_rotation
.as_ref()
.ok_or(Error::InvalidRequest)?;
if caller != request.old_account && caller != request.new_account {
return Err(Error::Unauthorized);
}
self.pending_admin_rotation = None;
Ok(())
}
// Helper functions
fn is_authorized_for_token(&self, _account: AccountId, _token_id: TokenId) -> bool {
// This would typically check with the property token contract
// For now, we'll assume any account can initiate a bridge
true
}
fn get_current_chain_id(&self) -> ChainId {
// This should return the current chain ID
// For now, we'll use a default value
1
}
fn generate_transaction_hash(&self, request: &MultisigBridgeRequest) -> Hash {
let data = (
request.request_id,
request.token_id,
request.source_chain,
request.destination_chain,
request.sender,
request.recipient,
self.env().block_timestamp(),
);
propchain_traits::crypto::hash_encoded(&data)
}
fn estimate_gas_usage(&self, request: &MultisigBridgeRequest) -> u64 {
// Estimate gas usage based on request complexity
let base_gas = 100000; // Base gas for bridge operation
let metadata_gas = request.metadata.legal_description.len() as u64 * 100; // Gas for metadata
base_gas + metadata_gas
}
fn check_and_update_rate_limits(
&mut self,
account: AccountId,
destination_chain: ChainId,
amount: u128,
is_nft: bool,
) -> Result<(), Error> {
if !self.config.rate_limit_enabled {
return Ok(());
}