-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathlib.rs
More file actions
7768 lines (7087 loc) · 308 KB
/
Copy pathlib.rs
File metadata and controls
7768 lines (7087 loc) · 308 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>,
}
/// Aggregated read of the protocol-wide limits that callers must respect
/// before submitting a transaction.
///
/// Every field mirrors a `pub const` in this module
/// ([`MAX_FEE_BPS`], [`BPS_DENOMINATOR`], [`MAX_BATCH_SIZE`],
/// [`MAX_COOLDOWN_SECS`]). Exposing them as a `#[contracttype]` lets an
/// on-chain caller or a client that did not compile against this crate
/// discover the enforced bounds in a single read via [`StableRouteRouter::get_limits`].
///
/// **Field order is part of the stable on-chain ABI** — do not reorder or
/// insert fields, as that would change the XDR encoding. New limits must be
/// appended. Documented in [`docs/abi.md`].
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RouterLimits {
/// Upper bound on the per-pair fee, in basis points. Mirrors [`MAX_FEE_BPS`].
pub max_fee_bps: u32,
/// Basis-point denominator (1 bps = 1 / `bps_denominator`). Mirrors [`BPS_DENOMINATOR`].
pub bps_denominator: i128,
/// Maximum number of entries in a single batch operation. Mirrors [`MAX_BATCH_SIZE`].
pub max_batch_size: u32,
/// Upper bound on the per-pair route cooldown, in seconds. Mirrors [`MAX_COOLDOWN_SECS`].
pub max_cooldown_secs: u64,
}
/// Aggregated read of the contract's global (non-pair-scoped) configuration:
/// fee recipient, absolute fee bounds, liquidity oracle, and governance
/// timelock delay. Lets callers fetch the whole admin-configured surface in
/// a single invocation instead of five separate getter calls.
///
/// Every field reads its documented sane default when unset (see
/// [`DataKey`]'s sentinel conventions), so this view is safe to call before
/// any admin configuration has taken place.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GlobalConfig {
/// Mirrors [`StableRouteRouter::get_fee_recipient`]. `None` when unset.
pub fee_recipient: Option<Address>,
/// Mirrors [`StableRouteRouter::get_max_fee_absolute`]. `None` when no
/// absolute ceiling is enforced.
pub max_fee_absolute: Option<i128>,
/// Mirrors [`StableRouteRouter::get_min_fee_absolute`]. `None` when no
/// absolute floor is enforced.
pub min_fee_absolute: Option<i128>,
/// Mirrors [`StableRouteRouter::get_oracle`]. `None` when unset.
pub oracle: Option<Address>,
/// Mirrors [`StableRouteRouter::get_timelock`]. Defaults to `0`.
pub timelock_secs: u64,
}
/// Storage keys used by the StableRoute router. Twenty-one variants total.
/// Most live in persistent storage; three hot-global singletons
/// ([`Admin`](DataKey::Admin), [`PendingAdmin`](DataKey::PendingAdmin),
/// [`Paused`](DataKey::Paused)) live in **instance** storage so they are
/// read together with the contract instance on every admin-gated or
/// pause-gated call, avoiding a separate persistent-storage hit.
///
/// 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, min 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`, **instance** — hot global).
/// 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`, **instance** — hot global). 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`, **instance**
/// — hot global). Route-accounting (`compute_route_fee`), pair
/// registration (`register_pair`, `register_pairs`), and fee setters
/// (`set_pair_fee_bps`, `set_pair_fees_bps`) reject calls while
/// paused. Admin/config setters (`set_pair_liquidity`,
/// `set_pair_cooldown`, `set_pair_min_amount`, `set_pair_max_amount`,
/// `set_fee_recipient`, `set_max_fee_absolute`,
/// `set_min_fee_absolute`, `set_oracle`, `remove_oracle`), lifecycle
/// entrypoints (`unregister_pair`, `purge_pair_metrics`), governance
/// (`pause`, `unpause`, `set_timelock`, `propose_admin_transfer`,
/// `cancel_admin_transfer`, `force_admin_transfer`,
/// `accept_admin_transfer`), migration (`migrate_v1_to_v2`), and
/// read-only queries (`quote_route`, getters, `version`) remain
/// available so the admin can recover and integrators can keep
/// planning routes. 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).
/// An explicitly set `0` liquidity makes the pair non-routable
/// in both `compute_route_fee` and `quote_route` via
/// `InsufficientLiquidity`.
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,
/// Protocol-wide lifetime sum of fees collected by `compute_route_fee`
/// (singleton, `i128`, persistent), owed to whoever holds
/// `FeeRecipient` once distributed off-chain. Accumulated with
/// `saturating_add` so it is monotonic and never panics on overflow.
/// Defaults to `0`.
RewardsAccrued,
/// 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),
/// `true` when `(source, destination)` has an active dispute flag
/// (keyed per-pair, `bool`, persistent). Set by `flag_pair_dispute`
/// and cleared by `resolve_pair_dispute` or `unregister_pair`. While
/// `true`, `quote_route` and `compute_route_fee` reject the pair with
/// `PairDisputed`. Defaults to `false`.
PairDisputed(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).
/// A stored value of 0 (from a pre-upgrade write) is treated as
/// `None` by both `apply_fee_cap` and `get_max_fee_absolute`; zero
/// caps are rejected at write time with `ZeroFeeCap` (#21).
/// [`StableRouteRouter::clear_max_fee_absolute`] is the supported
/// way to remove the cap entirely.
MaxFeeAbsolute,
/// Optional absolute per-route fee floor (singleton, `i128`,
/// persistent). When set, the effective fee is `max(capped_fee, floor)`.
/// Absent ↔ `None` (no absolute floor applies).
MinFeeAbsolute,
/// 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;
/// Ledger-count threshold below which a hot-state write (see
/// [`StableRouteRouter::bump_instance_ttl`]) renews the contract
/// instance's TTL. Assuming ~5s average ledger close time, this is
/// roughly 30 days. Kept well above [`INSTANCE_TTL_EXTEND_TO`]'s renewal
/// point is not required — the host clamps automatically — but choosing
/// a threshold this generous means the instance is topped up far before
/// it could ever approach archival.
pub const INSTANCE_TTL_THRESHOLD: u32 = 518_400;
/// Ledger count the contract instance's TTL is extended to whenever a
/// hot-state write triggers a renewal (see
/// [`StableRouteRouter::bump_instance_ttl`]). Assuming ~5s average
/// ledger close time, this is roughly 60 days.
pub const INSTANCE_TTL_EXTEND_TO: u32 = 1_036_800;
/// 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,
/// `set_max_fee_absolute` was called with zero, which would make every
/// route free. Use [`StableRouteRouter::clear_max_fee_absolute`] to
/// remove the cap entirely.
ZeroFeeCap = 21,
/// `quote_route` or `compute_route_fee` was called for a pair with an
/// active dispute flag (see [`StableRouteRouter::flag_pair_dispute`]).
PairDisputed = 22,
}
/// 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 {
// ── Lifecycle ──────────────────────────────────────────────────────────
// Contract construction, legacy init, and schema migration.
/// 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().instance().set(&DataKey::Admin, &admin);
Self::bump_instance_ttl(&env);
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);
}
// ── Governance ────────────────────────────────────────────────────────
// Pause control, governance timelock, and two-step admin handover.
/// Resume after a pause. Admin-gated and idempotent.
pub fn unpause(env: Env) {
Self::require_admin(&env);
env.storage().instance().set(&DataKey::Paused, &false);
Self::bump_instance_ttl(&env);
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().instance().set(&DataKey::Paused, &true);
Self::bump_instance_ttl(&env);
env.events().publish((symbol_short!("paused"),), true);
}
/// 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).
///
/// Emits a `tlock_set` event containing the old and new delay values.
///
/// # Events
///
/// - Topic: `(symbol_short!("tlock_set"),)`
/// - Payload: `(old_delay, new_delay): (u64, u64)`
/// - When: fires when the governance timelock delay is modified by the admin.
pub fn set_timelock(env: Env, delay_seconds: u64) {
Self::require_admin(&env);
let old_delay = Self::get_timelock(env.clone());
env.storage()
.persistent()
.set(&DataKey::Timelock, &delay_seconds);
env.events()
.publish((symbol_short!("tlock_set"),), (old_delay, delay_seconds));
}
/// Cancel a pending handover, clearing both the pending admin and its
/// queued eta. No-op (storage-wise) if none is pending.
///
/// Emits a `cancelled` event carrying the pending admin and eta that
/// were cleared (both `None` on a no-op cancellation) — the third leg
/// of the propose (`queued`) / accept-or-force (`executed`) / cancel
/// (`cancelled`) event trail, so every claim-state transition is
/// observable on-chain, not just the two that previously had events.
pub fn cancel_admin_transfer(env: Env) {
Self::require_admin(&env);
let pending: Option<Address> = env.storage().instance().get(&DataKey::PendingAdmin);
let eta: Option<u64> = env.storage().persistent().get(&DataKey::PendingAdminEta);
env.storage().instance().remove(&DataKey::PendingAdmin);
env.storage().persistent().remove(&DataKey::PendingAdminEta);
Self::bump_instance_ttl(&env);
env.events()
.publish((symbol_short!("cancelled"),), (pending, eta));
}
/// 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();
Self::require_pending_admin_and_timelock_elapsed(&env, &caller);
Self::finalize_admin_transfer(&env, 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()
.instance()
.set(&DataKey::PendingAdmin, &new_admin.clone());
env.storage()
.persistent()
.set(&DataKey::PendingAdminEta, &eta);
Self::bump_instance_ttl(&env);
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);
Self::require_pending_admin_and_timelock_elapsed(&env, &new_admin);
Self::finalize_admin_transfer(&env, new_admin);
}
// ── Roles ─────────────────────────────────────────────────────────────
// Protocol-wide role assignments (fee recipient, liquidity oracle).
/// Admin sets the address that receives protocol fees at
/// settlement time. The router itself never custodies funds.
/// Emits a `recip_set` event carrying the new recipient address.
pub fn set_fee_recipient(env: Env, recipient: Address) {
Self::require_admin(&env);
env.storage()
.persistent()
.set(&DataKey::FeeRecipient, &recipient);
env.events()
.publish((symbol_short!("recip_set"),), recipient);
}
/// Assign the contract's liquidity oracle.
///
/// Admin-gated. Only the configured oracle may subsequently update
/// pair liquidity values.
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);
}
/// Remove the currently configured liquidity oracle.
///
/// Admin-gated. After removal, no address is authorized to update
/// liquidity until a new oracle is configured.
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);
}
// ── Pair config ───────────────────────────────────────────────────────
// Register / unregister pairs, set per-pair fees, bounds, cooldown,
// liquidity, and global fee cap / floor.
/// 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, including on events —
/// `pair_reg` fires only on the transition from unregistered to
/// registered, never on a redundant re-assertion of an already
/// registered pair.
///
/// **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) {
Self::require_not_paused(&env);
Self::require_admin(&env);
if source == destination {
panic_with_error!(&env, RouterError::SourceEqualsDestination);
}
let already_registered = Self::read_pair_registered(&env, &source, &destination);
env.storage()
.persistent()
.set(&DataKey::Pair(source.clone(), destination.clone()), &true);
if !already_registered {
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, with the
/// same no-duplicate-emission rule: an entry that is already registered
/// re-asserts silently instead of re-firing the 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)>) {
Self::require_not_paused(&env);
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);
}
let already_registered = Self::read_pair_registered(&env, &source, &destination);
env.storage()
.persistent()
.set(&DataKey::Pair(source.clone(), destination.clone()), &true);
if !already_registered {
env.events()
.publish((symbol_short!("pair_reg"),), (source, destination));
}
}
}
/// Configure the minimum interval (in seconds) between successful routes
/// for a pair.
///
/// Admin-gated. A value of `0` disables rate limiting. Values greater than
/// [`MAX_COOLDOWN_SECS`] are rejected with
/// [`RouterError::CooldownTooLarge`].
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);
}
Self::require_pair_registered(&env, &source, &destination);
env.storage().persistent().set(
&DataKey::PairCooldown(source.clone(), destination.clone()),
&cooldown_secs,
);
env.events().publish(
(symbol_short!("cd_set"),),
(source, destination, cooldown_secs),
);
}
/// Admin flags `(source, destination)` as disputed. While disputed,
/// [`Self::quote_route`] and [`Self::compute_route_fee`] reject the
/// pair with [`RouterError::PairDisputed`] until
/// [`Self::resolve_pair_dispute`] clears the flag. Requires the pair
/// to already be registered.
///
/// Idempotent on the event: flagging an already-disputed pair
/// re-asserts the flag but does not re-emit `disp_set`.
pub fn flag_pair_dispute(env: Env, source: Symbol, destination: Symbol) {
Self::require_admin(&env);
Self::require_pair_registered(&env, &source, &destination);
let already_disputed = Self::read_pair_disputed(&env, &source, &destination);
env.storage().persistent().set(
&DataKey::PairDisputed(source.clone(), destination.clone()),
&true,
);
if !already_disputed {
env.events()
.publish((symbol_short!("disp_set"),), (source, destination, true));
}
}
/// Admin clears a dispute flag, restoring normal routing and quoting
/// for the pair.
///
/// Idempotent: resolving a pair with no active dispute is a clean
/// no-op that does not emit `disp_set`.
pub fn resolve_pair_dispute(env: Env, source: Symbol, destination: Symbol) {
Self::require_admin(&env);
let was_disputed = Self::read_pair_disputed(&env, &source, &destination);
env.storage().persistent().set(
&DataKey::PairDisputed(source.clone(), destination.clone()),
&false,
);
if was_disputed {
env.events()
.publish((symbol_short!("disp_set"),), (source, destination, false));
}
}
/// Configure an absolute upper bound on the fee charged for any route.
///
/// Admin-gated. The computed fee is clamped to this value after the
/// percentage-based calculation.
pub fn set_max_fee_absolute(env: Env, max_fee: i128) {
Self::require_admin(&env);
Self::require_non_negative_fee(&env, max_fee);
if max_fee == 0 {
panic_with_error!(&env, RouterError::ZeroFeeCap);
}
env.storage()
.persistent()
.set(&DataKey::MaxFeeAbsolute, &max_fee);
env.events().publish((symbol_short!("maxfee"),), max_fee);
}
/// Admin removes the absolute per-route fee ceiling, restoring the
/// default behaviour where only the relative `MAX_FEE_BPS` bound
/// applies.
///
/// Idempotent: removing when no cap is configured is a clean no-op.
/// Emits a `maxfee_clr` event carrying the previously configured cap
/// (`None` on a no-op removal) so indexers can audit cap lifecycle
/// changes. The distinct topic (`maxfee_clr` vs `maxfee`) ensures
/// revocations are visually distinguishable from cap adjustments in
/// the event stream.
pub fn clear_max_fee_absolute(env: Env) {
Self::require_admin(&env);
let removed: Option<i128> = env.storage().persistent().get(&DataKey::MaxFeeAbsolute);
env.storage().persistent().remove(&DataKey::MaxFeeAbsolute);
env.events().publish((symbol_short!("mxfee_clr"),), removed);
}
/// Configure an absolute minimum fee charged for every successful route.
///
/// Admin-gated. The computed fee is raised to this value whenever the
/// percentage-based fee would be lower.
pub fn set_min_fee_absolute(env: Env, min_fee: i128) {
Self::require_admin(&env);
Self::require_non_negative_fee(&env, min_fee);
env.storage()
.persistent()
.set(&DataKey::MinFeeAbsolute, &min_fee);
env.events().publish((symbol_short!("minfee"),), min_fee);
}
/// Update the available liquidity for a registered pair.
///
/// Requires authentication by the configured oracle. The pair must already
/// be registered.
pub fn set_pair_liquidity(
env: Env,
caller: Address,
source: Symbol,
destination: Symbol,
liquidity: i128,
) {
caller.require_auth();
let admin: Address = Self::load_admin(&env);
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),
);
}
/// Configure the maximum permitted route amount for a pair.
///
/// 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.
/// Emits a `max_set` event carrying the pair and the new ceiling.
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.clone(), destination.clone()),
&max_amount,
);
env.events().publish(
(symbol_short!("max_set"),),
(source, destination, max_amount),
);
}
/// Configure the minimum permitted route amount for a pair.
///
/// 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.
/// Emits a `min_set` event carrying the pair and the new floor.
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.clone(), destination.clone()),
&min_amount,
);
env.events().publish(
(symbol_short!("min_set"),),
(source, destination, min_amount),
);
}
/// Remove a registered pair from the router.
///
/// Admin-gated and idempotent. Registration is removed and per-pair
/// configuration is cleared, while historical routing metrics remain
/// until explicitly purged.
pub fn unregister_pair(env: Env, source: Symbol, destination: Symbol) {
Self::require_admin(&env);
env.storage()
.persistent()
.remove(&DataKey::Pair(source.clone(), destination.clone()));
Self::clear_pair_config(&env, source.clone(), destination.clone());
env.events().publish(
(symbol_short!("unreg"),),
(source.clone(), destination.clone()),
);
env.events()
.publish((symbol_short!("cfg_clr"),), (source, destination));
}
/// Permanently remove all recorded routing metrics for a pair.
///
/// Admin-gated. Clears the route count, cumulative volume, and last
/// successful route timestamp.
///
/// Publishes a `metr_rm` event **before** clearing so off-chain
/// consumers can capture the pre-purge snapshot for auditability:
///
/// # Events
///
/// - Topic: `(symbol_short!("metr_rm"),)`
/// - Payload: `(source, destination, route_count, volume):
/// (Symbol, Symbol, u64, i128)`
/// - When: fires immediately before the three metrics slots are
/// removed. `route_count` and `volume` are the values that were
/// stored *before* the purge (defaulting to `0` when absent).
pub fn purge_pair_metrics(env: Env, source: Symbol, destination: Symbol) {
Self::require_admin(&env);
let storage = env.storage().persistent();
let route_count: u64 = storage
.get(&DataKey::PairRouteCount(
source.clone(),
destination.clone(),
))
.unwrap_or(0);
let volume: i128 = storage
.get(&DataKey::PairVolume(source.clone(), destination.clone()))
.unwrap_or(0);
storage.remove(&DataKey::PairRouteCount(
source.clone(),
destination.clone(),
));
storage.remove(&DataKey::PairVolume(source.clone(), destination.clone()));
storage.remove(&DataKey::PairLastRouteAt(
source.clone(),
destination.clone(),
));
env.events().publish(
(symbol_short!("metr_rm"),),
(source.clone(), destination.clone(), route_count, volume),
);
env.events()
.publish((symbol_short!("pair_mrst"),), (source, destination));
}
/// Configure the routing fee for a single registered pair.
///
/// Admin-gated. The fee is expressed in basis points and must not exceed
/// [`MAX_FEE_BPS`].
pub fn set_pair_fee_bps(env: Env, source: Symbol, destination: Symbol, fee_bps: u32) {
Self::require_not_paused(&env);
Self::require_admin(&env);
Self::require_valid_fee_bps(&env, fee_bps);
Self::require_pair_registered(&env, &source, &destination);
env.storage().persistent().set(
&DataKey::PairFeeBps(source.clone(), destination.clone()),
&fee_bps,
);
env.events()
.publish((symbol_short!("fee_set"),), (source, destination, fee_bps));
}
/// Configure routing fees for multiple registered pairs in a single call.
///
/// Admin-gated. Each entry is validated independently and the transaction
/// is atomic: if any entry is invalid, no fee changes are applied.
pub fn set_pair_fees_bps(env: Env, entries: Vec<(Symbol, Symbol, u32)>) {
Self::require_not_paused(&env);
Self::require_admin(&env);
if entries.is_empty() {
panic_with_error!(&env, RouterError::EmptyBatch);
}
if entries.len() > MAX_BATCH_SIZE {
panic_with_error!(&env, RouterError::BatchTooLarge);
}
for (source, destination, fee_bps) in entries.iter() {
Self::require_valid_fee_bps(&env, fee_bps);
Self::require_pair_registered(&env, &source, &destination);
env.storage().persistent().set(
&DataKey::PairFeeBps(source.clone(), destination.clone()),
&fee_bps,
);
env.events()
.publish((symbol_short!("fee_set"),), (source, destination, fee_bps));
}
}
// ── Reads ─────────────────────────────────────────────────────────────
// Pure getters and aggregate queries — no state mutations.
/// 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)
}
/// Expose the protocol-wide limits that every caller must respect before
/// submitting a transaction.
///
/// Returns a [`RouterLimits`] snapshot mirroring the compile-time
/// constants [`MAX_FEE_BPS`], [`BPS_DENOMINATOR`], [`MAX_BATCH_SIZE`], and
/// [`MAX_COOLDOWN_SECS`]. This is the on-chain discovery surface: an
/// on-chain caller or a client that did not compile against this crate
/// can learn the enforced bounds from a single read instead of having to
/// know the crate's `pub const`s.
///
/// Read-only and auth-free; never touches storage.
pub fn get_limits(_env: Env) -> RouterLimits {
RouterLimits {
max_fee_bps: MAX_FEE_BPS,
bps_denominator: BPS_DENOMINATOR,
max_batch_size: MAX_BATCH_SIZE,
max_cooldown_secs: MAX_COOLDOWN_SECS,
}
}
/// Returns true iff the router is currently paused.
pub fn is_paused(env: Env) -> bool {
Self::paused(&env)
}
/// 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)
}
/// 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)
}
/// Read the pending admin if any.
pub fn get_pending_admin(env: Env) -> Option<Address> {
env.storage().instance().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 {
PendingAdminInfo {
pending: env.storage().instance().get(&DataKey::PendingAdmin),
eta: env.storage().persistent().get(&DataKey::PendingAdminEta),
}
}
/// Returns the admin set at `init`, if any.
pub fn get_admin(env: Env) -> Option<Address> {