forked from Maki-Zeninn/stellar-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
5537 lines (4837 loc) · 199 KB
/
Copy pathlib.rs
File metadata and controls
5537 lines (4837 loc) · 199 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
#![no_std]
//! # router-core
//!
//! Central dispatcher for the stellar-router suite.
//! Routes calls to registered contracts by name, enforces access control,
//! and delegates to the registry for address resolution.
//!
//! ## Features
//! - Route calls to contracts by name (resolved via registry)
//! - Admin-controlled route registration and removal
//! - Pause/unpause individual routes or all routing
//! - Event emission on every route operation
//!
//! ## Events (following naming convention: past tense verbs in snake_case)
//! - `route_registered` — Route registered (route_name, address)
//! - `route_updated` — Route updated (route_name)
//! - `route_overwritten` — Route overwritten by same name (route_name)
//! - `route_removed` — Route removed (route_name)
//! - `route_paused` — Route paused/unpaused (route_name, paused)
//! - `route_resolve_paused` — Route resolution paused (route_name)
//! - `routed` — Route resolved (route_name, address)
//! - `router_paused` — Router globally paused/unpaused (paused)
//! - `metadata_updated` — Route metadata updated (route_name, metadata)
//! - `route_tag_added` — Route tag added (route_name, tag)
//! - `route_tag_removed` — Route tag removed (route_name, tag)
//! - `route_ttl_set` — Route TTL set at registration (route_name, expiry_ledger)
//! - `route_ttl_extended` — Route TTL extended (route_name, new_expiry_ledger)
//! - `route_resolve_expired` — Route resolution attempted on an expired route (route_name)
//! - `alias_added` — Route alias added (existing_name, alias_name)
//! - `alias_removed` — Route alias removed (alias_name)
//! - `route_scored` — Route score updated (route_name, score)
//! - `best_route_selected` — Best route selected (route_name)
//! - `admin_transferred` — Admin transferred (old_admin, new_admin)
pub mod scoring;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, Address, Env, String, Symbol, Vec,
};
#[cfg(test)]
extern crate alloc;
// ── Storage Keys ──────────────────────────────────────────────────────────────
#[contracttype]
pub enum DataKey {
Admin,
Route(String), // name -> RouteEntry
RouteNames,
RouteCount, // u32: O(1) counter kept in sync with RouteNames
Paused,
TotalRouted,
Alias(String), // alias -> original_name
Aliases, // Vec<String> of all alias names
Score(String), // name -> RouteScore
Metadata(String), // name -> RouteMetadata (stored separately; avoids nested contracttype)
Dependencies(String), // name -> Vec<String> of direct dependencies
BestRoute, // cached name of the highest-scoring non-paused route, if any
}
// ── Types ─────────────────────────────────────────────────────────────────────
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteMetadata {
/// Human-readable description (max 256 chars)
pub description: String,
/// Tags for categorization (max 5 tags)
pub tags: Vec<String>,
/// Owner address (use the zero/contract address as sentinel for "no owner")
pub owner: Address,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteEntry {
/// Resolved contract address for this route
pub address: Address,
/// Human-readable route name
pub name: String,
/// Whether this specific route is paused
pub paused: bool,
/// Who last updated this route
pub updated_by: Address,
/// Absolute ledger sequence number after which this route is expired.
/// `None` means the route is permanent (no TTL).
pub expires_at: Option<u32>,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteRegisterInput {
pub name: String,
pub address: Address,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteScoreInput {
pub name: String,
pub score: RouteScore,
}
/// Scoring attributes for a route used in path selection.
///
/// Higher scores indicate more preferred routes. The composite score is
/// computed as: `liquidity_score + reliability_score - fee_bps / 10`.
/// All fields are set by the admin and reflect off-chain measurements.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteScore {
/// Liquidity depth score (0–100). Higher = more liquid.
pub liquidity_score: u32,
/// Fee rate in basis points (e.g., 30 = 0.30%). Lower = cheaper.
pub fee_bps: u32,
/// Historical reliability score (0–100). Higher = more reliable.
pub reliability_score: u32,
}
/// Resolution-specific errors returned by [`RouterCore::batch_resolve`].
///
/// Mirrors the subset of [`RouterError`] variants that `resolve` can produce,
/// represented as a `contracttype` so it can be embedded in a `Vec`.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum ResolveError {
RouterPaused,
RouteNotFound,
RoutePaused,
NotInitialized,
RouteExpired,
}
/// Per-entry result returned by [`RouterCore::batch_resolve`].
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum BatchResolveResult {
Ok(Address),
Err(ResolveError),
}
/// Aggregate statistics about the current router state.
///
/// Returned by [`RouterCore::get_stats`]. All counters are computed in a
/// single O(n) pass over the registered route set so callers get a consistent
/// snapshot without needing to iterate routes themselves.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouterStats {
/// Total number of routes currently registered (including paused and expired).
pub total_routes: u32,
/// Routes that are neither paused nor past their TTL.
pub active_routes: u32,
/// Routes that are explicitly paused (paused flag set to true).
pub paused_routes: u32,
/// Routes whose TTL has lapsed (expires_at < current ledger sequence).
pub expired_routes: u32,
/// Number of registered aliases.
pub alias_count: u32,
/// Number of routes that have a score assigned.
pub scored_routes: u32,
}
// ── Errors ────────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum RouterError {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
RouteNotFound = 4,
RoutePaused = 5,
RouterPaused = 6,
RouteAlreadyExists = 7,
InvalidRouteName = 8,
InvalidMetadata = 9,
CircularDependency = 10,
RouteInUse = 11,
InvalidAddress = 12,
RouteExpired = 13,
InvalidScore = 14,
InvalidTtlExtension = 15,
RecursionLimitExceeded = 15,
}
/// Maximum allowed recursion depth for dependency resolution.
const MAX_RECURSION_DEPTH: u32 = 10;
// ── Constants ─────────────────────────────────────────────────────────────────
/// Minimum remaining TTL (in ledgers) before instance storage is extended.
/// ~30 days at 5 s/ledger.
const INSTANCE_TTL_THRESHOLD: u32 = 17280 * 30;
/// Target TTL (in ledgers) applied to instance storage on every entry point.
/// ~60 days at 5 s/ledger.
const INSTANCE_TTL_EXTEND_TO: u32 = 17280 * 60;
// ── Contract ──────────────────────────────────────────────────────────────────
/// Returns `true` if `entry` has a TTL set and the current ledger sequence
/// number exceeds its expiry ledger. Routes with `expires_at: None` never expire.
pub(crate) fn is_route_expired(env: &Env, entry: &RouteEntry) -> bool {
entry
.expires_at
.is_some_and(|exp| env.ledger().sequence() > exp)
}
#[contract]
pub struct RouterCore;
#[contractimpl]
impl RouterCore {
/// Initialize the router with an admin address.
///
/// Sets up the admin, marks the router as unpaused, and resets the total
/// routed counter to zero. Must be called exactly once before any other
/// function.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `admin` - The address that will have admin privileges over this router.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::AlreadyInitialized`] — if the contract has already been initialized.
pub fn initialize(env: Env, admin: Address) -> Result<(), RouterError> {
admin.require_auth();
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
if env.storage().instance().has(&DataKey::Admin) {
return Err(RouterError::AlreadyInitialized);
}
env.storage().instance().set(&DataKey::Admin, &admin);
env.storage()
.instance()
.set(&DataKey::RouteNames, &Vec::<String>::new(&env));
env.storage()
.instance()
.set(&DataKey::Aliases, &Vec::<String>::new(&env));
env.storage().instance().set(&DataKey::Paused, &false);
env.storage().instance().set(&DataKey::TotalRouted, &0u64);
env.storage().instance().set(&DataKey::RouteCount, &0u32);
Ok(())
}
/// Register a new route by name pointing to a contract address.
///
/// Associates a human-readable `name` with a target contract `address`.
/// The route starts in an unpaused state. Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `name` - A unique human-readable identifier for the route. Must not be empty or whitespace-only.
/// * `address` - The contract address this route resolves to.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteAlreadyExists`] — if a route with `name` already exists.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn register_route(
env: Env,
caller: Address,
name: String,
address: Address,
metadata: Option<RouteMetadata>,
) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
// Use shared validation helper
Self::validate_route_name(&env, &name)?;
// Validate address is not the zero address
let zero_address = Address::from_string(&String::from_str(
&env,
"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
));
if address == zero_address {
return Err(RouterError::InvalidAddress);
}
// Validate metadata if provided
if let Some(ref meta) = metadata {
if meta.description.len() > 256 {
return Err(RouterError::InvalidMetadata);
}
if meta.tags.len() > 5 {
return Err(RouterError::InvalidMetadata);
}
}
let entry = RouteEntry {
address,
name: name.clone(),
paused: false,
updated_by: caller,
expires_at: None,
};
env.storage()
.instance()
.set(&DataKey::Route(name.clone()), &entry);
if let Some(meta) = metadata {
env.storage()
.instance()
.set(&DataKey::Metadata(name.clone()), &meta);
}
let mut route_names = Self::get_route_names(&env);
route_names.push_back(name.clone());
env.storage()
.instance()
.set(&DataKey::RouteNames, &route_names);
let count: u32 = env
.storage()
.instance()
.get(&DataKey::RouteCount)
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::RouteCount, &(count + 1));
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_REGISTERED),),
(name.clone(), entry.address.clone()),
);
Ok(())
}
/// Register a new route by name with an optional time-to-live.
///
/// Like [`register_route`](Self::register_route), but accepts `ttl_ledgers`
/// to make the route expire automatically. If `ttl_ledgers` is `Some(n)`,
/// the route's expiry is set to `n` ledgers from the current ledger
/// sequence number; once the ledger sequence exceeds that value, [`resolve`](Self::resolve)
/// returns [`RouterError::RouteExpired`] and the route is excluded from
/// [`get_all_routes`](Self::get_all_routes). If `ttl_ledgers` is `None`, the
/// route is permanent, identical to `register_route`.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `name` - A unique human-readable identifier for the route.
/// * `address` - The contract address this route resolves to.
/// * `ttl_ledgers` - Number of ledgers from now until expiry, or `None` for no expiry.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteAlreadyExists`] — if a route with `name` already exists.
/// * [`RouterError::InvalidRouteName`] — if `name` is invalid.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn register_route_with_ttl(
env: Env,
caller: Address,
name: String,
address: Address,
ttl_ledgers: Option<u32>,
) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
let expires_at = ttl_ledgers.map(|ttl| env.ledger().sequence().saturating_add(ttl));
Self::register_route_internal(&env, &caller, name.clone(), address, None, expires_at)?;
if let Some(exp) = expires_at {
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_TTL_SET),),
(name, exp),
);
}
Ok(())
}
/// Get the expiry ledger sequence number for a route.
///
/// Returns `None` if the route does not exist or has no TTL (permanent).
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `name` - The name of the route.
///
/// # Returns
/// `Some(expiry_ledger)` if the route has a TTL, `None` otherwise.
pub fn get_route_expiry(env: Env, name: String) -> Option<u32> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
env.storage()
.instance()
.get::<DataKey, RouteEntry>(&DataKey::Route(name))
.and_then(|entry| entry.expires_at)
}
/// Extend the TTL of a route that has not yet expired.
///
/// If the route currently has a TTL, the new expiry is `additional_ledgers`
/// past its existing expiry (extensions stack). If the route is permanent
/// (no TTL set), this gives it a TTL of `additional_ledgers` ledgers from
/// now. Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `name` - The name of the route to extend.
/// * `additional_ledgers` - Number of ledgers to add to the route's expiry.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteNotFound`] — if no route with `name` exists.
/// * [`RouterError::RouteExpired`] — if the route has already expired; extend before expiry.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn extend_route_ttl(
env: Env,
caller: Address,
name: String,
additional_ledgers: u32,
) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
if additional_ledgers == 0 {
return Err(RouterError::InvalidTtlExtension);
}
let mut entry: RouteEntry = env
.storage()
.instance()
.get(&DataKey::Route(name.clone()))
.ok_or(RouterError::RouteNotFound)?;
if is_route_expired(&env, &entry) {
return Err(RouterError::RouteExpired);
}
let current_ledger = env.ledger().sequence();
let base = entry.expires_at.unwrap_or(current_ledger);
let new_expiry = base.saturating_add(additional_ledgers);
entry.expires_at = Some(new_expiry);
entry.updated_by = caller;
env.storage()
.instance()
.set(&DataKey::Route(name.clone()), &entry);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_TTL_EXTENDED),),
(name, new_expiry),
);
Ok(())
}
/// Update an existing route to point to a new address.
///
/// Replaces the contract address for an existing route. The route must
/// already exist. Caller must be the admin. Emits both a `route_updated`
/// event and a `route_overwritten` event carrying the old and new addresses
/// so that off-chain observers can detect unintended redirections.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `name` - The name of the route to update.
/// * `new_address` - The new contract address for this route.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteNotFound`] — if no route with `name` exists.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn update_route(
env: Env,
caller: Address,
name: String,
new_address: Address,
) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
let mut entry: RouteEntry = env
.storage()
.instance()
.get(&DataKey::Route(name.clone()))
.ok_or(RouterError::RouteNotFound)?;
let old_address = entry.address.clone();
entry.address = new_address.clone();
entry.updated_by = caller;
env.storage()
.instance()
.set(&DataKey::Route(name.clone()), &entry);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_UPDATED),),
name.clone(),
);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_OVERWRITTEN),),
(name.clone(), old_address, new_address),
);
Ok(())
}
/// Remove a route entirely.
///
/// Deletes the route entry for `name` from storage and removes any aliases
/// that point to this route. Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `name` - The name of the route to remove.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteNotFound`] — if no route with `name` exists.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn remove_route(env: Env, caller: Address, name: String) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
if !env.storage().instance().has(&DataKey::Route(name.clone())) {
return Err(RouterError::RouteNotFound);
}
let route_names = Self::get_route_names(&env);
for dependent_name in route_names.iter() {
if dependent_name != name {
let dependencies = Self::get_dependencies_for_route(&env, dependent_name.clone());
for dependency in dependencies.iter() {
if dependency == name {
return Err(RouterError::RouteInUse);
}
}
}
}
env.storage()
.instance()
.remove(&DataKey::Route(name.clone()));
env.storage()
.instance()
.remove(&DataKey::Metadata(name.clone()));
let route_names = Self::get_route_names(&env);
let mut updated_route_names = Vec::new(&env);
for route_name in route_names.iter() {
if route_name != name {
updated_route_names.push_back(route_name);
}
}
env.storage()
.instance()
.set(&DataKey::RouteNames, &updated_route_names);
let count: u32 = env
.storage()
.instance()
.get(&DataKey::RouteCount)
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::RouteCount, &count.saturating_sub(1));
// Clean up any aliases pointing to this route
Self::remove_aliases_for_route(&env, &name);
// Removing a route may invalidate the cached best route; refresh it.
Self::recompute_best_route(&env);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_REMOVED),),
name.clone(),
);
Ok(())
}
/// Register multiple routes in a single transaction.
///
/// Associates multiple human-readable names with target contract addresses
/// in a single atomic operation. All routes start in an unpaused state.
/// Caller must be the admin. If any route fails validation, the entire
/// batch fails and no routes are registered.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `routes` - A vector of tuples (name, address, metadata) for each route to register.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteAlreadyExists`] — if any route name already exists.
/// * [`RouterError::InvalidRouteName`] — if any route name is empty or whitespace-only.
/// * [`RouterError::InvalidMetadata`] — if any metadata is invalid.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn register_routes_batch(
env: Env,
caller: Address,
routes: Vec<RouteRegisterInput>,
fail_fast: bool,
) -> Result<router_common::BatchResult, RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
let mut result = router_common::BatchResult::new(&env);
if fail_fast {
let mut seen = Vec::new(&env);
for (index, route) in routes.iter().enumerate() {
let idx = index as u32;
if seen.contains(&route.name) {
result.record_failure(idx, router_common::BatchItemError::AlreadyExists);
return Ok(result);
}
if let Err(err) = Self::validate_route_name(&env, &route.name) {
result.record_failure(idx, Self::router_error_to_batch(&env, err));
return Ok(result);
}
if env
.storage()
.instance()
.has(&DataKey::Route(route.name.clone()))
{
result.record_failure(idx, router_common::BatchItemError::AlreadyExists);
return Ok(result);
}
seen.push_back(route.name.clone());
}
for (index, route) in routes.iter().enumerate() {
Self::register_route_internal(
&env,
&caller,
route.name.clone(),
route.address.clone(),
None,
None,
)?;
result.record_success(index as u32);
}
} else {
for (index, route) in routes.iter().enumerate() {
let idx = index as u32;
match Self::register_route_internal(
&env,
&caller,
route.name.clone(),
route.address.clone(),
None,
None,
) {
Ok(()) => result.record_success(idx),
Err(err) => {
result.record_failure(idx, Self::router_error_to_batch(&env, err));
}
}
}
}
Ok(result)
}
/// Remove multiple routes in a single transaction.
///
/// Deletes route entries for all specified names from storage and removes
/// any aliases that point to these routes. Caller must be the admin.
/// If any route is not found, the entire batch fails and no routes are removed.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `names` - A vector of route names to remove.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteNotFound`] — if any route name does not exist.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn remove_routes_batch(
env: Env,
caller: Address,
names: Vec<String>,
fail_fast: bool,
) -> Result<router_common::BatchResult, RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
let mut result = router_common::BatchResult::new(&env);
if fail_fast {
for (index, name) in names.iter().enumerate() {
let idx = index as u32;
if !env.storage().instance().has(&DataKey::Route(name.clone())) {
result.record_failure(idx, router_common::BatchItemError::AlreadyExists);
return Ok(result);
}
}
for (index, name) in names.iter().enumerate() {
Self::remove_route_internal(&env, name.clone())?;
result.record_success(index as u32);
}
} else {
for (index, name) in names.iter().enumerate() {
let idx = index as u32;
match Self::remove_route_internal(&env, name.clone()) {
Ok(()) => result.record_success(idx),
Err(err) => {
result.record_failure(idx, Self::router_error_to_batch(&env, err));
}
}
}
}
// Removing routes may invalidate the cached best route; refresh it once.
Self::recompute_best_route(&env);
Ok(result)
}
/// Resolve a route name to its contract address.
///
/// Looks up the contract address registered under `name`, validates that
/// neither the router nor the individual route is paused or expired,
/// increments the total-routed counter, and emits a `routed` event. If
/// `name` is an alias, resolves to the original route.
///
/// When scored routes exist, score-based selection is applied via a cached
/// best-route key (maintained on score/pause/removal changes): the
/// highest-scoring non-paused, non-expired route is returned automatically
/// in O(1). If no scored, eligible route exists, falls back to the direct
/// lookup by `name`.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `name` - The name of the route to resolve.
///
/// # Returns
/// The [`Address`] of the contract registered under `name`.
///
/// # Errors
/// * [`RouterError::RouterPaused`] — if the entire router is paused.
/// * [`RouterError::RouteNotFound`] — if no route with `name` exists.
/// * [`RouterError::RoutePaused`] — if the specific route is paused.
/// * [`RouterError::RouteExpired`] — if the route's TTL has lapsed.
pub fn resolve(env: Env, name: String) -> Result<Address, RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
let paused: bool = env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false);
if paused {
return Err(RouterError::RouterPaused);
}
// Resolve alias if present
let (resolved_name, alias_used) = if let Some(original) = env
.storage()
.instance()
.get::<DataKey, String>(&DataKey::Alias(name.clone()))
{
(original, true)
} else {
(name.clone(), false)
};
if alias_used {
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ALIAS_RESOLVED),),
(name.clone(), resolved_name.clone()),
);
}
// Score-based selection: the best non-paused scored route is maintained
// in a cached storage key (DataKey::BestRoute), updated whenever scores,
// pause state, or routes change. This keeps resolution O(1) instead of
// scanning the entire RouteNames vector on every call. If no scored,
// non-paused route exists, the cache is absent and we fall back to the
// directly requested route.
//
// Unlike pausing, TTL expiry is not a write — a route can lapse purely
// from ledger time passing with no event to trigger a cache refresh.
// So the cached pointer is re-validated against expiry on every read;
// if it has gone stale, this call falls back to the requested route
// instead of trusting an expired cache entry.
let final_name = env
.storage()
.instance()
.get::<DataKey, String>(&DataKey::BestRoute)
.filter(|best| {
env.storage()
.instance()
.get::<DataKey, RouteEntry>(&DataKey::Route(best.clone()))
.map(|e| !is_route_expired(&env, &e))
.unwrap_or(false)
})
.unwrap_or(resolved_name);
let entry: RouteEntry = env
.storage()
.instance()
.get(&DataKey::Route(final_name.clone()))
.ok_or(RouterError::RouteNotFound)?;
if is_route_expired(&env, &entry) {
env.events().publish(
(Symbol::new(
&env,
router_common::EVENT_ROUTE_RESOLVE_EXPIRED,
),),
(final_name.clone(),),
);
return Err(RouterError::RouteExpired);
}
if entry.paused {
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_RESOLVE_PAUSED),),
(final_name.clone(),),
);
return Err(RouterError::RoutePaused);
}
// Increment total routed counter
let total: u64 = env
.storage()
.instance()
.get(&DataKey::TotalRouted)
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::TotalRouted, &(total + 1));
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTED),),
(name.clone(), entry.address.clone()),
);
Ok(entry.address)
}
/// Pause or unpause a specific route.
///
/// When a route is paused, calls to `resolve` for that route will
/// return [`RouterError::RoutePaused`]. Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `name` - The name of the route to pause or unpause.
/// * `paused` - `true` to pause the route, `false` to unpause it.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::RouteNotFound`] — if no route with `name` exists.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn set_route_paused(
env: Env,
caller: Address,
name: String,
paused: bool,
) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
let mut entry: RouteEntry = env
.storage()
.instance()
.get(&DataKey::Route(name.clone()))
.ok_or(RouterError::RouteNotFound)?;
entry.paused = paused;
entry.updated_by = caller.clone();
env.storage()
.instance()
.set(&DataKey::Route(name.clone()), &entry);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTE_PAUSED),),
(name.clone(), paused),
);
// Pause state affects best-route eligibility; refresh the cache.
Self::recompute_best_route(&env);
Ok(())
}
/// Pause or unpause the entire router.
///
/// When the router is paused, all calls to `resolve` will return
/// [`RouterError::RouterPaused`] regardless of individual route state.
/// Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `paused` - `true` to pause the router, `false` to unpause it.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`RouterError::Unauthorized`] — if `caller` is not the admin.
/// * [`RouterError::NotInitialized`] — if the contract has not been initialized.
pub fn set_paused(env: Env, caller: Address, paused: bool) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
env.storage().instance().set(&DataKey::Paused, &paused);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROUTER_PAUSED),),
paused,
);
Ok(())
}
/// Get a route entry by name.
///
/// Returns the full [`RouteEntry`] for the given `name`, or `None` if no
/// such route is registered.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `name` - The name of the route to look up.
///
/// # Returns
/// `Some(`[`RouteEntry`]`)` if the route exists, `None` otherwise.
pub fn get_route(env: Env, name: String) -> Option<RouteEntry> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
env.storage().instance().get(&DataKey::Route(name))
}
/// Associate a route with a required dependency.
///
/// The dependency is stored as a direct prerequisite for `route`. The
/// dependency must already exist, and adding the edge must not introduce a
/// cycle. Caller must be the admin.
pub fn set_route_dependency(
env: Env,
caller: Address,
route: String,
depends_on: String,
) -> Result<(), RouterError> {
router_common::extend_instance_ttl(&env, INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, RouterError)?;
if !env.storage().instance().has(&DataKey::Route(route.clone())) {
return Err(RouterError::RouteNotFound);
}
if !env
.storage()
.instance()
.has(&DataKey::Route(depends_on.clone()))
{
return Err(RouterError::RouteNotFound);