forked from StableRoute-Org/Stableroute-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
4370 lines (3996 loc) · 168 KB
/
Copy pathlib.rs
File metadata and controls
4370 lines (3996 loc) · 168 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(deprecated)] // TODO: migrate Soroban events to #[contractevent].
#![no_std]
// Contributing? See CONTRIBUTING.md for error-numbering, event-topic, auth,
// pause, and storage/TTL conventions plus the PR checklist.
#[cfg(test)]
extern crate std;
use soroban_sdk::xdr::ToXdr;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, panic_with_error, symbol_short, Address,
Bytes, BytesN, Env, Symbol, Vec,
};
/// Aggregated read of every pair-scoped storage slot (base fields).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PairInfo {
pub registered: bool,
pub fee_bps: u32,
pub min_amount: i128,
pub max_amount: i128,
pub liquidity: i128,
pub last_route_at: u64,
}
/// Extended aggregate read of every pair-scoped storage slot, including
/// cooldown, route count, and cumulative volume. See [`PairInfo`] for the
/// original (base) field set.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PairInfoExt {
pub registered: bool,
pub fee_bps: u32,
pub min_amount: i128,
pub max_amount: i128,
pub liquidity: i128,
pub last_route_at: u64,
pub cooldown_secs: u64,
pub route_count: u64,
pub volume: i128,
}
/// Aggregated read of the queued admin handover: the proposed pending
/// admin and the earliest timestamp at which it may accept.
///
/// Returned by [`StableRouteRouter::get_pending_admin_info`] so watchers
/// get both slots from a single invocation. Both fields are `None` when
/// no transfer is queued.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PendingAdminInfo {
/// Address proposed via `propose_admin_transfer`, if any.
pub pending: Option<Address>,
/// Earliest ledger timestamp at which the pending admin may call
/// `accept_admin_transfer` (`propose` time + timelock), if queued.
pub eta: Option<u64>,
}
/// Storage keys used by the StableRoute router. All twenty variants live
/// in persistent storage — no instance or temporary storage is used today.
///
/// See [`docs/storage.md`] for the authoritative reference: key shape,
/// value type, default-when-absent, reader/writer entrypoints, and TTL
/// classification (Static / Config / Hot).
///
/// ## Sentinel conventions
///
/// - Absent `bool` → `false` (pair registration, paused, reentrancy lock).
/// - `i128::MAX` → "unbounded" sentinel for `PairMaxAmount` and for
/// liquidity *inside `compute_route_fee` only*.
/// - `0` → default for counters, fees, timestamps (as `u64`),
/// `PairMinAmount`, and cooldowns.
/// - Absent `Option` → `None` (admin, pending admin, fee recipient,
/// last-route timestamp, max fee absolute, oracle).
/// - `SchemaVersion` → `1` when absent (the implicit pre-migration default).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataKey {
/// Operational admin (singleton, `Address`, persistent).
/// Set once by `__constructor`; only changed by a two-step handover
/// (`propose_admin_transfer` → `accept_admin_transfer`).
/// Absent reads panic with `NotInitialized` (#2).
Admin,
/// `true` if `(source, destination)` is a recognised route.
/// Keyed per-pair; stored as `bool` so callers can query without
/// distinguishing "absent" from "false". Defaults to `false`.
Pair(Symbol, Symbol),
/// Per-pair fee in basis points (1 bps = 0.01 %). Stored as `u32`
/// so the on-the-wire shape is fixed; values above `MAX_FEE_BPS`
/// are rejected at write time. Defaults to `0` (free).
PairFeeBps(Symbol, Symbol),
/// Pending admin proposed via `propose_admin_transfer` (singleton,
/// `Address`, persistent). Two-step handover guards against locking
/// the contract with a bad key. Absent ↔ `None` (no handover queued).
PendingAdmin,
/// `true` when the router is paused (singleton, `bool`, persistent).
/// All state-changing entrypoints reject calls until an unpause.
/// Defaults to `false` (not paused).
Paused,
/// Minimum routable amount per pair in source units (keyed per-pair,
/// `i128`, persistent). `compute_route_fee` rejects amounts below the
/// floor. Defaults to `0` (no floor).
PairMinAmount(Symbol, Symbol),
/// Maximum routable amount per pair in source units (keyed per-pair,
/// `i128`, persistent). `compute_route_fee` rejects amounts above the
/// ceiling. Defaults to `i128::MAX` (no ceiling).
PairMaxAmount(Symbol, Symbol),
/// Reported available liquidity in source units per pair (keyed
/// per-pair, `i128`, persistent). Updated by an off-chain oracle
/// (or the admin) via `set_pair_liquidity`; decremented on every
/// successful `compute_route_fee`. Default is context-dependent:
/// `get_pair_liquidity` returns `0` for absent, while
/// `compute_route_fee` treats absent as `i128::MAX` (unbounded).
PairLiquidity(Symbol, Symbol),
/// Address that receives protocol fees on settlement (singleton,
/// `Address`, persistent). Absent ↔ `None`.
FeeRecipient,
/// Protocol-wide lifetime counter of `compute_route_fee` invocations
/// (singleton, `u64`, persistent). Incremented with `saturating_add`
/// so it is monotonic and never panics. Defaults to `0`.
TotalRoutesAllTime,
/// Ledger timestamp of the most recent `compute_route_fee` for a
/// pair (keyed per-pair, `u64`, persistent). Used by the cooldown
/// rate-limit gate. Absent reads as `None` (`Option`); `get_pair_info`
/// flattens it to `0`.
PairLastRouteAt(Symbol, Symbol),
/// Per-pair lifetime counter of `compute_route_fee` invocations
/// (keyed per-pair, `u64`, persistent). Incremented with
/// `saturating_add` so it is monotonic and never panics on overflow.
/// Defaults to `0`.
PairRouteCount(Symbol, Symbol),
/// Per-pair cumulative routed volume — sum of `amount` in source
/// units (keyed per-pair, `i128`, persistent). Accumulated with
/// `saturating_add` so it is monotonic and never panics on overflow.
/// Defaults to `0`.
PairVolume(Symbol, Symbol),
/// On-chain storage schema version (singleton, `u32`, persistent).
/// Distinct from `version()`. Defaults to `1` when absent (the
/// implicit pre-migration layout). Advanced to `2` by
/// `migrate_v1_to_v2`.
SchemaVersion,
/// Governance timelock delay in seconds (singleton, `u64`,
/// persistent). When > 0, a proposed admin handover can only be
/// accepted after the delay has elapsed. Defaults to `0` (instant)
/// when unset, preserving prior behaviour.
Timelock,
/// Earliest ledger timestamp at which the currently pending admin
/// transfer may be accepted — `propose_admin_transfer` time + delay
/// (singleton, `u64`, persistent). Absent ↔ `None` (no handover
/// queued).
PendingAdminEta,
/// Non-reentrancy guard (singleton, `bool`, persistent). Set to
/// `true` before the write/event phase of `compute_route_fee` and
/// cleared to `false` on exit. Defaults to `false`.
ReentrancyLock,
/// Per-pair cooldown in seconds between route accounting calls
/// (keyed per-pair, `u64`, persistent). While non-zero,
/// `compute_route_fee` rejects a call until at least this many
/// seconds have elapsed since `PairLastRouteAt`. Capped at
/// `MAX_COOLDOWN_SECS` (30 days). Defaults to `0` (disabled).
PairCooldown(Symbol, Symbol),
/// Optional absolute per-route fee ceiling (singleton, `i128`,
/// persistent). When set, the effective fee is `min(bps_fee, cap)`.
/// Absent ↔ `None` (only the relative `MAX_FEE_BPS` bound applies).
MaxFeeAbsolute,
/// Scoped liquidity oracle address (singleton, `Address`,
/// persistent). The oracle may call `set_pair_liquidity` and
/// nothing else — it cannot set fees, pause, rotate admin, or
/// upgrade. Absent ↔ `None` (no oracle configured — admin-only
/// liquidity feed).
Oracle,
}
/// Upper bound on the per-pair fee. 1 000 bps = 10 %. Tightening this
/// further is a governance decision; raising it is append-only safe
/// but should be deliberate.
pub const MAX_FEE_BPS: u32 = 1_000;
/// Basis-point denominator: 1 bps = 1/10_000.
pub const BPS_DENOMINATOR: i128 = 10_000;
/// Maximum number of entries in a single batch operation
/// (`register_pairs`, `set_pair_fees_bps`). Kept modest to bound
/// per-transaction gas costs.
pub const MAX_BATCH_SIZE: u32 = 100;
/// Upper bound on the per-pair route cooldown, in seconds (30 days).
/// `set_pair_cooldown` rejects any larger value so a fat-fingered or
/// malicious config write (e.g. `u64::MAX`) cannot permanently brick a
/// corridor by making `compute_route_fee`'s `last + cooldown` gate
/// unreachable. Ledger timestamps are seconds since epoch and are nowhere
/// near `u64::MAX - MAX_COOLDOWN_SECS`, so capping here also guarantees
/// the `last + cooldown` addition in `compute_route_fee` cannot overflow
/// `u64` for the foreseeable future.
pub const MAX_COOLDOWN_SECS: u64 = 2_592_000;
/// Typed contract errors. Codes are append-only — never reuse or
/// renumber a variant once it has shipped.
#[contracterror]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u32)]
pub enum RouterError {
/// `init` was called but the admin address is already stored.
AlreadyInitialized = 1,
/// A read or write expected the admin to be set but it was not.
NotInitialized = 2,
/// `register_pair` was called with `source == destination`.
SourceEqualsDestination = 3,
/// `set_pair_fee_bps` was called with a value above [`MAX_FEE_BPS`].
FeeBpsTooHigh = 4,
/// `compute_route_fee` was called for a pair that was never registered.
PairNotRegistered = 5,
/// `compute_route_fee` was called with a non-positive amount.
AmountMustBePositive = 6,
/// `accept_admin_transfer` was called with no pending admin.
NoPendingAdminTransfer = 7,
/// `accept_admin_transfer` was called by a non-pending address.
NotPendingAdmin = 8,
/// A state-changing entrypoint was called while paused.
ContractPaused = 9,
/// Amount is below the configured PairMinAmount.
AmountBelowMin = 10,
/// Amount is above the configured PairMaxAmount.
AmountAboveMax = 11,
/// Reported pair liquidity is below the requested amount.
InsufficientLiquidity = 12,
/// `migrate_v1_to_v2` was called from a non-v1 schema.
MigrationVersionMismatch = 13,
/// `accept_admin_transfer` was called before the governance timelock
/// delay elapsed.
TimelockNotElapsed = 14,
/// A non-reentrant entrypoint was entered while already locked.
ReentrantCall = 15,
/// Caller was neither the admin nor the scoped oracle.
NotAuthorized = 16,
/// Per-pair cooldown has not elapsed since the last route.
RouteCooldownActive = 17,
/// `register_pairs` or `set_pair_fees_bps` was called with a batch
/// exceeding [`MAX_BATCH_SIZE`] entries.
BatchTooLarge = 18,
/// `register_pairs` or `set_pair_fees_bps` was called with an empty
/// batch.
EmptyBatch = 19,
/// `set_pair_cooldown` was called with a value above
/// [`MAX_COOLDOWN_SECS`].
CooldownTooLarge = 20,
}
/// StableRoute router contract — placeholder for routing logic.
/// In production this would integrate with path payments and liquidity data.
#[contract]
pub struct StableRouteRouter;
#[contractimpl]
impl StableRouteRouter {
/// Load the admin address, require its auth, and return it.
///
/// Every admin-gated entrypoint calls this instead of repeating the
/// six-line load-unwrap-require_auth block. Keeping it private
/// ensures it never appears in the generated client ABI.
fn require_admin(env: &Env) -> Address {
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, RouterError::NotInitialized));
admin.require_auth();
admin
}
/// Require that `(source, destination)` was previously registered via
/// [`Self::register_pair`]; panics with
/// [`RouterError::PairNotRegistered`] otherwise.
///
/// Every per-pair config setter (`set_pair_fee_bps`,
/// `set_pair_min_amount`, `set_pair_max_amount`, `set_pair_liquidity`)
/// calls this after its own admin/sign validation so a config write can
/// never create an orphan storage slot for a corridor an operator never
/// registered. Reuses the same [`RouterError::PairNotRegistered`] (#5)
/// that `compute_route_fee` and `quote_route` already raise, keeping
/// one error code for "this pair does not exist" across the contract.
fn require_pair_registered(env: &Env, source: &Symbol, destination: &Symbol) {
if !env
.storage()
.persistent()
.get::<_, bool>(&DataKey::Pair(source.clone(), destination.clone()))
.unwrap_or(false)
{
panic_with_error!(env, RouterError::PairNotRegistered);
}
}
/// Acquire the reentrancy lock; panics [`RouterError::ReentrantCall`]
/// if already held. Paired with [`Self::exit_nonreentrant`] on every
/// return path so that a re-entrant invocation (for example via a
/// future malicious token callback) is rejected instead of operating
/// on partially-applied effects.
fn enter_nonreentrant(env: &Env) {
if env
.storage()
.persistent()
.get(&DataKey::ReentrancyLock)
.unwrap_or(false)
{
panic_with_error!(env, RouterError::ReentrantCall);
}
env.storage()
.persistent()
.set(&DataKey::ReentrancyLock, &true);
}
/// Release the reentrancy lock. Must be called before every return
/// from a guarded entrypoint, including the success path, so that
/// back-to-back calls work.
fn exit_nonreentrant(env: &Env) {
env.storage()
.persistent()
.set(&DataKey::ReentrancyLock, &false);
}
/// Returns the router contract version.
pub fn version(_env: Env) -> Symbol {
symbol_short!("ROUTER_V2")
}
/// Read the persisted schema version, or 1 if absent (the implicit
/// pre-migration default).
pub fn get_schema_version(env: Env) -> u32 {
env.storage()
.persistent()
.get(&DataKey::SchemaVersion)
.unwrap_or(1)
}
/// Migrate the schema from v1 to v2. Admin-gated; panics with
/// MigrationVersionMismatch on a non-v1 starting state. v2 readers
/// default sensibly when their new slots are absent, so the body
/// only stamps the new SchemaVersion.
pub fn migrate_v1_to_v2(env: Env) {
Self::require_admin(&env);
let current: u32 = env
.storage()
.persistent()
.get(&DataKey::SchemaVersion)
.unwrap_or(1);
if current != 1 {
panic_with_error!(&env, RouterError::MigrationVersionMismatch);
}
env.storage()
.persistent()
.set(&DataKey::SchemaVersion, &2u32);
}
/// Deploy-time constructor — sets the operational admin **atomically**
/// at contract instantiation.
///
/// Running as the constructor closes the init front-running window:
/// the admin slot is written in the same transaction that deploys the
/// contract (`register(StableRouteRouter, (admin,))`), so there is no
/// observable deployed-but-uninitialized state for an attacker to race
/// a separate `init` call into. Requires `admin.require_auth()` and
/// emits the `init` event for indexers.
pub fn __constructor(env: Env, admin: Address) {
admin.require_auth();
env.storage().persistent().set(&DataKey::Admin, &admin);
env.events().publish((symbol_short!("init"),), admin);
}
/// Legacy initializer, retained for ABI compatibility only.
///
/// The admin is now set by [`Self::__constructor`] at deploy time, so
/// the slot is always populated and this entrypoint can never claim
/// it. It unconditionally panics with
/// [`RouterError::AlreadyInitialized`], preserving the historical
/// `#1` semantics for any client still calling `init` post-deploy and
/// guaranteeing an attacker can never seize the admin role via `init`.
pub fn init(env: Env, admin: Address) {
let _ = admin;
panic_with_error!(&env, RouterError::AlreadyInitialized);
}
/// Returns true iff the router is currently paused.
pub fn is_paused(env: Env) -> bool {
env.storage()
.persistent()
.get(&DataKey::Paused)
.unwrap_or(false)
}
/// Resume after a pause. Admin-gated and idempotent.
pub fn unpause(env: Env) {
Self::require_admin(&env);
env.storage().persistent().set(&DataKey::Paused, &false);
env.events().publish((symbol_short!("paused"),), false);
}
/// Admin pauses the router. All state-changing entrypoints will
/// then panic with ContractPaused.
pub fn pause(env: Env) {
Self::require_admin(&env);
env.storage().persistent().set(&DataKey::Paused, &true);
env.events().publish((symbol_short!("paused"),), true);
}
/// Read the configured governance timelock delay, in seconds
/// (0 when unset — handover is instant).
pub fn get_timelock(env: Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::Timelock)
.unwrap_or(0)
}
/// Admin sets the governance timelock delay (seconds). Applies to the
/// **next** `propose_admin_transfer`; already-queued actions keep the
/// eta they were stamped with. Pass 0 to disable (instant handover).
pub fn set_timelock(env: Env, delay_seconds: u64) {
Self::require_admin(&env);
env.storage()
.persistent()
.set(&DataKey::Timelock, &delay_seconds);
}
/// Read the earliest timestamp at which the pending admin transfer may
/// be accepted, or `None` when no transfer is queued.
pub fn get_pending_admin_eta(env: Env) -> Option<u64> {
env.storage().persistent().get(&DataKey::PendingAdminEta)
}
/// Cancel a pending handover, clearing both the pending admin and its
/// queued eta. No-op if none is pending.
pub fn cancel_admin_transfer(env: Env) {
Self::require_admin(&env);
env.storage().persistent().remove(&DataKey::PendingAdmin);
env.storage().persistent().remove(&DataKey::PendingAdminEta);
}
/// Read the pending admin if any.
pub fn get_pending_admin(env: Env) -> Option<Address> {
env.storage().persistent().get(&DataKey::PendingAdmin)
}
/// Read both components of the queued admin handover in one call.
///
/// Returns a consistent snapshot of the pending admin and its
/// earliest acceptance timestamp (ETA). Both fields are `None`
/// when no transfer is queued.
pub fn get_pending_admin_info(env: Env) -> PendingAdminInfo {
let s = env.storage().persistent();
PendingAdminInfo {
pending: s.get(&DataKey::PendingAdmin),
eta: s.get(&DataKey::PendingAdminEta),
}
}
/// Step 2 of admin handover. The pending admin claims the role
/// from their own key. Panics with NoPendingAdminTransfer if none
/// is pending or NotPendingAdmin if the caller does not match.
pub fn accept_admin_transfer(env: Env, caller: Address) {
caller.require_auth();
let pending: Address = env
.storage()
.persistent()
.get(&DataKey::PendingAdmin)
.unwrap_or_else(|| panic_with_error!(&env, RouterError::NoPendingAdminTransfer));
if pending != caller {
panic_with_error!(&env, RouterError::NotPendingAdmin);
}
// Honour the governance timelock: the handover cannot execute until
// its stamped eta has been reached.
let eta: u64 = env
.storage()
.persistent()
.get(&DataKey::PendingAdminEta)
.unwrap_or(0);
if env.ledger().timestamp() < eta {
panic_with_error!(&env, RouterError::TimelockNotElapsed);
}
env.storage()
.persistent()
.set(&DataKey::Admin, &caller.clone());
env.storage().persistent().remove(&DataKey::PendingAdmin);
env.storage().persistent().remove(&DataKey::PendingAdminEta);
env.events().publish((symbol_short!("executed"),), caller);
}
/// Step 1 of admin handover. Current admin proposes a new admin;
/// the new admin must then accept via `accept_admin_transfer` once the
/// governance timelock (if any) has elapsed.
///
/// Stamps `PendingAdminEta = now + timelock` and emits a `queued`
/// event carrying the new admin and the eta so watchers get a warning
/// window before control can actually change hands.
pub fn propose_admin_transfer(env: Env, new_admin: Address) {
Self::require_admin(&env);
let delay: u64 = env
.storage()
.persistent()
.get(&DataKey::Timelock)
.unwrap_or(0);
let eta = env.ledger().timestamp().saturating_add(delay);
env.storage()
.persistent()
.set(&DataKey::PendingAdmin, &new_admin.clone());
env.storage()
.persistent()
.set(&DataKey::PendingAdminEta, &eta);
env.events()
.publish((symbol_short!("queued"),), (new_admin, eta));
}
/// Force-complete an admin handover after the timelock has elapsed,
/// without requiring the new admin to call `accept_admin_transfer`.
///
/// Admin-gated. Requires that `propose_admin_transfer` was already
/// called with the same `new_admin` and that the timelock delay has
/// elapsed. Emits the same `executed` event as `accept_admin_transfer`
/// so indexers can treat it identically.
pub fn force_admin_transfer(env: Env, new_admin: Address) {
Self::require_admin(&env);
let pending: Address = env
.storage()
.persistent()
.get(&DataKey::PendingAdmin)
.unwrap_or_else(|| panic_with_error!(&env, RouterError::NoPendingAdminTransfer));
if pending != new_admin {
panic_with_error!(&env, RouterError::NotPendingAdmin);
}
let eta: u64 = env
.storage()
.persistent()
.get(&DataKey::PendingAdminEta)
.unwrap_or(0);
if env.ledger().timestamp() < eta {
panic_with_error!(&env, RouterError::TimelockNotElapsed);
}
env.storage()
.persistent()
.set(&DataKey::Admin, &new_admin.clone());
env.storage().persistent().remove(&DataKey::PendingAdmin);
env.storage().persistent().remove(&DataKey::PendingAdminEta);
env.events()
.publish((symbol_short!("executed"),), new_admin);
}
/// Returns the admin set at `init`, if any.
pub fn get_admin(env: Env) -> Option<Address> {
env.storage().persistent().get(&DataKey::Admin)
}
/// Register `(source, destination)` as a recognised route.
///
/// Admin-gated; rejects `source == destination`. Idempotent: a
/// second call with the same pair simply re-asserts the entry and
/// is a no-op from the caller's perspective.
///
/// **Registration-first invariant:** `set_pair_fee_bps`,
/// `set_pair_min_amount`, `set_pair_max_amount`, and
/// `set_pair_liquidity` all require the pair to already be registered
/// here, and panic with [`RouterError::PairNotRegistered`] (#5)
/// otherwise. Always call `register_pair` before configuring a
/// corridor's fee, bounds, or liquidity.
pub fn register_pair(env: Env, source: Symbol, destination: Symbol) {
if env
.storage()
.persistent()
.get(&DataKey::Paused)
.unwrap_or(false)
{
panic_with_error!(&env, RouterError::ContractPaused);
}
Self::require_admin(&env);
if source == destination {
panic_with_error!(&env, RouterError::SourceEqualsDestination);
}
env.storage()
.persistent()
.set(&DataKey::Pair(source.clone(), destination.clone()), &true);
env.events()
.publish((symbol_short!("pair_reg"),), (source, destination));
}
/// Register multiple `(source, destination)` pairs in a single
/// admin-gated call. Each entry is validated identically to
/// [`Self::register_pair`] and gets its own `pair_reg` event.
///
/// **All-or-nothing:** if any entry fails validation the entire
/// transaction is rolled back (Soroban transactions are atomic), so
/// callers must ensure every pair is valid before invoking this. The
/// batch must contain at least one entry; an empty batch panics with
/// [`RouterError::EmptyBatch`]. The batch is also capped at
/// [`MAX_BATCH_SIZE`] entries to bound gas; exceeding it panics with
/// [`RouterError::BatchTooLarge`].
pub fn register_pairs(env: Env, pairs: Vec<(Symbol, Symbol)>) {
if env
.storage()
.persistent()
.get(&DataKey::Paused)
.unwrap_or(false)
{
panic_with_error!(&env, RouterError::ContractPaused);
}
Self::require_admin(&env);
if pairs.is_empty() {
panic_with_error!(&env, RouterError::EmptyBatch);
}
if pairs.len() > MAX_BATCH_SIZE {
panic_with_error!(&env, RouterError::BatchTooLarge);
}
for (source, destination) in pairs.iter() {
if source == destination {
panic_with_error!(&env, RouterError::SourceEqualsDestination);
}
env.storage()
.persistent()
.set(&DataKey::Pair(source.clone(), destination.clone()), &true);
env.events()
.publish((symbol_short!("pair_reg"),), (source, destination));
}
}
/// Returns true iff the pair is registered AND has non-zero
/// reported liquidity. Useful as a quick is-routable check.
pub fn is_pair_active(env: Env, source: Symbol, destination: Symbol) -> bool {
let s = env.storage().persistent();
if !s
.get::<_, bool>(&DataKey::Pair(source.clone(), destination.clone()))
.unwrap_or(false)
{
return false;
}
s.get::<_, i128>(&DataKey::PairLiquidity(source, destination))
.unwrap_or(0)
> 0
}
/// Single round-trip aggregate read for the dashboard. Returns
/// every per-pair slot in one shot.
pub fn get_pair_info(env: Env, source: Symbol, destination: Symbol) -> PairInfo {
let s = env.storage().persistent();
PairInfo {
registered: s
.get(&DataKey::Pair(source.clone(), destination.clone()))
.unwrap_or(false),
fee_bps: s
.get(&DataKey::PairFeeBps(source.clone(), destination.clone()))
.unwrap_or(0),
min_amount: s
.get(&DataKey::PairMinAmount(source.clone(), destination.clone()))
.unwrap_or(0),
max_amount: s
.get(&DataKey::PairMaxAmount(source.clone(), destination.clone()))
.unwrap_or(i128::MAX),
liquidity: s
.get(&DataKey::PairLiquidity(source.clone(), destination.clone()))
.unwrap_or(0),
last_route_at: s
.get(&DataKey::PairLastRouteAt(source, destination))
.unwrap_or(0),
}
}
/// Extended aggregate read including newer per-pair slots that were
/// added after the original [`PairInfo`] shipped. Returns every
/// per-pair slot in a single round-trip so dashboards avoid issuing
/// separate calls for cooldown, route count, and volume.
///
/// Defaults follow the same sentinel conventions as the individual
/// getters: cooldown 0 (disabled), route count 0, volume 0.
pub fn get_pair_info_ext(env: Env, source: Symbol, destination: Symbol) -> PairInfoExt {
let s = env.storage().persistent();
PairInfoExt {
registered: s
.get(&DataKey::Pair(source.clone(), destination.clone()))
.unwrap_or(false),
fee_bps: s
.get(&DataKey::PairFeeBps(source.clone(), destination.clone()))
.unwrap_or(0),
min_amount: s
.get(&DataKey::PairMinAmount(source.clone(), destination.clone()))
.unwrap_or(0),
max_amount: s
.get(&DataKey::PairMaxAmount(source.clone(), destination.clone()))
.unwrap_or(i128::MAX),
liquidity: s
.get(&DataKey::PairLiquidity(source.clone(), destination.clone()))
.unwrap_or(0),
last_route_at: s
.get(&DataKey::PairLastRouteAt(
source.clone(),
destination.clone(),
))
.unwrap_or(0),
cooldown_secs: s
.get(&DataKey::PairCooldown(source.clone(), destination.clone()))
.unwrap_or(0),
route_count: s
.get(&DataKey::PairRouteCount(
source.clone(),
destination.clone(),
))
.unwrap_or(0),
volume: s
.get(&DataKey::PairVolume(source, destination))
.unwrap_or(0),
}
}
/// Read-only quote of fee + net for a pair without writing the
/// timestamp / counter. Useful as a planner-only hook.
pub fn quote_route(
env: Env,
source: Symbol,
destination: Symbol,
amount: i128,
) -> (i128, i128) {
if amount <= 0 {
panic_with_error!(&env, RouterError::AmountMustBePositive);
}
if !env
.storage()
.persistent()
.get::<_, bool>(&DataKey::Pair(source.clone(), destination.clone()))
.unwrap_or(false)
{
panic_with_error!(&env, RouterError::PairNotRegistered);
}
let fee_bps: u32 = env
.storage()
.persistent()
.get(&DataKey::PairFeeBps(source, destination))
.unwrap_or(0);
let fee = amount
.checked_mul(fee_bps as i128)
.map(|n| n / BPS_DENOMINATOR)
.unwrap_or(0);
let fee = Self::apply_fee_cap(&env, fee);
(fee, amount - fee)
}
/// Read the most recent ledger timestamp at which `compute_route_fee`
/// touched this pair. None when never routed.
pub fn get_pair_last_route_at(env: Env, source: Symbol, destination: Symbol) -> Option<u64> {
env.storage()
.persistent()
.get(&DataKey::PairLastRouteAt(source, destination))
}
/// Admin sets the per-pair route cooldown in seconds.
///
/// While set to a non-zero value, `compute_route_fee` rejects a call
/// for the pair until at least `cooldown_secs` seconds have elapsed
/// since the pair's last successful route (`PairLastRouteAt`).
/// Setting `0` (the default) disables the rate limit for the pair.
/// Rejects values above [`MAX_COOLDOWN_SECS`] with
/// [`RouterError::CooldownTooLarge`] so an absurdly large value
/// (e.g. `u64::MAX`) cannot permanently brick the corridor.
pub fn set_pair_cooldown(env: Env, source: Symbol, destination: Symbol, cooldown_secs: u64) {
Self::require_admin(&env);
if cooldown_secs > MAX_COOLDOWN_SECS {
panic_with_error!(&env, RouterError::CooldownTooLarge);
}
env.storage().persistent().set(
&DataKey::PairCooldown(source.clone(), destination.clone()),
&cooldown_secs,
);
env.events().publish(
(symbol_short!("cd_set"),),
(source, destination, cooldown_secs),
);
}
/// Read the per-pair route cooldown in seconds (0 when absent,
/// meaning the rate limit is disabled for the pair).
pub fn get_pair_cooldown(env: Env, source: Symbol, destination: Symbol) -> u64 {
env.storage()
.persistent()
.get(&DataKey::PairCooldown(source, destination))
.unwrap_or(0)
}
/// Read the protocol-wide lifetime counter of route quotes.
pub fn get_total_routes_all_time(env: Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::TotalRoutesAllTime)
.unwrap_or(0)
}
/// Read the per-pair lifetime count of `compute_route_fee`
/// invocations for `(source, destination)`. Returns 0 when the pair
/// has never been routed.
pub fn get_pair_route_count(env: Env, source: Symbol, destination: Symbol) -> u64 {
env.storage()
.persistent()
.get(&DataKey::PairRouteCount(source, destination))
.unwrap_or(0)
}
/// Read the per-pair cumulative routed volume (sum of `amount` in
/// source units) for `(source, destination)`. Returns 0 when the
/// pair has never been routed.
pub fn get_pair_volume(env: Env, source: Symbol, destination: Symbol) -> i128 {
env.storage()
.persistent()
.get(&DataKey::PairVolume(source, destination))
.unwrap_or(0)
}
/// Admin sets the address that receives protocol fees at
/// settlement time. The router itself never custodies funds.
pub fn set_fee_recipient(env: Env, recipient: Address) {
Self::require_admin(&env);
env.storage()
.persistent()
.set(&DataKey::FeeRecipient, &recipient);
}
/// Read the configured fee recipient, if any.
pub fn get_fee_recipient(env: Env) -> Option<Address> {
env.storage().persistent().get(&DataKey::FeeRecipient)
}
/// Clamp `fee` to the configured absolute ceiling when one is set.
/// Both the relative `MAX_FEE_BPS` bound and this absolute bound apply;
/// the tighter of the two wins. No-op when no absolute cap is configured.
fn apply_fee_cap(env: &Env, fee: i128) -> i128 {
match env
.storage()
.persistent()
.get::<_, i128>(&DataKey::MaxFeeAbsolute)
{
Some(cap) => fee.min(cap),
None => fee,
}
}
/// Read the absolute per-route fee ceiling, or `None` when unset.
pub fn get_max_fee_absolute(env: Env) -> Option<i128> {
env.storage().persistent().get(&DataKey::MaxFeeAbsolute)
}
/// Admin sets the absolute per-route fee ceiling (in source units).
/// Rejects negative caps with `AmountMustBePositive` (#6). A cap of `0`
/// makes every route effectively free. Emits a `maxfee` event. The cap
/// composes with `MAX_FEE_BPS`: a route is charged
/// `min(amount * fee_bps / 10_000, max_fee_absolute)`.
pub fn set_max_fee_absolute(env: Env, max_fee: i128) {
Self::require_admin(&env);
if max_fee < 0 {
panic_with_error!(&env, RouterError::AmountMustBePositive);
}
env.storage()
.persistent()
.set(&DataKey::MaxFeeAbsolute, &max_fee);
env.events().publish((symbol_short!("maxfee"),), max_fee);
}
/// Read the reported liquidity for a pair (0 when absent).
pub fn get_pair_liquidity(env: Env, source: Symbol, destination: Symbol) -> i128 {
env.storage()
.persistent()
.get(&DataKey::PairLiquidity(source, destination))
.unwrap_or(0)
}
/// Read the configured liquidity oracle, if any.
pub fn get_oracle(env: Env) -> Option<Address> {
env.storage().persistent().get(&DataKey::Oracle)
}
/// Admin sets (or rotates) the scoped liquidity oracle.
///
/// Admin-gated. The oracle may update pair liquidity via
/// [`Self::set_pair_liquidity`] and **nothing else** — it cannot set
/// fees, pause, rotate admin, or upgrade. Emits `oracle_set`.
pub fn set_oracle(env: Env, oracle: Address) {
Self::require_admin(&env);
env.storage().persistent().set(&DataKey::Oracle, &oracle);
// Topic shortened to satisfy the 9-char `symbol_short!` limit.
env.events().publish((symbol_short!("orac_set"),), oracle);
}
/// Admin revokes the scoped liquidity oracle.
///
/// Admin-gated (panics with [`RouterError::NotInitialized`] (#2) when
/// no admin is set, like every other admin entrypoint). Removes
/// `DataKey::Oracle` so [`Self::set_pair_liquidity`] once again
/// accepts **only the admin**: its dual-auth check
/// (`caller != admin && Some(caller) != oracle`) naturally degrades to
/// admin-only when the slot is absent, because `Some(caller)` can
/// never equal `None`. This is the recovery path for a compromised
/// oracle key — unlike [`Self::set_oracle`] (which can only rotate to
/// a new address, leaving *some* oracle authorized), `remove_oracle`
/// returns the contract to an admin-only liquidity feed.
///
/// Idempotent: removing when no oracle is configured is a clean
/// no-op. Emits `orac_rm` carrying the previously configured oracle
/// (`None` on a no-op) so indexers can audit revocations.
pub fn remove_oracle(env: Env) {
Self::require_admin(&env);
let removed: Option<Address> = env.storage().persistent().get(&DataKey::Oracle);
env.storage().persistent().remove(&DataKey::Oracle);
env.events().publish((symbol_short!("orac_rm"),), removed);
}
/// Set the reported liquidity for a pair (source units).
///
/// Dual-authorized: `caller` must be **either** the admin **or** the
/// configured oracle, and must `require_auth()`. This implements
/// least privilege — the frequently rotated oracle key can keep the
/// liquidity feed fresh without holding governance power. When no
/// oracle is configured (never set, or revoked via
/// [`Self::remove_oracle`]) the `Some(caller) != oracle` comparison is
/// always true, so only the admin is accepted. Any other
/// caller is rejected with [`RouterError::NotAuthorized`].
///
/// Requires the pair to already be registered via
/// [`Self::register_pair`]; rejects an unregistered pair with
/// [`RouterError::PairNotRegistered`] (#5) so liquidity can never be
/// configured for a corridor that was never (or no longer) enabled.
pub fn set_pair_liquidity(
env: Env,
caller: Address,
source: Symbol,
destination: Symbol,
liquidity: i128,
) {
caller.require_auth();
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, RouterError::NotInitialized));
let oracle: Option<Address> = env.storage().persistent().get(&DataKey::Oracle);
if caller != admin && Some(caller.clone()) != oracle {
panic_with_error!(&env, RouterError::NotAuthorized);
}
if liquidity < 0 {
panic_with_error!(&env, RouterError::AmountMustBePositive);
}
Self::require_pair_registered(&env, &source, &destination);
env.storage().persistent().set(
&DataKey::PairLiquidity(source.clone(), destination.clone()),
&liquidity,
);
env.events().publish(
(symbol_short!("liq_set"),),
(source, destination, liquidity),
);
}
/// Read the per-pair maximum (i128::MAX when absent).
pub fn get_pair_max_amount(env: Env, source: Symbol, destination: Symbol) -> i128 {
env.storage()
.persistent()
.get(&DataKey::PairMaxAmount(source, destination))
.unwrap_or(i128::MAX)
}
/// Admin sets the per-pair maximum routable amount.
///
/// Requires the pair to already be registered via
/// [`Self::register_pair`]; rejects an unregistered pair with
/// [`RouterError::PairNotRegistered`] (#5) so the maximum can never be
/// configured for a corridor that was never (or no longer) enabled.
pub fn set_pair_max_amount(env: Env, source: Symbol, destination: Symbol, max_amount: i128) {
Self::require_admin(&env);
if max_amount <= 0 {
panic_with_error!(&env, RouterError::AmountMustBePositive);
}
Self::require_pair_registered(&env, &source, &destination);
env.storage()
.persistent()
.set(&DataKey::PairMaxAmount(source, destination), &max_amount);
}
/// Read the per-pair minimum (0 when absent).
pub fn get_pair_min_amount(env: Env, source: Symbol, destination: Symbol) -> i128 {
env.storage()
.persistent()
.get(&DataKey::PairMinAmount(source, destination))
.unwrap_or(0)
}
/// Admin sets the per-pair minimum routable amount.
///
/// Requires the pair to already be registered via
/// [`Self::register_pair`]; rejects an unregistered pair with
/// [`RouterError::PairNotRegistered`] (#5) so the minimum can never be
/// configured for a corridor that was never (or no longer) enabled.
pub fn set_pair_min_amount(env: Env, source: Symbol, destination: Symbol, min_amount: i128) {
Self::require_admin(&env);
if min_amount < 0 {
panic_with_error!(&env, RouterError::AmountMustBePositive);
}
Self::require_pair_registered(&env, &source, &destination);
env.storage()
.persistent()
.set(&DataKey::PairMinAmount(source, destination), &min_amount);
}