-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathlib.rs
More file actions
6755 lines (6169 loc) · 267 KB
/
Copy pathlib.rs
File metadata and controls
6755 lines (6169 loc) · 267 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,
};
mod pool_storage;
use pool_storage::{bump_key_ttl, bump_pair_ttl};
mod error_taxonomy;
mod error_taxonomy;
/// 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,
}
/// Live fee and amount limits for one registered routing pair.
///
/// This aggregate is intentionally composed from the existing pair-scoped
/// storage slots, so adding the setter does not change storage layout or the
/// encoding of [`PairInfo`] and [`PairInfoExt`].
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PairParameters {
pub fee_bps: u32,
pub min_amount: i128,
pub max_amount: 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,
}
/// 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,
/// 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),
/// Monotonic optimistic-concurrency version for the guarded swap API.
/// Absent means version zero; it is advanced only after a successful swap.
PairSwapVersion(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,
/// An admin handover targeted the current admin or this contract itself.
InvalidAdminAddress = 22,
/// A combined pair-parameter update has a negative minimum, a non-positive
/// maximum, or a minimum greater than its maximum.
InvalidParameterRange = 23,
}
/// 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 {
/// Read the admin address from instance storage, panicking with
/// [`RouterError::NotInitialized`] if absent.
fn load_admin(env: &Env) -> Address {
env.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, RouterError::NotInitialized))
}
/// 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 = Self::load_admin(env);
admin.require_auth();
admin
}
/// Renew the contract instance's TTL. Called after every write to a
/// hot-global instance slot (`Admin`, `PendingAdmin`, `Paused`) so the
/// instance — and therefore these singletons — never archives as long
/// as the contract keeps receiving admin/pause/transfer traffic.
fn bump_instance_ttl(env: &Env) {
env.storage()
.instance()
.extend_ttl(INSTANCE_TTL_THRESHOLD, INSTANCE_TTL_EXTEND_TO);
}
/// 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 !Self::read_pair_registered(env, source, destination) {
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);
}
/// Release the reentrancy lock and panic with `err`. Consolidates the
/// exit-then-panic pattern used on every guard-failure path of
/// [`Self::compute_route_fee`] so the lock is never leaked on a
/// rejection.
fn route_abort(env: &Env, err: RouterError) -> ! {
Self::exit_nonreentrant(env);
panic_with_error!(env, err)
}
/// Read the paused flag from the instance-storage hot global.
/// Single source of truth for the `Paused` sentinel (absent → `false`).
fn paused(env: &Env) -> bool {
env.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
}
/// Panic with [`RouterError::ContractPaused`] when the router is paused.
/// Shared by every state-changing, pause-gated entrypoint.
fn require_not_paused(env: &Env) {
if Self::paused(env) {
panic_with_error!(env, RouterError::ContractPaused);
}
}
/// Finalise an admin handover: install `new_admin`, clear the pending
/// slots, renew the instance TTL, and emit the `executed` event. Shared
/// tail of [`Self::accept_admin_transfer`] and
/// [`Self::force_admin_transfer`].
fn finalize_admin_transfer(env: &Env, new_admin: Address) {
env.storage().instance().set(&DataKey::Admin, &new_admin);
env.storage().instance().remove(&DataKey::PendingAdmin);
env.storage().persistent().remove(&DataKey::PendingAdminEta);
Self::bump_instance_ttl(env);
env.events()
.publish((symbol_short!("executed"),), new_admin);
}
/// Read whether `(source, destination)` is a registered pair from
/// persistent storage.
///
/// Returns `false` when the slot is absent — the documented default for an
/// unregistered pair. This is the single source of truth for the
/// [`DataKey::Pair`] sentinel value.
fn read_pair_registered(env: &Env, source: &Symbol, destination: &Symbol) -> bool {
let key = DataKey::Pair(source.clone(), destination.clone());
let value = env.storage().persistent().get(&key).unwrap_or(false);
bump_key_ttl(env, &key);
value
}
/// Read the per-pair fee in basis points from persistent storage.
///
/// Returns `0` (free) when the slot is absent — the documented
/// default for an unconfigured, registered pair. This is the single
/// source of truth for the [`DataKey::PairFeeBps`] sentinel value.
fn read_pair_fee_bps(env: &Env, source: &Symbol, destination: &Symbol) -> u32 {
let key = DataKey::PairFeeBps(source.clone(), destination.clone());
let value = env.storage().persistent().get(&key).unwrap_or(0);
bump_key_ttl(env, &key);
value
}
/// Read the per-pair minimum routable amount from persistent storage.
///
/// Returns `0` (no floor) when the slot is absent — the documented
/// default. This is the single source of truth for the
/// [`DataKey::PairMinAmount`] sentinel value.
fn read_pair_min(env: &Env, source: &Symbol, destination: &Symbol) -> i128 {
let key = DataKey::PairMinAmount(source.clone(), destination.clone());
let value = env.storage().persistent().get(&key).unwrap_or(0);
bump_key_ttl(env, &key);
value
}
/// Read the per-pair maximum routable amount from persistent storage.
///
/// Returns `i128::MAX` (no ceiling — unbounded) when the slot is
/// absent. This is the single source of truth for the
/// [`DataKey::PairMaxAmount`] sentinel value.
fn read_pair_max(env: &Env, source: &Symbol, destination: &Symbol) -> i128 {
let key = DataKey::PairMaxAmount(source.clone(), destination.clone());
let value = env.storage().persistent().get(&key).unwrap_or(i128::MAX);
bump_key_ttl(env, &key);
value
}
/// Read the per-pair reported liquidity from persistent storage.
///
/// Returns `0` (no liquidity configured) when the slot is absent —
/// the documented default for getters and aggregate reads. Note that
/// [`Self::compute_route_fee`] intentionally uses `i128::MAX` as its
/// own unbounded sentinel (a context-dependent default, documented
/// in the [`DataKey::PairLiquidity`] variant and `storage.md`).
/// Callers needing the unbounded semantic should read the slot
/// directly with `unwrap_or(i128::MAX)`.
fn read_pair_liquidity(env: &Env, source: &Symbol, destination: &Symbol) -> i128 {
let key = DataKey::PairLiquidity(source.clone(), destination.clone());
let value = env.storage().persistent().get(&key).unwrap_or(0);
bump_key_ttl(env, &key);
value
}
/// Read the per-pair route cooldown from persistent storage.
///
/// Returns `0` (rate limit disabled) when the slot is absent — the
/// documented default for an unconfigured pair. This is the single
/// source of truth for the [`DataKey::PairCooldown`] sentinel value.
fn read_pair_cooldown(env: &Env, source: &Symbol, destination: &Symbol) -> u64 {
let key = DataKey::PairCooldown(source.clone(), destination.clone());
let value = env.storage().persistent().get(&key).unwrap_or(0);
bump_key_ttl(env, &key);
value
}
/// Read the optimistic-concurrency version for a pair. Version zero is
/// the stable default for pairs that have never completed a guarded swap.
fn read_swap_version(env: &Env, source: &Symbol, destination: &Symbol) -> u64 {
env.storage()
.persistent()
.get(&DataKey::PairSwapVersion(
source.clone(),
destination.clone(),
))
.unwrap_or(0)
}
/// 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,
}
}
/// Return the append-only typed error catalog for SDK discovery.
///
/// This read-only surface lets clients display exact negative-path codes
/// without copying the enum into a separate, drift-prone configuration.
pub fn get_error_catalog(env: Env) -> Vec<error_taxonomy::ErrorDescriptor> {
error_taxonomy::catalog(&env)
}
/// 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);
}
/// Returns true iff the router is currently paused.
pub fn is_paused(env: Env) -> bool {
Self::paused(&env)
}
/// 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);
}
/// 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).
///
/// 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));
}
/// 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);
let cancelled: Option<Address> = env.storage().instance().get(&DataKey::PendingAdmin);
env.storage().instance().remove(&DataKey::PendingAdmin);
env.storage().persistent().remove(&DataKey::PendingAdminEta);
Self::bump_instance_ttl(&env);
env.events()
.publish((symbol_short!("cancelled"),), cancelled);
}
/// 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),
}
}
/// 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()
.instance()
.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);
}
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) {
let admin = Self::require_admin(&env);
if new_admin == env.current_contract_address() || new_admin == admin {
panic_with_error!(&env, RouterError::InvalidAdminAddress);
}
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);
let pending: Address = env
.storage()
.instance()
.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);
}
Self::finalize_admin_transfer(&env, new_admin);
}
/// Returns the admin set at `init`, if any.
pub fn get_admin(env: Env) -> Option<Address> {
env.storage().instance().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) {
Self::require_not_paused(&env);
Self::require_admin(&env);
if source == destination {
panic_with_error!(&env, RouterError::SourceEqualsDestination);
}
env.storage()
.persistent()
.set(&DataKey::Pair(source.clone(), destination.clone()), &true);
bump_key_ttl(&env, &DataKey::Pair(source.clone(), destination.clone()));
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)>) {
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);
}
env.storage()
.persistent()
.set(&DataKey::Pair(source.clone(), destination.clone()), &true);
bump_key_ttl(&env, &DataKey::Pair(source.clone(), destination.clone()));
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 {
if !Self::read_pair_registered(&env, &source, &destination) {
return false;
}
Self::read_pair_liquidity(&env, &source, &destination) > 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: Self::read_pair_registered(&env, &source, &destination),
fee_bps: Self::read_pair_fee_bps(&env, &source, &destination),
min_amount: Self::read_pair_min(&env, &source, &destination),
max_amount: Self::read_pair_max(&env, &source, &destination),
liquidity: Self::read_pair_liquidity(&env, &source, &destination),
last_route_at: s
.get(&DataKey::PairLastRouteAt(source, destination))
.unwrap_or(0),
}
}
/// Read the fee and amount limits for a registered pair as one snapshot.
///
/// The view returns the same sentinels as the individual getters: a zero
/// minimum and `i128::MAX` maximum when no amount bounds were configured.
/// It is read-only and does not require admin authorization.
pub fn get_pair_parameters(env: Env, source: Symbol, destination: Symbol) -> PairParameters {
PairParameters {
fee_bps: Self::read_pair_fee_bps(&env, &source, &destination),
min_amount: Self::read_pair_min(&env, &source, &destination),
max_amount: Self::read_pair_max(&env, &source, &destination),
}
}
/// Atomically update the fee and amount limits for a registered pair.
///
/// The admin guard and pause guard run before any storage write. All
/// supplied values are validated before the old values are read or the
/// new values are written, so an invalid request cannot partially update
/// a pair. The `param_set` event carries both snapshots for indexers.
pub fn set_pair_parameters(
env: Env,
source: Symbol,
destination: Symbol,
parameters: PairParameters,
) {
Self::require_not_paused(&env);
Self::require_admin(&env);
if parameters.fee_bps > MAX_FEE_BPS
|| parameters.min_amount < 0
|| parameters.max_amount <= 0
|| parameters.min_amount > parameters.max_amount
{
panic_with_error!(&env, RouterError::InvalidParameterRange);
}
Self::require_pair_registered(&env, &source, &destination);
let old = Self::get_pair_parameters(env.clone(), source.clone(), destination.clone());
env.storage().persistent().set(
&DataKey::PairFeeBps(source.clone(), destination.clone()),
¶meters.fee_bps,
);
env.storage().persistent().set(
&DataKey::PairMinAmount(source.clone(), destination.clone()),
¶meters.min_amount,
);
env.storage().persistent().set(
&DataKey::PairMaxAmount(source.clone(), destination.clone()),
¶meters.max_amount,
);
bump_key_ttl(
&env,
&DataKey::PairFeeBps(source.clone(), destination.clone()),
);
bump_key_ttl(
&env,
&DataKey::PairMinAmount(source.clone(), destination.clone()),
);
bump_key_ttl(
&env,
&DataKey::PairMaxAmount(source.clone(), destination.clone()),
);
env.events().publish(
(symbol_short!("param_set"),),
(source, destination, old, parameters),
);
}
/// 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: Self::read_pair_registered(&env, &source, &destination),
fee_bps: Self::read_pair_fee_bps(&env, &source, &destination),
min_amount: Self::read_pair_min(&env, &source, &destination),
max_amount: Self::read_pair_max(&env, &source, &destination),
liquidity: Self::read_pair_liquidity(&env, &source, &destination),
last_route_at: s
.get(&DataKey::PairLastRouteAt(
source.clone(),
destination.clone(),
))
.unwrap_or(0),
cooldown_secs: Self::read_pair_cooldown(&env, &source, &destination),
route_count: s
.get(&DataKey::PairRouteCount(
source.clone(),
destination.clone(),
))
.unwrap_or(0),
volume: s